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