Unverified Commit ee885f86 authored by Andrew Imm's avatar Andrew Imm Committed by GitHub

Pre-warm a single NodeJS instance when the next devserver starts (#90174)

When cold-booting `next dev` on a fresh create-next-app, on the first server hit we need to fetch fonts and compile CSS, which takes up nearly half of the request time.

It shouldn't be necessary to wait until the first server request to launch the first NodeJS process (eventually used for PostCSS processing in Tailwind). Once the server has started, we can anticipate that first request and pre-warm a single Node process.

Because we grab the boot semaphore, if a request comes in as soon as the server is ready, it waits on the semaphore to resolve, and at most it takes as long as it would before this change. In all likelihood, the Node process is ready before any server request comes in.

It also slightly saves time on `next build`

I'd appreciate scrutiny of all the ways this can go wrong.
parent 0db78041
......@@ -10193,9 +10193,11 @@ dependencies = [
"turbo-bincode",
"turbo-rcstr",
"turbo-tasks",
"turbo-tasks-backend",
"turbo-tasks-bytes",
"turbo-tasks-env",
"turbo-tasks-fs",
"turbo-tasks-testing",
"turbopack-cli-utils",
"turbopack-core",
"turbopack-ecmascript",
......
......@@ -48,3 +48,8 @@ turbopack-core = { workspace = true }
turbopack-ecmascript = { workspace = true }
turbopack-resolve = { workspace = true }
[dev-dependencies]
rustc-hash = { workspace = true }
turbo-tasks-backend = { workspace = true }
turbo-tasks-testing = { workspace = true }
......@@ -200,6 +200,7 @@ pub async fn get_evaluate_pool(
available_parallelism().map_or(1, |v| v.get()),
debug,
);
pool.pre_warm();
additional_invalidation.await?;
Ok(pool.cell())
}
......
......@@ -18,7 +18,7 @@ pub mod embed_js;
pub mod evaluate;
pub mod execution_context;
mod heap_queue;
mod pool;
pub mod pool;
pub mod source_map;
pub mod transforms;
......
......@@ -509,6 +509,21 @@ impl NodeJsPoolProcess {
}
}
/// A snapshot of pool statistics, useful for testing and diagnostics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PoolStatsSnapshot {
/// Total number of processes ever successfully booted.
pub bootup_count: u32,
/// Number of completed operations that reused an idle process.
pub warm_operation_count: u32,
/// Number of completed operations that spawned a fresh process.
pub cold_operation_count: u32,
/// Current number of tracked workers (booting + idle + in-use).
pub workers: u32,
/// Current number of workers still booting.
pub booting_workers: u32,
}
#[derive(Default)]
struct NodeJsPoolStats {
pub total_bootup_time: Duration,
......@@ -676,6 +691,40 @@ type IdleProcessQueues = Mutex<Vec<Arc<HeapQueue<NodeJsPoolProcess>>>>;
/// This is used to scale down processes globally.
static ACTIVE_POOLS: Lazy<IdleProcessQueues> = Lazy::new(Default::default);
/// Arguments needed to spawn a new Node.js process. Extracted so that
/// `pre_warm` can clone them once instead of cloning each pool field
/// individually.
struct ProcessArgs {
cwd: PathBuf,
env: FxHashMap<RcStr, RcStr>,
entrypoint: PathBuf,
assets_for_source_mapping: ResolvedVc<AssetsForSourceMapping>,
assets_root: FileSystemPath,
project_dir: FileSystemPath,
shared_stdout: SharedOutputSet,
shared_stderr: SharedOutputSet,
debug: bool,
}
impl ProcessArgs {
async fn create_process(self) -> Result<(NodeJsPoolProcess, Duration)> {
let start = Instant::now();
let process = NodeJsPoolProcess::new(
&self.cwd,
&self.env,
&self.entrypoint,
self.assets_for_source_mapping,
self.assets_root,
self.project_dir,
self.shared_stdout,
self.shared_stderr,
self.debug,
)
.await?;
Ok((process, start.elapsed()))
}
}
/// A pool of Node.js workers operating on [entrypoint] with specific [cwd] and
/// [env].
///
......@@ -714,7 +763,7 @@ pub struct NodeJsPool {
impl NodeJsPool {
/// * debug: Whether to automatically enable Node's `--inspect-brk` when spawning it. Note:
/// automatically overrides concurrency to 1.
pub(super) fn new(
pub fn new(
cwd: PathBuf,
entrypoint: PathBuf,
env: FxHashMap<RcStr, RcStr>,
......@@ -779,22 +828,25 @@ impl NodeJsPool {
}
}
fn process_args(&self) -> ProcessArgs {
ProcessArgs {
cwd: self.cwd.clone(),
env: self.env.clone(),
entrypoint: self.entrypoint.clone(),
assets_for_source_mapping: self.assets_for_source_mapping,
assets_root: self.assets_root.clone(),
project_dir: self.project_dir.clone(),
shared_stdout: self.shared_stdout.clone(),
shared_stderr: self.shared_stderr.clone(),
debug: self.debug,
}
}
async fn create_process(&self) -> Result<(NodeJsPoolProcess, Duration), anyhow::Error> {
let start = Instant::now();
let process = NodeJsPoolProcess::new(
self.cwd.as_path(),
&self.env,
self.entrypoint.as_path(),
self.assets_for_source_mapping,
self.assets_root.clone(),
self.project_dir.clone(),
self.shared_stdout.clone(),
self.shared_stderr.clone(),
self.debug,
)
.await
.context("creating new process")?;
Ok((process, start.elapsed()))
self.process_args()
.create_process()
.await
.context("creating new process")
}
pub async fn operation(&self) -> Result<NodeJsOperation> {
......@@ -811,6 +863,42 @@ impl NodeJsPool {
})
}
/// Eagerly spawn a Node.js process so it's ready when the first
/// `operation()` is called. The process goes into the idle queue.
/// If a node request comes in while this is still initializing, it waits
/// on the bootup semaphore and will resume when the process is ready.
pub fn pre_warm(&self) {
let args = self.process_args();
let bootup_semaphore = self.bootup_semaphore.clone();
let idle_processes = self.idle_processes.clone();
let stats = self.stats.clone();
tokio::spawn(async move {
let Ok(bootup_permit) = bootup_semaphore.clone().acquire_owned().await else {
return;
};
{
stats.lock().add_booting_worker();
}
match args.create_process().await {
Ok((process, bootup_time)) => {
{
let mut s = stats.lock();
s.add_bootup_time(bootup_time);
s.finished_booting_worker();
}
drop(bootup_permit);
idle_processes.push(process, &ACTIVE_POOLS);
}
Err(_e) => {
let mut s = stats.lock();
s.finished_booting_worker();
s.remove_worker();
}
}
});
}
pub fn scale_down() {
let pools = ACTIVE_POOLS.lock().clone();
for pool in pools {
......@@ -824,6 +912,18 @@ impl NodeJsPool {
pool.reduce_to_zero(&ACTIVE_POOLS);
}
}
/// Returns a snapshot of the pool's internal statistics.
pub fn stats(&self) -> PoolStatsSnapshot {
let s = self.stats.lock();
PoolStatsSnapshot {
bootup_count: s.bootup_count,
warm_operation_count: s.warm_process_count,
cold_operation_count: s.cold_process_count,
workers: s.workers,
booting_workers: s.booting_workers,
}
}
}
pub struct NodeJsOperation {
......
#![feature(arbitrary_self_types)]
#![feature(arbitrary_self_types_pointers)]
use std::path::PathBuf;
use anyhow::Result;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use turbo_rcstr::RcStr;
use turbo_tasks::Vc;
use turbo_tasks_fs::{FileSystemPath, VirtualFileSystem};
use turbo_tasks_testing::{Registration, register, run_once_without_cache_check};
use turbopack_node::{AssetsForSourceMapping, pool::NodeJsPool};
static REGISTRATION: Registration = register!();
fn test_worker(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("tests/{name}"))
}
/// Create a pool backed by the given test worker JS file.
async fn create_pool(worker: &str, concurrency: usize) -> Result<NodeJsPool> {
let vfs = VirtualFileSystem::new();
let fs: Vc<Box<dyn turbo_tasks_fs::FileSystem>> = Vc::upcast(vfs);
let fs = fs.to_resolved().await?;
let root_path = FileSystemPath {
fs,
path: RcStr::default(),
};
let assets: Vc<AssetsForSourceMapping> = Vc::cell(Default::default());
let assets = assets.to_resolved().await?;
Ok(NodeJsPool::new(
std::env::current_dir()?,
test_worker(worker),
FxHashMap::default(),
assets,
root_path.clone(),
root_path,
concurrency,
false,
))
}
/// Shorthand: create a pool with the echo worker.
async fn create_test_pool(concurrency: usize) -> Result<NodeJsPool> {
create_pool("pool_test_worker.js", concurrency).await
}
/// Every response from the test worker includes the worker's PID, allowing
/// tests to verify whether the same OS process was reused across operations.
#[derive(Serialize, Deserialize, Debug)]
struct Echo {
echo: serde_json::Value,
pid: u32,
}
/// Helper: send a message and return the echo response.
async fn send_recv(op: &mut turbopack_node::pool::NodeJsOperation, msg: serde_json::Value) -> Echo {
op.send(msg).await.unwrap();
op.recv().await.unwrap()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_pool_single_operation() {
run_once_without_cache_check(&REGISTRATION, async {
let pool = create_test_pool(2).await.unwrap();
let mut op = pool.operation().await.unwrap();
let msg = serde_json::json!({"hello": "world"});
let resp = send_recv(&mut op, msg.clone()).await;
assert_eq!(resp.echo, msg);
assert!(resp.pid > 0);
drop(op);
let stats = pool.stats();
assert_eq!(stats.bootup_count, 1);
assert_eq!(stats.cold_operation_count, 1);
assert_eq!(stats.warm_operation_count, 0);
})
.await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_pool_process_reuse() {
run_once_without_cache_check(&REGISTRATION, async {
let pool = create_test_pool(2).await.unwrap();
// First operation — spawns a new process.
let pid1 = {
let mut op = pool.operation().await.unwrap();
let resp = send_recv(&mut op, serde_json::json!({"round": 1})).await;
resp.pid
// op is dropped here, returning the process to the idle queue.
};
let stats = pool.stats();
assert_eq!(stats.bootup_count, 1);
assert_eq!(stats.cold_operation_count, 1);
// Second operation — should reuse the same process.
let pid2 = {
let mut op = pool.operation().await.unwrap();
let resp = send_recv(&mut op, serde_json::json!({"round": 2})).await;
resp.pid
};
assert_eq!(
pid1, pid2,
"expected the second operation to reuse the same process"
);
let stats = pool.stats();
assert_eq!(
stats.bootup_count, 1,
"no new process should have been spawned"
);
assert_eq!(
stats.warm_operation_count, 1,
"second op should be warm (reused)"
);
assert_eq!(
stats.cold_operation_count, 1,
"only the first op should be cold"
);
})
.await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_pool_pre_warm() {
run_once_without_cache_check(&REGISTRATION, async {
let pool = create_test_pool(2).await.unwrap();
// Pre-warm spawns a process in the background.
pool.pre_warm();
// Wait for the pre-warmed process to finish booting.
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
loop {
if pool.stats().bootup_count == 1 {
break;
}
assert!(
tokio::time::Instant::now() < deadline,
"pre_warm did not complete within timeout"
);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
assert_eq!(pool.stats().workers, 1);
// The first operation should pick up the pre-warmed idle process,
// registering as a warm (not cold) operation.
let mut op = pool.operation().await.unwrap();
let resp = send_recv(&mut op, serde_json::json!({"pre_warmed": true})).await;
assert_eq!(resp.echo, serde_json::json!({"pre_warmed": true}));
drop(op);
let stats = pool.stats();
assert_eq!(
stats.bootup_count, 1,
"no additional process should have been spawned"
);
assert_eq!(
stats.warm_operation_count, 1,
"operation should have reused the pre-warmed process"
);
assert_eq!(stats.cold_operation_count, 0, "no cold operations expected");
})
.await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_pool_concurrent_operations() {
run_once_without_cache_check(&REGISTRATION, async {
let pool = create_test_pool(2).await.unwrap();
// Force two separate processes into the idle pool by holding the first
// operation open while starting the second. This prevents the pool from
// reusing the first process for the second request.
let pid1;
let pid2;
{
let mut op1 = pool.operation().await.unwrap();
// op1 is still held, so the pool must spawn a second process.
let mut op2 = pool.operation().await.unwrap();
pid1 = send_recv(&mut op1, serde_json::json!({"warmup": 1}))
.await
.pid;
pid2 = send_recv(&mut op2, serde_json::json!({"warmup": 2}))
.await
.pid;
}
assert_ne!(
pid1, pid2,
"holding two operations should use different processes"
);
let stats = pool.stats();
assert_eq!(stats.bootup_count, 2);
assert_eq!(stats.cold_operation_count, 2);
// Both processes are now idle. Run two operations concurrently — they
// should each pick up one of the idle processes.
let (r1, r2) = tokio::join!(
async {
let mut op = pool.operation().await.unwrap();
send_recv(&mut op, serde_json::json!({"task": "a"})).await
},
async {
let mut op = pool.operation().await.unwrap();
send_recv(&mut op, serde_json::json!({"task": "b"})).await
}
);
assert_eq!(r1.echo, serde_json::json!({"task": "a"}));
assert_eq!(r2.echo, serde_json::json!({"task": "b"}));
assert_ne!(
r1.pid, r2.pid,
"expected concurrent operations to use different processes"
);
// Both PIDs should match the original two processes (reuse, no new spawns).
assert!(
(r1.pid == pid1 || r1.pid == pid2) && (r2.pid == pid1 || r2.pid == pid2),
"expected concurrent operations to reuse the pre-existing processes"
);
let stats = pool.stats();
assert_eq!(
stats.bootup_count, 2,
"no new processes should have been spawned"
);
assert_eq!(
stats.warm_operation_count, 2,
"both concurrent ops should be warm"
);
})
.await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_pool_pre_warm_failure() {
run_once_without_cache_check(&REGISTRATION, async {
let pool = create_pool("pool_test_broken_worker.js", 2).await.unwrap();
// Pre-warm with a worker that exits immediately (startup failure).
pool.pre_warm();
// Wait for the pre_warm task to observe the failure. Since the worker
// exits right away, this should resolve quickly. We poll until workers
// returns to 0 (the error path calls remove_worker).
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
loop {
let stats = pool.stats();
// add_booting_worker sets workers=1, booting_workers=1.
// On failure: finished_booting_worker + remove_worker resets both to 0.
if stats.workers == 0 && stats.booting_workers == 0 {
break;
}
assert!(
tokio::time::Instant::now() < deadline,
"pre_warm failure was not cleaned up within timeout"
);
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
}
let stats = pool.stats();
assert_eq!(
stats.bootup_count, 0,
"failed boot should not count as successful"
);
assert_eq!(
stats.workers, 0,
"failed pre_warm should not leave phantom workers"
);
assert_eq!(stats.booting_workers, 0);
})
.await;
}
// A broken worker that exits immediately without connecting.
// Used to test the pre_warm error path.
process.exit(1)
// Minimal Node.js worker that implements the turbopack-node pool wire protocol.
// Used by pool.rs integration tests.
//
// Wire protocol:
// - Messages are framed as [u32 BE length][payload bytes]
// - The ready signal is a 0-length message
// - After each TCP send, write "TURBOPACK_OUTPUT_D\n" to both stdout and stderr
// to signal the Rust side that console output for this operation is done.
const net = require('node:net')
const port = parseInt(process.argv[2], 10)
const socket = net.createConnection({ port, host: '127.0.0.1' }, () => {
socket.setNoDelay(true)
// Send empty ready signal (0-length message).
const readyBuf = Buffer.alloc(4)
readyBuf.writeUInt32BE(0, 0)
socket.write(readyBuf)
signalOutputDone()
})
// When the socket closes, exit cleanly.
socket.once('close', () => {
process.exit(0)
})
function signalOutputDone() {
process.stdout.write('TURBOPACK_OUTPUT_D\n')
process.stderr.write('TURBOPACK_OUTPUT_D\n')
}
function sendMessage(obj) {
const json = JSON.stringify(obj)
const payload = Buffer.from(json, 'utf8')
const header = Buffer.alloc(4)
header.writeUInt32BE(payload.length, 0)
socket.write(Buffer.concat([header, payload]))
signalOutputDone()
}
// --- Receive loop ---
// Read framed messages: 4-byte BE length prefix, then payload.
let recvBuf = Buffer.alloc(0)
socket.on('data', (chunk) => {
recvBuf = Buffer.concat([recvBuf, chunk])
drainMessages()
})
function drainMessages() {
while (true) {
if (recvBuf.length < 4) return
const len = recvBuf.readUInt32BE(0)
if (recvBuf.length < 4 + len) return
const payload = recvBuf.subarray(4, 4 + len)
recvBuf = recvBuf.subarray(4 + len)
handleMessage(JSON.parse(payload.toString('utf8')))
}
}
function handleMessage(msg) {
// Echo the message back along with this worker's PID so tests can verify
// whether the same process was reused across operations.
sendMessage({ echo: msg, pid: process.pid })
}
|name, initial| {
use std::hash::BuildHasher;
let path = std::path::PathBuf::from(
format!("{}/.cache/{}", env!("CARGO_TARGET_TMPDIR"), rustc_hash::FxBuildHasher.hash_one(name)));
if initial {
let _ = std::fs::remove_dir_all(&path);
}
std::fs::create_dir_all(&path).unwrap();
turbo_tasks::TurboTasks::new(
turbo_tasks_backend::TurboTasksBackend::new(
turbo_tasks_backend::BackendOptions {
num_workers: Some(2),
small_preallocation: true,
..Default::default()
},
turbo_tasks_backend::default_backing_storage(
path.as_path(),
&turbo_tasks_backend::GitVersionInfo {
describe: "test-unversioned",
dirty: false,
},
false,
true,
).unwrap().0
)
)
}
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