Cancel a superseded Server Components HMR refresh's server-side work

When rapid edits overlap Server Components HMR refreshes in `next dev`,
only the newest refresh can commit. The client already aborts a
superseded refresh's fetch, which closes its response. We use that
response-close to stop the server work the superseded refresh started,
so the dev server no longer runs a render (and, under Cache Components,
a validation) whose result is discarded.

When the `serverComponentsHmrCancellation` flag is enabled and the
request is an HMR refresh over a Node response, we derive an abort
signal from `signalFromNodeResponse(ctx.res.originalResponse)` and
thread it into the Flight render. This covers both dev RSC render paths:
the Cache Components staged render in
`generateDynamicFlightRenderResultWithStagesInDev` and the
non-Cache-Components render in `generateDynamicFlightRenderResult`.

The render is aborted through `renderToNodeFlightStream`, which calls
`abort()` on the pipeable that `renderToPipeableStream` returns when the
signal fires. React's Node Flight API has no `signal` option, unlike the
Web `renderToReadableStream`, aborting the returned pipeable is the
intended way to stop the render. This also removes the incorrect
`signal` field from the `renderToPipeableStream` type declaration and
derives `FlightRenderOptions` from `renderToReadableStream`'s options,
so the render wrappers are no longer typed as `any`.

Under Cache Components the superseded refresh additionally skips its
detached validation, which only runs on the staged render, so it never
validates a discarded tree, and any error thrown while its background
renders tear down is swallowed. The aborted Flight renders surface as
abort errors that `createReactServerErrorHandler` already ignores, so
nothing reaches the error overlay or the CLI.

