Commit acf1625d authored by Will Binns-Smith's avatar Will Binns-Smith

Apply suggestion from @sokra

Co-authored-by: 's avatarTobias Koppers <tobias.koppers@googlemail.com>
parent fdbe45aa
...@@ -739,10 +739,10 @@ impl ProjectContainer { ...@@ -739,10 +739,10 @@ impl ProjectContainer {
self.project().entrypoints() self.project().entrypoints()
} }
/// See [Project::client_hmr_identifiers]. /// See [Project::client_hmr_chunk_names].
#[turbo_tasks::function] #[turbo_tasks::function]
pub fn client_hmr_identifiers(self: Vc<Self>) -> Vc<Vec<RcStr>> { pub fn client_hmr_chunk_names(self: Vc<Self>) -> Vc<Vec<RcStr>> {
self.project().client_hmr_identifiers() self.project().client_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
...@@ -2104,10 +2104,10 @@ impl Project { ...@@ -2104,10 +2104,10 @@ impl Project {
} }
} }
/// Gets a list of all HMR identifiers that can be subscribed to. This is /// Gets a list of all HMR chunk names that can be subscribed to. This is
/// only needed for testing purposes and isn't used in real apps. /// only needed for testing purposes and isn't used in real apps.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn client_hmr_identifiers(self: Vc<Self>) -> Result<Vc<Vec<RcStr>>> { pub async fn client_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.client_relative_path().owned().await?)) Ok(map.keys_in_path(self.client_relative_path().owned().await?))
} else { } else {
...@@ -2190,11 +2190,11 @@ impl Project { ...@@ -2190,11 +2190,11 @@ impl Project {
} }
} }
/// Gets a list of all server HMR identifiers that can be subscribed to. /// Gets a list of all server HMR chunk names that can be subscribed to.
/// These are paths relative to node_root (e.g., "server/app/page.js"). /// These are paths relative to node_root (e.g., "server/app/page.js").
/// This is the server-side equivalent of `hmr_identifiers`. /// This is the server-side equivalent of `hmr_chunk_names`.
#[turbo_tasks::function] #[turbo_tasks::function]
pub async fn server_hmr_identifiers(self: Vc<Self>) -> Result<Vc<Vec<RcStr>>> { pub async fn server_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.node_root().owned().await?)) Ok(map.keys_in_path(self.node_root().owned().await?))
} else { } else {
......
...@@ -257,7 +257,7 @@ async fn hmr( ...@@ -257,7 +257,7 @@ async fn hmr(
tracing::info!("HMR..."); tracing::info!("HMR...");
let session = TransientInstance::new(()); let session = TransientInstance::new(());
let idents = tt let idents = tt
.run(async move { project.client_hmr_identifiers().await }) .run(async move { project.client_hmr_chunk_names().await })
.await?; .await?;
let start = Instant::now(); let start = Instant::now();
for ident in idents { for ident in idents {
......
...@@ -1195,14 +1195,14 @@ pub fn project_entrypoints_subscribe( ...@@ -1195,14 +1195,14 @@ pub fn project_entrypoints_subscribe(
) )
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, TaskInput, Encode, Decode, TraceRawVcs)] #[derive(
Debug, Clone, Copy, PartialEq, Eq, Hash, TaskInput, Encode, Decode, TraceRawVcs, NonLocalValue,
)]
enum HmrTarget { enum HmrTarget {
Client, Client,
Server, Server,
} }
unsafe impl turbo_tasks::NonLocalValue for HmrTarget {}
impl std::str::FromStr for HmrTarget { impl std::str::FromStr for HmrTarget {
type Err = String; type Err = String;
...@@ -1373,47 +1373,47 @@ pub fn project_hmr_events( ...@@ -1373,47 +1373,47 @@ pub fn project_hmr_events(
} }
#[napi(object)] #[napi(object)]
struct HmrIdentifiers { struct HmrChunkNames {
pub chunk_paths: Vec<RcStr>, pub chunk_names: Vec<RcStr>,
} }
#[turbo_tasks::value(serialization = "none")] #[turbo_tasks::value(serialization = "none")]
struct HmrIdentifiersWithIssues { struct HmrChunkNamesWithIssues {
chunk_paths: ReadRef<Vec<RcStr>>, chunk_names: ReadRef<Vec<RcStr>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>, issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>, diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>, effects: Arc<Effects>,
} }
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
fn project_container_client_hmr_identifiers_operation( fn project_container_client_hmr_chunk_names_operation(
container: ResolvedVc<ProjectContainer>, container: ResolvedVc<ProjectContainer>,
) -> Vc<Vec<RcStr>> { ) -> Vc<Vec<RcStr>> {
container.client_hmr_identifiers() container.client_hmr_chunk_names()
} }
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
fn project_server_hmr_identifiers_operation( fn project_server_hmr_chunk_names_operation(
container: ResolvedVc<ProjectContainer>, container: ResolvedVc<ProjectContainer>,
) -> Vc<Vec<RcStr>> { ) -> Vc<Vec<RcStr>> {
container.project().server_hmr_identifiers() container.project().server_hmr_chunk_names()
} }
#[turbo_tasks::function(operation)] #[turbo_tasks::function(operation)]
async fn get_hmr_identifiers_with_issues_operation( async fn get_hmr_chunk_names_with_issues_operation(
container: ResolvedVc<ProjectContainer>, container: ResolvedVc<ProjectContainer>,
target: HmrTarget, target: HmrTarget,
) -> Result<Vc<HmrIdentifiersWithIssues>> { ) -> Result<Vc<HmrChunkNamesWithIssues>> {
let hmr_identifiers_op = match target { let hmr_chunk_names_op = match target {
HmrTarget::Client => project_container_client_hmr_identifiers_operation(container), HmrTarget::Client => project_container_client_hmr_chunk_names_operation(container),
HmrTarget::Server => project_server_hmr_identifiers_operation(container), HmrTarget::Server => project_server_hmr_chunk_names_operation(container),
}; };
let hmr_identifiers = hmr_identifiers_op.read_strongly_consistent().await?; let hmr_chunk_names = hmr_chunk_names_op.read_strongly_consistent().await?;
let issues = get_issues(hmr_identifiers_op, NEXT_ISSUE_FILTER).await?; let issues = get_issues(hmr_chunk_names_op, NEXT_ISSUE_FILTER).await?;
let diagnostics = get_diagnostics(hmr_identifiers_op).await?; let diagnostics = get_diagnostics(hmr_chunk_names_op).await?;
let effects = Arc::new(get_effects(hmr_identifiers_op).await?); let effects = Arc::new(get_effects(hmr_chunk_names_op).await?);
Ok(HmrIdentifiersWithIssues { Ok(HmrChunkNamesWithIssues {
chunk_paths: hmr_identifiers, chunk_names: hmr_chunk_names,
issues, issues,
diagnostics, diagnostics,
effects, effects,
...@@ -1421,9 +1421,9 @@ async fn get_hmr_identifiers_with_issues_operation( ...@@ -1421,9 +1421,9 @@ async fn get_hmr_identifiers_with_issues_operation(
.cell()) .cell())
} }
#[tracing::instrument(level = "info", name = "get HMR identifiers", skip(project, func), fields(target = %target))] #[tracing::instrument(level = "info", name = "get HMR chunk names", skip(project, func), fields(target = %target))]
#[napi(ts_return_type = "{ __napiType: \"RootTask\" }")] #[napi(ts_return_type = "{ __napiType: \"RootTask\" }")]
pub fn project_hmr_identifiers_subscribe( pub fn project_hmr_chunk_names_subscribe(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>, #[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: External<ProjectInstance>,
target: String, target: String,
func: JsFunction, func: JsFunction,
...@@ -1437,26 +1437,26 @@ pub fn project_hmr_identifiers_subscribe( ...@@ -1437,26 +1437,26 @@ pub fn project_hmr_identifiers_subscribe(
project.turbopack_ctx.clone(), project.turbopack_ctx.clone(),
func, func,
move || async move { move || async move {
let hmr_identifiers_with_issues_op = let hmr_chunk_names_with_issues_op =
get_hmr_identifiers_with_issues_operation(container, hmr_target); get_hmr_chunk_names_with_issues_operation(container, hmr_target);
let HmrIdentifiersWithIssues { let HmrChunkNamesWithIssues {
chunk_paths, chunk_names,
issues, issues,
diagnostics, diagnostics,
effects, effects,
} = &*hmr_identifiers_with_issues_op } = &*hmr_chunk_names_with_issues_op
.read_strongly_consistent() .read_strongly_consistent()
.await?; .await?;
effects.apply().await?; effects.apply().await?;
Ok((chunk_paths.clone(), issues.clone(), diagnostics.clone())) Ok((chunk_names.clone(), issues.clone(), diagnostics.clone()))
}, },
move |ctx| { move |ctx| {
let (chunk_paths, issues, diagnostics) = ctx.value; let (chunk_names, issues, diagnostics) = ctx.value;
Ok(vec![TurbopackResult { Ok(vec![TurbopackResult {
result: HmrIdentifiers { result: HmrChunkNames {
chunk_paths: ReadRef::into_owned(chunk_paths), chunk_names: ReadRef::into_owned(chunk_names),
}, },
issues: issues issues: issues
.iter() .iter()
......
...@@ -319,10 +319,10 @@ export declare function projectHmrEvents( ...@@ -319,10 +319,10 @@ export declare function projectHmrEvents(
target: string, target: string,
func: (...args: any[]) => any func: (...args: any[]) => any
): { __napiType: 'RootTask' } ): { __napiType: 'RootTask' }
export interface HmrIdentifiers { export interface HmrChunkNames {
chunkPaths: Array<RcStr> chunkNames: Array<RcStr>
} }
export declare function projectHmrIdentifiersSubscribe( export declare function projectHmrChunkNamesSubscribe(
project: { __napiType: 'Project' }, project: { __napiType: 'Project' },
target: string, target: string,
func: (...args: any[]) => any func: (...args: any[]) => any
......
...@@ -27,7 +27,7 @@ import type { ...@@ -27,7 +27,7 @@ import type {
CompilationEvent, CompilationEvent,
DefineEnv, DefineEnv,
Endpoint, Endpoint,
HmrIdentifiers, HmrChunkNames,
Lockfile, Lockfile,
NodeJsHmrUpdate, NodeJsHmrUpdate,
PartialProjectOptions, PartialProjectOptions,
...@@ -765,11 +765,11 @@ function bindingToApi( ...@@ -765,11 +765,11 @@ function bindingToApi(
* Chunk paths are output file paths like "server/chunks/ssr/..._.js" for server * Chunk paths are output file paths like "server/chunks/ssr/..._.js" for server
* or "_next/static/chunks/app/page.js" for client. * or "_next/static/chunks/app/page.js" for client.
*/ */
hmrIdentifiersSubscribe(target: HmrTarget) { hmrChunkNamesSubscribe(target: HmrTarget) {
return subscribe<TurbopackResult<HmrIdentifiers>>( return subscribe<TurbopackResult<HmrChunkNames>>(
false, false,
async (callback) => async (callback) =>
binding.projectHmrIdentifiersSubscribe( binding.projectHmrChunkNamesSubscribe(
this._nativeProject, this._nativeProject,
target, target,
callback callback
......
...@@ -216,9 +216,9 @@ export interface NodeJsPartialHmrUpdate extends BaseUpdate { ...@@ -216,9 +216,9 @@ export interface NodeJsPartialHmrUpdate extends BaseUpdate {
export type NodeJsHmrUpdate = IssuesUpdate | NodeJsPartialHmrUpdate export type NodeJsHmrUpdate = IssuesUpdate | NodeJsPartialHmrUpdate
export interface HmrIdentifiers { export interface HmrChunkNames {
/** Paths to output chunks that can receive HMR updates (e.g., "server/chunks/ssr/..._.js") */ /** Relative paths to output chunks that can receive HMR updates (e.g., "server/chunks/ssr/..._.js") */
chunkPaths: string[] chunkNames: string[]
} }
/** @see https://github.com/vercel/next.js/blob/415cd74b9a220b6f50da64da68c13043e9b02995/crates/next-napi-bindings/src/next_api/project.rs#L824-L833 */ /** @see https://github.com/vercel/next.js/blob/415cd74b9a220b6f50da64da68c13043e9b02995/crates/next-napi-bindings/src/next_api/project.rs#L824-L833 */
...@@ -277,9 +277,9 @@ export interface Project { ...@@ -277,9 +277,9 @@ export interface Project {
target: import('./index').HmrTarget.Server target: import('./index').HmrTarget.Server
): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>> ): AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
hmrIdentifiersSubscribe( hmrChunkNamesSubscribe(
target: import('./index').HmrTarget target: import('./index').HmrTarget
): AsyncIterableIterator<TurbopackResult<HmrIdentifiers>> ): AsyncIterableIterator<TurbopackResult<HmrChunkNames>>
getSourceForAsset(filePath: string): Promise<string | null> getSourceForAsset(filePath: string): Promise<string | null>
......
...@@ -204,14 +204,12 @@ function setupServerHmr(project: Project) { ...@@ -204,14 +204,12 @@ function setupServerHmr(project: Project) {
// Listen to the Rust bindings update us on changing server HMR chunk paths // Listen to the Rust bindings update us on changing server HMR chunk paths
;(async () => { ;(async () => {
const serverHmrChunkPaths = project.hmrIdentifiersSubscribe( const serverHmrChunkPaths = project.hmrChunkNamesSubscribe(HmrTarget.Server)
HmrTarget.Server
)
// Process chunk paths (both initial and subsequent updates) // Process chunk paths (both initial and subsequent updates)
for await (const data of serverHmrChunkPaths) { for await (const data of serverHmrChunkPaths) {
const currentChunkPaths = new Set( const currentChunkPaths = new Set(
data.chunkPaths.filter((path) => path.endsWith('.js')) data.chunkNames.filter((path) => path.endsWith('.js'))
) )
// Clean up subscriptions for removed chunk paths (like when pages are deleted) // Clean up subscriptions for removed chunk paths (like when pages are deleted)
......
...@@ -666,14 +666,14 @@ describe('next.rs api', () => { ...@@ -666,14 +666,14 @@ describe('next.rs api', () => {
} }
const result = await project const result = await project
.hmrIdentifiersSubscribe(HmrTarget.Client) .hmrChunkNamesSubscribe(HmrTarget.Client)
.next() .next()
expect(result.done).toBe(false) expect(result.done).toBe(false)
const chunkPaths = result.value.chunk_paths const chunkNames = result.value.chunkNames
expect(chunkPaths).toHaveProperty('length', expect.toBePositive()) expect(chunkNames).toHaveProperty('length', expect.toBePositive())
const subscriptions = chunkPaths.map((chunkPath) => const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(chunkPath, HmrTarget.Client) project.hmrEvents(chunkName, HmrTarget.Client)
) )
await Promise.all( await Promise.all(
subscriptions.map(async (subscription) => { subscriptions.map(async (subscription) => {
...@@ -795,14 +795,12 @@ describe('next.rs api', () => { ...@@ -795,14 +795,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 const result = await project.hmrChunkNamesSubscribe(HmrTarget.Client).next()
.hmrIdentifiersSubscribe(HmrTarget.Client)
.next()
expect(result.done).toBe(false) expect(result.done).toBe(false)
const identifiers = result.value.identifiers const chunkNames = result.value.chunkNames
const subscriptions = identifiers.map((identifier) => const subscriptions = chunkNames.map((chunkName) =>
project.hmrEvents(identifier, HmrTarget.Client) project.hmrEvents(chunkName, HmrTarget.Client)
) )
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