Unverified Commit 0c5881a3 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Unify how server responses are written into the client cache (#96876)

Every flow that writes a server response into the client cache now goes
through a single function, writeServerResponseIntoCache.

This is preparation for subsequent steps in this stack that migrate even
more callers to this unified path.

While we're modifying it, fetchSegmentPrefetchesUsingDynamicRequest is
renamed to fetchSegmentPrefetchesUsingRuntimeRequest: these responses
are produced by a runtime request, and "dynamic" refers to non-cached
data, which prefetch responses never contain.

One subtle fix that fell out of the unification: a runtime prefetch
response that carries no transport data used to make the flow bail
before writing anything; now the shared function rejects the pending
entries it was given, the same as a build id mismatch.
parent 730db756
......@@ -7,14 +7,11 @@ import type { AppRouterState } from './router-reducer-types'
import { transportNodeToFlightRouterState } from '../../../shared/lib/rsc-transport'
import { createInitialCacheNodeForHydration } from './ppr-navigations'
import {
resolveStaleAt,
processRuntimePrefetchStream,
writeRuntimePrefetchStreamIntoCache,
spawnStaticStageCacheWrite,
segmentCacheMap,
writeDynamicRenderResponseIntoCache,
writePrerenderResponseIntoCache,
} from '../segment-cache/cache'
import { decodeTransportTreeIntoRouteTree } from '../segment-cache/decode-server-response'
import { FetchStrategy } from '../segment-cache/types'
import {
UnknownDynamicStaleTime,
computeDynamicStaleAt,
......@@ -149,19 +146,13 @@ export function createInitialRouterState({
byteLength,
undefined
)
const now = Date.now()
const staleAt = await resolveStaleAt(now, staticStageResponse.s)
writePrerenderResponseIntoCache(
now,
FetchStrategy.PPR,
staticStageResponse.t,
undefined, // no build ID mismatch check for initial HTML
staticStageResponse.r ?? null,
staleAt,
spawnStaticStageCacheWrite(
Date.now(),
staticStageResponse,
true, // isResponsePartial
null, // responseHeaders — no build-id check for initial HTML
initialTree,
initialRenderedSearch,
true, // isResponsePartial
segmentCacheMap // hydration writes are bound to the shared map
)
})
......@@ -175,27 +166,23 @@ export function createInitialRouterState({
// the two branches) to avoid unnecessary decoding of the Flight data,
// since we can just take the seed data that we already decoded during
// hydration and write it into the cache directly.
const now = Date.now()
resolveStaleAt(now, initialStaleTime)
.then((staleAt) => {
writePrerenderResponseIntoCache(
now,
FetchStrategy.PPR,
initialTransportData,
undefined, // buildId — not applicable for initial HTML
initialRootVaryParams ?? null,
staleAt,
initialTree,
initialRenderedSearch,
false, // isResponsePartial
segmentCacheMap // hydration writes are bound to the shared map
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the page
// rendered normally, we just won't write into the cache.
})
spawnStaticStageCacheWrite(
Date.now(),
// The transport subset of the initial payload, already decoded
// during hydration. Synthesized so the helper can resolve the
// stale time from the response's own `s` field, the same as the
// truncated branch above.
{
t: initialTransportData,
r: initialRootVaryParams,
s: initialStaleTime,
},
false, // isResponsePartial
null, // responseHeaders — no build-id check for initial HTML
initialTree,
initialRenderedSearch,
segmentCacheMap // hydration writes are bound to the shared map
)
// Cancel the stream clone — fully static path doesn't need it.
initialFlightStreamForCache?.cancel()
......@@ -210,32 +197,16 @@ export function createInitialRouterState({
// subsequent navigations to serve runtime-prefetchable content from cache
// without a separate prefetch request.
if (initialRuntimePrefetchStream != null) {
processRuntimePrefetchStream(
writeRuntimePrefetchStreamIntoCache(
Date.now(),
initialRuntimePrefetchStream,
initialTree,
initialRenderedSearch
)
.then((processed) => {
if (processed !== null) {
writeDynamicRenderResponseIntoCache(
Date.now(),
FetchStrategy.PPRRuntime,
processed.buildId,
processed.isResponsePartial,
processed.headVaryParams,
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null,
segmentCacheMap // hydration writes are bound to the shared map
)
}
})
.catch(() => {
// Runtime prefetch cache write failed. Not fatal — the page rendered
// normally, we just won't cache runtime data.
})
initialRenderedSearch,
segmentCacheMap // hydration writes are bound to the shared map
).catch(() => {
// Runtime prefetch cache write failed. Not fatal — the page rendered
// normally, we just won't cache runtime data.
})
}
}
......
......@@ -41,7 +41,7 @@ import { getNavigationBuildId } from '../../navigation-build-id'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import {
stripIsPartialByte,
createNonTaskyPrefetchResponseStream,
bufferPrefetchResponseBody,
} from '../segment-cache/cache'
import { UnknownDynamicStaleTime } from '../segment-cache/bfcache'
......@@ -67,15 +67,6 @@ export interface FetchServerResponseOptions {
readonly signal?: AbortSignal
}
export type StaticStageData<
T extends
| NavigationFlightResponse
| InitialRSCPayload = NavigationFlightResponse,
> = {
readonly response: T
readonly isResponsePartial: boolean
}
type SpaFetchServerResponseResult = {
transportData: PartialTransportData | null
canonicalUrl: URL
......@@ -84,7 +75,15 @@ type SpaFetchServerResponseResult = {
supportsPerSegmentPrefetching: boolean
postponed: boolean
dynamicStaleTime: number
staticStageData: StaticStageData | null
/**
* Whether the response body was marked partial (contains unresolved
* dynamic holes), read from the leading isPartial byte. Always false when
* Cache Components is disabled. When `staticStageResponse` is non-null,
* this is also its partiality: a complete response is cached whole, a
* partial response is cached as its truncated static-stage prefix.
*/
isResponsePartial: boolean
staticStageResponse: NavigationFlightResponse | null
runtimePrefetchStream: ReadableStream<Uint8Array> | null
responseHeaders: Headers
debugInfo: Array<any> | null
......@@ -271,9 +270,9 @@ export async function fetchServerResponse(
return doMpaNavigation(flightResponse.n)
}
const staticStageData =
const staticStageResponse =
cacheData !== null
? await resolveStaticStageData(cacheData, flightResponse, headers)
? await resolveStaticStageResponse(cacheData, flightResponse, headers)
: null
return {
......@@ -295,7 +294,9 @@ export async function fetchServerResponse(
// When absent (UnknownDynamicStaleTime), the client falls back to the
// global DYNAMIC_STALETIME_MS. The value is in seconds.
dynamicStaleTime: flightResponse.d ?? UnknownDynamicStaleTime,
staticStageData,
isResponsePartial:
cacheData !== null ? cacheData.isResponsePartial : false,
staticStageResponse,
runtimePrefetchStream: flightResponse.p ?? null,
responseHeaders: res.headers,
debugInfo: flightResponsePromise._debugInfo ?? null,
......@@ -437,20 +438,23 @@ export async function processFetch(response: Response): Promise<{
/**
* Resolves the static stage response from the raw `processFetch` outputs and
* the decoded flight response, for writing into the segment cache.
* the decoded flight response, for writing into the segment cache. The
* resolved response's partiality is the whole response's partiality
* (`cacheData.isResponsePartial`): a complete response is resolved whole, a
* partial one as its truncated static-stage prefix.
*
* - Fully static: use the decoded flight response as-is, no truncation needed.
* - Not fully static + `l` field: truncate the body clone at the static stage
* byte boundary and decode.
* - Otherwise: no cache-worthy data.
*/
export async function resolveStaticStageData<
async function resolveStaticStageResponse<
T extends NavigationFlightResponse | InitialRSCPayload,
>(
cacheData: FetchResponseCacheData,
flightResponse: T,
headers: RequestHeaders | undefined
): Promise<StaticStageData<T> | null> {
): Promise<T | null> {
const { isResponsePartial, staticBodyClone } = cacheData
if (staticBodyClone) {
......@@ -458,20 +462,18 @@ export async function resolveStaticStageData<
// Fully static — cache the entire decoded response as-is.
staticBodyClone.cancel()
return { response: flightResponse, isResponsePartial: false }
return flightResponse
}
if (flightResponse.l !== undefined) {
// Partially static — truncate the body clone at the byte boundary and
// decode it.
const staticStageByteLength = await flightResponse.l
const response = await decodeStageUntilBoundary<T>(
return decodeStageUntilBoundary<T>(
staticBodyClone,
staticStageByteLength,
headers
)
return { response, isResponsePartial: true }
}
// No caching — cancel the unused clone.
......@@ -482,19 +484,16 @@ export async function resolveStaticStageData<
}
/**
* Resolves the shell stage of a prerender response, performing a separate
* Flight decode of the byte prefix when the shell differs from the main
* response. Returns null when no separate decode is needed:
* Resolves the shell stage of a prerender response:
*
* - `a === undefined`: server didn't emit shell stage info.
* - `a` resolves to `null`: the shell IS the main response — the caller can
* reuse the existing decoded `flightResponse` if it needs a shell payload.
*
* Returns the decoded shell payload when `a` resolves to a number, i.e.
* the shell is a strict prefix of the response and requires a separate
* decode at that byte boundary.
* - `a === undefined` (server didn't emit shell stage info) or no shell body
* clone: no shell exists — returns null.
* - `a` resolves to `null`: the shell IS the main response — returns
* `flightResponse` itself (callers compare by reference).
* - `a` resolves to a number: the shell is a strict prefix of the response —
* returns a separate Flight decode of the byte prefix.
*/
export async function resolveShellStageData<
export async function resolveShellStageResponse<
T extends NavigationFlightResponse | InitialRSCPayload,
>(
cacheData: FetchResponseCacheData,
......@@ -508,15 +507,20 @@ export async function resolveShellStageData<
}
if (flightResponse.a === undefined) {
// The render wasn't staged — no shell exists.
shellBodyClone.cancel()
return null
}
const shellByteLength = await flightResponse.a
if (shellByteLength === null) {
// Shell == main response — caller reuses the existing flightResponse.
// The shell IS the full response (no shell/full split). Return the full
// response itself — callers detect this case by reference equality —
// rather than collapsing it into null, which would lose the distinction
// from "no shell exists". This mirrors the convention of the per-segment
// prefetch fetch (see fetchAndWritePerSegmentPrefetchResponse in cache.ts).
shellBodyClone.cancel()
return null
return flightResponse
}
return decodeStageUntilBoundary<T>(shellBodyClone, shellByteLength, headers)
......@@ -532,15 +536,14 @@ export async function decodeStageUntilBoundary<T>(
byteLength: number,
headers: RequestHeaders | undefined
): Promise<T> {
const { buffer } = await createNonTaskyPrefetchResponseStream(
responseBodyClone,
byteLength
)
const buffer = await bufferPrefetchResponseBody(responseBodyClone, byteLength)
return decodeBufferedStage<T>(buffer, headers)
}
/**
* Decodes already-buffered Flight response bytes as a stage payload. The
* Decodes already-buffered Flight response bytes as a stage payload. A
* "stage" is a prefix of the staged server render — see `RenderStage` in
* packages/next/src/server/app-render/staged-rendering.ts. The
* bytes are delivered to Flight as a single chunk so all rows are processed
* synchronously in one call — required for the thenable-status reads that
* scope a response's late-resolving metadata (vary params, isPartial, ...)
......
......@@ -36,15 +36,11 @@ import {
waitForSegmentCacheEntry,
markRouteEntryAsDynamicRewrite,
invalidateRouteCacheEntries,
resolveStaleAt,
writePrerenderResponseIntoCache,
processRuntimePrefetchStream,
writeDynamicRenderResponseIntoCache,
spawnStaticStageCacheWrite,
writeRuntimePrefetchStreamIntoCache,
EntryStatus,
} from '../segment-cache/cache'
import { FetchStrategy } from '../segment-cache/types'
import { discoverKnownRoute } from '../segment-cache/optimistic-routes'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import { urlSearchParamsToParsedUrlQuery } from '../../route-params'
import type { NormalizedSearch } from '../segment-cache/cache-key'
import type { CacheMap } from '../segment-cache/cache-map'
......@@ -1840,65 +1836,29 @@ async function fetchMissingDynamicData(
await navigationLock
}
// TODO: Implement Shell extraction as part of Cached Navigations.
// Intentionally holding off on doing this until we decide how the Cached
// Navigations behavior should work in combination with App Shells.
if (routeCacheEntry !== null && result.staticStageData !== null) {
const { response: staticStageResponse, isResponsePartial } =
result.staticStageData
resolveStaleAt(now, staticStageResponse.s)
.then((staleAt) => {
const buildId =
result.responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??
staticStageResponse.b
writePrerenderResponseIntoCache(
now,
FetchStrategy.PPR,
staticStageResponse.t ?? null,
buildId,
staticStageResponse.r ?? null,
staleAt,
dynamicRequestTree,
result.renderedSearch,
isResponsePartial,
map
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the navigation
// completed normally, we just won't write into the cache.
})
if (routeCacheEntry !== null && result.staticStageResponse !== null) {
spawnStaticStageCacheWrite(
now,
result.staticStageResponse,
result.isResponsePartial,
result.responseHeaders,
dynamicRequestTree,
result.renderedSearch,
map
)
}
if (routeCacheEntry !== null && result.runtimePrefetchStream !== null) {
processRuntimePrefetchStream(
writeRuntimePrefetchStreamIntoCache(
now,
result.runtimePrefetchStream,
dynamicRequestTree,
result.renderedSearch
)
.then((processed) => {
if (processed !== null) {
writeDynamicRenderResponseIntoCache(
now,
FetchStrategy.PPRRuntime,
processed.buildId,
processed.isResponsePartial,
processed.headVaryParams,
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null,
map
)
}
})
.catch(() => {
// The runtime prefetch cache write failed. Not fatal — the
// navigation completed normally, we just won't cache runtime data.
})
result.renderedSearch,
map
).catch(() => {
// The runtime prefetch cache write failed. Not fatal — the
// navigation completed normally, we just won't cache runtime data.
})
}
// result.dynamicStaleTime is in seconds (from the server's `d` field).
......
......@@ -78,7 +78,7 @@ export type NavigationSeed = {
// request tree derived from a cached route entry, as during a prefetch:
// divergence then means the entry doesn't describe what the server renders
// — the URL has a rewrite that behaves dynamically (see
// fetchSegmentPrefetchesUsingDynamicRequest). During a navigation the base
// fetchSegmentPrefetchesUsingRuntimeRequest). During a navigation the base
// is the current page's tree, so divergence carries no signal. False when
// there was no base to compare against.
treeDivergedFromBase: boolean
......
......@@ -14,17 +14,14 @@ import {
type NavigationRequestAccumulation,
} from '../router-reducer/ppr-navigations'
import { createHrefFromUrl } from '../router-reducer/create-href-from-url'
import { NEXT_NAV_DEPLOYMENT_ID_HEADER } from '../../../lib/constants'
import {
EntryStatus,
segmentCacheMap,
type SegmentCacheEntry,
readRouteCacheEntry,
deprecated_requestOptimisticRouteCacheEntry,
resolveStaleAt,
writePrerenderResponseIntoCache,
processRuntimePrefetchStream,
writeDynamicRenderResponseIntoCache,
spawnStaticStageCacheWrite,
writeRuntimePrefetchStreamIntoCache,
type FulfilledRouteCacheEntry,
} from './cache'
import { discoverKnownRoute } from './optimistic-routes'
......@@ -515,7 +512,8 @@ async function navigateToUnknownRoute(
couldBeIntercepted,
supportsPerSegmentPrefetching,
dynamicStaleTime,
staticStageData,
isResponsePartial,
staticStageResponse,
runtimePrefetchStream,
responseHeaders,
debugInfo,
......@@ -558,68 +556,29 @@ async function navigateToUnknownRoute(
false // hasDynamicRewrite - not a retry, rewrite detection happens during traversal
)
if (staticStageData !== null) {
const { response: staticStageResponse, isResponsePartial } =
staticStageData
// Write the static stage of the response into the segment cache so that
// subsequent navigations can serve cached static segments instantly.
resolveStaleAt(now, staticStageResponse.s)
.then((staleAt) => {
const buildId =
responseHeaders.get(NEXT_NAV_DEPLOYMENT_ID_HEADER) ??
staticStageResponse.b
// TODO: Implement Shell extraction as part of Cached Navigations.
// Intentionally holding off on doing this until we decide how the
// Cached Navigations behavior should work in combination with App
// Shells.
writePrerenderResponseIntoCache(
now,
FetchStrategy.PPR,
staticStageResponse.t ?? null,
buildId,
staticStageResponse.r ?? null,
staleAt,
currentFlightRouterState,
renderedSearch,
isResponsePartial,
map
)
})
.catch(() => {
// The static stage processing failed. Not fatal — the navigation
// completed normally, we just won't write into the cache.
})
if (staticStageResponse !== null) {
spawnStaticStageCacheWrite(
now,
staticStageResponse,
isResponsePartial,
responseHeaders,
currentFlightRouterState,
renderedSearch,
map
)
}
if (runtimePrefetchStream !== null) {
processRuntimePrefetchStream(
writeRuntimePrefetchStreamIntoCache(
now,
runtimePrefetchStream,
currentFlightRouterState,
renderedSearch
)
.then((processed) => {
if (processed !== null) {
writeDynamicRenderResponseIntoCache(
now,
FetchStrategy.PPRRuntime,
processed.buildId,
processed.isResponsePartial,
processed.headVaryParams,
processed.rootVaryParamsIterable,
processed.staleAt,
processed.navigationSeed,
null,
map
)
}
})
.catch(() => {
// The runtime prefetch cache write failed. Not fatal — the
// navigation completed normally, we just won't cache runtime data.
})
renderedSearch,
map
).catch(() => {
// The runtime prefetch cache write failed. Not fatal — the
// navigation completed normally, we just won't cache runtime data.
})
}
}
......
......@@ -18,7 +18,7 @@ import {
type FulfilledRouteCacheEntry,
type RouteCacheEntry,
type RouteTree,
fetchSegmentPrefetchesUsingDynamicRequest,
fetchSegmentPrefetchesUsingRuntimeRequest,
type PendingSegmentCacheEntry,
type SegmentCacheEntry,
type SegmentBundle,
......@@ -977,7 +977,7 @@ function pingRootRouteTree(
)
if (spawnedEntries.size > 0) {
spawnPrefetchSubtask(
fetchSegmentPrefetchesUsingDynamicRequest(
fetchSegmentPrefetchesUsingRuntimeRequest(
task,
route,
runtimeStrategy,
......@@ -1024,7 +1024,7 @@ function pingRootRouteTree(
let needsDynamicRequest = spawnedEntries.size > 0
if (needsDynamicRequest) {
spawnPrefetchSubtask(
fetchSegmentPrefetchesUsingDynamicRequest(
fetchSegmentPrefetchesUsingRuntimeRequest(
task,
route,
fetchStrategy,
......
......@@ -40,7 +40,7 @@ export const enum FetchStrategy {
//
// These numeric values are client-internal and never cross the wire — the
// `next-router-prefetch` request header values are mapped explicitly in
// fetchSegmentPrefetchesUsingDynamicRequest (cache.ts) — so the members can
// fetchSegmentPrefetchesUsingRuntimeRequest (cache.ts) — so the members can
// be renumbered freely as long as the relative order is preserved.
LoadingBoundary = 0,
// The App Shell variant extracted from a static per-segment prefetch
......
......@@ -26,7 +26,7 @@ const APP_SHELL_PREFETCH_VALUE = '3'
// (`fetchSegmentsOnCacheMissImpl`) and the route tree fetch
// (`fetchRouteOnCacheMiss`).
// - 'runtime': dynamic prefetch requests, issued by
// `fetchSegmentPrefetchesUsingDynamicRequest` in the client. These carry a
// `fetchSegmentPrefetchesUsingRuntimeRequest` in the client. These carry a
// FlightRouterState request tree and a `next-router-prefetch` header value
// of '2' (FetchStrategy.PPRRuntime) or '3' (FetchStrategy.RuntimeShell).
// The other strategies used by that path — LoadingBoundary ('1') and Full
......
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