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 { ...@@ -39,6 +39,7 @@ import {
} from './middleware-turbopack' } from './middleware-turbopack'
import { PageNotFoundError } from '../../shared/lib/utils' import { PageNotFoundError } from '../../shared/lib/utils'
import { debounce } from '../utils' import { debounce } from '../utils'
import { clearManifestCache } from '../load-manifest.external'
import { deleteCache } from './require-cache' import { deleteCache } from './require-cache'
import { import {
dropDevValidationWorker, dropDevValidationWorker,
...@@ -182,17 +183,57 @@ declare global { ...@@ -182,17 +183,57 @@ declare global {
var __turbopack_server_hmr_handlers__: Map<string, unknown> | undefined 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( function setupServerHmr(
project: Project, project: Project,
{
reEvaluateAllModulesExpensive,
onApplied,
}: {
reEvaluateAllModulesExpensive: () => Promise<void> reEvaluateAllModulesExpensive: () => Promise<void>
onApplied: (chunkPaths: string[]) => void | Promise<void>
}
) { ) {
let pending = Promise.resolve() 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 let needsReEvaluation = false
async function recover() { async function recover() {
try { try {
await reEvaluateAllModulesExpensive() await reEvaluateAllModulesExpensive()
versions.clear()
needsReEvaluation = false needsReEvaluation = false
} catch (error) { } catch (error) {
console.error('[Server HMR] Re-evaluating modules failed:', error) console.error('[Server HMR] Re-evaluating modules failed:', error)
...@@ -207,8 +248,14 @@ function setupServerHmr( ...@@ -207,8 +248,14 @@ function setupServerHmr(
} }
try { try {
const update = await project.getServerHmrUpdate(version, entryPaths) const versionKey = [...entryPaths].sort().join('\0')
version = update.version ?? version const update = await project.getServerHmrUpdate(
versions.get(versionKey),
entryPaths
)
if (update.version) {
versions.set(versionKey, update.version)
}
switch (update.kind) { switch (update.kind) {
case 'none': case 'none':
return return
...@@ -227,6 +274,13 @@ function setupServerHmr( ...@@ -227,6 +274,13 @@ function setupServerHmr(
type: 'apply', type: 'apply',
update: payload, update: payload,
}) })
const updatedChunkPaths = collectUpdatedChunkPaths(
update.instruction
)
if (updatedChunkPaths.length > 0) {
await onApplied(updatedChunkPaths)
}
return return
} catch {} } catch {}
} }
...@@ -733,10 +787,27 @@ export async function createHotReloaderTurbopack( ...@@ -733,10 +787,27 @@ export async function createHotReloaderTurbopack(
dropDevValidationWorker() dropDevValidationWorker()
} }
const applyServerHmrUpdate = setupServerHmr( const applyServerHmrUpdate = setupServerHmr(project, {
project, reEvaluateAllModulesExpensive,
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() 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