Unverified Commit 84e6d993 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

fix(dev-overlay): report server errors after the pending webpack hot update is applied

In webpack dev, navigating to a route that isn't compiled yet triggers a
rebuild. Server errors for that navigation (e.g. instant validation errors
sent via HMR, or logs replayed while decoding the Flight response) could
reach the dev overlay before the client finished applying the hot update,
so the Fast Refresh at the end of the update cleared them again.

Wait for the pending webpack hot update before reporting them.
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent d50d2ce8
const mockCreateFromFetch = jest.fn()
const mockFetch = jest.fn()
const mockWaitForWebpackRuntimeHotUpdate = jest.fn()
jest.mock('react-server-dom-webpack/client', () => ({
createFromFetch: (...args: unknown[]) => mockCreateFromFetch(...args),
createFromReadableStream: jest.fn(),
}))
jest.mock('../segment-cache/fetch', () => ({
fetch: (...args: unknown[]) => mockFetch(...args),
}))
jest.mock('../../dev/hot-reloader/app/hot-reloader-app', () => ({
waitForWebpackRuntimeHotUpdate: () => mockWaitForWebpackRuntimeHotUpdate(),
}))
import { createFetch } from './fetch-server-response'
function createDeferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((res) => {
resolve = res
})
return { promise, resolve }
}
// Resolves on the next macrotask, after all pending microtasks have run.
function waitForPendingMicrotasks() {
return new Promise((resolve) => setImmediate(resolve))
}
describe('createFetch', () => {
const originalEnv = process.env
const hadSelf = 'self' in globalThis
beforeAll(() => {
// `createFetch` reads `self.__next_r` in dev.
if (!hadSelf) {
;(globalThis as any).self = globalThis
}
})
afterAll(() => {
if (!hadSelf) {
delete (globalThis as any).self
}
})
beforeEach(() => {
process.env = { ...originalEnv }
delete process.env.__NEXT_SERVER_COMPONENTS_HMR_CANCELLATION
mockCreateFromFetch.mockReset()
mockFetch.mockReset()
mockWaitForWebpackRuntimeHotUpdate.mockReset()
mockCreateFromFetch.mockImplementation(
(promiseForResponse: Promise<Response>) =>
promiseForResponse.then(() => ({}))
)
})
afterEach(() => {
process.env = originalEnv
})
/**
* Starts a navigation fetch and returns the promise that was handed to the
* Flight client, once the Flight client has been created. The network
* response is still pending at that point.
*/
async function startFetch() {
const network = createDeferred<Response>()
const fetchStarted = createDeferred<void>()
mockFetch.mockImplementation(() => {
fetchStarted.resolve()
return network.promise
})
const rscResponsePromise = createFetch(
new URL('http://localhost/target'),
{},
null,
true
)
await fetchStarted.promise
// The Flight client is created as soon as the request starts (before the
// response arrives), so React's debug timing includes the network latency.
expect(mockCreateFromFetch).toHaveBeenCalledTimes(1)
const promiseForResponse: Promise<Response> =
mockCreateFromFetch.mock.calls[0][0]
let resolvedResponse: Response | null = null
promiseForResponse.then((res) => {
resolvedResponse = res
})
const response = new Response('', { status: 200 })
network.resolve(response)
await rscResponsePromise
return { response, getResolvedResponse: () => resolvedResponse }
}
it('defers Flight decoding until the pending webpack hot update is applied', async () => {
process.env.__NEXT_DEV_SERVER = '1'
delete process.env.TURBOPACK
const hotUpdate = createDeferred<void>()
mockWaitForWebpackRuntimeHotUpdate.mockReturnValue(hotUpdate.promise)
const { response, getResolvedResponse } = await startFetch()
// The response has arrived, but the Flight client must not process it
// (and replay server logs into the dev overlay) while the webpack hot
// update is still pending.
await waitForPendingMicrotasks()
expect(mockWaitForWebpackRuntimeHotUpdate).toHaveBeenCalledTimes(1)
expect(getResolvedResponse()).toBe(null)
hotUpdate.resolve()
await waitForPendingMicrotasks()
expect(getResolvedResponse()).toBe(response)
})
it('does not wait for a webpack hot update with Turbopack', async () => {
process.env.__NEXT_DEV_SERVER = '1'
process.env.TURBOPACK = '1'
mockWaitForWebpackRuntimeHotUpdate.mockReturnValue(new Promise(() => {}))
const { response, getResolvedResponse } = await startFetch()
await waitForPendingMicrotasks()
expect(getResolvedResponse()).toBe(response)
expect(mockWaitForWebpackRuntimeHotUpdate).not.toHaveBeenCalled()
})
it('does not wait for a webpack hot update outside of the dev server', async () => {
delete process.env.__NEXT_DEV_SERVER
delete process.env.TURBOPACK
mockWaitForWebpackRuntimeHotUpdate.mockReturnValue(new Promise(() => {}))
const { response, getResolvedResponse } = await startFetch()
await waitForPendingMicrotasks()
expect(getResolvedResponse()).toBe(response)
expect(mockWaitForWebpackRuntimeHotUpdate).not.toHaveBeenCalled()
})
})
......@@ -449,6 +449,24 @@ function decodeNavigationResponse<T>(
// only a complete prerender has a shell we can use.
responseChunks: Array<Uint8Array> | null
): Promise<T> & { _debugInfo?: Array<any> } {
let debugChannelReady: Promise<unknown> | undefined
if (process.env.__NEXT_DEV_SERVER && !process.env.TURBOPACK) {
// Navigating to a route that hasn't been compiled yet triggers a webpack
// rebuild, and the client applies the resulting hot update in parallel
// with this request. Don't let the Flight client process the response
// until that update has been applied. Otherwise, server logs that React
// replays during decoding (e.g. errors) reach the dev overlay before the
// Fast Refresh completes, and the refresh clears them again.
const { waitForWebpackRuntimeHotUpdate } =
require('../../dev/hot-reloader/app/hot-reloader-app') as typeof import('../../dev/hot-reloader/app/hot-reloader-app')
responsePromise = responsePromise.then(async (response) => {
await waitForWebpackRuntimeHotUpdate()
return response
})
// React also replays server logs from the debug channel, which it starts
// reading as soon as the decode starts, so hold that back as well.
debugChannelReady = responsePromise
}
let closed = false
let reader: ReadableStreamDefaultReader<Uint8Array> | null = null
let chunks: Array<Uint8Array> | null = null
......@@ -539,6 +557,7 @@ function decodeNavigationResponse<T>(
return createFromNextReadableStream<T>(stream, headers, {
// Only a stream that closes on abort may end before the response does.
allowPartialStream: signal !== undefined,
debugChannelReady,
}) as Promise<T> & { _debugInfo?: Array<any> }
}
......@@ -754,12 +773,73 @@ export async function createFetch(
export function createFromNextReadableStream<T>(
flightStream: ReadableStream<Uint8Array>,
requestHeaders: RequestHeaders | undefined,
options?: { allowPartialStream?: boolean }
options?: {
allowPartialStream?: boolean
/**
* Dev only: when set, the debug channel isn't read until this settles.
* React starts reading the debug channel as soon as the decode starts,
* unlike `createFromFetch`, which waits for the response.
*/
debugChannelReady?: Promise<unknown>
}
): Promise<T> {
let debugChannel = createDebugChannel && createDebugChannel(requestHeaders)
if (debugChannel?.readable && options?.debugChannelReady) {
debugChannel = {
...debugChannel,
readable: delayReadableStream(
debugChannel.readable,
options.debugChannelReady
),
}
}
return createFromReadableStream(flightStream, {
callServer,
findSourceMapURL,
debugChannel: createDebugChannel && createDebugChannel(requestHeaders),
debugChannel,
unstable_allowPartialStream: options?.allowPartialStream,
})
}
// Returns a stream that passes `stream` through, but doesn't read from it
// until `ready` settles (whether it resolves or rejects).
function delayReadableStream<R>(
stream: ReadableStream<R>,
ready: Promise<unknown>
): ReadableStream<R> {
let reader: ReadableStreamDefaultReader<R> | null = null
let cancelled = false
return new ReadableStream<R>({
async pull(controller) {
if (reader === null) {
await ready.then(
() => {},
() => {}
)
if (cancelled) {
return
}
reader = stream.getReader()
}
try {
const { done, value } = await reader.read()
if (cancelled) {
return
}
if (done) {
controller.close()
} else {
controller.enqueue(value)
}
} catch (err) {
if (!cancelled) {
controller.error(err)
}
}
},
cancel(reason) {
cancelled = true
return reader !== null ? reader.cancel(reason) : stream.cancel(reason)
},
})
}
import { HMR_MESSAGE_SENT_TO_BROWSER } from '../../../../server/dev/hot-reloader-types'
import type { HmrMessageSentToBrowser } from '../../../../server/dev/hot-reloader-types'
const mockCreateFromReadableStream = jest.fn()
jest.mock('react-server-dom-webpack/client', () => ({
createFromReadableStream: (...args: unknown[]) =>
mockCreateFromReadableStream(...args),
}))
jest.mock('next/dist/compiled/next-devtools', () => ({
dispatcher: new Proxy({}, { get: () => () => {} }),
getSerializedOverlayState: jest.fn(),
getSegmentTrieData: jest.fn(),
}))
jest.mock('../../report-hmr-latency', () => jest.fn())
jest.mock('../../../components/app-router-instance', () => ({
publicAppRouterInstance: { hmrRefresh: jest.fn() },
}))
// Resolves on the next macrotask, after all pending microtasks have run.
function waitForPendingMicrotasks() {
return new Promise((resolve) => setImmediate(resolve))
}
describe('processMessage - ERRORS_TO_SHOW_IN_BROWSER', () => {
const originalEnv = process.env
const hadSelf = 'self' in globalThis
let consoleErrorSpy: jest.SpyInstance
beforeAll(() => {
// The HMR client reads debugging flags from `self`.
if (!hadSelf) {
;(globalThis as any).self = globalThis
}
})
afterAll(() => {
if (!hadSelf) {
delete (globalThis as any).self
}
})
beforeEach(() => {
jest.resetModules()
process.env = { ...originalEnv }
mockCreateFromReadableStream.mockReset()
consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => {})
jest.spyOn(console, 'log').mockImplementation(() => {})
})
afterEach(() => {
process.env = originalEnv
jest.restoreAllMocks()
jest.clearAllTimers()
jest.useRealTimers()
delete (globalThis as any).__webpack_hash__
})
function load() {
return require('./hot-reloader-app') as typeof import('./hot-reloader-app')
}
function send(
processMessage: ReturnType<typeof load>['processMessage'],
message: HmrMessageSentToBrowser
) {
processMessage(message, () => {}, jest.fn(), {
pathname: null,
appIsrManifest: null,
})
}
const errorsMessage: HmrMessageSentToBrowser = {
type: HMR_MESSAGE_SENT_TO_BROWSER.ERRORS_TO_SHOW_IN_BROWSER,
serializedErrors: new Uint8Array(),
}
it('waits for the pending webpack hot update before reporting server errors', async () => {
delete process.env.TURBOPACK
const { processMessage } = load()
const serverError = new Error('Route "/target": instant validation error')
mockCreateFromReadableStream.mockResolvedValue({ errors: [serverError] })
// A rebuild starts (e.g. on-demand compilation of a navigation target)...
send(processMessage, { type: HMR_MESSAGE_SENT_TO_BROWSER.BUILDING })
// ...and the server reports errors before the hot update is applied.
send(processMessage, errorsMessage)
await waitForPendingMicrotasks()
// Reporting now would let the upcoming Fast Refresh clear the error.
expect(consoleErrorSpy).not.toHaveBeenCalledWith(serverError)
// The build finishes and there is nothing left to apply, which resolves
// the pending hot update.
;(globalThis as any).__webpack_hash__ = 'hash-1'
send(processMessage, {
type: HMR_MESSAGE_SENT_TO_BROWSER.BUILT,
hash: 'hash-1',
errors: [],
warnings: [],
})
await waitForPendingMicrotasks()
expect(consoleErrorSpy).toHaveBeenCalledWith(serverError)
})
it('reports server errors immediately when no rebuild is pending', async () => {
delete process.env.TURBOPACK
const { processMessage } = load()
const serverError = new Error('Route "/target": instant validation error')
mockCreateFromReadableStream.mockResolvedValue({ errors: [serverError] })
send(processMessage, errorsMessage)
await waitForPendingMicrotasks()
expect(consoleErrorSpy).toHaveBeenCalledWith(serverError)
})
it('does not wait for a webpack hot update with Turbopack', async () => {
// Turbopack's BUILDING handler schedules a delayed HMR latency report.
// Keep it from outliving the test.
jest.useFakeTimers({ doNotFake: ['setImmediate', 'queueMicrotask'] })
process.env.TURBOPACK = '1'
const { processMessage } = load()
const serverError = new Error('Route "/target": instant validation error')
mockCreateFromReadableStream.mockResolvedValue({ errors: [serverError] })
send(processMessage, { type: HMR_MESSAGE_SENT_TO_BROWSER.BUILDING })
send(processMessage, errorsMessage)
await waitForPendingMicrotasks()
expect(consoleErrorSpy).toHaveBeenCalledWith(serverError)
})
})
......@@ -576,7 +576,15 @@ export function processMessage(
}),
{ findSourceMapURL }
).then(
({ errors }) => {
async ({ errors }) => {
if (!process.env.TURBOPACK) {
// These errors come from the server (e.g. instant validation that
// runs after a navigation to a freshly compiled route) and can
// arrive while the client is still applying the corresponding
// webpack hot update. Wait for it, so that the Fast Refresh at the
// end of the update doesn't clear the errors from the dev overlay.
await waitForWebpackRuntimeHotUpdate()
}
for (const error of errors) {
// These errors originated on the server and were already logged
// there. Mark them so the browser-to-terminal log forwarding
......
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