Diffinery

homeflare/celldpublic

828 lines · 31.4 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3// Isolate admission and deadlines are in the V8 arm outside the Actor execution
4// domain.
5#![allow(clippy::disallowed_methods)]
6
7//! The isolate pool: the shell around `celld_logic::isolate`.
8//!
9//! One multi-threaded tokio runtime owns every socket and timer. Isolates
10//! belong to no thread — `v8::Locker` installs the entering thread's
11//! per-isolate state, so any worker can take an isolate and run a turn in it.
12//! This module owns the isolates and the counters; every choice about which
13//! isolate, when to grow, what to shed and what to retire is made by
14//! `celld_logic::isolate` and merely performed here.
15//!
16//! **The gate exists so nothing blocks.** `SharedIsolate::lock()` blocks
17//! until its holder releases. Every path here takes the slot's async permit
18//! first, so that blocking lock is uncontended by construction. A `lock()`
19//! reached without the permit would park a tokio worker on V8, which is the
20//! one thing this runtime refuses to do.
21
22use std::sync::atomic::AtomicBool;
23use std::sync::atomic::AtomicU64;
24use std::sync::atomic::AtomicUsize;
25use std::sync::atomic::Ordering;
26use std::sync::Arc;
27use std::sync::Mutex;
28use std::sync::RwLock;
29
30use anyhow::Result;
31use celld_logic::isolate::HeapId;
32use celld_logic::isolate::IsolateId;
33use celld_logic::isolate::IsolateLoad;
34use celld_logic::isolate::Placement;
35use celld_logic::isolate::PoolLimits;
36use celld_logic::isolate::PoolLoad;
37use celld_logic::isolate::Refusal;
38
39use crate::js;
40
41/// Heap identity is process-wide because pressure policy compares cells from
42/// every script pool and every draining generation. A counter inside `Pool`
43/// would reproduce the collision this identity prevents. The core treats the
44/// value as opaque, so its allocation order is not a deterministic decision.
45static NEXT_HEAP_ID: AtomicU64 = AtomicU64::new(1);
46
47fn next_heap_id() -> HeapId {
48 let value = NEXT_HEAP_ID
49 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
50 value.checked_add(1)
51 })
52 .expect("V8 heap identity space exhausted");
53 HeapId::new(value)
54}
55
56/// A Queue producer parks in the owner-side commit group before it writes, so
57/// four bounded groups can install their waiters and overlap one group's
58/// durability proof with successor local commits. The turn scheduler remains
59/// fair by cell scope: one hot Queue turn yields to an alarm or another Queue
60/// before its next turn.
61///
62/// This equals `MAX_QUEUE_PRODUCER_EVENTS_PER_CELL`, so every admitted
63/// producer enters the isolate at once and the `waiting` lane in
64/// `QueueProducerAdmission` is latent: it carries no producer until a smaller
65/// turn cap re-arms it. It is kept because a turn cap below the event cap is
66/// the lever for a workload whose producers must not all park in the isolate,
67/// and no test drives that lane while the caps are equal.
68const MAX_QUEUE_PRODUCER_TURNS_PER_CELL: usize = 256;
69const _: () = assert!(
70 MAX_QUEUE_PRODUCER_TURNS_PER_CELL <= MAX_QUEUE_PRODUCER_EVENTS_PER_CELL,
71 "an execution position is one of the bounded producer events"
72);
73
74/// Bound the producer replies that can wait for one Queue's shared commit and
75/// durability proof. Four 64-call groups can overlap, and a stopped bucket
76/// still cannot retain an unbounded number of promises or copied bodies.
77pub(crate) const MAX_QUEUE_PRODUCER_EVENTS_PER_CELL: usize = 256;
78
79#[derive(Clone, Debug, Eq, Hash, PartialEq)]
80enum TurnLane {
81 Stateless,
82 Cell(String),
83}
84
85#[derive(Default)]
86struct TurnSchedule {
87 current: Option<TurnLane>,
88 ready: std::collections::VecDeque<TurnLane>,
89 waiting: std::collections::HashMap<
90 TurnLane,
91 std::collections::VecDeque<tokio::sync::oneshot::Sender<()>>,
92 >,
93}
94
95#[derive(Default)]
96struct TurnScheduler {
97 schedule: Mutex<TurnSchedule>,
98}
99
100struct TurnPermit<'a>(&'a TurnScheduler);
101
102impl TurnScheduler {
103 async fn acquire(&self, lane: TurnLane) -> TurnPermit<'_> {
104 let receive = {
105 let mut schedule = self.schedule.lock().expect("turn scheduler poisoned");
106 if schedule.current.is_none() {
107 schedule.current = Some(lane);
108 None
109 } else {
110 let (send, receive) = tokio::sync::oneshot::channel();
111 if !schedule.waiting.contains_key(&lane) && schedule.current.as_ref() != Some(&lane)
112 {
113 schedule.ready.push_back(lane.clone());
114 }
115 schedule.waiting.entry(lane).or_default().push_back(send);
116 Some(receive)
117 }
118 };
119 if let Some(receive) = receive {
120 // Cancellation leaves a closed sender in this lane. `release`
121 // skips it, so a dropped waiter cannot strand the active token.
122 let _ = receive.await;
123 }
124 TurnPermit(self)
125 }
126
127 fn release(&self) {
128 let mut schedule = self.schedule.lock().expect("turn scheduler poisoned");
129 let current = schedule
130 .current
131 .take()
132 .expect("a released turn scheduler has a current lane");
133 if schedule
134 .waiting
135 .get(&current)
136 .is_some_and(|waiters| !waiters.is_empty())
137 {
138 schedule.ready.push_back(current);
139 }
140 while let Some(lane) = schedule.ready.pop_front() {
141 let (send, keep_lane) = {
142 let waiters = schedule
143 .waiting
144 .get_mut(&lane)
145 .expect("a ready turn lane has waiters");
146 (waiters.pop_front().unwrap(), !waiters.is_empty())
147 };
148 if !keep_lane {
149 schedule.waiting.remove(&lane);
150 }
151 if send.send(()).is_ok() {
152 schedule.current = Some(lane);
153 return;
154 }
155 if keep_lane {
156 schedule.ready.push_back(lane);
157 }
158 }
159 }
160}
161
162impl Drop for TurnPermit<'_> {
163 fn drop(&mut self) {
164 self.0.release();
165 }
166}
167
168pub(crate) struct QueueProducerPermit {
169 slot: Arc<Slot>,
170 scope: String,
171 executing: bool,
172}
173
174#[derive(Default)]
175struct QueueProducerAdmission {
176 executing: usize,
177 outstanding: usize,
178 waiting: std::collections::VecDeque<tokio::sync::oneshot::Sender<()>>,
179}
180
181impl QueueProducerPermit {
182 /// A producer that installed its durability gate no longer occupies one
183 /// of the two isolate positions. It retains its outstanding reservation
184 /// until the durable reply completes, so stalled storage remains bounded.
185 pub(crate) fn reached_reply_gate(&mut self) {
186 if self.executing {
187 self.slot.release_queue_producer(&self.scope, true, false);
188 self.executing = false;
189 }
190 }
191}
192
193impl Drop for QueueProducerPermit {
194 fn drop(&mut self) {
195 self.slot
196 .release_queue_producer(&self.scope, self.executing, true);
197 }
198}
199
200/// One isolate, and everything the decision core needs to know about it.
201pub struct Slot {
202 /// The index used only inside this pool's placement snapshot and slot
203 /// vector. Distinct pools can use the same value.
204 pub id: IsolateId,
205 /// The identity reported to node-wide Actor and pressure policy.
206 heap_id: HeapId,
207 /// The async gate, holding the isolate it guards. Locking this is what
208 /// makes the V8 `Locker` beneath it uncontended.
209 ///
210 /// `None` once the isolate has been retired and freed. Retirement only
211 /// frees a slot that is drained — no turns, no affiliations — and a
212 /// retiring slot is filtered out of every placement decision, so nothing
213 /// can arrive afterwards. Entering one would be a bug in this module.
214 worker: tokio::sync::Mutex<Option<js::Worker>>,
215 turn_scheduler: TurnScheduler,
216 queue_producers: Mutex<std::collections::HashMap<String, QueueProducerAdmission>>,
217 turns: AtomicUsize,
218 requests: AtomicUsize,
219 /// The pool's admission bell, cloned into every slot so an
220 /// `Affiliation` drop can ring it without holding the pool.
221 freed: Arc<tokio::sync::Notify>,
222 /// Cells whose realm lives in this isolate. Not a count of live work: a
223 /// cell stays until it is evicted or handed to another node, which is
224 /// why `retire` refuses an isolate holding any.
225 cells: AtomicUsize,
226 retiring: AtomicBool,
227 #[cfg(celld_internal_tests)]
228 turn_observations: Mutex<Vec<String>>,
229}
230
231impl Slot {
232 fn observe(&self) -> IsolateLoad {
233 IsolateLoad {
234 turns: self.turns.load(Ordering::Relaxed),
235 requests: self.requests.load(Ordering::Relaxed),
236 cells: self.cells.load(Ordering::Relaxed),
237 retiring: self.retiring.load(Ordering::Relaxed),
238 }
239 }
240
241 /// Enter the isolate for one turn and run `f` inside it.
242 ///
243 /// Only the gate is awaited; `f` is synchronous by type, so holding the
244 /// isolate across an await is unwritable rather than a rule a comment
245 /// asks callers to remember.
246 pub async fn turn<T>(&self, f: impl FnOnce(&mut js::Worker) -> T) -> T {
247 self.turn_in(TurnLane::Stateless, f).await
248 }
249
250 /// Enter one cell turn through a round-robin lane for that cell. A hot
251 /// cell can retain its next place, but it cannot take the next place from
252 /// another cell that already waits on the same isolate.
253 pub async fn turn_cell<T>(&self, scope: &str, f: impl FnOnce(&mut js::Worker) -> T) -> T {
254 self.turn_in(TurnLane::Cell(scope.to_string()), f).await
255 }
256
257 async fn turn_in<T>(&self, lane: TurnLane, f: impl FnOnce(&mut js::Worker) -> T) -> T {
258 struct Counted<'a>(&'a Slot);
259 impl Drop for Counted<'_> {
260 fn drop(&mut self) {
261 self.0.turns.fetch_sub(1, Ordering::Relaxed);
262 }
263 }
264 self.turns.fetch_add(1, Ordering::Relaxed);
265 let _turn = Counted(self);
266 let _scheduled = self.turn_scheduler.acquire(lane.clone()).await;
267 let mut worker = self.worker.lock().await;
268 let worker = match worker.as_mut() {
269 Some(worker) => worker,
270 None => panic!("entered isolate {} after it was freed", self.id),
271 };
272 #[cfg(celld_internal_tests)]
273 self.turn_observations.lock().unwrap().push(match lane {
274 TurnLane::Stateless => "stateless".to_string(),
275 TurnLane::Cell(scope) => scope,
276 });
277 f(worker)
278 }
279
280 /// Reserve one bounded producer event, then wait outside the isolate for
281 /// one of its two execution positions. A durability gate releases only
282 /// the execution position; the complete event retains the outer bound.
283 pub(crate) async fn queue_producer(
284 self: &Arc<Self>,
285 scope: &str,
286 ) -> Option<QueueProducerPermit> {
287 let receive = {
288 let mut producers = self
289 .queue_producers
290 .lock()
291 .expect("Queue producer admission poisoned");
292 let admission = producers.entry(scope.to_string()).or_default();
293 if admission.outstanding >= MAX_QUEUE_PRODUCER_EVENTS_PER_CELL {
294 return None;
295 }
296 admission.outstanding += 1;
297 if admission.executing < MAX_QUEUE_PRODUCER_TURNS_PER_CELL {
298 admission.executing += 1;
299 None
300 } else {
301 let (send, receive) = tokio::sync::oneshot::channel();
302 admission.waiting.push_back(send);
303 Some(receive)
304 }
305 };
306 if let Some(receive) = receive {
307 // The Slot stays alive through `self`, and an execution permit is
308 // transferred until one live waiter accepts it. A closed channel
309 // therefore means the admission state was violated.
310 receive
311 .await
312 .expect("Queue producer admission dropped a live waiter");
313 }
314 Some(QueueProducerPermit {
315 slot: self.clone(),
316 scope: scope.to_string(),
317 executing: true,
318 })
319 }
320
321 fn release_queue_producer(&self, scope: &str, release_execution: bool, finish: bool) {
322 let mut producers = self
323 .queue_producers
324 .lock()
325 .expect("Queue producer admission poisoned");
326 let admission = producers
327 .get_mut(scope)
328 .expect("a Queue producer permit has an admission");
329 if release_execution {
330 let mut transferred = false;
331 while let Some(waiter) = admission.waiting.pop_front() {
332 if waiter.send(()).is_ok() {
333 transferred = true;
334 break;
335 }
336 }
337 if !transferred {
338 admission.executing -= 1;
339 }
340 }
341 if finish {
342 admission.outstanding -= 1;
343 }
344 if admission.outstanding == 0 {
345 debug_assert_eq!(admission.executing, 0);
346 debug_assert!(admission.waiting.is_empty());
347 producers.remove(scope);
348 }
349 }
350
351 /// Mark a request as living in this isolate. Held for the request's whole
352 /// life, including while it is suspended, because its promise stays in
353 /// this heap and every later turn must come back here.
354 pub fn affiliate(self: &Arc<Self>) -> Affiliation {
355 self.requests.fetch_add(1, Ordering::Relaxed);
356 Affiliation(self.clone())
357 }
358
359 /// A slot holding a Worker outside a placement pool.
360 ///
361 /// A dynamic Worker owns exactly one isolate, so it needs no
362 /// admission, growth, or retirement policy.
363 pub(crate) fn standalone(worker: js::Worker) -> Arc<Self> {
364 Arc::new(Slot {
365 id: 0,
366 heap_id: next_heap_id(),
367 worker: tokio::sync::Mutex::new(Some(worker)),
368 turn_scheduler: TurnScheduler::default(),
369 queue_producers: Mutex::new(std::collections::HashMap::new()),
370 turns: AtomicUsize::new(0),
371 requests: AtomicUsize::new(0),
372 freed: Arc::new(tokio::sync::Notify::new()),
373 cells: AtomicUsize::new(0),
374 retiring: AtomicBool::new(false),
375 #[cfg(celld_internal_tests)]
376 turn_observations: Mutex::new(Vec::new()),
377 })
378 }
379
380 #[cfg(celld_internal_tests)]
381 pub fn for_test(worker: js::Worker) -> Arc<Self> {
382 Self::standalone(worker)
383 }
384
385 #[cfg(all(test, celld_internal_tests))]
386 pub(crate) fn vacant_for_request_cancellation_test() -> Arc<Self> {
387 Arc::new(Slot {
388 id: 0,
389 heap_id: HeapId::new(0),
390 worker: tokio::sync::Mutex::new(None),
391 turn_scheduler: TurnScheduler::default(),
392 queue_producers: Mutex::new(std::collections::HashMap::new()),
393 turns: AtomicUsize::new(0),
394 requests: AtomicUsize::new(0),
395 freed: Arc::new(tokio::sync::Notify::new()),
396 cells: AtomicUsize::new(0),
397 retiring: AtomicBool::new(false),
398 turn_observations: Mutex::new(Vec::new()),
399 })
400 }
401
402 #[cfg(celld_internal_tests)]
403 #[doc(hidden)]
404 pub async fn hold_turn_for_test(&self) -> impl Drop + '_ {
405 self.worker.lock().await
406 }
407
408 #[cfg(celld_internal_tests)]
409 #[doc(hidden)]
410 pub fn queued_turns_for_test(&self) -> usize {
411 self.turns.load(Ordering::Relaxed)
412 }
413
414 #[cfg(celld_internal_tests)]
415 #[doc(hidden)]
416 pub fn reset_turn_observations_for_test(&self) {
417 self.turn_observations.lock().unwrap().clear();
418 }
419
420 #[cfg(celld_internal_tests)]
421 #[doc(hidden)]
422 pub fn turn_observations_for_test(&self) -> Vec<String> {
423 self.turn_observations.lock().unwrap().clone()
424 }
425
426 /// Give this isolate a cell's realm. Held for as long as the cell lives
427 /// here, which is what stops the isolate being retired underneath it.
428 fn house(self: &Arc<Self>) -> Residency {
429 self.cells.fetch_add(1, Ordering::Relaxed);
430 Residency(self.clone())
431 }
432
433 pub fn is_retiring(&self) -> bool {
434 self.retiring.load(Ordering::Relaxed)
435 }
436
437 /// The node-wide identity of this slot's currently installed V8 heap.
438 pub fn heap_id(&self) -> HeapId {
439 self.heap_id
440 }
441
442 fn is_reusable(&self) -> bool {
443 let load = self.observe();
444 if !celld_logic::isolate::may_free(&load) || load.cells != 0 {
445 return false;
446 }
447 self.worker.try_lock().is_ok_and(|worker| worker.is_none())
448 }
449}
450
451/// A request's claim on the isolate that ran its first turn.
452pub struct Affiliation(Arc<Slot>);
453
454impl Affiliation {
455 pub fn slot(&self) -> &Arc<Slot> {
456 &self.0
457 }
458}
459
460impl Drop for Affiliation {
461 fn drop(&mut self) {
462 self.0.requests.fetch_sub(1, Ordering::Relaxed);
463 // Exactly one admission waiter per freed slot: `notify_one` hands
464 // the capacity to a single parked request, where waking them all
465 // would stampede `admit` on every release.
466 self.0.freed.notify_one();
467 }
468}
469
470/// A cell's claim on the isolate that holds its realm.
471///
472/// The counterpart of [`Affiliation`], and the difference between them is
473/// the whole reason both exist: an affiliation lasts one request, a
474/// residency lasts until the cell is evicted or moves node.
475pub struct Residency(Arc<Slot>);
476
477impl Residency {
478 pub fn slot(&self) -> &Arc<Slot> {
479 &self.0
480 }
481}
482
483impl Drop for Residency {
484 fn drop(&mut self) {
485 self.0.cells.fetch_sub(1, Ordering::Relaxed);
486 }
487}
488
489type Build = Box<dyn Fn() -> Result<js::Worker> + Send + Sync>;
490
491pub struct Pool {
492 slots: RwLock<Vec<Arc<Slot>>>,
493 limits: PoolLimits,
494 build: Build,
495 freed: Arc<tokio::sync::Notify>,
496 admission_wait: std::time::Duration,
497 /// The whole pool belongs to a superseded generation. An isolate grown
498 /// after this is set starts out retiring: a placement that snapshotted
499 /// the old generation just before the flip can still land, but nothing
500 /// it builds outlives the work it was built for.
501 retired: AtomicBool,
502 /// Keeps admission and cell placement from racing isolate retirement.
503 /// Stateless admission takes a shared guard, while maintenance and cell
504 /// placement take the exclusive guard.
505 maintenance: RwLock<()>,
506}
507
508impl Pool {
509 pub fn new(limits: PoolLimits, admission_wait: std::time::Duration, build: Build) -> Self {
510 Pool {
511 slots: RwLock::new(Vec::new()),
512 limits,
513 build,
514 freed: Arc::new(tokio::sync::Notify::new()),
515 admission_wait,
516 retired: AtomicBool::new(false),
517 maintenance: RwLock::new(()),
518 }
519 }
520
521 fn load(&self) -> PoolLoad {
522 let slots = self.slots.read().expect("pool poisoned");
523 PoolLoad {
524 isolates: slots.iter().map(|s| s.observe()).collect(),
525 limits: self.limits,
526 }
527 }
528
529 pub fn len(&self) -> usize {
530 self.slots.read().expect("pool poisoned").len()
531 }
532
533 pub fn is_empty(&self) -> bool {
534 self.len() == 0
535 }
536
537 fn get(&self, id: IsolateId) -> Arc<Slot> {
538 self.slots.read().expect("pool poisoned")[id].clone()
539 }
540
541 /// Build an isolate and admit it to the pool.
542 ///
543 /// The isolate is constructed before the lock is taken: loading a script
544 /// runs JS and can take milliseconds, and holding the pool lock across it
545 /// would stall every other placement on the node.
546 /// Build an isolate, unless a capped pool reached `cap` while this one
547 /// was being built. Cell placement passes no cap because node memory is
548 /// bounded before placement and its per-isolate limit must remain exact.
549 ///
550 /// `cap` is re-checked under the write lock because admission decides
551 /// against a snapshot it does not hold. Without the re-check every
552 /// request that saw the same pre-growth snapshot grows, so a cap of two
553 /// produced sixteen isolates under load — the breach scaled with offered
554 /// concurrency, and the configured limit was met only when serialised.
555 fn grow(&self, cap: Option<usize>) -> Result<Arc<Slot>> {
556 let worker = (self.build)()?;
557 let mut slots = self.slots.write().expect("pool poisoned");
558 let live = slots.iter().filter(|slot| !slot.is_retiring()).count();
559 if cap.is_some_and(|cap| live >= cap) {
560 if let Some(slot) = slots.iter().find(|slot| !slot.is_retiring()) {
561 return Ok(slot.clone());
562 }
563 }
564 // A freed slot has no worker, work, affiliations, or cells. Reuse its
565 // stable index so placement scans scale with the current pool rather
566 // than with every isolate created during the process lifetime.
567 let reusable = slots.iter().position(|slot| slot.is_reusable());
568 let id = reusable.unwrap_or(slots.len());
569 let heap_id = next_heap_id();
570 let slot = Arc::new(Slot {
571 id,
572 heap_id,
573 worker: tokio::sync::Mutex::new(Some(worker)),
574 turn_scheduler: TurnScheduler::default(),
575 queue_producers: Mutex::new(std::collections::HashMap::new()),
576 turns: AtomicUsize::new(0),
577 requests: AtomicUsize::new(0),
578 freed: self.freed.clone(),
579 cells: AtomicUsize::new(0),
580 retiring: AtomicBool::new(self.retired.load(Ordering::Relaxed)),
581 #[cfg(celld_internal_tests)]
582 turn_observations: Mutex::new(Vec::new()),
583 });
584 if let Some(id) = reusable {
585 slots[id] = slot.clone();
586 } else {
587 slots.push(slot.clone());
588 }
589 tracing::info!(isolate = %heap_id, slot = id, total = slots.len(), "isolate started");
590 Ok(slot)
591 }
592
593 fn resolve(&self, placement: Placement, cap: Option<usize>) -> Result<Arc<Slot>> {
594 match placement {
595 Placement::Existing(id) => Ok(self.get(id)),
596 Placement::Grow => self.grow(cap),
597 }
598 }
599
600 /// Build one isolate up front.
601 ///
602 /// The pool is otherwise lazy, and an idle node holding no isolates is the
603 /// point. But the first isolate is built at startup for two reasons that
604 /// laziness cannot serve: a node whose script does not load must fail
605 /// *then*, not once per request forever after; and compiling the script
606 /// inside the first request adds its whole cost to that request's latency,
607 /// which a startup probe reads as a node that never came up.
608 pub fn warm(&self) -> Result<()> {
609 self.grow(Some(self.limits.max_stateless))?;
610 Ok(())
611 }
612
613 /// Take a stateless request, or refuse it.
614 ///
615 /// One call against one snapshot: admission and placement are the same
616 /// decision, so the node cannot admit a request it then fails to place.
617 pub fn admit(&self, shedding: bool) -> Result<Affiliation, AdmitError> {
618 // A configured request ceiling must remain exact under concurrent
619 // admission, so serialize the check and reservation only in that
620 // mode. The default unbounded path keeps concurrent shared access.
621 if self.limits.max_requests.is_some() {
622 let _maintenance = self.maintenance.write().expect("pool poisoned");
623 self.admit_locked(shedding)
624 } else {
625 let _maintenance = self.maintenance.read().expect("pool poisoned");
626 self.admit_locked(shedding)
627 }
628 }
629
630 fn admit_locked(&self, shedding: bool) -> Result<Affiliation, AdmitError> {
631 let placement = celld_logic::isolate::admit(&self.load(), shedding)?;
632 self.resolve(placement, Some(self.limits.max_stateless))
633 .map(|slot| slot.affiliate())
634 .map_err(AdmitError::Build)
635 }
636
637 /// [`admit`](Self::admit), except a request that finds the node full
638 /// waits — bounded — for a slot instead of being refused at once.
639 ///
640 /// The wait is the middle gear between "admit" and "refuse". At
641 /// overload the parse-and-503 path costs about half a served request,
642 /// so a node refusing 200k times a second spends its cores saying no.
643 /// A parked waiter costs nothing until an `Affiliation` drop hands it
644 /// the slot, and the excess load queues in kernel socket buffers
645 /// behind connections nobody is reading. `NodePressured` still
646 /// refuses at once: pressure means give resources back, not hold
647 /// callers.
648 pub async fn admit_or_wait(&self, shedding: bool) -> Result<Affiliation, AdmitError> {
649 let deadline_ms =
650 crate::asyncrt::mono_ms().saturating_add(self.admission_wait.as_millis() as u64);
651 loop {
652 // Armed before the check: a slot freed between a failed admit
653 // and the park would otherwise be a lost wakeup.
654 let freed = self.freed.notified();
655 match self.admit(shedding) {
656 Err(AdmitError::Refused(Refusal::NodeFull)) => {
657 tokio::pin!(freed);
658 // A freed slot before the deadline: both arms end the
659 // wait, so declaring the order costs nothing and makes
660 // the branch replayable. Priority to the wakeup, because
661 // a slot that freed in the same instant the deadline
662 // expired is a slot the caller can have.
663 crate::asyncrt::select_biased! {
664 "a slot freed in the same instant as the deadline goes to the caller";
665 _ = &mut freed => {},
666 _ = crate::asyncrt::sleep_until(deadline_ms) => {
667 return Err(AdmitError::Refused(Refusal::NodeFull));
668 }
669 }
670 }
671 other => return other,
672 }
673 }
674 }
675
676 /// Give a cell a home, building an isolate if every one is full.
677 ///
678 /// The counterpart of [`admit`](Self::admit) and deliberately the same
679 /// shape: one call against one snapshot. It cannot refuse — by the time
680 /// a cell needs a realm, ownership has already agreed the node serves
681 /// it, so `celld_logic::isolate::place_cell` always answers.
682 pub fn place_cell(&self) -> Result<Residency> {
683 let _maintenance = self.maintenance.write().expect("pool poisoned");
684 let placement = celld_logic::isolate::place_cell(&self.load());
685 // Cell isolates have no arbitrary total cap. The resident-cell and
686 // RSS limits bound node memory before placement. The lock keeps this
687 // reservation exact and prevents maintenance from retiring the slot.
688 Ok(self.resolve(placement, None)?.house())
689 }
690
691 /// One maintenance pass: give back an isolate the pool no longer needs,
692 /// and free whatever has finished draining.
693 ///
694 /// Without this the pool only grows. A burst takes it to `max_stateless`
695 /// and every one of those V8 heaps is held for the life of the process,
696 /// which is the whole reason `celld_logic::isolate::retire` exists —
697 /// and, until this existed, the reason it was dead code hiding a leak.
698 ///
699 /// Retire at most one isolate. Stateless pools use this paced maintenance
700 /// so a quiet interval does not discard every warm compiled Worker.
701 pub fn reap(&self) {
702 // Maintenance runs on a Tokio worker. Skip this pass when a blocking
703 // cell start is compiling an isolate instead of blocking the worker.
704 let Ok(_maintenance) = self.maintenance.try_write() else {
705 return;
706 };
707 self.retire_one();
708 self.free_retired();
709 }
710
711 /// Retire every empty isolate. Cell pools use this after eviction because
712 /// an empty cell heap carries no warm request capacity worth preserving.
713 pub fn reap_empty(&self) {
714 let Ok(_maintenance) = self.maintenance.try_write() else {
715 return;
716 };
717 while self.retire_one() {}
718 self.free_retired();
719 }
720
721 /// Retire every isolate, housed or not: the pool belongs to a superseded
722 /// application generation and must take no new work. Stateless slots
723 /// free as their affiliations drop; a slot hosting cells frees once the
724 /// last of them has moved to a newer generation, which `may_free`
725 /// enforces by refusing a housed isolate.
726 pub fn retire_all(&self) {
727 let _maintenance = self.maintenance.write().expect("pool poisoned");
728 self.retired.store(true, Ordering::Relaxed);
729 for slot in self.slots.read().expect("pool poisoned").iter() {
730 if !slot.retiring.swap(true, Ordering::Relaxed) {
731 tracing::info!(isolate = %slot.heap_id, slot = slot.id, "isolate retiring");
732 }
733 }
734 self.free_retired();
735 }
736
737 /// Whether every isolate this pool ever built has been freed. True for a
738 /// pool that never grew, so a generation whose scripts took no traffic
739 /// drains at once.
740 pub fn is_drained(&self) -> bool {
741 self.slots
742 .read()
743 .expect("pool poisoned")
744 .iter()
745 .all(|slot| slot.worker.try_lock().is_ok_and(|worker| worker.is_none()))
746 }
747
748 fn retire_one(&self) -> bool {
749 let Some(id) = celld_logic::isolate::retire(&self.load()) else {
750 return false;
751 };
752 let slot = self.get(id);
753 if !slot.retiring.swap(true, Ordering::Relaxed) {
754 tracing::info!(isolate = %slot.heap_id, slot = id, "isolate retiring");
755 }
756 true
757 }
758
759 fn free_retired(&self) {
760 // A retiring isolate takes no new work, so once its counters reach
761 // zero nothing can enter it again and its heap can go. `try_lock`
762 // rather than blocking: if a turn holds it, it is not drained and
763 // this pass has nothing to do.
764 for slot in self.slots.read().expect("pool poisoned").iter() {
765 if !celld_logic::isolate::may_free(&slot.observe()) {
766 continue;
767 }
768 let Ok(mut worker) = slot.worker.try_lock() else {
769 continue;
770 };
771 if worker.take().is_some() {
772 tracing::info!(isolate = %slot.heap_id, slot = slot.id, "isolate freed");
773 }
774 }
775 }
776
777 /// Return the current live-isolate count.
778 pub fn live(&self) -> usize {
779 self.slots
780 .read()
781 .expect("pool poisoned")
782 .iter()
783 .filter(|slot| !slot.is_retiring())
784 .count()
785 }
786}
787
788/// Refused by policy, or the isolate could not be built. Distinct because the
789/// first is a 503 the caller may retry elsewhere and the second is a fault.
790#[derive(Debug)]
791pub enum AdmitError {
792 Refused(Refusal),
793 Build(anyhow::Error),
794}
795
796impl From<Refusal> for AdmitError {
797 fn from(refusal: Refusal) -> Self {
798 AdmitError::Refused(refusal)
799 }
800}
801
802impl std::fmt::Display for AdmitError {
803 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
804 match self {
805 AdmitError::Refused(Refusal::NodeFull) => {
806 write!(f, "node is at its stateless request limit")
807 }
808 AdmitError::Refused(Refusal::NodePressured) => write!(f, "node is shedding load"),
809 AdmitError::Build(error) => write!(f, "isolate could not be started: {error}"),
810 }
811 }
812}
813
814impl std::error::Error for AdmitError {}
815
816/// The property the whole design rests on: an isolate and everything hanging
817/// off it can be reached from any tokio worker. This is what `v8::Locker` and
818/// `Send` Globals buy (denoland/rusty_v8#2044, #2045); without them
819/// `js::Worker` would not be `Send` and the pool could not exist.
820///
821/// A compile-time check rather than a comment, because losing it would show
822/// up as a confusing error somewhere far away.
823const _: fn() = || {
824 fn assert_send_sync<T: Send + Sync>() {}
825 assert_send_sync::<Pool>();
826 assert_send_sync::<Slot>();
827 assert_send_sync::<Affiliation>();
828};