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

Reap crashed Turbopack plugin workers instead of hanging forever

When a worker-thread plugin runtime dies unexpectedly (uncaught exception,
process.exit, OOM), nothing told the Rust worker pool about it: the dead
Worker stayed in loaderWorkers, the operation waiting for its response
hung forever, and every later evaluation could be handed the dead worker,
wedging the dev server's compilation permanently. This is the crash-time
sibling of #96592, which covered evaluation and IPC errors reported over
the channel.

JavaScript now attaches 'error'/'exit' listeners to pooled workers and
reports any death while the worker is still registered (intentional
terminations remove the worker from the map first, so they are never
reported; the thread id is captured at creation since it resets to -1 by
the time 'exit' fires). On the Rust side, a dead-worker set records
reaped ids and handle_worker_death classifies the death:

- busy: closes the in-flight task's channel (via a watch channel, which
  cannot lose the wakeup), so its pending recv fails and surfaces through
  the existing subprocess-crash path in pull_operation - synthesized
  issue, disallow_reuse, fresh worker on the next evaluation;
- idle: removed from the idle list and pool statistics;
- created but unassigned (in transit to an acquirer or routed to a
  waiter): total worker count decremented;
- boot failure: the pending creation for the same pool is failed (so
  create_worker errors instead of waiting forever) and the booting
  statistics are balanced - no phantom workers after a boot crash.

Every acquisition and return path checks the dead set so a reaped id is
never handed out again: acquire_worker retries after dead candidates
(idle pop, waiter handoff, fresh boot), and WorkerOperation's drop skips
returning a worker that died while checked out.

Verified end to end with turbopackPluginRuntimeStrategy: 'workerThreads':

- before: a loader calling process.exit(1) hangs the request forever and
  wedges all later compilations;
- after: the request fails in ~1s with "Node.js subprocess crashed while
  evaluating loaders", and the next request is served by a fresh worker
  in ~50ms. A worker that dies between tasks (idle) is reaped the same
  way.

The new development test covers the crash path: baseline (stock binary)
fails by hanging; candidate fails the evaluation and recovers. The #96592
error-cleanup test still passes. Autoreview panel findings addressed:
watch-channel close, dead-set validation on all handoff paths,
options-tagged pending creations, clean-exit reaping.

