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

Fix demand-driven server HMR state

Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent da4c7bd6
......@@ -39,6 +39,7 @@ import {
} from './middleware-turbopack'
import { PageNotFoundError } from '../../shared/lib/utils'
import { debounce } from '../utils'
import { clearManifestCache } from '../load-manifest.external'
import { deleteCache } from './require-cache'
import {
dropDevValidationWorker,
......@@ -182,17 +183,57 @@ declare global {
var __turbopack_server_hmr_handlers__: Map<string, unknown> | undefined
}
/**
* Collects the output chunk paths touched by a partial HMR update. Both
* single-chunk `EcmascriptMergedUpdate`s and `ChunkListUpdate`s (which nest
* per-chunk deltas inside `merged`) are flattened so the manifest cache can be
* invalidated for every affected chunk after a successful apply.
*/
function collectUpdatedChunkPaths(
instruction: NodeJsPartialHmrUpdate['instruction']
): string[] {
const paths = new Set<string>()
if (instruction.type === 'EcmascriptMergedUpdate') {
for (const chunkPath of Object.keys(instruction.chunks ?? {})) {
paths.add(chunkPath)
}
} else if (instruction.type === 'ChunkListUpdate') {
for (const chunkPath of Object.keys(instruction.chunks ?? {})) {
paths.add(chunkPath)
}
for (const merged of instruction.merged ?? []) {
for (const chunkPath of Object.keys(merged.chunks ?? {})) {
paths.add(chunkPath)
}
}
} else {
throw new Error(
`[Server HMR] unreachable: unknown HMR instruction type ${(instruction as { type: string }).type}`
)
}
return Array.from(paths)
}
function setupServerHmr(
project: Project,
reEvaluateAllModulesExpensive: () => Promise<void>
{
reEvaluateAllModulesExpensive,
onApplied,
}: {
reEvaluateAllModulesExpensive: () => Promise<void>
onApplied: (chunkPaths: string[]) => void | Promise<void>
}
) {
let pending = Promise.resolve()
let version: ServerHmrVersion | undefined
// Each pull snapshots only the requested endpoint's entries. Keep independent
// baselines so building one route does not discard another route's version.
const versions = new Map<string, ServerHmrVersion>()
let needsReEvaluation = false
async function recover() {
try {
await reEvaluateAllModulesExpensive()
versions.clear()
needsReEvaluation = false
} catch (error) {
console.error('[Server HMR] Re-evaluating modules failed:', error)
......@@ -207,8 +248,14 @@ function setupServerHmr(
}
try {
const update = await project.getServerHmrUpdate(version, entryPaths)
version = update.version ?? version
const versionKey = [...entryPaths].sort().join('\0')
const update = await project.getServerHmrUpdate(
versions.get(versionKey),
entryPaths
)
if (update.version) {
versions.set(versionKey, update.version)
}
switch (update.kind) {
case 'none':
return
......@@ -227,6 +274,13 @@ function setupServerHmr(
type: 'apply',
update: payload,
})
const updatedChunkPaths = collectUpdatedChunkPaths(
update.instruction
)
if (updatedChunkPaths.length > 0) {
await onApplied(updatedChunkPaths)
}
return
} catch {}
}
......@@ -733,10 +787,27 @@ export async function createHotReloaderTurbopack(
dropDevValidationWorker()
}
const applyServerHmrUpdate = setupServerHmr(
project,
reEvaluateAllModulesExpensive
)
const applyServerHmrUpdate = setupServerHmr(project, {
reEvaluateAllModulesExpensive,
onApplied: (chunkPaths: string[]) => {
// The runtime patched these chunks in place, so keep require.cache but
// clear evalManifest()'s shared cache before this request renders.
const manifestPaths = chunkPaths.map((chunkPath) =>
join(distDir, chunkPath)
)
for (const manifestPath of manifestPaths) {
clearManifestCache(manifestPath)
}
// The validation worker maintains its own manifest cache and must observe
// the same non-evicting invalidation as the request-serving runtime.
mirrorModuleStateToDevValidationWorker({
type: 'invalidate',
filePaths: manifestPaths,
evictModules: false,
})
},
})
const buildingIds = new Set()
......
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