Commit ad650741 authored by Jimmy Lai's avatar Jimmy Lai

Retry app-router client chunks via vendored React

parent 0124bf72
/**
* Shared retry timing utilities for chunk and RSC request retries.
* Shared retry timing utilities for chunk load retries.
*/
// Retry budget after the initial attempt.
export const MAX_RETRY_ATTEMPTS = 1
......
/**
* Utilities for detecting chunk load errors and network failures.
* Utilities for detecting chunk load errors.
*
* ChunkLoadError can come from:
* - Turbopack: error.name === 'ChunkLoadError'
* - Webpack: error.name === 'ChunkLoadError'
*
* We intentionally keep detection narrow to avoid false positives:
* - Server 4xx/5xx responses don't throw (they return Response objects)
* - We should NOT retry CORS errors, AbortErrors, or parsing failures
*/
/**
......@@ -18,27 +14,3 @@ export function isChunkLoadError(error: unknown): error is Error {
if (!error || typeof error !== 'object') return false
return (error as Error).name === 'ChunkLoadError'
}
/**
* Detects network-level request failures that are worth retrying.
*
* This intentionally avoids message matching because browser-specific error
* strings are brittle. For fetch-like APIs, network failures are typically a
* `TypeError` (or `NetworkError` in some environments).
*/
export function isNetworkError(error: unknown): error is Error {
if (!error || typeof error !== 'object') return false
const err = error as Error
// Never retry intentional aborts
if (err.name === 'AbortError') return false
return err.name === 'TypeError' || err.name === 'NetworkError'
}
/**
* Returns true if the error is a chunk load or network error worth retrying.
*/
export function isChunkOrNetworkError(error: unknown): boolean {
return isChunkLoadError(error) || isNetworkError(error)
}
import { isChunkLoadError } from './is-chunk-load-error'
import {
MAX_RETRY_ATTEMPTS,
getRetryDelayMs,
sleep,
} from './chunk-load-error-handler'
export function retryChunkLoadError<T>(load: () => Promise<T>): Promise<T> {
let retries = 0
const run = async (): Promise<T> => {
try {
return await load()
} catch (err) {
if (
typeof window !== 'undefined' &&
isChunkLoadError(err) &&
retries < MAX_RETRY_ATTEMPTS
) {
retries++
await sleep(getRetryDelayMs())
return run()
}
throw err
}
}
return run()
}
......@@ -29,12 +29,6 @@ import {
NEXT_HTML_REQUEST_ID_HEADER,
NEXT_REQUEST_ID_HEADER,
} from '../app-router-headers'
import { isChunkOrNetworkError } from '../chunk-load-error/is-chunk-load-error'
import {
MAX_RETRY_ATTEMPTS,
getRetryDelayMs,
sleep,
} from '../chunk-load-error/chunk-load-error-handler'
import { callServer } from '../../app-call-server'
import { findSourceMapURL } from '../../app-find-source-map-url'
import {
......@@ -143,14 +137,6 @@ if (typeof window !== 'undefined') {
export async function fetchServerResponse(
url: URL,
options: FetchServerResponseOptions
): Promise<FetchServerResponseResult> {
return fetchServerResponseWithRetry(url, options, 0)
}
async function fetchServerResponseWithRetry(
url: URL,
options: FetchServerResponseOptions,
retryCount: number
): Promise<FetchServerResponseResult> {
const { flightRouterState, nextUrl } = options
......@@ -306,17 +292,6 @@ async function fetchServerResponseWithRetry(
debugInfo: flightResponsePromise._debugInfo ?? null,
}
} catch (err) {
if (
err instanceof Error &&
isChunkOrNetworkError(err) &&
!isPageUnloading &&
retryCount < MAX_RETRY_ATTEMPTS
) {
// Retry once after a jittered delay for transient failures.
await sleep(getRetryDelayMs())
return fetchServerResponseWithRetry(originalUrl, options, retryCount + 1)
}
if (!isPageUnloading) {
console.error(
`Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,
......
......@@ -81,13 +81,34 @@
return promise;
}
function ignoreReject() {}
var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;
var retryingChunks = new Map();
function loadChunk(chunkUrl) {
var entry = retryingChunks.get(chunkUrl);
if (void 0 === entry) {
entry = retryChunkLoadError(function () {
return __turbopack_load_by_url__(chunkUrl);
}).then(
function (value) {
retryingChunks.delete(chunkUrl);
return value;
},
function (error) {
retryingChunks.delete(chunkUrl);
throw error;
}
);
retryingChunks.set(chunkUrl, entry);
}
return entry;
}
function preloadModule(metadata) {
for (
var chunks = metadata[1], promises = [], i = 0;
i < chunks.length;
i++
) {
var thenable = __turbopack_load_by_url__(chunks[i]);
var thenable = loadChunk(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
......
......@@ -72,9 +72,30 @@ function requireAsyncModule(id) {
var instrumentedChunks = new WeakSet(),
loadedChunks = new WeakSet();
function ignoreReject() {}
var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;
var retryingChunks = new Map();
function loadChunk(chunkUrl) {
var entry = retryingChunks.get(chunkUrl);
if (void 0 === entry) {
entry = retryChunkLoadError(function () {
return __turbopack_load_by_url__(chunkUrl);
}).then(
function (value) {
retryingChunks.delete(chunkUrl);
return value;
},
function (error) {
retryingChunks.delete(chunkUrl);
throw error;
}
);
retryingChunks.set(chunkUrl, entry);
}
return entry;
}
function preloadModule(metadata) {
for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; i++) {
var thenable = __turbopack_load_by_url__(chunks[i]);
var thenable = loadChunk(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
......
......@@ -81,13 +81,34 @@
return promise;
}
function ignoreReject() {}
var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;
var retryingChunks = new Map();
function loadChunk(chunkUrl) {
var entry = retryingChunks.get(chunkUrl);
if (void 0 === entry) {
entry = retryChunkLoadError(function () {
return __turbopack_load_by_url__(chunkUrl);
}).then(
function (value) {
retryingChunks.delete(chunkUrl);
return value;
},
function (error) {
retryingChunks.delete(chunkUrl);
throw error;
}
);
retryingChunks.set(chunkUrl, entry);
}
return entry;
}
function preloadModule(metadata) {
for (
var chunks = metadata[1], promises = [], i = 0;
i < chunks.length;
i++
) {
var thenable = __turbopack_load_by_url__(chunks[i]);
var thenable = loadChunk(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
......
......@@ -72,9 +72,30 @@ function requireAsyncModule(id) {
var instrumentedChunks = new WeakSet(),
loadedChunks = new WeakSet();
function ignoreReject() {}
var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;
var retryingChunks = new Map();
function loadChunk(chunkUrl) {
var entry = retryingChunks.get(chunkUrl);
if (void 0 === entry) {
entry = retryChunkLoadError(function () {
return __turbopack_load_by_url__(chunkUrl);
}).then(
function (value) {
retryingChunks.delete(chunkUrl);
return value;
},
function (error) {
retryingChunks.delete(chunkUrl);
throw error;
}
);
retryingChunks.set(chunkUrl, entry);
}
return entry;
}
function preloadModule(metadata) {
for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; i++) {
var thenable = __turbopack_load_by_url__(chunks[i]);
var thenable = loadChunk(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
......
......@@ -81,6 +81,10 @@
return promise;
}
function ignoreReject() {}
var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;
function clearChunkCache(chunkId) {
chunkCache.delete(chunkId);
}
function preloadModule(metadata) {
for (
var chunks = metadata[1], promises = [], i = 0;
......@@ -94,7 +98,7 @@
? ((chunkFilename = loadChunk(chunkId, chunkFilename)),
promises.push(chunkFilename),
(entry = chunkCache.set.bind(chunkCache, chunkId, null)),
chunkFilename.then(entry, ignoreReject),
chunkFilename.then(entry, clearChunkCache.bind(null, chunkId)),
chunkCache.set(chunkId, chunkFilename))
: null !== entry && promises.push(entry);
}
......@@ -122,7 +126,9 @@
}
function loadChunk(chunkId, filename) {
chunkMap.set(chunkId, filename);
return __webpack_chunk_load__(chunkId);
return retryChunkLoadError(function () {
return __webpack_chunk_load__(chunkId);
});
}
function getIteratorFn(maybeIterable) {
if (null === maybeIterable || "object" !== typeof maybeIterable)
......
......@@ -71,6 +71,10 @@ function requireAsyncModule(id) {
return promise;
}
function ignoreReject() {}
var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;
function clearChunkCache(chunkId) {
chunkCache.delete(chunkId);
}
function preloadModule(metadata) {
for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; ) {
var chunkId = chunks[i++],
......@@ -78,10 +82,12 @@ function preloadModule(metadata) {
entry = chunkCache.get(chunkId);
void 0 === entry
? (chunkMap.set(chunkId, chunkFilename),
(chunkFilename = __webpack_chunk_load__(chunkId)),
(chunkFilename = retryChunkLoadError(function () {
return __webpack_chunk_load__(chunkId);
})),
promises.push(chunkFilename),
(entry = chunkCache.set.bind(chunkCache, chunkId, null)),
chunkFilename.then(entry, ignoreReject),
chunkFilename.then(entry, clearChunkCache.bind(null, chunkId)),
chunkCache.set(chunkId, chunkFilename))
: null !== entry && promises.push(entry);
}
......
......@@ -81,6 +81,10 @@
return promise;
}
function ignoreReject() {}
var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;
function clearChunkCache(chunkId) {
chunkCache.delete(chunkId);
}
function preloadModule(metadata) {
for (
var chunks = metadata[1], promises = [], i = 0;
......@@ -94,7 +98,7 @@
? ((chunkFilename = loadChunk(chunkId, chunkFilename)),
promises.push(chunkFilename),
(entry = chunkCache.set.bind(chunkCache, chunkId, null)),
chunkFilename.then(entry, ignoreReject),
chunkFilename.then(entry, clearChunkCache.bind(null, chunkId)),
chunkCache.set(chunkId, chunkFilename))
: null !== entry && promises.push(entry);
}
......@@ -122,7 +126,9 @@
}
function loadChunk(chunkId, filename) {
chunkMap.set(chunkId, filename);
return __webpack_chunk_load__(chunkId);
return retryChunkLoadError(function () {
return __webpack_chunk_load__(chunkId);
});
}
function getIteratorFn(maybeIterable) {
if (null === maybeIterable || "object" !== typeof maybeIterable)
......
......@@ -71,6 +71,10 @@ function requireAsyncModule(id) {
return promise;
}
function ignoreReject() {}
var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;
function clearChunkCache(chunkId) {
chunkCache.delete(chunkId);
}
function preloadModule(metadata) {
for (var chunks = metadata[1], promises = [], i = 0; i < chunks.length; ) {
var chunkId = chunks[i++],
......@@ -78,10 +82,12 @@ function preloadModule(metadata) {
entry = chunkCache.get(chunkId);
void 0 === entry
? (chunkMap.set(chunkId, chunkFilename),
(chunkFilename = __webpack_chunk_load__(chunkId)),
(chunkFilename = retryChunkLoadError(function () {
return __webpack_chunk_load__(chunkId);
})),
promises.push(chunkFilename),
(entry = chunkCache.set.bind(chunkCache, chunkId, null)),
chunkFilename.then(entry, ignoreReject),
chunkFilename.then(entry, clearChunkCache.bind(null, chunkId)),
chunkCache.set(chunkId, chunkFilename))
: null !== entry && promises.push(entry);
}
......
......@@ -2,12 +2,7 @@ import { Suspense, Fragment, lazy } from 'react'
import { BailoutToCSR } from './dynamic-bailout-to-csr'
import type { ComponentModule } from './types'
import { PreloadChunks } from './preload-chunks'
import { isChunkLoadError } from '../../../client/components/chunk-load-error/is-chunk-load-error'
import {
MAX_RETRY_ATTEMPTS,
getRetryDelayMs,
sleep,
} from '../../../client/components/chunk-load-error/chunk-load-error-handler'
import { retryChunkLoadError } from '../../../client/components/chunk-load-error/retry-chunk-load-error'
// Normalize loader to return the module as form { default: Component } for `React.lazy`.
// Also for backward compatible since next/dynamic allows to resolve a component directly with loader
......@@ -31,32 +26,8 @@ function convertModule<P>(
}
}
/**
* Creates a loader function with automatic retry for chunk load errors.
* On first failure, retries once after a delay.
*/
function createRetryableLoader<T>(loader: () => Promise<T>): () => Promise<T> {
return async () => {
let retries = 0
while (true) {
try {
return await loader()
} catch (err) {
if (
typeof window !== 'undefined' &&
isChunkLoadError(err) &&
retries < MAX_RETRY_ATTEMPTS
) {
retries++
await sleep(getRetryDelayMs())
continue
}
throw err
}
}
}
return () => retryChunkLoadError(loader)
}
const defaultOptions = {
......
......@@ -24,12 +24,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
import React from 'react'
import { LoadableContext } from './loadable-context.shared-runtime'
import { isChunkLoadError } from '../../client/components/chunk-load-error/is-chunk-load-error'
import {
MAX_RETRY_ATTEMPTS,
getRetryDelayMs,
sleep,
} from '../../client/components/chunk-load-error/chunk-load-error-handler'
import { retryChunkLoadError } from '../../client/components/chunk-load-error/retry-chunk-load-error'
function resolve(obj: any) {
return obj && obj.default ? obj.default : obj
......@@ -40,27 +35,7 @@ const READY_INITIALIZERS: any[] = []
let initialized = false
function retryChunkLoadErrorOnce(loader: any) {
let retries = 0
const run = async (): Promise<any> => {
try {
return await loader()
} catch (err) {
if (
typeof window !== 'undefined' &&
isChunkLoadError(err) &&
retries < MAX_RETRY_ATTEMPTS
) {
retries++
await sleep(getRetryDelayMs())
return run()
}
throw err
}
}
return run()
return retryChunkLoadError(loader)
}
function load(loader: any) {
......
......@@ -1611,6 +1611,107 @@ export async function copy_vendor_react(task_) {
return statement.expression
}
function replaceOnce(source, searchValue, replaceValue, context) {
const replaced = source.replace(searchValue, replaceValue)
if (replaced === source) {
throw new Error(`Failed to patch vendored React file: ${context}`)
}
return replaced
}
function indentBlock(source, indent) {
return source
.split('\n')
.map((line) => (line.length > 0 ? indent + line : line))
.join('\n')
}
function insertAfterIgnoreReject(source, block, context) {
return replaceOnce(
source,
/(^(\s*)function ignoreReject\(\) \{\}\n)/m,
(match, line, indent) => line + indentBlock(block, indent) + '\n',
context
)
}
const retryChunkLoadErrorRequire = `var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;`
const webpackChunkLoadRetryHelpers = `${retryChunkLoadErrorRequire}
function clearChunkCache(chunkId) {
chunkCache.delete(chunkId);
}`
function patchReactServerDomWebpackBrowserClient(source) {
let newSource = insertAfterIgnoreReject(
source,
webpackChunkLoadRetryHelpers,
'insert webpack browser chunk retry helpers'
)
newSource = replaceOnce(
newSource,
'chunkFilename.then(entry, ignoreReject),',
'chunkFilename.then(entry, clearChunkCache.bind(null, chunkId)),',
'clear failed webpack browser chunk cache'
)
if (newSource.includes('function loadChunk(chunkId, filename)')) {
return replaceOnce(
newSource,
/^(\s*)return __webpack_chunk_load__\(chunkId\);$/m,
(match, indent) =>
`${indent}return retryChunkLoadError(function () {\n${indent} return __webpack_chunk_load__(chunkId);\n${indent}});`,
'wrap webpack browser chunk loader'
)
}
return replaceOnce(
newSource,
/^(\s*)\(chunkFilename = __webpack_chunk_load__\(chunkId\)\),$/m,
(match, indent) =>
`${indent}(chunkFilename = retryChunkLoadError(function () {\n${indent} return __webpack_chunk_load__(chunkId);\n${indent}})),`,
'wrap webpack browser chunk loader'
)
}
const turbopackChunkLoadRetryHelpers = `${retryChunkLoadErrorRequire}
var retryingChunks = new Map();
function loadChunk(chunkUrl) {
var entry = retryingChunks.get(chunkUrl);
if (void 0 === entry) {
entry = retryChunkLoadError(function () {
return __turbopack_load_by_url__(chunkUrl);
}).then(
function (value) {
retryingChunks.delete(chunkUrl);
return value;
},
function (error) {
retryingChunks.delete(chunkUrl);
throw error;
}
);
retryingChunks.set(chunkUrl, entry);
}
return entry;
}`
function patchReactServerDomTurbopackBrowserClient(source) {
let newSource = insertAfterIgnoreReject(
source,
turbopackChunkLoadRetryHelpers,
'insert turbopack browser chunk retry helpers'
)
return replaceOnce(
newSource,
'__turbopack_load_by_url__(chunks[i])',
'loadChunk(chunks[i])',
'wrap turbopack browser chunk loader'
)
}
// Remove unused files
const reactDomCompiledDir = join(
__dirname,
......@@ -1650,11 +1751,9 @@ export async function copy_vendor_react(task_) {
)
// eslint-disable-next-line require-yield
.run({ every: true }, function* (file) {
// We replace the module/chunk loading code with our own implementation in Next.js.
// NOTE: We only replace module/chunk loading for server builds because the server
// bundles have unique constraints like a runtime bundle. For browser builds this
// package will be bundled alongside user code and we don't need to introduce the extra
// indirection
// Server builds replace the module/chunk loading indirection for Next's
// runtime bundle constraints. Browser clients stay upstream except for
// a one-shot ChunkLoadError retry around client reference chunk loads.
if (
(file.base.startsWith('react-server-dom-webpack-client') &&
!file.base.startsWith('react-server-dom-webpack-client.browser')) ||
......@@ -1675,6 +1774,12 @@ export async function copy_vendor_react(task_) {
)
file.data = recast.print(ast).code
} else if (
file.base.startsWith('react-server-dom-webpack-client.browser')
) {
file.data = patchReactServerDomWebpackBrowserClient(
file.data.toString()
)
} else if (file.base === 'package.json') {
file.data = overridePackageName(file.data)
}
......@@ -1704,11 +1809,9 @@ export async function copy_vendor_react(task_) {
)
// eslint-disable-next-line require-yield
.run({ every: true }, function* (file) {
// We replace the module loading code with our own implementation in Next.js.
// NOTE: We only replace module loading for server builds because the server
// bundles have unique constraints like a runtime bundle. For browser builds this
// package will be bundled alongside user code and we don't need to introduce the extra
// indirection
// Server builds replace the module loading indirection for Next's
// runtime bundle constraints. Browser clients stay upstream except for
// a one-shot ChunkLoadError retry around client reference chunk loads.
if (
(file.base.startsWith('react-server-dom-turbopack-client') ||
......@@ -1734,6 +1837,12 @@ export async function copy_vendor_react(task_) {
)
file.data = recast.print(ast).code
} else if (
file.base.startsWith('react-server-dom-turbopack-client.browser')
) {
file.data = patchReactServerDomTurbopackBrowserClient(
file.data.toString()
)
} else if (file.base === 'package.json') {
file.data = overridePackageName(file.data)
}
......
......@@ -59,51 +59,55 @@ describe('chunk-load-failure', () => {
)
})
it('should retry failed RSC fetches without falling back to MPA navigation', async () => {
let rscRequestCount = 0
it('should recover after a transient async chunk load failure', async () => {
let nextDynamicChunk = await getChunkContainingText(
'this is a lazy loaded async component'
)
let chunkRequestCount = 0
let pageError: Error | undefined
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/other*', async (route) => {
if (route.request().url().includes('_rsc=')) {
rscRequestCount++
if (rscRequestCount === 1) {
await route.abort('connectionreset')
return
}
page.route(`**/${nextDynamicChunk}*`, async (route) => {
chunkRequestCount++
if (chunkRequestCount === 1) {
await route.abort('connectionreset')
return
}
await route.continue()
})
page.on('pageerror', (error: Error) => {
pageError = error
})
},
})
await browser.eval('window.__TEST_NO_RELOAD = true')
await browser.elementByCss('#to-other').click()
await retry(
async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain('this is other')
expect(await body.text()).toContain(
'this is a lazy loaded async component'
)
},
10_000,
250
)
expect(await browser.eval('window.__TEST_NO_RELOAD')).toBe(true)
// One initial request + one retry attempt.
expect(rscRequestCount).toBe(2)
expect(chunkRequestCount).toBe(2)
expect(pageError).toBeUndefined()
})
it('should recover after a transient async chunk load failure', async () => {
let nextDynamicChunk = await getChunkContainingText(
'this is a lazy loaded async component'
it('should recover after a transient pages-router chunk load failure', async () => {
let pagesDynamicChunk = await getChunkContainingText(
'this is a pages-router lazy loaded async component'
)
let chunkRequestCount = 0
let pageError: Error | undefined
const browser = await next.browser('/dynamic', {
const browser = await next.browser('/pages-dynamic', {
beforePageLoad(page) {
page.route(`**/${nextDynamicChunk}*`, async (route) => {
page.route(`**/${pagesDynamicChunk}*`, async (route) => {
chunkRequestCount++
if (chunkRequestCount === 1) {
await route.abort('connectionreset')
......@@ -121,7 +125,7 @@ describe('chunk-load-failure', () => {
async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain(
'this is a lazy loaded async component'
'this is a pages-router lazy loaded async component'
)
},
10_000,
......@@ -130,31 +134,53 @@ describe('chunk-load-failure', () => {
// One initial request + one retry attempt.
expect(chunkRequestCount).toBe(2)
expect(pageError).toBeUndefined()
// Browser/runtime paths differ here: some surface the first transient failure
// as a page error before retry succeeds, others recover without one.
if (pageError) {
expect(pageError.name).toBe('ChunkLoadError')
}
})
it('should fallback to MPA navigation after a persistent RSC fetch failure', async () => {
it('should recover after a transient app-router client chunk load failure', async () => {
let appRouterChunk = await getChunkContainingText('this is other')
const expectedChunkRequestCount = process.env.IS_TURBOPACK_TEST ? 3 : 2
let chunkRequestCount = 0
let rscRequestCount = 0
let documentRequestCount = 0
let pageError: Error | undefined
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/other*', async (route) => {
if (route.request().url().includes('_rsc=')) {
rscRequestCount++
page.route(`**/${appRouterChunk}*`, async (route) => {
chunkRequestCount++
if (chunkRequestCount === 1) {
await route.abort('connectionreset')
return
}
await route.continue()
})
page.on('request', (request) => {
const url = new URL(request.url())
if (
request.resourceType() === 'document' &&
url.pathname === '/other'
) {
documentRequestCount++
}
if (url.pathname === '/other' && url.searchParams.has('_rsc')) {
rscRequestCount++
}
})
page.on('pageerror', (error: Error) => {
pageError = error
})
},
})
await browser.eval('window.__TEST_NO_RELOAD = true')
await browser.elementByCss('#to-other').click()
await retry(
async () => {
expect(await browser.eval('window.location.pathname')).toBe('/other')
const body = await browser.elementByCss('body')
expect(await body.text()).toContain('this is other')
},
......@@ -162,28 +188,36 @@ describe('chunk-load-failure', () => {
250
)
// MPA fallback reloads the page context.
expect(await browser.eval('window.__TEST_NO_RELOAD')).toBeUndefined()
// One initial request + one retry attempt.
expect(rscRequestCount).toBe(2)
expect(chunkRequestCount).toBe(expectedChunkRequestCount)
expect(rscRequestCount).toBe(1)
expect(documentRequestCount).toBe(0)
expect(pageError).toBeUndefined()
})
it('should recover after a transient pages-router chunk load failure', async () => {
let pagesDynamicChunk = await getChunkContainingText(
'this is a pages-router lazy loaded async component'
)
it('should surface app-router client chunk failures after one retry', async () => {
let appRouterChunk = await getChunkContainingText('this is other')
let chunkRequestCount = 0
let rscRequestCount = 0
let documentRequestCount = 0
let pageError: Error | undefined
const browser = await next.browser('/pages-dynamic', {
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route(`**/${pagesDynamicChunk}*`, async (route) => {
page.route(`**/${appRouterChunk}*`, async (route) => {
chunkRequestCount++
if (chunkRequestCount === 1) {
await route.abort('connectionreset')
return
await route.abort('connectionreset')
})
page.on('request', (request) => {
const url = new URL(request.url())
if (
request.resourceType() === 'document' &&
url.pathname === '/other'
) {
documentRequestCount++
}
if (url.pathname === '/other' && url.searchParams.has('_rsc')) {
rscRequestCount++
}
await route.continue()
})
page.on('pageerror', (error: Error) => {
pageError = error
......@@ -191,24 +225,19 @@ describe('chunk-load-failure', () => {
},
})
await retry(
async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain(
'this is a pages-router lazy loaded async component'
)
},
10_000,
250
)
await browser.elementByCss('#to-other').click()
await retry(async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toMatch(/This page couldn\u2019t load/)
})
// One initial request + one retry attempt.
expect(chunkRequestCount).toBe(2)
// Browser/runtime paths differ here: some surface the first transient failure
// as a page error before retry succeeds, others recover without one.
if (pageError) {
expect(pageError.name).toBe('ChunkLoadError')
}
expect(rscRequestCount).toBe(1)
expect(documentRequestCount).toBe(0)
expect(pageError).toBeDefined()
expect(pageError.name).toBe('ChunkLoadError')
expect(pageError.message).toContain('/_next/static/' + appRouterChunk)
})
it('should report aborted chunks when navigating away', async () => {
......
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