Unverified Commit 5a4a08fd authored by Josh Story's avatar Josh Story Committed by GitHub

[dynamicIO] prioritize preprocessing RSC rows when prerendering (#80125)

When prerendering with dynamicIO we take advantage of a few things about
microtask behavior to ensure that anything prerenderable in RSC is
included in the HTML prerender. We found however that with large enough
RSC payloads certain things that should have been prerenderable could be
incorrectly excluded when paired with sync IO in the client because this
causes the prerender to abort earlier than one task. To prevent this we
allow the RSC response to pre-process entirely before continuing with
the prerender. This is possible as long as the RSC prerender is fully
complete before the HTML prerender begins.

We only do this when dynamicIO is enabled and only during prerender. By
construction this means that this also never happens in edge runtime.
parent 1a42db2b
...@@ -692,5 +692,6 @@ ...@@ -692,5 +692,6 @@
"691": "Accessed fallback \\`params\\` during prerendering.", "691": "Accessed fallback \\`params\\` during prerendering.",
"692": "Expected clientReferenceManifest to be defined.", "692": "Expected clientReferenceManifest to be defined.",
"693": "%s must not be used within a client component. Next.js should be preventing %s from being included in client components statically, but did not in this case.", "693": "%s must not be used within a client component. Next.js should be preventing %s from being included in client components statically, but did not in this case.",
"694": "createPrerenderPathname was called inside a client component scope." "694": "createPrerenderPathname was called inside a client component scope.",
"695": "Expected workUnitAsyncStorage to have a store."
} }
...@@ -3780,25 +3780,32 @@ async function prerenderToStream( ...@@ -3780,25 +3780,32 @@ async function prerenderToStream(
) )
try { try {
const fizzStream = await renderToInitialFizzStream({ // TODO we should use the same prerender semantics that we initially rendered
ReactDOMServer: require('react-dom/server.edge'), // with in this case too. The only reason why this is ok atm is because it's essentially
element: ( // an empty page and no user code runs.
<ErrorApp const fizzStream = await workUnitAsyncStorage.run(
reactServerStream={errorServerStream} prerenderLegacyStore,
ServerInsertedHTMLProvider={ServerInsertedHTMLProvider} renderToInitialFizzStream,
preinitScripts={errorPreinitScripts} {
clientReferenceManifest={clientReferenceManifest} ReactDOMServer: require('react-dom/server.edge'),
gracefullyDegrade={!!botType} element: (
nonce={nonce} <ErrorApp
/> reactServerStream={errorServerStream}
), ServerInsertedHTMLProvider={ServerInsertedHTMLProvider}
streamOptions: { preinitScripts={errorPreinitScripts}
nonce, clientReferenceManifest={clientReferenceManifest}
// Include hydration scripts in the HTML gracefullyDegrade={!!botType}
bootstrapScripts: [errorBootstrapScript], nonce={nonce}
formState, />
}, ),
}) streamOptions: {
nonce,
// Include hydration scripts in the HTML
bootstrapScripts: [errorBootstrapScript],
formState,
},
}
)
if (shouldGenerateStaticFlightData(workStore)) { if (shouldGenerateStaticFlightData(workStore)) {
const flightData = await streamToBuffer( const flightData = await streamToBuffer(
......
...@@ -3,6 +3,8 @@ import type { BinaryStreamOf } from './app-render' ...@@ -3,6 +3,8 @@ import type { BinaryStreamOf } from './app-render'
import { htmlEscapeJsonString } from '../htmlescape' import { htmlEscapeJsonString } from '../htmlescape'
import type { DeepReadonly } from '../../shared/lib/deep-readonly' import type { DeepReadonly } from '../../shared/lib/deep-readonly'
import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge' const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
...@@ -45,6 +47,24 @@ export function useFlightStream<T>( ...@@ -45,6 +47,24 @@ export function useFlightStream<T>(
nonce, nonce,
}) })
// Edge pages are never prerendered so they necessarily cannot have a workUnitStore type
// that requires the nextTick behavior. This is why it is safe to access a node only API here
if (process.env.NEXT_RUNTIME !== 'edge') {
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workUnitStore) {
throw new InvariantError('Expected workUnitAsyncStorage to have a store.')
}
if (workUnitStore.type === 'prerender-client') {
const responseOnNextTick = new Promise<T>((r) => {
process.nextTick(() => {
r(newResponse)
})
})
flightResponses.set(flightStream, responseOnNextTick)
return responseOnNextTick
}
}
flightResponses.set(flightStream, newResponse) flightResponses.set(flightStream, newResponse)
return newResponse return newResponse
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { assertNoErrorToast } from 'next-test-utils'
import { createExpectError } from './utils' import { createExpectError } from './utils'
...@@ -18,11 +19,6 @@ function runTests(options: { withMinification: boolean }) { ...@@ -18,11 +19,6 @@ function runTests(options: { withMinification: boolean }) {
return return
} }
if (isNextDev) {
it('does not run in dev', () => {})
return
}
beforeEach(async () => { beforeEach(async () => {
if (!withMinification) { if (!withMinification) {
await next.patchFile('next.config.js', (content) => await next.patchFile('next.config.js', (content) =>
...@@ -34,14 +30,22 @@ function runTests(options: { withMinification: boolean }) { ...@@ -34,14 +30,22 @@ function runTests(options: { withMinification: boolean }) {
} }
}) })
it('should not error the build sync IO is used inside a Suspense Boundary in a client Component and nothing else is dynamic', async () => { if (isNextDev) {
try { it('does not show a validation error in the dev overlay', async () => {
await next.start() await next.start()
} catch { const browser = await next.browser('/')
throw new Error('expected build not to fail') await assertNoErrorToast(browser)
} })
expect(next.cliOutput).toContain('◐ / ') } else {
}) it('should not error the build sync IO is used inside a Suspense Boundary in a client Component and nothing else is dynamic', async () => {
try {
await next.start()
} catch {
throw new Error('expected build not to fail')
}
expect(next.cliOutput).toContain('◐ / ')
})
}
}) })
describe('Error Attribution with Sync IO - Guarded RSC with unguarded Client sync IO', () => { describe('Error Attribution with Sync IO - Guarded RSC with unguarded Client sync IO', () => {
const { next, isNextDev, skipped } = nextTestSetup({ const { next, isNextDev, skipped } = nextTestSetup({
......
...@@ -3,6 +3,12 @@ export default function Root({ children }: { children: React.ReactNode }) { ...@@ -3,6 +3,12 @@ export default function Root({ children }: { children: React.ReactNode }) {
<html> <html>
<body> <body>
<main>{children}</main> <main>{children}</main>
<div>
We add extra content here because it increases the size of the dev RSC
payload which exercises the preloading of the RSC chunks more. We want
a greater page weight than this simple test would otherwise have
produced.
</div>
</body> </body>
</html> </html>
) )
......
...@@ -851,8 +851,11 @@ export async function assertHasRedbox(browser: Playwright) { ...@@ -851,8 +851,11 @@ export async function assertHasRedbox(browser: Playwright) {
} }
} }
export async function assertNoRedbox(browser: Playwright) { export async function assertNoRedbox(
await waitFor(5000) browser: Playwright,
{ waitInMs = 5000 }: { waitInMs?: number } = {}
) {
await waitFor(waitInMs)
const redbox = browser.locateRedbox() const redbox = browser.locateRedbox()
if (await redbox.isVisible()) { if (await redbox.isVisible()) {
...@@ -873,6 +876,26 @@ export async function assertNoRedbox(browser: Playwright) { ...@@ -873,6 +876,26 @@ export async function assertNoRedbox(browser: Playwright) {
} }
} }
export async function assertNoErrorToast(browser: Playwright): Promise<void> {
let didOpenRedbox = false
try {
await browser.waitForElementByCss('[data-issues]').click()
didOpenRedbox = true
} catch {
// We expect this to fail.
}
if (didOpenRedbox) {
// If a redbox was opened unexpectedly, we use the `assertNoRedbox` helper
// to print a useful error message containing the redbox contents.
await assertNoRedbox(browser, {
// We already know the redbox is open, so we can skip waiting for it.
waitInMs: 0,
})
}
}
export async function hasErrorToast(browser: Playwright): Promise<boolean> { export async function hasErrorToast(browser: Playwright): Promise<boolean> {
return Boolean( return Boolean(
await browser.eval(() => { await browser.eval(() => {
......
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