Unverified Commit 993e02c9 authored by David Alexandru Ilie's avatar David Alexandru Ilie Committed by GitHub

build: show non-200 prerender statuses

parent 1722e45c
......@@ -3441,6 +3441,11 @@ export default async function build(
route.pathname,
appConfig.revalidate
)
const prerenderStatus =
cacheControl.revalidate !== 0 &&
route.pathname !== UNDERSCORE_NOT_FOUND_ROUTE
? (routeResult?.prerenderStatus ?? metadata.status)
: undefined
// Generated concrete paths (for example `/blog/post-1`) inherit
// the route-level classification from the dynamic page
......@@ -3457,6 +3462,7 @@ export default async function build(
hasPostponed,
hasEmptyStaticShell,
initialCacheControl: cacheControl,
prerenderStatus,
})
// update the page (eg /blog/[slug]) to also have the postpone metadata
......@@ -3608,6 +3614,11 @@ export default async function build(
const metadata = routeResult?.metadata
const cacheControl = getCacheControl(route.pathname)
const prerenderStatus =
cacheControl.revalidate !== 0 &&
route.pathname !== UNDERSCORE_NOT_FOUND_ROUTE
? (routeResult?.prerenderStatus ?? metadata?.status)
: undefined
let dataRoute: string | null = null
if (!isAppRouteHandler) {
......@@ -3706,6 +3717,7 @@ export default async function build(
// if PPR is turned on and the route contains a dynamic segment,
// we assume it'll be partially prerendered
hasPostponed: isRoutePPREnabled,
prerenderStatus,
})
} else {
// Concrete generated paths inherit the parent route's base
......@@ -3723,6 +3735,7 @@ export default async function build(
// if PPR is turned on and the route contains a dynamic segment,
// we assume it'll be partially prerendered
hasPostponed: isRoutePPREnabled,
prerenderStatus,
})
}
......
......@@ -220,6 +220,8 @@ export interface PageInfo {
hasEmptyStaticShell?: boolean
hasPostponed?: boolean
isDynamicAppRoute?: boolean
/** The HTTP status produced when this route was prerendered. */
prerenderStatus?: number
}
export type PageInfos = Map<string, PageInfo>
......@@ -266,6 +268,96 @@ function getTreeViewSymbol(
return 'ƒ'
}
function getNon200PrerenderStatus(
pageInfo: PageInfo | undefined
): number | undefined {
const status = pageInfo?.prerenderStatus
return status !== undefined && status !== 200 ? status : undefined
}
function getPrerenderStatusAnnotation(pageInfo: PageInfo | undefined): string {
const status = getNon200PrerenderStatus(pageInfo)
return status !== undefined ? ` [status: ${status}]` : ''
}
type TreeViewRoute = {
route: string
duration: number
avgDuration?: number
hiddenStatusAnnotation?: string
}
function getHiddenStatusAnnotation(
routes: TreeViewRoute[],
pageInfos: Map<string, PageInfo>
): string | undefined {
const statusCounts = new Map<number, number>()
for (const route of routes) {
const status = getNon200PrerenderStatus(pageInfos.get(route.route))
if (status !== undefined) {
statusCounts.set(status, (statusCounts.get(status) ?? 0) + 1)
}
}
if (statusCounts.size === 0) {
return undefined
}
const summary = Array.from(statusCounts, ([status, count]) =>
count === 1 ? `${status}` : `${status} × ${count}`
).join(', ')
return ` [status: ${summary}]`
}
function selectTreeViewRoutePreview(
routes: TreeViewRoute[],
previewSize: number,
pageInfos: Map<string, PageInfo>
): { preview: TreeViewRoute[]; remaining: TreeViewRoute[] } {
const preview = routes.slice(0, previewSize)
const hiddenNon200Routes = routes
.slice(previewSize)
.filter(
(route) =>
getNon200PrerenderStatus(pageInfos.get(route.route)) !== undefined
)
if (hiddenNon200Routes.length === 0) {
return { preview, remaining: routes.slice(previewSize) }
}
// Preserve the normal preview size while replacing healthy samples with
// non-200 routes. Any remaining non-200 statuses are shown on the summary.
const selectedRoutes = new Set(preview)
for (const hiddenRoute of hiddenNon200Routes) {
let routeToReplace: TreeViewRoute | undefined
for (let i = preview.length - 1; i >= 0; i--) {
const candidate = preview[i]
if (
selectedRoutes.has(candidate) &&
getNon200PrerenderStatus(pageInfos.get(candidate.route)) === undefined
) {
routeToReplace = candidate
break
}
}
if (!routeToReplace) {
break
}
selectedRoutes.delete(routeToReplace)
selectedRoutes.add(hiddenRoute)
}
return {
preview: routes.filter((route) => selectedRoutes.has(route)),
remaining: routes.filter((route) => !selectedRoutes.has(route)),
}
}
export interface RoutesUsingEdgeRuntime {
[route: string]: 0
}
......@@ -391,6 +483,9 @@ export async function printTreeView(
const hasChildRoutes = Boolean(pageInfo?.ssgPageRoutes?.length)
const displayPath = getTreeViewDisplayPath(item)
const prerenderStatusAnnotation = hasChildRoutes
? ''
: getPrerenderStatusAnnotation(pageInfo)
if (hasGSPAndRevalidateZero.has(item)) {
usedSymbols.add('ƒ')
......@@ -416,7 +511,7 @@ export async function printTreeView(
}
messages.push([
`${border} ${hasChildRoutes ? ' ' : symbol} ${displayPath}${
`${border} ${hasChildRoutes ? ' ' : symbol} ${displayPath}${prerenderStatusAnnotation}${
totalDuration > MIN_DURATION
? ` (${getPrettyDuration(totalDuration)})`
: ''
......@@ -433,9 +528,7 @@ export async function printTreeView(
const totalRoutes = pageInfo.ssgPageRoutes.length
const contSymbol = i === arr.length - 1 ? ' ' : '│'
// HERE
let routes: { route: string; duration: number; avgDuration?: number }[]
let routes: TreeViewRoute[]
if (pageInfo.ssgPageDurations?.some((d) => d > MIN_DURATION)) {
const previewPages = totalRoutes === 8 ? 8 : Math.min(totalRoutes, 7)
const routesWithDuration = pageInfo.ssgPageRoutes
......@@ -448,8 +541,13 @@ export async function printTreeView(
// keep too small durations in original order at the end
a <= MIN_DURATION && b <= MIN_DURATION ? 0 : b - a
)
routes = routesWithDuration.slice(0, previewPages)
const remainingRoutes = routesWithDuration.slice(previewPages)
const preview = selectTreeViewRoutePreview(
routesWithDuration,
previewPages,
pageInfos
)
routes = preview.preview
const remainingRoutes = preview.remaining
if (remainingRoutes.length) {
const remaining = remainingRoutes.length
const avgDuration = Math.round(
......@@ -462,33 +560,51 @@ export async function printTreeView(
route: `[+${remaining} more paths]`,
duration: 0,
avgDuration,
hiddenStatusAnnotation: getHiddenStatusAnnotation(
remainingRoutes,
pageInfos
),
})
}
} else {
const previewPages = totalRoutes === 4 ? 4 : Math.min(totalRoutes, 3)
routes = pageInfo.ssgPageRoutes
.slice(0, previewPages)
.map((route) => ({ route, duration: 0 }))
if (totalRoutes > previewPages) {
const remaining = totalRoutes - previewPages
routes.push({ route: `[+${remaining} more paths]`, duration: 0 })
const preview = selectTreeViewRoutePreview(
pageInfo.ssgPageRoutes.map((route) => ({ route, duration: 0 })),
previewPages,
pageInfos
)
routes = preview.preview
if (preview.remaining.length) {
const remaining = preview.remaining.length
routes.push({
route: `[+${remaining} more paths]`,
duration: 0,
hiddenStatusAnnotation: getHiddenStatusAnnotation(
preview.remaining,
pageInfos
),
})
}
}
routes.forEach(
({ route, duration, avgDuration }, index, { length }) => {
(
{ route, duration, avgDuration, hiddenStatusAnnotation },
index,
{ length }
) => {
const innerSymbol = index === length - 1 ? '└' : '├'
// Generated child paths can have more precise metadata than the
// parent route pattern, so prefer the child entry when present.
const routePageInfo = pageInfos.get(route) ?? pageInfo
const childPageInfo = pageInfos.get(route)
const routePageInfo = childPageInfo ?? pageInfo
const routeSymbol = getTreeViewSymbol(route, routePageInfo)
usedSymbols.add(routeSymbol)
const initialCacheControl =
pageInfos.get(route)?.initialCacheControl
const initialCacheControl = childPageInfo?.initialCacheControl
messages.push([
`${contSymbol} ${innerSymbol} ${routeSymbol} ${route}${
`${contSymbol} ${innerSymbol} ${routeSymbol} ${route}${getPrerenderStatusAnnotation(childPageInfo)}${hiddenStatusAnnotation ?? ''}${
duration > MIN_DURATION
? ` (${getPrettyDuration(duration)})`
: ''
......
......@@ -846,6 +846,9 @@ async function exportAppImpl(
if (typeof result.metadata !== 'undefined') {
info.metadata = result.metadata
}
if (typeof result.prerenderStatus !== 'undefined') {
info.prerenderStatus = result.prerenderStatus
}
if (typeof result.hasEmptyStaticShell !== 'undefined') {
info.hasEmptyStaticShell = result.hasEmptyStaticShell
......
......@@ -236,6 +236,9 @@ export async function exportAppPage(
segmentPaths: meta.segmentPaths,
prefetchHints: meta.prefetchHints,
},
// Keep the status available to build diagnostics even when deployment
// metadata is filtered in environments without Next.js support.
prerenderStatus: status,
hasEmptyStaticShell: Boolean(postponed) && html === '',
hasPostponed: Boolean(postponed),
hasPendingUi: hasPendingUi ?? false,
......
......@@ -69,6 +69,8 @@ export type ExportRouteResult =
| {
cacheControl: CacheControl
metadata?: Partial<RouteMetadata>
/** The HTTP status produced while prerendering this route. */
prerenderStatus?: number
ssgNotFound?: boolean
hasEmptyStaticShell?: boolean
hasPostponed?: boolean
......@@ -144,6 +146,10 @@ export type ExportAppResult = {
* The metadata for the page.
*/
metadata?: Partial<RouteMetadata>
/**
* The HTTP status produced while prerendering the page.
*/
prerenderStatus?: number
/**
* If the page has an empty static shell when using PPR.
*/
......
......@@ -69,6 +69,32 @@ describe('build-output-tree-view', () => {
})
})
describe('with a non-200 prerendered app route', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, 'fixtures/prerender-status'),
skipStart: true,
env: {
__NEXT_PRIVATE_DETERMINISTIC_BUILD_OUTPUT: '1',
},
})
beforeAll(() => next.build())
it('should show the prerendered status for user routes only', () => {
const treeView = getTreeView(next.cliOutput)
expect(treeView).toContain('◐ /error-shell [status: 404]')
expect(treeView).toContain('○ /healthy')
expect(treeView).not.toContain('/healthy [status:')
expect(treeView).toContain('○ /generated/b [status: 404]')
expect(treeView).toContain('○ /generated/c [status: 404]')
expect(treeView).toContain('○ /generated/d [status: 404]')
expect(treeView).toContain('[+4 more paths] [status: 404 × 2]')
expect(treeView).not.toContain('/generated/[slug] [status:')
expect(treeView).not.toContain('/_not-found [status:')
})
})
describe('with generated app routes that mix static and partial outputs', () => {
const { next } = nextTestSetup({
files: path.join(__dirname, '../../../e2e/app-dir/cache-components'),
......
import { notFound } from 'next/navigation'
import { connection } from 'next/server'
export async function generateMetadata() {
await connection()
return { title: 'Runtime metadata' }
}
export default function ErrorShellPage() {
notFound()
}
import { notFound } from 'next/navigation'
export function generateStaticParams() {
return [
{ slug: 'a' },
{ slug: 'b' },
{ slug: 'c' },
{ slug: 'd' },
{ slug: 'e' },
{ slug: 'f' },
]
}
export default async function GeneratedPage({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
if (slug !== 'a') {
notFound()
}
return <p>{slug}</p>
}
import type { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
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