Unverified Commit 93bb2799 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Apply fixes for onBuildComplete and route module (#88831)

This applies fixes for outputs in `onBuildComplete` with various slight
differences from expected values. This also applies some fixes in the
route-module interface to ensure we install the process handlers for PPR
since currently that was done in `next-server` which we want to get rid
of and there was an edge case with query parsing logic in the
route-module.

Our E2E tests were run against this here to validate
https://github.com/vercel/next.js/actions/runs/21324578779 and failures
are matching existing failures on canary.

x-ref: https://github.com/nextjs/adapter-vercel/pull/11
x-ref: https://github.com/vercel/vercel/pull/14574

---------
Co-authored-by: 's avatarvercel[bot] <35613825+vercel[bot]@users.noreply.github.com>
parent f4c2d546
......@@ -90,6 +90,33 @@ jobs:
runs_on_labels: '["ubuntu-latest"]'
overrideProxyAddress: ${{ inputs.overrideProxyAddress || '' }}
test-deploy-adapter:
name: Run Deploy Adapter Tests
needs: setup
uses: ./.github/workflows/build_reusable.yml
secrets: inherit
strategy:
fail-fast: false
matrix:
group: [1/1]
with:
afterBuild: |
npm i -g vercel@latest && \
NEXT_E2E_TEST_TIMEOUT=240000 \
NEXT_TEST_MODE=deploy \
IS_WEBPACK_TEST=1 \
NEXT_ENABLE_ADAPTER=1 \
NEXT_EXTERNAL_TESTS_FILTERS="test/deploy-tests-manifest.json" \
NEXT_TEST_VERSION="${{ github.event.inputs.nextVersion || needs.setup.outputs.next-version || 'canary' }}" \
VERCEL_CLI_VERSION="${{ github.event.inputs.vercelCliVersion || 'vercel@latest' }}" \
node run-tests.js --timings -g ${{ matrix.group }} -c 2 test/e2e/app-dir/segment-cache/client-params/client-params.test.ts test/e2e/app-dir/app-static/app-static.test.ts test/e2e/app-dir/cache-components/cache-components.test.ts test/e2e/app-dir/app/index.test.ts test/e2e/app-dir/app-edge/app-edge.test.ts test/e2e/edge-pages-support/index.test.ts test/e2e/prerender.test.ts test/e2e/middleware-general/test/index.test.ts test/e2e/middleware-rewrites/test/index.test.ts test/e2e/app-dir/actions/app-action-node-middleware.test.ts
skipNativeBuild: 'yes'
skipNativeInstall: 'no'
stepName: 'test-deploy-adapter-${{ matrix.group }}'
timeout_minutes: 180
runs_on_labels: '["ubuntu-latest"]'
overrideProxyAddress: ${{ inputs.overrideProxyAddress || '' }}
report-test-results-to-datadog:
needs: test-deploy
if: ${{ always() }}
......
......@@ -176,50 +176,38 @@ export interface AdapterOutput {
/**
* fallback is initial cache data generated during build for a prerender
*/
fallback?:
| {
/**
* path to the fallback file can be HTML/JSON/RSC,
*/
filePath: string
/**
* initialStatus is the status code that should be applied
* when serving the fallback
*/
initialStatus?: number
/**
* initialHeaders are the headers that should be sent when
* serving the fallback
*/
initialHeaders?: Record<string, string | string[]>
/**
* initial expiration is how long until the fallback entry
* is considered expired and no longer valid to serve
*/
initialExpiration?: number
/**
* initial revalidate is how long until the fallback is
* considered stale and should be revalidated
*/
initialRevalidate?: Revalidate
/**
* postponedState is the PPR state when it postponed and is used for resuming
*/
postponedState?: string
}
| {
/*
a fallback filePath can be omitted when postponedState is
present which signals the fallback should just resume with
the postpone state but doesn't have fallback to seed cache
*/
postponedState: string
initialExpiration?: number
initialRevalidate?: Revalidate
initialHeaders?: Record<string, string | string[]>
initialStatus?: number
}
fallback?: {
/**
* path to the fallback file can be HTML/JSON/RSC,
*/
filePath: string | undefined
/**
* initialStatus is the status code that should be applied
* when serving the fallback
*/
initialStatus?: number
/**
* initialHeaders are the headers that should be sent when
* serving the fallback
*/
initialHeaders?: Record<string, string | string[]>
/**
* initial expiration is how long until the fallback entry
* is considered expired and no longer valid to serve
*/
initialExpiration?: number
/**
* initial revalidate is how long until the fallback is
* considered stale and should be revalidated
*/
initialRevalidate?: Revalidate
/**
* postponedState is the PPR state when it postponed and is used for resuming
*/
postponedState: string | undefined
}
/**
* config related to the route
*/
......@@ -701,9 +689,9 @@ export async function handleBuildComplete({
function handleFile(file: string) {
const originalPath = path.join(distDir, file)
const fileOutputPath = path.join(
path.relative(tracingRoot, distDir),
file
const fileOutputPath = path.relative(
config.distDir,
path.join(path.relative(tracingRoot, distDir), file)
)
if (!output.assets) {
output.assets = {}
......@@ -714,7 +702,10 @@ export async function handleBuildComplete({
handleFile(file)
}
for (const item of [...(page.assets || [])]) {
handleFile(item.filePath)
if (!output.assets) {
output.assets = {}
}
output.assets[item.name] = path.join(distDir, item.filePath)
}
for (const item of page.wasm || []) {
if (!output.wasmAssets) {
......@@ -756,6 +747,17 @@ export async function handleBuildComplete({
pathname: rscPathname,
id: page.name + '.rsc',
})
} else if (serverPropsPages.has(route === '/index' ? '/' : route)) {
const nextDataPath = path.posix.join(
'/_next/data/',
buildId,
normalizePagePath(output.pathname) + '.json'
)
outputs.appPages.push({
...output,
pathname: nextDataPath,
id: page.name,
})
}
}
......@@ -1086,6 +1088,10 @@ export async function handleBuildComplete({
meta: {
postponed?: string
segmentPaths?: string[]
},
ctx: {
htmlAllowQuery?: string[]
dataAllowQuery?: string[]
}
) => {
if (meta.postponed && initialOutput.fallback) {
......@@ -1099,6 +1105,20 @@ export async function handleBuildComplete({
`${normalizedRoute}${prefetchSegmentDirSuffix}`
)
// If client param parsing is enabled, we follow the same logic as
// the HTML allowQuery as it's already going to vary based on if
// there's a static shell generated or if there's fallback root
// params. If there are fallback root params, and we can serve a
// fallback, then we should follow the same logic for the segment
// prerenders.
//
// If client param parsing is not enabled, we have to use the
// allowQuery because the segment payloads will contain dynamic
// segment values.
const segmentAllowQuery = routesManifest.rsc.clientParamParsing
? ctx.htmlAllowQuery
: ctx.dataAllowQuery
for (const segmentPath of meta.segmentPaths) {
const outputSegmentPath =
path.join(
......@@ -1106,10 +1126,16 @@ export async function handleBuildComplete({
segmentPath
) + prefetchSegmentSuffix
const fallbackPathname = path.join(
segmentsDir,
segmentPath + prefetchSegmentSuffix
)
// Only use the fallback value when the allowQuery is defined and
// is empty, which means that the segments do not vary based on
// the route parameters. This is safer than ensuring that we only
// use the fallback when this is not a fallback because we know in
// this new logic that it doesn't vary based on the route
// parameters and therefore can be used for all requests instead.
const fallbackPathname =
segmentAllowQuery && segmentAllowQuery.length === 0
? path.join(segmentsDir, segmentPath + prefetchSegmentSuffix)
: undefined
outputs.prerenders.push({
id: outputSegmentPath,
......@@ -1120,10 +1146,12 @@ export async function handleBuildComplete({
config: {
...initialOutput.config,
bypassFor: undefined,
},
fallback: {
filePath: fallbackPathname,
postponedState: undefined,
initialExpiration: initialOutput.fallback?.initialExpiration,
initialRevalidate: initialOutput.fallback?.initialRevalidate,
......@@ -1165,11 +1193,19 @@ export async function handleBuildComplete({
// normalize these for consistency
for (const key of Object.keys(meta.headers)) {
const keyLower = key.toLowerCase()
let value = meta.headers[key]
// normalize values to strings (e.g. set-cookie can be an array)
if (Array.isArray(value)) {
value = value.join(', ')
} else if (typeof value !== 'string') {
value = String(value)
}
if (keyLower !== key) {
const value = meta.headers[key]
delete meta.headers[key]
meta.headers[keyLower] = value
}
meta.headers[keyLower] = value
}
}
......@@ -1208,6 +1244,12 @@ export async function handleBuildComplete({
const isAppPage =
Boolean(appOutputMap[srcRoute]) || srcRoute === '/_not-found'
// if we already have 404.html favor that instead of
// _not-found prerender
if (srcRoute === '/_not-found' && hasStatic404) {
continue
}
const isNotFoundTrue = prerenderManifest.notFoundRoutes.includes(route)
let allowQuery: string[] | undefined
......@@ -1215,7 +1257,7 @@ export async function handleBuildComplete({
(item) => item.page === srcRoute
)?.routeKeys
if (!isDynamicRoute(srcRoute)) {
if (!isDynamicRoute(route)) {
// for non-dynamic routes we use an empty array since
// no query values bust the cache for non-dynamic prerenders
// prerendered paths also do not pass allowQuery as they match
......@@ -1253,6 +1295,42 @@ export async function handleBuildComplete({
const meta = await getAppRouteMeta(route, isAppPage)
let htmlAllowQuery = allowQuery
let dataAllowQuery = allowQuery
const dataInitialHeaders: Record<string, string> = {}
// We additionally vary based on if there's a postponed prerender
// because if there isn't, then that means that we generated an
// empty shell, and producing an empty RSC shell would be a waste.
// If there is a postponed prerender, then the RSC shell would be
// non-empty, and it would be valuable to also generate an empty
// RSC shell.
if (meta.postponed) {
htmlAllowQuery = []
if (routesManifest.rsc.dynamicRSCPrerender) {
// If client param parsing is enabled, we follow the same logic as the
// HTML allowQuery as it's already going to vary based on if there's a
// static shell generated or if there's fallback root params. If there
// are fallback root params, and we can serve a fallback, then we
// should follow the same logic for the dynamic RSC routes.
//
// If client param parsing is not enabled, we have to use the
// allowQuery because the RSC payloads will contain dynamic segment
// values.
if (routesManifest.rsc.clientParamParsing) {
dataAllowQuery = htmlAllowQuery
}
}
}
if (renderingMode === RenderingMode.PARTIALLY_STATIC) {
// Dynamic RSC requests cannot be cached, so we explicity set it
// here to ensure that the response is not cached by the browser.
dataInitialHeaders['cache-control'] =
'private, no-store, no-cache, max-age=0, must-revalidate'
}
const initialOutput: AdapterOutput['PRERENDER'] = {
id: route,
type: AdapterOutputType.PRERENDER,
......@@ -1264,7 +1342,7 @@ export async function handleBuildComplete({
groupId: prerenderGroupId,
pprChain:
isAppPage && config.experimental.ppr
isAppPage && renderingMode === RenderingMode.PARTIALLY_STATIC
? {
headers: {
[NEXT_RESUME_HEADER]: '1',
......@@ -1278,8 +1356,11 @@ export async function handleBuildComplete({
!isNotFoundTrue || (isNotFoundTrue && hasStatic404)
? {
filePath,
postponedState: undefined,
initialStatus:
(initialStatus ?? isNotFoundTrue) ? 404 : undefined,
initialStatus ??
meta.status ??
(isNotFoundTrue ? 404 : undefined),
initialHeaders: {
...initialHeaders,
vary: varyHeader,
......@@ -1297,7 +1378,10 @@ export async function handleBuildComplete({
allowQuery,
allowHeader,
renderingMode,
bypassFor: experimentalBypassFor,
bypassFor:
isAppPage && srcRoute !== '/_not-found'
? experimentalBypassFor
: undefined,
bypassToken: prerenderManifest.preview.previewModeId,
},
}
......@@ -1333,25 +1417,23 @@ export async function handleBuildComplete({
renderingMode === RenderingMode.PARTIALLY_STATIC &&
!(await cachedFilePathCheck(dataFilePath))
) {
// TODO: allowQuery should diverge based on app client param
// parsing flag
outputs.prerenders.push({
...initialOutput,
id: dataRoute,
pathname: dataRoute,
fallback: !postponed
? undefined
: {
...initialOutput.fallback,
postponedState: postponed,
initialHeaders: {
...initialOutput.fallback?.initialHeaders,
'content-type': isAppPage
? rscContentTypeHeader
: JSON_CONTENT_TYPE_HEADER,
},
filePath: undefined,
},
fallback: {
...initialOutput.fallback,
postponedState: postponed,
initialStatus: undefined,
initialHeaders: {
...initialOutput.fallback?.initialHeaders,
...dataInitialHeaders,
'content-type': isAppPage
? rscContentTypeHeader
: JSON_CONTENT_TYPE_HEADER,
},
filePath: undefined,
},
})
} else {
outputs.prerenders.push({
......@@ -1362,12 +1444,15 @@ export async function handleBuildComplete({
? undefined
: {
...initialOutput.fallback,
initialStatus: undefined,
initialHeaders: {
...initialOutput.fallback?.initialHeaders,
...dataInitialHeaders,
'content-type': isAppPage
? rscContentTypeHeader
: JSON_CONTENT_TYPE_HEADER,
},
postponedState: undefined,
filePath: dataFilePath,
},
})
......@@ -1375,7 +1460,10 @@ export async function handleBuildComplete({
}
if (isAppPage) {
await handleAppMeta(route, initialOutput, meta)
await handleAppMeta(route, initialOutput, meta, {
htmlAllowQuery,
dataAllowQuery,
})
}
prerenderGroupId += 1
}
......@@ -1388,6 +1476,7 @@ export async function handleBuildComplete({
fallbackHeaders,
fallbackStatus,
fallbackSourceRoute,
fallbackRootParams,
allowHeader,
dataRoute,
renderingMode,
......@@ -1398,12 +1487,29 @@ export async function handleBuildComplete({
const parentOutput = getParentOutput(srcRoute, dynamicRoute)
const isAppPage = Boolean(appOutputMap[srcRoute])
const meta = await getAppRouteMeta(dynamicRoute, isAppPage)
const allowQuery = Object.values(
routesManifest.dynamicRoutes.find(
(item) => item.page === dynamicRoute
)?.routeKeys || {}
)
const meta = await getAppRouteMeta(dynamicRoute, isAppPage)
let htmlAllowQuery = allowQuery
// We only want to vary on the shell contents if there is a fallback
// present and able to be served.
if (typeof fallback === 'string') {
if (fallbackRootParams && fallbackRootParams.length > 0) {
htmlAllowQuery = fallbackRootParams as string[]
} // We additionally vary based on if there's a postponed prerender
// because if there isn't, then that means that we generated an
// empty shell, and producing an empty RSC shell would be a waste.
// If there is a postponed prerender, then the RSC shell would be
// non-empty, and it would be valuable to also generate an empty
// RSC shell.
else if (meta.postponed) {
htmlAllowQuery = []
}
}
const initialOutput: AdapterOutput['PRERENDER'] = {
id: dynamicRoute,
......@@ -1411,13 +1517,16 @@ export async function handleBuildComplete({
pathname: dynamicRoute,
parentOutputId: parentOutput.id,
groupId: prerenderGroupId,
config: {
allowQuery,
allowHeader,
renderingMode,
bypassFor: experimentalBypassFor,
bypassToken: prerenderManifest.preview.previewModeId,
},
pprChain:
isAppPage && renderingMode === RenderingMode.PARTIALLY_STATIC
? {
headers: {
[NEXT_RESUME_HEADER]: '1',
},
}
: undefined,
fallback:
typeof fallback === 'string'
? {
......@@ -1427,15 +1536,25 @@ export async function handleBuildComplete({
// extension so ensure it's added here
fallback.endsWith('.html') ? fallback : `${fallback}.html`
),
initialStatus: fallbackStatus,
postponedState: undefined,
initialStatus: fallbackStatus ?? meta.status,
initialHeaders: {
...fallbackHeaders,
...(appPageKeys?.length ? { vary: varyHeader } : {}),
'content-type': HTML_CONTENT_TYPE_HEADER,
...meta.headers,
},
initialExpiration: fallbackExpire,
initialRevalidate: fallbackRevalidate || 1,
initialRevalidate: fallbackRevalidate ?? 1,
}
: undefined,
config: {
allowQuery: htmlAllowQuery,
allowHeader,
renderingMode,
bypassFor: isAppPage ? experimentalBypassFor : undefined,
bypassToken: prerenderManifest.preview.previewModeId,
},
}
if (!config.i18n || isAppPage) {
......@@ -1456,8 +1575,36 @@ export async function handleBuildComplete({
})
}
let dataAllowQuery = allowQuery
const dataInitialHeaders: Record<string, string> = {}
if (meta.postponed && routesManifest.rsc.dynamicRSCPrerender) {
// If client param parsing is enabled, we follow the same logic as the
// HTML allowQuery as it's already going to vary based on if there's a
// static shell generated or if there's fallback root params. If there
// are fallback root params, and we can serve a fallback, then we
// should follow the same logic for the dynamic RSC routes.
//
// If client param parsing is not enabled, we have to use the
// allowQuery because the RSC payloads will contain dynamic segment
// values.
if (routesManifest.rsc.clientParamParsing) {
dataAllowQuery = htmlAllowQuery
}
}
if (renderingMode === RenderingMode.PARTIALLY_STATIC) {
// Dynamic RSC requests cannot be cached, so we explicity set it
// here to ensure that the response is not cached by the browser.
dataInitialHeaders['cache-control'] =
'private, no-store, no-cache, max-age=0, must-revalidate'
}
if (isAppPage) {
await handleAppMeta(dynamicRoute, initialOutput, meta)
await handleAppMeta(dynamicRoute, initialOutput, meta, {
htmlAllowQuery,
dataAllowQuery,
})
}
if (renderingMode === RenderingMode.PARTIALLY_STATIC) {
......@@ -1465,18 +1612,24 @@ export async function handleBuildComplete({
...initialOutput,
id: `${dynamicRoute}.rsc`,
pathname: `${dynamicRoute}.rsc`,
fallback: meta.postponed
? {
...initialOutput.fallback,
postponedState: meta.postponed,
initialHeaders: {
...initialOutput.fallback?.initialHeaders,
'content-type': isAppPage
? rscContentTypeHeader
: JSON_CONTENT_TYPE_HEADER,
},
}
: undefined,
fallback: {
...initialOutput.fallback,
filePath: undefined,
postponedState: meta.postponed,
initialStatus: undefined,
initialHeaders: {
...initialOutput.fallback?.initialHeaders,
...dataInitialHeaders,
'content-type': isAppPage
? rscContentTypeHeader
: JSON_CONTENT_TYPE_HEADER,
},
},
config: {
...initialOutput.config,
allowQuery: dataAllowQuery,
},
})
} else if (dataRoute) {
outputs.prerenders.push({
......@@ -1489,7 +1642,7 @@ export async function handleBuildComplete({
prerenderGroupId += 1
} else {
for (const locale of config.i18n.locales) {
const currentOutput = {
const currentOutput: AdapterOutput['PRERENDER'] = {
...initialOutput,
pathname: path.posix.join(`/${locale}`, initialOutput.pathname),
id: path.posix.join(`/${locale}`, initialOutput.id),
......@@ -1497,6 +1650,8 @@ export async function handleBuildComplete({
typeof fallback === 'string'
? {
...initialOutput.fallback,
initialStatus: undefined,
postponedState: undefined,
filePath: path.join(
pagesDistDir,
locale,
......@@ -1624,7 +1779,7 @@ export async function handleBuildComplete({
const sourceRegex = routeRegex.namedRegex.replace(
'^',
`^${config.basePath && config.basePath !== '/' ? path.posix.join('/', config.basePath || '') : ''}[/]?${shouldLocalize ? '(?<nextLocale>[^/]{1,})?' : ''}`
`^${config.basePath && config.basePath !== '/' ? path.posix.join('/', config.basePath || '') : ''}[/]?${shouldLocalize ? '(?<nextLocale>[^/]{1,})' : ''}`
)
const destination =
path.posix.join(
......@@ -1751,7 +1906,7 @@ export async function handleBuildComplete({
config.basePath,
`_next/data`,
escapeStringRegexp(buildId)
)}[/]?${shouldLocalize ? '(?<nextLocale>[^/]{1,})?' : ''}`
)}[/]?${shouldLocalize ? '(?<nextLocale>[^/]{1,})' : ''}`
),
destination,
has: isFallbackFalse ? fallbackFalseHasCondition : undefined,
......
......@@ -407,7 +407,7 @@ export async function handler(
// when fixing this to correct logic it causes hydration issue since we set
// serveStreamingMetadata to true during export
const serveStreamingMetadata =
isHtmlBot && isRoutePPREnabled
botType && isRoutePPREnabled
? false
: !userAgent
? true
......@@ -417,9 +417,10 @@ export async function handler(
(prerenderInfo ||
isPrerendered ||
prerenderManifest.routes[normalizedSrcPage]) &&
// If this is a html bot request and PPR is enabled, then we don't want
// to serve a static response.
!(isHtmlBot && isRoutePPREnabled)
// If this is a bot request and PPR is enabled, then we don't want
// to serve a static response. This applies to both DOM bots (like Googlebot)
// and HTML-limited bots.
!(botType && isRoutePPREnabled)
)
// When a page supports cacheComponents, we can support RDC for Navigations
......@@ -449,8 +450,9 @@ export async function handler(
: // Otherwise, we can support dynamic responses if it's a dynamic RSC request.
isDynamicRSCRequest)
// When html bots request PPR page, perform the full dynamic rendering.
const shouldWaitOnAllReady = isHtmlBot && isRoutePPREnabled
// When bots request PPR page, perform the full dynamic rendering.
// This applies to both DOM bots (like Googlebot) and HTML-limited bots.
const shouldWaitOnAllReady = Boolean(botType) && isRoutePPREnabled
let ssgCacheKey: string | null = null
if (
......@@ -575,7 +577,17 @@ export async function handler(
})
}
const incrementalCache = getRequestMeta(req, 'incrementalCache')
const incrementalCache =
getRequestMeta(req, 'incrementalCache') ||
(await routeModule.getIncrementalCache(
req,
nextConfig,
prerenderManifest,
isMinimalMode
))
incrementalCache?.resetRequestCache()
;(globalThis as any).__incrementalCache = incrementalCache
const doRender = async ({
span,
......
......@@ -203,6 +203,19 @@ export async function handler(
const method = req.method || 'GET'
const tracer = getTracer()
const activeSpan = tracer.getActiveScopeSpan()
const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'))
const incrementalCache =
getRequestMeta(req, 'incrementalCache') ||
(await routeModule.getIncrementalCache(
req,
nextConfig,
prerenderManifest,
isMinimalMode
))
incrementalCache?.resetRequestCache()
;(globalThis as any).__incrementalCache = incrementalCache
const context: AppRouteRouteHandlerContext = {
params,
......@@ -213,7 +226,7 @@ export async function handler(
},
cacheComponents: Boolean(nextConfig.cacheComponents),
supportsDynamicResponse,
incrementalCache: getRequestMeta(req, 'incrementalCache'),
incrementalCache,
cacheLifeProfiles: nextConfig.cacheLife,
waitUntil: ctx.waitUntil,
onClose: (cb) => {
......@@ -289,7 +302,6 @@ export async function handler(
}
})
}
const isMinimalMode = Boolean(getRequestMeta(req, 'minimalMode'))
const handleResponse = async (currentSpan?: Span) => {
const responseGenerator: ResponseGenerator = async ({
......
......@@ -118,7 +118,6 @@ import { AsyncCallbackSet } from './lib/async-callback-set'
import { initializeCacheHandlers, setCacheHandler } from './use-cache/handlers'
import type { UnwrapPromise } from '../lib/coalesced-function'
import { populateStaticEnv } from '../lib/static-env'
import { isPostpone } from './lib/router-utils/is-postpone'
import { NodeModuleLoader } from './lib/module-loader/node-module-loader'
import { NoFallbackError } from '../shared/lib/no-fallback-error.external'
import {
......@@ -130,6 +129,7 @@ import {
routerServerGlobal,
} from './lib/router-utils/router-server-context'
import { installGlobalBehaviors } from './node-environment-extensions/global-behaviors'
import { installProcessErrorHandlers } from './node-environment-extensions/process-error-handlers'
export * from './base-server'
......@@ -170,88 +170,6 @@ function getMiddlewareMatcher(
return matcher
}
function installProcessErrorHandlers(
shouldRemoveUncaughtErrorAndRejectionListeners: boolean
) {
// The conventional wisdom of Node.js and other runtimes is to treat
// unhandled errors as fatal and exit the process.
//
// But Next.js is not a generic JS runtime — it's a specialized runtime for
// React Server Components.
//
// Many unhandled rejections are due to the late-awaiting pattern for
// prefetching data. In Next.js it's OK to call an async function without
// immediately awaiting it, to start the request as soon as possible
// without blocking unncessarily on the result. These can end up
// triggering an "unhandledRejection" if it later turns out that the
// data is not needed to render the page. Example:
//
// const promise = fetchData()
// const shouldShow = await checkCondition()
// if (shouldShow) {
// return <Component promise={promise} />
// }
//
// In this example, `fetchData` is called immediately to start the request
// as soon as possible, but if `shouldShow` is false, then it will be
// discarded without unwrapping its result. If it errors, it will trigger
// an "unhandledRejection" event.
//
// Ideally, we would suppress these rejections completely without warning,
// because we don't consider them real errors. (TODO: Currently we do warn.)
//
// But regardless of whether we do or don't warn, we definitely shouldn't
// crash the entire process.
//
// Even a "legit" unhandled error unrelated to prefetching shouldn't
// prevent the rest of the page from rendering.
//
// So, we're going to intentionally override the default error handling
// behavior of the outer JS runtime to be more forgiving
// Remove any existing "unhandledRejection" and "uncaughtException" handlers.
// This is gated behind an experimental flag until we've considered the impact
// in various deployment environments. It's possible this may always need to
// be configurable.
if (shouldRemoveUncaughtErrorAndRejectionListeners) {
process.removeAllListeners('uncaughtException')
process.removeAllListeners('unhandledRejection')
}
// Install a new handler to prevent the process from crashing.
process.on('unhandledRejection', (reason: unknown) => {
if (isPostpone(reason)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return
}
// Immediately log the error.
// TODO: Ideally, if we knew that this error was triggered by application
// code, we would suppress it entirely without logging. We can't reliably
// detect all of these, but when cacheComponents is enabled, we could suppress
// at least some of them by waiting to log the error until after all in-
// progress renders have completed. Then, only log errors for which there
// was not a corresponding "rejectionHandled" event.
console.error(reason)
})
process.on('rejectionHandled', () => {
// TODO: See note in the unhandledRejection handler above. In the future,
// we may use the "rejectionHandled" event to de-queue an error from
// being logged.
})
// Unhandled exceptions are errors triggered by non-async functions, so this
// is unrelated to the late-awaiting pattern. However, for similar reasons,
// we still shouldn't crash the process. Just log it.
process.on('uncaughtException', (reason: unknown) => {
if (isPostpone(reason)) {
return
}
console.error(reason)
})
}
export default class NextNodeServer extends BaseServer<
Options,
NodeNextRequest,
......
import { isPostpone } from '../lib/router-utils/is-postpone'
let _global = globalThis as typeof globalThis & {
nextInitializedProcessErrorHandlers?: boolean
}
export function installProcessErrorHandlers(
shouldRemoveUncaughtErrorAndRejectionListeners: boolean
) {
if (_global.nextInitializedProcessErrorHandlers) return
_global.nextInitializedProcessErrorHandlers = true
// The conventional wisdom of Node.js and other runtimes is to treat
// unhandled errors as fatal and exit the process.
//
// But Next.js is not a generic JS runtime — it's a specialized runtime for
// React Server Components.
//
// Many unhandled rejections are due to the late-awaiting pattern for
// prefetching data. In Next.js it's OK to call an async function without
// immediately awaiting it, to start the request as soon as possible
// without blocking unncessarily on the result. These can end up
// triggering an "unhandledRejection" if it later turns out that the
// data is not needed to render the page. Example:
//
// const promise = fetchData()
// const shouldShow = await checkCondition()
// if (shouldShow) {
// return <Component promise={promise} />
// }
//
// In this example, `fetchData` is called immediately to start the request
// as soon as possible, but if `shouldShow` is false, then it will be
// discarded without unwrapping its result. If it errors, it will trigger
// an "unhandledRejection" event.
//
// Ideally, we would suppress these rejections completely without warning,
// because we don't consider them real errors. (TODO: Currently we do warn.)
//
// But regardless of whether we do or don't warn, we definitely shouldn't
// crash the entire process.
//
// Even a "legit" unhandled error unrelated to prefetching shouldn't
// prevent the rest of the page from rendering.
//
// So, we're going to intentionally override the default error handling
// behavior of the outer JS runtime to be more forgiving
// Remove any existing "unhandledRejection" and "uncaughtException" handlers.
// This is gated behind an experimental flag until we've considered the impact
// in various deployment environments. It's possible this may always need to
// be configurable.
if (shouldRemoveUncaughtErrorAndRejectionListeners) {
process.removeAllListeners('uncaughtException')
process.removeAllListeners('unhandledRejection')
}
// Install a new handler to prevent the process from crashing.
process.on('unhandledRejection', (reason: unknown) => {
if (isPostpone(reason)) {
// React postpones that are unhandled might end up logged here but they're
// not really errors. They're just part of rendering.
return
}
// Immediately log the error.
// TODO: Ideally, if we knew that this error was triggered by application
// code, we would suppress it entirely without logging. We can't reliably
// detect all of these, but when cacheComponents is enabled, we could suppress
// at least some of them by waiting to log the error until after all in-
// progress renders have completed. Then, only log errors for which there
// was not a corresponding "rejectionHandled" event.
console.error(reason)
})
process.on('rejectionHandled', () => {
// TODO: See note in the unhandledRejection handler above. In the future,
// we may use the "rejectionHandled" event to de-queue an error from
// being logged.
})
// Unhandled exceptions are errors triggered by non-async functions, so this
// is unrelated to the late-awaiting pattern. However, for similar reasons,
// we still shouldn't crash the process. Just log it.
process.on('uncaughtException', (reason: unknown) => {
if (isPostpone(reason)) {
return
}
console.error(reason)
})
}
......@@ -630,12 +630,35 @@ export abstract class RouteModule<
const { routesManifest, prerenderManifest, serverFilesManifest } = manifests
const { basePath, i18n, rewrites } = routesManifest
const relativeProjectDir =
getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir
const routerServerContext =
routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]
const nextConfig =
routerServerContext?.nextConfig || serverFilesManifest?.config
// Injected in base-server.ts
const protocol = req.headers['x-forwarded-proto']?.includes('https')
? 'https'
: 'http'
// When there are hostname and port we build an absolute URL
if (!getRequestMeta(req, 'initURL')) {
const initUrl = serverFilesManifest?.config.experimental.trustHostHeader
? `${protocol}://${req.headers.host || 'localhost'}${req.url}`
: `${protocol}://${routerServerContext?.hostname || 'localhost'}${req.url}`
addRequestMeta(req, 'initURL', initUrl)
addRequestMeta(req, 'initProtocol', protocol)
}
if (basePath) {
req.url = removePathPrefix(req.url || '/', basePath)
}
const parsedUrl = parseReqUrl(req.url || '/')
addRequestMeta(req, 'initQuery', { ...parsedUrl?.query })
// if we couldn't parse the URL we can't continue
if (!parsedUrl) {
return
......@@ -815,12 +838,14 @@ export abstract class RouteModule<
if (
// if both query and params are valid but one
// provided more information rely on that one
// provided more information and the query params
// were nxtP prefixed rely on that one
query &&
params &&
paramsResult.hasValidParams &&
queryResult.hasValidParams &&
Object.keys(paramsResult.params).length <
routeParamKeys.size > 0 &&
Object.keys(paramsResult.params).length <=
Object.keys(queryResult.params).length
) {
paramsToInterpolate = queryResult.params
......@@ -880,6 +905,15 @@ export abstract class RouteModule<
for (const key of routeParamKeys) {
if (!(key in originalQuery)) {
delete query[key]
// handle the case where there's collision and we
// normalized nxtPid=123 -> id=123 but user also
// sends id=456 as separate key
} else if (
originalQuery[key] &&
query[key] &&
originalQuery[key] !== query[key]
) {
query[key] = originalQuery[key]
}
}
......@@ -903,18 +937,21 @@ export abstract class RouteModule<
isDraftMode = previewData !== false
}
const relativeProjectDir =
getRequestMeta(req, 'relativeProjectDir') || this.relativeProjectDir
const routerServerContext =
routerServerGlobal[RouterServerContextSymbol]?.[relativeProjectDir]
const nextConfig =
routerServerContext?.nextConfig || serverFilesManifest?.config
if (!nextConfig) {
throw new Error("Invariant: nextConfig couldn't be loaded")
}
if (process.env.NEXT_RUNTIME !== 'edge') {
const { installProcessErrorHandlers } =
require('../node-environment-extensions/process-error-handlers') as typeof import('../node-environment-extensions/process-error-handlers')
installProcessErrorHandlers(
Boolean(
nextConfig.experimental.removeUncaughtErrorAndRejectionListeners
)
)
}
let resolvedPathname = normalizedSrcPage
if (isDynamicRoute(resolvedPathname) && params) {
resolvedPathname = serverUtils.interpolateDynamicPath(
......@@ -926,6 +963,17 @@ export abstract class RouteModule<
if (resolvedPathname === '/index') {
resolvedPathname = '/'
}
if (
res &&
Boolean(req.headers['x-nextjs-data']) &&
(!res.statusCode || res.statusCode === 200)
) {
res.setHeader(
'x-nextjs-matched-path',
removeTrailingSlash(`${locale ? `/${locale}` : ''}${normalizedSrcPage}`)
)
}
const encodedResolvedPathname = resolvedPathname
// we decode for cache key/manifest usage encoded is
......
......@@ -61,10 +61,6 @@ const myAdapter = {
`Missing fallback file for prerender ${output.id}: ${JSON.stringify(output, null, 2)}`
)
}
} else if (!output.fallback.postponedState) {
throw new Error(
`Missing postponed state or filePath for prerender ${output.id} ${JSON.stringify(output, null, 2)}`
)
}
}
......
......@@ -4,7 +4,8 @@
const nextConfig = {
cacheComponents: true,
experimental: {
adapterPath: require.resolve('./my-adapter.mjs'),
adapterPath:
process.env.NEXT_ADAPTER_PATH ?? require.resolve('./my-adapter.mjs'),
},
}
......
......@@ -275,9 +275,13 @@ export class NextInstance {
},
...(this.resolutions ? { resolutions: this.resolutions } : {}),
scripts: {
// since we can't get the build id as a build artifact, make it
// available under the static files
'post-build': `cp ${this.distDir}/BUILD_ID ${this.distDir}/static/__BUILD_ID`,
...(isNextDeploy
? // since we can't get the build id as a build artifact,
// add it in build logs
{
'post-build': `node -e 'console.log("BUILD" + "_ID: " + require("fs").readFileSync("${this.distDir}/BUILD_ID"))'`,
}
: {}),
...pkgScripts,
build:
(pkgScripts['build'] || this.buildCommand || 'next build') +
......
......@@ -8,7 +8,6 @@ import {
TEST_TEAM_NAME,
TEST_TOKEN,
} from '../../../scripts/reset-project.mjs'
import fetch from 'node-fetch'
import { Span } from 'next/dist/trace'
export class NextDeployInstance extends NextInstance {
......@@ -141,6 +140,9 @@ export class NextDeployInstance extends NextInstance {
if (process.env.IS_WEBPACK_TEST) {
additionalEnv.push(`IS_WEBPACK_TEST=1`)
}
if (process.env.NEXT_ENABLE_ADAPTER) {
additionalEnv.push(`NEXT_ENABLE_ADAPTER=1`)
}
const deployRes = await execa(
'vercel',
......@@ -214,20 +216,6 @@ export class NextDeployInstance extends NextInstance {
}
require('console').log(`Deployment URL: ${this._url}`)
const buildIdUrl = `${this._url}${
this.basePath || ''
}/_next/static/__BUILD_ID`
const buildIdRes = await fetch(buildIdUrl)
if (!buildIdRes.ok) {
require('console').error(
`Failed to load buildId ${buildIdUrl} (${buildIdRes.status})`
)
}
this._buildId = (await buildIdRes.text()).trim()
require('console').log(`Got buildId: ${this._buildId}`)
// Use the vercel inspect command to get the CLI output from the build.
const buildLogs = await execa(
......@@ -241,13 +229,20 @@ export class NextDeployInstance extends NextInstance {
if (buildLogs.exitCode !== 0) {
throw new Error(`Failed to get build output logs: ${buildLogs.stderr}`)
}
// Use the stdout from the logs command as the CLI output. The CLI will
// output other unrelated logs to stderr.
// TODO: Combine with runtime logs (via `vercel logs`)
// Build logs seem to be piped to stderr, so we'll combine them to make sure we get all the logs.
this._cliOutput = buildLogs.stdout + buildLogs.stderr
const buildId = this._cliOutput.match(/BUILD_ID: (.+)/)?.[1]?.trim()
if (!buildId) {
throw new Error(`Failed to get buildId from logs ${this._cliOutput}`)
}
this._buildId = buildId
require('console').log(`Got buildId: ${this._buildId}`)
// Use the stdout from the logs command as the CLI output. The CLI will
// output other unrelated logs to stderr.
}
public async destroy() {
......
......@@ -63,7 +63,7 @@ const myAdapter = {
)
}
} else if (!output.fallback.postponedState) {
throw new Error(
console.error(
`Missing postponed state or filePath for prerender ${output.id} ${JSON.stringify(output, null, 2)}`
)
}
......
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