Unverified Commit 553d0b9f authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Fix Instant Navs DevTools capture bugs and re-enable its test suite (#94866)

parent 763d85b8
......@@ -924,14 +924,18 @@ export function upsertSegmentEntry(
// (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)
(!existingEntry.isPartial && candidateEntry.isPartial)
) {
// We're going to leave revalidating entry in the cache so that it doesn't
// get revalidated again unnecessarily. Downgrade the Fulfilled entry to
// Rejected and null out the data so it can be garbage collected. We leave
// `staleAt` intact to prevent subsequent revalidation attempts only until
// the entry expires.
const rejectedEntry: RejectedSegmentCacheEntry = candidateEntry as any
rejectedEntry.status = EntryStatus.Rejected
rejectedEntry.rsc = null
// The existing entry supersedes the candidate. Leave the existing entry
// in place and discard the candidate by not inserting it.
//
// We must not mutate the candidate here (e.g. downgrade it to Rejected or
// null out its `rsc`). The caller does not transfer exclusive ownership
// of it: it may already have been fulfilled, resolving its promise to a
// waiter that holds the entry and reads `rsc` off it later. A navigation
// seed is such a waiter, via `waitForSegmentCacheEntry`. Nulling `rsc`
// after the fact resolves that read to `null`, so the waiter loses the
// data it was about to render. Declining to insert it is enough: the
// existing entry stays canonical, and the candidate keeps its valid (if
// less complete) data for any waiter that already took it.
return null
}
......
......@@ -2,16 +2,44 @@ import { NEXT_REQUEST_ID_HEADER } from '../components/app-router-headers'
import { InvariantError } from '../../shared/lib/invariant-error'
export interface DebugChannelReadableWriterPair {
readonly readable: ReadableStream<Uint8Array>
/**
* The remaining, not-yet-handed-out copy of the request's debug stream. A
* request can be decoded more than once (the primary decode plus any stage
* extractions that re-parse a slice of the same response, see
* `decodeStageUntilBoundary`), and each decode needs its own reader. Every
* time a consumer asks for the readable we tee it and reassign this field to
* the remainder, so each consumer gets an independent branch. The remainder
* is only ever tee'd again, never read directly, so it retains every chunk
* from the start and replays the full stream into each new branch.
*/
readable: ReadableStream<Uint8Array>
readonly writer: WritableStreamDefaultWriter<Uint8Array>
}
const pairs = new Map<string, DebugChannelReadableWriterPair>()
/**
* Upper bound on the number of in-memory debug-channel pairs we retain, evicted
* least-recently-used, bounding the live per-request map.
*
* A pair must outlive its stream's close so a late decode of the same response
* (the primary decode plus stage extractions via `decodeStageUntilBoundary`,
* which can run after the channel closed over the WebSocket) still finds the
* buffered data. The cap only needs to exceed the pairs live or recently closed
* at once (bounded by how many prefetch/navigation requests are in flight
* together), so a few dozen leaves ample headroom even for the segment-heavy
* bursts the Instant Navs DevTools capture can produce.
*/
const MAX_DEBUG_CHANNEL_PAIRS = 64
const DB_NAME = '__next_debug_channel'
const STORE_NAME = 'channels'
const CREATED_AT_INDEX = 'createdAt'
const MAX_ENTRIES = 10
/**
* Upper bound on persisted document debug channels in IndexedDB (one per
* document, kept for HTTP-cache restore), evicted oldest-first.
*/
const MAX_PERSISTED_DOCUMENT_CHANNELS = 10
interface DebugChannelEntry {
readonly requestId: string
......@@ -76,7 +104,7 @@ async function persistDebugChannelToIndexedDB(
// scanning, and the cursor deletes commit atomically with the put above.
const countReq = store.count()
countReq.onsuccess = () => {
let entriesToDelete = countReq.result - MAX_ENTRIES
let entriesToDelete = countReq.result - MAX_PERSISTED_DOCUMENT_CHANNELS
if (entriesToDelete <= 0) {
return
}
......@@ -304,56 +332,88 @@ function getNavigationEntry(): NavigationEntry | undefined {
}
}
/**
* Reclaim the least-recently-used debug-channel pairs once the map exceeds
* `MAX_DEBUG_CHANNEL_PAIRS`. The map is iterated in insertion order and we
* re-insert entries on access (see
* `getOrCreateDebugChannelReadableWriterPair`), so the least-recently-used
* pairs sit at the front. Evicting only ever affects future lookups for that
* request id; consumers that already hold a tee branch keep reading
* independently of the map.
*/
function evictExcessDebugChannelPairs(): void {
while (pairs.size > MAX_DEBUG_CHANNEL_PAIRS) {
const oldestRequestId = pairs.keys().next().value
if (oldestRequestId === undefined) {
break
}
pairs.delete(oldestRequestId)
}
}
export function getOrCreateDebugChannelReadableWriterPair(
requestId: string
): DebugChannelReadableWriterPair {
let pair = pairs.get(requestId)
if (!pair) {
// Buffer chunks only for the initial document's debug channel, not for
// client-side navigation requests. Persisted to IndexedDB once complete so
// it can be restored when the browser serves the page from HTTP cache
// (back-forward navigation, tab duplication, etc.).
const chunks: Uint8Array[] | null = requestId === self.__next_r ? [] : null
const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
if (chunks) {
chunks.push(chunk.slice())
}
controller.enqueue(chunk)
},
})
const existingPair = pairs.get(requestId)
if (existingPair) {
// Refresh the LRU recency of an already-known channel by re-inserting it at
// the most-recent position, so a channel that's still being written to or
// read from isn't evicted while a late consumer (e.g. a stage re-decode of
// the same response) still needs it.
pairs.delete(requestId)
pairs.set(requestId, existingPair)
return existingPair
}
pair = { readable, writer: writable.getWriter() }
pairs.set(requestId, pair)
// Buffer chunks only for the initial document's debug channel, not for
// client-side navigation requests. Persisted to IndexedDB once complete so it
// can be restored when the browser serves the page from HTTP cache
// (back-forward navigation, tab duplication, etc.).
const chunks: Uint8Array[] | null = requestId === self.__next_r ? [] : null
pair.writer.closed
.then(async () => {
if (!chunks) {
return
}
// The initial document's debug stream closes while hydration is still
// running, so persisting here would steal main-thread time from it.
// Wait for genuine idle (no timeout): persistence is best-effort, so if
// the page never idles before navigation we skip it and a later restore
// falls back to a reload, rather than forcing a blocking write.
await whenIdle()
await persistDebugChannelToIndexedDB(requestId, chunks)
})
.catch((error) => {
// writer.closed rejected (e.g., stream aborted) — nothing to persist.
console.debug('Debug channel writer closed with error', error)
})
.finally(() => {
pairs.delete(requestId)
// Release the buffered chunk bytes once the channel is done, whether or
// not we were able to persist them.
if (chunks) {
chunks.length = 0
}
})
const { readable, writable } = new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
if (chunks) {
chunks.push(chunk.slice())
}
controller.enqueue(chunk)
},
})
const pair: DebugChannelReadableWriterPair = {
readable,
writer: writable.getWriter(),
}
pairs.set(requestId, pair)
// Retain the pair past its stream's close (see MAX_DEBUG_CHANNEL_PAIRS) and
// bound the map by reclaiming the least-recently-used.
evictExcessDebugChannelPairs()
pair.writer.closed
.then(async () => {
if (!chunks) {
return
}
// The initial document's debug stream closes while hydration is still
// running, so persisting here would steal main-thread time from it. Wait
// for genuine idle (no timeout): persistence is best-effort, so if the
// page never idles before navigation we skip it and a later restore falls
// back to a reload, rather than forcing a blocking write.
await whenIdle()
await persistDebugChannelToIndexedDB(requestId, chunks)
})
.catch((error) => {
// writer.closed rejected (e.g., stream aborted), nothing to persist.
console.debug('Debug channel writer closed with error', error)
})
.finally(() => {
// Keep the now-closed pair in the map so late decodes of this request
// still resolve against its buffered stream; it's reclaimed later by LRU
// eviction. Release the IndexedDB staging buffer now that it's persisted.
if (chunks) {
chunks.length = 0
}
})
return pair
}
......@@ -402,9 +462,13 @@ export function createDebugChannel(
}
}
const { readable } = getOrCreateDebugChannelReadableWriterPair(requestId)
const pair = getOrCreateDebugChannelReadableWriterPair(requestId)
// Hand out a fresh tee branch per consumer and keep the remainder for the
// next one (see the `readable` field doc above).
const [branch, rest] = pair.readable.tee()
pair.readable = rest
return { readable }
return { readable: branch }
}
/**
......
......@@ -14,25 +14,18 @@ import type { InstantNavCookieData } from '../../../../shared/lib/instant-nav-co
const COOKIE_NAME = 'next-instant-navigation-testing'
type InstantNavContentStatus = 'idle' | 'pending' | 'mpa' | 'spa'
type InstantNavStatus =
| InstantNavContentStatus
// Waiting for the refresh action to start (renderingIndicator -> true).
| 'rearming-awaiting-start'
// Refresh in progress, waiting for it to finish (renderingIndicator -> false).
| 'rearming-awaiting-end'
// Refresh finished and the new pending cookie has been written; waiting
// for the CookieStore change event to land so the panel can read it.
// Keeping the status non-idle through this window prevents a flicker
// back to the idle UI between cookie write and cookie change event.
| 'rearming-awaiting-cookie'
// Module-level state machine for the "Continue Rendering" -> re-arm flow.
// The panel is a singleton in the dev overlay, so this is safe. Tracking
// the transition outside React lets us read/write it from both event
// handlers and effects without tripping React Compiler rules. The status
// is exposed to React via a useSyncExternalStore hook so the panel can
// re-render while we wait for the refresh to complete (otherwise the
// panel would flicker back to idle between the cookie delete and re-set).
// During a "Continue Rendering" restart the cookie is briefly absent (it's
// deleted, then re-written as a new pending cookie). The transient "restarting"
// status keeps the panel on "Awaiting navigation..." across that gap instead
// of flickering back to idle until the new pending cookie lands.
type InstantNavStatus = InstantNavContentStatus | 'restarting'
// Transient restart status held at module scope. The panel is a singleton in
// the dev overlay, so this is safe, and it lets us set the status from the
// click handler and clear it from an effect without tripping React Compiler
// rules. It's exposed to React via a useSyncExternalStore hook so the panel
// re-renders (and stays on "Awaiting navigation...") between the cookie delete
// and the new pending cookie landing.
let instantNavTransientStatus: InstantNavStatus = 'idle'
const instantNavStatusSubscribers = new Set<() => void>()
......@@ -51,14 +44,14 @@ function getInstantNavTransientStatus(): InstantNavStatus {
return instantNavTransientStatus
}
function isRearmingStatus(
function isRestartingStatus(
status: InstantNavStatus
): status is Exclude<InstantNavStatus, InstantNavContentStatus> {
return status.startsWith('rearming-')
return status === 'restarting'
}
function getContentStatus(status: InstantNavStatus): InstantNavContentStatus {
if (isRearmingStatus(status)) {
if (isRestartingStatus(status)) {
return 'pending'
}
return status
......@@ -66,10 +59,10 @@ function getContentStatus(status: InstantNavStatus): InstantNavContentStatus {
function getInstantNavStatus(
cookieData: InstantNavCookieData | null,
rearmStatus: InstantNavStatus
restartStatus: InstantNavStatus
): InstantNavStatus {
if (isRearmingStatus(rearmStatus)) {
return rearmStatus
if (isRestartingStatus(restartStatus)) {
return restartStatus
}
if (cookieData?.state === 'spa') {
return 'spa'
......@@ -205,7 +198,7 @@ function clearInstantNavCaptureCookie(): void {
}
export function InstantNavsPanel() {
const { state, dispatch } = useDevOverlayContext()
const { dispatch } = useDevOverlayContext()
const { panel } = usePanelRouterContext()
// The cookie is the sole source of truth for the instant navigation
......@@ -231,49 +224,18 @@ export function InstantNavsPanel() {
}
}, [panel, dispatch])
// State machine for "Continue Rendering" in a captured state (mpa/spa):
// delete the cookie (which triggers a soft refresh via the lock listener),
// wait for the refresh to actually complete, then re-arm capture by
// writing a new pending cookie. We observe completion by watching
// state.renderingIndicator transition false -> true -> false, which is
// driven by useTransition's isPending around the refresh dispatch.
// The transient rearming status lives at module scope so it can be
// read and written from both event handlers and effects.
// Clear the transient restarting status once the new pending cookie has landed
// in the panel's view of cookie state, handing the UI back to the cookie.
useEffect(() => {
if (
instantNavTransientStatus === 'rearming-awaiting-start' &&
state.renderingIndicator
) {
setInstantNavTransientStatus('rearming-awaiting-end')
} else if (
instantNavTransientStatus === 'rearming-awaiting-end' &&
!state.renderingIndicator
) {
setInstantNavTransientStatus('rearming-awaiting-cookie')
if (typeof cookieStore !== 'undefined') {
const cookie: InstantCookie = [0, `p${Math.random()}`]
cookieStore.set({
name: COOKIE_NAME,
value: JSON.stringify(cookie),
path: '/',
})
}
}
}, [state.renderingIndicator])
// Clear the rearm status once the new pending cookie has actually landed
// in the panel's view of cookie state. Until then we keep isRearming true
// so the UI stays on the "Awaiting navigation..." card.
useEffect(() => {
if (
instantNavTransientStatus === 'rearming-awaiting-cookie' &&
instantNavTransientStatus === 'restarting' &&
cookieData?.state === 'pending'
) {
setInstantNavTransientStatus('idle')
}
}, [cookieData?.state])
// While we're waiting for a "Continue Rendering" -> re-arm to finish,
// While we're waiting for a "Continue Rendering" -> restart to finish,
// the cookie is briefly absent. Treat that window as pending so the
// panel keeps showing the "Awaiting navigation..." UI instead of
// flickering back to idle.
......@@ -390,8 +352,22 @@ export function InstantNavsPanel() {
className="instant-nav-capture-button instant-nav-capture-button--inline-icon"
onClick={() => {
if (typeof cookieStore !== 'undefined') {
cookieStore.delete(COOKIE_NAME)
setInstantNavTransientStatus('rearming-awaiting-start')
// Continue Rendering: delete the cookie (which releases the
// lock and triggers a soft refresh for real data via the lock
// listener), then restart capture for the next navigation by
// writing a fresh pending cookie. Chaining the writes keeps
// them as two ordered cookie events (delete -> refresh, then
// restart) rather than coalescing into one, so the refresh runs
// and snapshots the released lock before the restart re-acquires it.
setInstantNavTransientStatus('restarting')
const pendingCookie: InstantCookie = [0, `p${Math.random()}`]
cookieStore.delete(COOKIE_NAME).then(() => {
cookieStore.set({
name: COOKIE_NAME,
value: JSON.stringify(pendingCookie),
path: '/',
})
})
}
}}
disabled={!isLocked || isPending}
......
......@@ -1133,7 +1133,11 @@ async function spawnRuntimePrefetchWithFilledCaches(
requestStore.cookies,
requestStore.draftMode,
onError,
staleTimeIterable
staleTimeIterable,
// This path is only reached on the production Cache Components + Cached
// Navigations renders (the staged Flight response and the HTML hydration
// payload), which set up no React debug channel.
undefined
)
await result.prelude.pipeTo(writable)
......@@ -1407,9 +1411,12 @@ async function generateRuntimePrefetchResult(
requestStore: RequestStore,
isShellPrefetch: boolean
): Promise<RenderResult> {
const { workStore, renderOpts } = ctx
const { isBuildTimePrerendering = false, onInstrumentationRequestError } =
renderOpts
const { workStore, renderOpts, htmlRequestId, requestId } = ctx
const {
isBuildTimePrerendering = false,
onInstrumentationRequestError,
setReactDebugChannel,
} = renderOpts
const { appShells } = renderOpts.experimental
function onFlightDataRenderError(err: DigestedError, silenceLog: boolean) {
......@@ -1469,6 +1476,13 @@ async function generateRuntimePrefetchResult(
}
: { type: 'runtime-only' }
const debugChannel = setReactDebugChannel
? createWebDebugChannel()
: undefined
if (debugChannel && setReactDebugChannel) {
setReactDebugChannel(debugChannel.clientSide, htmlRequestId, requestId)
}
const response = await finalRuntimeServerPrerender(
mode,
ctx,
......@@ -1489,7 +1503,8 @@ async function generateRuntimePrefetchResult(
requestStore.cookies,
requestStore.draftMode,
onError,
staleTimeIterable
staleTimeIterable,
debugChannel?.serverSide
)
applyMetadataFromPrerenderResult(response, metadata, workStore)
......@@ -1675,7 +1690,8 @@ async function finalRuntimeServerPrerender(
cookies: PrerenderStoreModernRuntime['cookies'],
draftMode: PrerenderStoreModernRuntime['draftMode'],
onError: (err: unknown) => string | undefined,
staleTimeIterable: StaleTimeIterable
staleTimeIterable: StaleTimeIterable,
debugChannel: RenderToReadableStreamServerOptions['debugChannel']
) {
const { implicitTags, renderOpts } = ctx
const { ComponentMod, experimental, isDebugDynamicAccesses } = renderOpts
......@@ -1803,6 +1819,7 @@ async function finalRuntimeServerPrerender(
filterStackFrame,
onError,
signal: finalServerController.signal,
debugChannel,
}
)
......
......@@ -48,6 +48,22 @@ export default function Page() {
>
Go to target page &rarr;
</Link>
<Link
href="/target-page/my-post?search=foo"
id="link-to-target-prefetch"
prefetch={true}
style={{
display: 'inline-block',
marginLeft: '0.75rem',
padding: '0.5rem 1rem',
background: '#7c3aed',
color: '#fff',
borderRadius: 6,
textDecoration: 'none',
}}
>
Go to target page (prefetch) &rarr;
</Link>
<Link
href="/mpa-target"
id="link-to-mpa-target"
......
......@@ -3,6 +3,7 @@
*/
const nextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
module.exports = nextConfig
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment