Unverified Commit 05aeb5bb authored by vercel[bot]'s avatar vercel[bot] Committed by GitHub

Fix route HMR reactivation ordering

Co-Authored-By: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
parent 2dbbe886
......@@ -33,6 +33,8 @@ pub fn is_entry_chunk_list_content(content: ResolvedVc<Box<dyn VersionedContent>
pub struct AggregateHmrVersion {
#[turbo_tasks(trace_ignore)]
pub versions: FxIndexMap<RcStr, TraitRef<Box<dyn Version>>>,
/// Monotonic token identifying the active-route aggregate transition.
pub reactivation_epoch: u32,
}
#[turbo_tasks::value_impl]
......@@ -54,6 +56,7 @@ impl Version for AggregateHmrVersion {
.await?;
let mut hasher = Xxh3Hash64Hasher::new();
hasher.write_value(self.reactivation_epoch);
hasher.write_value(entries.len());
for (path, id) in entries {
hasher.write_value(path.as_str());
......@@ -71,15 +74,24 @@ impl AggregateHmrVersion {
// An empty `versions` map behaves the same as `NotFoundVersion` would in
// `diff_chunks_against`, so no special case is needed here.
let snapshot = map.hmr_chunks_in_path(root).await?;
Ok(Vc::upcast(Self::from_chunks(&snapshot.active).await?))
Ok(Vc::upcast(
Self::from_chunks(&snapshot.active, snapshot.reactivation_epoch).await?,
))
}
pub async fn from_chunks(chunks: &[HmrChunkWithContent]) -> Result<Vc<Self>> {
pub async fn from_chunks(
chunks: &[HmrChunkWithContent],
reactivation_epoch: u32,
) -> Result<Vc<Self>> {
let versions = Self::versions_from_chunks(chunks)
.await?
.into_iter()
.collect();
Ok(Self { versions }.cell())
Ok(Self {
versions,
reactivation_epoch,
}
.cell())
}
/// Builds the next aggregate version while retaining the last version of
......@@ -89,6 +101,7 @@ impl AggregateHmrVersion {
pub async fn from_chunks_with_previous(
chunks: &[HmrChunkWithContent],
inactive_paths: &FxHashSet<RcStr>,
reactivation_epoch: u32,
previous: Vc<VersionState>,
) -> Result<Vc<Self>> {
let mut versions = Self::versions_from_chunks(chunks).await?;
......@@ -110,10 +123,29 @@ impl AggregateHmrVersion {
versions.sort_by(|(a, _), (b, _)| a.cmp(b));
Ok(Self {
versions: versions.into_iter().collect(),
reactivation_epoch,
}
.cell())
}
pub async fn reactivation_epoch_from_state(state: Vc<VersionState>) -> Result<Option<u32>> {
let version = state.get().to_resolved().await?;
let Some(version) = ResolvedVc::try_downcast_type::<AggregateHmrVersion>(version) else {
return Ok(None);
};
Ok(Some(version.await?.reactivation_epoch))
}
pub async fn reactivation_epoch_from_version(
version: TraitRef<Box<dyn Version>>,
) -> Result<Option<u32>> {
let version = TraitRef::cell(version).to_resolved().await?;
let Some(version) = ResolvedVc::try_downcast_type::<AggregateHmrVersion>(version) else {
return Ok(None);
};
Ok(Some(version.await?.reactivation_epoch))
}
async fn versions_from_chunks(
chunks: &[HmrChunkWithContent],
) -> Result<Vec<(RcStr, TraitRef<Box<dyn Version>>)>> {
......
......@@ -40,7 +40,7 @@ use tracing::{Instrument, field::Empty};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{
Completion, Completions, FxIndexMap, NonLocalValue, OperationValue, OperationVc, ReadRef,
ResolvedVc, State, TransientInstance, TryFlatJoinIterExt, TryJoinIterExt, Vc,
ResolvedVc, State, TraitRef, TransientInstance, TryFlatJoinIterExt, TryJoinIterExt, Vc,
debug::ValueDebugFormat, fxindexmap, trace::TraceRawVcs,
};
use turbo_tasks_env::{EnvMap, ProcessEnv};
......@@ -211,6 +211,13 @@ impl std::str::FromStr for HmrTarget {
}
}
/// Extracts the route-reactivation acknowledgement carried by an aggregate HMR version.
pub async fn aggregate_hmr_reactivation_epoch(
version: TraitRef<Box<dyn Version>>,
) -> Result<Option<u32>> {
AggregateHmrVersion::reactivation_epoch_from_version(version).await
}
/// Pre-converted route keys from debug build paths for O(1) lookups.
struct DebugBuildPathsRouteKeys {
app: FxHashSet<RcStr>,
......@@ -820,7 +827,9 @@ impl ProjectContainer {
chunk_names: Vec<RcStr>,
target: HmrTarget,
active: bool,
) -> Result<()> {
reactivation_source_paths: Vec<RcStr>,
advance_reactivation_epoch: bool,
) -> Result<u32> {
let project_op = project_operation(self);
let project = project_op.resolve().strongly_consistent().await?;
let project_ref = project_op.read_strongly_consistent().await?;
......@@ -830,20 +839,36 @@ impl ProjectContainer {
let root = project_hmr_root_path_operation(project, target)
.read_strongly_consistent()
.await?;
let project_fs = project_fs_operation(project)
.read_strongly_consistent()
.await?;
let project_fs_op = project_fs_operation(project);
let project_fs_vc = project_fs_op.resolve().strongly_consistent().await?;
let project_fs = project_fs_op.read_strongly_consistent().await?;
let paths = chunk_names
.into_iter()
.map(|chunk_name| root.join(&chunk_name))
.collect::<Result<Vec<_>>>()?;
let reactivation_source_paths = reactivation_source_paths
.into_iter()
.map(|path| {
project_fs
.try_from_sys_path(project_fs_vc, Path::new(path.as_str()), None)
.map(|path| project_fs.to_sys_path_raw(&path))
.with_context(|| {
format!("source path is outside the project filesystem: {path}")
})
})
.collect::<Result<Vec<_>>>()?;
versioned_content_map_operation(map)
.read_strongly_consistent()
.await?
.set_hmr_chunks_active(paths, active, &project_fs)
.await?;
Ok(())
.set_hmr_chunks_active(
paths,
active,
&project_fs,
reactivation_source_paths,
advance_reactivation_epoch,
)
.await
}
/// Permanently removes output entry chunks for routes deleted during a dev
......@@ -2721,15 +2746,16 @@ impl Project {
let root = self.aggregate_hmr_root_path(target).owned().await?;
let chunk_snapshot = map.hmr_chunks_in_path(&root).await?;
// No chunks to diff yet (e.g. before any endpoints have been written).
if chunk_snapshot.active.is_empty() {
return Ok(Update::None.cell());
}
// Build `to` up front so we can return it on every escape hatch below.
// Build `to` up front so even an empty active set can carry a route
// reactivation acknowledgement to the server runtime.
let from_reactivation_epoch =
AggregateHmrVersion::reactivation_epoch_from_state(from).await?;
let reactivation_epoch_changed =
from_reactivation_epoch != Some(chunk_snapshot.reactivation_epoch);
let to_aggregate = AggregateHmrVersion::from_chunks_with_previous(
&chunk_snapshot.active,
&chunk_snapshot.inactive_paths,
chunk_snapshot.reactivation_epoch,
from,
)
.await?;
......@@ -2765,7 +2791,7 @@ impl Project {
}
}
if builder.is_empty() && !has_new_chunks {
if builder.is_empty() && !has_new_chunks && !reactivation_epoch_changed {
return Ok(Update::None.cell());
}
......
use anyhow::Result;
use std::path::PathBuf;
use anyhow::{Result, bail};
use bincode::{Decode, Encode};
use next_core::emit_assets;
use rustc_hash::{FxHashMap, FxHashSet};
......@@ -116,6 +118,8 @@ unsafe impl OperationValue for InactiveOutputOperations {}
pub struct HmrChunkSnapshot {
pub active: Vec<HmrChunkWithContent>,
pub inactive_paths: FxHashSet<RcStr>,
/// Monotonic acknowledgement token for aggregate-HMR route reactivation.
pub reactivation_epoch: u32,
}
// TODO: Ideally this structure is never persisted, so new sessions start from scratch and don't
......@@ -137,6 +141,9 @@ pub struct VersionedContentMap {
/// changes do not invalidate or rebuild the aggregate subscription until the
/// entry becomes active again.
inactive_hmr_paths: State<InactiveHmrPaths>,
/// Advances after a route rejoins the aggregate HMR working set. The token is
/// carried by the aggregate version so JS can wait for that exact transition.
reactivation_epoch: State<u32>,
}
impl VersionedContentMap {
......@@ -149,6 +156,7 @@ impl VersionedContentMap {
inactive_output_operations: State::new(InactiveOutputOperations::default()),
removed_hmr_paths: State::new(InactiveHmrPaths::default()),
inactive_hmr_paths: State::new(InactiveHmrPaths::default()),
reactivation_epoch: State::new(0),
}
.resolved_cell()
}
......@@ -174,7 +182,11 @@ impl VersionedContentMap {
// awaits below, so snapshot the keys and release it. Keep the inactive
// paths from the same snapshot: only those paths may retain their prior
// aggregate version when absent from the active chunks below.
let (paths, inactive_paths): (Vec<FileSystemPath>, FxHashSet<RcStr>) = {
let (paths, inactive_paths, reactivation_epoch): (
Vec<FileSystemPath>,
FxHashSet<RcStr>,
u32,
) = {
let map = &this.map_path_to_op.get().0;
let inactive_hmr_paths = &this.inactive_hmr_paths.get().0;
let removed_hmr_paths = &this.removed_hmr_paths.get().0;
......@@ -189,6 +201,7 @@ impl VersionedContentMap {
.iter()
.filter_map(|path| root.get_path_to(path).map(RcStr::from))
.collect(),
*this.reactivation_epoch.get(),
)
};
......@@ -227,6 +240,7 @@ impl VersionedContentMap {
Ok(HmrChunkSnapshot {
active: chunks,
inactive_paths,
reactivation_epoch,
})
}
......@@ -244,7 +258,12 @@ impl VersionedContentMap {
paths: impl IntoIterator<Item = FileSystemPath>,
active: bool,
project_fs: &DiskFileSystem,
) -> Result<()> {
reactivation_source_paths: Vec<PathBuf>,
advance_reactivation_epoch: bool,
) -> Result<u32> {
if advance_reactivation_epoch && !active {
bail!("cannot acknowledge an inactive HMR chunk");
}
let paths = paths.into_iter().collect::<Vec<_>>();
let operations = {
let map = &self.map_path_to_op.get().0;
......@@ -263,6 +282,9 @@ impl VersionedContentMap {
let removed = self.removed_hmr_paths.get_untracked();
paths.iter().any(|path| removed.0.contains(path))
};
if was_removed && reactivation_source_paths.is_empty() {
bail!("re-adding an HMR chunk requires its source path");
}
let reactivated = {
let inactive = self.inactive_output_operations.get_untracked();
operations
......@@ -287,10 +309,15 @@ impl VersionedContentMap {
});
// Deleted routes need conservative catch-up because Turbopack may
// reuse the disconnected operation when the same file is added again.
// Invalidate only the re-added source file. Route discovery already
// observed the file before this call, so invalidating ancestor directory
// reads here would needlessly invalidate unrelated route graphs.
// Ordinary inactive routes never disconnect their output graph.
if was_removed {
project_fs.invalidate_with_reason(|path| invalidation::Initialize {
path: RcStr::from(path.to_string_lossy()),
project_fs.invalidate_path_with_reason(reactivation_source_paths, |path| {
invalidation::Initialize {
path: RcStr::from(path.to_string_lossy()),
}
});
}
// Reconnect and strongly read removed output graphs after catch-up.
......@@ -323,6 +350,12 @@ impl VersionedContentMap {
}
changed
});
if advance_reactivation_epoch {
let mut epoch = self.reactivation_epoch.get_untracked();
*epoch = epoch
.checked_add(1)
.expect("HMR reactivation epoch overflow");
}
} else {
// Keep the endpoint output operations connected so source changes
// continue to invalidate them while the route is inactive. Omitting
......@@ -337,7 +370,7 @@ impl VersionedContentMap {
changed
});
}
Ok(())
Ok(*self.reactivation_epoch.get_untracked())
}
/// Removes deleted routes from aggregate HMR versions and drops their
......
use std::{
borrow::Cow,
collections::BTreeMap,
fs::{canonicalize, create_dir_all},
io::Write,
path::{Path, PathBuf},
......@@ -27,7 +28,7 @@ use next_api::{
},
project::{
DebugBuildPaths, DefineEnv, DraftModeOptions, HmrTarget, PartialProjectOptions, Project,
ProjectContainer, ProjectOptions, WatchOptions,
ProjectContainer, ProjectOptions, WatchOptions, aggregate_hmr_reactivation_epoch,
},
project_asset_hashes_manifest::immutable_hashes_manifest_asset_if_enabled,
route::{Endpoint, EndpointGroupKey, Route},
......@@ -766,7 +767,9 @@ pub async fn project_set_hmr_chunks_active(
chunk_names: Vec<RcStr>,
target: String,
active: bool,
) -> napi::Result<()> {
reactivation_source_paths: Option<Vec<RcStr>>,
advance_reactivation_epoch: Option<bool>,
) -> napi::Result<u32> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
......@@ -776,7 +779,13 @@ pub async fn project_set_hmr_chunks_active(
ctx.turbo_tasks()
.run(async move {
container
.set_hmr_chunks_active(chunk_names, hmr_target, active)
.set_hmr_chunks_active(
chunk_names,
hmr_target,
active,
reactivation_source_paths.unwrap_or_default(),
advance_reactivation_epoch.unwrap_or_default(),
)
.await
})
.or_else(|e| ctx.throw_turbopack_internal_result(&e.into()))
......@@ -1979,19 +1988,23 @@ pub fn project_all_hmr_events(
unmark_top_level_task_may_leak_eventually_consistent_state();
let HmrUpdateWithIssues { update, issues, .. } = &*read;
match &**update {
Update::Missing | Update::None => {}
let reactivation_epoch = match &**update {
Update::Missing | Update::None => None,
Update::Total(TotalUpdate { to }) => {
let epoch = aggregate_hmr_reactivation_epoch(to.clone()).await?;
state.set(to.clone()).await?;
epoch
}
Update::Partial(PartialUpdate { to, .. }) => {
let epoch = aggregate_hmr_reactivation_epoch(to.clone()).await?;
state.set(to.clone()).await?;
epoch
}
}
Ok((Some(update.clone()), issues.clone()))
};
Ok((Some(update.clone()), issues.clone(), reactivation_epoch))
},
move |ctx| {
let (update, issues) = ctx.value;
let (update, issues, reactivation_epoch) = ctx.value;
let napi_issues = issues
.iter()
......@@ -2004,7 +2017,12 @@ pub fn project_all_hmr_events(
let identifier = ResourceIdentifier {
path: identifier_path.clone(),
headers: None,
headers: reactivation_epoch.map(|epoch| {
BTreeMap::from([(
rcstr!("x-next-hmr-reactivation-epoch"),
RcStr::from(epoch.to_string()),
)])
}),
};
let update = match update.as_deref() {
None | Some(Update::Missing) | Some(Update::Total(_)) => {
......
......@@ -341,8 +341,10 @@ export declare function projectSetHmrChunksActive(
project: { __napiType: 'Project' },
chunkNames: Array<RcStr>,
target: string,
active: boolean
): Promise<void>
active: boolean,
reactivationSourcePaths?: Array<RcStr> | undefined | null,
advanceReactivationEpoch?: boolean | undefined | null
): Promise<number>
export declare function projectRemoveHmrChunks(
project: { __napiType: 'Project' },
chunkNames: Array<RcStr>,
......
......@@ -775,13 +775,17 @@ function bindingToApi(
setHmrChunksActive(
chunkNames: string[],
target: HmrTarget.Server,
active: boolean
): Promise<void> {
active: boolean,
reactivationSourcePaths?: string[],
advanceReactivationEpoch?: boolean
): Promise<number> {
return binding.projectSetHmrChunksActive(
this._nativeProject,
chunkNames,
target,
active
active,
reactivationSourcePaths,
advanceReactivationEpoch
)
}
......
......@@ -343,8 +343,10 @@ export interface Project {
setHmrChunksActive(
chunkNames: string[],
target: import('./index').HmrTarget.Server,
active: boolean
): Promise<void>
active: boolean,
reactivationSourcePaths?: string[],
advanceReactivationEpoch?: boolean
): Promise<number>
removeHmrChunks(
chunkNames: string[],
......
......@@ -160,8 +160,6 @@ const sessionId = Math.floor(Number.MAX_SAFE_INTEGER * Math.random())
/** Output directory (relative to `distDir`) of server-HMR-managed chunks. */
const SERVER_HMR_CHUNKS_DIR = join('server', 'chunks')
/** Virtual output prefix; turbo-tasks paths always use forward slashes. */
const SERVER_HMR_VIRTUAL_CHUNKS_PREFIX = 'server/chunks/'
/** Virtual output directory containing the App Router's server entry chunks. */
const SERVER_HMR_APP_DIR = 'server/app'
const SERVER_HMR_REENTRY_WAIT_MS = 1000
......@@ -210,18 +208,15 @@ function collectUpdatedChunkPaths(
return Array.from(paths)
}
const SERVER_HMR_REACTIVATION_EPOCH_HEADER = 'x-next-hmr-reactivation-epoch'
type ServerHmrUpdateWaiter = {
afterGeneration: number
chunkPaths: Set<string>
reactivationEpoch: number
resolve: () => void
}
type ServerHmrUpdateTracker = {
captureGeneration: () => number
waitForChunkPathsAfter: (
afterGeneration: number,
chunkPaths: Iterable<string>
) => Promise<void>
waitForReactivationEpoch: (reactivationEpoch: number) => Promise<void>
}
function setupServerHmr(
......@@ -234,29 +229,28 @@ function setupServerHmr(
onApplied: (chunkPaths: string[]) => void | Promise<void>
}
): ServerHmrUpdateTracker {
let appliedGeneration = 0
let fullReEvaluationGeneration = 0
const chunkPathGenerations = new Map<string, number>()
let appliedReactivationEpoch = 0
const updateWaiters = new Set<ServerHmrUpdateWaiter>()
function getReactivationEpoch(update: NodeJsHmrUpdate) {
if (!('resource' in update)) return 0
const rawEpoch = (
update.resource.headers as Record<string, string> | undefined
)?.[SERVER_HMR_REACTIVATION_EPOCH_HEADER]
if (rawEpoch === undefined) return 0
const epoch = Number(rawEpoch)
return Number.isSafeInteger(epoch) && epoch > 0 ? epoch : 0
}
function hasApplied(waiter: ServerHmrUpdateWaiter) {
return (
fullReEvaluationGeneration > waiter.afterGeneration ||
Array.from(waiter.chunkPaths).every(
(path) => (chunkPathGenerations.get(path) ?? 0) > waiter.afterGeneration
)
)
return appliedReactivationEpoch >= waiter.reactivationEpoch
}
function recordAppliedUpdate(chunkPaths?: string[]) {
const generation = ++appliedGeneration
if (chunkPaths === undefined) {
fullReEvaluationGeneration = generation
} else {
for (const path of chunkPaths) {
chunkPathGenerations.set(path, generation)
}
}
function recordAppliedUpdate(reactivationEpoch: number) {
appliedReactivationEpoch = Math.max(
appliedReactivationEpoch,
reactivationEpoch
)
for (const waiter of updateWaiters) {
if (hasApplied(waiter)) {
updateWaiters.delete(waiter)
......@@ -272,7 +266,6 @@ function setupServerHmr(
}
const promise = Promise.resolve()
.then(reEvaluateAllModulesExpensive)
.then(() => recordAppliedUpdate())
.finally(() => {
if (fullReEvaluationPromise === promise) {
fullReEvaluationPromise = undefined
......@@ -292,6 +285,7 @@ function setupServerHmr(
for await (const result of subscription) {
const update = result as NodeJsHmrUpdate
const reactivationEpoch = getReactivationEpoch(update)
// A 'restart' from the wire protocol means the update can't be applied
// incrementally, so we must fully re-evaluate all chunks from disk. This
......@@ -299,6 +293,7 @@ function setupServerHmr(
const requiresFullReEvaluation = update.type === 'restart'
if (requiresFullReEvaluation) {
await runFullReEvaluation()
recordAppliedUpdate(reactivationEpoch)
continue
}
......@@ -322,12 +317,11 @@ function setupServerHmr(
const updatedChunkPaths = collectUpdatedChunkPaths(instruction)
// No handler registered yet (before first request, or right after
// reEvaluateAllModulesExpensive()) — nothing live to update. Recording the
// paths still releases a reentry waiter because there is no live cache that
// could serve stale modules.
// reEvaluateAllModulesExpensive()) — nothing live can serve stale modules.
// Acknowledge the aggregate transition directly.
const handlers = globalThis.__turbopack_server_hmr_handlers__
if (!handlers || handlers.size === 0) {
recordAppliedUpdate(updatedChunkPaths)
recordAppliedUpdate(reactivationEpoch)
continue
}
......@@ -339,6 +333,7 @@ function setupServerHmr(
// so the next request loads fresh, then skip onApplied. (A no-match
// update is a no-op and does not throw.)
await runFullReEvaluation()
recordAppliedUpdate(reactivationEpoch)
continue
}
......@@ -348,9 +343,10 @@ function setupServerHmr(
if (updatedChunkPaths.length > 0) {
await onApplied(updatedChunkPaths)
}
recordAppliedUpdate(updatedChunkPaths)
recordAppliedUpdate(reactivationEpoch)
} else {
await runFullReEvaluation()
recordAppliedUpdate(reactivationEpoch)
}
}
}
......@@ -373,14 +369,12 @@ function setupServerHmr(
})()
return {
captureGeneration: () => appliedGeneration,
waitForChunkPathsAfter(afterGeneration, chunkPaths) {
waitForReactivationEpoch(reactivationEpoch) {
const waiter: ServerHmrUpdateWaiter = {
afterGeneration,
chunkPaths: new Set(chunkPaths),
reactivationEpoch,
resolve: () => {},
}
if (waiter.chunkPaths.size === 0 || hasApplied(waiter)) {
if (reactivationEpoch === 0 || hasApplied(waiter)) {
return Promise.resolve()
}
let fallbackTimer: ReturnType<typeof setTimeout> | undefined
......@@ -398,11 +392,12 @@ function setupServerHmr(
resolve()
return
}
// Some endpoint output paths (notably client-component SSR chunks)
// are owned by a separate always-active aggregate entry and may have
// applied before this reentry began. Bound the route-specific wait and
// use the existing safe full-re-evaluation fallback rather than hanging.
runFullReEvaluation().then(resolve, reject)
// A subscription failure must not hang a request. A full evaluation
// installs the latest aggregate state and safely acknowledges this epoch.
runFullReEvaluation().then(() => {
recordAppliedUpdate(reactivationEpoch)
resolve()
}, reject)
}, SERVER_HMR_REENTRY_WAIT_MS)
})
return Promise.race([updatePromise, fallbackPromise]).finally(() => {
......@@ -753,11 +748,9 @@ export async function createHotReloaderTurbopack(
writtenEndpoint: WrittenEndpoint,
{
force,
onServerHmrChunkChanged,
}: {
// Always clear the cache, don't check if files have changed
force?: boolean
onServerHmrChunkChanged?: (path: string) => void
} = {}
): boolean {
if (force) {
......@@ -784,9 +777,6 @@ export async function createHotReloaderTurbopack(
(globalHash && globalHash !== contentHash)
) {
hasChange = true
if (path.startsWith(SERVER_HMR_VIRTUAL_CHUNKS_PREFIX)) {
onServerHmrChunkChanged?.(path)
}
serverPathState.set(localKey, contentHash)
serverPathState.set(path, contentHash)
} else {
......@@ -1111,10 +1101,6 @@ export async function createHotReloaderTurbopack(
const maxInactiveAge = nextConfig.onDemandEntries?.maxInactiveAge ?? 60 * 1000
const pagesBufferLength = nextConfig.onDemandEntries?.pagesBufferLength ?? 5
const routeChangeSubscriptionDisposals = new Map<EntryKey, Promise<void>>()
const routeChangeSubscriptionRetiredHmrGenerations = new Map<
EntryKey,
number
>()
const routeChangeSubscriptionReactivations = new Map<
EntryKey,
{ promise: Promise<void>; resolve: () => void }
......@@ -1146,14 +1132,21 @@ export async function createHotReloaderTurbopack(
async function setRouteHmrChunksActive(
keys: Iterable<EntryKey>,
active: boolean
active: boolean,
reactivationSourcePaths?: string[],
advanceReactivationEpoch = false
) {
const chunkPaths = Array.from(keys, getServerHmrEntryChunkPath).filter(
(path): path is string => path !== undefined
)
if (chunkPaths.length > 0) {
await project.setHmrChunksActive(chunkPaths, HmrTarget.Server, active)
}
if (chunkPaths.length === 0) return 0
return project.setHmrChunksActive(
chunkPaths,
HmrTarget.Server,
active,
reactivationSourcePaths,
advanceReactivationEpoch
)
}
async function removeRouteChangeSubscriptionState(keys: EntryKey[]) {
......@@ -1193,7 +1186,6 @@ export async function createHotReloaderTurbopack(
inactiveRouteChangeSubscriptions.delete(key)
routeChangeSubscriptionsNeedingCatchUp.delete(key)
routeChangeSubscriptionDisposals.delete(key)
routeChangeSubscriptionRetiredHmrGenerations.delete(key)
const removedChunkPath = chunkPathsByKey.get(key)
if (removedChunkPath) {
removedRouteHmrChunkPaths.set(key, removedChunkPath)
......@@ -1216,7 +1208,10 @@ export async function createHotReloaderTurbopack(
}
}
async function markRouteChangeSubscriptionActive(key: EntryKey) {
async function markRouteChangeSubscriptionActive(
key: EntryKey,
reactivationSourcePath: string
) {
markRouteChangeSubscriptionRecentlyActive(key)
// If cleanup raced with a request for this route, let its native aggregate
......@@ -1234,7 +1229,7 @@ export async function createHotReloaderTurbopack(
const existingReactivation = routeChangeSubscriptionReactivations.get(key)
if (existingReactivation) {
await existingReactivation.promise
return { wasInactive: false, wasRemoved: false, ownsReactivation: false }
return { ownsReactivation: false }
}
const wasInactive = inactiveRouteChangeSubscriptions.has(key)
......@@ -1258,7 +1253,12 @@ export async function createHotReloaderTurbopack(
// be written. Ordinary inactive operations stay connected, so keep their
// aggregate path inactive until the catch-up write is complete.
if (wasRemoved) {
await setRouteHmrChunksActive([key], true)
await setRouteHmrChunksActive(
[key],
true,
[reactivationSourcePath],
false
)
removedRouteHmrChunkPaths.delete(key)
}
// Stop suppressing endpoint issues before compiling. If catch-up fails,
......@@ -1266,7 +1266,7 @@ export async function createHotReloaderTurbopack(
inactiveRouteChangeSubscriptions.delete(key)
routeChangeSubscriptionsNeedingCatchUp.add(key)
}
return { wasInactive, wasRemoved, ownsReactivation }
return { ownsReactivation }
} catch (error) {
if (
ownedReactivation &&
......@@ -1312,13 +1312,7 @@ export async function createHotReloaderTurbopack(
// output and change roots connected so edits cannot leave a stale graph.
// The subscription loop suppresses refreshes and issues for inactive keys.
await setRouteHmrChunksActive(keys, false)
const retiredHmrGeneration =
serverHmrUpdateTracker?.captureGeneration() ?? 0
for (const key of keys) {
routeChangeSubscriptionRetiredHmrGenerations.set(
key,
retiredHmrGeneration
)
currentEntryIssues.delete(key)
}
})()
......@@ -2387,7 +2381,7 @@ export async function createHotReloaderTurbopack(
let reactivatedRouteChangeSubscription = false
let ownsRouteChangeSubscriptionReactivation = false
let pendingNativeRouteHmrReactivation = false
const reactivatedServerHmrChunkPaths = new Set<string>()
let routeHmrReactivationEpoch = 0
let routeChangeSubscriptionEntryKey: EntryKey | undefined
try {
if (
......@@ -2407,15 +2401,17 @@ export async function createHotReloaderTurbopack(
) ?? 0) + 1
)
const reactivation = await markRouteChangeSubscriptionActive(
routeChangeSubscriptionEntryKey
routeChangeSubscriptionEntryKey,
routeDef.filename
)
ownsRouteChangeSubscriptionReactivation =
reactivation.ownsReactivation
pendingNativeRouteHmrReactivation = reactivation.wasInactive
reactivatedRouteChangeSubscription =
routeChangeSubscriptionsNeedingCatchUp.has(
routeChangeSubscriptionEntryKey
)
pendingNativeRouteHmrReactivation =
reactivatedRouteChangeSubscription
if (reactivatedRouteChangeSubscription) {
await route.htmlEndpoint.invalidateOutput()
}
......@@ -2445,11 +2441,6 @@ export async function createHotReloaderTurbopack(
assetMapper.setPathsForKey(id, result.clientPaths)
const didChange = clearRequireCache(id, result, {
force: forceDeleteCache,
onServerHmrChunkChanged: (path) => {
if (reactivatedRouteChangeSubscription) {
reactivatedServerHmrChunkPaths.add(path)
}
},
})
if (didChange && reactivatedRouteChangeSubscription) {
// Advance the cache version in the same synchronous step that
......@@ -2467,29 +2458,22 @@ export async function createHotReloaderTurbopack(
routeChangeSubscriptionEntryKey
) {
// Publish the route back into aggregate HMR only after its output is
// current. Wait for the existing runtime to apply the changed chunks
// before the request can render; force-evicting shared runtime chunks
// here would orphan sibling routes' server-HMR handlers.
const generation =
routeChangeSubscriptionRetiredHmrGenerations.get(
routeChangeSubscriptionEntryKey
) ??
serverHmrUpdateTracker?.captureGeneration() ??
0
await setRouteHmrChunksActive(
// current. Native returns the exact aggregate transition that the
// runtime must apply before this request can render.
routeHmrReactivationEpoch = await setRouteHmrChunksActive(
[routeChangeSubscriptionEntryKey],
true,
undefined,
true
)
pendingNativeRouteHmrReactivation = false
await serverHmrUpdateTracker?.waitForChunkPathsAfter(
generation,
reactivatedServerHmrChunkPaths
}
if (routeHmrReactivationEpoch > 0) {
await serverHmrUpdateTracker?.waitForReactivationEpoch(
routeHmrReactivationEpoch
)
}
if (routeChangeSubscriptionEntryKey) {
routeChangeSubscriptionRetiredHmrGenerations.delete(
routeChangeSubscriptionEntryKey
)
routeChangeSubscriptionsNeedingCatchUp.delete(
routeChangeSubscriptionEntryKey
)
......@@ -2572,7 +2556,6 @@ export async function createHotReloaderTurbopack(
removedRouteHmrChunkPaths.clear()
routeChangeSubscriptionsNeedingCatchUp.clear()
routeChangeSubscriptionDisposals.clear()
routeChangeSubscriptionRetiredHmrGenerations.clear()
for (const reactivation of routeChangeSubscriptionReactivations.values()) {
reactivation.resolve()
}
......
......@@ -759,15 +759,24 @@ describe('server-hmr route activity', () => {
await browser.loadPage(`${next.url}/route-activity`)
await waitForRedbox(browser)
await next.patchFile(routeFile, (content) =>
content.replace(
'export default function Page(',
'export default function Page()'
)
content
.replace(
'export default function Page(',
'export default function Page()'
)
.replace('inactive local update', 'recovered route')
)
// The request retry owns the catch-up left behind by the failed compile.
// Its first response must wait for the recovery update to reach the runtime.
const firstRecoveryResponse = await next.fetch('/route-activity')
expect(firstRecoveryResponse.status).toBe(200)
const firstRecoveryHtml = await firstRecoveryResponse.text()
expect(firstRecoveryHtml).toContain('recovered route')
expect(firstRecoveryHtml).toContain('inactive route update')
await retry(async () => {
expect(
await browser.elementByCss('#route-activity-greeting').text()
).toBe('inactive local update: inactive route update')
).toBe('recovered route: inactive route update')
}, 10_000)
// Deleting a retired route must prune its emitted output mappings and frozen
......@@ -783,9 +792,16 @@ describe('server-hmr route activity', () => {
// must rebuild from the current files and install a fresh HMR subscription
// rather than reviving the deleted output snapshot.
await next.patchFile(routeFile, originalRouteSource)
let firstReaddedRouteHtml: string | undefined
await retry(async () => {
expect((await next.fetch('/route-activity')).status).toBe(200)
const response = await next.fetch('/route-activity')
expect(response.status).toBe(200)
firstReaddedRouteHtml = await response.text()
}, 10_000)
// Assert outside retry so a stale first successful response cannot be hidden
// by a later request after the aggregate HMR update has caught up.
expect(firstReaddedRouteHtml).toContain('route activity page')
expect(firstReaddedRouteHtml).toContain('inactive route update')
await browser.loadPage(`${next.url}/route-activity`)
expect(
await browser.elementByCss('#route-activity-greeting').text()
......
......@@ -376,11 +376,12 @@ impl DiskFileSystemInner {
}
/// Invalidates tracked files/directories for `paths` and their children.
/// Also invalidates tracked directory reads for all parent directories to
/// account for file creations/deletions under the deferred subtree.
/// Optionally invalidates tracked directory reads for all parent directories
/// to account for file creations/deletions under a subtree.
fn invalidate_path_and_children_with_reason<R: InvalidationReason + Clone>(
&self,
paths: impl IntoIterator<Item = PathBuf>,
invalidate_parent_dirs: bool,
reason: impl Fn(&Path) -> R + Sync,
) {
let _span =
......@@ -396,10 +397,12 @@ impl DiskFileSystemInner {
let mut parent_dirs_to_invalidate = FxHashSet::default();
for path in paths {
let mut current_parent = path.parent();
while let Some(parent) = current_parent {
parent_dirs_to_invalidate.insert(parent.to_path_buf());
current_parent = parent.parent();
if invalidate_parent_dirs {
let mut current_parent = path.parent();
while let Some(parent) = current_parent {
parent_dirs_to_invalidate.insert(parent.to_path_buf());
current_parent = parent.parent();
}
}
for (invalidated_path, path_invalidators) in
......@@ -504,7 +507,18 @@ impl DiskFileSystem {
reason: impl Fn(&Path) -> R + Sync,
) {
self.inner
.invalidate_path_and_children_with_reason(paths, reason);
.invalidate_path_and_children_with_reason(paths, true, reason);
}
/// Invalidates tracked reads at `paths` without invalidating directory reads
/// for their ancestors. Use this when discovery has already observed the path.
pub fn invalidate_path_with_reason<R: InvalidationReason + Clone>(
&self,
paths: impl IntoIterator<Item = PathBuf>,
reason: impl Fn(&Path) -> R + Sync,
) {
self.inner
.invalidate_path_and_children_with_reason(paths, false, reason);
}
pub async fn start_watching(&self, poll_interval: Option<Duration>) -> Result<()> {
......
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