Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 25 additions & 14 deletions crates/next-api/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1836,32 +1836,43 @@ impl Project {
///
/// Use this instead of [Self::whole_app_module_graphs] when you need to collect issues from
/// the computation (e.g. for the `get_compilation_issues` MCP tool).
#[turbo_tasks::function]
///
/// Session dependent so that it scales down the Node.js pool in every session, see
/// [Self::whole_app_module_graphs].
#[turbo_tasks::function(session_dependent)]
pub async fn whole_app_module_graphs_without_dropping_issues(
self: ResolvedVc<Self>,
) -> Result<Vc<BaseAndFullModuleGraph>> {
let module_graphs_op = whole_app_module_graph_operation(self);
let module_graphs_vc = module_graphs_op.connect();
// Wait for the graph before scaling down the Node.js pool, see `whole_app_module_graphs`.
let module_graphs_vc = module_graphs_op.resolve().strongly_consistent().await;
scale_down_node_pool(self).await?;
Ok(module_graphs_vc)
Ok(*module_graphs_vc?)
}

/// Computes the whole app module graph, dropping issues in development mode so that
/// individual routes don't each report every issue from the shared graph.
#[turbo_tasks::function(root)]
///
/// Session dependent so that it executes, and scales down the Node.js pool, in every session.
/// With a warm cache, loaders run again for changed modules, but the graph's own tasks don't
/// necessarily execute again. Executing it again is cheap: the graph is read from the cache,
/// and its result doesn't change unless the graph did.
#[turbo_tasks::function(root, session_dependent)]
pub async fn whole_app_module_graphs(
self: ResolvedVc<Self>,
) -> Result<Vc<BaseAndFullModuleGraph>> {
let module_graphs_op = whole_app_module_graph_operation(self);
let module_graphs_vc = if self.next_mode().await?.is_production() {
module_graphs_op.connect()
} else {
let vc = module_graphs_op.resolve().strongly_consistent().await?;
module_graphs_op.drop_issues();
*vc
};
// Wait for the graph, and everything computed under it, before scaling down the Node.js
// pool below. Otherwise the pool would be scaled down before the graph's loaders spawn
// their processes, which would then stay alive until the build exits.
// Scale down even if computing the graph failed, so a failed build doesn't keep them.
let module_graphs_vc = module_graphs_op.resolve().strongly_consistent().await;
scale_down_node_pool(self).await?;
Ok(module_graphs_vc)
let module_graphs_vc = module_graphs_vc?;
if !self.next_mode().await?.is_production() {
module_graphs_op.drop_issues();
}
Ok(*module_graphs_vc)
}

#[turbo_tasks::function]
Expand Down Expand Up @@ -3198,9 +3209,9 @@ async fn scale_down_node_pool(project: ResolvedVc<Project>) -> Result<()> {
let execution_context = project.execution_context().await?;
let node_backend = execution_context.node_backend.into_trait_ref().await?;
if *project.is_watch_enabled().await? {
node_backend.scale_down()?;
node_backend.scale_down();
} else {
node_backend.scale_zero()?;
node_backend.scale_zero();
}
Ok(())
}
Expand Down
12 changes: 12 additions & 0 deletions crates/next-napi-bindings/src/next_api/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,8 @@ pub struct ProjectInstance {
// Never locked across an await point.
exit_receiver: Mutex<Option<ExitReceiver>>,
shutdown: Arc<ShutdownHooks>,
/// Whether the file system is watched, i.e. whether the Node.js pools are kept warm.
watch: bool,
// Pin the ProjectContainer for as long as this struct survives.
_container_gc_root: GcRoot<ProjectContainer>,
}
Expand Down Expand Up @@ -651,6 +653,7 @@ pub fn project_new<'env>(

let options = options.into_project_options();
let is_dev = options.dev;
let watch = options.watch.enable;
let root_path = options.root_path.clone();
let shutdown = Arc::new(ShutdownHooks::default());
let shutdown_hooks = shutdown.clone();
Expand Down Expand Up @@ -717,6 +720,7 @@ pub fn project_new<'env>(
container,
exit_receiver: Mutex::new(Some(exit_receiver)),
shutdown,
watch,
_container_gc_root: container_gc_root,
}),
},
Expand Down Expand Up @@ -939,6 +943,14 @@ pub async fn project_shutdown(
#[napi(ts_arg_type = "{ __napiType: \"Project\" }")] project: &External<ProjectInstance>,
) -> napi::Result<()> {
let tt = project.turbopack_ctx.turbo_tasks();
// Without watching, the pools were scaled to zero once the module graph was built (see
// `Project::whole_app_module_graphs`), so no Node.js process should still be holding memory.
debug_assert!(
project.watch || turbopack_node::idle_node_process_count() == 0,
"{} idle Node.js processes are still running at shutdown, but they should have been \
stopped after building the module graph",
turbopack_node::idle_node_process_count()
);
let eager_purge = TurboMalloc::enter_eager_purge_mode();
run_shutdown_hooks(project).await;
tt.stop_and_wait().await;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
import { execFileSync } from 'node:child_process'
import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

const dirname = path.dirname(fileURLToPath(import.meta.url))

/**
* Counts Turbopack's Node.js loader processes that are still running. They are
* children of the build process, so this only sees this build's processes.
*/
function countLoaderProcesses() {
try {
return execFileSync('ps', ['-A', '-ww', '-o', 'ppid=,command='], {
encoding: 'utf8',
})
.split('\n')
.map((line) => line.trim().match(/^(\d+)\s+(.*)$/))
.filter(
(match) =>
match &&
Number(match[1]) === process.pid &&
match[2].includes('[turbopack-node]')
).length
} catch {
// `ps` isn't available, e.g. on Windows.
return 'unknown'
}
}

export default {
turbopack: {
rules: {
Expand All @@ -11,4 +36,12 @@ export default {
},
},
},
compiler: {
async runAfterProductionCompile({ distDir }) {
await fs.writeFile(
path.join(distDir, 'loader-processes.txt'),
String(countLoaderProcesses())
)
},
},
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,37 @@ import { nextTestSetup } from 'e2e-utils'
describe('webpack-loader-traced-imports', () => {
const { next } = nextTestSetup({
files: __dirname,
env: {
// Locally built native bindings disable the persistent cache in a dirty
// checkout, which the warm build below relies on.
TURBO_ENGINE_IGNORE_DIRTY: '1',
},
})

it('builds when a loader resolves a module with a dynamic require', async () => {
const $ = await next.render$('/')
expect($('main').text()).toBe('Webpack loader traced imports')
})

// Turbopack's Node.js loader processes should exit once the module graph is
// built, instead of staying alive (and holding memory) until the build exits.
// `runAfterProductionCompile` in next.config.mjs counts them right after
// compilation. Webpack has no such processes, and counting needs `ps`.
// @force-gate turbopack && !windows
it('stops loader processes after compilation', async () => {
expect(await next.readFile('.next/loader-processes.txt')).toBe('0')
})

// A warm build runs the loader again for the edited page, without
// necessarily executing the module graph's own tasks again.
// @force-gate turbopack && !windows
it('stops loader processes after compilation in a warm build', async () => {
await next.stop()
await next.patchFile('app/page.tsx', (content) =>
content!.replace('</main>', ' (edited)</main>')
)
const { exitCode } = await next.build()
expect(exitCode).toBe(0)
expect(await next.readFile('.next/loader-processes.txt')).toBe('0')
})
})
6 changes: 4 additions & 2 deletions turbopack/crates/turbopack-node/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,9 @@ pub trait NodeBackend: sealed::Sealed {

fn create_pool(&self, options: CreatePoolOptions) -> CreatePoolFuture;

fn scale_down(&self) -> Result<()>;
/// Stops all idle processes of each pool except one.
fn scale_down(&self);

fn scale_zero(&self) -> Result<()>;
/// Stops all idle processes of each pool.
fn scale_zero(&self);
}
11 changes: 11 additions & 0 deletions turbopack/crates/turbopack-node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ pub fn worker_threads_backend() -> Vc<Box<dyn backend::NodeBackend>> {
Vc::upcast(worker_pool::WorkerThreadsBackend.cell())
}

/// The number of idle Node.js processes and worker threads across all pools. Pools are scaled
/// to zero after building the module graph when not watching, so this should be 0 at shutdown.
pub fn idle_node_process_count() -> usize {
let count = 0;
#[cfg(all(feature = "process_pool", not(target_family = "wasm")))]
let count = count + process_pool::idle_process_count();
#[cfg(feature = "worker_pool")]
let count = count + worker_pool::idle_worker_count();
count
}

#[turbo_tasks::function]
async fn emit(
intermediate_asset: Vc<Box<dyn OutputAsset>>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ impl<T: Ord> HeapQueue<T> {
Ok(item)
}

pub(super) fn len(&self) -> usize {
self.heap.lock().len()
}

pub(super) fn reduce_to_one(&self) {
// Drain the semaphore permits
let mut n = self.semaphore.forget_permits(usize::MAX);
Expand Down
40 changes: 24 additions & 16 deletions turbopack/crates/turbopack-node/src/process_pool/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -733,14 +733,12 @@ impl NodeBackend for ChildProcessesBackend {
})
}

fn scale_down(&self) -> Result<()> {
ChildProcessPool::scale_down();
Ok(())
fn scale_down(&self) {
scale_down();
}

fn scale_zero(&self) -> Result<()> {
ChildProcessPool::scale_zero();
Ok(())
fn scale_zero(&self) {
scale_zero();
}
}

Expand Down Expand Up @@ -867,19 +865,29 @@ impl ChildProcessPool {
.await
.context("creating new process")
}
}

fn scale_down() {
let pools = ACTIVE_POOLS.lock().clone();
for pool in pools {
pool.reduce_to_one();
}
/// The number of idle processes across all pools.
pub(crate) fn idle_process_count() -> usize {
// Release `ACTIVE_POOLS` before locking the heaps: `HeapQueue` locks its heap first, then
// `ACTIVE_POOLS`, so holding both in the other order could deadlock.
let pools = ACTIVE_POOLS.lock().clone();
pools.iter().map(|pool| pool.len()).sum()
}

/// Stops all idle processes of each pool except one.
fn scale_down() {
let pools = ACTIVE_POOLS.lock().clone();
for pool in pools {
pool.reduce_to_one();
}
}

fn scale_zero() {
let pools = ACTIVE_POOLS.lock().clone();
for pool in pools {
pool.reduce_to_zero(&ACTIVE_POOLS);
}
/// Stops all idle processes of each pool.
fn scale_zero() {
let pools = ACTIVE_POOLS.lock().clone();
for pool in pools {
pool.reduce_to_zero(&ACTIVE_POOLS);
}
}

Expand Down
21 changes: 7 additions & 14 deletions turbopack/crates/turbopack-node/src/worker_pool/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,25 +197,18 @@ impl NodeBackend for WorkerThreadsBackend {
})
}

fn scale_down(&self) -> Result<()> {
WorkerThreadPool::scale_down();
Ok(())
fn scale_down(&self) {
WORKER_POOL_OPERATION.scale_down();
}

fn scale_zero(&self) -> Result<()> {
WorkerThreadPool::scale_zero();
Ok(())
fn scale_zero(&self) {
WORKER_POOL_OPERATION.scale_zero();
}
}

impl WorkerThreadPool {
fn scale_down() {
let _ = WORKER_POOL_OPERATION.scale_down();
}

fn scale_zero() {
let _ = WORKER_POOL_OPERATION.scale_zero();
}
/// The number of idle workers across all pools.
pub(crate) fn idle_worker_count() -> usize {
WORKER_POOL_OPERATION.idle_worker_count()
}

#[async_trait::async_trait]
Expand Down
Loading
Loading