Unverified Commit e2fb664c authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Remove HmrTarget (#97253)

With #94948 we intended to move the client over to the firehose feed of
HMR events with the intent of unifying the code paths for maintenance.
However, now that Server HMR is moving to a pull-based model (which
client HMR will not be able to implement), let's keep the split.

There's no need to encode the HmrTarget into each surface, and we can
just use the function name to indicate which mode of HMR it's for.
parent 1a304e37
...@@ -179,39 +179,6 @@ pub struct DebugBuildPaths { ...@@ -179,39 +179,6 @@ pub struct DebugBuildPaths {
pub pages: Vec<RcStr>, pub pages: Vec<RcStr>,
} }
/// Target for HMR operations - client-side (browser) or server-side (Node.js).
#[turbo_tasks::task_input]
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, Hash, TraceRawVcs, Encode, Decode)]
pub enum HmrTarget {
#[default]
Client,
Server,
}
impl std::fmt::Display for HmrTarget {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
HmrTarget::Client => write!(f, "client"),
HmrTarget::Server => write!(f, "server"),
}
}
}
impl std::str::FromStr for HmrTarget {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"client" => Ok(HmrTarget::Client),
"server" => Ok(HmrTarget::Server),
_ => Err(format!(
"Invalid HMR target: '{}'. Expected 'client' or 'server'",
s
)),
}
}
}
/// Pre-converted route keys from debug build paths for O(1) lookups. /// Pre-converted route keys from debug build paths for O(1) lookups.
struct DebugBuildPathsRouteKeys { struct DebugBuildPathsRouteKeys {
app: FxHashSet<RcStr>, app: FxHashSet<RcStr>,
...@@ -894,8 +861,8 @@ impl ProjectContainer { ...@@ -894,8 +861,8 @@ impl ProjectContainer {
/// See [`Project::hmr_chunk_names`]. /// See [`Project::hmr_chunk_names`].
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn hmr_chunk_names(self: Vc<Self>, target: HmrTarget) -> Vc<Vec<RcStr>> { pub fn hmr_chunk_names(self: Vc<Self>) -> Vc<Vec<RcStr>> {
self.project().hmr_chunk_names(target) self.project().hmr_chunk_names()
} }
/// Gets a source map for a particular `file_path`. If `dev` mode is disabled, this will always /// Gets a source map for a particular `file_path`. If `dev` mode is disabled, this will always
...@@ -2491,36 +2458,16 @@ impl Project { ...@@ -2491,36 +2458,16 @@ impl Project {
.await .await
} }
/// Returns the root path for HMR content based on the target.
/// Client uses client_relative_path, Server uses node_root.
#[turbo_tasks::function]
async fn hmr_root_path(self: Vc<Self>, target: HmrTarget) -> Result<Vc<FileSystemPath>> {
Ok(match target {
HmrTarget::Client => self.client_relative_path(),
HmrTarget::Server => self.node_root(),
})
}
#[turbo_tasks::function] #[turbo_tasks::function]
async fn aggregate_hmr_root_path( async fn server_hmr_root_path(self: Vc<Self>) -> Result<Vc<FileSystemPath>> {
self: Vc<Self>, Ok(self.node_root().await?.join("server/app")?.cell())
target: HmrTarget,
) -> Result<Vc<FileSystemPath>> {
match target {
HmrTarget::Client => bail!("aggregate HMR is not implemented for the client"),
HmrTarget::Server => Ok(self.node_root().await?.join("server/app")?.cell()),
}
} }
/// Get HMR content by chunk_name for the specified target. /// Get client HMR content by chunk_name.
#[turbo_tasks::function] #[turbo_tasks::function]
async fn hmr_content( async fn hmr_content(self: Vc<Self>, chunk_name: RcStr) -> Result<Vc<OptionVersionedContent>> {
self: Vc<Self>,
chunk_name: RcStr,
target: HmrTarget,
) -> Result<Vc<OptionVersionedContent>> {
if let Some(map) = self.await?.versioned_content_map { if let Some(map) = self.await?.versioned_content_map {
let content = map.get(self.hmr_root_path(target).await?.join(&chunk_name)?); let content = map.get(self.client_relative_path().await?.join(&chunk_name)?);
Ok(content) Ok(content)
} else { } else {
bail!("must be in dev mode to hmr") bail!("must be in dev mode to hmr")
...@@ -2533,7 +2480,6 @@ impl Project { ...@@ -2533,7 +2480,6 @@ impl Project {
pub async fn hmr_version_state( pub async fn hmr_version_state(
self: ResolvedVc<Self>, self: ResolvedVc<Self>,
chunk_name: RcStr, chunk_name: RcStr,
target: HmrTarget,
session: TransientInstance<()>, session: TransientInstance<()>,
) -> Result<Vc<VersionState>> { ) -> Result<Vc<VersionState>> {
// The session argument is important to avoid caching this function between // The session argument is important to avoid caching this function between
...@@ -2544,23 +2490,22 @@ impl Project { ...@@ -2544,23 +2490,22 @@ impl Project {
level = "info", level = "info",
name = "get HMR version", name = "get HMR version",
skip_all, skip_all,
fields(chunk_name = %chunk_name, target = %target), fields(chunk_name = %chunk_name),
)] )]
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
async fn hmr_version_operation( async fn hmr_version_operation(
this: ResolvedVc<Project>, this: ResolvedVc<Project>,
chunk_name: RcStr, chunk_name: RcStr,
target: HmrTarget,
) -> Result<Vc<Box<dyn Version>>> { ) -> Result<Vc<Box<dyn Version>>> {
tracing::info!(chunk_name = %chunk_name, target = %target, "hmr subscription"); tracing::info!(chunk_name = %chunk_name, "hmr subscription");
let content = this.hmr_content(chunk_name, target).await?; let content = this.hmr_content(chunk_name).await?;
if let Some(content) = &*content { if let Some(content) = &*content {
Ok(content.version()) Ok(content.version())
} else { } else {
Ok(Vc::upcast(NotFoundVersion::new())) Ok(Vc::upcast(NotFoundVersion::new()))
} }
} }
let version_op = hmr_version_operation(self, chunk_name, target); let version_op = hmr_version_operation(self, chunk_name);
// INVALIDATION: This is intentionally untracked to avoid invalidating this // INVALIDATION: This is intentionally untracked to avoid invalidating this
// function completely. We want to initialize the VersionState with the // function completely. We want to initialize the VersionState with the
...@@ -2576,16 +2521,15 @@ impl Project { ...@@ -2576,16 +2521,15 @@ impl Project {
} }
/// Emits opaque HMR events whenever a change is detected in the chunk group /// Emits opaque HMR events whenever a change is detected in the chunk group
/// internally known as `chunk_name` for the specified target. /// internally known as `chunk_name`.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn hmr_update( pub async fn hmr_update(
self: Vc<Self>, self: Vc<Self>,
chunk_name: RcStr, chunk_name: RcStr,
target: HmrTarget,
from: Vc<VersionState>, from: Vc<VersionState>,
) -> Result<Vc<Update>> { ) -> Result<Vc<Update>> {
let from = from.get(); let from = from.get();
let content = self.hmr_content(chunk_name, target).await?; let content = self.hmr_content(chunk_name).await?;
if let Some(content) = *content { if let Some(content) = *content {
Ok(content.update(from)) Ok(content.update(from))
} else { } else {
...@@ -2594,35 +2538,21 @@ impl Project { ...@@ -2594,35 +2538,21 @@ impl Project {
} }
/// Aggregate counterpart to [`Self::hmr_version_state`]: one [`VersionState`] /// Aggregate counterpart to [`Self::hmr_version_state`]: one [`VersionState`]
/// covering every HMR-eligible chunk under `target`'s root. See /// covering every server HMR-eligible chunk. See [`Self::server_hmr_update`].
/// [`Self::all_hmr_update`].
#[turbo_tasks::function(session_dependent)] #[turbo_tasks::function(session_dependent)]
pub async fn all_hmr_version_state( pub async fn server_hmr_version_state(self: ResolvedVc<Self>) -> Result<Vc<VersionState>> {
self: ResolvedVc<Self>, #[tracing::instrument(level = "info", name = "get server HMR version", skip_all)]
target: HmrTarget,
) -> Result<Vc<VersionState>> {
if target == HmrTarget::Client {
bail!("all_hmr_version_state is not yet implemented for the client target");
}
#[tracing::instrument(
level = "info",
name = "get aggregate HMR version",
skip_all,
fields(target = %target),
)]
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
async fn aggregate_hmr_version_operation( async fn server_hmr_version_operation(
this: ResolvedVc<Project>, this: ResolvedVc<Project>,
target: HmrTarget,
) -> Result<Vc<Box<dyn Version>>> { ) -> Result<Vc<Box<dyn Version>>> {
let Some(map) = this.await?.versioned_content_map else { let Some(map) = this.await?.versioned_content_map else {
bail!("must be in dev mode to hmr") bail!("must be in dev mode to hmr")
}; };
let root = this.aggregate_hmr_root_path(target).owned().await?; let root = this.server_hmr_root_path().owned().await?;
AggregateHmrVersion::from_map(*map, root).await AggregateHmrVersion::from_map(*map, root).await
} }
let version_op = aggregate_hmr_version_operation(self, target); let version_op = server_hmr_version_operation(self);
// INVALIDATION: untracked initial read; the subscription drives invalidation. // INVALIDATION: untracked initial read; the subscription drives invalidation.
let state = VersionState::new( let state = VersionState::new(
...@@ -2636,8 +2566,7 @@ impl Project { ...@@ -2636,8 +2566,7 @@ impl Project {
} }
/// Aggregate counterpart to [`Self::hmr_update`]: a single `Update` whose /// Aggregate counterpart to [`Self::hmr_update`]: a single `Update` whose
/// combined `ChunkListUpdate` is the union of the per-entry-chunk diffs /// combined `ChunkListUpdate` is the union of the server entry chunk diffs.
/// under `target`'s root.
/// ///
/// Each tracked entry chunk's own update is a `ChunkListUpdate` (carrying /// Each tracked entry chunk's own update is a `ChunkListUpdate` (carrying
/// the module deltas for its shared chunks via the merger) or a bare /// the module deltas for its shared chunks via the merger) or a bare
...@@ -2649,19 +2578,11 @@ impl Project { ...@@ -2649,19 +2578,11 @@ impl Project {
/// chunks absent from `from` are skipped; the runtime require()s them on /// chunks absent from `from` are skipped; the runtime require()s them on
/// demand. /// demand.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn all_hmr_update( pub async fn server_hmr_update(self: Vc<Self>, from: Vc<VersionState>) -> Result<Vc<Update>> {
self: Vc<Self>,
target: HmrTarget,
from: Vc<VersionState>,
) -> Result<Vc<Update>> {
if target == HmrTarget::Client {
bail!("all_hmr_update is not yet implemented for the client target");
}
let Some(map) = self.await?.versioned_content_map else { let Some(map) = self.await?.versioned_content_map else {
bail!("must be in dev mode to hmr") bail!("must be in dev mode to hmr")
}; };
let root = self.aggregate_hmr_root_path(target).owned().await?; let root = self.server_hmr_root_path().owned().await?;
let chunks_versioned_content = map.hmr_chunks_in_path(root).await?; let chunks_versioned_content = map.hmr_chunks_in_path(root).await?;
// No chunks to diff yet (e.g. before any endpoints have been written). // No chunks to diff yet (e.g. before any endpoints have been written).
...@@ -2710,14 +2631,11 @@ impl Project { ...@@ -2710,14 +2631,11 @@ impl Project {
Ok(builder.build(to_ref).cell()) Ok(builder.build(to_ref).cell())
} }
/// Gets a list of all HMR chunk names that can be subscribed to for the /// Gets a list of all client HMR chunk names that can be subscribed to.
/// specified target. Used by the dev server to set up server-side HMR
/// subscriptions for all Node.js App Router entries (pages and route
/// handlers).
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn hmr_chunk_names(self: Vc<Self>, target: HmrTarget) -> Result<Vc<Vec<RcStr>>> { pub async fn hmr_chunk_names(self: Vc<Self>) -> Result<Vc<Vec<RcStr>>> {
if let Some(map) = self.await?.versioned_content_map { if let Some(map) = self.await?.versioned_content_map {
Ok(map.keys_in_path(self.hmr_root_path(target).owned().await?)) Ok(map.keys_in_path(self.client_relative_path().owned().await?))
} else { } else {
bail!("must be in dev mode to hmr") bail!("must be in dev mode to hmr")
} }
......
...@@ -8,7 +8,7 @@ use anyhow::{Context, Result, bail}; ...@@ -8,7 +8,7 @@ use anyhow::{Context, Result, bail};
use futures_util::{StreamExt, TryStreamExt}; use futures_util::{StreamExt, TryStreamExt};
use next_api::{ use next_api::{
entrypoints::Entrypoints, entrypoints::Entrypoints,
project::{HmrTarget, ProjectContainer, ProjectOptions}, project::{ProjectContainer, ProjectOptions},
route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk}, route::{Endpoint, EndpointOutputPaths, Route, endpoint_write_to_disk},
}; };
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
...@@ -292,7 +292,7 @@ async fn hmr( ...@@ -292,7 +292,7 @@ async fn hmr(
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
fn project_hmr_chunk_names_operation(project: ResolvedVc<ProjectContainer>) -> Vc<Vec<RcStr>> { fn project_hmr_chunk_names_operation(project: ResolvedVc<ProjectContainer>) -> Vc<Vec<RcStr>> {
project.hmr_chunk_names(HmrTarget::Client) project.hmr_chunk_names()
} }
let idents = tt let idents = tt
...@@ -316,10 +316,8 @@ async fn hmr( ...@@ -316,10 +316,8 @@ async fn hmr(
let ident = ident_for_task.clone(); let ident = ident_for_task.clone();
async move { async move {
let project = project.project(); let project = project.project();
let state = project.hmr_version_state(ident.clone(), HmrTarget::Client, session); let state = project.hmr_version_state(ident.clone(), session);
project project.hmr_update(ident.clone(), state).await?;
.hmr_update(ident.clone(), HmrTarget::Client, state)
.await?;
Ok(Vc::<()>::cell(())) Ok(Vc::<()>::cell(()))
} }
}); });
......
...@@ -26,7 +26,7 @@ use next_api::{ ...@@ -26,7 +26,7 @@ use next_api::{
RouteOperation, RouteOperation,
}, },
project::{ project::{
DebugBuildPaths, DefineEnv, DraftModeOptions, HmrTarget, PartialProjectOptions, Project, DebugBuildPaths, DefineEnv, DraftModeOptions, PartialProjectOptions, Project,
ProjectContainer, ProjectOptions, WatchOptions, ProjectContainer, ProjectOptions, WatchOptions,
}, },
project_asset_hashes_manifest::immutable_hashes_manifest_asset_if_enabled, project_asset_hashes_manifest::immutable_hashes_manifest_asset_if_enabled,
...@@ -1814,27 +1814,25 @@ struct HmrUpdateWithIssues { ...@@ -1814,27 +1814,25 @@ struct HmrUpdateWithIssues {
fn project_hmr_update_operation( fn project_hmr_update_operation(
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
chunk_name: RcStr, chunk_name: RcStr,
target: HmrTarget,
state: ResolvedVc<VersionState>, state: ResolvedVc<VersionState>,
) -> Vc<Update> { ) -> Vc<Update> {
project.hmr_update(chunk_name, target, *state) project.hmr_update(chunk_name, *state)
} }
#[tracing::instrument( #[tracing::instrument(
level = "info", level = "info",
name = "hmr subscription", name = "hmr subscription",
skip_all, skip_all,
fields(chunk_name = %chunk_name, target = %target), fields(chunk_name = %chunk_name),
)] )]
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
async fn hmr_update_with_issues_operation( async fn hmr_update_with_issues_operation(
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
chunk_name: RcStr, chunk_name: RcStr,
state: ResolvedVc<VersionState>, state: ResolvedVc<VersionState>,
target: HmrTarget,
) -> Result<Vc<HmrUpdateWithIssues>> { ) -> Result<Vc<HmrUpdateWithIssues>> {
tracing::info!(chunk_name = %chunk_name, target = %target, "hmr subscription"); tracing::info!(chunk_name = %chunk_name, "hmr subscription");
let update_op = project_hmr_update_operation(project, chunk_name, target, state); let update_op = project_hmr_update_operation(project, chunk_name, state);
// NOTE: we do not use `strongly_consistent_catch_collectables` here. The JS HMR // NOTE: we do not use `strongly_consistent_catch_collectables` here. The JS HMR
// consumers in `hot-reloader-turbopack.ts` (`subscribeToServerHmr` and // consumers in `hot-reloader-turbopack.ts` (`subscribeToServerHmr` and
// `subscribeToClientHmrEvents`) rely on this read *throwing* on build-graph // `subscribeToClientHmrEvents`) rely on this read *throwing* on build-graph
...@@ -1853,29 +1851,22 @@ async fn hmr_update_with_issues_operation( ...@@ -1853,29 +1851,22 @@ async fn hmr_update_with_issues_operation(
/// Aggregate counterpart to [`project_hmr_update_operation`]. /// Aggregate counterpart to [`project_hmr_update_operation`].
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
fn project_all_hmr_update_operation( fn project_server_hmr_update_operation(
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
target: HmrTarget,
state: ResolvedVc<VersionState>, state: ResolvedVc<VersionState>,
) -> Vc<Update> { ) -> Vc<Update> {
project.all_hmr_update(target, *state) project.server_hmr_update(*state)
} }
/// Aggregate counterpart to [`hmr_update_with_issues_operation`]. /// Aggregate counterpart to [`hmr_update_with_issues_operation`].
#[tracing::instrument( #[tracing::instrument(level = "info", name = "server hmr subscription", skip_all)]
level = "info",
name = "aggregate hmr subscription",
skip_all,
fields(target = %target),
)]
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
async fn all_hmr_update_with_issues_operation( async fn server_hmr_update_with_issues_operation(
project: ResolvedVc<Project>, project: ResolvedVc<Project>,
state: ResolvedVc<VersionState>, state: ResolvedVc<VersionState>,
target: HmrTarget,
) -> Result<Vc<HmrUpdateWithIssues>> { ) -> Result<Vc<HmrUpdateWithIssues>> {
tracing::info!(target = %target, "aggregate hmr subscription"); tracing::info!("server hmr subscription");
let update_op = project_all_hmr_update_operation(project, target, state); let update_op = project_server_hmr_update_operation(project, state);
// See `hmr_update_with_issues_operation`: the JS consumer relies on this // See `hmr_update_with_issues_operation`: the JS consumer relies on this
// read *throwing* on build-graph failures; don't swallow errors. // read *throwing* on build-graph failures; don't swallow errors.
let update = update_op let update = update_op
...@@ -1893,19 +1884,18 @@ async fn all_hmr_update_with_issues_operation( ...@@ -1893,19 +1884,18 @@ async fn all_hmr_update_with_issues_operation(
.cell()) .cell())
} }
#[tracing::instrument(level = "info", name = "get all HMR events", skip(env, project, func), fields(target = %target))] #[tracing::instrument(
level = "info",
name = "get server HMR events",
skip(env, project, func)
)]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")] #[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_all_hmr_events( pub fn project_server_hmr_events(
env: Env, env: Env,
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>, #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
target: String,
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult<NodeJsHmrUpdate>) => void")] #[napi(ts_arg_type = "(err: Error, value: TurbopackResult<NodeJsHmrUpdate>) => void")]
func: FunctionRef<TurbopackResult<Unknown<'static>>, ()>, func: FunctionRef<TurbopackResult<Unknown<'static>>, ()>,
) -> napi::Result<External<RootTask>> { ) -> napi::Result<External<RootTask>> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
let container = project.container; let container = project.container;
// Sentinel resource id for the aggregated stream (no real chunk path). // Sentinel resource id for the aggregated stream (no real chunk path).
let identifier_path: RcStr = rcstr!("__next_all_hmr__"); let identifier_path: RcStr = rcstr!("__next_all_hmr__");
...@@ -1918,12 +1908,9 @@ pub fn project_all_hmr_events( ...@@ -1918,12 +1908,9 @@ pub fn project_all_hmr_events(
unmark_top_level_task_may_leak_eventually_consistent_state(); unmark_top_level_task_may_leak_eventually_consistent_state();
let project = container.project().to_resolved().await?; let project = container.project().to_resolved().await?;
let state = project let state = project.server_hmr_version_state().to_resolved().await?;
.all_hmr_version_state(hmr_target)
.to_resolved()
.await?;
let update_op = all_hmr_update_with_issues_operation(project, state, hmr_target); let update_op = server_hmr_update_with_issues_operation(project, state);
// HACK(bgw): Remove this mark call // HACK(bgw): Remove this mark call
mark_top_level_task(); mark_top_level_task();
...@@ -1982,20 +1969,17 @@ pub fn project_all_hmr_events( ...@@ -1982,20 +1969,17 @@ pub fn project_all_hmr_events(
) )
} }
#[tracing::instrument(level = "info", name = "get HMR events", skip(env, project, func), fields(target = %target, chunk_name = %chunk_name))] #[tracing::instrument(level = "info", name = "get client HMR events", skip(env, project, func), fields(chunk_name = %chunk_name))]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")] #[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_events( pub fn project_client_hmr_events(
env: Env, env: Env,
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>, #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
chunk_name: RcStr, chunk_name: RcStr,
target: String, #[napi(ts_arg_type = "(err: Error, value: TurbopackResult<Update>) => void")] func: FunctionRef<
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult<Update | NodeJsHmrUpdate>) => void")] TurbopackResult<Unknown<'static>>,
func: FunctionRef<TurbopackResult<Unknown<'static>>, ()>, (),
>,
) -> napi::Result<External<RootTask>> { ) -> napi::Result<External<RootTask>> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
let container = project.container; let container = project.container;
let session = TransientInstance::new(()); let session = TransientInstance::new(());
subscribe( subscribe(
...@@ -2013,16 +1997,12 @@ pub fn project_hmr_events( ...@@ -2013,16 +1997,12 @@ pub fn project_hmr_events(
unmark_top_level_task_may_leak_eventually_consistent_state(); unmark_top_level_task_may_leak_eventually_consistent_state();
let project = container.project().to_resolved().await?; let project = container.project().to_resolved().await?;
let state = project let state = project
.hmr_version_state(chunk_name.clone(), hmr_target, session) .hmr_version_state(chunk_name.clone(), session)
.to_resolved() .to_resolved()
.await?; .await?;
let update_op = hmr_update_with_issues_operation( let update_op =
project, hmr_update_with_issues_operation(project, chunk_name.clone(), state);
chunk_name.clone(),
state,
hmr_target,
);
// HACK(bgw): Remove this mark call // HACK(bgw): Remove this mark call
mark_top_level_task(); mark_top_level_task();
let read = let read =
...@@ -2093,19 +2073,17 @@ struct HmrChunkNamesWithIssues { ...@@ -2093,19 +2073,17 @@ struct HmrChunkNamesWithIssues {
} }
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
fn project_hmr_chunk_names_operation( fn project_client_hmr_chunk_names_operation(
container: ResolvedVc<ProjectContainer>, container: ResolvedVc<ProjectContainer>,
target: HmrTarget,
) -> Vc<Vec<RcStr>> { ) -> Vc<Vec<RcStr>> {
container.hmr_chunk_names(target) container.hmr_chunk_names()
} }
#[turbo_tasks::function(operation, root)] #[turbo_tasks::function(operation, root)]
async fn get_hmr_chunk_names_with_issues_operation( async fn get_client_hmr_chunk_names_with_issues_operation(
container: ResolvedVc<ProjectContainer>, container: ResolvedVc<ProjectContainer>,
target: HmrTarget,
) -> Result<Vc<HmrChunkNamesWithIssues>> { ) -> Result<Vc<HmrChunkNamesWithIssues>> {
let hmr_chunk_names_op = project_hmr_chunk_names_operation(container, target); let hmr_chunk_names_op = project_client_hmr_chunk_names_operation(container);
// Do NOT switch this to `strongly_consistent_catch_collectables`. The JS HMR // Do NOT switch this to `strongly_consistent_catch_collectables`. The JS HMR
// chunk-names consumer in `hot-reloader-turbopack.ts` relies on this read // chunk-names consumer in `hot-reloader-turbopack.ts` relies on this read
// *throwing* on build-graph failures so its outer `try` block exits the // *throwing* on build-graph failures so its outer `try` block exits the
...@@ -2124,19 +2102,18 @@ async fn get_hmr_chunk_names_with_issues_operation( ...@@ -2124,19 +2102,18 @@ async fn get_hmr_chunk_names_with_issues_operation(
.cell()) .cell())
} }
#[tracing::instrument(level = "info", name = "get HMR chunk names", skip(env, project, func), fields(target = %target))] #[tracing::instrument(
level = "info",
name = "get client HMR chunk names",
skip(env, project, func)
)]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")] #[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_chunk_names_subscribe( pub fn project_client_hmr_chunk_names_subscribe(
env: Env, env: Env,
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>, #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
target: String,
#[napi(ts_arg_type = "(err: Error, value: TurbopackResult<HmrChunkNames>) => void")] #[napi(ts_arg_type = "(err: Error, value: TurbopackResult<HmrChunkNames>) => void")]
func: FunctionRef<TurbopackResult<HmrChunkNames>, ()>, func: FunctionRef<TurbopackResult<HmrChunkNames>, ()>,
) -> napi::Result<External<RootTask>> { ) -> napi::Result<External<RootTask>> {
let hmr_target = target
.parse::<HmrTarget>()
.map_err(napi::Error::from_reason)?;
let container = project.container; let container = project.container;
subscribe( subscribe(
project.turbopack_ctx.clone(), project.turbopack_ctx.clone(),
...@@ -2144,7 +2121,7 @@ pub fn project_hmr_chunk_names_subscribe( ...@@ -2144,7 +2121,7 @@ pub fn project_hmr_chunk_names_subscribe(
&func, &func,
move || async move { move || async move {
let hmr_chunk_names_with_issues_op = let hmr_chunk_names_with_issues_op =
get_hmr_chunk_names_with_issues_operation(container, hmr_target); get_client_hmr_chunk_names_with_issues_operation(container);
let read = let read =
read_strongly_consistent_and_apply_effects(hmr_chunk_names_with_issues_op, |v| { read_strongly_consistent_and_apply_effects(hmr_chunk_names_with_issues_op, |v| {
&v.effects &v.effects
......
...@@ -581,10 +581,15 @@ export declare function parse( ...@@ -581,10 +581,15 @@ export declare function parse(
signal?: AbortSignal | undefined | null signal?: AbortSignal | undefined | null
): Promise<string> ): Promise<string>
export declare function projectAllHmrEvents( export declare function projectClientHmrChunkNamesSubscribe(
project: { __napiType: 'Project' }, project: { __napiType: 'Project' },
target: string, func: (err: Error, value: TurbopackResult<HmrChunkNames>) => void
func: (err: Error, value: TurbopackResult<NodeJsHmrUpdate>) => void ): { __napiType: 'RootTask' }
export declare function projectClientHmrEvents(
project: { __napiType: 'Project' },
chunkName: RcStr,
func: (err: Error, value: TurbopackResult<Update>) => void
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
/** Subscribes to all compilation events that are not cached like timing and progress information. */ /** Subscribes to all compilation events that are not cached like timing and progress information. */
...@@ -634,19 +639,6 @@ export declare function projectGetSourceMapSync( ...@@ -634,19 +639,6 @@ export declare function projectGetSourceMapSync(
sourceMapUrl: RcStr sourceMapUrl: RcStr
): string | null ): string | null
export declare function projectHmrChunkNamesSubscribe(
project: { __napiType: 'Project' },
target: string,
func: (err: Error, value: TurbopackResult<HmrChunkNames>) => void
): { __napiType: 'RootTask' }
export declare function projectHmrEvents(
project: { __napiType: 'Project' },
chunkName: RcStr,
target: string,
func: (err: Error, value: TurbopackResult<Update | NodeJsHmrUpdate>) => void
): { __napiType: 'RootTask' }
/** /**
* Invalidates the filesystem cache so that it will be deleted next time that a turbopack project * Invalidates the filesystem cache so that it will be deleted next time that a turbopack project
* is created with filesystem cache enabled. * is created with filesystem cache enabled.
...@@ -671,6 +663,11 @@ export declare function projectOnExit(project: { ...@@ -671,6 +663,11 @@ export declare function projectOnExit(project: {
__napiType: 'Project' __napiType: 'Project'
}): Promise<void> }): Promise<void>
export declare function projectServerHmrEvents(
project: { __napiType: 'Project' },
func: (err: Error, value: TurbopackResult<NodeJsHmrUpdate>) => void
): { __napiType: 'RootTask' }
/** /**
* Runs `project_on_exit`, and then waits for turbo_tasks to gracefully shut down. * Runs `project_on_exit`, and then waits for turbo_tasks to gracefully shut down.
* *
......
...@@ -43,11 +43,6 @@ import type { ...@@ -43,11 +43,6 @@ import type {
} from './types' } from './types'
import { runLoaderWorkerPool } from './loaderWorkerPool' import { runLoaderWorkerPool } from './loaderWorkerPool'
export enum HmrTarget {
Client = 'client',
Server = 'server',
}
type RawBindings = typeof import('./generated-native') type RawBindings = typeof import('./generated-native')
type RawWasmBindings = typeof import('./generated-wasm') & { type RawWasmBindings = typeof import('./generated-wasm') & {
default?(): Promise<typeof import('./generated-wasm')> default?(): Promise<typeof import('./generated-wasm')>
...@@ -762,47 +757,27 @@ function bindingToApi( ...@@ -762,47 +757,27 @@ function bindingToApi(
})() })()
} }
// Note: only the Server target is implemented in the native binding; serverHmrEvents(): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>> {
// add a Client overload once `all_hmr_update` supports it.
allHmrEvents(
target: HmrTarget.Server
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>> {
return subscribe(true, async (callback) => return subscribe(true, async (callback) =>
binding.projectAllHmrEvents(this._nativeProject, target, callback) binding.projectServerHmrEvents(this._nativeProject, callback)
) )
} }
hmrEvents( clientHmrEvents(
chunkName: string, chunkName: string
target: HmrTarget.Client ): AsyncIterableIterator<TurbopackResult<Update>> {
): AsyncIterableIterator<TurbopackResult<Update>>
hmrEvents(
chunkName: string,
target: HmrTarget.Server
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
hmrEvents(chunkName: string, target: HmrTarget.Client | HmrTarget.Server) {
return subscribe(true, async (callback) => return subscribe(true, async (callback) =>
binding.projectHmrEvents( binding.projectClientHmrEvents(this._nativeProject, chunkName, callback)
this._nativeProject,
chunkName,
target,
callback
)
) )
} }
/** /** Subscribe to client output chunk paths that can receive HMR updates. */
* Subscribe to the list of output chunk paths that can receive HMR updates. clientHmrChunkNamesSubscribe() {
* Chunk paths are output file paths like "server/chunks/ssr/..._.js" for server
* or "_next/static/chunks/app/page.js" for client.
*/
hmrChunkNamesSubscribe(target: HmrTarget) {
return subscribe<TurbopackResult<HmrChunkNames>>( return subscribe<TurbopackResult<HmrChunkNames>>(
false, false,
async (callback) => async (callback) =>
binding.projectHmrChunkNamesSubscribe( binding.projectClientHmrChunkNamesSubscribe(
this._nativeProject, this._nativeProject,
target,
callback callback
) )
) )
......
...@@ -334,24 +334,15 @@ export interface Project { ...@@ -334,24 +334,15 @@ export interface Project {
TurbopackResult<RawEntrypoints | {}> TurbopackResult<RawEntrypoints | {}>
> >
// Note: only the Server target is implemented in the native binding; serverHmrEvents(): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
// add a Client overload once `all_hmr_update` supports it.
allHmrEvents( clientHmrEvents(
target: import('./index').HmrTarget.Server identifier: string
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
hmrEvents(
identifier: string,
target: import('./index').HmrTarget.Client
): AsyncIterableIterator<TurbopackResult<Update>> ): AsyncIterableIterator<TurbopackResult<Update>>
hmrEvents(
identifier: string, clientHmrChunkNamesSubscribe(): AsyncIterableIterator<
target: import('./index').HmrTarget.Server TurbopackResult<HmrChunkNames>
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>> >
hmrChunkNamesSubscribe(
target: import('./index').HmrTarget
): AsyncIterableIterator<TurbopackResult<HmrChunkNames>>
getSourceForAsset(filePath: string): Promise<string | null> getSourceForAsset(filePath: string): Promise<string | null>
......
...@@ -28,7 +28,7 @@ import type { ...@@ -28,7 +28,7 @@ import type {
NodeJsHmrUpdate, NodeJsHmrUpdate,
NodeJsPartialHmrUpdate, NodeJsPartialHmrUpdate,
} from '../../build/swc/types' } from '../../build/swc/types'
import { createDefineEnv, getBindingsSync, HmrTarget } from '../../build/swc' import { createDefineEnv, getBindingsSync } from '../../build/swc'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import { BLOCKED_PAGES } from '../../shared/lib/constants' import { BLOCKED_PAGES } from '../../shared/lib/constants'
import { import {
...@@ -217,7 +217,7 @@ function setupServerHmr( ...@@ -217,7 +217,7 @@ function setupServerHmr(
} }
) { ) {
async function runSubscription() { async function runSubscription() {
const subscription = project.allHmrEvents(HmrTarget.Server) const subscription = project.serverHmrEvents()
// Subscribing immediately emits one event describing the current state. // Subscribing immediately emits one event describing the current state.
// There's no previous state to diff it against, so it never carries anything // There's no previous state to diff it against, so it never carries anything
...@@ -988,7 +988,7 @@ export async function createHotReloaderTurbopack( ...@@ -988,7 +988,7 @@ export async function createHotReloaderTurbopack(
return return
} }
const subscription = project!.hmrEvents(id, HmrTarget.Client) const subscription = project!.clientHmrEvents(id)
state.subscriptions.set(id, subscription) state.subscriptions.set(id, subscription)
// The subscription will always emit once, which is the initial // The subscription will always emit once, which is the initial
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { PHASE_DEVELOPMENT_SERVER } from 'next/constants' import { PHASE_DEVELOPMENT_SERVER } from 'next/constants'
import { createDefineEnv, loadBindings, HmrTarget } from 'next/dist/build/swc' import { createDefineEnv, loadBindings } from 'next/dist/build/swc'
import type { import type {
Issue, Issue,
MemoryEvictionMode, MemoryEvictionMode,
...@@ -618,15 +618,13 @@ describe('next.rs api', () => { ...@@ -618,15 +618,13 @@ describe('next.rs api', () => {
} }
} }
const result = await project const result = await project.clientHmrChunkNamesSubscribe().next()
.hmrChunkNamesSubscribe(HmrTarget.Client)
.next()
expect(result.done).toBe(false) expect(result.done).toBe(false)
const chunkNames = result.value.chunkNames const chunkNames = result.value.chunkNames
expect(chunkNames).toHaveProperty('length', expect.toBePositive()) expect(chunkNames).toHaveProperty('length', expect.toBePositive())
const subscriptions = chunkNames.map((chunkName) => const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(chunkName, HmrTarget.Client) project.clientHmrEvents(chunkName)
) )
await Promise.all( await Promise.all(
subscriptions.map(async (subscription) => { subscriptions.map(async (subscription) => {
...@@ -740,12 +738,12 @@ describe('next.rs api', () => { ...@@ -740,12 +738,12 @@ describe('next.rs api', () => {
if (route.type !== 'page') throw new Error('unknown route type') if (route.type !== 'page') throw new Error('unknown route type')
await route.htmlEndpoint.writeToDisk() await route.htmlEndpoint.writeToDisk()
const result = await project.hmrChunkNamesSubscribe(HmrTarget.Client).next() const result = await project.clientHmrChunkNamesSubscribe().next()
expect(result.done).toBe(false) expect(result.done).toBe(false)
const chunkNames = result.value.chunkNames const chunkNames = result.value.chunkNames
const subscriptions = chunkNames.map((chunkName) => const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(chunkName, HmrTarget.Client) project.clientHmrEvents(chunkName)
) )
await Promise.all( await Promise.all(
subscriptions.map(async (subscription) => { subscriptions.map(async (subscription) => {
......
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