Unverified Commit 92042340 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Remove params from segment path (#82249)

When performing a segment prefetch, we send a "segment path" to the
server, which represents the particular segment that we're requesting.
Originally, I thought these needed to fully encode all the param values,
but since we already request the segments within the context of a
particular target page, it's unnecessary — the base URL already contains
all the param information (and is indeed the source of truth for where
the param values come from). The only thing we need to put in the paths
are the param names.

On the client, though, these segments are cached across pages (that's
the whole point of the Segment Cache). So in the prefetch cache, we do
need to cache them by their concrete param values.

Splitting out the param names and the param values into separate keys
will allow us to implement "fallback PPR" behavior for the client, where
if a segment entry does not reference a particular param, it can be
reused for all possible values of that param. (We already do this for
search strings.)

For now, I've split the current "segment path" key into two separate
keys, which I'm calling the "cache key" and the "request key". It's a
bit confusing since we have so many different types of cache keys, but I
think it's OK for now — this will be refactored soon anyway to support
the fallback PPR behavior.

Despite the line count, most of this PR is just a mechanical refactor.
Most of it was done by tab completion in Cursor. The substance of the
change is in the `segment-value-encoding.ts` file.
parent 6e20a10d
......@@ -274,7 +274,7 @@ function readRenderSnapshotFromCache(
let loading: LoadingModuleData | Promise<LoadingModuleData> = null
let isPartial: boolean = true
const segmentEntry = readSegmentCacheEntry(now, route, tree.key)
const segmentEntry = readSegmentCacheEntry(now, route, tree.cacheKey)
if (segmentEntry !== null) {
switch (segmentEntry.status) {
case EntryStatus.Fulfilled: {
......
......@@ -38,6 +38,7 @@ import {
addSearchParamsIfPageSegment,
PAGE_SEGMENT_KEY,
} from '../../../shared/lib/segment'
import type { SegmentCacheKey } from '../../../shared/lib/segment-cache/segment-value-encoding'
const scheduleMicrotask =
typeof queueMicrotask === 'function'
......@@ -583,7 +584,10 @@ function pingRootRouteTree(
case FetchStrategy.PPRRuntime:
case FetchStrategy.LoadingBoundary: {
// Prefetch multiple segments using a single dynamic request.
const spawnedEntries = new Map<string, PendingSegmentCacheEntry>()
const spawnedEntries = new Map<
SegmentCacheKey,
PendingSegmentCacheEntry
>()
const dynamicRequestTree = diffRouteTreeAgainstCurrent(
now,
task,
......@@ -658,8 +662,8 @@ function pingPPRRouteTree(
route: FulfilledRouteCacheEntry,
tree: RouteTree
): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {
const segment = readOrCreateSegmentCacheEntry(now, task, route, tree.key)
pingPerSegment(now, task, route, segment, task.key, tree.key)
const segment = readOrCreateSegmentCacheEntry(now, task, route, tree.cacheKey)
pingPerSegment(now, task, route, segment, task.key, tree)
if (tree.slots !== null) {
if (!hasNetworkBandwidth(task)) {
// Stop prefetching segments until there's more bandwidth.
......@@ -848,7 +852,7 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
let refetchMarker: 'refetch' | 'inside-shared-layout' | null =
refetchMarkerContext === null ? 'inside-shared-layout' : null
const segment = readOrCreateSegmentCacheEntry(now, task, route, tree.key)
const segment = readOrCreateSegmentCacheEntry(now, task, route, tree.cacheKey)
switch (segment.status) {
case EntryStatus.Empty: {
// This segment is not cached. Add a refetch marker so the server knows
......@@ -861,7 +865,7 @@ function pingPPRDisabledRouteTreeUpToLoadingBoundary(
// Add the pending cache entry to the result map.
spawnedEntries.set(
tree.key,
tree.cacheKey,
upgradeToPendingSegment(
segment,
// Set the fetch strategy to LoadingBoundary to indicate that the server
......@@ -951,7 +955,7 @@ function pingRouteTreeAndIncludeDynamicData(
// explicit "refetch" marker so the server knows where to start rendering.
// Once the server starts rendering along a path, it keeps rendering the
// entire subtree.
const segment = readOrCreateSegmentCacheEntry(now, task, route, tree.key)
const segment = readOrCreateSegmentCacheEntry(now, task, route, tree.cacheKey)
let spawnedSegment: PendingSegmentCacheEntry | null = null
......@@ -980,7 +984,7 @@ function pingRouteTreeAndIncludeDynamicData(
task,
route,
segment,
tree.key,
tree,
fetchStrategy
)
}
......@@ -1001,7 +1005,7 @@ function pingRouteTreeAndIncludeDynamicData(
task,
route,
segment,
tree.key,
tree,
fetchStrategy
)
}
......@@ -1029,7 +1033,7 @@ function pingRouteTreeAndIncludeDynamicData(
if (spawnedSegment !== null) {
// Add the pending entry to the result map.
spawnedEntries.set(tree.key, spawnedSegment)
spawnedEntries.set(tree.cacheKey, spawnedSegment)
}
// Don't bother to add a refetch marker if one is already present in a parent.
......@@ -1052,7 +1056,7 @@ function pingPerSegment(
route: FulfilledRouteCacheEntry,
segment: SegmentCacheEntry,
routeKey: RouteCacheKey,
segmentKey: string
tree: RouteTree
): void {
switch (segment.status) {
case EntryStatus.Empty:
......@@ -1062,7 +1066,7 @@ function pingPerSegment(
route,
upgradeToPendingSegment(segment, FetchStrategy.PPR),
routeKey,
segmentKey
tree
)
)
break
......@@ -1090,7 +1094,7 @@ function pingPerSegment(
segment,
route,
routeKey,
segmentKey
tree
)
}
break
......@@ -1119,14 +1123,7 @@ function pingPerSegment(
// Because a rejected segment will definitely prevent the segment (and
// all of its children) from rendering, we perform this revalidation
// immediately instead of deferring it to a background task.
pingPPRSegmentRevalidation(
now,
task,
segment,
route,
routeKey,
segmentKey
)
pingPPRSegmentRevalidation(now, task, segment, route, routeKey, tree)
break
default:
segment.fetchStrategy satisfies never
......@@ -1151,7 +1148,7 @@ function pingPPRSegmentRevalidation(
currentSegment: SegmentCacheEntry,
route: FulfilledRouteCacheEntry,
routeKey: RouteCacheKey,
segmentKey: string
tree: RouteTree
): void {
const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(
now,
......@@ -1164,13 +1161,13 @@ function pingPPRSegmentRevalidation(
upsertSegmentOnCompletion(
task,
route,
segmentKey,
tree.cacheKey,
spawnPrefetchSubtask(
fetchSegmentOnCacheMiss(
route,
upgradeToPendingSegment(revalidatingSegment, FetchStrategy.PPR),
routeKey,
segmentKey
tree
)
)
)
......@@ -1194,7 +1191,7 @@ function pingFullSegmentRevalidation(
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
currentSegment: SegmentCacheEntry,
segmentKey: string,
tree: RouteTree,
fetchStrategy: FetchStrategy.Full | FetchStrategy.PPRRuntime
): PendingSegmentCacheEntry | null {
const revalidatingSegment = readOrCreateRevalidatingSegmentEntry(
......@@ -1214,7 +1211,7 @@ function pingFullSegmentRevalidation(
upsertSegmentOnCompletion(
task,
route,
segmentKey,
tree.cacheKey,
waitForSegmentCacheEntry(pendingSegment)
)
return pendingSegment
......@@ -1239,7 +1236,7 @@ function pingFullSegmentRevalidation(
upsertSegmentOnCompletion(
task,
route,
segmentKey,
tree.cacheKey,
waitForSegmentCacheEntry(pendingSegment)
)
return pendingSegment
......@@ -1266,14 +1263,14 @@ const noop = () => {}
function upsertSegmentOnCompletion(
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
key: string,
cacheKey: SegmentCacheKey,
promise: Promise<FulfilledSegmentCacheEntry | null>
) {
// Wait for a segment to finish loading, then upsert it into the cache
promise.then((fulfilled) => {
if (fulfilled !== null) {
// Received new data. Attempt to replace the existing entry in the cache.
const keypath = getSegmentKeypathForTask(task, route, key)
const keypath = getSegmentKeypathForTask(task, route, cacheKey)
upsertSegmentEntry(Date.now(), keypath, fulfilled)
}
}, noop)
......
import type { DynamicParamTypesShort } from '../server/app-render/types'
import { PAGE_SEGMENT_KEY } from '../shared/lib/segment'
import { ROOT_SEGMENT_KEY } from '../shared/lib/segment-cache/segment-value-encoding'
import { ROOT_SEGMENT_REQUEST_KEY } from '../shared/lib/segment-cache/segment-value-encoding'
import {
NEXT_REWRITTEN_PATH_HEADER,
NEXT_REWRITTEN_QUERY_HEADER,
......@@ -93,7 +93,7 @@ export function doesStaticSegmentAppearInURL(segment: string): boolean {
// inferring it on the client based on the segment type. Something like
// a `doesAppearInURL` flag in FlightRouterState.
if (
segment === ROOT_SEGMENT_KEY ||
segment === ROOT_SEGMENT_REQUEST_KEY ||
// For some reason, the loader tree sometimes includes extra __PAGE__
// "layouts" when part of a parallel route. But it's not a leaf node.
// Otherwise, we wouldn't need this special case because pages are
......
......@@ -3915,8 +3915,7 @@ async function prerenderToStream(
flightData,
finalServerPrerenderStore,
ComponentMod,
renderOpts,
fallbackRouteParams
renderOpts
)
// If there are fallback route params, the RSC data is inherently dynamic
......@@ -4130,8 +4129,7 @@ async function prerenderToStream(
flightData,
ssrPrerenderStore,
ComponentMod,
renderOpts,
fallbackRouteParams
renderOpts
)
}
......@@ -4331,8 +4329,7 @@ async function prerenderToStream(
flightData,
prerenderLegacyStore,
ComponentMod,
renderOpts,
fallbackRouteParams
renderOpts
)
}
......@@ -4511,8 +4508,7 @@ async function prerenderToStream(
flightData,
prerenderLegacyStore,
ComponentMod,
renderOpts,
fallbackRouteParams
renderOpts
)
}
......@@ -4637,8 +4633,7 @@ async function collectSegmentData(
fullPageDataBuffer: Buffer,
prerenderStore: PrerenderStore,
ComponentMod: AppPageModule,
renderOpts: RenderOpts,
fallbackRouteParams: FallbackRouteParams | null
renderOpts: RenderOpts
): Promise<Map<string, Buffer> | undefined> {
// Per-segment prefetch data
//
......@@ -4687,7 +4682,6 @@ async function collectSegmentData(
fullPageDataBuffer,
staleTime,
clientReferenceManifest.clientModules as ManifestNode,
serverConsumerManifest,
fallbackRouteParams
serverConsumerManifest
)
}
......@@ -21,13 +21,12 @@ import type {
LoadingModuleData,
} from '../../shared/lib/app-router-context.shared-runtime'
import {
encodeChildSegmentKey,
encodeSegment,
ROOT_SEGMENT_KEY,
type EncodedSegment,
type SegmentRequestKey,
createSegmentRequestKeyPart,
appendSegmentRequestKeyPart,
ROOT_SEGMENT_REQUEST_KEY,
} from '../../shared/lib/segment-cache/segment-value-encoding'
import { getDigestForWellKnownError } from './create-error-handler'
import type { FallbackRouteParams } from '../request/fallback-params'
// Contains metadata about the route tree. The client must fetch this before
// it can fetch any actual segment data.
......@@ -87,13 +86,12 @@ export async function collectSegmentData(
fullPageDataBuffer: Buffer,
staleTime: number,
clientModules: ManifestNode,
serverConsumerManifest: any,
fallbackRouteParams: FallbackRouteParams | null
): Promise<Map<string, Buffer>> {
serverConsumerManifest: any
): Promise<Map<SegmentRequestKey, Buffer>> {
// Traverse the router tree and generate a prefetch response for each segment.
// A mutable map to collect the results as we traverse the route tree.
const resultMap = new Map<string, Buffer>()
const resultMap = new Map<SegmentRequestKey, Buffer>()
// Before we start, warm up the module cache by decoding the page data once.
// Then we can assume that any remaining async tasks that occur the next time
......@@ -122,7 +120,7 @@ export async function collectSegmentData(
// tree, we'll also spawn additional tasks to generate the segment prefetches.
// The promises for these tasks are pushed to a mutable array that we will
// await once the route tree is fully rendered.
const segmentTasks: Array<Promise<[string, Buffer]>> = []
const segmentTasks: Array<Promise<[SegmentRequestKey, Buffer]>> = []
const { prelude: treeStream } = await prerender(
// RootTreePrefetch is not a valid return type for a React component, but
// we need to use a component so that when we decode the original stream
......@@ -130,7 +128,6 @@ export async function collectSegmentData(
// @ts-expect-error
<PrefetchTreeData
fullPageDataBuffer={fullPageDataBuffer}
fallbackRouteParams={fallbackRouteParams}
serverConsumerManifest={serverConsumerManifest}
clientModules={clientModules}
staleTime={staleTime}
......@@ -147,7 +144,7 @@ export async function collectSegmentData(
// Write the route tree to a special `/_tree` segment.
const treeBuffer = await streamToBuffer(treeStream)
resultMap.set('/_tree', treeBuffer)
resultMap.set('/_tree' as SegmentRequestKey, treeBuffer)
// Now that we've finished rendering the route tree, all the segment tasks
// should have been spawned. Await them in parallel and write the segment
......@@ -161,7 +158,6 @@ export async function collectSegmentData(
async function PrefetchTreeData({
fullPageDataBuffer,
fallbackRouteParams,
serverConsumerManifest,
clientModules,
staleTime,
......@@ -170,10 +166,9 @@ async function PrefetchTreeData({
}: {
fullPageDataBuffer: Buffer
serverConsumerManifest: any
fallbackRouteParams: FallbackRouteParams | null
clientModules: ManifestNode
staleTime: number
segmentTasks: Array<Promise<[string, Buffer]>>
segmentTasks: Array<Promise<[SegmentRequestKey, Buffer]>>
onCompletedProcessingRouteTree: () => void
}): Promise<RootTreePrefetch | null> {
// We're currently rendering a Flight response for the route tree prefetch.
......@@ -211,9 +206,8 @@ async function PrefetchTreeData({
flightRouterState,
buildId,
seedData,
fallbackRouteParams,
clientModules,
ROOT_SEGMENT_KEY,
ROOT_SEGMENT_REQUEST_KEY,
segmentTasks
)
......@@ -239,9 +233,8 @@ function collectSegmentDataImpl(
route: FlightRouterState,
buildId: string,
seedData: CacheNodeSeedData | null,
fallbackRouteParams: FallbackRouteParams | null,
clientModules: ManifestNode,
key: string,
requestKey: SegmentRequestKey,
segmentTasks: Array<Promise<[string, Buffer]>>
): TreePrefetch {
// Metadata about the segment. Sent as part of the tree prefetch. Null if
......@@ -256,23 +249,17 @@ function collectSegmentDataImpl(
const childSeedData =
seedDataChildren !== null ? seedDataChildren[parallelRouteKey] : null
const childKey = encodeChildSegmentKey(
key,
const childRequestKey = appendSegmentRequestKeyPart(
requestKey,
parallelRouteKey,
Array.isArray(childSegment) && fallbackRouteParams !== null
? encodeSegmentWithPossibleFallbackParam(
childSegment,
fallbackRouteParams
)
: encodeSegment(childSegment)
createSegmentRequestKeyPart(childSegment)
)
const childTree = collectSegmentDataImpl(
childRoute,
buildId,
childSeedData,
fallbackRouteParams,
clientModules,
childKey,
childRequestKey,
segmentTasks
)
if (slotMetadata === null) {
......@@ -287,7 +274,7 @@ function collectSegmentDataImpl(
// Since we're already in the middle of a render, wait until after the
// current task to escape the current rendering context.
waitAtLeastOneReactRenderTask().then(() =>
renderSegmentPrefetch(buildId, seedData, key, clientModules)
renderSegmentPrefetch(buildId, seedData, requestKey, clientModules)
)
)
} else {
......@@ -307,41 +294,12 @@ function collectSegmentDataImpl(
}
}
function encodeSegmentWithPossibleFallbackParam(
segment: Exclude<FlightRouterStateSegment, string>,
fallbackRouteParams: FallbackRouteParams
): EncodedSegment {
const name = segment[0]
if (!fallbackRouteParams.has(name)) {
// Normal case. No matching fallback parameter.
return encodeSegment(segment)
}
// This segment includes a fallback parameter. During prerendering, a random
// placeholder value was used; however, for segment prefetches, we need the
// segment path to be predictable so the server can create a rewrite for it.
// So, replace the placeholder segment value with a "template" string,
// e.g. `[name]`.
// TODO: This will become a bit cleaner once remove route parameters from the
// server response, and instead add them to the segment keys on the client.
// Instead of a string replacement, like we do here, route params will always
// be encoded in separate step from the rest of the segment, not just in the
// case of fallback params.
const encodedSegment = encodeSegment(segment)
const lastIndex = encodedSegment.lastIndexOf('$')
const encodedFallbackSegment =
// NOTE: This is guaranteed not to clash with the rest of the segment
// because non-simple characters (including [ and ]) trigger a base
// 64 encoding.
encodedSegment.substring(0, lastIndex + 1) + `[${name}]`
return encodedFallbackSegment as EncodedSegment
}
async function renderSegmentPrefetch(
buildId: string,
seedData: CacheNodeSeedData,
key: string,
requestKey: SegmentRequestKey,
clientModules: ManifestNode
): Promise<[string, Buffer]> {
): Promise<[SegmentRequestKey, Buffer]> {
// Render the segment data to a stream.
// In the future, this is where we can include additional metadata, like the
// stale time and cache tags.
......@@ -368,10 +326,10 @@ async function renderSegmentPrefetch(
}
)
const segmentBuffer = await streamToBuffer(segmentStream)
if (key === ROOT_SEGMENT_KEY) {
return ['/_index', segmentBuffer]
if (requestKey === ROOT_SEGMENT_REQUEST_KEY) {
return ['/_index' as SegmentRequestKey, segmentBuffer]
} else {
return [key, segmentBuffer]
return [requestKey, segmentBuffer]
}
}
......
......@@ -4,11 +4,17 @@ import type { Segment as FlightRouterStateSegment } from '../../../server/app-re
// TypeScript trick to simulate opaque types, like in Flow.
type Opaque<K, T> = T & { __brand: K }
export type EncodedSegment = Opaque<'EncodedSegment', string>
export type SegmentRequestKeyPart = Opaque<'SegmentRequestKeyPart', string>
export type SegmentRequestKey = Opaque<'SegmentRequestKey', string>
export type SegmentCacheKeyPart = Opaque<'SegmentCacheKeyPart', string>
export type SegmentCacheKey = Opaque<'SegmentCacheKey', string>
export function encodeSegment(
export const ROOT_SEGMENT_REQUEST_KEY = '' as SegmentRequestKey
export const ROOT_SEGMENT_CACHE_KEY = '' as SegmentCacheKey
export function createSegmentRequestKeyPart(
segment: FlightRouterStateSegment
): EncodedSegment {
): SegmentRequestKeyPart {
if (typeof segment === 'string') {
if (segment.startsWith(PAGE_SEGMENT_KEY)) {
// The Flight Router State type sometimes includes the search params in
......@@ -20,7 +26,7 @@ export function encodeSegment(
// Segment Cache implementation has settled.
// TODO: We should hoist the search params out of the FlightRouterState
// type entirely, This is our plan for dynamic route params, too.
return PAGE_SEGMENT_KEY as EncodedSegment
return PAGE_SEGMENT_KEY as SegmentRequestKeyPart
}
const safeName =
// TODO: FlightRouterState encodes Not Found routes as "/_not-found".
......@@ -31,26 +37,22 @@ export function encodeSegment(
: encodeToFilesystemAndURLSafeString(segment)
// Since this is not a dynamic segment, it's fully encoded. It does not
// need to be "hydrated" with a param value.
return safeName as EncodedSegment
return safeName as SegmentRequestKeyPart
}
const name = segment[0]
const paramValue = segment[1]
const paramType = segment[2]
const safeName = encodeToFilesystemAndURLSafeString(name)
const safeValue = encodeToFilesystemAndURLSafeString(paramValue)
const encodedName = '$' + paramType + '$' + safeName + '$' + safeValue
return encodedName as EncodedSegment
const encodedName = '$' + paramType + '$' + safeName
return encodedName as SegmentRequestKeyPart
}
export const ROOT_SEGMENT_KEY = ''
export function encodeChildSegmentKey(
// TODO: Make segment keys an opaque type, too?
parentSegmentKey: string,
export function appendSegmentRequestKeyPart(
parentRequestKey: SegmentRequestKey,
parallelRouteKey: string,
segment: EncodedSegment
): string {
childRequestKeyPart: SegmentRequestKeyPart
): SegmentRequestKey {
// Aside from being filesystem safe, segment keys are also designed so that
// each segment and parallel route creates its own subdirectory. Roughly in
// the same shape as the source app directory. This is mostly just for easier
......@@ -61,10 +63,33 @@ export function encodeChildSegmentKey(
// common case. Saves some bytes (and it's what the app directory does).
const slotKey =
parallelRouteKey === 'children'
? segment
: `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${segment}`
? childRequestKeyPart
: `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childRequestKeyPart}`
return (parentRequestKey + '/' + slotKey) as SegmentRequestKey
}
return parentSegmentKey + '/' + slotKey
export function createSegmentCacheKeyPart(
requestKeyPart: SegmentRequestKeyPart,
segment: FlightRouterStateSegment
): SegmentCacheKeyPart {
if (typeof segment === 'string') {
return requestKeyPart as any as SegmentCacheKeyPart
}
const paramValue = segment[1]
const safeValue = encodeToFilesystemAndURLSafeString(paramValue)
return (requestKeyPart + '$' + safeValue) as SegmentCacheKeyPart
}
export function appendSegmentCacheKeyPart(
parentSegmentKey: SegmentCacheKey,
parallelRouteKey: string,
childCacheKeyPart: SegmentCacheKeyPart
): SegmentCacheKey {
const slotKey =
parallelRouteKey === 'children'
? childCacheKeyPart
: `@${encodeToFilesystemAndURLSafeString(parallelRouteKey)}/${childCacheKeyPart}`
return (parentSegmentKey + '/' + slotKey) as SegmentCacheKey
}
// Define a regex pattern to match the most common characters found in a route
......
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