Commit 6b4b73d0 authored by Jimmy Lai's avatar Jimmy Lai

test: expand chunk retry coverage and unify retry budget

parent 6adecd80
/**
* Shared retry timing utilities for chunk and RSC request retries.
*/
// Retry budget after the initial attempt.
export const MAX_RETRY_ATTEMPTS = 1
const BASE_DELAY_MS = 200
const MAX_JITTER_MS = 400
const MAX_RTT_MS = 500
......
......@@ -31,6 +31,7 @@ import {
} 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'
......@@ -119,7 +120,6 @@ function doMpaNavigation(url: string): FetchServerResponseResult {
}
let isPageUnloading = false
const MAX_RSC_FETCH_RETRIES = 1
if (typeof window !== 'undefined') {
// Track when the page is unloading, e.g. due to reloading the page or
......@@ -310,7 +310,7 @@ async function fetchServerResponseWithRetry(
err instanceof Error &&
isChunkOrNetworkError(err) &&
!isPageUnloading &&
retryCount < MAX_RSC_FETCH_RETRIES
retryCount < MAX_RETRY_ATTEMPTS
) {
// Retry once after a jittered delay for transient failures.
await sleep(getRetryDelayMs())
......
......@@ -4,6 +4,7 @@ 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'
......@@ -36,15 +37,24 @@ function convertModule<P>(
*/
function createRetryableLoader<T>(loader: () => Promise<T>): () => Promise<T> {
return async () => {
try {
return await loader()
} catch (err) {
if (typeof window !== 'undefined' && isChunkLoadError(err)) {
await sleep(getRetryDelayMs())
return 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
throw err
}
}
}
}
......
......@@ -26,6 +26,7 @@ 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'
......@@ -39,14 +40,27 @@ const READY_INITIALIZERS: any[] = []
let initialized = false
function retryChunkLoadErrorOnce(loader: any) {
return loader().catch(async (err: any) => {
if (typeof window !== 'undefined' && isChunkLoadError(err)) {
await sleep(getRetryDelayMs())
return loader()
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
}
}
throw err
})
return run()
}
function load(loader: any) {
......
......@@ -9,15 +9,13 @@ describe('chunk-load-failure', () => {
files: __dirname,
})
async function getNextDynamicChunk() {
async function getChunkContainingText(marker: string) {
const chunksPath = path.join(next.testDir, '.next/static/')
const browserChunks = await recursiveReadDir(chunksPath, {
pathnameFilter: (f) => /\.js$/.test(f),
})
let nextDynamicChunks = browserChunks.filter((f) =>
fs
.readFileSync(path.join(chunksPath, f), 'utf8')
.includes('this is a lazy loaded async component')
fs.readFileSync(path.join(chunksPath, f), 'utf8').includes(marker)
)
expect(nextDynamicChunks).toHaveLength(1)
......@@ -25,7 +23,9 @@ describe('chunk-load-failure', () => {
}
it('should report async chunk load failures', async () => {
let nextDynamicChunk = await getNextDynamicChunk()
let nextDynamicChunk = await getChunkContainingText(
'this is a lazy loaded async component'
)
let chunkRequestCount = 0
let pageError: Error | undefined
......@@ -97,7 +97,9 @@ describe('chunk-load-failure', () => {
})
it('should recover after a transient async chunk load failure', async () => {
let nextDynamicChunk = await getNextDynamicChunk()
let nextDynamicChunk = await getChunkContainingText(
'this is a lazy loaded async component'
)
let chunkRequestCount = 0
let pageError: Error | undefined
......@@ -133,8 +135,85 @@ describe('chunk-load-failure', () => {
expect(pageError).toBeUndefined()
})
it('should fallback to MPA navigation after a persistent RSC fetch failure', async () => {
let rscRequestCount = 0
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/other*', async (route) => {
if (route.request().url().includes('_rsc=')) {
rscRequestCount++
await route.abort('connectionreset')
return
}
await route.continue()
})
},
})
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')
},
10_000,
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)
})
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('/pages-dynamic', {
beforePageLoad(page) {
page.route(`**/${pagesDynamicChunk}*`, async (route) => {
chunkRequestCount++
if (chunkRequestCount === 1) {
await route.abort('connectionreset')
return
}
await route.continue()
})
page.on('pageerror', (error: Error) => {
pageError = error
})
},
})
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
)
// One initial request + one retry attempt.
expect(chunkRequestCount).toBe(2)
expect(pageError).toBeDefined()
expect(pageError.name).toBe('ChunkLoadError')
})
it('should report aborted chunks when navigating away', async () => {
let nextDynamicChunk = await getNextDynamicChunk()
let nextDynamicChunk = await getChunkContainingText(
'this is a lazy loaded async component'
)
let resolve
try {
......
export default function PagesAsync() {
return 'this is a pages-router lazy loaded async component'
}
import dynamic from 'next/dynamic'
import Link from 'next/link'
import { Suspense } from 'react'
const PagesAsync = dynamic(() => import('../components/pages-async'), {
ssr: false,
})
export default function PagesDynamic() {
return (
<>
<Link href="/pages-other" id="to-pages-other" prefetch={false}>
to pages other
</Link>
<Suspense fallback={<div>Loading...</div>}>
<PagesAsync />
</Suspense>
</>
)
}
export default function PagesOther() {
return <>this is pages other</>
}
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