Unverified Commit 937a3246 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Resolve request ID confusion (#85809)

Setting the cache status for a page in dev mode is a sequential
operation that only requires the HTML request ID to identify WebSocket
clients across different browser tabs/windows. This is different from
connecting the React debug channel (after which the cache status
handling was modeled), which requires both the HTML request ID as well
as the request ID to correctly associate debug chunks for a given client
with the matching request, which might be for the HTML document, a
client-side navigation, or a server function call.

With this PR, we're removing the unused `requestId` parameter from the
`setCacheStatus` function. We're also renaming the WebSocket client's
request ID to `htmlRequestId`, as well as renaming the associated maps
and variables accordingly.

This avoids confusion and better reflects the purpose of these IDs. One
of those confusions was apparent in the `setReactDebugChannel` methods,
which is now cleared up as well.
parent 1226b535
...@@ -792,7 +792,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -792,7 +792,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
// Before we kick off the render, we set the cache status back to it's initial state // Before we kick off the render, we set the cache status back to it's initial state
// in case a previous render bypassed the cache. // in case a previous render bypassed the cache.
if (setCacheStatus) { if (setCacheStatus) {
setCacheStatus('ready', htmlRequestId, requestId) setCacheStatus('ready', htmlRequestId)
} }
const result = await renderWithRestartOnCacheMissInDev( const result = await renderWithRestartOnCacheMissInDev(
...@@ -812,7 +812,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -812,7 +812,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
// Set cache status to bypass when specifically bypassing caches in dev // Set cache status to bypass when specifically bypassing caches in dev
if (setCacheStatus) { if (setCacheStatus) {
setCacheStatus('bypass', htmlRequestId, requestId) setCacheStatus('bypass', htmlRequestId)
} }
debugChannel = setReactDebugChannel && createDebugChannel() debugChannel = setReactDebugChannel && createDebugChannel()
...@@ -2613,7 +2613,7 @@ async function renderToStream( ...@@ -2613,7 +2613,7 @@ async function renderToStream(
// This lets the client know not to cache anything based on this render. // This lets the client know not to cache anything based on this render.
if (renderOpts.setCacheStatus) { if (renderOpts.setCacheStatus) {
// we know this is available when cacheComponents is enabled, but typeguard to be safe // we know this is available when cacheComponents is enabled, but typeguard to be safe
renderOpts.setCacheStatus('bypass', htmlRequestId, requestId) renderOpts.setCacheStatus('bypass', htmlRequestId)
} }
payload._bypassCachesInDev = createElement(WarnForBypassCachesInDev, { payload._bypassCachesInDev = createElement(WarnForBypassCachesInDev, {
route: workStore.route, route: workStore.route,
...@@ -3060,7 +3060,6 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -3060,7 +3060,6 @@ async function renderWithRestartOnCacheMissInDev(
const { const {
htmlRequestId, htmlRequestId,
renderOpts, renderOpts,
requestId,
componentMod: { componentMod: {
routeModule: { routeModule: {
userland: { loaderTree }, userland: { loaderTree },
...@@ -3203,7 +3202,7 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -3203,7 +3202,7 @@ async function renderWithRestartOnCacheMissInDev(
} }
if (process.env.NODE_ENV === 'development' && setCacheStatus) { if (process.env.NODE_ENV === 'development' && setCacheStatus) {
setCacheStatus('filling', htmlRequestId, requestId) setCacheStatus('filling', htmlRequestId)
} }
// Cache miss. We will use the initial render to fill caches, and discard its result. // Cache miss. We will use the initial render to fill caches, and discard its result.
...@@ -3276,7 +3275,7 @@ async function renderWithRestartOnCacheMissInDev( ...@@ -3276,7 +3275,7 @@ async function renderWithRestartOnCacheMissInDev(
) )
if (process.env.NODE_ENV === 'development' && setCacheStatus) { if (process.env.NODE_ENV === 'development' && setCacheStatus) {
setCacheStatus('filled', htmlRequestId, requestId) setCacheStatus('filled', htmlRequestId)
} }
return { return {
......
...@@ -109,11 +109,7 @@ export interface RenderOptsPartial { ...@@ -109,11 +109,7 @@ export interface RenderOptsPartial {
} }
isOnDemandRevalidate?: boolean isOnDemandRevalidate?: boolean
isPossibleServerAction?: boolean isPossibleServerAction?: boolean
setCacheStatus?: ( setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void
status: ServerCacheStatus,
htmlRequestId: string,
requestId: string
) => void
setIsrStatus?: (key: string, value: boolean | undefined) => void setIsrStatus?: (key: string, value: boolean | undefined) => void
setReactDebugChannel?: ( setReactDebugChannel?: (
debugChannel: { readable: ReadableStream<Uint8Array> }, debugChannel: { readable: ReadableStream<Uint8Array> },
......
...@@ -9,21 +9,16 @@ export interface ReactDebugChannelForBrowser { ...@@ -9,21 +9,16 @@ export interface ReactDebugChannelForBrowser {
// Might also get a writable stream as return channel in the future. // Might also get a writable stream as return channel in the future.
} }
const reactDebugChannelsByRequestId = new Map< const reactDebugChannelsByHtmlRequestId = new Map<
string, string,
ReactDebugChannelForBrowser ReactDebugChannelForBrowser
>() >()
export function connectReactDebugChannel( export function connectReactDebugChannel(
requestId: string, requestId: string,
debugChannel: ReactDebugChannelForBrowser,
sendToClient: (message: HmrMessageSentToBrowser) => void sendToClient: (message: HmrMessageSentToBrowser) => void
) { ) {
const debugChannel = reactDebugChannelsByRequestId.get(requestId)
if (!debugChannel) {
return
}
const reader = debugChannel.readable const reader = debugChannel.readable
.pipeThrough( .pipeThrough(
// We're sending the chunks in batches to reduce overhead in the browser. // We're sending the chunks in batches to reduce overhead in the browser.
...@@ -37,8 +32,6 @@ export function connectReactDebugChannel( ...@@ -37,8 +32,6 @@ export function connectReactDebugChannel(
requestId, requestId,
chunk: null, chunk: null,
}) })
reactDebugChannelsByRequestId.delete(requestId)
} }
const onError = (err: unknown) => { const onError = (err: unknown) => {
...@@ -63,13 +56,30 @@ export function connectReactDebugChannel( ...@@ -63,13 +56,30 @@ export function connectReactDebugChannel(
reader.read().then(progress, onError) reader.read().then(progress, onError)
} }
export function setReactDebugChannel( export function connectReactDebugChannelForHtmlRequest(
requestId: string, htmlRequestId: string,
sendToClient: (message: HmrMessageSentToBrowser) => void
) {
const debugChannel = reactDebugChannelsByHtmlRequestId.get(htmlRequestId)
if (!debugChannel) {
return
}
reactDebugChannelsByHtmlRequestId.delete(htmlRequestId)
connectReactDebugChannel(htmlRequestId, debugChannel, sendToClient)
}
export function setReactDebugChannelForHtmlRequest(
htmlRequestId: string,
debugChannel: ReactDebugChannelForBrowser debugChannel: ReactDebugChannelForBrowser
) { ) {
reactDebugChannelsByRequestId.set(requestId, debugChannel) // TODO: Clean up after a timeout, in case the client never connects, e.g.
// when CURL'ing the page, or loading the page with JavaScript disabled etc.
reactDebugChannelsByHtmlRequestId.set(htmlRequestId, debugChannel)
} }
export function deleteReactDebugChannel(requestId: string) { export function deleteReactDebugChannelForHtmlRequest(htmlRequestId: string) {
reactDebugChannelsByRequestId.delete(requestId) reactDebugChannelsByHtmlRequestId.delete(htmlRequestId)
} }
...@@ -71,8 +71,8 @@ function getStatsForSyncEvent( ...@@ -71,8 +71,8 @@ function getStatsForSyncEvent(
} }
export class WebpackHotMiddleware { export class WebpackHotMiddleware {
private clientsWithoutRequestId = new Set<ws>() private clientsWithoutHtmlRequestId = new Set<ws>()
private clientsByRequestId: Map<string, ws> = new Map() private clientsByHtmlRequestId: Map<string, ws> = new Map()
private closed = false private closed = false
private clientLatestStats: { ts: number; stats: webpack.Stats } | null = null private clientLatestStats: { ts: number; stats: webpack.Stats } | null = null
private middlewareLatestStats: { ts: number; stats: webpack.Stats } | null = private middlewareLatestStats: { ts: number; stats: webpack.Stats } | null =
...@@ -163,20 +163,20 @@ export class WebpackHotMiddleware { ...@@ -163,20 +163,20 @@ export class WebpackHotMiddleware {
* and we still want to show the client overlay with the error while * and we still want to show the client overlay with the error while
* the error page should be rendered just fine. * the error page should be rendered just fine.
*/ */
onHMR = (client: ws, requestId: string | null) => { onHMR = (client: ws, htmlRequestId: string | null) => {
if (this.closed) return if (this.closed) return
if (requestId) { if (htmlRequestId) {
this.clientsByRequestId.set(requestId, client) this.clientsByHtmlRequestId.set(htmlRequestId, client)
} else { } else {
this.clientsWithoutRequestId.add(client) this.clientsWithoutHtmlRequestId.add(client)
} }
client.addEventListener('close', () => { client.addEventListener('close', () => {
if (requestId) { if (htmlRequestId) {
this.clientsByRequestId.delete(requestId) this.clientsByHtmlRequestId.delete(htmlRequestId)
} else { } else {
this.clientsWithoutRequestId.delete(client) this.clientsWithoutHtmlRequestId.delete(client)
} }
}) })
...@@ -228,8 +228,8 @@ export class WebpackHotMiddleware { ...@@ -228,8 +228,8 @@ export class WebpackHotMiddleware {
}) })
} }
getClient = (requestId: string): ws | undefined => { getClient = (htmlRequestId: string): ws | undefined => {
return this.clientsByRequestId.get(requestId) return this.clientsByHtmlRequestId.get(htmlRequestId)
} }
publishToClient = (client: ws, message: HmrMessageSentToBrowser) => { publishToClient = (client: ws, message: HmrMessageSentToBrowser) => {
...@@ -251,8 +251,8 @@ export class WebpackHotMiddleware { ...@@ -251,8 +251,8 @@ export class WebpackHotMiddleware {
} }
for (const wsClient of [ for (const wsClient of [
...this.clientsWithoutRequestId, ...this.clientsWithoutHtmlRequestId,
...this.clientsByRequestId.values(), ...this.clientsByHtmlRequestId.values(),
]) { ]) {
this.publishToClient(wsClient, message) this.publishToClient(wsClient, message)
} }
...@@ -270,12 +270,12 @@ export class WebpackHotMiddleware { ...@@ -270,12 +270,12 @@ export class WebpackHotMiddleware {
// inferring it from the presence of a request ID. // inferring it from the presence of a request ID.
if (!this.config.cacheComponents) { if (!this.config.cacheComponents) {
for (const wsClient of this.clientsByRequestId.values()) { for (const wsClient of this.clientsByHtmlRequestId.values()) {
this.publishToClient(wsClient, message) this.publishToClient(wsClient, message)
} }
} }
for (const wsClient of this.clientsWithoutRequestId) { for (const wsClient of this.clientsWithoutHtmlRequestId) {
this.publishToClient(wsClient, message) this.publishToClient(wsClient, message)
} }
} }
...@@ -290,30 +290,35 @@ export class WebpackHotMiddleware { ...@@ -290,30 +290,35 @@ export class WebpackHotMiddleware {
this.closed = true this.closed = true
for (const wsClient of [ for (const wsClient of [
...this.clientsWithoutRequestId, ...this.clientsWithoutHtmlRequestId,
...this.clientsByRequestId.values(), ...this.clientsByHtmlRequestId.values(),
]) { ]) {
// it's okay to not cleanly close these websocket connections, this is dev // it's okay to not cleanly close these websocket connections, this is dev
wsClient.terminate() wsClient.terminate()
} }
this.clientsWithoutRequestId.clear() this.clientsWithoutHtmlRequestId.clear()
this.clientsByRequestId.clear() this.clientsByHtmlRequestId.clear()
} }
deleteClient = (client: ws, requestId: string | null) => { deleteClient = (client: ws, htmlRequestId: string | null) => {
if (requestId) { if (htmlRequestId) {
this.clientsByRequestId.delete(requestId) this.clientsByHtmlRequestId.delete(htmlRequestId)
} else { } else {
this.clientsWithoutRequestId.delete(client) this.clientsWithoutHtmlRequestId.delete(client)
} }
} }
hasClients = () => { hasClients = () => {
return this.clientsWithoutRequestId.size + this.clientsByRequestId.size > 0 return (
this.clientsWithoutHtmlRequestId.size + this.clientsByHtmlRequestId.size >
0
)
} }
getClientCount = () => { getClientCount = () => {
return this.clientsWithoutRequestId.size + this.clientsByRequestId.size return (
this.clientsWithoutHtmlRequestId.size + this.clientsByHtmlRequestId.size
)
} }
} }
...@@ -109,8 +109,9 @@ import { ...@@ -109,8 +109,9 @@ import {
} from '../../next-devtools/server/devtools-config-middleware' } from '../../next-devtools/server/devtools-config-middleware'
import { import {
connectReactDebugChannel, connectReactDebugChannel,
deleteReactDebugChannel, connectReactDebugChannelForHtmlRequest,
setReactDebugChannel, deleteReactDebugChannelForHtmlRequest,
setReactDebugChannelForHtmlRequest,
} from './debug-channel' } from './debug-channel'
import { import {
getVersionInfo, getVersionInfo,
...@@ -439,9 +440,9 @@ export async function createHotReloaderTurbopack( ...@@ -439,9 +440,9 @@ export async function createHotReloaderTurbopack(
let hmrEventHappened = false let hmrEventHappened = false
let hmrHash = 0 let hmrHash = 0
const clientsWithoutRequestId = new Set<ws>() const clientsWithoutHtmlRequestId = new Set<ws>()
const clientsByRequestId = new Map<string, ws>() const clientsByHtmlRequestId = new Map<string, ws>()
const cacheStatusesByRequestId = new Map<string, ServerCacheStatus>() const cacheStatusesByHtmlRequestId = new Map<string, ServerCacheStatus>()
const clientStates = new WeakMap<ws, ClientState>() const clientStates = new WeakMap<ws, ClientState>()
function sendToClient(client: ws, message: HmrMessageSentToBrowser) { function sendToClient(client: ws, message: HmrMessageSentToBrowser) {
...@@ -465,8 +466,8 @@ export async function createHotReloaderTurbopack( ...@@ -465,8 +466,8 @@ export async function createHotReloaderTurbopack(
} }
for (const client of [ for (const client of [
...clientsWithoutRequestId, ...clientsWithoutHtmlRequestId,
...clientsByRequestId.values(), ...clientsByHtmlRequestId.values(),
]) { ]) {
const state = clientStates.get(client) const state = clientStates.get(client)
if (!state) { if (!state) {
...@@ -501,8 +502,8 @@ export async function createHotReloaderTurbopack( ...@@ -501,8 +502,8 @@ export async function createHotReloaderTurbopack(
const sendHmr: SendHmr = (id: string, message: HmrMessageSentToBrowser) => { const sendHmr: SendHmr = (id: string, message: HmrMessageSentToBrowser) => {
for (const client of [ for (const client of [
...clientsWithoutRequestId, ...clientsWithoutHtmlRequestId,
...clientsByRequestId.values(), ...clientsByHtmlRequestId.values(),
]) { ]) {
clientStates.get(client)?.messages.set(id, message) clientStates.get(client)?.messages.set(id, message)
} }
...@@ -519,8 +520,8 @@ export async function createHotReloaderTurbopack( ...@@ -519,8 +520,8 @@ export async function createHotReloaderTurbopack(
payload.issues = [] payload.issues = []
for (const client of [ for (const client of [
...clientsWithoutRequestId, ...clientsWithoutHtmlRequestId,
...clientsByRequestId.values(), ...clientsByHtmlRequestId.values(),
]) { ]) {
clientStates.get(client)?.turbopackUpdates.push(payload) clientStates.get(client)?.turbopackUpdates.push(payload)
} }
...@@ -683,7 +684,10 @@ export async function createHotReloaderTurbopack( ...@@ -683,7 +684,10 @@ export async function createHotReloaderTurbopack(
dev: { dev: {
assetMapper, assetMapper,
changeSubscriptions, changeSubscriptions,
clients: [...clientsWithoutRequestId, ...clientsByRequestId.values()], clients: [
...clientsWithoutHtmlRequestId,
...clientsByHtmlRequestId.values(),
],
clientStates, clientStates,
serverFields, serverFields,
...@@ -779,7 +783,7 @@ export async function createHotReloaderTurbopack( ...@@ -779,7 +783,7 @@ export async function createHotReloaderTurbopack(
distDir, distDir,
sendHmrMessage: (message) => hotReloader.send(message), sendHmrMessage: (message) => hotReloader.send(message),
getActiveConnectionCount: () => getActiveConnectionCount: () =>
clientsWithoutRequestId.size + clientsByRequestId.size, clientsWithoutHtmlRequestId.size + clientsByHtmlRequestId.size,
getDevServerUrl: () => process.env.__NEXT_PRIVATE_ORIGIN, getDevServerUrl: () => process.env.__NEXT_PRIVATE_ORIGIN,
}), }),
] ]
...@@ -877,7 +881,7 @@ export async function createHotReloaderTurbopack( ...@@ -877,7 +881,7 @@ export async function createHotReloaderTurbopack(
const clientIssues: EntryIssuesMap = new Map() const clientIssues: EntryIssuesMap = new Map()
const subscriptions: Map<string, AsyncIterator<any>> = new Map() const subscriptions: Map<string, AsyncIterator<any>> = new Map()
const requestId = req.url const htmlRequestId = req.url
? new URL(req.url, 'http://n').searchParams.get('id') ? new URL(req.url, 'http://n').searchParams.get('id')
: null : null
...@@ -886,24 +890,24 @@ export async function createHotReloaderTurbopack( ...@@ -886,24 +890,24 @@ export async function createHotReloaderTurbopack(
// Router clients are also considered legacy clients. TODO: Maybe mark // Router clients are also considered legacy clients. TODO: Maybe mark
// clients as App Router / Pages Router clients explicitly, instead of // clients as App Router / Pages Router clients explicitly, instead of
// inferring it from the presence of a request ID. // inferring it from the presence of a request ID.
if (requestId) { if (htmlRequestId) {
clientsByRequestId.set(requestId, client) clientsByHtmlRequestId.set(htmlRequestId, client)
const enableCacheComponents = nextConfig.cacheComponents const enableCacheComponents = nextConfig.cacheComponents
if (enableCacheComponents) { if (enableCacheComponents) {
onUpgrade(client, { isLegacyClient: false }) onUpgrade(client, { isLegacyClient: false })
const cacheStatus = cacheStatusesByRequestId.get(requestId) const cacheStatus = cacheStatusesByHtmlRequestId.get(htmlRequestId)
if (cacheStatus !== undefined) { if (cacheStatus !== undefined) {
sendToClient(client, { sendToClient(client, {
type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR, type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR,
state: cacheStatus, state: cacheStatus,
}) })
cacheStatusesByRequestId.delete(requestId) cacheStatusesByHtmlRequestId.delete(htmlRequestId)
} }
} else { } else {
onUpgrade(client, { isLegacyClient: true }) onUpgrade(client, { isLegacyClient: true })
} }
} else { } else {
clientsWithoutRequestId.add(client) clientsWithoutHtmlRequestId.add(client)
onUpgrade(client, { isLegacyClient: true }) onUpgrade(client, { isLegacyClient: true })
} }
...@@ -921,11 +925,11 @@ export async function createHotReloaderTurbopack( ...@@ -921,11 +925,11 @@ export async function createHotReloaderTurbopack(
} }
clientStates.delete(client) clientStates.delete(client)
if (requestId) { if (htmlRequestId) {
clientsByRequestId.delete(requestId) clientsByHtmlRequestId.delete(htmlRequestId)
deleteReactDebugChannel(requestId) deleteReactDebugChannelForHtmlRequest(htmlRequestId)
} else { } else {
clientsWithoutRequestId.delete(client) clientsWithoutHtmlRequestId.delete(client)
} }
}) })
...@@ -1094,8 +1098,11 @@ export async function createHotReloaderTurbopack( ...@@ -1094,8 +1098,11 @@ export async function createHotReloaderTurbopack(
sendToClient(client, syncMessage) sendToClient(client, syncMessage)
if (requestId) { if (htmlRequestId) {
connectReactDebugChannel(requestId, sendToClient.bind(null, client)) connectReactDebugChannelForHtmlRequest(
htmlRequestId,
sendToClient.bind(null, client)
)
} }
})() })()
}) })
...@@ -1105,8 +1112,8 @@ export async function createHotReloaderTurbopack( ...@@ -1105,8 +1112,8 @@ export async function createHotReloaderTurbopack(
const payload = JSON.stringify(action) const payload = JSON.stringify(action)
for (const client of [ for (const client of [
...clientsWithoutRequestId, ...clientsWithoutHtmlRequestId,
...clientsByRequestId.values(), ...clientsByHtmlRequestId.values(),
]) { ]) {
client.send(payload) client.send(payload)
} }
...@@ -1122,23 +1129,19 @@ export async function createHotReloaderTurbopack( ...@@ -1122,23 +1129,19 @@ export async function createHotReloaderTurbopack(
// inferring it from the presence of a request ID. // inferring it from the presence of a request ID.
if (!nextConfig.cacheComponents) { if (!nextConfig.cacheComponents) {
for (const client of clientsByRequestId.values()) { for (const client of clientsByHtmlRequestId.values()) {
client.send(payload) client.send(payload)
} }
} }
for (const client of clientsWithoutRequestId) { for (const client of clientsWithoutHtmlRequestId) {
client.send(payload) client.send(payload)
} }
}, },
setCacheStatus( setCacheStatus(status: ServerCacheStatus, htmlRequestId: string): void {
status: ServerCacheStatus,
htmlRequestId: string,
requestId: string
): void {
// Legacy clients don't have Cache Components. // Legacy clients don't have Cache Components.
const client = clientsByRequestId.get(htmlRequestId) const client = clientsByHtmlRequestId.get(htmlRequestId)
if (client !== undefined) { if (client !== undefined) {
sendToClient(client, { sendToClient(client, {
type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR, type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR,
...@@ -1147,20 +1150,37 @@ export async function createHotReloaderTurbopack( ...@@ -1147,20 +1150,37 @@ export async function createHotReloaderTurbopack(
} else { } else {
// If the client is not connected, store the status so that we can send it // If the client is not connected, store the status so that we can send it
// when the client connects. // when the client connects.
cacheStatusesByRequestId.set(requestId, status) cacheStatusesByHtmlRequestId.set(htmlRequestId, status)
} }
}, },
setReactDebugChannel(debugChannel, htmlRequestId, requestId) { setReactDebugChannel(debugChannel, htmlRequestId, requestId) {
// Store the debug channel, regardless of whether the client is connected. const client = clientsByHtmlRequestId.get(htmlRequestId)
setReactDebugChannel(requestId, debugChannel)
if (htmlRequestId === requestId) {
// If the client is connected, we can connect the debug channel // The debug channel is for the HTML request.
// immediately. Otherwise, we'll do that when the client connects. if (client) {
const client = clientsByRequestId.get(htmlRequestId) // If the client is connected, we can connect the debug channel for
// the HTML request immediately.
if (client) { connectReactDebugChannel(
connectReactDebugChannel(requestId, sendToClient.bind(null, client)) htmlRequestId,
debugChannel,
sendToClient.bind(null, client)
)
} else {
// Otherwise, we'll do that when the client connects and just store
// the debug channel.
setReactDebugChannelForHtmlRequest(htmlRequestId, debugChannel)
}
} else if (client) {
// The debug channel is for a subsequent request (e.g. client-side
// navigation for server function call). If the client is not connected
// anymore, we don't need to connect the debug channel.
connectReactDebugChannel(
requestId,
debugChannel,
sendToClient.bind(null, client)
)
} }
}, },
...@@ -1400,14 +1420,14 @@ export async function createHotReloaderTurbopack( ...@@ -1400,14 +1420,14 @@ export async function createHotReloaderTurbopack(
recordMcpTelemetry(opts.telemetry) recordMcpTelemetry(opts.telemetry)
for (const wsClient of [ for (const wsClient of [
...clientsWithoutRequestId, ...clientsWithoutHtmlRequestId,
...clientsByRequestId.values(), ...clientsByHtmlRequestId.values(),
]) { ]) {
// it's okay to not cleanly close these websocket connections, this is dev // it's okay to not cleanly close these websocket connections, this is dev
wsClient.terminate() wsClient.terminate()
} }
clientsWithoutRequestId.clear() clientsWithoutHtmlRequestId.clear()
clientsByRequestId.clear() clientsByHtmlRequestId.clear()
}, },
} }
...@@ -1467,8 +1487,8 @@ export async function createHotReloaderTurbopack( ...@@ -1467,8 +1487,8 @@ export async function createHotReloaderTurbopack(
addErrors(errors, currentEntryIssues) addErrors(errors, currentEntryIssues)
for (const client of [ for (const client of [
...clientsWithoutRequestId, ...clientsWithoutHtmlRequestId,
...clientsByRequestId.values(), ...clientsByHtmlRequestId.values(),
]) { ]) {
const state = clientStates.get(client) const state = clientStates.get(client)
if (!state) { if (!state) {
......
...@@ -229,11 +229,7 @@ export interface NextJsHotReloaderInterface { ...@@ -229,11 +229,7 @@ export interface NextJsHotReloaderInterface {
* and App Router clients that don't have Cache Components enabled. * and App Router clients that don't have Cache Components enabled.
*/ */
sendToLegacyClients(action: HmrMessageSentToBrowser): void sendToLegacyClients(action: HmrMessageSentToBrowser): void
setCacheStatus( setCacheStatus(status: ServerCacheStatus, htmlRequestId: string): void
status: ServerCacheStatus,
htmlRequestId: string,
requestId: string
): void
setReactDebugChannel( setReactDebugChannel(
debugChannel: ReactDebugChannelForBrowser, debugChannel: ReactDebugChannelForBrowser,
htmlRequestId: string, htmlRequestId: string,
......
...@@ -99,8 +99,9 @@ import { ...@@ -99,8 +99,9 @@ import {
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { import {
connectReactDebugChannel, connectReactDebugChannel,
deleteReactDebugChannel, connectReactDebugChannelForHtmlRequest,
setReactDebugChannel, deleteReactDebugChannelForHtmlRequest,
setReactDebugChannelForHtmlRequest,
type ReactDebugChannelForBrowser, type ReactDebugChannelForBrowser,
} from './debug-channel' } from './debug-channel'
import { import {
...@@ -444,7 +445,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -444,7 +445,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
) => void ) => void
) { ) {
wsServer.handleUpgrade(req, req.socket, head, (client) => { wsServer.handleUpgrade(req, req.socket, head, (client) => {
const requestId = req.url const htmlRequestId = req.url
? new URL(req.url, 'http://n').searchParams.get('id') ? new URL(req.url, 'http://n').searchParams.get('id')
: null : null
...@@ -452,7 +453,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -452,7 +453,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
throw new InvariantError('Did not start HotReloaderWebpack.') throw new InvariantError('Did not start HotReloaderWebpack.')
} }
this.webpackHotMiddleware.onHMR(client, requestId) this.webpackHotMiddleware.onHMR(client, htmlRequestId)
this.onDemandEntries?.onHMR(client, () => this.hmrServerError) this.onDemandEntries?.onHMR(client, () => this.hmrServerError)
const enableCacheComponents = this.config.cacheComponents const enableCacheComponents = this.config.cacheComponents
...@@ -461,7 +462,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -461,7 +462,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
// Router clients are also considered legacy clients. TODO: Maybe mark // Router clients are also considered legacy clients. TODO: Maybe mark
// clients as App Router / Pages Router clients explicitly, instead of // clients as App Router / Pages Router clients explicitly, instead of
// inferring it from the presence of a request ID. // inferring it from the presence of a request ID.
const isLegacyClient = !requestId || !enableCacheComponents const isLegacyClient = !htmlRequestId || !enableCacheComponents
callback(client, { isLegacyClient }) callback(client, { isLegacyClient })
...@@ -639,28 +640,28 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -639,28 +640,28 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
} }
}) })
if (requestId) { if (htmlRequestId) {
connectReactDebugChannel( connectReactDebugChannelForHtmlRequest(
requestId, htmlRequestId,
this.sendToClient.bind(this, client) this.sendToClient.bind(this, client)
) )
if (enableCacheComponents) { if (enableCacheComponents) {
const status = this.cacheStatusesByRequestId.get(requestId) const status = this.cacheStatusesByRequestId.get(htmlRequestId)
if (status) { if (status) {
this.sendToClient(client, { this.sendToClient(client, {
type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR, type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR,
state: status, state: status,
}) })
this.cacheStatusesByRequestId.delete(requestId) this.cacheStatusesByRequestId.delete(htmlRequestId)
} }
} }
} }
client.on('close', () => { client.on('close', () => {
this.webpackHotMiddleware?.deleteClient(client, requestId) this.webpackHotMiddleware?.deleteClient(client, htmlRequestId)
if (requestId) { if (htmlRequestId) {
deleteReactDebugChannel(requestId) deleteReactDebugChannelForHtmlRequest(htmlRequestId)
} }
}) })
}) })
...@@ -1748,8 +1749,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1748,8 +1749,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
public setCacheStatus( public setCacheStatus(
status: ServerCacheStatus, status: ServerCacheStatus,
htmlRequestId: string, htmlRequestId: string
requestId: string
): void { ): void {
const client = this.webpackHotMiddleware?.getClient(htmlRequestId) const client = this.webpackHotMiddleware?.getClient(htmlRequestId)
if (client !== undefined) { if (client !== undefined) {
...@@ -1760,7 +1760,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1760,7 +1760,7 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
} else { } else {
// If the client is not connected, store the status so that we can send it // If the client is not connected, store the status so that we can send it
// when the client connects. // when the client connects.
this.cacheStatusesByRequestId.set(requestId, status) this.cacheStatusesByRequestId.set(htmlRequestId, status)
} }
} }
...@@ -1769,15 +1769,32 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -1769,15 +1769,32 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
htmlRequestId: string, htmlRequestId: string,
requestId: string requestId: string
): void { ): void {
// Store the debug channel, regardless of whether the client is connected.
setReactDebugChannel(requestId, debugChannel)
// If the client is connected, we can connect the debug channel immediately.
// Otherwise, we'll do that when the client connects.
const client = this.webpackHotMiddleware?.getClient(htmlRequestId) const client = this.webpackHotMiddleware?.getClient(htmlRequestId)
if (client) { if (htmlRequestId === requestId) {
connectReactDebugChannel(requestId, this.sendToClient.bind(this, client)) // The debug channel is for the HTML request.
if (client) {
// If the client is connected, we can connect the debug channel for
// the HTML request immediately.
connectReactDebugChannel(
htmlRequestId,
debugChannel,
this.sendToClient.bind(this, client)
)
} else {
// Otherwise, we'll do that when the client connects and just store
// the debug channel.
setReactDebugChannelForHtmlRequest(htmlRequestId, debugChannel)
}
} else if (client) {
// The debug channel is for a subsequent request (e.g. client-side
// navigation for server function call). If the client is not connected
// anymore, we don't need to connect the debug channel.
connectReactDebugChannel(
requestId,
debugChannel,
this.sendToClient.bind(this, client)
)
} }
} }
......
...@@ -98,10 +98,9 @@ export class DevBundlerService { ...@@ -98,10 +98,9 @@ export class DevBundlerService {
public setCacheStatus( public setCacheStatus(
status: ServerCacheStatus, status: ServerCacheStatus,
htmlRequestId: string, htmlRequestId: string
requestId: string
): void { ): void {
this.bundler.hotReloader.setCacheStatus(status, htmlRequestId, requestId) this.bundler.hotReloader.setCacheStatus(status, htmlRequestId)
} }
public setIsrStatus(key: string, value: boolean | undefined) { public setIsrStatus(key: string, value: boolean | undefined) {
......
...@@ -44,11 +44,7 @@ export type RouterServerContext = Record< ...@@ -44,11 +44,7 @@ export type RouterServerContext = Record<
htmlRequestId: string, htmlRequestId: string,
requestId: string requestId: string
) => void ) => void
setCacheStatus?: ( setCacheStatus?: (status: ServerCacheStatus, htmlRequestId: string) => void
status: ServerCacheStatus,
htmlRequestId: string,
requestId: string
) => void
} }
> >
......
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