Unverified Commit 1edced6f authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] Implement `unstable_ensureStatic = "shell" | "prefetch"` (#98191)

Builds on #98129, where we made it possible for shells to be static
while the prefetches depending on where runtime data is accessed:
- `ensureStatic = "shell"` simply defers all runtime tracking until the
prefetch (semantically, it's as if it was gated by `await prefetch()`).
this means that the shell will always be considered static (although the
prefetch can still be runtime)
- `ensureStatic = "prefetch"` is analogous, but means that the prefetch
should be static (semantically, it's as if it was gated by `await
navigation()`). this effectively skips the tracking altogether, and
*both* the shell and the prefetch will be static.
- notably, in this mode, accessing fallback params in an ISR fallback no
longer sets `needsRuntimeRequest` either, because the config disallows
runtime prefetches, even if it'd let us skip waiting for the ISR
prerender to finish.

note that "static" here means "statically prerendered", as opposed to
"rendered on demand via runtime prerender". both options still allow the
prerender to have dynamic holes. disallowing dynamic holes altogether
will be handled by `ensureStatic = "navigation"` in a follow up.

### Implementation notes

i've also renamed `walkNeedsRuntimeCompleteness` to
`walkCanUseRuntimeRequests` -- in practice, the function checks "is this
a PPF route", but being PPF no longer means that runtime completeness is
required, because `ensureStatic` deliberately gets rid of it.
`walkCanUseRuntimeRequests` is a bit more accurate, because it tells us
whether runtime requests are possible at all. This change (and the
associated changes in comments) are in a separate commit for ease of
review.
parent 690f1ad8
...@@ -933,18 +933,10 @@ function pingRootRouteTree( ...@@ -933,18 +933,10 @@ function pingRootRouteTree(
return PrefetchTaskExitStatus.InProgress return PrefetchTaskExitStatus.InProgress
} }
// We may need to do a runtime prefetch for one or more segments. // `pingNewPartOfCacheComponentsTree` may have determined that
// Before checking, we can do some fast checks to bail out of this // we need to do a runtime prefetch for one or more segments.
// branch early. // Bail out early if runtime prefetches are not permitted for this route.
// if (walkCanUseRuntimeRequests(staticWalkStrategy, route)) {
// Runtime prefetches are only issued for walks that require runtime
// completeness — the same per-pass predicate that produced the
// deopt registrations during the traversal above; see the decision
// point in pingNewPartOfCacheComponentsTree. Which segments
// actually need a runtime request — registered directly, or only
// as the fallback after an insufficient static attempt — was
// decided there.
if (walkRequiresRuntimeCompleteness(staticWalkStrategy, route)) {
const runtimeStrategy = const runtimeStrategy =
staticWalkStrategy === FetchStrategy.StaticShell staticWalkStrategy === FetchStrategy.StaticShell
? FetchStrategy.RuntimeShell ? FetchStrategy.RuntimeShell
...@@ -1089,16 +1081,12 @@ function pingStaticHead( ...@@ -1089,16 +1081,12 @@ function pingStaticHead(
// it's derived. // it's derived.
fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell fetchStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell
): void { ): void {
// The head is subject to the same per-pass runtime-completeness contract const headCanUseRuntimeRequests = walkCanUseRuntimeRequests(
// as the route's segments: during a StaticShell walk, and during any walk
// of a Partial Prefetching route, the head needs a response at least as
// complete as a runtime one.
const headRequiresRuntimeCompleteness = walkRequiresRuntimeCompleteness(
fetchStrategy, fetchStrategy,
route route
) )
if ( if (
headRequiresRuntimeCompleteness && headCanUseRuntimeRequests &&
// The head is not a tree node — it hangs off the route root — so the // The head is not a tree node — it hangs off the route root — so the
// static-attempt hints are read from the root's node. (Segments read the // static-attempt hints are read from the root's node. (Segments read the
// hints from their own node; see `pingNewPartOfCacheComponentsTree.`) // hints from their own node; see `pingNewPartOfCacheComponentsTree.`)
...@@ -1140,7 +1128,7 @@ function pingStaticHead( ...@@ -1140,7 +1128,7 @@ function pingStaticHead(
fetchStrategy, fetchStrategy,
true true
) )
if (headRequiresRuntimeCompleteness && needsRuntimeRequest) { if (headCanUseRuntimeRequests && needsRuntimeRequest) {
// The static attempt was insufficient for the head. Deopt to a // The static attempt was insufficient for the head. Deopt to a
// runtime prefetch. (Outside of runtime-completeness contexts the // runtime prefetch. (Outside of runtime-completeness contexts the
// head's signal is unused — a partial static head is filled in by the // head's signal is unused — a partial static head is filled in by the
...@@ -1150,36 +1138,22 @@ function pingStaticHead( ...@@ -1150,36 +1138,22 @@ function pingStaticHead(
} }
/** /**
* Whether the task needs a cache entry at least as complete as a runtime * Whether the task can use runtime requests to prefetch the content.
* response for every segment it walks before the prefetch counts as done.
* Runtime completeness is the universal contract for Partial Prefetching,
* so the predicate is per pass, not per segment:
*
* - Every walk of a route that opts into Partial Prefetching (any segment
* with a partial-prefetching config, or the global `partialPrefetching`
* flag — both surfaced as SubtreeHasPartialPrefetching on the route
* root), in both the Shell and Speculative phases.
* - Every StaticShell walk — the Shell phase's walk, whose target (the
* conceptual App Shell) must be reusable across all params by definition.
* (In practice this is implied by the first case — the Shell phase only
* runs for Partial Prefetching routes.)
* *
* Routes without Partial Prefetching keep the static-only contract: their * This is true for every walk of a route that opts into Partial Prefetching
* walks prefetch static data and partial entries are acceptable — the * (any segment with a partial-prefetching config, or the global `partialPrefetching`
* dynamic holes are filled by the navigation-time request. * flag, indicated by `SubtreeHasPartialPrefetching` on the route root),
* in both the Shell and Speculative phases.
* *
* Note: The runtime contract is affordable because most * Note that this does not mean that the route *will* use runtime requests --
* routes carry the ShouldAttemptStatic{Shell,Prefetch} hints: their segments are * it might be optimized statically, either because it does not use runtime data
* prefetched statically and the responses' own sufficiency signal makes a * in the shell/prefetch, or if it's forced to use static requests by
* runtime request rare. On a hint-unset route, a walked segment deopts * `export const ensureStatic = "shell" | "prefetch" | "navigation"`.
* directly to the batched runtime request.
* *
* This is also the gate for the batched runtime request at the end of * Routes without Partial Prefetching never use runtime requests for prefetches
* pingRootRouteTree; requiring runtime completeness does not itself mean a * (excluding `Full` prefetches)
* runtime request is issued for a given segment — see the decision point in
* pingNewPartOfCacheComponentsTree.
*/ */
function walkRequiresRuntimeCompleteness( function walkCanUseRuntimeRequests(
staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell, staticWalkStrategy: FetchStrategy.PPR | FetchStrategy.StaticShell,
route: FulfilledRouteCacheEntry route: FulfilledRouteCacheEntry
): boolean { ): boolean {
...@@ -1478,26 +1452,21 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1478,26 +1452,21 @@ function pingNewPartOfCacheComponentsTree(
// the shared layouts.) Segments in here default to being prefetched // the shared layouts.) Segments in here default to being prefetched
// statically, at the per-pass strategy derived in pingRootRouteTree. // statically, at the per-pass strategy derived in pingRootRouteTree.
// //
// When the walk requires runtime completeness — an entry at least as // This is where we decide whether we should use runtime requests, if the walk
// complete as a runtime response for every segment before the prefetch // is allowed to do so (see `walkCanUseRuntimeRequests`).
// can complete (see walkRequiresRuntimeCompleteness) — this function is //
// also the per-segment decision point. If the segment's node carries the // If runtime requests are allowed, but the segment's node has one of the
// ShouldAttemptStatic{Shell,Prefetch} hints (the build-time prerender accessed no // `ShouldAttemptStatic{Shell,Prefetch}` hints set (either because the build-time
// runtime data), its subtree is prefetched statically first, // prerender accessed no runtime data, or because of `ensureStatic`), then its
// and the responses themselves decide whether that was enough: every // subtree should be prefetched statically first.
// fulfilled entry carries a needsRuntimeRequest signal. Pending responses // However, the hint may be stale after a revalidation, so we'll also check the
// block the task, so the attempt is serial, never raced: static attempt → // `needsRuntimeRequest` promise on the static response, and will follow up with
// observe → runtime only if needed. Without the hint, the segment deopts // a runtime request if needed.
// directly. Deopting registers the segment's request key in // Pending responses block the task, so the attempt is serial, never raced:
// spawnedRuntimePrefetches; the runtime gate at the end of // static attempt → observe → runtime (if needed).
// pingRootRouteTree issues a single batched runtime request for
// everything that accumulated, and that request re-fetches the whole
// subtree, so the walk stops descending at a deopt.
// //
// Outside a runtime-completeness walk the same needsRuntimeRequest signal // The static hints and `needsRuntimeRequest` have no effect if runtime requests
// is routine and ignored — any partial entry of a page that accesses // are not allowed (i.e. outside of Partial Prefetching).
// runtime data carries it, and the dynamic holes are filled by the
// navigation-time request.
// In PPF, links may skip speculative prefetching if they only need a shell. // In PPF, links may skip speculative prefetching if they only need a shell.
if ( if (
...@@ -1509,10 +1478,7 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1509,10 +1478,7 @@ function pingNewPartOfCacheComponentsTree(
// Constant for the whole pass; recomputed here only because the walk is // Constant for the whole pass; recomputed here only because the walk is
// recursive and the check is cheap. // recursive and the check is cheap.
const requiresRuntimeCompleteness = walkRequiresRuntimeCompleteness( const canUseRuntimeRequests = walkCanUseRuntimeRequests(fetchStrategy, route)
fetchStrategy,
route
)
// A force-disabled segment deliberately does NOT deopt here: disabling // A force-disabled segment deliberately does NOT deopt here: disabling
// prefetch is passive. It never initiates a request — its accumulation // prefetch is passive. It never initiates a request — its accumulation
...@@ -1521,7 +1487,7 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1521,7 +1487,7 @@ function pingNewPartOfCacheComponentsTree(
// on another segment's behalf. // on another segment's behalf.
if ( if (
requiresRuntimeCompleteness && canUseRuntimeRequests &&
!shouldSegmentAttemptStaticRequest(fetchStrategy, tree) !shouldSegmentAttemptStaticRequest(fetchStrategy, tree)
) { ) {
// Deopt directly to a runtime prefetch, without a static attempt. // Deopt directly to a runtime prefetch, without a static attempt.
...@@ -1554,7 +1520,7 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1554,7 +1520,7 @@ function pingNewPartOfCacheComponentsTree(
) )
const bundleInProgress = accumulation.bundle const bundleInProgress = accumulation.bundle
if (requiresRuntimeCompleteness && accumulation.needsRuntimeRequest) { if (canUseRuntimeRequests && accumulation.needsRuntimeRequest) {
// The static attempt for this segment was insufficient. Stop the walk // The static attempt for this segment was insufficient. Stop the walk
// and deopt — the runtime prefetch covers the whole subtree. (Unlike the // and deopt — the runtime prefetch covers the whole subtree. (Unlike the
// direct deopt above, any open bundle is dropped rather than finished: a // direct deopt above, any open bundle is dropped rather than finished: a
...@@ -2283,7 +2249,7 @@ function pingSegmentBundle( ...@@ -2283,7 +2249,7 @@ function pingSegmentBundle(
break break
case EntryStatus.Fulfilled: { case EntryStatus.Fulfilled: {
let willBeSupersededByRuntimeRequest = false let willBeSupersededByRuntimeRequest = false
if (walkRequiresRuntimeCompleteness(fetchStrategy, route)) { if (walkCanUseRuntimeRequests(fetchStrategy, route)) {
const runtimeWouldProvideMore = wouldRuntimeRequestProvideMore( const runtimeWouldProvideMore = wouldRuntimeRequestProvideMore(
nodeEntry, nodeEntry,
fetchStrategy fetchStrategy
......
...@@ -8926,6 +8926,7 @@ async function prerenderToStream( ...@@ -8926,6 +8926,7 @@ async function prerenderToStream(
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one // We don't track vary params during initial prerender, only the final one
varyParamsAccumulator: null, varyParamsAccumulator: null,
ensureStaticLevel,
prerenderDataTracking: null, prerenderDataTracking: null,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
} }
...@@ -8962,6 +8963,7 @@ async function prerenderToStream( ...@@ -8962,6 +8963,7 @@ async function prerenderToStream(
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
// We don't track vary params during initial prerender, only the final one // We don't track vary params during initial prerender, only the final one
varyParamsAccumulator: null, varyParamsAccumulator: null,
ensureStaticLevel,
prerenderDataTracking: null, prerenderDataTracking: null,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
}) })
...@@ -9216,6 +9218,7 @@ async function prerenderToStream( ...@@ -9216,6 +9218,7 @@ async function prerenderToStream(
resumeDataCache, resumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator, varyParamsAccumulator,
ensureStaticLevel,
prerenderDataTracking, prerenderDataTracking,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
} }
...@@ -9271,6 +9274,7 @@ async function prerenderToStream( ...@@ -9271,6 +9274,7 @@ async function prerenderToStream(
resumeDataCache, resumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator, varyParamsAccumulator,
ensureStaticLevel,
prerenderDataTracking, prerenderDataTracking,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
}) })
...@@ -9997,6 +10001,7 @@ async function prerenderToStream( ...@@ -9997,6 +10001,7 @@ async function prerenderToStream(
resumeDataCache: originalResumeDataCache, resumeDataCache: originalResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator: null, varyParamsAccumulator: null,
ensureStaticLevel: null,
prerenderDataTracking: null, prerenderDataTracking: null,
isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true, isFallbackUpgradeable: renderOpts.isFallbackUpgradeable === true,
} }
......
...@@ -23,6 +23,7 @@ import type { ...@@ -23,6 +23,7 @@ import type {
import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking' import type { ValidationBoundaryTracking } from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples' import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
import type { PrerenderDataTracking } from '../dynamic-rendering-utils' import type { PrerenderDataTracking } from '../dynamic-rendering-utils'
import type { EnsureStaticLevel } from './segment-config/ensure-static'
export type WorkUnitPhase = 'action' | 'render' | 'after' export type WorkUnitPhase = 'action' | 'render' | 'after'
...@@ -178,6 +179,7 @@ export interface PrerenderStoreModernServer ...@@ -178,6 +179,7 @@ export interface PrerenderStoreModernServer
readonly stagedRendering: StagedRenderingController | null readonly stagedRendering: StagedRenderingController | null
ensureStaticLevel: EnsureStaticLevel | null
/* /*
* Records usages of non-static data during a prerender to determine * Records usages of non-static data during a prerender to determine
* whether it should be statically optimized. * whether it should be statically optimized.
......
import { InvariantError } from '../shared/lib/invariant-error' import { InvariantError } from '../shared/lib/invariant-error'
import { createPromiseWithResolvers } from '../shared/lib/promise-with-resolvers' import { createPromiseWithResolvers } from '../shared/lib/promise-with-resolvers'
import { EnsureStaticLevel } from './app-render/segment-config/ensure-static'
import { import {
RenderStage, RenderStage,
type StagedRenderingController, type StagedRenderingController,
...@@ -385,6 +386,9 @@ function trackRuntimeDataAccessed( ...@@ -385,6 +386,9 @@ function trackRuntimeDataAccessed(
return return
} }
const ensureStaticLevel =
workUnitStore.ensureStaticLevel ?? EnsureStaticLevel.None
// NOTE: In general, we keep hints in sync with `needsRuntimeRequest`, but they // NOTE: In general, we keep hints in sync with `needsRuntimeRequest`, but they
// don't have to always match. The client re-uses hints for the entire route, // don't have to always match. The client re-uses hints for the entire route,
// while `needsRuntimeRequest` can vary across individual prerendered param values // while `needsRuntimeRequest` can vary across individual prerendered param values
...@@ -405,13 +409,21 @@ function trackRuntimeDataAccessed( ...@@ -405,13 +409,21 @@ function trackRuntimeDataAccessed(
| RenderStage.PrefetchStatic | RenderStage.PrefetchStatic
| null = null | null = null
if (currentStage <= RenderStage.ShellStatic) { if (
currentStage <= RenderStage.ShellStatic &&
// Only track if we're not forcing the shell to be static.
ensureStaticLevel < EnsureStaticLevel.Shell
) {
prerenderDataTracking.shouldAttemptStaticShell = false prerenderDataTracking.shouldAttemptStaticShell = false
firstAffectedStage ??= RenderStage.ShellStatic firstAffectedStage ??= RenderStage.ShellStatic
logRuntimeDeopt?.(expression, 'shell') logRuntimeDeopt?.(expression, 'shell')
} }
if (currentStage <= RenderStage.PrefetchStatic) { if (
currentStage <= RenderStage.PrefetchStatic &&
// Only track if we're not forcing the prefetch to be static.
ensureStaticLevel < EnsureStaticLevel.Prefetch
) {
prerenderDataTracking.shouldAttemptStaticPrefetch = false prerenderDataTracking.shouldAttemptStaticPrefetch = false
// NOTE: if the shell is affected, don't override it. // NOTE: if the shell is affected, don't override it.
firstAffectedStage ??= RenderStage.PrefetchStatic firstAffectedStage ??= RenderStage.PrefetchStatic
...@@ -434,11 +446,13 @@ function trackRuntimeDataAccessed( ...@@ -434,11 +446,13 @@ function trackRuntimeDataAccessed(
// static prefetch would hit) so it does not indicate the need for a runtime // static prefetch would hit) so it does not indicate the need for a runtime
// request and thus does not affect the static hints. // request and thus does not affect the static hints.
// //
// We still set `runtimeDataAccessed` (while keeping the hints static) so that, // If runtime prefetches are not disallowed by `ensureStatic`, then we still
// set `runtimeDataAccessed` (while keeping the hints static). This means that
// if the concrete prerender isn't ready yet and we served the fallback, then // if the concrete prerender isn't ready yet and we served the fallback, then
// the client knows it can use a *runtime* prefetch for speculative links -- // the client knows it can use a *runtime* prefetch for speculative links --
// a runtime prefetch can provide the same content (or more) as the concrete // a runtime prefetch can provide the same content (or more) as the concrete
// prerender would. // prerender would.
if (ensureStaticLevel < EnsureStaticLevel.Prefetch) {
markRuntimeDataAccessWhenStageReached( markRuntimeDataAccessWhenStageReached(
prerenderDataTracking, prerenderDataTracking,
stagedRendering, stagedRendering,
...@@ -446,6 +460,7 @@ function trackRuntimeDataAccessed( ...@@ -446,6 +460,7 @@ function trackRuntimeDataAccessed(
RenderStage.PrefetchStatic RenderStage.PrefetchStatic
) )
logRuntimeUpgradeableFallback?.() logRuntimeUpgradeableFallback?.()
}
break break
} }
// not an upgradeable fallback param access, so we treat it as URL data. // not an upgradeable fallback param access, so we treat it as URL data.
...@@ -453,7 +468,10 @@ function trackRuntimeDataAccessed( ...@@ -453,7 +468,10 @@ function trackRuntimeDataAccessed(
} }
case PrerenderDataKind.UrlData: { case PrerenderDataKind.UrlData: {
// Only deopt the prefetch, not the shell, which cannot access URL data anyway. // Only deopt the prefetch, not the shell, which cannot access URL data anyway.
if (currentStage <= RenderStage.PrefetchStatic) { if (
currentStage <= RenderStage.PrefetchStatic &&
ensureStaticLevel < EnsureStaticLevel.Prefetch
) {
prerenderDataTracking.shouldAttemptStaticPrefetch = false prerenderDataTracking.shouldAttemptStaticPrefetch = false
logRuntimeDeopt?.(expression, 'prefetch') logRuntimeDeopt?.(expression, 'prefetch')
...@@ -463,7 +481,6 @@ function trackRuntimeDataAccessed( ...@@ -463,7 +481,6 @@ function trackRuntimeDataAccessed(
RenderStage.PrefetchStatic RenderStage.PrefetchStatic
) )
} }
break break
} }
} }
......
...@@ -597,6 +597,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -597,6 +597,7 @@ export class AppRouteRouteModule extends RouteModule<
resumeDataCache: prerenderResumeDataCache, resumeDataCache: prerenderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator: null, varyParamsAccumulator: null,
ensureStaticLevel: null,
prerenderDataTracking: null, prerenderDataTracking: null,
isFallbackUpgradeable: false, isFallbackUpgradeable: false,
}) })
...@@ -695,6 +696,7 @@ export class AppRouteRouteModule extends RouteModule< ...@@ -695,6 +696,7 @@ export class AppRouteRouteModule extends RouteModule<
resumeDataCache: prerenderResumeDataCache, resumeDataCache: prerenderResumeDataCache,
hmrRefreshHash: undefined, hmrRefreshHash: undefined,
varyParamsAccumulator: null, varyParamsAccumulator: null,
ensureStaticLevel: null,
prerenderDataTracking: null, prerenderDataTracking: null,
isFallbackUpgradeable: false, isFallbackUpgradeable: false,
}) })
......
...@@ -183,7 +183,7 @@ export type CompressedRefreshState = [url: string, renderedSearch: string] ...@@ -183,7 +183,7 @@ export type CompressedRefreshState = [url: string, renderedSearch: string]
export const enum PrefetchHint { export const enum PrefetchHint {
// NOTE: The 0b00001 bit was previously HasRuntimePrefetch (prefetch: // NOTE: The 0b00001 bit was previously HasRuntimePrefetch (prefetch:
// 'allow-runtime'). Partial Prefetching now implies runtime completeness // 'allow-runtime'). Partial Prefetching allows using runtime requests
// for every segment, so the bit was removed. Do not reuse it without // for every segment, so the bit was removed. Do not reuse it without
// considering caches populated by older builds. // considering caches populated by older builds.
...@@ -193,14 +193,15 @@ export const enum PrefetchHint { ...@@ -193,14 +193,15 @@ export const enum PrefetchHint {
// `partialPrefetching` config). Propagates upward so the root segment // `partialPrefetching` config). Propagates upward so the root segment
// reflects the entire subtree. // reflects the entire subtree.
// //
// Partial Prefetching segments require RUNTIME COMPLETENESS: a prefetch // Partial Prefetching routes may use runtime requests for both shells
// isn't considered done for such a segment until an entry at least as // and prefetches. They *may* be optimized to a use a static request
// complete as a runtime response exists. This does NOT mean the segment // if no runtime data was accessed during the prerender.
// lacks static data — the server emits static data unconditionally, and the // However, If the route has `ensureStatic` configured to "shell", "prefetch",
// scheduler may attempt a static prefetch first (per // or "navigation", we *must* use static requests for the shell (and possibly the
// ShouldAttemptStaticPrefetch), issuing the runtime request only if the // prefetch).
// static response's own `needsRuntimeRequest` signal says it would // Both of these cases are signalled to the scheduler via the
// return more. // `ShouldAttemptStatic{Shell,Prefetch}` hints and the `needsRuntimeRequest`
// promise.
SubtreeHasPartialPrefetching = 0b00010, SubtreeHasPartialPrefetching = 0b00010,
// This segment itself has a loading.tsx boundary. // This segment itself has a loading.tsx boundary.
SegmentHasLoadingBoundary = 0b00100, SegmentHasLoadingBoundary = 0b00100,
...@@ -297,7 +298,7 @@ export const enum PrefetchHint { ...@@ -297,7 +298,7 @@ export const enum PrefetchHint {
* *
* Static prefetching is disabled ONLY by `prefetch: 'force-disabled'` * Static prefetching is disabled ONLY by `prefetch: 'force-disabled'`
* (PrefetchDisabled). Notably, Partial Prefetching segments DO have static * (PrefetchDisabled). Notably, Partial Prefetching segments DO have static
* data even though they require runtime completeness: the server emits it * data even though they can use runtime requests: the server emits it
* unconditionally — it can't be gated on the ShouldAttemptStatic{Shell,Prefetch} * unconditionally — it can't be gated on the ShouldAttemptStatic{Shell,Prefetch}
* hints, because which segments carry static data must be deterministic * hints, because which segments carry static data must be deterministic
* from build-time config. A runtime request may still be needed for the * from build-time config. A runtime request may still be needed for the
......
...@@ -34,13 +34,31 @@ export default function Page() { ...@@ -34,13 +34,31 @@ export default function Page() {
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={linkForSlug('not-prerendered-1-no-cookies-prefetch-auto')} href={linkForSlug('not-prerendered_no-cookies_prefetch-auto')}
prefetch="auto" prefetch="auto"
/> />
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={linkForSlug('not-prerendered-1-no-cookies-prefetch-true')} href={linkForSlug('not-prerendered_no-cookies_prefetch-true')}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={
linkForSlug('not-prerendered_no-cookies_ensure-static-shell') +
'/ensure-static/shell'
}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={
linkForSlug('not-prerendered_no-cookies_ensure-static-prefetch') +
'/ensure-static/prefetch'
}
prefetch={true} prefetch={true}
/> />
</li> </li>
...@@ -50,13 +68,32 @@ export default function Page() { ...@@ -50,13 +68,32 @@ export default function Page() {
<ul> <ul>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={linkForSlug('not-prerendered-2-yes-cookies-prefetch-auto')} href={linkForSlug('not-prerendered_yes-cookies_prefetch-auto')}
prefetch="auto" prefetch="auto"
/> />
</li> </li>
<li> <li>
<DebugLinkAccordion <DebugLinkAccordion
href={linkForSlug('not-prerendered-2-yes-cookies-prefetch-true')} href={linkForSlug('not-prerendered_yes-cookies_prefetch-true')}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={
linkForSlug('not-prerendered_yes-cookies_ensure-static-shell') +
'/ensure-static/shell'
}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={
linkForSlug(
'not-prerendered_yes-cookies_ensure-static-prefetch'
) + '/ensure-static/prefetch'
}
prefetch={true} prefetch={true}
/> />
</li> </li>
......
export const unstable_ensureStatic = 'prefetch'
export { default, generateStaticParams } from '../../page'
export const unstable_ensureStatic = 'shell'
export { default, generateStaticParams } from '../../page'
...@@ -537,7 +537,11 @@ describe('prefetch inlining', () => { ...@@ -537,7 +537,11 @@ describe('prefetch inlining', () => {
'.next/server/prefetch-hints.json' '.next/server/prefetch-hints.json'
) )
// The page awaits fallback params (and no other runtime data), so: // The page uses Cache Components (without partialPrefetching), so both the shell
// and prefetch hints are set -- in Cache Components, prefetches are always static.
//
// The page awaits fallback params (and no other runtime data), so if partialPrefetching
// were enabled, we'd get the following:
// - the shell can be static (ShouldAttemptStaticShell hint set), // - the shell can be static (ShouldAttemptStaticShell hint set),
// - the prefetch is runtime (ShouldAttemptStaticPrefetch hint is NOT set). // - the prefetch is runtime (ShouldAttemptStaticPrefetch hint is NOT set).
expect( expect(
...@@ -546,19 +550,19 @@ describe('prefetch inlining', () => { ...@@ -546,19 +550,19 @@ describe('prefetch inlining', () => {
) )
).toMatchInlineSnapshot(` ).toMatchInlineSnapshot(`
{ {
"hints": "InlinedIntoChild | ShouldAttemptStaticShell", "hints": "InlinedIntoChild | ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch",
"slots": { "slots": {
"children": { "children": {
"hints": "ParentInlinedIntoSelf | InlinedIntoChild | ShouldAttemptStaticShell", "hints": "ParentInlinedIntoSelf | InlinedIntoChild | ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch",
"slots": { "slots": {
"children": { "children": {
"hints": "ParentInlinedIntoSelf | ShouldAttemptStaticShell", "hints": "ParentInlinedIntoSelf | ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch",
"slots": { "slots": {
"children": { "children": {
"hints": "InlinedIntoChild | ShouldAttemptStaticShell", "hints": "InlinedIntoChild | ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch",
"slots": { "slots": {
"children": { "children": {
"hints": "ParentInlinedIntoSelf | HeadInlinedIntoSelf | ShouldAttemptStaticShell", "hints": "ParentInlinedIntoSelf | HeadInlinedIntoSelf | ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch",
"slots": null, "slots": null,
}, },
}, },
......
export const unstable_ensureStatic = false
export { Page as default } from '../../shared'
export const unstable_ensureStatic = 'prefetch'
export { Page as default } from '../../shared'
import { cookies } from 'next/headers'
import { Suspense } from 'react'
export function Page() {
return (
<main>
<p id="page-content">Cookies page shell text</p>
<Suspense fallback={<p id="cookie-loading">Loading cookie...</p>}>
<CookieContent />
</Suspense>
</main>
)
}
async function CookieContent() {
const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none'
return <div id="cookie-content">{`Cookie value: ${value}`}</div>
}
export const unstable_ensureStatic = 'shell'
export { Page as default } from '../../shared'
...@@ -251,6 +251,43 @@ export default function Page() { ...@@ -251,6 +251,43 @@ export default function Page() {
</LinkAccordion> </LinkAccordion>
</li> </li>
</ul> </ul>
<h2>ensureStatic</h2>
<ul>
<li>
<LinkAccordion href="/ensure-static/false/uses-cookies">
Page with <code>ensureStatic = false</code> that uses cookies
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/ensure-static/shell/uses-cookies">
Page with <code>ensureStatic = "shell"</code> that uses cookies
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/ensure-static/shell/uses-cookies"
prefetch={true}
>
Page with <code>ensureStatic = "shell"</code> that uses cookies
(prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/ensure-static/prefetch/uses-cookies">
Page with <code>ensureStatic = "prefetch"</code> that uses cookies
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/ensure-static/prefetch/uses-cookies"
prefetch={true}
>
Page with <code>ensureStatic = "prefetch"</code> that uses cookies
(prefetch=true)
</LinkAccordion>
</li>
</ul>
</main> </main>
) )
} }
...@@ -2137,4 +2137,213 @@ describe('static App Shell prefetch attempt', () => { ...@@ -2137,4 +2137,213 @@ describe('static App Shell prefetch attempt', () => {
}) })
}) })
}) })
describe('unstable_ensureStatic', () => {
describe('unstable_ensureStatic = false', () => {
it('uses a runtime shell for a page that uses cookies', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal the link to the page.
// The page has `unstable_ensureStatic = false`, and uses cookies (with no other dynamic holes).
// It should use a runtime shell.
await act(async () => {
await browser
.elementByCss(
'input[data-link-accordion="/ensure-static/false/uses-cookies"]'
)
.click()
}, [
// Cookies are included in the runtime shell.
{ includes: 'cookie-content', kind: 'runtime' },
// No static request.
{
includes: 'Cookies page shell text',
kind: 'static',
block: 'reject',
},
])
// The shell is complete, so navigating should not require any extra requests.
await act(
() =>
browser
.elementByCss('a[href="/ensure-static/false/uses-cookies"]')
.click(),
'no-requests'
)
})
})
describe('unstable_ensureStatic = "shell"', () => {
it('uses a static shell for a page that uses cookies`', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal a prefetch-auto link to the page.
// The page has `unstable_ensureStatic = "shell"`, and uses cookies.
// It should use a static prefetch.
await act(async () => {
await browser
.elementByCss(
'input[data-prefetch="auto"][data-link-accordion="/ensure-static/shell/uses-cookies"]'
)
.click()
}, [
// Static prefetch (for the shell)
{
includes: 'Cookies page shell text',
kind: 'static',
},
// No runtime requests
{
includes: 'Cookies page shell text',
kind: 'runtime',
block: 'reject',
},
])
// The shell has a dynamic hole from `cookies()`, so navigating should spawn an
// extra request to fill it in.
await act(
() =>
browser
.elementByCss('a[href="/ensure-static/shell/uses-cookies"]')
.click(),
[{ includes: 'cookie-content' }]
)
})
it('uses a static shell and a runtime prefetch for a `prefetch={true}` link to a page that uses cookies`', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal a prefetch-true link to the page.
// The page has `unstable_ensureStatic = "shell"`, and uses cookies.
// It should use a static prefetch, and a runtime shell.
await act(async () => {
await browser
.elementByCss(
'input[data-prefetch="true"][data-link-accordion="/ensure-static/shell/uses-cookies"]'
)
.click()
}, [
// Static prefetch (for the shell)
{
includes: 'Cookies page shell text',
kind: 'static',
},
// Runtime prefetch
{
includes: 'cookie-content',
kind: 'runtime',
},
])
// The shell was partial, but the prefetch is complete, so we should not need any requests to navigate.
await act(
() =>
browser
.elementByCss('a[href="/ensure-static/shell/uses-cookies"]')
.click(),
'no-requests'
)
})
})
describe('unstable_ensureStatic = "prefetch"', () => {
it('uses a static request for a link to a page that uses cookies', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal a prefetch-auto link to the page.
// The page has `unstable_ensureStatic = "prefetch"`, and uses cookies (with no other dynamic holes).
// It should use a static prefetch.
await act(async () => {
await browser
.elementByCss(
'input[data-prefetch="auto"][data-link-accordion="/ensure-static/prefetch/uses-cookies"]'
)
.click()
}, [
// Static prefetch
{
includes: 'Cookies page shell text',
kind: 'static',
},
// No runtime requests.
{ includes: 'cookie-content', kind: 'runtime', block: 'reject' },
])
// The prefetch has a dynamic hole from `cookies()`, so navigating should spawn an
// extra request to fill it in.
await act(
() =>
browser
.elementByCss('a[href="/ensure-static/prefetch/uses-cookies"]')
.click(),
[{ includes: 'cookie-content' }]
)
})
it('uses a static request for a `prefetch={true}` link to a page that uses cookies', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal a prefetch-true link to the page.
// The page has `unstable_ensureStatic = "prefetch"`, and uses cookies (with no other dynamic holes).
// It should use a static prefetch.
await act(async () => {
await browser
.elementByCss(
'input[data-prefetch="true"][data-link-accordion="/ensure-static/prefetch/uses-cookies"]'
)
.click()
}, [
// Static prefetch
{
includes: 'Cookies page shell text',
kind: 'static',
},
// No runtime requests.
{ includes: 'cookie-content', kind: 'runtime', block: 'reject' },
])
// The prefetch has a dynamic hole from `cookies()`, so navigating should spawn an
// extra request to fill it in.
await act(
() =>
browser
.elementByCss('a[href="/ensure-static/prefetch/uses-cookies"]')
.click(),
[{ includes: 'cookie-content' }]
)
})
})
})
}) })
...@@ -667,6 +667,7 @@ async function readNormalizedNFT(next, name) { ...@@ -667,6 +667,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/server/app-render/instant-validation/boundary-tracking.js", "/node_modules/next/dist/server/app-render/instant-validation/boundary-tracking.js",
"/node_modules/next/dist/server/app-render/module-loading/track-module-loading.external.js", "/node_modules/next/dist/server/app-render/module-loading/track-module-loading.external.js",
"/node_modules/next/dist/server/app-render/module-loading/track-module-loading.instance.js", "/node_modules/next/dist/server/app-render/module-loading/track-module-loading.instance.js",
"/node_modules/next/dist/server/app-render/segment-config/ensure-static.js",
"/node_modules/next/dist/server/app-render/staged-rendering.js", "/node_modules/next/dist/server/app-render/staged-rendering.js",
"/node_modules/next/dist/server/app-render/sync-io-messages.js", "/node_modules/next/dist/server/app-render/sync-io-messages.js",
"/node_modules/next/dist/server/app-render/work-async-storage-instance.js", "/node_modules/next/dist/server/app-render/work-async-storage-instance.js",
...@@ -675,6 +676,7 @@ async function readNormalizedNFT(next, name) { ...@@ -675,6 +676,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/server/app-render/work-unit-async-storage.external.js", "/node_modules/next/dist/server/app-render/work-unit-async-storage.external.js",
"/node_modules/next/dist/server/dev/browser-logs/file-logger.js", "/node_modules/next/dist/server/dev/browser-logs/file-logger.js",
"/node_modules/next/dist/server/dynamic-rendering-utils.js", "/node_modules/next/dist/server/dynamic-rendering-utils.js",
"/node_modules/next/dist/server/lib/app-dir-module.js",
"/node_modules/next/dist/server/lib/incremental-cache/memory-cache.external.js", "/node_modules/next/dist/server/lib/incremental-cache/memory-cache.external.js",
"/node_modules/next/dist/server/lib/incremental-cache/shared-cache-controls.external.js", "/node_modules/next/dist/server/lib/incremental-cache/shared-cache-controls.external.js",
"/node_modules/next/dist/server/lib/incremental-cache/tags-manifest.external.js", "/node_modules/next/dist/server/lib/incremental-cache/tags-manifest.external.js",
...@@ -720,6 +722,8 @@ async function readNormalizedNFT(next, name) { ...@@ -720,6 +722,8 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.js", "/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.js",
"/node_modules/next/dist/shared/lib/no-fallback-error.external.js", "/node_modules/next/dist/shared/lib/no-fallback-error.external.js",
"/node_modules/next/dist/shared/lib/promise-with-resolvers.js", "/node_modules/next/dist/shared/lib/promise-with-resolvers.js",
"/node_modules/next/dist/shared/lib/router/utils/parse-loader-tree.js",
"/node_modules/next/dist/shared/lib/segment.js",
"/node_modules/next/dist/shared/lib/server-reference-info.js", "/node_modules/next/dist/shared/lib/server-reference-info.js",
"/node_modules/react/cjs/react.development.js", "/node_modules/react/cjs/react.development.js",
"/node_modules/react/cjs/react.production.js", "/node_modules/react/cjs/react.production.js",
......
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