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. * 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 BASE_DELAY_MS = 200
const MAX_JITTER_MS = 400 const MAX_JITTER_MS = 400
const MAX_RTT_MS = 500 const MAX_RTT_MS = 500
......
...@@ -31,6 +31,7 @@ import { ...@@ -31,6 +31,7 @@ import {
} from '../app-router-headers' } from '../app-router-headers'
import { isChunkOrNetworkError } from '../chunk-load-error/is-chunk-load-error' import { isChunkOrNetworkError } from '../chunk-load-error/is-chunk-load-error'
import { import {
MAX_RETRY_ATTEMPTS,
getRetryDelayMs, getRetryDelayMs,
sleep, sleep,
} from '../chunk-load-error/chunk-load-error-handler' } from '../chunk-load-error/chunk-load-error-handler'
...@@ -119,7 +120,6 @@ function doMpaNavigation(url: string): FetchServerResponseResult { ...@@ -119,7 +120,6 @@ function doMpaNavigation(url: string): FetchServerResponseResult {
} }
let isPageUnloading = false let isPageUnloading = false
const MAX_RSC_FETCH_RETRIES = 1
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
// Track when the page is unloading, e.g. due to reloading the page or // Track when the page is unloading, e.g. due to reloading the page or
...@@ -310,7 +310,7 @@ async function fetchServerResponseWithRetry( ...@@ -310,7 +310,7 @@ async function fetchServerResponseWithRetry(
err instanceof Error && err instanceof Error &&
isChunkOrNetworkError(err) && isChunkOrNetworkError(err) &&
!isPageUnloading && !isPageUnloading &&
retryCount < MAX_RSC_FETCH_RETRIES retryCount < MAX_RETRY_ATTEMPTS
) { ) {
// Retry once after a jittered delay for transient failures. // Retry once after a jittered delay for transient failures.
await sleep(getRetryDelayMs()) await sleep(getRetryDelayMs())
......
...@@ -4,6 +4,7 @@ import type { ComponentModule } from './types' ...@@ -4,6 +4,7 @@ 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 { isChunkLoadError } from '../../../client/components/chunk-load-error/is-chunk-load-error'
import { import {
MAX_RETRY_ATTEMPTS,
getRetryDelayMs, getRetryDelayMs,
sleep, sleep,
} from '../../../client/components/chunk-load-error/chunk-load-error-handler' } from '../../../client/components/chunk-load-error/chunk-load-error-handler'
...@@ -36,15 +37,24 @@ function convertModule<P>( ...@@ -36,15 +37,24 @@ function convertModule<P>(
*/ */
function createRetryableLoader<T>(loader: () => Promise<T>): () => Promise<T> { function createRetryableLoader<T>(loader: () => Promise<T>): () => Promise<T> {
return async () => { return async () => {
try { let retries = 0
return await loader()
} catch (err) { while (true) {
if (typeof window !== 'undefined' && isChunkLoadError(err)) { try {
await sleep(getRetryDelayMs()) return await loader()
return 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' ...@@ -26,6 +26,7 @@ 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 { isChunkLoadError } from '../../client/components/chunk-load-error/is-chunk-load-error'
import { import {
MAX_RETRY_ATTEMPTS,
getRetryDelayMs, getRetryDelayMs,
sleep, sleep,
} from '../../client/components/chunk-load-error/chunk-load-error-handler' } from '../../client/components/chunk-load-error/chunk-load-error-handler'
...@@ -39,14 +40,27 @@ const READY_INITIALIZERS: any[] = [] ...@@ -39,14 +40,27 @@ const READY_INITIALIZERS: any[] = []
let initialized = false let initialized = false
function retryChunkLoadErrorOnce(loader: any) { function retryChunkLoadErrorOnce(loader: any) {
return loader().catch(async (err: any) => { let retries = 0
if (typeof window !== 'undefined' && isChunkLoadError(err)) {
await sleep(getRetryDelayMs()) const run = async (): Promise<any> => {
return loader() 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) { function load(loader: any) {
......
...@@ -9,15 +9,13 @@ describe('chunk-load-failure', () => { ...@@ -9,15 +9,13 @@ describe('chunk-load-failure', () => {
files: __dirname, files: __dirname,
}) })
async function getNextDynamicChunk() { async function getChunkContainingText(marker: string) {
const chunksPath = path.join(next.testDir, '.next/static/') const chunksPath = path.join(next.testDir, '.next/static/')
const browserChunks = await recursiveReadDir(chunksPath, { const browserChunks = await recursiveReadDir(chunksPath, {
pathnameFilter: (f) => /\.js$/.test(f), pathnameFilter: (f) => /\.js$/.test(f),
}) })
let nextDynamicChunks = browserChunks.filter((f) => let nextDynamicChunks = browserChunks.filter((f) =>
fs fs.readFileSync(path.join(chunksPath, f), 'utf8').includes(marker)
.readFileSync(path.join(chunksPath, f), 'utf8')
.includes('this is a lazy loaded async component')
) )
expect(nextDynamicChunks).toHaveLength(1) expect(nextDynamicChunks).toHaveLength(1)
...@@ -25,7 +23,9 @@ describe('chunk-load-failure', () => { ...@@ -25,7 +23,9 @@ describe('chunk-load-failure', () => {
} }
it('should report async chunk load failures', async () => { 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 chunkRequestCount = 0
let pageError: Error | undefined let pageError: Error | undefined
...@@ -97,7 +97,9 @@ describe('chunk-load-failure', () => { ...@@ -97,7 +97,9 @@ describe('chunk-load-failure', () => {
}) })
it('should recover after a transient async chunk load failure', async () => { 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 chunkRequestCount = 0
let pageError: Error | undefined let pageError: Error | undefined
...@@ -133,8 +135,85 @@ describe('chunk-load-failure', () => { ...@@ -133,8 +135,85 @@ describe('chunk-load-failure', () => {
expect(pageError).toBeUndefined() 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 () => { 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 let resolve
try { 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