[test] Add deploy coverage for a non-ASCII postponed state

A PPR route whose postponed state contains a multi-byte character is
served with a corrupt document on Vercel, while the same build serves it
correctly under `next start`. This adds a deploy test for that, built
around two routes that differ only in a single character: `/ascii`
renders a list item keyed `Doppelganger`, and `/non-ascii` keys the same
item `Doppelgänger`.

The key is what carries the character into the postponed state. React
records every element enclosing a postponed boundary as a replay node
and copies its `key` in verbatim, so keying the list item that wraps the
boundary puts the label into the serialized state rather than only into
the prerendered HTML. `ä` occupies two bytes in UTF-8 but a single
UTF-16 code unit, which is enough to make the state's byte length exceed
its `String.prototype.length`. The `/revalidated` route additionally
holds a tagged `use cache` entry, so the test can invalidate that tag
through `app/api/revalidate/route.js` and assert the same invariant
against a cache entry produced by revalidation rather than one written
at build time. Those two cases are handled by different code, so neither
covers the other.

Three of the five tests fail on deploy today and all of them pass in dev
and start. The served document arrives as `l<!DOCTYPE html>`, and a
client-side navigation to the affected route ends on the "This page
couldn't load" screen with React error #412 ("Connection closed"),
because the same stray byte in front of the RSC payload shifts the first
flight row id, so the row the model references never resolves. Two
different lengths are involved here, and only one of them is wrong.
Inside the serialized state, Next.js writes a length prefix in UTF-16
code units and reads it back with `String.prototype.slice`, so that pair
agrees with itself. The `state-length` parameter on the
`application/x-nextjs-pre-render` content type is a byte offset into the
cached body, used to separate the postponed state from the prerendered
content, and it is the one currently measured in UTF-16 code units, so
the split lands short whenever the state is not pure ASCII. The local
modes pass because nothing there divides the state by a byte offset.

Note that `/ascii` and `/non-ascii` deliberately avoid `use cache`,
which keeps their Resume Data Cache empty and its serialized tail the
literal `null`. Any truncation of that tail fails to inflate, so those
two routes fail loudly. `/revalidated` has a base64 tail instead, where
dropping the final byte can still inflate, so on that route the resume
survives and the leading stray byte is the only signal. The comments in
the fixture record this so the assertions are not tightened into
something that only holds for one of the two shapes.
parent 9690bae7
import { revalidateTag } from 'next/cache'
export async function POST(request) {
const tag = new URL(request.url).searchParams.get('tag')
revalidateTag(tag, 'max')
return Response.json({ ok: true, tag })
}
import { KeyedBoundary } from '../../components/keyed-boundary'
export default function Page() {
return <KeyedBoundary label="Doppelganger" />
}
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { KeyedBoundary } from '../../components/keyed-boundary'
export default function Page() {
return <KeyedBoundary label="Doppelgänger" />
}
import Link from 'next/link'
export default function Page() {
return (
<nav>
<Link href="/ascii">ascii</Link>
<Link href="/non-ascii">non-ascii</Link>
</nav>
)
}
import { cacheTag } from 'next/cache'
import { KeyedBoundary } from '../../components/keyed-boundary'
// A tagged `use cache` entry gives the test something to invalidate, which is
// what forces the CDN to ask the running function for a new cache entry instead
// of serving the one written at build time. That is the only way to reach the
// code that records the state length during revalidation.
//
// Note that this also puts entries in the Resume Data Cache, so the serialized
// state ends with a base64 tail rather than the literal `null` of the other two
// routes. Truncating that tail by a single byte can still inflate, so on this
// route the doctype assertion is the reliable signal, not the resume.
async function CachedAt() {
'use cache'
cacheTag('boundary')
return <span id="cached-at">{new Date().toISOString()}</span>
}
export default function Page() {
return (
<>
<CachedAt />
<KeyedBoundary label="Doppelgänger" />
</>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
// React records every element that encloses a postponed boundary as a replay
// node in the postponed state, and copies its `key` in verbatim. So `label`
// decides whether the postponed state is pure ASCII or carries a multi-byte
// character.
export function KeyedBoundary({ label }) {
return (
<ul>
<li key={label}>
<Suspense fallback={null}>
<Dynamic />
</Suspense>
</li>
</ul>
)
}
async function Dynamic() {
await connection()
return <span id="resumed">resumed</span>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
import cheerio from 'cheerio'
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// A PPR resume must not depend on whether the postponed state happens to be
// ASCII. `ä` takes two bytes in UTF-8 but a single UTF-16 code unit, so a
// consumer that measures the postponed state with `String.prototype.length` and
// then slices it by bytes cuts it short: the tail is left in front of the
// served document, and the truncated state can no longer be resumed.
//
// `/ascii` is the control, and differs from `/non-ascii` only in that one
// character. `/revalidated` covers the same invariant for a cache entry
// produced by revalidation rather than one written at build time, because the
// state length for those two is recorded in different places.
describe('ppr-non-ascii-postponed-state', () => {
const { next } = nextTestSetup({
files: __dirname,
})
for (const pathname of ['/ascii', '/non-ascii']) {
it(`resumes the postponed boundary on ${pathname}`, async () => {
expectResumed(await getHtml(pathname))
})
}
// This is the only coverage for the RSC data route, whose state length is
// recorded separately from the HTML one. A corrupt RSC payload takes the
// router down with React error #412 ("Connection closed"): the stray byte
// shifts the first flight row id, so the row the model references never
// resolves and the navigation ends on the "This page couldn't load" screen
// instead of the page.
for (const pathname of ['/ascii', '/non-ascii']) {
it(`completes a client-side navigation to ${pathname}`, async () => {
const browser = await next.browser('/')
await browser.elementByCss(`a[href="${pathname}"]`).click()
expect(await browser.elementByCss('#resumed').text()).toBe('resumed')
})
}
it('resumes the postponed boundary on a runtime-written entry', async () => {
const initial = await getHtml('/revalidated')
const cachedAt = cheerio.load(initial)('#cached-at').text()
const res = await next.fetch('/api/revalidate?tag=boundary', {
method: 'POST',
})
expect(res.status).toBe(200)
// Invalidation takes a moment to propagate, and a changed timestamp is what
// proves the entry was rewritten by the function.
const rewritten = await retry(
async () => {
const html = await getHtml('/revalidated')
expect(cheerio.load(html)('#cached-at').text()).not.toBe(cachedAt)
return html
},
30_000,
1_000
)
expectResumed(rewritten)
})
async function getHtml(pathname: string) {
const res = await next.fetch(pathname)
expect(res.status).toBe(200)
return res.text()
}
function expectResumed(html: string) {
// Anything before the doctype is a leftover of the postponed state.
expect(html.slice(0, 15)).toBe('<!DOCTYPE html>')
// Without a resume the boundary only exists as inlined RSC data inside a
// <script>, which cheerio does not parse.
expect(cheerio.load(html)('#resumed').length).toBe(1)
}
})
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