The `hmr-rsc-cancellation` suite exercises both render paths, with Cache
Components controlled by the `__NEXT_CACHE_COMPONENTS` test shard rather
than the fixture config. A child component logs when React renders it,
and the test asserts the superseded refresh never logs, since its render
is aborted before reaching the child, while the committed refresh does.
The detached-validation assertions run only when Cache Components is
enabled.
parent 614443ce
...@@ -48,6 +48,11 @@ import { ...@@ -48,6 +48,11 @@ import {
atLeastOneTask, atLeastOneTask,
waitAtLeastOneReactRenderTask, waitAtLeastOneReactRenderTask,
} from '../../lib/scheduler' } from '../../lib/scheduler'
import type {
FlightPayload,
FlightClientModules,
FlightRenderOptions,
} from './stream-ops.web'
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Re-export shared types from the web module // Re-export shared types from the web module
...@@ -536,21 +541,38 @@ export { renderToWebFlightStream } from './stream-ops.web' ...@@ -536,21 +541,38 @@ export { renderToWebFlightStream } from './stream-ops.web'
export function renderToNodeFlightStream( export function renderToNodeFlightStream(
ComponentMod: FlightComponentMod, ComponentMod: FlightComponentMod,
payload: any, payload: FlightPayload,
clientModules: any, clientModules: FlightClientModules,
opts: any opts: FlightRenderOptions
): AnyStream { ): AnyStream {
if (!ComponentMod.renderToPipeableStream) { if (!ComponentMod.renderToPipeableStream) {
throw new Error('renderToPipeableStream is not implemented') throw new Error('renderToPipeableStream is not implemented')
} }
// `renderToPipeableStream` has no `signal` option (unlike the Web
// `renderToReadableStream`), so pull `signal` out of the options and abort
// the returned pipeable ourselves when it fires. The listener is removed once
// the passthrough closes.
const { signal, ...renderOptions } = opts ?? {}
const pt = new PassThrough() const pt = new PassThrough()
const pipeable = ComponentMod.renderToPipeableStream!( const pipeable = ComponentMod.renderToPipeableStream!(
payload, payload,
clientModules, clientModules,
opts renderOptions
) )
pipeable.pipe(pt) pipeable.pipe(pt)
if (signal) {
if (signal.aborted) {
pipeable.abort(signal.reason)
} else {
const onAbort = () => pipeable.abort(signal.reason)
signal.addEventListener('abort', onAbort, { once: true })
pt.on('close', () => signal.removeEventListener('abort', onAbort))
}
}
return pt return pt
} }
......
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
import type { PostponedState, PrerenderOptions } from 'react-dom/static' import type { PostponedState, PrerenderOptions } from 'react-dom/static'
import { resume, renderToReadableStream } from 'react-dom/server' import { resume, renderToReadableStream } from 'react-dom/server'
import { prerender } from 'react-dom/static' import { prerender } from 'react-dom/static'
import type { renderToReadableStream as flightRenderToReadableStream } from 'react-server-dom-webpack/server'
import { import {
renderToInitialFizzStream, renderToInitialFizzStream,
...@@ -32,11 +33,7 @@ import type { AnyStream as AnyStreamType } from './app-render-prerender-utils' ...@@ -32,11 +33,7 @@ import type { AnyStream as AnyStreamType } from './app-render-prerender-utils'
// Shared types // Shared types
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
type FlightRenderToReadableStream = ( type FlightRenderToReadableStream = typeof flightRenderToReadableStream
model: any,
webpackMap: any,
options?: any
) => ReadableStream<Uint8Array>
export type AnyStream = AnyStreamType export type AnyStream = AnyStreamType
...@@ -73,7 +70,17 @@ export type ServerPrerenderComponentMod = { ...@@ -73,7 +70,17 @@ export type ServerPrerenderComponentMod = {
export type FlightPayload = Parameters<FlightRenderToReadableStream>[0] export type FlightPayload = Parameters<FlightRenderToReadableStream>[0]
export type FlightClientModules = Parameters<FlightRenderToReadableStream>[1] export type FlightClientModules = Parameters<FlightRenderToReadableStream>[1]
export type FlightRenderOptions = Parameters<FlightRenderToReadableStream>[2]
/**
* The options our Flight render wrappers accept, taken from React's Flight
* `renderToReadableStream`. `signal` aborts the render: the Web wrapper passes
* it straight to `renderToReadableStream`, while the Node wrapper aborts the
* pipeable returned by `renderToPipeableStream` (which has no `signal` option)
* when it fires.
*/
export type FlightRenderOptions = NonNullable<
Parameters<FlightRenderToReadableStream>[2]
>
export type FizzStreamResult = { export type FizzStreamResult = {
stream: AnyStream stream: AnyStream
......
...@@ -1196,7 +1196,7 @@ export interface ExperimentalConfig { ...@@ -1196,7 +1196,7 @@ export interface ExperimentalConfig {
serverComponentsHmrCache?: boolean serverComponentsHmrCache?: boolean
/** /**
* Cancels the render and validation work for a Server Component HMR refresh * Cancels the render and validation work for a Server Components HMR refresh
* once a newer refresh supersedes it. Development only. * once a newer refresh supersedes it. Development only.
*/ */
serverComponentsHmrCancellation?: boolean serverComponentsHmrCancellation?: boolean
......
...@@ -240,7 +240,6 @@ declare module 'react-server-dom-webpack/server.node' { ...@@ -240,7 +240,6 @@ declare module 'react-server-dom-webpack/server.node' {
) => boolean) ) => boolean)
| undefined | undefined
onError?: (error: unknown) => void onError?: (error: unknown) => void
signal?: AbortSignal
// React's Node API expects debugChannel to be a Node.js Writable // React's Node API expects debugChannel to be a Node.js Writable
// (has .write()), Duplex (has .read()), or WebSocket (has .send()). // (has .write()), Duplex (has .read()), or WebSocket (has .send()).
// This differs from the web API which expects { readable?, writable? }. // This differs from the web API which expects { readable?, writable? }.
......
import { connection } from 'next/server' import { connection } from 'next/server'
import { Suspense } from 'react' import { Suspense } from 'react'
// Editing any of these constants triggers a Server Component HMR refresh. // Editing any of these constants triggers a Server Components HMR refresh.
// `boundaryKey` is the Suspense boundary's key: changing it remounts the // `boundaryKey` is the Suspense boundary's key: changing it remounts the
// boundary, so the remounted boundary has no prior content and commits its // boundary, so the remounted boundary has no prior content and commits its
// fallback while `DynamicContent` streams — a partially committed tree. // fallback while `DynamicContent` streams (a partially committed tree).
const boundaryKey = 'initial' const boundaryKey = 'initial'
const dynamicMarker = 'initial' const dynamicMarker = 'initial'
const dynamicDelayMs = 0 const dynamicDelayMs = 0
// Logs when React renders it. A superseded refresh's render is aborted while
// `DynamicContent` is still awaiting, so React never renders this child and no
// log arrives for that marker; only the refresh that commits logs.
function DynamicMarker({ marker }: { marker: string }) {
console.log(`[hmr-rsc-cancellation] rendered ${marker}`)
return <p id="dynamic">{marker}</p>
}
async function DynamicContent() { async function DynamicContent() {
await connection() await connection()
await new Promise((resolve) => setTimeout(resolve, dynamicDelayMs)) await new Promise((resolve) => setTimeout(resolve, dynamicDelayMs))
return <p id="dynamic">{dynamicMarker}</p> return <DynamicMarker marker={dynamicMarker} />
} }
export default function Page() { export default function Page() {
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry, assertNoConsoleErrors } from 'next-test-utils' import { retry, assertNoConsoleErrors } from 'next-test-utils'
import { parseValidationMessages } from 'e2e-utils/instant-validation'
import type { Playwright } from 'next-webdriver' import type { Playwright } from 'next-webdriver'
const cacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
describe('hmr-rsc-cancellation', () => { describe('hmr-rsc-cancellation', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
files: __dirname, files: __dirname,
skipStart: true, skipStart: true,
// Emit `<VALIDATION_MESSAGE>` markers so the server-side validation-skip
// can be asserted.
env: { NEXT_TEST_LOG_VALIDATION: '1' },
}) })
let pristinePage: string let pristinePage: string
...@@ -79,7 +85,21 @@ describe('hmr-rsc-cancellation', () => { ...@@ -79,7 +85,21 @@ describe('hmr-rsc-cancellation', () => {
expect(output).not.toContain('unhandledRejection') expect(output).not.toContain('unhandledRejection')
} }
it('cancels a superseded Server Component HMR request', async () => { // The markers `DynamicMarker` logs when React renders it. The dev server
// forwards server-component logs to the browser console, so we read them from
// there. A render aborted before React reaches the child logs nothing for its
// marker.
async function renderedMarkers(browser: Playwright): Promise<string[]> {
const logs = await browser.log()
return logs.flatMap((entry) => {
const match = entry.message.match(
/\[hmr-rsc-cancellation\] rendered (\w+)/
)
return match ? [match[1]] : []
})
}
it('cancels a superseded Server Components HMR request', async () => {
await next.start() await next.start()
const browser = await next.browser('/', { pushErrorAsConsoleLog: true }) const browser = await next.browser('/', { pushErrorAsConsoleLog: true })
await retry(async () => { await retry(async () => {
...@@ -219,12 +239,10 @@ describe('hmr-rsc-cancellation', () => { ...@@ -219,12 +239,10 @@ describe('hmr-rsc-cancellation', () => {
) )
.replace(/const dynamicDelayMs = \d+/, 'const dynamicDelayMs = 0') .replace(/const dynamicDelayMs = \d+/, 'const dynamicDelayMs = 0')
) )
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('latest')
})
// With cancellation disabled, neither refresh is aborted; both run to // With cancellation disabled, neither refresh is aborted; both run to
// completion like before. // completion. Which marker ends up committed is a race (the superseded
// refresh can still finish and clobber the newest), so we assert only that
// both requests ran, unaborted, rather than the final DOM.
await retry(async () => { await retry(async () => {
const { requests } = await readResult(browser) const { requests } = await readResult(browser)
expect(requests).toMatchObject([ expect(requests).toMatchObject([
...@@ -233,4 +251,69 @@ describe('hmr-rsc-cancellation', () => { ...@@ -233,4 +251,69 @@ describe('hmr-rsc-cancellation', () => {
]) ])
}) })
}) })
it("aborts the superseded refresh's render server-side", async () => {
await next.start()
const browser = await next.browser('/', { pushErrorAsConsoleLog: true })
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('initial')
})
await instrumentBrowser(browser)
const cliStart = next.cliOutput.length
// Request A: a slow refresh that stays in flight until B supersedes it.
await next.patchFile('app/page.tsx', (src) =>
src
.replace(
/const dynamicMarker = '[^']*'/,
"const dynamicMarker = 'slow'"
)
.replace(/const dynamicDelayMs = \d+/, 'const dynamicDelayMs = 5000')
)
await retry(async () => {
expect(
await browser.eval(() => (window as any).__hmrRequests.length)
).toBe(1)
})
// Request B changes only the marker, so it keeps A's slow delay while
// superseding it. By the time B commits, A's delay has elapsed: had A's
// render not been aborted, `DynamicMarker` would already have rendered and
// logged `slow`.
await next.patchFile('app/page.tsx', (src) =>
src.replace(
/const dynamicMarker = '[^']*'/,
"const dynamicMarker = 'latest'"
)
)
await retry(async () => {
expect(await browser.elementById('dynamic').text()).toBe('latest')
}, 10000)
await retry(async () => {
const markers = await renderedMarkers(browser)
// The superseding refresh rendered; the superseded refresh's render was
// aborted before React reached `DynamicMarker`, so it never logged.
expect(markers).toContain('latest')
expect(markers).not.toContain('slow')
}, 10000)
if (cacheComponentsEnabled) {
// On the Cache Components staged render the superseded refresh also skips
// its detached validation: it emits `validation_aborted` and never a
// start/end pair, while the committed refresh validates normally.
await retry(async () => {
const events = parseValidationMessages(next.cliOutput.slice(cliStart))
expect(events).toMatchObject([
{ type: 'validation_aborted' },
{ type: 'validation_start' },
{ type: 'validation_end' },
])
expect(events[0].requestId).not.toBe(events[1].requestId)
}, 10000)
}
await assertNoConsoleErrors(browser)
expectCleanCliOutput(next.cliOutput.slice(cliStart))
})
}) })
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
* @type {import('next').NextConfig} * @type {import('next').NextConfig}
*/ */
const nextConfig = { const nextConfig = {
cacheComponents: true,
experimental: { experimental: {
serverComponentsHmrCancellation: true, serverComponentsHmrCancellation: true,
}, },
......
...@@ -2,7 +2,10 @@ import { retry } from '../next-test-utils' ...@@ -2,7 +2,10 @@ import { retry } from '../next-test-utils'
import { getDeterministicOutput } from '../../e2e/app-dir/cache-components-errors/utils' import { getDeterministicOutput } from '../../e2e/app-dir/cache-components-errors/utils'
import { inspect } from 'util' import { inspect } from 'util'
export type ValidationEvent = ValidationStartEvent | ValidationEndEvent export type ValidationEvent =
| ValidationStartEvent
| ValidationEndEvent
| ValidationAbortedEvent
type ValidationStartEvent = { type ValidationStartEvent = {
type: 'validation_start' type: 'validation_start'
...@@ -14,6 +17,13 @@ type ValidationEndEvent = { ...@@ -14,6 +17,13 @@ type ValidationEndEvent = {
requestId: string requestId: string
url: string url: string
} }
// Emitted instead of a start/end pair when a request is aborted before its
// detached validation runs (e.g. Server Components HMR cancellation).
type ValidationAbortedEvent = {
type: 'validation_aborted'
requestId: string
url: string
}
export function parseValidationMessages(output: string): ValidationEvent[] { export function parseValidationMessages(output: string): ValidationEvent[] {
const messageRe = /<VALIDATION_MESSAGE>(.*?)<\/VALIDATION_MESSAGE>/g const messageRe = /<VALIDATION_MESSAGE>(.*?)<\/VALIDATION_MESSAGE>/g
......
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