Unverified Commit 3cb82f9c authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

test: unflake prefetch-fallback-static in deploy (#99366)

the ISR fallback tests were written in a way that only worked if the
first retry yielded a concrete prerender. this is enough in `next
start`, but in deploy, the ISR fallback retry does not always succeed in
one attempt. this PR adjusts the `act()` assertions to support multiple
retry attempts. this is not easy to express using usual `act()`
patterns, so we try the assertion, and retry it if it threw an error
that indicates that an expected response didn't show up (other errors
are rethrown)
parent f08c4536
import { Suspense } from 'react'
import { DebugLinkAccordion } from '../components/link-accordion'
import { io } from 'next/cache'
export default function Page() {
type SearchParams = { unique?: string }
export default async function Page({
searchParams,
}: {
searchParams: Promise<SearchParams>
}) {
return (
<Suspense fallback={<p>Loading...</p>}>
<Inner searchParams={searchParams} />
</Suspense>
)
}
async function Inner({
searchParams,
}: {
searchParams: Promise<SearchParams>
}) {
await io()
const unique =
(await searchParams).unique ?? (await io().then(() => Date.now()))
// NOTE: all "not-prerendered" slugs should be suffixed with the unique value
// (which is different for each test) to guarantee that two tests don't
// accidentally use the same slug.
const slugWithUnique = (slug: string) => `${slug}_u${unique}`
const linkForSlug = (slug: string) => `/static-for-some-params/${slug}`
return (
<main>
<div>
Current unique seed: {unique} (
<a href={`/unique=${unique}`}>Permalink</a>)
</div>
<h2>Prerendered, did not use cookies</h2>
<ul>
<li>
......@@ -34,21 +68,22 @@ export default function Page() {
<ul>
<li>
<DebugLinkAccordion
href={linkForSlug('not-prerendered_no-cookies_prefetch-auto')}
href={linkForSlug(slugWithUnique('not-prerendered_no-cookies'))}
prefetch="auto"
/>
</li>
<li>
<DebugLinkAccordion
href={linkForSlug('not-prerendered_no-cookies_prefetch-true')}
href={linkForSlug(slugWithUnique('not-prerendered_no-cookies'))}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={
linkForSlug('not-prerendered_no-cookies_ensure-static-shell') +
'/ensure-static/shell'
linkForSlug(
slugWithUnique('not-prerendered_no-cookies_es-shell')
) + '/ensure-static/shell'
}
prefetch={true}
/>
......@@ -56,8 +91,9 @@ export default function Page() {
<li>
<DebugLinkAccordion
href={
linkForSlug('not-prerendered_no-cookies_ensure-static-prefetch') +
'/ensure-static/prefetch'
linkForSlug(
slugWithUnique('not-prerendered_no-cookies_es-prefetch')
) + '/ensure-static/prefetch'
}
prefetch={true}
/>
......@@ -65,33 +101,42 @@ export default function Page() {
</ul>
<h2>Not prerendered, did use cookies</h2>
<h3>Without ensureStatic</h3>
<ul>
<li>
<DebugLinkAccordion
href={linkForSlug('not-prerendered_yes-cookies_prefetch-auto')}
href={linkForSlug(slugWithUnique('not-prerendered_yes-cookies'))}
prefetch="auto"
/>
</li>
<li>
<DebugLinkAccordion
href={linkForSlug('not-prerendered_yes-cookies_prefetch-true')}
href={linkForSlug(slugWithUnique('not-prerendered_yes-cookies'))}
prefetch={true}
/>
</li>
</ul>
<h3>with ensureStatic = "shell"</h3>
<ul>
<li>
<DebugLinkAccordion
href={
linkForSlug('not-prerendered_yes-cookies_ensure-static-shell') +
'/ensure-static/shell'
linkForSlug(
slugWithUnique('not-prerendered_yes-cookies_es-shell')
) + '/ensure-static/shell'
}
prefetch={true}
/>
</li>
</ul>
<h3>with ensureStatic = "prefetch"</h3>
<ul>
<li>
<DebugLinkAccordion
href={
linkForSlug(
'not-prerendered_yes-cookies_ensure-static-prefetch'
slugWithUnique(`not-prerendered_yes-cookies_es-prefetch`)
) + '/ensure-static/prefetch'
}
prefetch={true}
......
'use client'
import { useState } from 'react'
import { LinkAccordion } from './link-accordion'
export function DynamicLinkAccordion({
hrefPattern,
placeholder,
initialValue,
}: {
hrefPattern: string
placeholder: string
initialValue: string
}) {
const [value, setValue] = useState(initialValue)
const href = hrefPattern.replace(placeholder, value)
return (
<div
data-dynamic-link-accordion={hrefPattern}
style={{ border: '1px solid lightgrey', padding: '1em' }}
>
<div>
<span>
Dynamic link generator{' '}
<label>
Value
<input type="text" onChange={(e) => setValue(e.target.value)} />
</label>
</span>
<div>
<code>{hrefPattern}</code>
</div>
</div>
<div>
<LinkAccordion key={href} href={href} prefetch="auto">
{href} (prefetch="auto")
</LinkAccordion>
</div>
<div>
<LinkAccordion key={href} href={href} prefetch={true}>
{href} {`(prefetch={true})`}
</LinkAccordion>
</div>
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
import { StaticAttemptHints } from 'next/src/shared/lib/app-router-types'
import { createRouterAct } from 'router-act'
import { createRouterAct, waitForSuccessfulISRFallbackRetry } from 'router-act'
import type * as Playwright from 'playwright'
import {
HintsManifest,
......@@ -45,7 +45,7 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
expect('\n' + extractPrerenderedRouteInfo(next.cliOutput) + '\n')
.toMatchInlineSnapshot(`
"
┌ ○ /
┌ ◐ /
├ ○ /_not-found
├ /static-for-some-params/[slug]
│ ├ ◐ /static-for-some-params/[slug]
......@@ -115,9 +115,6 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
'This page only accesses runtime data for some param values.'
describe('when the param was not prerendered and an ISR fallback was served', () => {
/** The router waits 2s before retrying ISR fallbacks. */
const ISR_RETRY_DELAY = 2000 + 500
const usedSlugs = new Set<string>()
/**
* Used to prevent accidental slug re-use across tests.
......@@ -136,10 +133,19 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
return slug
}
// To ensure that the pages that haven't been prerendered yet, we append
// a unique cache-buster value to all slugs (passed to the index page via a search param)
let unique: string = Date.now() + ''
beforeEach(() => {
unique = Date.now() + ''
})
const indexPageWithUnique = () => `/?unique=${unique}`
const slugWithUnique = (slug: string) => `${slug}_u${unique}`
describe('when the prefetch did not use runtime data during the prerender', () => {
it('prefetch="auto": retries the static request, and does not use a runtime prefetch', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
const browser = await next.browser(indexPageWithUnique(), {
beforePageLoad(p: Playwright.Page) {
page = p
},
......@@ -147,59 +153,47 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
const act = createRouterAct(page, { includeAppShellRequests: true })
// The route was not prerendered during build.
// It does not use runtime data based on the slug.
const slug = trackUsedSlug('not-prerendered_no-cookies_prefetch-auto')
const slug = trackUsedSlug(slugWithUnique('not-prerendered_no-cookies'))
const href = `/static-for-some-params/${slug}`
const prefetch = 'auto'
await act(async () => {
await act(
async () => {
// Reveal a prefetch-auto link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
// After this act()'s callback, the initial request is resolved.
// It yielded an ISR fallback, so the router should retry it.
// But the retry is delayed, so initially nothing happens.
'no-requests'
)
// Wait for the router to do a retry.
await new Promise((resolve) => setTimeout(resolve, ISR_RETRY_DELAY))
}, [
// The retried request yields a concrete prerender with params.
{
includes: `Slug: ${slug}`,
kind: 'static',
},
// NO Runtime prefetch to get the content (not requested by link)
// or runtime requests of any kind
{
includes: '',
kind: 'runtime',
block: 'reject',
await act(
async () => {
// Reveal a prefetch-auto link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
])
// After this act()'s callback, the initial request is resolved.
// It yielded an ISR fallback, so the router should retry it.
// But the retry is delayed, so initially nothing happens.
'no-requests'
)
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
})
})
it('prefetch={true}: waits for the ISR retry instead of using a runtime prefetch', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
const browser = await next.browser(indexPageWithUnique(), {
beforePageLoad(p: Playwright.Page) {
page = p
},
......@@ -207,64 +201,51 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
const act = createRouterAct(page, { includeAppShellRequests: true })
// The route was not prerendered during build.
// It does not use runtime data based on the slug.
const slug = trackUsedSlug('not-prerendered_no-cookies_prefetch-true')
const slug = trackUsedSlug(slugWithUnique('not-prerendered_no-cookies'))
const href = `/static-for-some-params/${slug}`
const prefetch = true
await act(async () => {
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
// Wait for the router to do a retry.
await new Promise((resolve) => setTimeout(resolve, ISR_RETRY_DELAY))
}, [
// The retried request yields a concrete prerender with params.
{
includes: `Slug: ${slug}`,
kind: 'static',
},
// The concrete page is cache complete, so no runtime prefetch.
{
includes: '',
kind: 'runtime',
block: 'reject',
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
])
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
})
})
describe('with ensureStatic', () => {
describe('ensureStatic = "shell"', () => {
// FIXME: Flaky test
// @force-gate !deploy
it('prefetch={true}: waits for the ISR retry instead of using a runtime prefetch', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
const browser = await next.browser(indexPageWithUnique(), {
beforePageLoad(p: Playwright.Page) {
page = p
},
......@@ -278,67 +259,52 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
// The `ensureStatic` config should not change the behavior from the default, because
// it affects the shell, not the prefetch.
const slug = trackUsedSlug(
'not-prerendered_no-cookies_ensure-static-shell'
slugWithUnique('not-prerendered_no-cookies_es-shell')
)
const href = `/static-for-some-params/${slug}/ensure-static/shell`
const prefetch = true
await act(async () => {
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
// Wait for the router to do a retry.
await new Promise((resolve) =>
setTimeout(resolve, ISR_RETRY_DELAY)
)
}, [
// The retried request yields a concrete prerender with params.
{
includes: `Slug: ${slug}`,
kind: 'static',
},
// The concrete page is cache complete, so no runtime prefetch.
{
includes: '',
kind: 'runtime',
block: 'reject',
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
])
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
})
})
})
describe('ensureStatic = "prefetch"', () => {
// FIXME: Flaky test
// @force-gate !deploy
it('prefetch={true}: does not use a runtime prefetch as a replacement for not-yet-available ISR content', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
const browser = await next.browser(indexPageWithUnique(), {
beforePageLoad(p: Playwright.Page) {
page = p
},
......@@ -352,13 +318,13 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
// The `ensureStatic` config should change the behavior from the default, because it
// disallows using runtime prefetches altogether.
const slug = trackUsedSlug(
'not-prerendered_no-cookies_ensure-static-prefetch'
slugWithUnique('not-prerendered_no-cookies_es-prefetch')
)
const href = `/static-for-some-params/${slug}/ensure-static/prefetch`
const prefetch = true
await act(async () => {
await act(async () => {
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
......@@ -379,34 +345,18 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
},
]
)
}, [
// After this act()'s callback, the blocked static request is resolved.
// The router sees that it's an ISR fallback and kicks off the ISR retry loop.
// Unlike the default behavior, it should NOT use a runtime request for the
// missing content, because the route has `ensureStatic = "prefetch"`, so
// runtime prefetches are not allowed.
{
includes: '',
kind: 'runtime',
block: 'reject',
},
])
// Wait for the router to do a retry.
await new Promise((resolve) =>
setTimeout(resolve, ISR_RETRY_DELAY)
)
}, [
// The retried request yields a concrete prerender with params.
{
includes: `Slug: ${slug}`,
kind: 'static',
},
{
includes: '',
kind: 'runtime',
block: 'reject',
},
])
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
})
})
})
})
......@@ -417,11 +367,9 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
// above, because it can't know the slug. We only find out that the page
// needs runtime data once the retry gets the concrete prerender.
// FIXME: Flaky test
// @force-gate !deploy
it('prefetch="auto": does not use a runtime prefetch', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
const browser = await next.browser(indexPageWithUnique(), {
beforePageLoad(p: Playwright.Page) {
page = p
},
......@@ -430,64 +378,50 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
// The route was not prerendered during build.
// It used runtime data based on the slug.
const slug = trackUsedSlug('not-prerendered_yes-cookies_prefetch-auto')
const slug = trackUsedSlug(
slugWithUnique('not-prerendered_yes-cookies')
)
const href = `/static-for-some-params/${slug}`
const prefetch = 'auto'
await act(async () => {
await act(
async () => {
// Reveal a prefetch-auto link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
// After this act()'s callback, the initial request is resolved.
// It yielded an ISR fallback, so the router should retry it.
// But the retry is delayed, so initially nothing happens.
'no-requests'
)
// Wait for the router to do a retry.
await new Promise((resolve) => setTimeout(resolve, ISR_RETRY_DELAY))
}, [
// The retried request yields a concrete prerender with params.
{
includes: `Slug: ${slug}`,
kind: 'static',
await act(
async () => {
// Reveal a prefetch-auto link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
// After this act()'s callback, the initial request is resolved.
// It yielded an ISR fallback, so the router should retry it.
// But the retry is delayed, so initially nothing happens.
'no-requests'
)
// NO Runtime prefetch to get the content (not requested by link)
// or runtime requests of any kind
{
includes: '',
kind: 'runtime',
block: 'reject',
},
])
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
})
})
// FIXME: Flaky test
// @force-gate !deploy
it('prefetch={true}: waits for the ISR retry, then uses a runtime prefetch because the page needs one', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
const browser = await next.browser(indexPageWithUnique(), {
beforePageLoad(p: Playwright.Page) {
page = p
},
......@@ -496,48 +430,53 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
// The route was not prerendered during build.
// It used runtime data based on the slug.
const slug = trackUsedSlug('not-prerendered_yes-cookies_prefetch-true')
const slug = trackUsedSlug(
slugWithUnique('not-prerendered_yes-cookies')
)
const href = `/static-for-some-params/${slug}`
const prefetch = true
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
// The retried request yields a concrete prerender with params.
// It also says that the route needs a runtime prefetch (because it used
// runtime data) but we already did one.
await act(async () => {
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
// Wait for the router to do a retry.
await new Promise((resolve) => setTimeout(resolve, ISR_RETRY_DELAY))
}, [
// The retried request yields a concrete prerender with params.
{
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
},
block: true,
})
}, [
// After the outer act() callback, the blocked concrete response resolves.
// The concrete page needs runtime data, so now the link uses a
// runtime prefetch.
{
......@@ -549,11 +488,9 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
describe('with ensureStatic', () => {
describe('ensureStatic = "shell"', () => {
// FIXME: Flaky test
// @force-gate !deploy
it('prefetch={true}: waits for the ISR retry, then uses a runtime prefetch because the page needs one', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
const browser = await next.browser(indexPageWithUnique(), {
beforePageLoad(p: Playwright.Page) {
page = p
},
......@@ -566,51 +503,49 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
// The `ensureStatic` config should not affect the behavior here, because runtime
// data is only used in the prefetch, not the shell.
const slug = trackUsedSlug(
'not-prerendered_yes-cookies_ensure-static-shell'
slugWithUnique('not-prerendered_yes-cookies_es-shell')
)
const href = `/static-for-some-params/${slug}/ensure-static/shell`
const prefetch = true
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
await act(async () => {
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
browser
.elementByCss(linkAccordionSelector({ href, prefetch }))
.click(),
[
// Static shell/prefetch (based on hint) yields an ISR fallback
{
includes: STATIC_SHELL_CONTENT,
kind: 'static',
block: true,
},
// It's a fallback, so it should not contain params.
{
includes: `Slug: ${slug}`,
block: 'reject',
},
]
)
},
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
// Wait for the router to do a retry.
await new Promise((resolve) =>
setTimeout(resolve, ISR_RETRY_DELAY)
)
}, [
// The retried request yields a concrete prerender with params.
{
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
},
block: true,
})
}, [
// After the outer act() callback, the blocked concrete response resolves.
// The concrete page needs runtime data, so now the link uses a
// runtime prefetch.
{
......@@ -622,11 +557,9 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
})
describe('ensureStatic = "prefetch"', () => {
// FIXME: Flaky test
// @force-gate !deploy
it('prefetch={true}: does not use a runtime prefetch as a replacement for not-yet-available ISR content', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
const browser = await next.browser(indexPageWithUnique(), {
beforePageLoad(p: Playwright.Page) {
page = p
},
......@@ -640,13 +573,13 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
// The `ensureStatic` config SHOULD change the behavior here -- we should ignore the
// fact that runtime data was used, and only use static requests anyway.
const slug = trackUsedSlug(
'not-prerendered_yes-cookies_ensure-static-prefetch'
slugWithUnique('not-prerendered_yes-cookies_es-prefetch')
)
const href = `/static-for-some-params/${slug}/ensure-static/prefetch`
const prefetch = true
await act(async () => {
await act(async () => {
await act(
async () => {
// Reveal a prefetch-true link to the route, but delay the initial request.
await act(
() =>
......@@ -667,34 +600,18 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
},
]
)
}, [
// After this act()'s callback, the blocked static request is resolved.
// The router sees that it's an ISR fallback and kicks off the ISR retry loop.
// Unlike the default behavior, it should NOT use a runtime request for the
// missing content, because the route has `ensureStatic = "prefetch"`, so
// runtime prefetches are not allowed.
{
includes: '',
kind: 'runtime',
block: 'reject',
},
])
// Wait for the router to do a retry.
await new Promise((resolve) =>
setTimeout(resolve, ISR_RETRY_DELAY)
)
}, [
// The retried request yields a concrete prerender with params.
{
includes: `Slug: ${slug}`,
kind: 'static',
},
{
includes: '',
kind: 'runtime',
block: 'reject',
},
])
// After this act()'s callback, the blocked static request is resolved.
// It yielded an ISR fallback, so the router retries it. The retry is the
// same request, still in flight, so the link waits for it instead of
// sending a runtime prefetch.
'no-requests'
)
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
})
})
})
})
......
import { isNextDeploy, nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
import {
createRouterAct,
isActMissingResponseError,
waitForSuccessfulISRFallbackRetry,
} from 'router-act'
import { retry } from '../../../../lib/next-test-utils'
const REPRODUCE_UNNECESSARY_RUNTIME_PREFETCH =
......@@ -2733,24 +2737,6 @@ describe('static App Shell prefetch attempt', () => {
// TODO(ensure-static): In deploy, we apparently serve an ISR fallback for RSC prefetches
// even though the route is configured as blocking.
// The client router should retry the request.
const isActMissingSlugError = (thrown: unknown) => {
if (
thrown &&
typeof thrown === 'object' &&
'message' in thrown &&
typeof thrown.message === 'string'
) {
const error = thrown as Error
return (
error.message.includes(
'Expected a response containing the given string'
) && error.message.includes(`Slug: ${slug}`)
)
}
return false
}
try {
await act(async () => {
await browser
......@@ -2769,51 +2755,18 @@ describe('static App Shell prefetch attempt', () => {
])
} catch (err) {
// We might not get the slug in the initial request.
// TODO: nested with block: true?
if (!isActMissingSlugError(err)) {
if (isActMissingResponseError(err, `Slug: ${slug}`)) {
console.error(
'initial link reveal failed (likely an ISR fallback)',
err
)
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
})
} else {
throw err
}
console.error(
'initial link reveal failed (likely an ISR fallback)',
err
)
const interval = 2_000
const maxAttempts = 5
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
await act(async () => {
await new Promise<void>((resolve) =>
setTimeout(resolve, interval + 500)
)
}, [
// Static prefetch
{
includes: `Slug: ${slug}`,
kind: 'static',
},
// No runtime requests (e.g. runtime follow-up due to ISR fallback)
{ includes: '', kind: 'runtime', block: 'reject' },
])
// if act() succeeded, then we got a complete prerender, and can stop waiting
// for retries.
break
} catch (err) {
// act() threw.
if (!isActMissingSlugError(err)) {
throw err
}
// The router did a retry, but got an ISR fallback again.
if (attempt < maxAttempts) {
console.error(`Retry ${attempt} failed:`, err)
} else {
console.error(`Retry ${attempt} failed, aborting`)
throw err
}
}
}
}
} else {
await act(async () => {
......@@ -2862,24 +2815,6 @@ describe('static App Shell prefetch attempt', () => {
// TODO(ensure-static): In deploy, we apparently serve an ISR fallback for RSC prefetches
// even though the route is configured as blocking.
// The client router should retry the request.
const isActMissingSlugError = (thrown: unknown) => {
if (
thrown &&
typeof thrown === 'object' &&
'message' in thrown &&
typeof thrown.message === 'string'
) {
const error = thrown as Error
return (
error.message.includes(
'Expected a response containing the given string'
) && error.message.includes(`Slug: ${slug}`)
)
}
return false
}
try {
await act(async () => {
await browser
......@@ -2898,51 +2833,18 @@ describe('static App Shell prefetch attempt', () => {
])
} catch (err) {
// We might not get the slug in the initial request.
// TODO: nested with block: true?
if (!isActMissingSlugError(err)) {
if (isActMissingResponseError(err, `Slug: ${slug}`)) {
console.error(
'initial link reveal failed (likely an ISR fallback)',
err
)
await waitForSuccessfulISRFallbackRetry(act, {
includes: `Slug: ${slug}`,
kind: 'static',
})
} else {
throw err
}
console.error(
'initial link reveal failed (likely an ISR fallback)',
err
)
const interval = 2_000
const maxAttempts = 5
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
await act(async () => {
await new Promise<void>((resolve) =>
setTimeout(resolve, interval + 500)
)
}, [
// Static prefetch
{
includes: `Slug: ${slug}`,
kind: 'static',
},
// No runtime requests (e.g. runtime follow-up due to ISR fallback)
{ includes: '', kind: 'runtime', block: 'reject' },
])
// if act() succeeded, then we got a complete prerender, and can stop waiting
// for retries.
break
} catch (err) {
// act() threw.
if (!isActMissingSlugError(err)) {
throw err
}
// The router did a retry, but got an ISR fallback again.
if (attempt < maxAttempts) {
console.error(`Retry ${attempt} failed:`, err)
} else {
console.error(`Retry ${attempt} failed, aborting`)
throw err
}
}
}
}
} else {
await act(async () => {
......
......@@ -120,6 +120,8 @@ type ActConfig =
| 'no-requests'
| null
export type RouterAct = ReturnType<typeof createRouterAct>
export function createRouterAct(
page: Playwright.Page,
options?: {
......@@ -827,10 +829,14 @@ ${fulfilled.body}
// Print a helpful error message.
if (expectedResponses.length === 1) {
const includes = expectedResponses[0].includes
error.message =
'Expected a response containing the given string:\n\n' +
expectedResponses[0].includes +
includes +
'\n'
;(error as ActMissingResponseError).code =
MISSING_RESPONSE_ERROR_CODE
;(error as ActMissingResponseError).includes = includes
} else {
const expectedSubstrings = expectedResponses.map(
(item) => item.includes
......@@ -892,3 +898,83 @@ ${fulfilled.body}
return act
}
const MISSING_RESPONSE_ERROR_CODE = 'MISSING_RESPONSE'
type ActMissingResponseError = Error & {
code: typeof MISSING_RESPONSE_ERROR_CODE
includes: string
}
export function isActMissingResponseError(
thrown: unknown,
expected: string
): thrown is ActMissingResponseError {
if (
thrown &&
typeof thrown === 'object' &&
'message' in thrown &&
typeof thrown.message === 'string' &&
'code' in thrown &&
thrown.code === MISSING_RESPONSE_ERROR_CODE
) {
const error = thrown as ActMissingResponseError
return error.includes === expected
}
return false
}
/**
* Waits for the ISR fallback retry loop to receive a concrete response.
*
* @param concretePrerenderAssertion - An `act()` assertion that matches the concrete prerender.
* If the response needs to be delayed (e.g. to assert that it's followed with a runtime prefetch),
* nest the call in an another `act()` and set `block: true`.
* */
export async function waitForSuccessfulISRFallbackRetry(
act: RouterAct,
concretePrerenderAssertion: {
includes: string
kind: 'static'
block?: boolean
}
) {
// The router retries ISR fallbacks in 2s intervals.
const interval = 2_000
const maxAttempts = 5
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
await act(async () => {
await new Promise<void>((resolve) =>
setTimeout(resolve, interval + 100)
)
}, [
// The retried request eventually yields a concrete prerender.
concretePrerenderAssertion,
// NO Runtime prefetch to get the content
// or runtime requests of any kind
{ includes: '', kind: 'runtime', block: 'reject' },
])
// if act() succeeded, then we got a complete prerender, and can stop waiting
// for retries.
break
} catch (err) {
// act() threw. Check if it's because we still didn't get a slug in the response.
// This may happen if the concrete prerender hasn't finished yet.
if (isActMissingResponseError(err, concretePrerenderAssertion.includes)) {
// The router did a retry, but got an ISR fallback again.
if (attempt < maxAttempts) {
console.error(`Retry ${attempt} failed:`, err)
} else {
throw new Error(
`Did not receive a concrete prerender after ${maxAttempts} attempts`,
{ cause: err }
)
}
} else {
// All other errors get reported as-is.
throw err
}
}
}
}
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