Unverified Commit 88019a04 authored by Jiachi Liu's avatar Jiachi Liu Committed by GitHub

Add graceful error fallback for bots requests (#77916)

parent bd628216
......@@ -25,6 +25,7 @@ import type { InitialRSCPayload } from '../server/app-render/types'
import { createInitialRouterState } from './components/router-reducer/create-initial-router-state'
import { MissingSlotContext } from '../shared/lib/app-router-context.shared-runtime'
import { setAppBuildId } from './app-build-id'
import { isBot } from '../shared/lib/router/utils/is-bot'
/// <reference types="react-dom/experimental" />
......@@ -169,6 +170,7 @@ function ServerRoot({
const router = (
<AppRouter
gracefullyDegrade={isBot(window.navigator.userAgent)}
actionQueue={actionQueue}
globalErrorComponentAndStyles={initialRSCPayload.G}
assetPrefix={initialRSCPayload.p}
......
......@@ -198,10 +198,12 @@ function Router({
actionQueue,
assetPrefix,
globalError,
gracefullyDegrade,
}: {
actionQueue: AppRouterActionQueue
assetPrefix: string
globalError: [GlobalErrorComponent, React.ReactNode]
gracefullyDegrade: boolean
}) {
const state = useActionQueue(actionQueue)
const { canonicalUrl } = state
......@@ -512,15 +514,18 @@ function Router({
</HotReloader>
)
} else {
// In production, we only apply the user-customized global error boundary.
content = (
<ErrorBoundary
errorComponent={globalError[0]}
errorStyles={globalError[1]}
>
{content}
</ErrorBoundary>
)
// If gracefully degrading is applied in production,
// leave the app as it is rather than caught by GlobalError boundary.
if (!gracefullyDegrade) {
content = (
<ErrorBoundary
errorComponent={globalError[0]}
errorStyles={globalError[1]}
>
{content}
</ErrorBoundary>
)
}
}
return (
......@@ -555,26 +560,37 @@ export default function AppRouter({
actionQueue,
globalErrorComponentAndStyles: [globalErrorComponent, globalErrorStyles],
assetPrefix,
gracefullyDegrade,
}: {
actionQueue: AppRouterActionQueue
globalErrorComponentAndStyles: [GlobalErrorComponent, React.ReactNode]
assetPrefix: string
gracefullyDegrade: boolean
}) {
useNavFailureHandler()
return (
<ErrorBoundary
// At the very top level, use the default GlobalError component as the final fallback.
// When the app router itself fails, which means the framework itself fails, we show the default error.
errorComponent={DefaultGlobalError}
>
<Router
actionQueue={actionQueue}
assetPrefix={assetPrefix}
globalError={[globalErrorComponent, globalErrorStyles]}
/>
</ErrorBoundary>
const router = (
<Router
actionQueue={actionQueue}
assetPrefix={assetPrefix}
globalError={[globalErrorComponent, globalErrorStyles]}
gracefullyDegrade={gracefullyDegrade}
/>
)
if (gracefullyDegrade) {
return router
} else {
return (
<ErrorBoundary
// At the very top level, use the default GlobalError component as the final fallback.
// When the app router itself fails, which means the framework itself fails, we show the default error.
errorComponent={DefaultGlobalError}
>
{router}
</ErrorBoundary>
)
}
}
const runtimeStyles = new Set<string>()
......
......@@ -1075,15 +1075,17 @@ function App<T>({
reactServerStream,
preinitScripts,
clientReferenceManifest,
nonce,
ServerInsertedHTMLProvider,
ServerInsertedMetadataProvider,
gracefullyDegrade,
nonce,
}: {
reactServerStream: BinaryStreamOf<T>
preinitScripts: () => void
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
ServerInsertedMetadataProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean
nonce?: string
}): JSX.Element {
preinitScripts()
......@@ -1128,6 +1130,7 @@ function App<T>({
actionQueue={actionQueue}
globalErrorComponentAndStyles={response.G}
assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/>
</ServerInsertedHTMLProvider>
</ServerInsertedMetadataProvider>
......@@ -1144,6 +1147,7 @@ function ErrorApp<T>({
clientReferenceManifest,
ServerInsertedMetadataProvider,
ServerInsertedHTMLProvider,
gracefullyDegrade,
nonce,
}: {
reactServerStream: BinaryStreamOf<T>
......@@ -1151,6 +1155,7 @@ function ErrorApp<T>({
clientReferenceManifest: NonNullable<RenderOpts['clientReferenceManifest']>
ServerInsertedMetadataProvider: React.ComponentType<{ children: JSX.Element }>
ServerInsertedHTMLProvider: React.ComponentType<{ children: JSX.Element }>
gracefullyDegrade: boolean
nonce?: string
}): JSX.Element {
preinitScripts()
......@@ -1186,6 +1191,7 @@ function ErrorApp<T>({
actionQueue={actionQueue}
globalErrorComponentAndStyles={response.G}
assetPrefix={response.p}
gracefullyDegrade={gracefullyDegrade}
/>
</ServerInsertedHTMLProvider>
</ServerInsertedMetadataProvider>
......@@ -1960,6 +1966,7 @@ async function renderToStream(
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
nonce={ctx.nonce}
gracefullyDegrade={!!ctx.renderOpts.botType}
/>,
postponed,
{
......@@ -2000,6 +2007,7 @@ async function renderToStream(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={ctx.nonce}
/>,
{
......@@ -2157,6 +2165,7 @@ async function renderToStream(
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={ctx.nonce}
/>
),
......@@ -2378,6 +2387,7 @@ async function spawnDynamicValidationInDev(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>,
{
......@@ -2523,6 +2533,7 @@ async function spawnDynamicValidationInDev(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={ctx.nonce}
/>,
{
......@@ -2912,6 +2923,7 @@ async function prerenderToStream(
ServerInsertedMetadataProvider={
ServerInsertedMetadataProvider
}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>,
{
......@@ -3070,6 +3082,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>,
{
......@@ -3195,6 +3208,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>,
JSON.parse(JSON.stringify(postponed)),
......@@ -3386,6 +3400,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>,
{
......@@ -3541,6 +3556,7 @@ async function prerenderToStream(
ServerInsertedMetadataProvider={
ServerInsertedMetadataProvider
}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>,
{
......@@ -3720,6 +3736,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>,
{
......@@ -3852,6 +3869,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>,
JSON.parse(JSON.stringify(postponed)),
......@@ -3931,6 +3949,7 @@ async function prerenderToStream(
clientReferenceManifest={clientReferenceManifest}
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
ServerInsertedMetadataProvider={ServerInsertedMetadataProvider}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>,
{
......@@ -4095,6 +4114,7 @@ async function prerenderToStream(
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
preinitScripts={errorPreinitScripts}
clientReferenceManifest={clientReferenceManifest}
gracefullyDegrade={!!ctx.renderOpts.botType}
nonce={nonce}
/>
),
......
......@@ -1795,14 +1795,13 @@ export default abstract class Server<
>
): Promise<void> {
const ua = partialContext.req.headers['user-agent'] || ''
const isBotRequest = isBot(ua)
const ctx: RequestContext<ServerRequest, ServerResponse> = {
...partialContext,
renderOpts: {
...this.renderOpts,
supportsDynamicResponse: !isBotRequest,
botType: getBotType(ua),
// `renderOpts.botType` is accumulated in `this.renderImpl()`
supportsDynamicResponse: !this.renderOpts.botType,
serveStreamingMetadata: shouldServeStreamingMetadata(
ua,
this.nextConfig.htmlLimitedBots
......@@ -1933,6 +1932,9 @@ export default abstract class Server<
pathname = '/'
}
const ua = req.headers['user-agent'] || ''
this.renderOpts.botType = getBotType(ua)
// we allow custom servers to call render for all URLs
// so check if we need to serve a static _next file or not.
// we don't modify the URL for _next/data request but still
......
......@@ -283,6 +283,7 @@ export type RenderOptsPartial = {
isPossibleServerAction?: boolean
isExperimentalCompile?: boolean
isPrefetch?: boolean
isBot?: boolean
expireTime?: number
experimental: {
clientTraceMetadata?: string[]
......
......@@ -54,7 +54,8 @@ export abstract class BrowserInterface<TCurrent = any> {
locale: string,
javaScriptEnabled: boolean,
ignoreHttpsErrors: boolean,
headless: boolean
headless: boolean,
userAgent: string | undefined
): Promise<void>
abstract close(): Promise<void>
......
......@@ -125,7 +125,8 @@ export class Playwright extends BrowserInterface {
locale: string,
javaScriptEnabled: boolean,
ignoreHTTPSErrors: boolean,
headless: boolean
headless: boolean,
userAgent: string | undefined
) {
let device
......@@ -148,6 +149,7 @@ export class Playwright extends BrowserInterface {
locale,
javaScriptEnabled,
ignoreHTTPSErrors,
...(userAgent ? { userAgent } : {}),
...device,
})
contextHasJSEnabled = javaScriptEnabled
......@@ -160,6 +162,7 @@ export class Playwright extends BrowserInterface {
locale,
javaScriptEnabled,
ignoreHTTPSErrors,
...(userAgent ? { userAgent } : {}),
...device,
})
contextHasJSEnabled = javaScriptEnabled
......
......@@ -75,6 +75,11 @@ export interface WebdriverOptions {
ignoreHTTPSErrors?: boolean
cpuThrottleRate?: number
pushErrorAsConsoleLog?: boolean
/**
* Override the user agent
*/
userAgent?: string
}
/**
......@@ -107,6 +112,7 @@ export default async function webdriver(
headless,
cpuThrottleRate,
pushErrorAsConsoleLog,
userAgent,
} = options
const { Playwright, quit } = await import('./browsers/playwright')
......@@ -121,7 +127,8 @@ export default async function webdriver(
!disableJavaScript,
ignoreHTTPSErrors,
// allow headless to be overwritten for a particular test
typeof headless !== 'undefined' ? headless : !!process.env.HEADLESS
typeof headless !== 'undefined' ? headless : !!process.env.HEADLESS,
userAgent
)
;(global as any).browserName = browserName
......
'use client'
import dynamic from 'next/dynamic'
export const Large = dynamic(() => import('./content'))
'use client'
import dynamic from 'next/dynamic'
const AsyncLayout = dynamic(async () => import('./layout-wrapper'))
export default AsyncLayout
'use client'
export default function Large() {
return <p>large test content</p>
}
'use client'
export default ({ children }: any) => (
<html className="layout-cls">
<body className="body-cls">{children}</body>
</html>
)
'use client'
import AsyncLayout from './async-layout'
export default function Root({ children }: { children: React.ReactNode }) {
return <AsyncLayout>{children}</AsyncLayout>
}
'use client'
import { Large } from './async-content'
export default function Page() {
return (
<div className="page">
<p>hello world von server</p>
<Large />
</div>
)
}
export { default } from './page-client'
export const dynamic = 'force-dynamic'
import fs from 'fs'
import path from 'path'
export function deleteBrowserDynamicChunks(next) {
const clientChunkDir = path.join(next.testDir, '.next', 'static', 'chunks')
const clientChunkFiles = fs
.readdirSync(clientChunkDir)
// filter out the js file that contains the text "large test content"
.filter((filename) => {
const filePath = path.join(clientChunkDir, filename)
const isJsFile = filename.endsWith('.js')
const fileContent = isJsFile
? fs.readFileSync(filePath, { encoding: 'utf8' })
: ''
return (
isJsFile && fileContent && fileContent.includes('large test content')
)
})
.map((file) => path.join(clientChunkDir, file))
// Intended to log to help debugging tests
console.log('Deleting client chunk files:', clientChunkFiles)
// delete all chunk files
clientChunkFiles.map((file) => fs.rmSync(file))
}
// Duplicate the test file of graceful-degrade-error-bot.test.ts since we need to
// restart with a new browser context for UA setting. Otherwise the browser context
// will not be closed and reset properly. TODO: investigate why browser.close didn't help.
import { nextTestSetup } from 'e2e-utils'
import { deleteBrowserDynamicChunks } from './delete-dynamic-chunk'
describe('graceful-degrade-error - non bot', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// Delete client chunks to simulate chunk loading failure
beforeAll(() => {
deleteBrowserDynamicChunks(next)
})
it('should not degrade to graceful error when chunk loading fails in ssr for non-bot user agents', async () => {
const browser = await next.browser('/')
const logs = await browser.log()
const errors = logs
.filter((x) => x.source === 'error')
.map((x) => x.message)
.join('\n')
expect(errors).toMatch(/Failed to load resource./)
// Should not show the original content
const html = await browser.elementByCss('html')
const body = await browser.elementByCss('body')
expect(await html.getAttribute('class')).not.toBe('layout-cls')
expect(await body.getAttribute('class')).not.toBe('body-cls')
const bodyText = await body.text()
expect(bodyText).toMatch(
/Application error: a client-side exception has occurred while loading/
)
})
})
import { nextTestSetup } from 'e2e-utils'
import { deleteBrowserDynamicChunks } from './delete-dynamic-chunk'
describe('graceful-degrade-error', () => {
const { next } = nextTestSetup({
files: __dirname,
})
// Delete client chunks to simulate chunk loading failure
beforeAll(() => {
deleteBrowserDynamicChunks(next)
})
it('should degrade to graceful error when chunk loading fails in ssr for bot', async () => {
const browser = await next.browser('/', {
userAgent: 'Googlebot',
})
const logs = await browser.log()
const errors = logs
.filter((x) => x.source === 'error')
.map((x) => x.message)
.join('\n')
expect(errors).toMatch(/Failed to load resource./)
// Should show the original content
const originHtml = await browser.elementByCss('html')
const originBody = await browser.elementByCss('body')
expect(await originHtml.getAttribute('class')).toBe('layout-cls')
expect(await originBody.getAttribute('class')).toBe('body-cls')
// Do not contain the global error boundary text
const bodyText = await originBody.text()
expect(bodyText).not.toMatch(
/Application error: a client-side exception has occurred while loading/
)
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
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