Unverified Commit 676b665e authored by Jan Kassens's avatar Jan Kassens Committed by GitHub

Pass lazy response lifecycle capabilities into App rendering (#100395)

## Summary

Continue decoupling App Router rendering from HTTP responses by binding
lazy development response capabilities at the route-module boundary. HMR
cancellation, validation scheduling, and worker snapshots use these
capabilities instead of accessing `originalResponse` in the renderer.

Preserves listener registration timing, abort reasons, live completion
state, and the response wrapper's preview-cookie synchronization. Adds
unit coverage for these behaviors and scoped import restrictions to keep
response lifecycle access at the adapter boundary.

## Verification

38 test executions passed:

- Lifecycle and existing response-completion unit tests: 11.
- `test-dev-turbo`: HMR cancellation, validation scheduling, and worker
source maps: 11; 9 snapshots.
- `__NEXT_CACHE_COMPONENTS=true test-dev-turbo`: HMR cancellation and
static-shell validation: 8; 1 snapshot.
- `test-dev-webpack`: HMR cancellation and validation scheduling: 6.
- `test-start-webpack`: standalone Node/Edge bundling: 2.

<!-- NEXT_JS_LLM -->
parent 443a9e7a
......@@ -205,15 +205,13 @@ import {
} from './dynamic-rendering-validation'
import { logBuildDebugHint } from './blocking-route-messages'
import { ClientComponentLoadTracker } from '../client-component-renderer-logger'
import { isNodeNextResponse } from '../base-http/helpers'
import type { DevResponseLifecycle } from './dev-response-lifecycle'
import { installGlobalModuleLoadingHandlers } from './install-global-module-loading-handlers'
import { waitForResponseToFinish } from './wait-for-response'
import {
beginDevValidation,
type DevValidationGeneration,
yieldToForegroundRequest,
} from './dev-validation-scheduler'
import { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'
import {
parseRelativeUrl,
type ParsedRelativeUrl,
......@@ -420,6 +418,7 @@ export type AppRenderContext = {
isNotFoundPath: boolean
nonce: string | undefined
res: BaseNextResponse
devResponseLifecycle: DevResponseLifecycle | null
/**
* For now, the implicit tags are common for the whole route. If we ever start
* rendering/revalidating segments independently, they need to move to the
......@@ -839,9 +838,8 @@ async function generateDynamicFlightRenderResult(
const requestAbortSignal =
process.env.__NEXT_DEV_SERVER &&
renderOpts.experimental.serverComponentsHmrCancellation === true &&
requestStore.isHmrRefresh === true &&
isNodeNextResponse(ctx.res)
? signalFromNodeResponse(ctx.res.originalResponse)
requestStore.isHmrRefresh === true
? ctx.devResponseLifecycle?.getCloseSignal()
: undefined
if (process.env.__NEXT_USE_NODE_STREAMS) {
......@@ -1402,9 +1400,8 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
// render" button.
const requestAbortSignal =
renderOpts.experimental.serverComponentsHmrCancellation === true &&
initialRequestStore.isHmrRefresh === true &&
isNodeNextResponse(ctx.res)
? signalFromNodeResponse(ctx.res.originalResponse)
initialRequestStore.isHmrRefresh === true
? ctx.devResponseLifecycle?.getCloseSignal()
: undefined
const result = await stagedRenderWithCachesInDev({
......@@ -2539,7 +2536,8 @@ async function prepareAppPageRender(
routeMatch: RouteMatch,
generateRequestId: GenerateRequestId,
missingPrefetchHintPolicy: MissingPrefetchHintPolicy,
renderCapabilities: AppRenderCapabilities
renderCapabilities: AppRenderCapabilities,
devResponseLifecycle: DevResponseLifecycle | null
): Promise<PreparedAppPageRender> {
const isNotFoundPath = pagePath === '/404'
if (isNotFoundPath) {
......@@ -2675,6 +2673,7 @@ async function prepareAppPageRender(
isNotFoundPath,
nonce,
res,
devResponseLifecycle,
sharedContext,
implicitTags,
}
......@@ -3148,7 +3147,8 @@ async function renderToHTMLOrFlightImpl(
interpolatedParams: Params,
fallbackRouteParams: OpaqueFallbackRouteParams | null,
routeMatch: RouteMatch,
stagedFallbackParams: OpaqueFallbackRouteParams | null
stagedFallbackParams: OpaqueFallbackRouteParams | null,
devResponseLifecycle: DevResponseLifecycle | null
) {
if (renderOpts.ComponentMod.__next_app__) {
installGlobalModuleLoadingHandlers(
......@@ -3179,7 +3179,8 @@ async function renderToHTMLOrFlightImpl(
{
isPossiblyPartialResponse: false,
supportsPerSegmentPrefetching: renderOpts.cacheComponents,
}
},
devResponseLifecycle
)
return renderAppPage(
req,
......@@ -3236,7 +3237,8 @@ async function prerenderToHTMLOrFlightImpl(
{
isPossiblyPartialResponse: isRoutePPREnabled,
supportsPerSegmentPrefetching: true,
}
},
null
)
return prerenderAppPage(prepared)
}
......@@ -3255,7 +3257,8 @@ export type AppPageRender = (
routeMatch: RouteMatch,
parsedRequestHeaders: ParsedRequestHeaders,
serverActionRequestMetadata: ServerActionRequestMetadata,
stagedFallbackParams: OpaqueFallbackRouteParams | null
stagedFallbackParams: OpaqueFallbackRouteParams | null,
devResponseLifecycle: DevResponseLifecycle | null
) => Promise<RenderResult<AppPageRenderResultMetadata>>
export type AppPagePrerender = (
......@@ -3358,7 +3361,8 @@ export const renderToHTMLOrFlight: AppPageRender = (
routeMatch,
parsedRequestHeaders,
serverActionRequestMetadata,
stagedFallbackParams
stagedFallbackParams,
devResponseLifecycle
) => {
const { url, interpolatedParams, postponedState } = prepareAppPage(
serverActionRequestMetadata,
......@@ -3400,7 +3404,8 @@ export const renderToHTMLOrFlight: AppPageRender = (
interpolatedParams,
fallbackRouteParams,
routeMatch,
stagedFallbackParams
stagedFallbackParams,
devResponseLifecycle
)
}
......@@ -4789,8 +4794,8 @@ function runDevValidationInBackground(
// the response has finished so that work cannot delay Flight delivery or
// the client navigation.
if (
isNodeNextResponse(ctx.res) &&
!(await waitForResponseToFinish(ctx.res.originalResponse))
ctx.devResponseLifecycle &&
!(await ctx.devResponseLifecycle.waitForFinish())
) {
logValidationAborted(ctx)
return
......@@ -6602,8 +6607,7 @@ async function runWithDevValidationLogging(
const requestId = ctx.requestId
const url = ctx.url.href
const responseFinished =
!isNodeNextResponse(ctx.res) || ctx.res.originalResponse.writableFinished
const responseFinished = ctx.devResponseLifecycle?.isFinished() ?? true
console.log(
formatValidationEvent({
......@@ -8611,6 +8615,7 @@ async function validateInstantConfigInBuildWithSample(
isNotFoundPath: outerCtx.isNotFoundPath,
nonce: outerCtx.nonce,
res: outerCtx.res,
devResponseLifecycle: outerCtx.devResponseLifecycle,
sharedContext: outerCtx.sharedContext,
implicitTags: outerCtx.implicitTags,
}
......
import type { BaseNextResponse } from '../base-http'
import { isNodeNextResponse } from '../base-http/helpers'
import { waitForResponseToFinish } from './wait-for-response'
import { signalFromNodeResponse } from '../web/spec-extension/adapters/next-request'
/** Live response observations used only by development rendering. */
export type DevResponseLifecycle = {
getCloseSignal(): AbortSignal
waitForFinish(): Promise<boolean>
isFinished(): boolean
}
/** Bind capabilities without observing the response or registering listeners yet. */
export function createDevResponseLifecycle(
res: BaseNextResponse
): DevResponseLifecycle | null {
if (!isNodeNextResponse(res)) {
return null
}
return {
getCloseSignal() {
return signalFromNodeResponse(res.originalResponse)
},
waitForFinish() {
return waitForResponseToFinish(res.originalResponse)
},
isFinished() {
return res.originalResponse.writableFinished
},
}
}
......@@ -7,8 +7,6 @@ import type {
SerializedValidationInputs,
} from './dev-validation-worker-globals'
import { isNodeNextResponse } from '../base-http/helpers'
/**
* Builds the serializable snapshot the dev validation worker needs to rebuild
* the render context and inputs and run `runValidationInDev` on the worker
......@@ -26,8 +24,7 @@ export async function buildDevValidationSnapshot(
devRenderDidError: boolean
): Promise<DevValidationSnapshot> {
const requestStore = staticInputs.requestStore
const responseFinished =
!isNodeNextResponse(ctx.res) || ctx.res.originalResponse.writableFinished
const responseFinished = ctx.devResponseLifecycle?.isFinished() ?? true
// The instant and static inputs may share one debug channel, so drain each
// channel only once.
......
......@@ -39,6 +39,7 @@ import { RSCPathnameNormalizer } from '../../normalizers/request/rsc'
import { SegmentPrefixRSCPathnameNormalizer } from '../../normalizers/request/segment-prefix-rsc'
import type { UrlWithParsedQuery } from 'url'
import type { IncomingHttpHeaders, IncomingMessage } from 'http'
import { createDevResponseLifecycle } from '../../app-render/dev-response-lifecycle'
import {
applyAppPageRscRequestMetaFromHeaders,
normalizeAppPageRequestUrl,
......@@ -207,7 +208,8 @@ export class AppPageRouteModule extends RouteModule<
context.routeMatch,
context.parsedRequestHeaders,
context.serverActionRequestMetadata,
context.stagedFallbackParams
context.stagedFallbackParams,
process.env.__NEXT_DEV_SERVER ? createDevResponseLifecycle(res) : null
)
}
......
import { once } from 'node:events'
import { NodeNextResponse } from 'next/dist/server/base-http/node'
import { WebNextResponse } from 'next/dist/server/base-http/web'
import { SYMBOL_CLEARED_COOKIES } from 'next/dist/server/api-utils'
import { MockedResponse } from 'next/dist/server/lib/mock-request'
import { createDevResponseLifecycle } from 'next/dist/server/app-render/dev-response-lifecycle'
describe('development response lifecycle', () => {
it('does not observe the response or install listeners when constructed', () => {
const raw = new MockedResponse()
const response = new NodeNextResponse(raw)
const originalResponse = jest.spyOn(response, 'originalResponse', 'get')
const finishListeners = raw.listenerCount('finish')
const lifecycle = createDevResponseLifecycle(response)
expect(lifecycle).toBeDefined()
expect(originalResponse).not.toHaveBeenCalled()
expect(raw.listenerCount('close')).toBe(0)
expect(raw.listenerCount('finish')).toBe(finishListeners)
originalResponse.mockRestore()
})
it('observes current completion state and synchronizes wrapper state lazily', async () => {
const raw = new MockedResponse()
const response = new NodeNextResponse(raw)
const lifecycle = createDevResponseLifecycle(response)!
response[SYMBOL_CLEARED_COOKIES] = true
expect(Reflect.get(raw, SYMBOL_CLEARED_COOKIES)).toBeUndefined()
expect(lifecycle.isFinished()).toBe(false)
expect(Reflect.get(raw, SYMBOL_CLEARED_COOKIES)).toBe(true)
const finished = once(raw, 'finish')
raw.end()
await finished
expect(lifecycle.isFinished()).toBe(true)
})
it('aborts when the client disconnects before completion', async () => {
const raw = new MockedResponse()
const lifecycle = createDevResponseLifecycle(new NodeNextResponse(raw))!
const signal = lifecycle.getCloseSignal()
expect(signal.aborted).toBe(false)
const closed = once(raw, 'close')
raw.destroy()
await closed
expect(signal.aborted).toBe(true)
expect(signal.reason.name).toBe('ResponseAborted')
})
it('observes disconnection that happened after binding but before signal creation', async () => {
const raw = new MockedResponse()
const lifecycle = createDevResponseLifecycle(new NodeNextResponse(raw))!
const closed = once(raw, 'close')
raw.destroy()
await closed
const signal = lifecycle.getCloseSignal()
expect(signal.aborted).toBe(true)
expect(signal.reason.name).toBe('ResponseAborted')
})
it('does not abort a response that finishes normally', async () => {
const raw = new MockedResponse()
const lifecycle = createDevResponseLifecycle(new NodeNextResponse(raw))!
const signal = lifecycle.getCloseSignal()
const closed = once(raw, 'close')
raw.end()
await closed
expect(signal.aborted).toBe(false)
expect(lifecycle.isFinished()).toBe(true)
})
it('waits for completion and removes its listeners', async () => {
const raw = new MockedResponse()
const lifecycle = createDevResponseLifecycle(new NodeNextResponse(raw))!
const finishListeners = raw.listenerCount('finish')
const completed = lifecycle.waitForFinish()
expect(raw.listenerCount('finish')).toBe(finishListeners + 1)
expect(raw.listenerCount('close')).toBe(1)
raw.end()
await expect(completed).resolves.toBe(true)
expect(raw.listenerCount('finish')).toBe(finishListeners)
expect(raw.listenerCount('close')).toBe(0)
})
it('reports premature closure without treating it as completion', async () => {
const raw = new MockedResponse()
const lifecycle = createDevResponseLifecycle(new NodeNextResponse(raw))!
const finishListeners = raw.listenerCount('finish')
const completed = lifecycle.waitForFinish()
raw.destroy()
await expect(completed).resolves.toBe(false)
expect(lifecycle.isFinished()).toBe(false)
expect(raw.listenerCount('finish')).toBe(finishListeners)
expect(raw.listenerCount('close')).toBe(0)
})
it('leaves Edge responses without Node lifecycle capabilities', () => {
const previousRuntime = process.env.NEXT_RUNTIME
process.env.NEXT_RUNTIME = 'edge'
try {
expect(createDevResponseLifecycle(new WebNextResponse())).toBeNull()
} finally {
if (previousRuntime === undefined) delete process.env.NEXT_RUNTIME
else process.env.NEXT_RUNTIME = previousRuntime
}
})
})
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