Commit 90232b56 authored by Jimmy Lai's avatar Jimmy Lai

Move chunk retries into runtime loaders

parent ad650741
......@@ -2,11 +2,14 @@
// https://github.com/webpack/webpack/blob/2738eebc7880835d88c727d364ad37f3ec557593/lib/RuntimeGlobals.js#L204
import './register-deployment-id-global'
import { patchWebpackChunkLoad } from './patch-webpack-chunk-load'
import { getAssetToken, getAssetTokenQuery } from '../shared/lib/deployment-id'
import { encodeURIPath } from '../shared/lib/encode-uri-path'
declare const __webpack_require__: any
patchWebpackChunkLoad()
// If we have a deployment ID, we need to append it to the webpack chunk names
// I am keeping the process check explicit so this can be statically optimized
if (getAssetToken()) {
......
......@@ -5,6 +5,30 @@ import {
sleep,
} from './chunk-load-error-handler'
const RETRY_EXHAUSTED = Symbol.for('next.chunk-load-error.retry-exhausted')
type RetryTaggedError = Error & {
[RETRY_EXHAUSTED]?: true
}
function hasExhaustedChunkLoadRetry(error: unknown): error is RetryTaggedError {
return !!(
error &&
typeof error === 'object' &&
(error as RetryTaggedError)[RETRY_EXHAUSTED]
)
}
function markExhaustedChunkLoadRetry(error: unknown) {
if (!error || typeof error !== 'object') {
return
}
try {
;(error as RetryTaggedError)[RETRY_EXHAUSTED] = true
} catch {}
}
export function retryChunkLoadError<T>(load: () => Promise<T>): Promise<T> {
let retries = 0
......@@ -15,6 +39,7 @@ export function retryChunkLoadError<T>(load: () => Promise<T>): Promise<T> {
if (
typeof window !== 'undefined' &&
isChunkLoadError(err) &&
!hasExhaustedChunkLoadRetry(err) &&
retries < MAX_RETRY_ATTEMPTS
) {
retries++
......@@ -22,6 +47,10 @@ export function retryChunkLoadError<T>(load: () => Promise<T>): Promise<T> {
return run()
}
if (isChunkLoadError(err)) {
markExhaustedChunkLoadRetry(err)
}
throw err
}
}
......
import { retryChunkLoadError } from './components/chunk-load-error/retry-chunk-load-error'
type ChunkLoad = ((...args: any[]) => Promise<any>) & {
[patched]?: true
}
declare const __webpack_require__: {
e?: ChunkLoad
[patched]?: true
}
declare let __webpack_chunk_load__: ChunkLoad | undefined
const patched = Symbol.for('next.webpack.chunk-load.retry.patched')
function markPatched(load: ChunkLoad): ChunkLoad {
load[patched] = true
return load
}
function wrapChunkLoad(load: ChunkLoad): ChunkLoad {
// Webpack can reject from either the low-level script loader or the higher-level
// ensureChunk Promise. `retryChunkLoadError()` tags exhausted errors so these
// wrappers can compose without multiplying retries.
return markPatched((...args: any[]) =>
retryChunkLoadError(() => load(...args))
)
}
export function patchWebpackChunkLoad() {
if (__webpack_require__[patched]) {
return
}
const originalChunkLoad =
typeof __webpack_chunk_load__ === 'function' ? __webpack_chunk_load__ : null
const originalEnsureChunk =
typeof __webpack_require__.e === 'function' ? __webpack_require__.e : null
if (originalChunkLoad && !originalChunkLoad[patched]) {
const wrappedChunkLoad = wrapChunkLoad(originalChunkLoad)
__webpack_chunk_load__ = wrappedChunkLoad
if (originalEnsureChunk === originalChunkLoad) {
__webpack_require__.e = wrappedChunkLoad
}
}
if (
originalEnsureChunk &&
originalEnsureChunk !== originalChunkLoad &&
!originalEnsureChunk[patched]
) {
__webpack_require__.e = wrapChunkLoad(originalEnsureChunk)
}
__webpack_require__[patched] = true
}
......@@ -2,6 +2,9 @@ declare const __webpack_require__: any
declare let __webpack_public_path__: string
import { getAssetToken, getAssetTokenQuery } from '../shared/lib/deployment-id'
import { patchWebpackChunkLoad } from './patch-webpack-chunk-load'
patchWebpackChunkLoad()
// If we have a deployment ID query string, we need to append it to the webpack chunk names
// I am keeping the process check explicit so this can be statically optimized
......
......@@ -81,34 +81,13 @@
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 = loadChunk(chunks[i]);
var thenable = __turbopack_load_by_url__(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
......
......@@ -72,30 +72,9 @@ 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 = loadChunk(chunks[i]);
var thenable = __turbopack_load_by_url__(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
......
......@@ -81,34 +81,13 @@
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 = loadChunk(chunks[i]);
var thenable = __turbopack_load_by_url__(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
......
......@@ -72,30 +72,9 @@ 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 = loadChunk(chunks[i]);
var thenable = __turbopack_load_by_url__(chunks[i]);
loadedChunks.has(thenable) || promises.push(thenable);
if (!instrumentedChunks.has(thenable)) {
var resolve = loadedChunks.add.bind(loadedChunks, thenable);
......
......@@ -81,7 +81,6 @@
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);
}
......@@ -126,9 +125,7 @@
}
function loadChunk(chunkId, filename) {
chunkMap.set(chunkId, filename);
return retryChunkLoadError(function () {
return __webpack_chunk_load__(chunkId);
});
return __webpack_chunk_load__(chunkId);
}
function getIteratorFn(maybeIterable) {
if (null === maybeIterable || "object" !== typeof maybeIterable)
......
......@@ -71,7 +71,6 @@ 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);
}
......@@ -82,9 +81,7 @@ function preloadModule(metadata) {
entry = chunkCache.get(chunkId);
void 0 === entry
? (chunkMap.set(chunkId, chunkFilename),
(chunkFilename = retryChunkLoadError(function () {
return __webpack_chunk_load__(chunkId);
})),
(chunkFilename = __webpack_chunk_load__(chunkId)),
promises.push(chunkFilename),
(entry = chunkCache.set.bind(chunkCache, chunkId, null)),
chunkFilename.then(entry, clearChunkCache.bind(null, chunkId)),
......
......@@ -81,7 +81,6 @@
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);
}
......@@ -126,9 +125,7 @@
}
function loadChunk(chunkId, filename) {
chunkMap.set(chunkId, filename);
return retryChunkLoadError(function () {
return __webpack_chunk_load__(chunkId);
});
return __webpack_chunk_load__(chunkId);
}
function getIteratorFn(maybeIterable) {
if (null === maybeIterable || "object" !== typeof maybeIterable)
......
......@@ -71,7 +71,6 @@ 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);
}
......@@ -82,9 +81,7 @@ function preloadModule(metadata) {
entry = chunkCache.get(chunkId);
void 0 === entry
? (chunkMap.set(chunkId, chunkFilename),
(chunkFilename = retryChunkLoadError(function () {
return __webpack_chunk_load__(chunkId);
})),
(chunkFilename = __webpack_chunk_load__(chunkId)),
promises.push(chunkFilename),
(entry = chunkCache.set.bind(chunkCache, chunkId, null)),
chunkFilename.then(entry, clearChunkCache.bind(null, chunkId)),
......
......@@ -2,7 +2,6 @@ import { Suspense, Fragment, lazy } from 'react'
import { BailoutToCSR } from './dynamic-bailout-to-csr'
import type { ComponentModule } from './types'
import { PreloadChunks } from './preload-chunks'
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
......@@ -26,10 +25,6 @@ function convertModule<P>(
}
}
function createRetryableLoader<T>(loader: () => Promise<T>): () => Promise<T> {
return () => retryChunkLoadError(loader)
}
const defaultOptions = {
loader: () => Promise.resolve(convertModule(() => null)),
loading: null,
......@@ -45,11 +40,7 @@ interface LoadableOptions {
function Loadable(options: LoadableOptions) {
const opts = { ...defaultOptions, ...options }
// Wrap loader with retry logic for chunk load errors (client-side only)
const retryableLoader = createRetryableLoader(() =>
opts.loader().then(convertModule)
)
const Lazy = lazy(retryableLoader)
const Lazy = lazy(() => opts.loader().then(convertModule))
const Loading = opts.loading
function LoadableComponent(props: any) {
......
......@@ -24,7 +24,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
import React from 'react'
import { LoadableContext } from './loadable-context.shared-runtime'
import { retryChunkLoadError } from '../../client/components/chunk-load-error/retry-chunk-load-error'
function resolve(obj: any) {
return obj && obj.default ? obj.default : obj
......@@ -34,12 +33,8 @@ const ALL_INITIALIZERS: any[] = []
const READY_INITIALIZERS: any[] = []
let initialized = false
function retryChunkLoadErrorOnce(loader: any) {
return retryChunkLoadError(loader)
}
function load(loader: any) {
let promise = retryChunkLoadErrorOnce(loader)
let promise = loader()
let state: any = {
loading: true,
......
......@@ -1635,81 +1635,23 @@ export async function copy_vendor_react(task_) {
)
}
const retryChunkLoadErrorRequire = `var retryChunkLoadError = require("next/dist/client/components/chunk-load-error/retry-chunk-load-error").retryChunkLoadError;`
const webpackChunkLoadRetryHelpers = `${retryChunkLoadErrorRequire}
function clearChunkCache(chunkId) {
const webpackChunkLoadCacheHelpers = `function clearChunkCache(chunkId) {
chunkCache.delete(chunkId);
}`
function patchReactServerDomWebpackBrowserClient(source) {
let newSource = insertAfterIgnoreReject(
const newSource = insertAfterIgnoreReject(
source,
webpackChunkLoadRetryHelpers,
'insert webpack browser chunk retry helpers'
webpackChunkLoadCacheHelpers,
'insert webpack browser chunk cache helpers'
)
newSource = replaceOnce(
return 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
......@@ -1810,8 +1752,8 @@ function loadChunk(chunkUrl) {
// eslint-disable-next-line require-yield
.run({ every: true }, function* (file) {
// 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.
// runtime bundle constraints. Browser clients stay upstream because
// runtime-level chunk retries now live below React.
if (
(file.base.startsWith('react-server-dom-turbopack-client') ||
......@@ -1837,12 +1779,6 @@ function loadChunk(chunkUrl) {
)
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)
}
......
......@@ -240,6 +240,74 @@ describe('chunk-load-failure', () => {
expect(pageError.message).toContain('/_next/static/' + appRouterChunk)
})
it('should recover after a later app-router navigation once a failed chunk is available again', async () => {
let appRouterChunk = await getChunkContainingText('this is other')
let chunkRequestCount = 0
let rscRequestCount = 0
let documentRequestCount = 0
let pageErrorCount = 0
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route(`**/${appRouterChunk}*`, async (route) => {
chunkRequestCount++
if (chunkRequestCount <= 2) {
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', () => {
pageErrorCount++
})
},
})
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/)
})
expect(chunkRequestCount).toBe(2)
expect(pageErrorCount).toBe(1)
await browser.back()
await retry(async () => {
const link = await browser.elementByCss('#to-other')
expect(await link.text()).toBe('to other')
})
await browser.elementByCss('#to-other').click()
await retry(
async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain('this is other')
},
10_000,
250
)
expect(chunkRequestCount).toBeGreaterThanOrEqual(3)
expect(rscRequestCount).toBe(2)
expect(documentRequestCount).toBe(0)
})
it('should report aborted chunks when navigating away', async () => {
let nextDynamicChunk = await getChunkContainingText(
'this is a lazy loaded async component'
......
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