Validation: pnpm build-all (TS + native), cargo fmt --check, cargo clippy
-p turbopack-node --all-targets -D warnings, cargo test -p turbopack-node
--lib, candidate integration test pass, exact baseline binary fails by
hanging.
Co-Authored-By: 's avatarMarcos Hernanz <96699542+marcoshernanz@users.noreply.github.com>
parent 865d623a
......@@ -39,7 +39,8 @@ export declare function registerWorkerScheduler(
creator: (arg: NapiWorkerCreation) => any,
terminator: (arg: NapiWorkerTermination) => any
): void
export declare function workerCreated(workerId: number): void
export declare function workerCreated(creation: NapiWorkerTermination): void
export declare function workerDied(termination: NapiWorkerTermination): void
export interface NapiWorkerCreation {
options: NapiWorkerOptions
}
......
......@@ -22,6 +22,10 @@ export async function runLoaderWorkerPool(
workerData: {
bindingPath,
cwd,
// The worker reports these exact options when it has booted:
// process.argv is inherited from the parent and cannot be used to
// identify the entrypoint.
filename,
},
})
......@@ -31,7 +35,30 @@ export async function runLoaderWorkerPool(
const workers =
loaderWorkers[poolId] || (loaderWorkers[poolId] = new Map())
workers.set(worker.threadId, worker)
// The thread id must be captured up-front: by the time the 'error' and
// 'exit' events fire, `worker.threadId` has already reset to -1.
const threadId = worker.threadId
workers.set(threadId, worker)
const reportWorkerDeath = () => {
// Intentional terminations remove the worker from the map before
// terminating it, so a worker that is no longer registered died on
// purpose and must not be reported again. Any exit while still
// registered is unexpected, including a clean `process.exit(0)`.
// `workerDied` may also be absent when the loaded native binding
// predates it; in that case there is nothing to notify.
if (!workers.has(threadId) || typeof bindings.workerDied !== 'function') {
return
}
workers.delete(threadId)
bindings.workerDied({
options: { filename, cwd },
workerId: threadId,
})
}
worker.once('error', reportWorkerDeath)
worker.once('exit', reportWorkerDeath)
},
(termination) => {
const {
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
const data = require('../input.crashprobe')
export default function Page() {
return <p>{data.default}</p>
}
module.exports = function crashLoader(source) {
const value = source.trim()
// Kills the worker before the evaluation result is reported back.
if (value === 'exit-during-eval') {
process.exit(1)
}
// Lets the evaluation succeed, then kills the worker asynchronously.
if (value === 'exit-after-eval') {
setTimeout(() => process.exit(1), 250)
return `export default "exit-after-eval"`
}
return `export default ${JSON.stringify(value)}`
}
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
turbopackPluginRuntimeStrategy: 'workerThreads',
},
turbopack: {
rules: {
'*.crashprobe': {
as: '*.js',
loaders: [
{
loader: require.resolve('./crash-loader.js'),
},
],
},
},
},
}
import { nextTestSetup } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils'
describe('turbopack worker thread crash recovery', () => {
const { next, isTurbopack } = nextTestSetup({
files: __dirname,
})
const itOnlyTurbopack = isTurbopack ? it : it.skip
itOnlyTurbopack(
'fails the evaluation instead of hanging when a loader worker dies, and recovers',
async () => {
expect((await next.render$('/'))('p').text()).toBe('initial')
// The loader calls process.exit(1), killing the worker thread before it
// reports the evaluation result. Without worker-death reaping this
// request would hang forever.
await next.patchFile('input.crashprobe', 'exit-during-eval')
await waitFor(1500)
// Trigger the evaluation. It fails the compile rather than hanging.
await next.fetch('/')
await retry(
async () => {
expect(next.cliOutput).toContain(
'Node.js subprocess crashed while evaluating'
)
},
30_000,
500
)
// The pool must hand out a fresh worker after the crash: a new
// evaluation with a working probe succeeds.
await next.patchFile('input.crashprobe', 'recovered')
await retry(async () => {
expect((await next.render$('/'))('p').text()).toBe('recovered')
})
},
60_000
)
})
......@@ -11,7 +11,10 @@ const binding: Binding = require(
/* turbopackIgnore: true */ workerData.bindingPath
)
binding.workerCreated(workerId)
binding.workerCreated({
options: { filename: workerData.filename, cwd: workerData.cwd },
workerId,
})
export const run = async (
moduleFactory: () => Promise<{
......
......@@ -11,7 +11,10 @@ export interface TaskMessage {
export interface Binding {
recvTaskMessageInWorker(workerId: number): Promise<TaskMessage>
sendTaskMessage(msg: TaskMessage): void
workerCreated(workerId: number): void
workerCreated(creation: {
options: { filename: string; cwd: string }
workerId: number
}): void
}
// Export this, maybe in the future, we can add an implementation via web worker on browser
......
......@@ -44,6 +44,15 @@ impl NodeJsPoolStats {
self.booting_workers = self.booting_workers.saturating_sub(1);
}
/// A worker that was being booted died before it could be used: both the
/// booting counter and the total worker counter have to be decremented or
/// the pool statistics leak a phantom worker per boot crash.
#[allow(unused)]
pub fn failed_booting_worker(&mut self) {
self.booting_workers = self.booting_workers.saturating_sub(1);
self.workers = self.workers.saturating_sub(1);
}
pub fn remove_worker(&mut self) {
self.workers = self.workers.saturating_sub(1);
}
......
......@@ -95,32 +95,51 @@ impl WorkerThreadPool {
}
async fn acquire_worker(&self) -> Result<(u32, AcquiredPermits)> {
let concurrency_permit = self.concurrency_semaphore.clone().acquire_owned().await?;
// Held in an Option so a retry after a dead candidate can reuse it.
let mut concurrency_permit =
Some(self.concurrency_semaphore.clone().acquire_owned().await?);
// A worker can die at any point between being routed to this
// acquisition and being registered for a task, so every candidate is
// validated against the dead-worker set and the acquisition retried.
// The death path owns all statistics for dead workers; skipped
// candidates need no accounting here. The retry is bounded so
// pathologically repeated deaths surface an error instead of
// spinning replacements forever.
let mut dead_candidates = 0;
loop {
{
let mut idle = self.state.idle_workers.lock();
if let Some(worker_id) = idle.pop() {
while let Some(worker_id) = idle.pop() {
if !WORKER_POOL_OPERATION.is_dead(worker_id) {
return Ok((
worker_id,
AcquiredPermits::Idle {
_concurrency_permit: concurrency_permit,
_concurrency_permit: concurrency_permit
.take()
.expect("concurrency permit used once"),
},
));
}
}
}
let (tx, rx) = oneshot::channel();
{
let mut waiters = self.state.waiters.lock();
let mut idle = self.state.idle_workers.lock();
if let Some(worker_id) = idle.pop() {
while let Some(worker_id) = idle.pop() {
if !WORKER_POOL_OPERATION.is_dead(worker_id) {
return Ok((
worker_id,
AcquiredPermits::Idle {
_concurrency_permit: concurrency_permit,
_concurrency_permit: concurrency_permit
.take()
.expect("concurrency permit used once"),
},
));
}
}
waiters.push(tx);
}
......@@ -131,10 +150,14 @@ impl WorkerThreadPool {
permit
};
select! {
let maybe_acquired = select! {
worker_id = rx => {
let worker_id = worker_id?;
Ok((worker_id, AcquiredPermits::Idle { _concurrency_permit: concurrency_permit }))
if WORKER_POOL_OPERATION.is_dead(worker_id) {
None
} else {
Some((worker_id, AcquiredPermits::Idle { _concurrency_permit: concurrency_permit.take().expect("concurrency permit used once") }))
}
}
bootup_permit = bootup => {
let bootup_permit = bootup_permit.context("acquiring bootup permit")?;
......@@ -143,13 +166,22 @@ impl WorkerThreadPool {
}
let worker_id = create_worker(self.worker_options.clone()).await?;
{
let mut stats = self.state.stats.lock();
stats.finished_booting_worker();
self.bootup_semaphore.add_permits(1);
if WORKER_POOL_OPERATION.is_dead(worker_id) {
None
} else {
Some((worker_id, AcquiredPermits::Fresh { _concurrency_permit: concurrency_permit.take().expect("concurrency permit used once"), _bootup_permit: bootup_permit }))
}
}
};
if let Some(acquired) = maybe_acquired {
return Ok(acquired);
}
self.bootup_semaphore.add_permits(1);
Ok((worker_id, AcquiredPermits::Fresh { _concurrency_permit: concurrency_permit, _bootup_permit: bootup_permit }))
dead_candidates += 1;
if dead_candidates >= 3 {
anyhow::bail!("acquired workers died repeatedly before they could be used");
}
}
}
......@@ -219,8 +251,18 @@ impl WorkerThreadPool {
#[async_trait::async_trait]
impl EvaluateOperation for WorkerThreadPool {
async fn operation(&self) -> Result<Box<dyn Operation>> {
// A worker can die between acquisition and task registration; the
// death path then owns the statistics and cannot close the (not yet
// existing) task channel, so registration is re-checked and the
// acquisition retried with a replacement worker. The retry is
// bounded so pathologically repeated deaths surface an error instead
// of spinning replacements forever.
let operation = {
let _guard = duration_span!("Node.js operation");
let mut attempts = 0;
loop {
attempts += 1;
let worker_options = self.worker_options.clone();
let task_id = OPERATION_TASK_ID.fetch_add(1, Ordering::Release);
......@@ -236,11 +278,31 @@ impl EvaluateOperation for WorkerThreadPool {
// Pre-allocate channels for this task to avoid HashMap lookups during communication
let channels = TaskChannels::new(task_id, worker_id);
WorkerOperation {
if WORKER_POOL_OPERATION.is_dead(worker_id) {
// Close the fresh task channel so nothing can hang on it,
// drop it to undo the registration, and acquire a
// replacement. Statistics are owned by the death path.
channels.close_task_channel();
drop(channels);
if attempts >= 3 {
anyhow::bail!("acquired workers died repeatedly before task registration");
}
continue;
}
break WorkerOperation {
worker_options,
worker_id,
state: state.clone(),
on_drop: Some(Box::new(move |worker_id| {
// A worker that died while it was checked out (e.g. right
// after sending its final message) must not be returned
// to the pool: the next task sent to it would hang. The
// death path already balanced the pool statistics for it.
if WORKER_POOL_OPERATION.is_dead(worker_id) {
return;
}
let mut waiters = state.waiters.lock();
loop {
if let Some(tx) = waiters.pop() {
......@@ -255,6 +317,7 @@ impl EvaluateOperation for WorkerThreadPool {
})),
_permits: permits,
channels,
};
}
};
......
......@@ -6,11 +6,11 @@ use std::{
use anyhow::{Context, Result};
use bytes::Bytes;
use parking_lot::Mutex;
use rustc_hash::FxHashMap;
use rustc_hash::{FxHashMap, FxHashSet};
use tokio::sync::{
Mutex as AsyncMutex,
mpsc::{self, UnboundedReceiver, UnboundedSender},
oneshot,
oneshot, watch,
};
use turbo_rcstr::RcStr;
......@@ -25,14 +25,19 @@ use crate::{
pub(crate) struct MessageChannel<T: Send + Sync + 'static> {
sender: UnboundedSender<T>,
receiver: Arc<AsyncMutex<UnboundedReceiver<T>>>,
close_tx: watch::Sender<bool>,
close_rx: watch::Receiver<bool>,
}
impl<T: Send + Sync + 'static> MessageChannel<T> {
pub(super) fn unbounded() -> Self {
let (sender, receiver) = mpsc::unbounded_channel();
let (close_tx, close_rx) = watch::channel(false);
Self {
sender,
receiver: Arc::new(AsyncMutex::new(receiver)),
close_tx,
close_rx,
}
}
......@@ -50,11 +55,32 @@ impl<T: Send + Sync + 'static> MessageChannel<T> {
.map_err(|_| anyhow::anyhow!("failed to send message"))
}
/// Closes the channel, causing any pending or future `recv` to fail. Used
/// to unblock an operation whose worker died without reporting back. A
/// watch channel cannot lose the wakeup: a close that lands before the
/// receiver starts waiting is still observed.
pub(crate) fn close(&self) {
let _ = self.close_tx.send(true);
}
pub(crate) async fn recv(&self) -> Result<T> {
let mut rx = self.receiver.lock().await;
rx.recv()
.await
.ok_or_else(|| anyhow::anyhow!("failed to recv message"))
let mut close_rx = self.close_rx.clone();
tokio::select! {
msg = rx.recv() => {
msg.ok_or_else(|| anyhow::anyhow!("failed to recv message"))
}
result = close_rx.changed() => {
let _ = result;
// A message that was already queued before the close must
// win: the worker's final response is still valid, only its
// reuse is unsafe.
match rx.try_recv() {
Ok(msg) => Ok(msg),
Err(_) => Err(anyhow::anyhow!("channel closed")),
}
}
}
}
}
......@@ -65,6 +91,25 @@ pub(crate) struct PoolState {
pub(crate) waiters: Mutex<Vec<oneshot::Sender<u32>>>,
}
/// Classification of a dead worker for pool accounting.
pub(crate) enum WorkerDeath {
/// The worker was executing a task: its channel was closed so the pending
/// `recv` fails. Statistics are balanced by the operation's
/// `disallow_reuse`/`wait_or_kill` path, which removes the worker exactly
/// once.
Busy,
/// The worker was idle: it was removed from the idle list and the pool
/// statistics.
Idle,
/// The worker finished booting but was neither busy nor idle (in transit
/// to an acquirer, or routed to a waiter): the total worker count was
/// decremented.
CreatedUnassigned,
/// The worker never finished booting: the caller fails the matching
/// pending creation and balances the booting statistics.
BootFailed,
}
#[turbo_tasks::value(cell = "new", serialization = "skip", eq = "manual", shared)]
#[derive(Clone, PartialEq, Eq, Hash)]
pub(super) struct WorkerOptions {
......@@ -85,6 +130,16 @@ pub(crate) struct WorkerPoolOperation {
worker_routed_channel: Mutex<FxHashMap<u32, Arc<MessageChannel<(u32, Bytes)>>>>,
#[allow(clippy::type_complexity)]
task_routed_channel: Mutex<FxHashMap<u32, Arc<MessageChannel<Bytes>>>>,
/// The task each worker is currently executing, if any.
worker_current_task: Mutex<FxHashMap<u32, u32>>,
/// Workers that finished booting and have not died since. Distinguishes
/// "died while booting" (never in this set) from "created but currently
/// neither busy nor idle" (in transit to an acquirer or waiter-routed).
created_workers: Mutex<FxHashSet<u32>>,
/// Workers that died unexpectedly. Ids are process-unique, so a dead id
/// must never be handed out again by any path (idle pop, waiter handoff,
/// operation drop, acquisition).
dead_workers: Mutex<FxHashSet<u32>>,
pub(crate) pools: Mutex<FxHashMap<Arc<WorkerOptions>, Arc<PoolState>>>,
}
......@@ -107,7 +162,13 @@ impl WorkerPoolOperation {
let workers = idle.split_off(1);
let mut stats = state.stats.lock();
for worker_id in workers {
// Claim the accounting while removing from idle: a
// worker that self-exits in between is then a no-op
// in the death handler instead of being counted a
// second time.
if self.mark_worker_dead(worker_id) {
stats.remove_worker();
}
to_terminate.push((worker_options.clone(), worker_id));
}
}
......@@ -132,7 +193,11 @@ impl WorkerPoolOperation {
let workers = std::mem::take(&mut *idle);
let mut stats = state.stats.lock();
for worker_id in workers {
// See scale_down: claim the accounting while removing
// from idle so the death handler becomes a no-op.
if self.mark_worker_dead(worker_id) {
stats.remove_worker();
}
to_terminate.push((worker_options.clone(), worker_id));
}
}
......@@ -152,6 +217,11 @@ impl WorkerPoolOperation {
worker_id: u32,
) -> Result<()> {
self.remove_worker_channel(worker_id);
self.created_workers.lock().remove(&worker_id);
// Mark before scheduling the JavaScript-side termination: the
// terminator callback runs later, and a self-exit that lands in
// between must not be accounted a second time.
self.mark_worker_dead(worker_id);
worker_thread::terminate_worker(worker_options, worker_id);
Ok(())
}
......@@ -160,6 +230,97 @@ impl WorkerPoolOperation {
self.worker_routed_channel.lock().remove(&worker_id);
}
/// Whether the worker is known to have died unexpectedly. Dead workers
/// must never be handed out again, so every acquisition and return path
/// checks this set.
pub(crate) fn is_dead(&self, worker_id: u32) -> bool {
self.dead_workers.lock().contains(&worker_id)
}
/// Atomically claims a worker as accounted for. Returns `true` when this
/// call won the claim — only then may the caller balance the pool
/// statistics. Any exit report or termination path that comes later sees
/// the id already marked and becomes a no-op, keeping the accounting
/// single-owner in every interleaving.
pub(crate) fn mark_worker_dead(&self, worker_id: u32) -> bool {
self.dead_workers.lock().insert(worker_id)
}
/// Records that a worker finished booting. Death classification relies on
/// this to tell boot deaths apart from created-but-unassigned deaths.
pub(crate) fn mark_worker_created(&self, worker_id: u32) {
self.created_workers.lock().insert(worker_id);
}
/// Reaps a worker that died unexpectedly (crash, `process.exit`, OOM).
///
/// Records the id as dead so no path ever hands it out again, removes
/// the routed channel, closes the in-flight task's channel when busy so
/// a pending `recv` fails and surfaces as a subprocess crash instead of
/// hanging forever, and balances pool statistics for every non-busy
/// class. Boot failures are reported to the caller, which fails the
/// pending creation for the same pool.
pub(crate) fn handle_worker_death(
&self,
worker_options: Arc<WorkerOptions>,
worker_id: u32,
) -> WorkerDeath {
// A worker already marked dead (by an earlier report, or by the
// termination path balancing the statistics before scheduling the JS
// terminator) must not be accounted for a second time. Such a report
// is short-circuited before it can be mistaken for a boot failure.
let newly_marked = self.dead_workers.lock().insert(worker_id);
self.remove_worker_channel(worker_id);
let was_created = self.created_workers.lock().remove(&worker_id);
if !newly_marked {
return WorkerDeath::CreatedUnassigned;
}
// The removed task id is bound outside the `if let` scrutinee: the
// guard must drop before `task_routed_channel` is locked, matching
// the lock order in `TaskChannels::drop`.
let removed_task = { self.worker_current_task.lock().remove(&worker_id) };
if let Some(task_id) = removed_task {
let channel = self.task_routed_channel.lock().remove(&task_id);
if let Some(channel) = channel {
channel.close();
}
// The death path owns the statistics for every dead worker, busy
// or not: `disallow_reuse`/`wait_or_kill`/`on_drop` skip removal
// for workers in the dead set, so the count stays exact even when
// the operation had already received its final message.
if let Some(state) = self.pools.lock().get(worker_options.as_ref()) {
state.stats.lock().remove_worker();
}
return WorkerDeath::Busy;
}
if let Some(state) = self.pools.lock().get(worker_options.as_ref()) {
let mut idle = state.idle_workers.lock();
if let Some(position) = idle.iter().position(|id| *id == worker_id) {
idle.remove(position);
if newly_marked {
state.stats.lock().remove_worker();
}
return WorkerDeath::Idle;
}
if was_created {
// Finished booting but neither busy nor idle: in transit to
// an acquirer or routed to a waiter. The booting counter was
// already balanced when the boot completed, so only the total
// worker count has to be decremented here.
if newly_marked {
state.stats.lock().remove_worker();
}
return WorkerDeath::CreatedUnassigned;
}
}
WorkerDeath::BootFailed
}
pub(crate) async fn recv_task_message_in_worker(&self, worker_id: u32) -> Result<(u32, Bytes)> {
let channel = {
let mut map = self.worker_routed_channel.lock();
......@@ -205,6 +366,7 @@ pub(crate) struct TaskChannels {
/// Channel for Worker -> Rust communication (data)
task_channel: Arc<MessageChannel<Bytes>>,
task_id: u32,
worker_id: u32,
}
impl TaskChannels {
......@@ -225,10 +387,16 @@ impl TaskChannels {
.clone()
};
WORKER_POOL_OPERATION
.worker_current_task
.lock()
.insert(worker_id, task_id);
Self {
worker_channel,
task_channel,
task_id,
worker_id,
}
}
......@@ -247,6 +415,13 @@ impl TaskChannels {
.await
.context("failed to recv task message")
}
/// Closes the task channel so a pending or future `recv_from_worker`
/// fails immediately. Used when the worker dies between acquisition and
/// task registration.
pub(crate) fn close_task_channel(&self) {
self.task_channel.close();
}
}
impl Drop for TaskChannels {
......@@ -256,6 +431,11 @@ impl Drop for TaskChannels {
.task_routed_channel
.lock()
.remove(&self.task_id);
let mut current_tasks = WORKER_POOL_OPERATION.worker_current_task.lock();
if current_tasks.get(&self.worker_id) == Some(&self.task_id) {
current_tasks.remove(&self.worker_id);
}
}
}
......@@ -290,7 +470,12 @@ impl Operation for WorkerOperation {
async fn wait_or_kill(&mut self) -> Result<ExitStatus> {
if self.on_drop.is_some() {
// Atomically claim the accounting before balancing it: a worker
// that dies in between reports itself already marked and becomes
// a no-op instead of being counted twice.
if WORKER_POOL_OPERATION.mark_worker_dead(self.worker_id) {
self.state.stats.lock().remove_worker();
}
self.on_drop = None;
}
terminate_worker(self.worker_options.clone(), self.worker_id)?;
......@@ -299,7 +484,12 @@ impl Operation for WorkerOperation {
fn disallow_reuse(&mut self) {
if self.on_drop.is_some() {
// Atomically claim the accounting before balancing it: a worker
// that dies in between reports itself already marked and becomes
// a no-op instead of being counted twice.
if WORKER_POOL_OPERATION.mark_worker_dead(self.worker_id) {
self.state.stats.lock().remove_worker();
}
self.on_drop = None;
// Clearing the return-to-pool callback does not stop the underlying Node.js worker.
let _ = terminate_worker(self.worker_options.clone(), self.worker_id);
......
......@@ -15,7 +15,7 @@ use turbo_rcstr::RcStr;
use crate::worker_pool::{
WorkerOptions,
operation::{TaskMessage, WORKER_POOL_OPERATION},
operation::{TaskMessage, WORKER_POOL_OPERATION, WorkerDeath},
};
static WORKER_CREATOR: OnceLock<ThreadsafeFunction<NapiWorkerCreation, ErrorStrategy::Fatal>> =
......@@ -25,7 +25,11 @@ static WORKER_TERMINATOR: OnceLock<
ThreadsafeFunction<NapiWorkerTermination, ErrorStrategy::Fatal>,
> = OnceLock::new();
static PENDING_CREATIONS: OnceLock<Mutex<VecDeque<oneshot::Sender<u32>>>> = OnceLock::new();
/// Creations are tagged with their pool options: boot completion (and boot
/// failure) must be paired with the creation for the same pool, not just the
/// oldest one globally.
static PENDING_CREATIONS: OnceLock<Mutex<VecDeque<(Arc<WorkerOptions>, oneshot::Sender<u32>)>>> =
OnceLock::new();
// Allow dead_code for test builds where napi exports are not entry points
#[allow(dead_code)]
......@@ -71,7 +75,7 @@ pub async fn create_worker(options: Arc<WorkerOptions>) -> anyhow::Result<u32> {
.lock()
.entry(options.clone())
.or_default();
pending.lock().push_back(tx);
pending.lock().push_back((options.clone(), tx));
}
if let Some(creator) = WORKER_CREATOR.get() {
......@@ -86,18 +90,52 @@ pub async fn create_worker(options: Arc<WorkerOptions>) -> anyhow::Result<u32> {
}
let worker_id = rx.await?;
// The boot completed: balance the booting counter here (not in the
// caller) so that every later death classification sees a uniform state
// for created workers. A boot that fails never reaches this point; the
// death path balances it with the matching pending creation instead.
if let Some(state) = WORKER_POOL_OPERATION
.pools
.lock()
.get(options.as_ref())
.cloned()
{
state.stats.lock().finished_booting_worker();
}
Ok(worker_id)
}
/// Called from a worker once it finished booting. The worker reports the
/// options it was created with (its entry filename and cwd) so the creation
/// can be paired with the pending request for the same pool instead of
/// blindly taking the oldest slot of any pool.
// Allow dead_code for test builds where napi exports are not entry points
#[allow(dead_code)]
#[napi]
pub fn worker_created(worker_id: u32) {
if let Some(pending) = PENDING_CREATIONS.get()
&& let Some(tx) = pending.lock().pop_front()
{
pub fn worker_created(creation: NapiWorkerTermination) {
let NapiWorkerTermination { options, worker_id } = creation;
WORKER_POOL_OPERATION.mark_worker_created(worker_id);
if let Some(pending) = PENDING_CREATIONS.get() {
let tx = {
let mut pending = pending.lock();
let position = pending.iter().position(|(pending_options, _)| {
pending_options.filename == options.filename && pending_options.cwd == options.cwd
});
// Fall back to the oldest slot if the reported options do not
// match any pending creation exactly (e.g. path normalization
// differences): a mispaired worker is interchangeable, a pending
// creation that is never completed hangs.
position
.or(if pending.is_empty() { None } else { Some(0) })
.and_then(|position| pending.remove(position))
.map(|(_, tx)| tx)
};
if let Some(tx) = tx {
let _ = tx.send(worker_id);
}
}
}
pub fn terminate_worker(options: Arc<WorkerOptions>, worker_id: u32) {
......@@ -142,6 +180,56 @@ pub struct NapiWorkerTermination {
pub worker_id: u32,
}
/// Called from JavaScript when a pooled worker died unexpectedly (uncaught
/// exception, `process.exit`, OOM). Intentional terminations do not reach
/// this: the terminator removes the worker from the JavaScript-side map
/// before terminating it, so the death is not reported.
// Allow dead_code for test builds where napi exports are not entry points
#[allow(dead_code)]
#[napi]
pub fn worker_died(termination: NapiWorkerTermination) {
let NapiWorkerTermination { options, worker_id } = termination;
let worker_options = Arc::new(WorkerOptions {
filename: options.filename.clone(),
cwd: options.cwd.clone(),
});
match WORKER_POOL_OPERATION.handle_worker_death(worker_options.clone(), worker_id) {
WorkerDeath::BootFailed => {
// The worker never reported itself as created, so it died while
// booting. Fail the pending creation *for the same pool* (failing
// an unrelated pool's creation would both hang this one and leak
// the other): dropping the sender errors the receiver, and the
// pool's booting statistics are balanced so no phantom worker
// remains.
if let Some(pending) = PENDING_CREATIONS.get() {
let failed = {
let mut pending = pending.lock();
pending
.iter()
.position(|(pending_options, _)| {
pending_options.filename == options.filename
&& pending_options.cwd == options.cwd
})
.and_then(|position| pending.remove(position))
};
if let Some((failed_options, tx)) = failed {
drop(tx);
if let Some(state) = WORKER_POOL_OPERATION
.pools
.lock()
.get(failed_options.as_ref())
.cloned()
{
state.stats.lock().failed_booting_worker();
}
}
}
}
WorkerDeath::Busy | WorkerDeath::Idle | WorkerDeath::CreatedUnassigned => {}
}
}
// Allow dead_code for test builds where napi exports are not entry points
#[allow(dead_code)]
#[napi(object)]
......
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