Unverified Commit 3fa9f31c authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

fix: updates for resuming postponed in minimal mode (#57375)

Co-authored-by: 's avatarJimmy Lai <11064311+feedthejim@users.noreply.github.com>
parent b8b1ec24
......@@ -28,6 +28,9 @@ import {
MIDDLEWARE_FILENAME,
PAGES_DIR_ALIAS,
INSTRUMENTATION_HOOK_FILENAME,
NEXT_DID_POSTPONE_HEADER,
RSC_PREFETCH_SUFFIX,
RSC_SUFFIX,
} from '../lib/constants'
import { FileType, fileExists } from '../lib/file-exists'
import { findPagesDir } from '../lib/find-pages-dir'
......@@ -135,8 +138,8 @@ import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import {
ACTION,
NEXT_ROUTER_PREFETCH,
RSC,
NEXT_ROUTER_PREFETCH_HEADER,
RSC_HEADER,
RSC_CONTENT_TYPE_HEADER,
RSC_VARY_HEADER,
} from '../client/components/app-router-headers'
......@@ -162,13 +165,19 @@ interface ExperimentalBypassForInfo {
experimentalBypassFor?: RouteHas[]
}
interface ExperimentalPPRInfo {
experimentalPPR: boolean | undefined
}
interface DataRouteRouteInfo {
dataRoute: string | null
prefetchDataRoute: string | null | undefined
}
export interface SsgRoute
extends ExperimentalBypassForInfo,
DataRouteRouteInfo {
DataRouteRouteInfo,
ExperimentalPPRInfo {
initialRevalidateSeconds: Revalidate
srcRoute: string | null
initialStatus?: number
......@@ -177,10 +186,12 @@ export interface SsgRoute
export interface DynamicSsgRoute
extends ExperimentalBypassForInfo,
DataRouteRouteInfo {
routeRegex: string
DataRouteRouteInfo,
ExperimentalPPRInfo {
fallback: string | null | false
routeRegex: string
dataRouteRegex: string | null
prefetchDataRouteRegex: string | null | undefined
}
export type PrerenderManifest = {
......@@ -243,9 +254,12 @@ export type RoutesManifest = {
localeDetection?: false
}
rsc: {
header: typeof RSC
header: typeof RSC_HEADER
didPostponeHeader: typeof NEXT_DID_POSTPONE_HEADER
varyHeader: typeof RSC_VARY_HEADER
prefetchHeader: typeof NEXT_ROUTER_PREFETCH
prefetchHeader: typeof NEXT_ROUTER_PREFETCH_HEADER
suffix: typeof RSC_SUFFIX
prefetchSuffix: typeof RSC_PREFETCH_SUFFIX
}
skipMiddlewareUrlNormalize?: boolean
caseSensitive?: boolean
......@@ -826,13 +840,16 @@ export default async function build(
dataRoutes: [],
i18n: config.i18n || undefined,
rsc: {
header: RSC,
header: RSC_HEADER,
varyHeader: RSC_VARY_HEADER,
prefetchHeader: NEXT_ROUTER_PREFETCH,
prefetchHeader: NEXT_ROUTER_PREFETCH_HEADER,
didPostponeHeader: NEXT_DID_POSTPONE_HEADER,
contentTypeHeader: RSC_CONTENT_TYPE_HEADER,
suffix: RSC_SUFFIX,
prefetchSuffix: RSC_PREFETCH_SUFFIX,
},
skipMiddlewareUrlNormalize: config.skipMiddlewareUrlNormalize,
}
} as RoutesManifest
})
if (rewrites.beforeFiles.length === 0 && rewrites.fallback.length === 0) {
......@@ -1317,6 +1334,7 @@ export default async function build(
minimalMode: ciEnvironment.hasNextSupport,
allowedRevalidateHeaderKeys:
config.experimental.allowedRevalidateHeaderKeys,
experimental: { ppr: config.experimental.ppr === true },
})
incrementalCacheIpcPort = cacheInitialization.ipcPort
......@@ -1676,6 +1694,7 @@ export default async function build(
appStaticPaths.set(originalAppPath, [])
appStaticPathsEncoded.set(originalAppPath, [])
isStatic = true
isPPR = false
}
}
......@@ -1686,10 +1705,13 @@ export default async function build(
}
appDefaultConfigs.set(originalAppPath, appConfig)
// Only generate the app prefetch rsc if the route is
// an app page.
if (
!isStatic &&
!isAppRouteRoute(originalAppPath) &&
!isDynamicRoute(originalAppPath)
!isDynamicRoute(originalAppPath) &&
!isPPR
) {
appPrefetchPaths.set(originalAppPath, page)
}
......@@ -2095,6 +2117,7 @@ export default async function build(
}
}
})
// Append the "well-known" routes we should prerender for, e.g. blog
// post slugs.
additionalSsgPaths.forEach((routes, page) => {
......@@ -2136,6 +2159,13 @@ export default async function build(
})
})
// Ensure we don't generate explicit app prefetches while in PPR.
if (config.experimental.ppr && appPrefetchPaths.size > 0) {
throw new Error(
"Invariant: explicit app prefetches shouldn't generated with PPR"
)
}
for (const [originalAppPath, page] of appPrefetchPaths) {
defaultMap[page] = {
page: originalAppPath,
......@@ -2236,6 +2266,13 @@ export default async function build(
const isRouteHandler = isAppRouteRoute(originalAppPath)
// When this is an app page and PPR is enabled, the route supports
// partial pre-rendering.
const experimentalPPR =
!isRouteHandler && config.experimental.ppr === true
? true
: undefined
// this flag is used to selectively bypass the static cache and invoke the lambda directly
// to enable server actions on static routes
const bypassFor: RouteHas[] = [
......@@ -2266,9 +2303,20 @@ export default async function build(
if (revalidate !== 0) {
const normalizedRoute = normalizePagePath(route)
const dataRoute = isRouteHandler
? null
: path.posix.join(`${normalizedRoute}.rsc`)
let dataRoute: string | null
if (isRouteHandler) {
dataRoute = null
} else {
dataRoute = path.posix.join(`${normalizedRoute}${RSC_SUFFIX}`)
}
let prefetchDataRoute: string | null | undefined
if (experimentalPPR) {
prefetchDataRoute = path.posix.join(
`${normalizedRoute}${RSC_PREFETCH_SUFFIX}`
)
}
const routeMeta: Partial<SsgRoute> = {}
......@@ -2303,10 +2351,12 @@ export default async function build(
finalPrerenderRoutes[route] = {
...routeMeta,
experimentalPPR,
experimentalBypassFor: bypassFor,
initialRevalidateSeconds: revalidate,
srcRoute: page,
dataRoute,
prefetchDataRoute,
}
} else {
hasDynamicData = true
......@@ -2322,7 +2372,16 @@ export default async function build(
if (!hasDynamicData && isDynamicRoute(originalAppPath)) {
const normalizedRoute = normalizePagePath(page)
const dataRoute = path.posix.join(`${normalizedRoute}.rsc`)
const dataRoute = path.posix.join(
`${normalizedRoute}${RSC_SUFFIX}`
)
let prefetchDataRoute: string | null | undefined
if (experimentalPPR) {
prefetchDataRoute = path.posix.join(
`${normalizedRoute}${RSC_PREFETCH_SUFFIX}`
)
}
pageInfos.set(page, {
...(pageInfos.get(page) as PageInfo),
......@@ -2332,6 +2391,7 @@ export default async function build(
// TODO: create a separate manifest to allow enforcing
// dynamicParams for non-static paths?
finalDynamicRoutes[page] = {
experimentalPPR,
experimentalBypassFor: bypassFor,
routeRegex: normalizeRouteRegex(
getNamedRouteRegex(page, false).re.source
......@@ -2350,6 +2410,19 @@ export default async function build(
false
).re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.rsc$')
),
prefetchDataRoute,
prefetchDataRouteRegex:
isRouteHandler || !prefetchDataRoute
? undefined
: normalizeRouteRegex(
getNamedRouteRegex(
prefetchDataRoute.replace(/\.prefetch\.rsc$/, ''),
false
).re.source.replace(
/\(\?:\\\/\)\?\$$/,
'\\.prefetch\\.rsc$'
)
),
}
}
}
......@@ -2566,24 +2639,29 @@ export default async function build(
initialRevalidateSeconds:
exportResult.byPath.get(localePage)?.revalidate ??
false,
experimentalPPR: undefined,
srcRoute: null,
dataRoute: path.posix.join(
'/_next/data',
buildId,
`${file}.json`
),
prefetchDataRoute: undefined,
}
}
} else {
finalPrerenderRoutes[page] = {
initialRevalidateSeconds:
exportResult.byPath.get(page)?.revalidate ?? false,
experimentalPPR: undefined,
srcRoute: null,
dataRoute: path.posix.join(
'/_next/data',
buildId,
`${file}.json`
),
// Pages does not have a prefetch data route.
prefetchDataRoute: undefined,
}
}
// Set Page Revalidation Interval
......@@ -2645,12 +2723,15 @@ export default async function build(
finalPrerenderRoutes[route] = {
initialRevalidateSeconds,
experimentalPPR: undefined,
srcRoute: page,
dataRoute: path.posix.join(
'/_next/data',
buildId,
`${normalizePagePath(route)}.json`
),
// Pages does not have a prefetch data route.
prefetchDataRoute: undefined,
}
// Set route Revalidation Interval
......@@ -2729,6 +2810,7 @@ export default async function build(
routeRegex: normalizeRouteRegex(
getNamedRouteRegex(tbdRoute, false).re.source
),
experimentalPPR: undefined,
dataRoute,
fallback: ssgBlockingFallbackPages.has(tbdRoute)
? null
......@@ -2741,9 +2823,12 @@ export default async function build(
false
).re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.json$')
),
// Pages does not have a prefetch data route.
prefetchDataRoute: undefined,
prefetchDataRouteRegex: undefined,
}
})
const prerenderManifest: PrerenderManifest = {
const prerenderManifest: Readonly<PrerenderManifest> = {
version: 4,
routes: finalPrerenderRoutes,
dynamicRoutes: finalDynamicRoutes,
......@@ -2774,7 +2859,7 @@ export default async function build(
locales: config.i18n?.locales || [],
})
} else {
const prerenderManifest: PrerenderManifest = {
const prerenderManifest: Readonly<PrerenderManifest> = {
version: 4,
routes: {},
dynamicRoutes: {},
......
......@@ -1284,6 +1284,7 @@ export async function buildAppStaticPaths({
CurCacheHandler: CacheHandler,
requestHeaders,
minimalMode: ciEnvironment.hasNextSupport,
experimental: { ppr },
})
return StaticGenerationAsyncStorageWrapper.wrap(
......@@ -1296,7 +1297,7 @@ export async function buildAppStaticPaths({
supportsDynamicHTML: true,
isRevalidate: false,
isBot: false,
ppr,
experimental: { ppr },
},
},
async () => {
......
export const RSC = 'RSC' as const
export const RSC_HEADER = 'RSC' as const
export const ACTION = 'Next-Action' as const
export const NEXT_ROUTER_STATE_TREE = 'Next-Router-State-Tree' as const
export const NEXT_ROUTER_PREFETCH = 'Next-Router-Prefetch' as const
export const NEXT_ROUTER_PREFETCH_HEADER = 'Next-Router-Prefetch' as const
export const NEXT_URL = 'Next-Url' as const
export const RSC_CONTENT_TYPE_HEADER = 'text/x-component' as const
export const RSC_VARY_HEADER =
`${RSC}, ${NEXT_ROUTER_STATE_TREE}, ${NEXT_ROUTER_PREFETCH}, ${NEXT_URL}` as const
`${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_URL}` as const
export const FLIGHT_PARAMETERS = [
[RSC],
[RSC_HEADER],
[NEXT_ROUTER_STATE_TREE],
[NEXT_ROUTER_PREFETCH],
[NEXT_ROUTER_PREFETCH_HEADER],
] as const
export const NEXT_RSC_UNION_QUERY = '_rsc' as const
......@@ -17,11 +17,11 @@ import type {
NextFlightResponse,
} from '../../../server/app-render/types'
import {
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE,
NEXT_RSC_UNION_QUERY,
NEXT_URL,
RSC,
RSC_HEADER,
RSC_CONTENT_TYPE_HEADER,
} from '../app-router-headers'
import { urlToUrlWithoutFlightMarker } from '../app-router'
......@@ -51,13 +51,13 @@ export async function fetchServerResponse(
prefetchKind?: PrefetchKind
): Promise<FetchServerResponseResult> {
const headers: {
[RSC]: '1'
[RSC_HEADER]: '1'
[NEXT_ROUTER_STATE_TREE]: string
[NEXT_URL]?: string
[NEXT_ROUTER_PREFETCH]?: '1'
[NEXT_ROUTER_PREFETCH_HEADER]?: '1'
} = {
// Enable flight response
[RSC]: '1',
[RSC_HEADER]: '1',
// Provide the current router state
[NEXT_ROUTER_STATE_TREE]: encodeURIComponent(
JSON.stringify(flightRouterState)
......@@ -71,7 +71,7 @@ export async function fetchServerResponse(
* - `prefetchKind` is `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully
*/
if (prefetchKind === PrefetchKind.AUTO) {
headers[NEXT_ROUTER_PREFETCH] = '1'
headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'
}
if (nextUrl) {
......@@ -80,7 +80,7 @@ export async function fetchServerResponse(
const uniqueCacheQuery = hexHash(
[
headers[NEXT_ROUTER_PREFETCH] || '0',
headers[NEXT_ROUTER_PREFETCH_HEADER] || '0',
headers[NEXT_ROUTER_STATE_TREE],
headers[NEXT_URL],
].join(',')
......
......@@ -11,7 +11,8 @@ export function createIncrementalCache(
fetchCacheKeyPrefix: string | undefined,
distDir: string,
dir: string,
enabledDirectories: NextEnabledDirectories
enabledDirectories: NextEnabledDirectories,
experimental: { ppr: boolean }
) {
// Custom cache handler overrides.
let CacheHandler: any
......@@ -46,6 +47,7 @@ export function createIncrementalCache(
serverDistDir: path.join(distDir, 'server'),
CurCacheHandler: CacheHandler,
minimalMode: hasNextSupport,
experimental,
})
;(globalThis as any).__incrementalCache = incrementalCache
......
......@@ -19,7 +19,7 @@ import { formatAmpMessages } from '../build/output/index'
import type { AmpPageStatus } from '../build/output/index'
import * as Log from '../build/output/log'
import createSpinner from '../build/spinner'
import { SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants'
import { RSC_SUFFIX, SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants'
import { recursiveCopy } from '../lib/recursive-copy'
import {
BUILD_ID_FILE,
......@@ -504,7 +504,7 @@ export async function exportAppImpl(
: {}),
strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.experimental.deploymentId,
ppr: nextConfig.experimental.ppr === true,
experimental: { ppr: nextConfig.experimental.ppr === true },
}
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......@@ -776,6 +776,12 @@ export async function exportAppImpl(
const endWorkerPromise = workers.end()
// Export mode provide static outputs that are not compatible with PPR mode.
if (!options.buildExport && nextConfig.experimental.ppr) {
// TODO: add message
throw new Error('Invariant: PPR cannot be enabled in export mode')
}
// copy prerendered routes to outDir
if (!options.buildExport && prerenderManifest) {
await Promise.all(
......@@ -838,7 +844,7 @@ export async function exportAppImpl(
await fs.mkdir(dirname(jsonDest), { recursive: true })
const htmlSrc = `${orig}.html`
const jsonSrc = `${orig}${isAppPath ? '.rsc' : '.json'}`
const jsonSrc = `${orig}${isAppPath ? RSC_SUFFIX : '.json'}`
await fs.copyFile(htmlSrc, htmlDest)
await fs.copyFile(jsonSrc, jsonDest)
......
......@@ -9,12 +9,16 @@ import type {
MockedResponse,
} from '../../server/lib/mock-request'
import {
RSC,
RSC_HEADER,
NEXT_URL,
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_PREFETCH_HEADER,
} from '../../client/components/app-router-headers'
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'
import { NEXT_CACHE_TAGS_HEADER } from '../../lib/constants'
import {
NEXT_CACHE_TAGS_HEADER,
RSC_PREFETCH_SUFFIX,
RSC_SUFFIX,
} from '../../lib/constants'
import { hasNextSupport } from '../../telemetry/ci-info'
import { lazyRenderAppPage } from '../../server/future/route-modules/app-page/module.render'
......@@ -25,7 +29,7 @@ export const enum ExportedAppPageFiles {
POSTPONED = 'POSTPONED',
}
export async function generatePrefetchRsc(
async function generatePrefetchRsc(
req: MockedRequest,
path: string,
res: MockedResponse,
......@@ -34,9 +38,17 @@ export async function generatePrefetchRsc(
renderOpts: RenderOpts,
fileWriter: FileWriter
) {
req.headers[RSC.toLowerCase()] = '1'
// When we're in PPR, the RSC payload is emitted as the prefetch payload, so
// attempting to generate a prefetch RSC is an error.
if (renderOpts.experimental.ppr) {
throw new Error(
'Invariant: explicit prefetch RSC cannot be generated with PPR enabled'
)
}
req.headers[RSC_HEADER.toLowerCase()] = '1'
req.headers[NEXT_URL.toLowerCase()] = path
req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] = '1'
renderOpts.supportsDynamicHTML = true
renderOpts.isPrefetch = true
......@@ -56,7 +68,7 @@ export async function generatePrefetchRsc(
await fileWriter(
ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, '.prefetch.rsc'),
htmlFilepath.replace(/\.html$/, RSC_PREFETCH_SUFFIX),
prefetchRscData
)
}
......@@ -102,11 +114,18 @@ export async function exportAppPage(
query,
renderOpts
)
const html = result.toUnchunkedString()
const {
metadata: { pageData, revalidate = false, postponed, fetchTags },
} = result
const { metadata } = result
const flightData = metadata.pageData
const revalidate = metadata.revalidate ?? false
const postponed = metadata.postponed
// Ensure we don't postpone without having PPR enabled.
if (postponed && !renderOpts.experimental.ppr) {
throw new Error('Invariant: page postponed without PPR being enabled')
}
if (revalidate === 0) {
if (isDynamicError) {
......@@ -145,10 +164,29 @@ export async function exportAppPage(
return { revalidate: 0 }
}
// If PPR is enabled, we want to emit a prefetch rsc file for the page
// instead of the standard rsc. This is because the standard rsc will
// contain the dynamic data.
else if (renderOpts.experimental.ppr) {
// If PPR is enabled, we should emit the flight data as the prefetch
// payload.
await fileWriter(
ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, RSC_PREFETCH_SUFFIX),
pageData
)
} else {
// Writing the RSC payload to a file if we don't have PPR enabled.
await fileWriter(
ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, RSC_SUFFIX),
pageData
)
}
let headers: OutgoingHttpHeaders | undefined
if (metadata.fetchTags) {
headers = { [NEXT_CACHE_TAGS_HEADER]: metadata.fetchTags }
if (fetchTags) {
headers = { [NEXT_CACHE_TAGS_HEADER]: fetchTags }
}
// Writing static HTML to a file.
......@@ -172,13 +210,6 @@ export async function exportAppPage(
JSON.stringify(meta, null, 2)
)
// Writing the RSC payload to a file.
await fileWriter(
ExportedAppPageFiles.FLIGHT,
htmlFilepath.replace(/\.html$/, '.rsc'),
flightData
)
return {
// Only include the metadata if the environment has next support.
metadata: hasNextSupport ? meta : undefined,
......
......@@ -60,7 +60,7 @@ export async function exportAppRoute(
notFoundRoutes: [],
},
renderOpts: {
ppr: false,
experimental: { ppr: false },
originalPathname: page,
nextExport: true,
supportsDynamicHTML: false,
......
......@@ -224,7 +224,9 @@ async function exportPageImpl(
fetchCacheKeyPrefix,
distDir,
dir,
enabledDirectories
enabledDirectories,
// PPR is not available for Pages.
{ ppr: false }
)
: undefined
......
......@@ -8,6 +8,9 @@ export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =
export const NEXT_DID_POSTPONE_HEADER = 'x-nextjs-postponed'
export const RSC_PREFETCH_SUFFIX = '.prefetch.rsc'
export const RSC_SUFFIX = '.rsc'
export const NEXT_CACHE_TAGS_HEADER = 'x-next-cache-tags'
export const NEXT_CACHE_SOFT_TAGS_HEADER = 'x-next-cache-soft-tags'
export const NEXT_CACHE_REVALIDATED_TAGS_HEADER = 'x-next-revalidated-tags'
......
......@@ -9,7 +9,7 @@ import type { SizeLimit } from '../../../types'
import {
ACTION,
RSC,
RSC_HEADER,
RSC_CONTENT_TYPE_HEADER,
} from '../../client/components/app-router-headers'
import { isNotFoundError } from '../../client/components/not-found'
......@@ -146,7 +146,7 @@ async function createRedirectRenderResult(
// if we're redirecting to a relative path, we'll try to stream the response
if (redirectUrl.startsWith('/')) {
const forwardedHeaders = getForwardedHeaders(req, res)
forwardedHeaders.set(RSC, '1')
forwardedHeaders.set(RSC_HEADER, '1')
const host = req.headers['host']
const proto =
......
......@@ -32,9 +32,9 @@ import {
import { canSegmentBeOverridden } from '../../client/components/match-segments'
import { stripInternalQueries } from '../internal-utils'
import {
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE,
RSC,
RSC_HEADER,
} from '../../client/components/app-router-headers'
import { createMetadataComponents } from '../../lib/metadata/metadata'
import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper'
......@@ -393,7 +393,6 @@ async function renderToHTMLOrFlightImpl(
renderOpts: RenderOpts,
baseCtx: AppRenderBaseContext
) {
const isFlight = req.headers[RSC.toLowerCase()] !== undefined
const isNotFoundPath = pagePath === '/404'
// A unique request timestamp used by development to ensure that it's
......@@ -469,7 +468,8 @@ async function renderToHTMLOrFlightImpl(
const isStaticGeneration = staticGenerationStore.isStaticGeneration
// when static generation fails during PPR, we log the errors separately. We intentionally
// silence the error logger in this case to avoid double logging.
const silenceStaticGenerationErrors = renderOpts.ppr && isStaticGeneration
const silenceStaticGenerationErrors =
renderOpts.experimental.ppr && isStaticGeneration
const serverComponentsErrorHandler = createErrorHandler({
_source: 'serverComponentsRenderer',
......@@ -539,17 +539,21 @@ async function renderToHTMLOrFlightImpl(
query = { ...query }
stripInternalQueries(query)
const isPrefetch =
req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()] !== undefined
const isRSCRequest = req.headers[RSC_HEADER.toLowerCase()] !== undefined
const isPrefetchRSCRequest =
isRSCRequest &&
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] !== undefined
/**
* Router state provided from the client-side router. Used to handle rendering from the common layout down.
*/
let providedFlightRouterState = isFlight
? parseAndValidateFlightRouterState(
req.headers[NEXT_ROUTER_STATE_TREE.toLowerCase()]
)
: undefined
let providedFlightRouterState =
isRSCRequest && (!isPrefetchRSCRequest || !renderOpts.experimental.ppr)
? parseAndValidateFlightRouterState(
req.headers[NEXT_ROUTER_STATE_TREE.toLowerCase()]
)
: undefined
/**
* The metadata items array created in next-app-loader with all relevant information
......@@ -584,7 +588,7 @@ async function renderToHTMLOrFlightImpl(
...baseCtx,
getDynamicParamFromSegment,
query,
isPrefetch,
isPrefetch: isPrefetchRSCRequest,
providedSearchParams,
requestTimestamp,
searchParamsProps,
......@@ -601,7 +605,7 @@ async function renderToHTMLOrFlightImpl(
res,
}
if (isFlight && !isStaticGeneration) {
if (isRSCRequest && !isStaticGeneration) {
return generateFlight(ctx)
}
......@@ -701,7 +705,7 @@ async function renderToHTMLOrFlightImpl(
)
const renderer = createStaticRenderer({
ppr: renderOpts.ppr,
ppr: renderOpts.experimental.ppr,
isStaticGeneration: staticGenerationStore.isStaticGeneration,
postponed: renderOpts.postponed
? JSON.parse(renderOpts.postponed)
......@@ -1003,7 +1007,7 @@ async function renderToHTMLOrFlightImpl(
if (
// if PPR is enabled
renderOpts.ppr &&
renderOpts.experimental.ppr &&
// and a call to `maybePostpone` happened
staticGenerationStore.postponeWasTriggered &&
// but there's no postpone state
......
......@@ -139,7 +139,7 @@ export interface RenderOptsPartial {
allowedForwardedHosts?: string[]
params?: ParsedUrlQuery
isPrefetch?: boolean
ppr: boolean
experimental: { ppr: boolean }
postponed?: string
}
......
......@@ -17,7 +17,7 @@ export type StaticGenerationContext = {
isDraftMode?: boolean
isServerAction?: boolean
waitUntil?: Promise<any>
ppr: boolean
experimental: { ppr: boolean }
/**
* A hack around accessing the store value outside the context of the
......@@ -76,9 +76,7 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<
isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,
isDraftMode: renderOpts.isDraftMode,
experimental: {
ppr: renderOpts.ppr,
},
experimental: renderOpts.experimental,
}
// TODO: remove this when we resolve accessing the store outside the execution context
......
......@@ -40,6 +40,8 @@ import type { AppRouteRouteHandlerContext } from './future/route-modules/app-rou
import type { Server as HTTPServer } from 'http'
import type { ImageConfigComplete } from '../shared/lib/image-config'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import type { TLSSocket } from 'tls'
import type { PathnameNormalizer } from './future/normalizers/request/pathname-normalizer'
import { format as formatUrl, parse as parseUrl } from 'url'
import { formatHostname } from './lib/format-hostname'
......@@ -78,12 +80,11 @@ import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import {
RSC,
RSC_HEADER,
RSC_VARY_HEADER,
FLIGHT_PARAMETERS,
NEXT_RSC_UNION_QUERY,
ACTION,
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_PREFETCH_HEADER,
RSC_CONTENT_TYPE_HEADER,
} from '../client/components/app-router-headers'
import type {
......@@ -122,13 +123,14 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass
import { stripInternalHeaders } from './internal-utils'
import { RSCPathnameNormalizer } from './future/normalizers/request/rsc'
import { PostponedPathnameNormalizer } from './future/normalizers/request/postponed'
import type { TLSSocket } from 'tls'
import { stripFlightHeaders } from './app-render/strip-flight-headers'
import {
isAppPageRouteModule,
isAppRouteRouteModule,
isPagesRouteModule,
} from './future/route-modules/checks'
import { PrefetchRSCPathnameNormalizer } from './future/normalizers/request/prefetch-rsc'
import { NextDataPathnameNormalizer } from './future/normalizers/request/next-data'
export type FindComponentsResult = {
components: LoadComponentsReturnType
......@@ -145,7 +147,7 @@ export type RouteHandler = (
req: BaseNextRequest,
res: BaseNextResponse,
parsedUrl: NextUrlWithParsedQuery
) => PromiseLike<boolean | void> | boolean | void
) => PromiseLike<boolean> | boolean
/**
* The normalized route manifest is the same as the route manifest, but with
......@@ -258,7 +260,7 @@ type BaseRenderOpts = {
appDirDevErrorLogger?: (err: any) => Promise<void>
strictNextHead: boolean
isExperimentalCompile?: boolean
ppr: boolean
experimental: { ppr: boolean }
}
export interface BaseRequestHandler {
......@@ -405,6 +407,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected readonly normalizers: {
readonly postponed: PostponedPathnameNormalizer
readonly rsc: RSCPathnameNormalizer
readonly prefetchRSC: PrefetchRSCPathnameNormalizer
readonly data: NextDataPathnameNormalizer
}
public constructor(options: ServerOptions) {
......@@ -475,6 +479,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
this.enabledDirectories.app && this.nextConfig.experimental.ppr
),
rsc: new RSCPathnameNormalizer(this.enabledDirectories.app),
prefetchRSC: new PrefetchRSCPathnameNormalizer(
this.enabledDirectories.app
),
data: new NextDataPathnameNormalizer(this.buildId),
}
this.nextFontManifest = this.getNextFontManifest()
......@@ -523,7 +531,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// @ts-expect-error internal field not publicly exposed
isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile,
ppr: this.nextConfig.experimental.ppr === true,
experimental: {
ppr: this.nextConfig.experimental.ppr === true,
},
}
// Initialize next/config with the environment configuration
......@@ -553,24 +563,52 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}
private handleRSCRequest: RouteHandler = (req, _res, parsedUrl) => {
if (
!parsedUrl.pathname ||
!this.normalizers.rsc.match(parsedUrl.pathname)
) {
return
if (!parsedUrl.pathname) return false
if (this.normalizers.prefetchRSC.match(parsedUrl.pathname)) {
parsedUrl.pathname = this.normalizers.prefetchRSC.normalize(
parsedUrl.pathname,
true
)
// Mark the request as a router prefetch request.
req.headers[RSC_HEADER.toLowerCase()] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] = '1'
addRequestMeta(req, 'isRSCRequest', true)
addRequestMeta(req, 'isPrefetchRSCRequest', true)
} else if (this.normalizers.rsc.match(parsedUrl.pathname)) {
parsedUrl.pathname = this.normalizers.rsc.normalize(
parsedUrl.pathname,
true
)
// Mark the request as a RSC request.
req.headers[RSC_HEADER.toLowerCase()] = '1'
addRequestMeta(req, 'isRSCRequest', true)
} else if (req.headers['x-now-route-matches']) {
// If we didn't match, return with the flight headers stripped. If in
// minimal mode we didn't match based on the path, this can't be a RSC
// request. This is because Vercel only sends this header during
// revalidation requests and we want the cache to instead depend on the
// request path for flight information.
stripFlightHeaders(req.headers)
return false
} else {
// Otherwise just return without doing anything.
return false
}
// If we're here, this is a data request, as it didn't return and it matched
// either a RSC or a prefetch RSC request.
parsedUrl.query.__nextDataReq = '1'
parsedUrl.pathname = this.normalizers.rsc.normalize(
parsedUrl.pathname,
true
)
if (req.url) {
const parsed = parseUrl(req.url)
parsed.pathname = parsedUrl.pathname
req.url = formatUrl(parsed)
}
return false
}
protected handleNextPostponedRequest: RouteHandler = async (
......@@ -580,10 +618,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
) => {
if (
!parsedUrl.pathname ||
req.method !== 'POST' ||
!this.normalizers.postponed.match(parsedUrl.pathname)
!this.normalizers.postponed.match(parsedUrl.pathname) ||
req.method !== 'POST'
) {
return
return false
}
parsedUrl.pathname = this.normalizers.postponed.normalize(
......@@ -597,14 +635,24 @@ export default abstract class Server<ServerOptions extends Options = Options> {
req.url = formatUrl(parsed)
}
// If we've already read the postponed body, then we don't need to do so
// again.
let postponed = getRequestMeta(req, 'postponed') ?? ''
if (postponed) return false
// Read the body in chunks. If it errors here it's because the chunks
// being decoded are not strings.
let postponed = ''
const body: Array<Buffer> = []
for await (const chunk of req.body) {
postponed += chunk
body.push(chunk)
}
// Decode the body as a string.
postponed = Buffer.concat(body).toString('utf8')
addRequestMeta(req, 'postponed', postponed)
return false
}
private handleNextDataRequest: RouteHandler = async (req, res, parsedUrl) => {
......@@ -700,9 +748,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return false
}
protected handleNextImageRequest: RouteHandler = () => {}
protected handleCatchallRenderRequest: RouteHandler = () => {}
protected handleCatchallMiddlewareRequest: RouteHandler = () => {}
protected handleNextImageRequest: RouteHandler = () => false
protected handleCatchallRenderRequest: RouteHandler = () => false
protected handleCatchallMiddlewareRequest: RouteHandler = () => false
protected getRouteMatchers(): RouteMatcherManager {
// Create a new manifest loader that get's the manifests from the server.
......@@ -891,15 +939,14 @@ export default abstract class Server<ServerOptions extends Options = Options> {
)
}
let finished = await this.handleRSCRequest(req, res, parsedUrl)
if (finished) return
finished = await this.handleNextPostponedRequest(req, res, parsedUrl)
if (finished) return
let finished: boolean = false
if (this.minimalMode && this.enabledDirectories.app) {
finished = await this.handleRSCRequest(req, res, parsedUrl)
if (finished) return
if (this.minimalMode && req.headers['x-now-route-matches']) {
for (const param of FLIGHT_PARAMETERS) {
delete req.headers[param.toString().toLowerCase()]
if (this.nextConfig.experimental.ppr) {
finished = await this.handleNextPostponedRequest(req, res, parsedUrl)
if (finished) return
}
}
......@@ -948,6 +995,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
parsedUrl.pathname =
parsedUrl.pathname === '/index' ? '/' : parsedUrl.pathname
}
// x-matched-path is the source of truth, it tells what page
// should be rendered because we don't process rewrites in minimalMode
let { pathname: matchedPath } = new URL(
......@@ -955,26 +1003,18 @@ export default abstract class Server<ServerOptions extends Options = Options> {
'http://localhost'
)
if (this.normalizers.rsc.match(matchedPath)) {
matchedPath = this.normalizers.rsc.normalize(matchedPath, true)
} else if (this.normalizers.postponed.match(matchedPath)) {
matchedPath = this.normalizers.postponed.normalize(
matchedPath,
true
)
}
let urlPathname = new URL(req.url, 'http://localhost').pathname
// For ISR the URL is normalized to the prerenderPath so if
// it's a data request the URL path will be the data URL,
// basePath is already stripped by this point
if (urlPathname.startsWith(`/_next/data/`)) {
if (this.normalizers.data.match(parsedUrl.pathname)) {
parsedUrl.query.__nextDataReq = '1'
}
const normalizedUrlPath = this.stripNextDataPath(urlPathname)
matchedPath = this.stripNextDataPath(matchedPath, false)
// We should attempt route normalization for these routes, but don't
// use them to determine the kind of the request, this is just now
// used for routing.
matchedPath = this.normalize(matchedPath)
const normalizedUrlPath = this.normalize(parsedUrl.pathname)
// Perform locale detection and normalization.
const localeAnalysisResult = this.i18nProvider?.analyze(matchedPath, {
......@@ -1154,7 +1194,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
parsedUrl.pathname = matchedPath
url.pathname = parsedUrl.pathname
finished = await this.handle(req, res, parsedUrl)
finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)
if (finished) return
} catch (err) {
if (err instanceof DecodeError || err instanceof NormalizeError) {
......@@ -1318,7 +1358,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
)
}
finished = await this.handle(req, res, parsedUrl)
finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)
if (finished) return
await this.handleCatchallRenderRequest(req, res, parsedUrl)
......@@ -1329,7 +1369,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
process.env.NEXT_RUNTIME !== 'edge' &&
req.headers['x-middleware-invoke']
) {
finished = await this.handle(req, res, parsedUrl)
finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)
if (finished) return
finished = await this.handleCatchallMiddlewareRequest(
......@@ -1387,31 +1427,60 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}
}
protected handle: RouteHandler = async (req, res, url) => {
let finished = await this.handleNextImageRequest(req, res, url)
if (finished) return true
/**
* Normalizes a pathname without attaching any metadata from any matched
* normalizer.
*
* @param pathname the pathname to normalize
* @returns the normalized pathname
*/
private normalize = (pathname: string) => {
const normalizers: Array<PathnameNormalizer> = []
finished = await this.handleNextDataRequest(req, res, url)
if (finished) return true
if (this.enabledDirectories.pages) {
normalizers.push(this.normalizers.data)
}
if (this.minimalMode && this.enabledDirectories.app) {
finished = await this.handleRSCRequest(req, res, url)
if (finished) return true
if (this.nextConfig.experimental.ppr) {
finished = await this.handleNextPostponedRequest(req, res, url)
if (finished) return true
if (this.renderOpts.experimental.ppr) {
normalizers.push(this.normalizers.postponed)
// We have to put the prefetch normalizer before the RSC normalizer
// because the RSC normalizer will match the prefetch RSC routes too.
normalizers.push(this.normalizers.prefetchRSC)
}
normalizers.push(this.normalizers.rsc)
}
for (const normalizer of normalizers) {
if (!normalizer.match(pathname)) continue
return normalizer.normalize(pathname, true)
}
return pathname
}
private normalizeAndAttachMetadata: RouteHandler = async (req, res, url) => {
let finished = await this.handleNextImageRequest(req, res, url)
if (finished) return true
if (this.enabledDirectories.pages) {
finished = await this.handleNextDataRequest(req, res, url)
if (finished) return true
}
return false
}
/**
* @internal - this method is internal to Next.js and should not be used directly by end-users
*/
public getRequestHandlerWithMetadata(meta: RequestMeta): BaseRequestHandler {
const handler = this.getRequestHandler()
return (req, res, parsedUrl) => {
setRequestMeta(req, meta)
return this.handleRequest(req, res, parsedUrl)
return handler(req, res, parsedUrl)
}
}
......@@ -1779,8 +1848,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
* If true, this indicates that the request being made is for an app
* prefetch request.
*/
const isAppPrefetch =
req.headers[NEXT_ROUTER_PREFETCH.toLowerCase()] === '1'
const isPrefetchRSCRequest =
(req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] === '1' ||
getRequestMeta(req, 'isPrefetchRSCRequest')) ??
false
// when we are handling a middleware prefetch and it doesn't
// resolve to a static data route we bail early to avoid
......@@ -1823,7 +1894,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}
// Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later
const isFlightRequest = Boolean(req.headers[RSC.toLowerCase()])
const isRSCRequest =
(Boolean(req.headers[RSC_HEADER.toLowerCase()]) ||
getRequestMeta(req, 'isRSCRequest')) ??
false
// If we're in minimal mode, then try to get the postponed information from
// the request metadata. If available, use it for resuming the postponed
......@@ -1836,14 +1910,20 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}
}
// If PPR is enabled, and this is a RSC request (but not a prefetch), then
// we can use this fact to only generate the flight data for the request
// because we can't cache the HTML (as it's also dynamic).
const isDynamicRSCRequest =
this.renderOpts.experimental.ppr && isRSCRequest && !isPrefetchRSCRequest
// For pages we need to ensure the correct Vary header is set too, to avoid
// caching issues when navigating between pages and app
if (!isAppPath && isFlightRequest) {
if (!isAppPath && isRSCRequest) {
res.setHeader('vary', RSC_VARY_HEADER)
}
// we need to ensure the status code if /404 is visited directly
if (is404Page && !isDataReq && !isFlightRequest) {
if (is404Page && !isDataReq && !isRSCRequest) {
res.statusCode = 404
}
......@@ -1934,24 +2014,22 @@ export default abstract class Server<ServerOptions extends Options = Options> {
if (isAppPath) {
res.setHeader('vary', RSC_VARY_HEADER)
// We don't clear RSC headers in development since SSG doesn't apply
// These headers are cleared for SSG as we need to always generate the
// full RSC response for ISR.
if (
!this.renderOpts.dev &&
!isPreviewMode &&
isSSG &&
req.headers[RSC.toLowerCase()]
) {
if (!this.renderOpts.dev && !isPreviewMode && isSSG && isRSCRequest) {
// If this is an RSC request but we aren't in minimal mode, then we mark
// that this is a data request so that we can generate the flight data
// only.
if (!this.minimalMode) {
isDataReq = true
}
// Strip the flight headers so that we generate both the RSC and HTML
// for the request.
// If this is a dynamic RSC request, ensure that we don't purge the
// flight headers to ensure that we will only produce the RSC response.
// We only need to do this in non-edge environments (as edge doesn't
// support static generation).
if (
!isEdgeRuntime(opts.runtime) ||
(this.serverOptions as any).webServerConfig
!isDynamicRSCRequest &&
(!isEdgeRuntime(opts.runtime) ||
(this.serverOptions as any).webServerConfig)
) {
stripFlightHeaders(req.headers)
}
......@@ -2017,7 +2095,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
isSSG &&
!opts.supportsDynamicHTML &&
!isServerAction &&
!resumed
!resumed &&
!isDynamicRSCRequest
) {
ssgCacheKey = `${locale ? `/${locale}` : ''}${
(pathname === '/' || resolvedUrlPathname === '/') && locale
......@@ -2086,7 +2165,30 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const doRender: Renderer = async (postponed) => {
// In development, we always want to generate dynamic HTML.
const supportsDynamicHTML =
(!isDataReq && opts.dev) || !(isSSG || hasStaticPaths) || !!postponed
// If this isn't a data request and we're not in development, then we
// support dynamic HTML.
(!isDataReq && opts.dev) ||
// If this is not SSG or does not have static paths, then it supports
// dynamic HTML.
!(isSSG || hasStaticPaths) ||
// If this request has provided postponed data, it supports dynamic
// HTML.
!!postponed ||
// If this is a dynamic RSC request, then this render supports dynamic
// HTML (it's dynamic).
isDynamicRSCRequest
// Ensure we bail if a prefetch RSC request is made while PPR is
// enabled that has dynamic HTML enabled.
if (
this.renderOpts.experimental.ppr &&
isPrefetchRSCRequest &&
supportsDynamicHTML
) {
throw new Error(
"Invariant: prefetch RSC requests can't support dynamic HTML"
)
}
let headers: OutgoingHttpHeaders | undefined
......@@ -2155,7 +2257,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
prerenderManifest,
renderOpts: {
// App Route's cannot postpone, so don't enable it.
ppr: false,
experimental: { ppr: false },
originalPathname: components.ComponentMod.originalPathname,
supportsDynamicHTML,
incrementalCache,
......@@ -2240,7 +2342,12 @@ export default abstract class Server<ServerOptions extends Options = Options> {
{ page: pathname, params: opts.params, query, renderOpts }
)
} else if (isAppPageRouteModule(routeModule)) {
if (isAppPrefetch && process.env.NODE_ENV === 'production') {
if (
!this.renderOpts.experimental.ppr &&
isPrefetchRSCRequest &&
process.env.NODE_ENV === 'production' &&
!this.minimalMode
) {
try {
const prefetchRsc = await this.getPrefetchRsc(resolvedUrlPathname)
if (prefetchRsc) {
......@@ -2308,22 +2415,19 @@ export default abstract class Server<ServerOptions extends Options = Options> {
metadata.revalidate === 0 &&
!this.renderOpts.dev
) {
const staticBailoutInfo: {
stack?: string
description?: string
} = metadata.staticBailoutInfo || {}
const staticBailoutInfo = metadata.staticBailoutInfo
const err = new Error(
`Page changed from static to dynamic at runtime ${urlPathname}${
staticBailoutInfo.description
staticBailoutInfo?.description
? `, reason: ${staticBailoutInfo.description}`
: ``
}` +
`\nsee more here https://nextjs.org/docs/messages/app-static-to-dynamic-error`
)
if (staticBailoutInfo.stack) {
const stack = staticBailoutInfo.stack as string
if (staticBailoutInfo?.stack) {
const stack = staticBailoutInfo.stack
err.stack = err.message + stack.substring(stack.indexOf('\n'))
}
......@@ -2563,17 +2667,43 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// Coerce the revalidate parameter from the render.
let revalidate: Revalidate | undefined
if (
// If this is a resume request in minimal mode it is streamed with dynamic
// content and should not be cached.
if (this.minimalMode && resumed?.postponed) {
revalidate = 0
}
// If this is in minimal mode and this is a flight request that isn't a
// prefetch request while PPR is enabled, it cannot be cached as it contains
// dynamic content.
else if (
this.minimalMode &&
isRSCRequest &&
!isPrefetchRSCRequest &&
this.renderOpts.experimental.ppr
) {
revalidate = 0
} else if (
typeof cacheEntry.revalidate !== 'undefined' &&
(!this.renderOpts.dev || (hasServerProps && !isDataReq))
) {
// If this is a preview mode request, we shouldn't cache it. We also don't
// cache 404 pages.
if (isPreviewMode || (is404Page && !isDataReq)) {
revalidate = 0
} else if (!isSSG) {
}
// If this isn't SSG, then we should set change the header only if it is
// not set already.
else if (!isSSG) {
if (!res.getHeader('Cache-Control')) {
revalidate = 0
}
} else if (typeof cacheEntry.revalidate === 'number') {
}
// If the cache entry has a revalidate value that's a number, use it.
else if (typeof cacheEntry.revalidate === 'number') {
if (cacheEntry.revalidate < 1) {
throw new Error(
`Invariant: invalid Cache-Control duration provided: ${cacheEntry.revalidate} < 1`
......@@ -2581,10 +2711,14 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}
revalidate = cacheEntry.revalidate
} else if (typeof cacheEntry.revalidate === 'boolean') {
}
// Otherwise if the revalidate value is false, then we should use the cache
// time of one year.
else if (cacheEntry.revalidate === false) {
revalidate = CACHE_ONE_YEAR
}
}
cacheEntry.revalidate = revalidate
// If there's a callback for `onCacheEntry`, call it with the cache entry
......@@ -2667,13 +2801,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
cachedData.headers[NEXT_CACHE_TAGS_HEADER] as string
)
}
if (isDataReq && typeof cachedData.pageData !== 'string') {
throw new Error(
'invariant: Expected pageData to be a string for app data request but received ' +
typeof cachedData.pageData +
'. This is a bug in Next.js.'
)
}
if (cachedData.status) {
res.statusCode = cachedData.status
......@@ -2682,40 +2809,42 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// Mark that the request did postpone if this is a data request or we're
// testing. It's used to verify that we're actually serving a postponed
// request so we can trust the cache headers.
if (cachedData.postponed && (isDataReq || process.env.__NEXT_TEST_MODE)) {
if (
cachedData.postponed &&
(isRSCRequest || process.env.__NEXT_TEST_MODE)
) {
res.setHeader(NEXT_DID_POSTPONE_HEADER, '1')
}
if (isDataReq) {
// If this isn't a prefetch and this isn't a resume request, we want to
// respond with the dynamic flight data. In the case that this is a
// resume request the page data will already be dynamic.
if (!isAppPrefetch && !resumed) {
const result = await doRender(cachedData.postponed)
if (!result) {
return null
}
if (result.value?.kind !== 'PAGE') {
throw new Error('Invariant: Expected a page response')
// If this is a dynamic RSC request, then stream the response.
if (isDynamicRSCRequest) {
if (cachedData.pageData) {
throw new Error('Invariant: Expected pageData to be undefined')
}
if (!result.value.pageData) {
throw new Error('Invariant: Expected pageData to be present')
if (cachedData.postponed) {
throw new Error('Invariant: Expected postponed to be undefined')
}
return {
type: 'rsc',
body: RenderResult.fromStatic(result.value.pageData as string),
body: cachedData.html,
revalidate: cacheEntry.revalidate,
}
}
if (typeof cachedData.pageData !== 'string') {
throw new Error(
`Invariant: expected pageData to be a string, got ${typeof cachedData.pageData}`
)
}
// As this isn't a prefetch request, we should serve the static flight
// data.
return {
type: 'rsc',
body: RenderResult.fromStatic(cachedData.pageData as string),
body: RenderResult.fromStatic(cachedData.pageData),
revalidate: cacheEntry.revalidate,
}
}
......@@ -2726,7 +2855,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// If there's no postponed state, we should just serve the HTML. This
// should also be the case for a resume request because it's completed
// as a server render (rather than a static render).
if (!cachedData.postponed) {
if (!cachedData.postponed || this.minimalMode) {
return {
type: 'html',
body,
......
import type { Normalizer } from '../normalizer'
import type { PathnameNormalizer } from './pathname-normalizer'
export class BasePathPathnameNormalizer implements Normalizer {
export class BasePathPathnameNormalizer implements PathnameNormalizer {
private readonly basePath?: string
constructor(basePath: string) {
// A basePath of `/` is not a basePath.
......
import type { Normalizer } from '../normalizer'
import type { PathnameNormalizer } from './pathname-normalizer'
export class NextDataPathnameNormalizer implements Normalizer {
export class NextDataPathnameNormalizer implements PathnameNormalizer {
private readonly prefix: string
constructor(buildID: string) {
if (!buildID) {
......
import type { Normalizer } from '../normalizer'
export interface PathnameNormalizer extends Normalizer {
match(pathname: string): boolean
normalize(pathname: string, matched?: boolean): string
}
......@@ -65,5 +65,10 @@ describe('PostponedPathnameNormalizer', () => {
)
}
})
it('should normalize `/index` to `/`', () => {
const normalizer = new PostponedPathnameNormalizer(true)
expect(normalizer.normalize('/_next/postponed/index', true)).toBe('/')
})
})
})
import type { Normalizer } from '../normalizer'
import type { PathnameNormalizer } from './pathname-normalizer'
export class PostponedPathnameNormalizer implements Normalizer {
export class PostponedPathnameNormalizer implements PathnameNormalizer {
constructor(private readonly ppr: boolean | undefined) {}
public match(pathname: string) {
......@@ -21,6 +21,11 @@ export class PostponedPathnameNormalizer implements Normalizer {
if (!matched && !this.match(pathname)) return pathname
// Remove the prefix.
return pathname.substring('/_next/postponed'.length) || '/'
pathname = pathname.substring('/_next/postponed'.length) || '/'
// If the pathname is equal to `/index`, we normalize it to `/`.
if (pathname === '/index') return '/'
return pathname
}
}
import { PrefetchRSCPathnameNormalizer } from './prefetch-rsc'
describe('PrefetchRSCPathnameNormalizer', () => {
describe('match', () => {
it('should return false if the pathname does not end with `.prefetch.rsc`', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
it('should return true if it matches', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(true)
}
})
it('should return false if it is disabled but ends with .prefetch.rsc', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(false)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
it('should return false if it only ends in .rsc', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(false)
const pathnames = ['/foo.rsc', '/foo/bar.rsc', '/fooo/bar.rsc']
for (const pathname of pathnames) {
expect(normalizer.match(pathname)).toBe(false)
}
})
})
describe('normalize', () => {
it('should return the same pathname if we are not matched and the pathname does not end with `.prefetch.rsc`', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
it('should strip the `.prefetch.rsc` extension from the pathname when it matches', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(true)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
const expected = ['/foo', '/foo/bar', '/fooo/bar']
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(
expected[pathnames.indexOf(pathname)]
)
}
})
it('should return the same pathname if it is disabled but ends with .prefetch.rsc', () => {
const normalizer = new PrefetchRSCPathnameNormalizer(false)
const pathnames = [
'/foo.prefetch.rsc',
'/foo/bar.prefetch.rsc',
'/fooo/bar.prefetch.rsc',
]
for (const pathname of pathnames) {
expect(normalizer.normalize(pathname)).toBe(pathname)
}
})
})
})
import type { PathnameNormalizer } from './pathname-normalizer'
import { RSC_PREFETCH_SUFFIX } from '../../../../lib/constants'
import { SuffixPathnameNormalizer } from './suffix'
export class PrefetchRSCPathnameNormalizer implements PathnameNormalizer {
private readonly suffix = new SuffixPathnameNormalizer(RSC_PREFETCH_SUFFIX)
constructor(private readonly hasAppDir: boolean) {}
public match(pathname: string) {
// If there's no app directory, we don't match.
if (!this.hasAppDir) return false
return this.suffix.match(pathname)
}
public normalize(pathname: string, matched?: boolean): string {
// If there's no app directory, we don't need to normalize.
if (!this.hasAppDir) return pathname
return this.suffix.normalize(pathname, matched)
}
}
import type { Normalizer } from '../normalizer'
import type { PathnameNormalizer } from './pathname-normalizer'
import { RSC_SUFFIX } from '../../../../lib/constants'
import { SuffixPathnameNormalizer } from './suffix'
export class RSCPathnameNormalizer implements PathnameNormalizer {
private readonly suffix = new SuffixPathnameNormalizer(RSC_SUFFIX)
export class RSCPathnameNormalizer implements Normalizer {
constructor(private readonly hasAppDir: boolean) {}
public match(pathname: string) {
// If there's no app directory, we don't match.
if (!this.hasAppDir) return false
// If the pathname doesn't end in `.rsc`, we don't match.
if (!pathname.endsWith('.rsc')) return false
return true
return this.suffix.match(pathname)
}
public normalize(pathname: string, matched?: boolean): string {
// If there's no app directory, we don't need to normalize.
if (!this.hasAppDir) return pathname
// If we're not matched and we don't match, we don't need to normalize.
if (!matched && !this.match(pathname)) return pathname
return pathname.substring(0, pathname.length - 4)
return this.suffix.normalize(pathname, matched)
}
}
import type { Normalizer } from '../normalizer'
export class SuffixPathnameNormalizer implements Normalizer {
constructor(private readonly suffix: string) {}
public match(pathname: string) {
// If the pathname doesn't end in the suffix, we don't match.
if (!pathname.endsWith(this.suffix)) return false
return true
}
public normalize(pathname: string, matched?: boolean): string {
// If we're not matched and we don't match, we don't need to normalize.
if (!matched && !this.match(pathname)) return pathname
return pathname.substring(0, pathname.length - this.suffix.length)
}
}
......@@ -8,7 +8,11 @@ import type {
import LRUCache from 'next/dist/compiled/lru-cache'
import path from '../../../shared/lib/isomorphic/path'
import { NEXT_CACHE_TAGS_HEADER } from '../../../lib/constants'
import {
NEXT_CACHE_TAGS_HEADER,
RSC_PREFETCH_SUFFIX,
RSC_SUFFIX,
} from '../../../lib/constants'
type FileSystemCacheContext = Omit<
CacheHandlerContext,
......@@ -16,6 +20,7 @@ type FileSystemCacheContext = Omit<
> & {
fs: CacheFs
serverDistDir: string
experimental: { ppr: boolean }
}
type TagsManifest = {
......@@ -33,6 +38,7 @@ export default class FileSystemCache implements CacheHandler {
private pagesDir: boolean
private tagsManifestPath?: string
private revalidatedTags: string[]
private readonly experimental: { ppr: boolean }
constructor(ctx: FileSystemCacheContext) {
this.fs = ctx.fs
......@@ -41,6 +47,7 @@ export default class FileSystemCache implements CacheHandler {
this.appDir = !!ctx._appDir
this.pagesDir = !!ctx._pagesDir
this.revalidatedTags = ctx.revalidatedTags
this.experimental = ctx.experimental
if (ctx.maxMemoryCacheSize && !memoryCache) {
memoryCache = new LRUCache({
......@@ -187,7 +194,12 @@ export default class FileSystemCache implements CacheHandler {
} else {
const pageData = isAppPath
? await this.fs.readFile(
this.getFilePath(`${key}.rsc`, 'app'),
this.getFilePath(
`${key}${
this.experimental.ppr ? RSC_PREFETCH_SUFFIX : RSC_SUFFIX
}`,
'app'
),
'utf8'
)
: JSON.parse(
......
......@@ -32,6 +32,7 @@ export interface CacheHandlerContext {
fetchCacheKeyPrefix?: string
prerenderManifest?: PrerenderManifest
revalidatedTags: string[]
experimental: { ppr: boolean }
_appDir: boolean
_pagesDir: boolean
_requestHeaders: IncrementalCache['requestHeaders']
......@@ -91,6 +92,7 @@ export class IncrementalCache implements IncrementalCacheType {
fetchCacheKeyPrefix,
CurCacheHandler,
allowedRevalidateHeaderKeys,
experimental,
}: {
fs?: CacheFs
dev: boolean
......@@ -107,6 +109,7 @@ export class IncrementalCache implements IncrementalCacheType {
getPrerenderManifest: () => PrerenderManifest
fetchCacheKeyPrefix?: string
CurCacheHandler?: typeof CacheHandler
experimental: { ppr: boolean }
}) {
const debug = !!process.env.NEXT_PRIVATE_DEBUG_CACHE
if (!CurCacheHandler) {
......@@ -175,6 +178,7 @@ export class IncrementalCache implements IncrementalCacheType {
_appDir: !!appDir,
_requestHeaders: requestHeaders,
fetchCacheKeyPrefix,
experimental,
})
}
}
......@@ -569,12 +573,15 @@ export class IncrementalCache implements IncrementalCacheType {
// revalidateAfter values so we update this on set
if (typeof ctx.revalidate !== 'undefined' && !ctx.fetchCache) {
this.prerenderManifest.routes[pathname] = {
experimentalPPR: undefined,
dataRoute: path.posix.join(
'/_next/data',
`${normalizePagePath(pathname)}.json`
),
srcRoute: null, // FIXME: provide actual source route, however, when dynamically appending it doesn't really matter
initialRevalidateSeconds: ctx.revalidate,
// Pages routes do not have a prefetch data route.
prefetchDataRoute: undefined,
}
}
await this.cacheHandler?.set(pathname, data, ctx)
......
......@@ -39,6 +39,7 @@ import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-s
import { normalizeMetadataRoute } from '../../../lib/metadata/get-metadata-route'
import { RSCPathnameNormalizer } from '../../future/normalizers/request/rsc'
import { PostponedPathnameNormalizer } from '../../future/normalizers/request/postponed'
import { PrefetchRSCPathnameNormalizer } from '../../future/normalizers/request/prefetch-rsc'
export type FsOutput = {
type:
......@@ -371,6 +372,7 @@ export async function setupFsCheck(opts: {
// Because we can't know if the app directory is enabled or not at this
// stage, we assume that it is.
rsc: new RSCPathnameNormalizer(true),
prefetchRSC: new PrefetchRSCPathnameNormalizer(true),
postponed: new PostponedPathnameNormalizer(opts.config.experimental.ppr),
}
......@@ -419,7 +421,9 @@ export async function setupFsCheck(opts: {
// Simulate minimal mode requests by normalizing RSC and postponed
// requests.
if (opts.minimalMode) {
if (normalizers.rsc.match(itemPath)) {
if (normalizers.prefetchRSC.match(itemPath)) {
itemPath = normalizers.prefetchRSC.normalize(itemPath, true)
} else if (normalizers.rsc.match(itemPath)) {
itemPath = normalizers.rsc.normalize(itemPath, true)
} else if (normalizers.postponed.match(itemPath)) {
itemPath = normalizers.postponed.normalize(itemPath, true)
......
......@@ -82,7 +82,10 @@ import { setHttpClientAndAgentOptions } from './setup-http-agent-env'
import { isPagesAPIRouteMatch } from './future/route-matches/pages-api-route-match'
import type { PagesAPIRouteMatch } from './future/route-matches/pages-api-route-match'
import type { MatchOptions } from './future/route-matcher-managers/route-matcher-manager'
import { INSTRUMENTATION_HOOK_FILENAME } from '../lib/constants'
import {
INSTRUMENTATION_HOOK_FILENAME,
RSC_PREFETCH_SUFFIX,
} from '../lib/constants'
import { getTracer } from './lib/trace/tracer'
import { NextNodeServerSpan } from './lib/trace/constants'
import { nodeFs } from './lib/node-fs-methods'
......@@ -324,6 +327,7 @@ export default class NextNodeServer extends BaseServer {
!this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,
getPrerenderManifest: () => this.getPrerenderManifest(),
CurCacheHandler: CacheHandler,
experimental: this.renderOpts.experimental,
})
}
......@@ -996,7 +1000,7 @@ export default class NextNodeServer extends BaseServer {
protected getPrefetchRsc(pathname: string): Promise<string> {
return this.getCacheFilesystem().readFile(
join(this.serverDistDir, 'app', `${pathname}.prefetch.rsc`),
join(this.serverDistDir, 'app', `${pathname}${RSC_PREFETCH_SUFFIX}`),
'utf8'
)
}
......
......@@ -14,7 +14,10 @@ type ContentTypeOption = string | undefined
export type RenderResultMetadata = {
pageData?: any
revalidate?: Revalidate
staticBailoutInfo?: any
staticBailoutInfo?: {
stack?: string
description?: string
}
assetQueryString?: string
isNotFound?: boolean
isRedirect?: boolean
......
......@@ -68,6 +68,16 @@ export interface RequestMeta {
*/
incrementalCache?: any
/**
* True when the request is for the prefetch flight data.
*/
isPrefetchRSCRequest?: true
/**
* True when the request is for the flight data.
*/
isRSCRequest?: true
/**
* Postponed state to use for resumption. If present it's assumed that the
* request is for a page that has postponed (there are no guarantees that the
......
......@@ -74,6 +74,8 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
CurCacheHandler:
this.serverOptions.webServerConfig.incrementalCacheHandler,
getPrerenderManifest: () => this.getPrerenderManifest(),
// PPR is not supported in the edge runtime.
experimental: { ppr: false },
})
}
protected getResponseCache() {
......
......@@ -110,7 +110,7 @@ export class EdgeRouteModuleWrapper {
renderOpts: {
supportsDynamicHTML: true,
// App Route's cannot be postponed.
ppr: false,
experimental: { ppr: false },
},
}
......
......@@ -2557,9 +2557,12 @@ const runTests = (isDev = false) => {
rsc: {
header: 'RSC',
contentTypeHeader: 'text/x-component',
didPostponeHeader: 'x-nextjs-postponed',
varyHeader:
'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url',
prefetchHeader: 'Next-Router-Prefetch',
prefetchSuffix: '.prefetch.rsc',
suffix: '.rsc',
},
})
})
......
......@@ -1492,9 +1492,12 @@ function runTests({ dev }) {
rsc: {
header: 'RSC',
contentTypeHeader: 'text/x-component',
didPostponeHeader: 'x-nextjs-postponed',
varyHeader:
'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url',
prefetchHeader: 'Next-Router-Prefetch',
prefetchSuffix: '.prefetch.rsc',
suffix: '.rsc',
},
})
})
......
......@@ -15,6 +15,7 @@ import {
describe('minimal-mode-response-cache', () => {
let next: NextInstance
let server
let port
let appPort
let output = ''
......@@ -60,14 +61,14 @@ describe('minimal-mode-response-cache', () => {
.replace('console.error(err)', `console.error('top-level', err)`)
.replace('port:', 'minimalMode: true,port:')
)
appPort = await findPort()
port = await findPort()
server = await initNextServerScript(
testServer,
/- Local:/,
{
...process.env,
HOSTNAME: '',
PORT: appPort,
PORT: port.toString(),
},
undefined,
{
......@@ -80,6 +81,7 @@ describe('minimal-mode-response-cache', () => {
},
}
)
appPort = `http://127.0.0.1:${port}`
})
afterAll(async () => {
await next.destroy()
......@@ -128,25 +130,22 @@ describe('minimal-mode-response-cache', () => {
headers,
})
const content1 = await res1.text()
expect(res1.headers.get('content-type')).toContain('text/x-component')
expect(content1).not.toContain('<html')
expect(content1).toContain('app-another')
expect(res1.headers.get('content-type')).toContain('text/x-component')
const res2 = await fetchViaHTTP(appPort, '/app-another', undefined, {
headers,
})
const content2 = await res2.text()
expect(res2.headers.get('content-type')).toContain('text/html')
expect(content2).toContain('<html')
expect(content2).toContain('app-another')
expect(res2.headers.get('content-type')).toContain('text/html')
})
it('should have correct "Started server on" log', async () => {
expect(output).toContain(`- Local:`)
let pattern = new RegExp(
`Local:\\s*http://localhost:${appPort}|Local:\\s*http://127.0.0.1:${appPort}|Local: http://\\[::1\\]:${appPort}`
)
expect(output).toMatch(pattern)
expect(output).toContain(`http://localhost:${port}`)
})
it('should have correct responses', async () => {
......
......@@ -15,6 +15,9 @@ describe('FileSystemCache', () => {
fs: nodeFs,
serverDistDir: cacheDir,
revalidatedTags: [],
experimental: {
ppr: false,
},
})
const binary = await fs.readFile(
......
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