Unverified Commit 00f25a86 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Partial Prefetching] Small optimizations and fixes (#99695)

Fixes a few oversights in the Partial Prefetching implementation that I
discovered while working on a larger refactor. I've moved these into a
separate PR so they can be reviewed independently of the upcoming
restructuring.

These can be reviewed commit-by-commit.
parent 8f761662
......@@ -592,7 +592,6 @@ async function generateDynamicRSCPayload(
skipPageRendering?: boolean
staleTimeIterable?: AsyncIterable<number>
shellByteLengthPromise?: Promise<number | null>
shellUsedSessionDataPromise?: Promise<boolean>
runtimePrefetchStream?: ReadableStream<Uint8Array>
}
): Promise<RSCPayload> {
......@@ -748,9 +747,6 @@ async function generateDynamicRSCPayload(
if (options?.shellByteLengthPromise !== undefined) {
baseResponse.a = options.shellByteLengthPromise
}
if (options?.shellUsedSessionDataPromise !== undefined) {
baseResponse.w = options.shellUsedSessionDataPromise
}
if (options?.runtimePrefetchStream !== undefined) {
baseResponse.p = options.runtimePrefetchStream
......@@ -1142,7 +1138,6 @@ async function spawnRuntimePrefetchWithFilledCaches(
// We want to be able to rewind the result to a session shell.
const mode: RuntimePrerenderMode & { type: 'navigation' } = {
type: 'navigation',
shellUsedSessionDataDeferred: createPromiseWithResolvers(),
shellByteLengthDeferred: createPromiseWithResolvers(),
}
......@@ -1152,7 +1147,6 @@ async function spawnRuntimePrefetchWithFilledCaches(
generateDynamicRSCPayload.bind(null, ctx, {
staleTimeIterable,
shellByteLengthPromise: mode.shellByteLengthDeferred.promise,
shellUsedSessionDataPromise: mode.shellUsedSessionDataDeferred.promise,
}),
prerenderResumeDataCache,
rootParams,
......@@ -1527,13 +1521,9 @@ async function generateRuntimePrefetchResult(
)
const mode: RuntimePrerenderMode = isShellPrefetch
? {
type: 'session-shell-only',
shellUsedSessionDataDeferred: createPromiseWithResolvers(),
}
? { type: 'session-shell-only' }
: {
type: 'rewindable-session-shell',
shellUsedSessionDataDeferred: createPromiseWithResolvers(),
shellByteLengthDeferred: createPromiseWithResolvers(),
}
......@@ -1564,7 +1554,6 @@ async function generateRuntimePrefetchResult(
mode.type === 'rewindable-session-shell'
? mode.shellByteLengthDeferred.promise
: undefined,
shellUsedSessionDataPromise: mode.shellUsedSessionDataDeferred.promise,
}),
prerenderResumeDataCache,
rootParams,
......@@ -1753,18 +1742,13 @@ function prependIsPartialByteToChunks(
}
type RuntimePrerenderMode =
| {
type: 'session-shell-only'
shellUsedSessionDataDeferred: PromiseWithResolvers<boolean>
}
| { type: 'session-shell-only' }
| {
type: 'rewindable-session-shell'
shellUsedSessionDataDeferred: PromiseWithResolvers<boolean>
shellByteLengthDeferred: PromiseWithResolvers<number | null>
}
| {
type: 'navigation'
shellUsedSessionDataDeferred: PromiseWithResolvers<boolean>
shellByteLengthDeferred: PromiseWithResolvers<number | null>
}
......@@ -1899,6 +1883,10 @@ async function finalRuntimeServerPrerender(
}
}
// Whether resolving link data unblocked new content. We check this right
// after the PrefetchRuntime stage, before anything later is flushed.
let didLinkDataUnblockNewContent = false
await runInSequentialTasks(
async () => {
stageController.advanceStage(RenderStage.ShellStatic)
......@@ -1955,25 +1943,9 @@ async function finalRuntimeServerPrerender(
() => {
if (checkUnexpectedAbort()) return
// Check if session data unblocked new content in the shell.
const didSessionDataUnblockNewContent =
stageByteLengths[RenderStage.ShellRuntime] >
stageByteLengths[RenderStage.Static]
mode.shellUsedSessionDataDeferred.resolve(didSessionDataUnblockNewContent)
if ('shellByteLengthDeferred' in mode) {
// If advancing to the PrefetchRuntime stage didn't unblock new content,
// then the result does not depend on link data and can be used as a shell (indicated via `null`).
// Otherwise, send a byte length to indicate where the shell content ends.
const didLinkDataUnblockNewContent =
stageByteLengths[RenderStage.PrefetchRuntime] >
stageByteLengths[RenderStage.ShellRuntime]
mode.shellByteLengthDeferred.resolve(
didLinkDataUnblockNewContent
? stageByteLengths[RenderStage.ShellRuntime]
: null
)
}
didLinkDataUnblockNewContent =
stageByteLengths[RenderStage.PrefetchRuntime] >
stageByteLengths[RenderStage.ShellRuntime]
},
() => {
if (checkUnexpectedAbort()) return
......@@ -1988,6 +1960,28 @@ async function finalRuntimeServerPrerender(
// which is scheduled in a (fast) immediate, so we do this in a separate task
// (fast immediates will be drained at the end of the task, so in the next task we know we're done flushing)
// An aborted render emits no more chunks, so there's no offset to send.
if (
'shellByteLengthDeferred' in mode &&
!finalServerController.signal.aborted
) {
// If neither link data nor `navigation()` unblocked new content, then
// the result can be used as a shell (indicated via `null`). Otherwise,
// send a byte length to indicate where the shell content ends.
// NOTE: we must capture this *before* closing the accumulators below,
// which emit new rows. If the render stopped before the
// NavigationRuntime stage, that stage's count is the same as
// PrefetchRuntime's.
const didNavigationUnblockNewContent =
stageByteLengths[RenderStage.NavigationRuntime] >
stageByteLengths[RenderStage.PrefetchRuntime]
mode.shellByteLengthDeferred.resolve(
didLinkDataUnblockNewContent || didNavigationUnblockNewContent
? stageByteLengths[RenderStage.ShellRuntime]
: null
)
}
staleTimeIterable.close()
finishAccumulatingVaryParams(varyParamsAccumulator)
},
......
......@@ -336,7 +336,12 @@ function createStaticPrerenderParams(
)
}
if (isEmptyParams(underlyingParams)) {
// An optional catch-all with no value isn't a property of the params
// object, but reading it is still a param read, so the route has params.
if (
isEmptyParams(underlyingParams) &&
optionalCatchAllParamName === null
) {
// This route has no params.
return makeUntrackedParams(userspaceParams)
}
......@@ -356,6 +361,7 @@ function createStaticPrerenderParams(
// by delaying them to the static stage. However, root params are allowed in shells,
// so if all the params are root params, they can be included as well.
if (
optionalCatchAllParamName !== null ||
!allParamsAreRootParams(underlyingParams, prerenderStore.rootParams)
) {
const staticParamsStage =
......@@ -423,13 +429,18 @@ function createRuntimePrerenderParams(
)
}
if (isEmptyParams(underlyingParams)) {
// An absent optional catch-all is still a param (see
// createStaticPrerenderParams).
if (isEmptyParams(underlyingParams) && optionalCatchAllParamName === null) {
// This route has no params.
return makeUntrackedParams(userspaceParams)
}
// Root params are allowed in shells, so we allow them to resolve without a delay.
if (allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {
if (
optionalCatchAllParamName === null &&
allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)
) {
return makeUntrackedParams(userspaceParams)
}
......@@ -496,6 +507,7 @@ function createRenderParamsForPage(
stagedRendering,
asyncApiPromises,
underlyingParams,
optionalCatchAllParamName,
userspaceParams
)
}
......@@ -521,6 +533,7 @@ function createStagedRenderParams(
stagedRendering: NonNullable<RequestStore['stagedRendering']>,
asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,
underlyingParams: Params,
optionalCatchAllParamName: string | null,
userspaceParams: Params
) {
const promise = createStagedRenderParamsImpl(
......@@ -528,6 +541,7 @@ function createStagedRenderParams(
stagedRendering,
asyncApiPromises,
underlyingParams,
optionalCatchAllParamName,
userspaceParams
)
if (process.env.NODE_ENV === 'development') {
......@@ -547,11 +561,13 @@ function createStagedRenderParamsImpl(
asyncApiPromises: NonNullable<RequestStore['asyncApiPromises']>,
/** The actual param values, without any instrumentation */
underlyingParams: Params,
/** An optional catch-all param with no value, which is still a param */
optionalCatchAllParamName: string | null,
/** The params object to return to userspace, possibly wrapped in a proxy */
userspaceParams: Params
) {
// If the route has no params, they should resolve immediately.
if (isEmptyParams(underlyingParams)) {
if (isEmptyParams(underlyingParams) && optionalCatchAllParamName === null) {
return makeUntrackedParams(userspaceParams)
}
......@@ -570,7 +586,10 @@ function createStagedRenderParamsImpl(
// If we're rendering with shells, even static params must be delayed to exclude them from the shell.
// However, root params are allowed in shells, so if all the params are root params, they can be included as well.
if (!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)) {
if (
optionalCatchAllParamName !== null ||
!allParamsAreRootParams(underlyingParams, workUnitStore.rootParams)
) {
// For a dynamic request we generally want to recover a static shell,
// so static params can resolve in the static stage, because session
// shells are handled with a separate render.
......
......@@ -573,14 +573,6 @@ type NavigationFlightResponseBase = {
* response.
*/
u?: Promise<boolean>
/**
* shellUsedSessionData — present only in runtime-shell prefetch
* responses: true if resolving session data unblocked new content in the
* shell. Only meaningful where there's a proper session shell.
* Promise-encoded so the answer rewinds with a truncated decode.
* Currently has no client consumer; emitted for forward compatibility.
*/
w?: Promise<boolean>
/**
* isUpgradeableISRFallback — present (true) iff this is a per-segment
* prefetch response generated from a fallback shell render (i.e. the page
......
......@@ -20,18 +20,14 @@ describe('segment cache - static shell vary params regression', () => {
// which replaces every non-root param with Fallback. That's only correct
// when the payload really is the param-independent shell.
//
// When a route renders with no dynamic hole, the response has no shell/full
// split — the "shell" payload IS the concrete render for the params that
// were requested. Keying it at the wildcard path published one param's page
// as the answer for every other param value, and recorded it at the highest
// tier, so later navigations rendered the wrong page and skipped the network
// entirely.
// On an optional catch-all, the index (empty slug) is the case that hit
// this: prefetching /docs poisoned /docs/alpha and /docs/beta, so later
// navigations rendered the index page and skipped the network entirely.
//
// On an optional catch-all, the index (empty slug) is the case that hits
// this: prefetching /docs poisoned /docs/alpha and /docs/beta.
//
// The fix makes the server-reported vary params authoritative, so the shell
// path is used exactly when the segment really is param-independent.
// The fix keys entries by the vary params the server reports, so we only
// use the shell path when the segment really doesn't depend on the params.
// The server also keeps the index's absent slug out of the shell, like any
// other param, so the shared shell has no slug-dependent content.
it('does not serve the catch-all index page for a different slug', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
......@@ -41,9 +37,8 @@ describe('segment cache - static shell vary params regression', () => {
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Prefetch the fully static index of the optional catch-all route. Its
// response has no shell/full split, so this is the write that used to land
// in the param-wildcard slot.
// Prefetch the fully static index of the optional catch-all route. This is
// the payload that used to be stored at the shell vary path.
await act(
async () => {
await browser.elementByCss('input[data-link-accordion="/docs"]').click()
......@@ -59,24 +54,26 @@ describe('segment cache - static shell vary params regression', () => {
)
}, 'no-requests')
// Now prefetch a different slug on the same route. Before the fix the
// index's page segment was sitting in the wildcard slot marked complete,
// so this fired no request at all for the page content and this
// expectation would time out.
// Now prefetch a different slug on the same route. The shared shell is
// already cached, and a shell link only needs the shell, so nothing is
// requested.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/docs/alpha"]')
.click()
}, 'no-requests')
// The navigation fetches alpha's page. Before the fix, the index's page
// segment was stored at the shell vary path and marked complete, so this
// rendered the index page without a request.
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/docs/alpha"]')
.click()
await browser.elementByCss('a[href="/docs/alpha"]').click()
},
{ includes: 'Docs: alpha' }
)
await act(async () => {
await browser.elementByCss('a[href="/docs/alpha"]').click()
expect(await browser.elementById('docs-page-alpha').text()).toBe(
'Docs: alpha'
)
}, 'no-requests')
expect(await browser.elementById('docs-page-alpha').text()).toBe(
'Docs: alpha'
)
})
})
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