Diffinery

homeflare/celldpublic

celld/crates/celld/runtime.rs
3602 lines · 136.6 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3// RuntimeManager is the V8 cell-host arm, so its executor and observability
4// clocks remain ambient.
5#![allow(clippy::disallowed_methods)]
6
7//! V8 runtime materialization behind core-authorized lifecycle effects.
8//!
9//! The manager owns handles and filesystem paths, never lifecycle policy.
10//! StartRuntime, Publish, and StopRuntime decide when a cell handle moves from
11//! starting to externally dispatchable to closed.
12
13use crate::asyncrt;
14pub(crate) use crate::engine_api::StopMode;
15use crate::generation::{Generation, GenerationId};
16use crate::js::{self, CellJob, CellStorage, HttpResponse, Worker, WorkerConfig};
17
18pub use crate::clean_reload::take_clean_reload_generation;
19pub use crate::clean_reload::write_clean_reload_marker;
20pub use crate::engine_api::admission_wait;
21pub use crate::engine_api::AlarmObserver;
22pub use crate::engine_api::RuntimeFetch;
23pub use crate::engine_api::RuntimeOptions;
24pub use crate::engine_api::ServiceFetch;
25pub use crate::ltx_replication::Replication;
26use anyhow::{anyhow, Context};
27use futures_util::StreamExt as _;
28use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
29use std::path::Path;
30use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
31use std::sync::{Arc, Mutex};
32use std::time::{Duration, Instant};
33
34const REMOTE_ABORT_TTL: Duration = Duration::from_secs(600);
35const REMOTE_COMPLETION_TTL: Duration = Duration::from_secs(60);
36const MAX_REMOTE_PENDING_ABORTS: usize = 65_536;
37#[doc(hidden)]
38pub const MAX_REMOTE_COMPLETIONS: usize = 65_536;
39const MAX_ALARM_COMPLETIONS: usize = 65_536;
40
41/// How often the isolate pool gives back what it no longer needs.
42const REAP_INTERVAL: Duration = Duration::from_secs(30);
43
44/// How long a reclaim waits before it retries when admission holds the pool.
45const RECLAIM_RETRY: Duration = Duration::from_millis(10);
46
47/// How often a suspended request re-reads its cancellation flag. Matches the
48/// blocking run loop's own cap, which exists for the same reason: a client
49/// disconnect is raised on another thread and has nothing to wake this one.
50const CANCELLATION_TICK: Duration = Duration::from_millis(10);
51/// Cell fetches that one target can hold before celld refuses excess work.
52///
53/// The last nonsaturated Queue step in the AWS partition staircase held
54/// approximately 40 requests by Little's Law. A limit of 64 keeps that step
55/// below the gate and prevents one target from consuming hundreds of client
56/// slots after its throughput stops increasing.
57pub const DEFAULT_MAX_CELL_REQUESTS: usize = 64;
58
59/// Serialize each publisher that owns this lifetime with the target request
60/// driver's final cancellation cleanup. Without this shared lifetime, the
61/// driver can clear and exit between a publisher observing a pending reply and
62/// publishing its abort. This race leaves a tombstone with no remaining driver.
63///
64/// This hidden public type is the embedder boundary for a stateless request.
65/// An embedder can give clones to abort publishers, but it must give the same
66/// lifetime to the driver through [`Self::drive_stateless_fetch`].
67#[doc(hidden)]
68pub struct RequestCancellationLifetime {
69 request_id: js::RequestId,
70 finished: Mutex<bool>,
71}
72
73impl RequestCancellationLifetime {
74 #[doc(hidden)]
75 pub fn stateless() -> Arc<Self> {
76 Self::from_request_id(js::next_request_id())
77 }
78
79 fn from_request_id(request_id: js::RequestId) -> Arc<Self> {
80 Arc::new(Self {
81 request_id,
82 finished: Mutex::new(false),
83 })
84 }
85
86 #[doc(hidden)]
87 pub fn request_id(&self) -> js::RequestId {
88 self.request_id
89 }
90
91 /// Publish an abort from an embedder that owns this lifetime.
92 #[doc(hidden)]
93 pub fn publish_abort(&self) {
94 #[cfg(all(test, celld_internal_tests))]
95 // Pause before taking `finished`: the test must let retirement win
96 // this ordering without deadlocking on the very lock under test.
97 js::pause_abort_request_if_armed_for_test(self.request_id);
98 let finished = self
99 .finished
100 .lock()
101 .expect("request cancellation lifetime poisoned");
102 if !*finished {
103 js::abort_request(self.request_id);
104 }
105 }
106
107 pub(crate) fn finish(&self) {
108 let mut finished = self
109 .finished
110 .lock()
111 .expect("request cancellation lifetime poisoned");
112 js::clear_request_cancellation(self.request_id);
113 *finished = true;
114 }
115
116 /// Drive one cancellable stateless fetch with this same lifetime.
117 ///
118 /// This function constructs the driver future and its retirement guard
119 /// before it returns. Thus, dropping the future before its first poll also
120 /// retires the request. The request ID is derived here, so a publisher
121 /// cannot name one request while the driver retires another request.
122 #[doc(hidden)]
123 pub fn drive_stateless_fetch(
124 self: Arc<Self>,
125 slot: Arc<crate::pool::Slot>,
126 url: String,
127 method: String,
128 body: js::RequestBody,
129 headers: Vec<(String, String)>,
130 reply: tokio::sync::oneshot::Sender<anyhow::Result<HttpResponse>>,
131 ) -> impl std::future::Future<Output = ()> + Send + 'static {
132 let job = stateless_fetch_job_factory(None, url, method, body, headers, Some(self))(reply);
133 drive_affiliated(slot.affiliate(), job, None)
134 }
135
136 /// Drive a fully built fetch job, such as a loaded Worker's, with this
137 /// lifetime. The job's request id is overwritten from the lifetime, so the
138 /// caller cannot pair an abort publisher with a different request.
139 pub(crate) fn drive_fetch_job(
140 self: Arc<Self>,
141 slot: Arc<crate::pool::Slot>,
142 mut job: crate::WorkerJob,
143 ) -> impl std::future::Future<Output = ()> + Send + 'static {
144 if let crate::WorkerJob::Fetch { request_id, .. } = &mut job {
145 *request_id = Some(self.request_id);
146 }
147 let job = StatelessWorkerJob {
148 job,
149 cancellation: RequestCancellationGuard::shared(self),
150 };
151 drive_affiliated(slot.affiliate(), job, None)
152 }
153}
154
155/// A stateless job and the only cancellation lifetime that can name it.
156/// Cancellable constructors derive the copied JavaScript request id from the
157/// lifetime, so a caller cannot pair one id with another lifetime.
158struct StatelessWorkerJob {
159 job: crate::WorkerJob,
160 cancellation: RequestCancellationGuard,
161}
162
163impl StatelessWorkerJob {
164 fn fetch(
165 entrypoint: Option<crate::WorkerFetchEntrypoint>,
166 url: String,
167 method: String,
168 body: js::RequestBody,
169 headers: Vec<(String, String)>,
170 cancellation: RequestCancellationGuard,
171 reply: tokio::sync::oneshot::Sender<anyhow::Result<HttpResponse>>,
172 ) -> Self {
173 let request_id = cancellation
174 .lifetime()
175 .map(|lifetime| lifetime.request_id());
176 Self {
177 job: crate::WorkerJob::Fetch {
178 queued_at: Instant::now(),
179 entrypoint,
180 invocation_limits: None,
181 url,
182 method,
183 body,
184 headers,
185 request_id,
186 tail_report: None,
187 reply,
188 },
189 cancellation,
190 }
191 }
192
193 fn driver_owned(job: crate::WorkerJob) -> Self {
194 // This compatibility constructor is for a job with no publisher. A
195 // publisher must give its lifetime to the fetch factory because a
196 // copied request id cannot prove that the publisher and driver match.
197 let lifetime = match &job {
198 crate::WorkerJob::Fetch { request_id, .. } => {
199 request_id.map(RequestCancellationLifetime::from_request_id)
200 }
201 crate::WorkerJob::Rpc { .. } | crate::WorkerJob::Queue { .. } => None,
202 };
203 let cancellation = RequestCancellationGuard::new(lifetime);
204 Self { job, cancellation }
205 }
206}
207
208fn stateless_fetch_job_factory(
209 entrypoint: Option<crate::WorkerFetchEntrypoint>,
210 url: String,
211 method: String,
212 body: js::RequestBody,
213 headers: Vec<(String, String)>,
214 cancellation: Option<Arc<RequestCancellationLifetime>>,
215) -> impl FnOnce(tokio::sync::oneshot::Sender<anyhow::Result<HttpResponse>>) -> StatelessWorkerJob {
216 // The factory crosses the admission await, so it owns retirement until it
217 // transfers the same guard into the spawned driver's job.
218 let cancellation = RequestCancellationGuard::new(cancellation);
219 move |reply| {
220 StatelessWorkerJob::fetch(entrypoint, url, method, body, headers, cancellation, reply)
221 }
222}
223
224/// Remove a request's cancellation state when its driver leaves. Each
225/// publisher for this request must share this lifetime, so publication
226/// serializes with cleanup.
227struct RequestCancellationGuard(Option<Arc<RequestCancellationLifetime>>);
228
229impl RequestCancellationGuard {
230 fn new(lifetime: Option<Arc<RequestCancellationLifetime>>) -> Self {
231 Self(lifetime)
232 }
233
234 fn shared(lifetime: Arc<RequestCancellationLifetime>) -> Self {
235 Self::new(Some(lifetime))
236 }
237
238 fn lifetime(&self) -> Option<&Arc<RequestCancellationLifetime>> {
239 self.0.as_ref()
240 }
241}
242
243impl Drop for RequestCancellationGuard {
244 fn drop(&mut self) {
245 if let Some(lifetime) = &self.0 {
246 lifetime.finish();
247 }
248 }
249}
250
251async fn drive_with_request_cancellation(
252 driving: impl std::future::Future<Output = ()> + Send + 'static,
253 cancellation: RequestCancellationGuard,
254) {
255 // The caller constructs the guard before it creates this future. The
256 // future therefore owns retirement before its first poll, and this local
257 // keeps that ownership until the complete driver future returns.
258 let _request_cancellation = cancellation;
259 driving.await;
260}
261
262#[derive(Clone)]
263#[doc(hidden)]
264pub enum RemoteRequestState {
265 PendingAbort(Instant),
266 Active(Arc<RequestCancellationLifetime>),
267 Completed(Instant),
268}
269
270#[derive(Default)]
271#[doc(hidden)]
272pub struct RemoteRequestRegistry {
273 pub states: HashMap<js::RequestId, RemoteRequestState>,
274 pending: VecDeque<(Instant, js::RequestId)>,
275 completed: VecDeque<(Instant, js::RequestId)>,
276}
277
278impl RemoteRequestRegistry {
279 fn prune(&mut self) {
280 while self.pending.len() > MAX_REMOTE_PENDING_ABORTS
281 || self
282 .pending
283 .front()
284 .is_some_and(|(created, _)| created.elapsed() >= REMOTE_ABORT_TTL)
285 {
286 let (created, request) = self.pending.pop_front().expect("checked pending abort");
287 if matches!(
288 self.states.get(&request),
289 Some(RemoteRequestState::PendingAbort(current)) if *current == created
290 ) {
291 self.states.remove(&request);
292 }
293 }
294 while self.completed.len() > MAX_REMOTE_COMPLETIONS
295 || self
296 .completed
297 .front()
298 .is_some_and(|(created, _)| created.elapsed() >= REMOTE_COMPLETION_TTL)
299 {
300 let (created, request) = self.completed.pop_front().expect("checked completion");
301 if matches!(
302 self.states.get(&request),
303 Some(RemoteRequestState::Completed(current)) if *current == created
304 ) {
305 self.states.remove(&request);
306 }
307 }
308 }
309
310 fn pending_abort(&mut self, request: js::RequestId) {
311 let created = Instant::now();
312 self.states
313 .insert(request, RemoteRequestState::PendingAbort(created));
314 self.pending.push_back((created, request));
315 }
316
317 #[doc(hidden)]
318 pub fn completed(&mut self, request: js::RequestId) {
319 let created = Instant::now();
320 self.states
321 .insert(request, RemoteRequestState::Completed(created));
322 self.completed.push_back((created, request));
323 self.prune();
324 }
325
326 /// Record that `request` has been handed to a cell isolate.
327 #[doc(hidden)]
328 pub fn active(&mut self, request: js::RequestId) -> Arc<RequestCancellationLifetime> {
329 let lifetime = RequestCancellationLifetime::from_request_id(request);
330 self.states
331 .insert(request, RemoteRequestState::Active(lifetime.clone()));
332 lifetime
333 }
334
335 /// Record and publish a hang-up for `request`, and report whether it
336 /// reached an active fetch.
337 ///
338 /// An `Active` fetch is tombstoned here instead of being left in place.
339 /// `fetch_cell` is what normally retires an id, but a caller that
340 /// disconnects mid-fetch has that future dropped underneath it, so the
341 /// retiring `completed()` never runs. `prune` reclaims only the ids it can
342 /// reach through `pending` or `completed`, so without this tombstone the
343 /// entry stays in `states` for the life of the process, and one routine
344 /// disconnect leaks one entry. A `fetch_cell` that does outlive the abort
345 /// enqueues a fresher tombstone, and `prune`'s generation guard discards
346 /// the stale enqueue without disturbing the live entry.
347 #[doc(hidden)]
348 pub fn abort(&mut self, request: js::RequestId) -> bool {
349 match self.states.get(&request).cloned() {
350 Some(RemoteRequestState::Active(lifetime)) => {
351 self.completed(request);
352 // Publish while the registry still owns the state transition,
353 // so every direct abort reaches the same lifetime handshake.
354 lifetime.publish_abort();
355 true
356 }
357 Some(RemoteRequestState::Completed(_) | RemoteRequestState::PendingAbort(_)) => false,
358 None => {
359 self.pending_abort(request);
360 false
361 }
362 }
363 }
364}
365
366#[derive(Default)]
367struct AlarmRequestRegistry {
368 states: BTreeMap<(String, celld_logic::OpId), AlarmRequestState>,
369 completed: VecDeque<(String, celld_logic::OpId)>,
370}
371
372#[derive(Clone, Copy)]
373enum AlarmRequestState {
374 PendingAbort,
375 Active(js::RequestId),
376 Completed,
377}
378
379impl AlarmRequestRegistry {
380 fn begin(&mut self, cell: String, op: celld_logic::OpId, request: js::RequestId) -> bool {
381 let key = (cell, op);
382 let cancel = matches!(
383 self.states.remove(&key),
384 Some(AlarmRequestState::PendingAbort)
385 );
386 assert!(
387 self.states
388 .insert(key, AlarmRequestState::Active(request))
389 .is_none(),
390 "one shell alarm task per core operation"
391 );
392 cancel
393 }
394
395 fn finish(&mut self, cell: &str, op: celld_logic::OpId, request: js::RequestId) {
396 let key = (cell.to_string(), op);
397 if matches!(
398 self.states.get(&key),
399 Some(AlarmRequestState::Active(active)) if *active == request
400 ) {
401 self.states
402 .insert(key.clone(), AlarmRequestState::Completed);
403 self.completed.push_back(key);
404 }
405 while self.completed.len() > MAX_ALARM_COMPLETIONS {
406 let completed = self.completed.pop_front().expect("checked completion");
407 if matches!(
408 self.states.get(&completed),
409 Some(AlarmRequestState::Completed)
410 ) {
411 self.states.remove(&completed);
412 }
413 }
414 }
415
416 fn aborting(&mut self, cell: &str, op: celld_logic::OpId) -> Option<js::RequestId> {
417 let key = (cell.to_string(), op);
418 match self.states.get(&key).copied() {
419 Some(AlarmRequestState::Active(request)) => Some(request),
420 Some(AlarmRequestState::PendingAbort | AlarmRequestState::Completed) => None,
421 None => {
422 self.states.insert(key, AlarmRequestState::PendingAbort);
423 None
424 }
425 }
426 }
427}
428
429struct AlarmRequestGuard {
430 registry: Arc<Mutex<AlarmRequestRegistry>>,
431 cell: String,
432 op: celld_logic::OpId,
433 request: js::RequestId,
434}
435
436impl Drop for AlarmRequestGuard {
437 fn drop(&mut self) {
438 self.registry
439 .lock()
440 .expect("alarm registry poisoned")
441 .finish(&self.cell, self.op, self.request);
442 }
443}
444
445/// The isolate pool's limits, built from the environment here because the
446/// decision core never reads it.
447///
448/// `max_requests` is the node's only bound on stateless memory, and it is
449/// live: `Slot::affiliate` counts an affiliation for a request's whole life,
450/// `observe` reports it, and `isolate::admit` refuses against it. Unset
451/// means unbounded, not unwired — `engine/load-under-pressure.md` measures
452/// `CELLD_MAX_REQUESTS=32` admitting 641 rps against a theoretical 640.
453pub fn pool_limits() -> celld_logic::isolate::PoolLimits {
454 const GROW_AT: usize = 2;
455 const SHRINK_UNDER: usize = 1;
456 const MAX_CELLS_PER_ISOLATE: usize = 32;
457 let cores = std::thread::available_parallelism()
458 .map(|n| n.get())
459 .unwrap_or(4);
460 celld_logic::isolate::PoolLimits {
461 // These thresholds form one hysteresis policy, so they are constants
462 // rather than two independently configurable values.
463 grow_at: GROW_AT,
464 shrink_under: SHRINK_UNDER,
465 max_stateless: env_usize("CELLD_MAX_STATELESS_ISOLATES").unwrap_or(cores),
466 max_requests: env_usize("CELLD_MAX_REQUESTS"),
467 // This is an engine blast-radius policy. The resident-cell and RSS
468 // limits are the operator controls for node memory.
469 max_cells: MAX_CELLS_PER_ISOLATE,
470 }
471}
472
473fn env_usize(name: &str) -> Option<usize> {
474 crate::env_vars::positive(name).expect("validated positive runtime limit")
475}
476
477#[derive(Clone)]
478#[doc(hidden)]
479pub struct StatelessRuntime {
480 pub node: Arc<str>,
481 pub region: Arc<str>,
482 /// The isolates fetch runs on, entered one turn at a time from whichever
483 /// tokio worker is driving the request.
484 pub isolates: Arc<crate::pool::Pool>,
485}
486
487#[derive(Clone, Copy)]
488#[doc(hidden)]
489pub enum StatelessVerb {
490 Fetch,
491 Rpc,
492 Queue,
493}
494
495impl StatelessVerb {
496 fn task_died(self, error: tokio::task::JoinError) -> anyhow::Error {
497 match self {
498 Self::Fetch => anyhow!("stateless request task died: {error}"),
499 Self::Rpc => anyhow!("stateless RPC task died: {error}"),
500 Self::Queue => anyhow!("stateless queue task died: {error}"),
501 }
502 }
503
504 fn dropped_result(self) -> anyhow::Error {
505 match self {
506 Self::Fetch => anyhow!("stateless Worker dropped response"),
507 Self::Rpc => anyhow!("stateless Worker dropped RPC result"),
508 Self::Queue => anyhow!("stateless Worker dropped queue result"),
509 }
510 }
511}
512
513struct CellHandle {
514 epoch: u64,
515 /// The application generation whose isolate holds this cell, reported
516 /// when the cell leaves for a swap.
517 generation: GenerationId,
518 startup_us: u64,
519 /// The cell's claim on the isolate holding its realm. An event knows
520 /// where to run from it, and dropping it gives the placement back.
521 residency: crate::pool::Residency,
522 /// The source value and wake revision stay together in the registry.
523 /// Reading a newer flusher revision beside an older cached value would
524 /// authorize that old value to delete a later arm's entry.
525 alarm: celld_logic::wake::AlarmSnapshot,
526 requests: Arc<CellRequestAdmission>,
527}
528
529struct CellRequestAdmission {
530 in_flight: AtomicUsize,
531 saturated: AtomicBool,
532 limit: usize,
533}
534
535impl CellRequestAdmission {
536 fn acquire(self: &Arc<Self>) -> Option<CellRequestPermit> {
537 let admitted = self
538 .in_flight
539 .fetch_update(Ordering::AcqRel, Ordering::Acquire, |held| {
540 (held < self.limit).then_some(held + 1)
541 })
542 .is_ok();
543 if admitted {
544 // A successful admission proves that the target left its prior
545 // saturated interval. Reset here as well as on release because a
546 // refusal and a release can race between the failed count check
547 // and the saturation transition.
548 self.saturated.store(false, Ordering::Release);
549 }
550 admitted.then(|| CellRequestPermit(self.clone()))
551 }
552}
553
554struct CellRequestPermit(Arc<CellRequestAdmission>);
555
556impl Drop for CellRequestPermit {
557 fn drop(&mut self) {
558 let held = self.0.in_flight.fetch_sub(1, Ordering::AcqRel);
559 if held == self.0.limit {
560 self.0.saturated.store(false, Ordering::Release);
561 }
562 }
563}
564
565struct AdmittedCellRequest {
566 affiliation: crate::pool::Affiliation,
567 permit: CellRequestPermit,
568}
569
570/// How a turn's alarm move reaches the host. `drive_cell` calls it with
571/// what `take_alarm_moves` drained; it caches the value on the cell's
572/// handle and forwards a real change to the observer.
573#[doc(hidden)]
574pub type AlarmReporter = Arc<dyn Fn(String, celld_logic::wake::AlarmSnapshot) + Send + Sync>;
575
576/// Each committed installation reaches the host, including same-time re-arms.
577/// Duplicate observations of that installation are deduplicated. A
578/// scope without a handle was stopped mid-flight; its ActivityFinished
579/// report is gone with it, so a move for it says nothing and is dropped.
580///
581/// The observer is called under the registry lock, and `with_alarm` reads
582/// and reports under the same lock, so what reaches the core is monotone
583/// with the cache: a stale end-of-request read cannot land *after* a
584/// fresher report and unarm an alarm the core just learned about — the
585/// core overwrites on observation and deletes the wake entry on `None`,
586/// so that ordering loses the alarm outright. The observer only sends on
587/// an unbounded channel, so holding the lock across it cannot block.
588fn alarm_reporter(cells: &Arc<Mutex<CellRegistry>>, observe: &AlarmObserver) -> AlarmReporter {
589 let cells_ = cells.clone();
590 let observe_ = observe.clone();
591 Arc::new(
592 move |scope: String, alarm: celld_logic::wake::AlarmSnapshot| {
593 let mut registry = cells_.lock().expect("cell registry poisoned");
594 let handle = if let Some(handle) = registry.published.get_mut(&scope) {
595 Some(handle)
596 } else {
597 registry.starting.get_mut(&scope)
598 };
599 if let Some(handle) = handle {
600 let changed = handle.alarm.at_ms() != alarm.at_ms();
601 // Refresh the revision even when a same-time rearm needs no timer
602 // change. An ActivityFinished must use that source's snapshot.
603 handle.alarm = alarm;
604 if changed {
605 observe_(scope, alarm);
606 }
607 }
608 },
609 )
610}
611
612#[derive(Default)]
613struct CellRegistry {
614 starting: HashMap<String, CellHandle>,
615 published: HashMap<String, CellHandle>,
616}
617
618#[derive(Clone)]
619pub struct RuntimeManager {
620 /// What the node's cell runtime holds whichever engine runs the cells.
621 core: crate::cell_runtime::CellRuntime,
622 cells: Arc<Mutex<CellRegistry>>,
623 alarm_reporter: AlarmReporter,
624 /// A peer abort can arrive before the forwarded fetch. The tombstone and
625 /// cell enqueue share this lock so neither ordering can lose cancellation.
626 remote_requests: Arc<Mutex<RemoteRequestRegistry>>,
627 /// Shell alarm tasks keyed by the core firing operation. A shutdown
628 /// cancellation must target the firing it observed, not a later retry.
629 alarm_requests: Arc<Mutex<AlarmRequestRegistry>>,
630 max_cell_requests: usize,
631}
632
633/// The engine-neutral half, so a method of either reads as the manager's own.
634impl std::ops::Deref for RuntimeManager {
635 type Target = crate::cell_runtime::CellRuntime;
636 fn deref(&self) -> &crate::cell_runtime::CellRuntime {
637 &self.core
638 }
639}
640
641/// The engine's part of `Generation::build`: V8 starts once per process.
642pub(crate) fn init_engine() {
643 init_v8();
644}
645
646/// The isolates a script's cells live in, built from the script's config.
647pub(crate) fn cell_pool(config: Arc<WorkerConfig>) -> Arc<crate::pool::Pool> {
648 Arc::new(crate::pool::Pool::new(
649 pool_limits(),
650 admission_wait(),
651 Box::new(move || load_cell_isolate(config.clone())),
652 ))
653}
654
655/// Wait for one cell fetch reply without retaining the internal receiver after
656/// its external caller disconnects. Dropping that receiver is the direct wake
657/// for a reply that already belongs to a detached wake-entry gate task.
658async fn receive_cell_fetch_reply(
659 mut receive: tokio::sync::oneshot::Receiver<anyhow::Result<HttpResponse>>,
660 cancellation: Option<Arc<RequestCancellationLifetime>>,
661 cancel: Option<tokio::sync::oneshot::Receiver<()>>,
662) -> anyhow::Result<HttpResponse> {
663 let received = match (cancellation, cancel) {
664 (Some(cancellation), Some(mut cancel)) => asyncrt::select_biased! {
665 "a completed cell reply wins a tie with an external disconnect";
666 result = &mut receive => result,
667 cancelled = &mut cancel => match cancelled {
668 Ok(()) => {
669 // The driver reads this between turns. Dropping the
670 // receiver also wakes a reply that has already left V8
671 // and is waiting only on its event's durability gates.
672 cancellation.publish_abort();
673 drop(receive);
674 return Err(anyhow!("The client has disconnected"));
675 }
676 Err(_) => receive.await,
677 }
678 },
679 _ => receive.await,
680 };
681 received.context("cell isolate dropped response")?
682}
683
684pub(crate) async fn receive_service_fetch_response(
685 response: impl std::future::Future<Output = anyhow::Result<HttpResponse>>,
686 cancellation: Arc<RequestCancellationLifetime>,
687 cancel: Option<tokio::sync::oneshot::Receiver<()>>,
688) -> anyhow::Result<HttpResponse> {
689 match cancel {
690 Some(mut cancel) => crate::asyncrt::select_biased! {
691 "a completed service response wins a tie with an external disconnect";
692 response = response => response,
693 _ = &mut cancel => {
694 cancellation.publish_abort();
695 Err(anyhow!("service-binding caller disconnected"))
696 }
697 },
698 None => response.await,
699 }
700}
701
702#[cfg(celld_internal_tests)]
703#[doc(hidden)]
704pub async fn receive_cell_fetch_reply_for_test(
705 receive: tokio::sync::oneshot::Receiver<anyhow::Result<HttpResponse>>,
706 request_id: Option<js::RequestId>,
707 cancel: Option<tokio::sync::oneshot::Receiver<()>>,
708) -> anyhow::Result<HttpResponse> {
709 let cancellation = request_id.map(RequestCancellationLifetime::from_request_id);
710 receive_cell_fetch_reply(receive, cancellation, cancel).await
711}
712
713#[cfg(celld_internal_tests)]
714#[derive(Clone)]
715#[doc(hidden)]
716pub struct RequestCancellationLifetimeForTest(Arc<RequestCancellationLifetime>);
717
718#[cfg(celld_internal_tests)]
719#[doc(hidden)]
720pub fn request_cancellation_lifetime_for_test(
721 request_id: js::RequestId,
722) -> RequestCancellationLifetimeForTest {
723 RequestCancellationLifetimeForTest(RequestCancellationLifetime::from_request_id(request_id))
724}
725
726#[cfg(celld_internal_tests)]
727#[doc(hidden)]
728pub fn finish_request_cancellation_for_test(lifetime: &RequestCancellationLifetimeForTest) {
729 lifetime.0.finish();
730}
731
732#[cfg(celld_internal_tests)]
733#[doc(hidden)]
734pub fn finish_active_request_cancellation_for_test(lifetime: &Arc<RequestCancellationLifetime>) {
735 lifetime.finish();
736}
737
738#[cfg(celld_internal_tests)]
739#[doc(hidden)]
740pub async fn receive_cell_fetch_reply_with_lifetime_for_test(
741 receive: tokio::sync::oneshot::Receiver<anyhow::Result<HttpResponse>>,
742 lifetime: RequestCancellationLifetimeForTest,
743 cancel: tokio::sync::oneshot::Receiver<()>,
744 entered: tokio::sync::oneshot::Sender<()>,
745) -> anyhow::Result<HttpResponse> {
746 let _ = entered.send(());
747 receive_cell_fetch_reply(receive, Some(lifetime.0), Some(cancel)).await
748}
749
750#[cfg(all(test, celld_internal_tests))]
751pub(crate) async fn receive_service_fetch_response_for_test(
752 response: impl std::future::Future<Output = anyhow::Result<HttpResponse>>,
753 lifetime: Arc<RequestCancellationLifetime>,
754 cancel: tokio::sync::oneshot::Receiver<()>,
755) -> anyhow::Result<HttpResponse> {
756 receive_service_fetch_response(response, lifetime, Some(cancel)).await
757}
758
759impl RuntimeManager {
760 /// A deployment with no Durable Object classes can never land a Worker fetch
761 /// on a cell, so the core's round-robin routing always returns `None`. Lets
762 /// the request path skip the core round-trip entirely for stateless workers.
763 pub fn has_cell_classes(&self) -> bool {
764 self.generation().has_cell_classes()
765 }
766
767 /// The reserved cell carrying the current deployment's cron schedule, or
768 /// `None` when it declares no `triggers.crons`. Asked after every
769 /// adoption so the schedule is armed without a request.
770 pub fn cron_cell(&self) -> Option<String> {
771 self.generation().cron_cell()
772 }
773
774 /// Start the node's cell runtime around its first generation.
775 ///
776 /// The generation is built before this is called, by `Generation::build`,
777 /// which is also what a reload calls: a deployment reaches a running
778 /// node through exactly one function whether the node is booting or
779 /// adopting. What starts here is the node-level state that outlives any
780 /// generation — the cell registry, replication, the wake flusher.
781 pub fn start(generation: Generation, options: RuntimeOptions) -> anyhow::Result<Self> {
782 let RuntimeOptions {
783 data_dir,
784 replication,
785 wake,
786 alarm_observer,
787 node,
788 region,
789 bucket,
790 } = options;
791 let max_cell_requests =
792 crate::env_vars::positive_or("CELLD_MAX_CELL_REQUESTS", DEFAULT_MAX_CELL_REQUESTS)?;
793 let generation = Arc::new(generation);
794 let core = crate::cell_runtime::CellRuntime::new(
795 generation.clone(),
796 data_dir,
797 replication,
798 wake,
799 alarm_observer,
800 node,
801 region,
802 )?;
803 let cells = Arc::new(Mutex::new(CellRegistry::default()));
804 let alarm_reporter = alarm_reporter(&cells, &core.alarm_observer);
805 let manager = Self {
806 core,
807 cells,
808 alarm_reporter,
809 remote_requests: Arc::new(Mutex::new(RemoteRequestRegistry::default())),
810 alarm_requests: Arc::new(Mutex::new(AlarmRequestRegistry::default())),
811 max_cell_requests,
812 };
813 manager.watch_generation(&generation);
814 crate::container::configure(
815 manager.node.to_string(),
816 bucket,
817 manager.data_dir.as_ref().clone(),
818 );
819 install_container_specs(&generation);
820 Ok(manager)
821 }
822
823 /// Make `generation` current: the flip.
824 ///
825 /// From the moment this returns, new stateless requests, new cell
826 /// activations, ingress asset lookups, service-binding resolution, and
827 /// queue dispatch use the new generation. The previous one stops taking
828 /// new work and drains; it is dropped once every isolate it built has
829 /// been freed. Requests and cells already on it finish there.
830 pub fn adopt(&self, generation: Generation) -> Arc<Generation> {
831 let next = Arc::new(generation);
832 self.watch_generation(&next);
833 install_container_specs(&next);
834 let previous = {
835 let mut generations = self.generations.write().expect("generation lock poisoned");
836 let previous = std::mem::replace(&mut generations.current, next.clone());
837 // Installed in the same instant the new one becomes current. A
838 // call from an isolate of the previous generation must never
839 // find neither, because `generation_by_id` answers "neither"
840 // with the current generation and the call would cross.
841 generations.draining.push(previous.clone());
842 previous
843 };
844 tracing::info!(
845 event = "deployment_generation_adopted",
846 generation = next.id,
847 version = %next.version,
848 prefix = %next.prefix,
849 previous_generation = previous.id,
850 previous_version = %previous.version,
851 "application generation adopted"
852 );
853 // After the install, never before: retiring walks every pool of the
854 // previous generation and this must not hold the generation lock,
855 // which every request reads.
856 previous.retire();
857 next
858 }
859
860 /// Spawn the maintenance loop for one generation's cell pools.
861 ///
862 /// The loop holds a weak reference. A strong one would keep a superseded
863 /// generation — its compiled scripts and every pool — alive for the life
864 /// of the process, so the loop ends when the generation is dropped. The
865 /// draining list is what keeps a superseded generation alive until then,
866 /// and this loop is what removes it from that list once every isolate it
867 /// built has been freed.
868 fn watch_generation(&self, generation: &Arc<Generation>) {
869 let Ok(handle) = tokio::runtime::Handle::try_current() else {
870 return;
871 };
872 let reaping = Arc::downgrade(generation);
873 let generations = self.generations.clone();
874 handle.spawn(async move {
875 let mut tick = tokio::time::interval_at(
876 tokio::time::Instant::now() + REAP_INTERVAL,
877 REAP_INTERVAL,
878 );
879 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
880 loop {
881 tick.tick().await;
882 let Some(generation) = reaping.upgrade() else {
883 return;
884 };
885 generation.reap_cell_pools();
886 if !generation.is_drained() {
887 continue;
888 }
889 let mut generations = generations.write().expect("generation lock poisoned");
890 if let Some(index) = generations
891 .draining
892 .iter()
893 .position(|candidate| Arc::ptr_eq(candidate, &generation))
894 {
895 generations.draining.remove(index);
896 tracing::info!(
897 event = "deployment_generation_freed",
898 generation = generation.id,
899 version = %generation.version,
900 "application generation freed"
901 );
902 }
903 }
904 });
905 }
906
907 pub async fn fetch_worker(
908 &self,
909 url: String,
910 method: String,
911 body: Vec<u8>,
912 headers: Vec<(String, String)>,
913 ) -> anyhow::Result<HttpResponse> {
914 // The snapshot is held for the whole request, so the generation it
915 // started on outlives it even after the node adopts another.
916 let generation = self.generation();
917 generation
918 .stateless
919 .fetch(url, method, body.into(), headers, None)
920 .await
921 }
922
923 /// Dispatch a cancellable top-level Worker request to the stateless pool.
924 pub fn fetch_worker_pool(
925 &self,
926 url: String,
927 method: String,
928 body: js::RequestBody,
929 headers: Vec<(String, String)>,
930 cancellation: Arc<RequestCancellationLifetime>,
931 ) -> impl std::future::Future<Output = anyhow::Result<HttpResponse>> + Send + 'static {
932 let generation = self.generation();
933 let fetching = generation
934 .stateless
935 .fetch(url, method, body, headers, Some(cancellation));
936 async move {
937 let _generation = generation;
938 fetching.await
939 }
940 }
941
942 /// Dispatch a top-level Worker request on the exact resident runtime the
943 /// decision core reserved. The activity token pins that lifecycle choice
944 /// until the queued event has completely left the isolate loop.
945 pub async fn fetch_worker_on_cell(
946 &self,
947 cell: String,
948 epoch: u64,
949 request: RuntimeFetch,
950 inline_activity: crate::CellActivityGuard,
951 ) -> anyhow::Result<HttpResponse> {
952 let RuntimeFetch {
953 url,
954 method,
955 body,
956 headers,
957 request_id,
958 // A resident Worker fetch is not a cell event; its inbound
959 // traceparent is honored by the drive, from the headers.
960 order: _,
961 parent: _,
962 } = request;
963 let request_id = request_id.context("resident Worker fetch requires a request id")?;
964 let isolate = self
965 .cells
966 .lock()
967 .expect("cell registry poisoned")
968 .published
969 .get(&cell)
970 .filter(|handle| handle.epoch == epoch)
971 // Affiliated under the registry lock for the driver's whole
972 // lifetime, exactly like cell_isolate (denoland/celld#147).
973 .map(|handle| handle.residency.slot().affiliate())
974 .ok_or_else(|| anyhow!("cell runtime is not published at epoch {epoch}: {cell}"))?;
975 // The Worker entry, run in the isolate that hosts the cell it will
976 // route to. The call still goes out through the host -- every cell
977 // dispatch does -- but it comes back to an isolate that is already
978 // warm for this cell, with its storage open and its instance live.
979 //
980 // It needs no rescheduling any more. A Worker fetch could not be
981 // nested inside an actor event, and delivery used to nest, so a job
982 // that arrived mid-event had to be handed back to the stateless
983 // pool. Events no longer nest: this is an entry like any other, and
984 // it waits for its turn rather than for the isolate to go idle.
985 let (reply, receive) = tokio::sync::oneshot::channel();
986 let job = crate::WorkerJob::Fetch {
987 queued_at: Instant::now(),
988 entrypoint: None,
989 invocation_limits: None,
990 url,
991 method,
992 body,
993 headers,
994 request_id: Some(request_id),
995 tail_report: None,
996 reply,
997 };
998 tokio::spawn(async move {
999 let _inline_activity = inline_activity;
1000 drive_worker_on_cell(isolate, job).await;
1001 });
1002 receive
1003 .await
1004 .context("cell isolate dropped Worker response")?
1005 }
1006
1007 /// Call a service binding. `generation` is the caller's, so the target
1008 /// comes from the deployment graph the caller was built with.
1009 pub async fn fetch_service(&self, call: ServiceFetch) -> anyhow::Result<HttpResponse> {
1010 let ServiceFetch {
1011 generation,
1012 script,
1013 entrypoint,
1014 url,
1015 method,
1016 body,
1017 headers,
1018 cancel,
1019 } = call;
1020 let generation = self.generation_by_id(generation);
1021 let pool = generation
1022 .service(&script)
1023 .ok_or_else(|| anyhow!("no service Worker for script {script}"))?;
1024 let cancellation = RequestCancellationLifetime::stateless();
1025 let response = pool.fetch_target(
1026 entrypoint,
1027 url,
1028 method,
1029 body,
1030 headers,
1031 Some(cancellation.clone()),
1032 );
1033 receive_service_fetch_response(response, cancellation, cancel).await
1034 }
1035
1036 pub async fn rpc_service(
1037 &self,
1038 generation: GenerationId,
1039 script: &str,
1040 entrypoint: String,
1041 props: Vec<u8>,
1042 operation: crate::WorkerRpcOperation,
1043 ) -> anyhow::Result<Vec<u8>> {
1044 let generation = self.generation_by_id(generation);
1045 generation
1046 .service(script)
1047 .ok_or_else(|| anyhow!("no service Worker for script {script}"))?
1048 .rpc(entrypoint, props, operation)
1049 .await
1050 }
1051
1052 /// Dispatch one broker-leased batch to its attached consumer script.
1053 pub async fn queue_service(
1054 &self,
1055 generation: GenerationId,
1056 script: &str,
1057 batch: js::QueueBatch,
1058 ) -> anyhow::Result<js::QueueDispatchResult> {
1059 let generation = self.generation_by_id(generation);
1060 generation
1061 .service(script)
1062 .ok_or_else(|| anyhow!("no Queue consumer Worker for script {script}"))?
1063 .queue(batch)
1064 .await
1065 }
1066
1067 pub async fn restore_cell(
1068 &self,
1069 cell: &str,
1070 spec: &celld_logic::RestoreSpec,
1071 ) -> anyhow::Result<celld_logic::RestoreOutcome> {
1072 let path = self.db_path(cell, spec.epoch);
1073 self.facets.register(cell, spec);
1074 if let Some(replication) = &self.replication {
1075 let (restored_path, restored, vfs) = replication.restore(cell, spec, true).await?;
1076 if restored_path != path {
1077 return Err(anyhow!(
1078 "replication restored {} instead of {}",
1079 restored_path.display(),
1080 path.display()
1081 ));
1082 }
1083 return Ok(celld_logic::RestoreOutcome {
1084 restored,
1085 alarm: self.restored_alarm(cell, &path, vfs.as_deref()).await,
1086 });
1087 }
1088 let parent = path.parent().context("cell database has no parent")?;
1089 let parent = parent.to_path_buf();
1090 let parent_display = parent.display().to_string();
1091 let filesystem = asyncrt::fs();
1092 asyncrt::blocking(move || filesystem.create_dir_all(&parent))
1093 .await?
1094 .with_context(|| format!("create cell data directory {parent_display}"))?;
1095 Ok(celld_logic::RestoreOutcome {
1096 restored: false,
1097 alarm: self.restored_alarm(cell, &path, None).await,
1098 })
1099 }
1100
1101 /// The alarm the restored database already had armed, read directly by
1102 /// path. Read-only, and the connection is dropped here -- the isolate
1103 /// opens the same file moments later through `spawn_cell`.
1104 async fn restored_alarm(
1105 &self,
1106 cell: &str,
1107 path: &std::path::Path,
1108 vfs: Option<&str>,
1109 ) -> Option<celld_logic::RestoredAlarm> {
1110 // A paged cell's alarm read faults pages in on the reading thread, so
1111 // it runs on a blocking thread rather than on this runtime worker.
1112 let path_ = path.to_string_lossy().into_owned();
1113 let cell_ = cell.to_string();
1114 let vfs_ = vfs.map(str::to_string);
1115 let persisted = asyncrt::blocking(move || {
1116 crate::storage::persisted_alarm(&path_, &cell_, vfs_.as_deref())
1117 })
1118 .await
1119 .ok()
1120 .flatten();
1121 restored_alarm_from_persisted(cell, persisted, |at_ms| {
1122 self.alarm_covered(
1123 cell,
1124 celld_logic::wake::AlarmSnapshot::without_wake(Some(at_ms)),
1125 )
1126 })
1127 }
1128
1129 /// Detach every resident runtime, prove and retain its exact database path,
1130 /// and remove stale live-named epochs. The caller has already stopped
1131 /// admission and drained request effects.
1132 pub async fn prepare_clean_reload(
1133 &self,
1134 cells: &[celld_logic::PresenceCell],
1135 ) -> anyhow::Result<usize> {
1136 let replication = self
1137 .replication
1138 .as_ref()
1139 .context("clean reload requires replication")?;
1140 let keep: BTreeSet<_> = cells
1141 .iter()
1142 .map(|cell| (cell.id.clone(), cell.epoch))
1143 .collect();
1144 anyhow::ensure!(
1145 keep.len() == cells.len(),
1146 "clean reload resident inventory contains duplicates"
1147 );
1148 let mut closes = futures_util::stream::iter(cells.iter().cloned())
1149 .map(|cell| {
1150 let runtime = self.clone();
1151 let replication = replication.clone();
1152 async move {
1153 // A normal stop releases the replica before returning.
1154 // Keep it registered until the final capture proves the
1155 // stopped database position present in the bucket.
1156 runtime.swap_out_cell(&cell.id, cell.epoch).await?;
1157 for facet in runtime.facets.stopping(&cell.id, cell.epoch) {
1158 replication.close_for_reload(&facet, cell.epoch).await?;
1159 runtime.facets.stopped(&cell.id, cell.epoch, &facet);
1160 }
1161 replication.close_for_reload(&cell.id, cell.epoch).await?;
1162 runtime.facets.forget(&cell.id, cell.epoch);
1163 anyhow::Ok(())
1164 }
1165 })
1166 .buffer_unordered(128);
1167 while let Some(result) = closes.next().await {
1168 result?;
1169 }
1170 let pruned = replication.prune_stale_live(&keep)?;
1171 Ok(pruned)
1172 }
1173
1174 /// Take a cell out of its isolate for a generation swap.
1175 ///
1176 /// The first half of `stop_cell` and nothing more: close the application
1177 /// database in the isolate that holds it, and drop the residency so the
1178 /// isolate can be reclaimed once its last cell leaves. The replica keeps
1179 /// its handle and its file, the owner record keeps its epoch, and the
1180 /// core starts the cell again on the current generation as soon as it
1181 /// hears the stop. A cell already gone is not an error: the swap and an
1182 /// eviction can race, and the eviction's stop did this work.
1183 pub async fn swap_out_cell(&self, cell: &str, epoch: u64) -> anyhow::Result<()> {
1184 // The isolates to release, taken by reference rather than by handle.
1185 // A release that fails can leave this cell's database open in that
1186 // realm, and the handle owns both the residency that keeps the realm
1187 // from being reclaimed and the registry entry a retry finds it
1188 // through -- so only a release that succeeded gives them up.
1189 let slots: Vec<(Arc<crate::pool::Slot>, GenerationId)> = {
1190 let cells = self.cells.lock().expect("cell registry poisoned");
1191 [&cells.starting, &cells.published]
1192 .into_iter()
1193 .filter_map(|residents| residents.get(cell))
1194 .filter(|handle| handle.epoch == epoch)
1195 .map(|handle| (handle.residency.slot().clone(), handle.generation))
1196 .collect()
1197 };
1198 for (slot, generation) in slots {
1199 // Taking the isolate for this turn is the barrier: an event of
1200 // this cell either finished its turn before it or has not
1201 // started one, so closing its SQLite cannot land mid-handler.
1202 slot.turn(|worker| {
1203 #[cfg(debug_assertions)]
1204 if let Some(error) = crate::engine_api::injected_swap_release_failure() {
1205 return Err(error);
1206 }
1207 worker.own_cell(cell, None)
1208 })
1209 .await
1210 .with_context(|| format!("release {cell} from its isolate for a generation swap"))?;
1211 crate::js::release_root_facets(cell, epoch, crate::js::RootRelease::Swap).await;
1212 tracing::info!(
1213 event = "generation_swap_out",
1214 scope = %cell,
1215 epoch,
1216 generation,
1217 "cell left its isolate for a generation swap"
1218 );
1219 }
1220 // Released, so the placements can go back. Dropping each handle drops
1221 // its residency, which is what lets the isolate be reclaimed once its
1222 // last cell has left.
1223 let mut cells = self.cells.lock().expect("cell registry poisoned");
1224 let CellRegistry {
1225 starting,
1226 published,
1227 } = &mut *cells;
1228 for residents in [starting, published] {
1229 if residents
1230 .get(cell)
1231 .is_some_and(|handle| handle.epoch == epoch)
1232 {
1233 residents.remove(cell);
1234 }
1235 }
1236 Ok(())
1237 }
1238
1239 /// Materialize an isolate and retain it as non-routable until publication.
1240 /// Start a cell's runtime and report which isolate took its realm and the
1241 /// generation it belongs to. The core groups eviction on the isolate and
1242 /// the swap pump keys on the generation, so both come back from here.
1243 pub async fn start_cell(
1244 &self,
1245 cell: String,
1246 epoch: u64,
1247 fresh: bool,
1248 ) -> anyhow::Result<(celld_logic::isolate::HeapId, GenerationId)> {
1249 let db_path = self.db_path(&cell, epoch);
1250 let class = cell
1251 .split_once(':')
1252 .map(|(class, _)| class)
1253 .ok_or_else(|| anyhow!("cell scope has no class: {cell}"))?;
1254 let generation = self.generation();
1255 let config = generation
1256 .cell_config(class)
1257 .ok_or_else(|| anyhow!("no Worker exports Durable Object class {class}"))?;
1258 // The object's `running` is read synchronously, so the engine
1259 // answers it here, before the object exists. A container a previous
1260 // activation on this node left running is adopted by name.
1261 if config.container_class(class) {
1262 let engine = crate::container::engine().await?;
1263 engine.attach(&cell, class).await?;
1264 }
1265 let startup_timing = CellIsolateStartupTiming {
1266 started: Instant::now(),
1267 scope: cell.clone(),
1268 node: self.node.clone(),
1269 region: self.region.clone(),
1270 epoch,
1271 fresh,
1272 };
1273
1274 let isolates = generation
1275 .cell_isolates(&config.script_name)
1276 .ok_or_else(|| anyhow!("no cell isolates for script {}", config.script_name))?;
1277 // Building an isolate compiles the script, so it runs on a blocking
1278 // thread: the pool builds before taking its lock, but the caller is a
1279 // tokio worker either way.
1280 let placed = {
1281 let isolates = isolates.clone();
1282 tokio::task::spawn_blocking(move || isolates.place_cell())
1283 .await
1284 .context("cell placement panicked")?
1285 };
1286 let residency = match placed {
1287 Ok(residency) => residency,
1288 Err(error) => {
1289 startup_timing.emit("error", "worker_load");
1290 return Err(error);
1291 }
1292 };
1293 let placed_in = residency.slot().heap_id();
1294
1295 // Everything the cell needs that the isolate must do: open its
1296 // SQLite — which the isolate owns, not the caller — and restore its
1297 // persisted id name. A paged restore leaves the file sparse behind
1298 // the activation's VFS, so the actor's connection must open through
1299 // it too.
1300 //
1301 // A direct call rather than a job: adoption is not an event, it runs
1302 // no handler, and it needs one turn.
1303 // The activation's own answer, not a guess from an absent handle: a
1304 // cell removed between restore and adoption must not be opened
1305 // plainly over a sparse or missing file.
1306 let paged_vfs = match self.replication.as_ref() {
1307 Some(replication) => match replication.ltx().activation_vfs(&cell, epoch) {
1308 Ok(vfs) => vfs,
1309 Err(error) => {
1310 startup_timing.emit("error", "storage_open");
1311 return Err(error);
1312 }
1313 },
1314 None => None,
1315 };
1316 let adopted = residency
1317 .adopt(
1318 &cell,
1319 CellStorage {
1320 path: path_text(&db_path),
1321 epoch,
1322 replicated_wake: self.wake.is_some(),
1323 vfs: paged_vfs.as_deref(),
1324 },
1325 )
1326 .await;
1327 let (residency, alarm) = match adopted {
1328 Ok(adopted) => adopted,
1329 Err(error) => {
1330 startup_timing.emit("error", "storage_open");
1331 return Err(error);
1332 }
1333 };
1334 (self.alarm_observer)(cell.clone(), alarm);
1335 let startup_us = startup_timing.emit("ready", "");
1336
1337 {
1338 let mut cells = self.cells.lock().expect("cell registry poisoned");
1339 if cells.starting.contains_key(&cell) || cells.published.contains_key(&cell) {
1340 return Err(anyhow!("cell runtime already exists: {cell}"));
1341 }
1342 cells.starting.insert(
1343 cell.clone(),
1344 CellHandle {
1345 epoch,
1346 generation: generation.id,
1347 startup_us,
1348 residency,
1349 alarm,
1350 requests: Arc::new(CellRequestAdmission {
1351 in_flight: AtomicUsize::new(0),
1352 saturated: AtomicBool::new(false),
1353 limit: self.max_cell_requests,
1354 }),
1355 },
1356 );
1357 Ok((placed_in, generation.id))
1358 }
1359 }
1360
1361 /// Make the exact started generation visible to request dispatch.
1362 pub fn publish_cell(&self, cell: &str, epoch: u64) -> anyhow::Result<()> {
1363 let mut cells = self.cells.lock().expect("cell registry poisoned");
1364 if cells
1365 .starting
1366 .get(cell)
1367 .is_none_or(|handle| handle.epoch != epoch)
1368 {
1369 return Err(anyhow!("no started cell runtime for {cell} epoch {epoch}"));
1370 }
1371 let handle = cells
1372 .starting
1373 .remove(cell)
1374 .expect("checked started runtime");
1375 let startup_us = handle.startup_us;
1376 if let Some(replaced) = cells.published.insert(cell.to_string(), handle) {
1377 // Nothing to shut down: the isolate serves other cells, and
1378 // dropping the handle drops the residency that held its place.
1379 drop(replaced);
1380 return Err(anyhow!("replaced published cell runtime for {cell}"));
1381 }
1382 drop(cells);
1383 tracing::info!(
1384 event = "cell_runtime_publication",
1385 outcome = "published",
1386 scope = %cell,
1387 node = %self.node,
1388 region = %self.region,
1389 runtime_version = env!("CARGO_PKG_VERSION"),
1390 epoch,
1391 isolate_startup_us = startup_us,
1392 "cell runtime published"
1393 );
1394 Ok(())
1395 }
1396
1397 pub(crate) async fn stop_cell(
1398 &self,
1399 cell: &str,
1400 epoch: u64,
1401 mode: StopMode,
1402 ) -> anyhow::Result<()> {
1403 // No facet opens once the stop begins; the facet loop below stops
1404 // the streams this answers again, with any that opened before.
1405 self.facets.stopping(cell, epoch);
1406 if let Some(engine) = crate::container::engine_if_ready() {
1407 // Only an idle eviction keeps the cell on this node, so only it
1408 // keeps the container: the next activation here reconnects.
1409 let release = match &mode {
1410 StopMode::Evict {
1411 preserve_local: true,
1412 ..
1413 } => crate::container::Release::Keep,
1414 _ => crate::container::Release::Destroy,
1415 };
1416 engine.release(cell, release).await;
1417 }
1418 let mut stopped = Vec::new();
1419 {
1420 let mut cells = self.cells.lock().expect("cell registry poisoned");
1421 if cells
1422 .starting
1423 .get(cell)
1424 .is_some_and(|handle| handle.epoch == epoch)
1425 {
1426 if let Some(handle) = cells.starting.remove(cell) {
1427 stopped.push(handle);
1428 }
1429 }
1430 if cells
1431 .published
1432 .get(cell)
1433 .is_some_and(|handle| handle.epoch == epoch)
1434 {
1435 if let Some(handle) = cells.published.remove(cell) {
1436 stopped.push(handle);
1437 }
1438 }
1439 }
1440 for handle in stopped {
1441 // Give the cell back rather than shutting the isolate down: it
1442 // serves other cells. Taking the isolate for this turn is the
1443 // barrier — an event of this cell either finished its turn
1444 // before it, or has not started one — so closing its SQLite
1445 // cannot land under a handler that is mid-turn.
1446 // The cell's own lane, not the shared stateless one: this stop
1447 // follows the turns already admitted for this cell, and it does
1448 // not wait behind every stateless turn queued on the isolate. On
1449 // a loaded node that queue held a handoff batch for minutes.
1450 let _ = handle
1451 .residency
1452 .slot()
1453 .turn_cell(cell, |worker| worker.own_cell(cell, None))
1454 .await;
1455 // Dropping the handle drops its residency, which is what gives
1456 // the isolate its place back — and what lets `retire` reclaim
1457 // the isolate once no cell is left in it.
1458 drop(handle);
1459 }
1460 // After the give-back, so the root cannot start another facet call,
1461 // and before the facet streams stop, so no write reaches a file that
1462 // the facet's eviction unlinked.
1463 crate::js::release_root_facets(cell, epoch, crate::js::RootRelease::Stop).await;
1464 let Some(replication) = &self.replication else {
1465 self.facets.forget(cell, epoch);
1466 return Ok(());
1467 };
1468 // The root and its facets stop in the order `FacetStreams::stop_root`
1469 // owns, which a test drives through its failures.
1470 let stop_root = || async {
1471 // Every stop releases the handle, and this does not consult
1472 // `stopped_runtime`. The replication entry is created by
1473 // `Effect::Restore` and the registry entry by
1474 // `Effect::StartRuntime`, so the entry outlives a start that fails
1475 // between the two and there is nothing else that would ever remove
1476 // it. Its lifetime is the activation's, not the registry's.
1477 //
1478 // The mode pairs the durability authority with the file outcome.
1479 // Passing these as independent booleans let cleanup close a proved
1480 // remote restore in place, where no later activation could use it.
1481 match &mode {
1482 // A failed final sync leaves the handle and files in place.
1483 // This call is therefore intentionally retryable after the
1484 // runtime itself has already stopped. An abandoned one is not:
1485 // it returns `EvictionAbandoned`, and the caller ends the stop
1486 // instead of trying again.
1487 StopMode::Evict {
1488 preserve_local,
1489 abandon,
1490 } => replication
1491 .evict(cell, epoch, *preserve_local, abandon.as_deref())
1492 .await
1493 .map(|_| ()),
1494 StopMode::Rebase => replication.release(cell, epoch).await,
1495 StopMode::CloseInPlace => replication.close_in_place(cell, epoch).await,
1496 StopMode::Discard => {
1497 replication.ltx().discard(cell, epoch);
1498 Ok(())
1499 }
1500 }
1501 };
1502 let stop_facet = |facet: String| {
1503 let mode = &mode;
1504 async move {
1505 // A retry after the facet's stream stopped, or after shutdown
1506 // took the handle, has nothing left to stop.
1507 if !replication.ltx().is_resident(&facet, epoch) {
1508 return Ok(());
1509 }
1510 match mode {
1511 // A facet keeps no local file past an eviction: its handler
1512 // writes through a connection of its own, which can outlive
1513 // the root's stop, and a preserved file would become the
1514 // next activation's baseline. The root is gone by now, so
1515 // the eviction is not abandoned.
1516 StopMode::Evict { .. } => replication
1517 .evict(&facet, epoch, false, None)
1518 .await
1519 .map(|_| ()),
1520 StopMode::Rebase => replication.release(&facet, epoch).await,
1521 StopMode::CloseInPlace => replication.close_in_place(&facet, epoch).await,
1522 StopMode::Discard => {
1523 replication.ltx().discard(&facet, epoch);
1524 Ok(())
1525 }
1526 }
1527 }
1528 };
1529 self.facets
1530 .stop_root(
1531 cell,
1532 epoch,
1533 replication.ltx().is_resident(cell, epoch),
1534 stop_root,
1535 stop_facet,
1536 )
1537 .await
1538 }
1539
1540 pub async fn fetch_cell(
1541 &self,
1542 cell: String,
1543 name: Option<String>,
1544 request: RuntimeFetch,
1545 cancel: Option<tokio::sync::oneshot::Receiver<()>>,
1546 ) -> anyhow::Result<HttpResponse> {
1547 let RuntimeFetch {
1548 url,
1549 method,
1550 body,
1551 headers,
1552 request_id,
1553 order,
1554 parent,
1555 } = request;
1556 let admitted = match self.admit_cell_request(&cell)? {
1557 Some(admitted) => admitted,
1558 None => {
1559 return Ok(HttpResponse {
1560 status: 503,
1561 headers: vec![
1562 ("retry-after".to_string(), "1".to_string()),
1563 ("x-celld-overload".to_string(), "cell".to_string()),
1564 ],
1565 body: b"cell request limit reached".to_vec(),
1566 websocket: None,
1567 stream: None,
1568 write_position: None,
1569 observed_position: None,
1570 });
1571 }
1572 };
1573 let AdmittedCellRequest {
1574 affiliation,
1575 permit,
1576 } = admitted;
1577 let (reply, receive) = tokio::sync::oneshot::channel();
1578 let job = CellJob::Fetch {
1579 request_id,
1580 scope: cell,
1581 name,
1582 url,
1583 method,
1584 body,
1585 headers,
1586 reply,
1587 order,
1588 };
1589 let cancellation = if let Some(request_id) = request_id {
1590 let mut requests = self
1591 .remote_requests
1592 .lock()
1593 .expect("request registry poisoned");
1594 requests.prune();
1595 if matches!(
1596 requests.states.remove(&request_id),
1597 Some(RemoteRequestState::PendingAbort(_))
1598 ) {
1599 requests.completed(request_id);
1600 return Err(anyhow!("the client disconnected before dispatch"));
1601 }
1602 Some(requests.active(request_id))
1603 } else {
1604 None
1605 };
1606 let alarm_reporter = self.alarm_reporter.clone();
1607 let drive_cancellation = cancellation.clone();
1608 tokio::spawn(async move {
1609 let _permit = permit;
1610 drive_cell_with_request_cancellation(
1611 affiliation,
1612 job,
1613 Some(alarm_reporter),
1614 parent,
1615 drive_cancellation,
1616 )
1617 .await;
1618 });
1619 let result = receive_cell_fetch_reply(receive, cancellation, cancel).await;
1620 if let Some(request_id) = request_id {
1621 let mut requests = self
1622 .remote_requests
1623 .lock()
1624 .expect("request registry poisoned");
1625 requests.completed(request_id);
1626 }
1627 result
1628 }
1629
1630 /// Tell a cell to abandon a fetch, by name.
1631 ///
1632 /// `fetch_cell` drops its reply receiver and returns when its explicit
1633 /// cancellation signal arrives. A caller that learns about a hang-up only
1634 /// in a destructor has no future left to receive that signal, so it uses
1635 /// this direct path instead.
1636 pub fn abort_fetch(&self, cell: &str, request_id: js::RequestId) {
1637 let mut requests = self
1638 .remote_requests
1639 .lock()
1640 .expect("request registry poisoned");
1641 requests.prune();
1642 requests.abort(request_id);
1643 drop(requests);
1644 let _ = cell;
1645 }
1646
1647 pub fn published_epoch(&self, cell: &str) -> Option<u64> {
1648 self.cells
1649 .lock()
1650 .expect("cell registry poisoned")
1651 .published
1652 .get(cell)
1653 .map(|handle| handle.epoch)
1654 }
1655
1656 pub fn alarm(&self, cell: &str) -> Option<i64> {
1657 self.with_alarm(cell, |at_ms| at_ms)
1658 }
1659
1660 /// Read the cell's alarm cache and call `f` before the registry lock is
1661 /// released. The reporter sends under the same lock, so whatever `f`
1662 /// sends is ordered with the reporter's sends: a read taken here cannot
1663 /// reach the core after a fresher report (see `alarm_reporter`).
1664 pub fn with_alarm<T>(&self, cell: &str, f: impl FnOnce(Option<i64>) -> T) -> T {
1665 self.with_alarm_snapshot(cell, |alarm| f(alarm.at_ms()))
1666 }
1667
1668 pub(crate) fn with_alarm_snapshot<T>(
1669 &self,
1670 cell: &str,
1671 f: impl FnOnce(celld_logic::wake::AlarmSnapshot) -> T,
1672 ) -> T {
1673 let cells = self.cells.lock().expect("cell registry poisoned");
1674 let alarm = cells
1675 .published
1676 .get(cell)
1677 .or_else(|| cells.starting.get(cell))
1678 .map(|handle| handle.alarm)
1679 .unwrap_or_else(|| celld_logic::wake::AlarmSnapshot::without_wake(None));
1680 f(alarm)
1681 }
1682
1683 pub async fn fire_alarm(
1684 &self,
1685 op: celld_logic::OpId,
1686 cell: String,
1687 scheduled_ms: i64,
1688 ) -> anyhow::Result<(celld_logic::wake::AlarmSnapshot, bool, Option<u64>)> {
1689 let request_id = js::next_request_id();
1690 let cancel = self
1691 .alarm_requests
1692 .lock()
1693 .expect("alarm registry poisoned")
1694 .begin(cell.clone(), op, request_id);
1695 let (reply, receive) = tokio::sync::oneshot::channel();
1696 let job = CellJob::Alarm {
1697 request_id: Some(request_id),
1698 scope: cell.clone(),
1699 scheduled_ms,
1700 claim: js::AlarmDispatch::Due,
1701 reply,
1702 };
1703 let guard = AlarmRequestGuard {
1704 registry: self.alarm_requests.clone(),
1705 cell: cell.clone(),
1706 op,
1707 request: request_id,
1708 };
1709 let isolate = self.cell_isolate(&cell)?;
1710 let alarm_reporter = self.alarm_reporter.clone();
1711 let drive = crate::asyncrt::spawn(async move {
1712 let _guard = guard;
1713 drive_alarm(isolate, job, Some(alarm_reporter)).await
1714 });
1715 if cancel {
1716 js::abort_request_for_shutdown(request_id);
1717 }
1718 let result = receive.await.context("cell isolate dropped alarm result")?;
1719 match result {
1720 // A handler that returned settled its claim inside its completion
1721 // turn (`Answer::Alarm`), so the snapshot and the delta it replied
1722 // with are already final and nothing below reads the drive's
1723 // position. The drive itself runs on, because a completed cell
1724 // event keeps its pending I/O (`completed_cell_event`), exactly as
1725 // it does after a fetch answers. Waiting for it here held the
1726 // core in `AlarmState::Firing` until the leftover I/O ended or the
1727 // operation deadline expired the firing, so an `alarm()` that left
1728 // one pending timer — what `AbortSignal.timeout` leaves behind
1729 // after its fetch finished — delayed every re-arm by up to
1730 // `CELLD_OPERATION_DEADLINE_MS`, and the core booked a handler
1731 // that succeeded as a stuck one (denoland/celld#228).
1732 Ok((alarm, wrote)) => {
1733 watch_detached_alarm_drive(drive, &cell, op);
1734 Ok((alarm, self.alarm_covered(&cell, alarm), wrote))
1735 }
1736 Err(error) => {
1737 // A cancelled or failed alarm settles its claim in the drive's
1738 // final isolate turn. The event reply is itself held behind
1739 // every wake-entry arm, so waiting for the drive makes that
1740 // final cache authoritative before the core sees completion.
1741 let final_write = drive.await.expect("cell alarm drive task panicked")?;
1742 // The drive completed its final isolate turn before this
1743 // branch. Its alarm cache is therefore authoritative even
1744 // when the handler failed: `Some` is the automatic retry or
1745 // an explicit re-arm, and `None` is an explicit change which
1746 // wins over retry. Returning the old firing as an error would
1747 // resurrect an alarm which storage no longer contains and
1748 // leave a draining cell permanently uncovered.
1749 //
1750 // The position travels as it does for a success. What the
1751 // handler committed before it failed, and the retry record
1752 // the final turn wrote, are unproven writes the core must
1753 // prove before a reader can reveal them; without a position
1754 // the alarm settled at once and opened no barrier (#715).
1755 // A handler that rejected settled its claim before its error
1756 // left, so the error carries the whole delta; one that
1757 // failed before or between turns had its record written by
1758 // the final turn, whose sample is the later one.
1759 let alarm = self.with_alarm_snapshot(&cell, |alarm| alarm);
1760 Ok((
1761 alarm,
1762 self.alarm_covered(&cell, alarm),
1763 final_write.max(js::failed_write_position(&error)),
1764 ))
1765 }
1766 }
1767 }
1768
1769 pub fn abort_alarm(&self, cell: &str, op: celld_logic::OpId) {
1770 let request = self
1771 .alarm_requests
1772 .lock()
1773 .expect("alarm registry poisoned")
1774 .aborting(cell, op);
1775 if let Some(request) = request {
1776 js::abort_request_for_shutdown(request);
1777 }
1778 }
1779
1780 /// Run `webSocketOpen`. The answer is the position the handler's writes
1781 /// reached, or the error carries it, so the caller can open their barrier.
1782 pub async fn ws_open(
1783 &self,
1784 cell: String,
1785 ws_id: u64,
1786 protocol: String,
1787 ) -> anyhow::Result<Option<u64>> {
1788 let (reply, receive) = tokio::sync::oneshot::channel();
1789 let job = CellJob::WsOpen {
1790 scope: cell.clone(),
1791 ws_id,
1792 facet_opening: None,
1793 protocol,
1794 reply,
1795 };
1796 self.cell_event(&cell, job, receive, "cell isolate dropped WebSocket open")
1797 .await
1798 }
1799
1800 /// Run `webSocketOpen` in the facet `scope` that dialed `ws_id`. A write
1801 /// of the handler is proved by the facet's next output, as for
1802 /// `facet_ws_closed`.
1803 pub async fn facet_ws_open(
1804 &self,
1805 scope: String,
1806 facet: &js::FacetSocket,
1807 ws_id: u64,
1808 protocol: String,
1809 ) -> anyhow::Result<()> {
1810 let (reply, receive) = tokio::sync::oneshot::channel();
1811 let job = CellJob::WsOpen {
1812 scope: scope.clone(),
1813 ws_id,
1814 facet_opening: Some(facet.opening),
1815 protocol,
1816 reply,
1817 };
1818 self.facet_event(
1819 &scope,
1820 facet,
1821 job,
1822 receive,
1823 "facet isolate dropped WebSocket open",
1824 )
1825 .await
1826 .map(|_| ())
1827 }
1828
1829 pub async fn rpc(
1830 &self,
1831 cell: String,
1832 name: Option<String>,
1833 method: String,
1834 args: js::RpcData,
1835 request_id: Option<js::RequestId>,
1836 ) -> anyhow::Result<js::RpcOutcome> {
1837 let (reply, receive) = tokio::sync::oneshot::channel();
1838 let job = CellJob::Rpc {
1839 request_id,
1840 scope: cell.clone(),
1841 name,
1842 method,
1843 args,
1844 reply,
1845 };
1846 self.cell_event(&cell, job, receive, "cell isolate dropped RPC result")
1847 .await
1848 }
1849
1850 pub async fn ws_message(
1851 &self,
1852 cell: String,
1853 ws_id: u64,
1854 data: js::WsIn,
1855 started: tokio::sync::oneshot::Sender<()>,
1856 ) -> anyhow::Result<js::WsDispatch> {
1857 let (reply, receive) = tokio::sync::oneshot::channel();
1858 let job = CellJob::WsMessage {
1859 scope: cell.clone(),
1860 ws_id,
1861 facet_opening: None,
1862 data,
1863 started: Some(started),
1864 reply,
1865 };
1866 self.cell_event(
1867 &cell,
1868 job,
1869 receive,
1870 "cell isolate dropped WebSocket message",
1871 )
1872 .await
1873 }
1874
1875 /// Run `webSocketClose`. The answer is the position the handler's writes
1876 /// reached, or the error carries it, so the caller can open their barrier.
1877 pub async fn ws_closed(
1878 &self,
1879 cell: String,
1880 ws_id: u64,
1881 code: u16,
1882 reason: String,
1883 was_clean: bool,
1884 ) -> anyhow::Result<Option<u64>> {
1885 let (reply, receive) = tokio::sync::oneshot::channel();
1886 let job = CellJob::WsClosed {
1887 scope: cell.clone(),
1888 ws_id,
1889 facet_opening: None,
1890 code,
1891 reason,
1892 was_clean,
1893 reply,
1894 };
1895 self.cell_event(&cell, job, receive, "cell isolate dropped WebSocket close")
1896 .await
1897 }
1898
1899 /// Run `webSocketMessage` in the facet `scope` that accepted `ws_id`.
1900 ///
1901 /// The frames leave only after the facet's stream proves every write the
1902 /// facet committed, as a facet's reply waits in `op_facet_fetch`. The
1903 /// answer carries no position: a facet's write positions count in the
1904 /// facet's stream, and the root cell's gate would read them as its own.
1905 pub async fn facet_ws_message(
1906 &self,
1907 scope: String,
1908 facet: &js::FacetSocket,
1909 ws_id: u64,
1910 data: js::WsIn,
1911 started: tokio::sync::oneshot::Sender<()>,
1912 ) -> anyhow::Result<js::WsDispatch> {
1913 let (reply, receive) = tokio::sync::oneshot::channel();
1914 let job = CellJob::WsMessage {
1915 scope: scope.clone(),
1916 ws_id,
1917 facet_opening: Some(facet.opening),
1918 data,
1919 started: Some(started),
1920 reply,
1921 };
1922 let dispatch = self
1923 .facet_event(
1924 &scope,
1925 facet,
1926 job,
1927 receive,
1928 "facet isolate dropped WebSocket message",
1929 )
1930 .await?;
1931 js::prove_facet_stream(facet.stream.clone(), facet.epoch).await?;
1932 Ok(js::WsDispatch {
1933 frames: dispatch.frames,
1934 write_position: None,
1935 observed_position: None,
1936 })
1937 }
1938
1939 /// Run `webSocketClose` in the facet `scope` that accepted `ws_id`. A
1940 /// write of the handler is proved by the facet's next output, which
1941 /// waits for the facet's whole stream.
1942 pub async fn facet_ws_closed(
1943 &self,
1944 scope: String,
1945 facet: &js::FacetSocket,
1946 ws_id: u64,
1947 code: u16,
1948 reason: String,
1949 was_clean: bool,
1950 ) -> anyhow::Result<()> {
1951 let (reply, receive) = tokio::sync::oneshot::channel();
1952 let job = CellJob::WsClosed {
1953 scope: scope.clone(),
1954 ws_id,
1955 facet_opening: Some(facet.opening),
1956 code,
1957 reason,
1958 was_clean,
1959 reply,
1960 };
1961 self.facet_event(
1962 &scope,
1963 facet,
1964 job,
1965 receive,
1966 "facet isolate dropped WebSocket close",
1967 )
1968 .await
1969 .map(|_| ())
1970 }
1971
1972 /// Start one event of a facet's socket and wait for its answer.
1973 ///
1974 /// A loaded Worker's isolate stays alive while its root's record holds
1975 /// it. Any other facet runs in the root's own isolate, which the root's
1976 /// residency pins. A facet that closed in either place is refused by the
1977 /// event's own first turn (`facet_socket_refusal`).
1978 async fn facet_event<T>(
1979 &self,
1980 scope: &str,
1981 facet: &js::FacetSocket,
1982 job: CellJob,
1983 receive: tokio::sync::oneshot::Receiver<anyhow::Result<T>>,
1984 dropped: &'static str,
1985 ) -> anyhow::Result<T> {
1986 let isolate = match js::recorded_facet_slot(&facet.root, facet.epoch, scope) {
1987 Some(slot) => slot.affiliate(),
1988 None => self.cell_isolate(&facet.root)?,
1989 };
1990 // No alarm reporter: a facet cannot set an alarm.
1991 run_cell_event(isolate, job, None, receive, dropped).await
1992 }
1993
1994 /// The isolate a published cell's events run in.
1995 fn cell_isolate(&self, cell: &str) -> anyhow::Result<crate::pool::Affiliation> {
1996 // The affiliation is taken UNDER the registry lock, while the
1997 // cell's Residency provably pins the slot, and it is held by the
1998 // driver for the event's entire async lifetime — including while
1999 // the event is suspended awaiting host I/O. Without it, a
2000 // suspended event holds only a bare Arc<Slot>: stop_cell() drops
2001 // the Residency, the pool reaps the "drained" isolate, and the
2002 // resumed event enters a freed worker and aborts the process
2003 // (denoland/celld#147).
2004 self.cells
2005 .lock()
2006 .expect("cell registry poisoned")
2007 .published
2008 .get(cell)
2009 .map(|handle| handle.residency.slot().affiliate())
2010 .ok_or_else(|| anyhow!("cell runtime is not published: {cell}"))
2011 }
2012
2013 /// Reserve one fetch against a published cell and return its isolate
2014 /// affiliation with the reservation. Returning either value alone would
2015 /// let a caller run work that the target did not admit or release the
2016 /// admission before the event's asynchronous lifetime ended.
2017 fn admit_cell_request(&self, cell: &str) -> anyhow::Result<Option<AdmittedCellRequest>> {
2018 let cells = self.cells.lock().expect("cell registry poisoned");
2019 let handle = cells
2020 .published
2021 .get(cell)
2022 .ok_or_else(|| anyhow!("cell runtime is not published: {cell}"))?;
2023 let Some(permit) = handle.requests.acquire() else {
2024 let in_flight = handle.requests.in_flight.load(Ordering::Acquire);
2025 if !handle.requests.saturated.swap(true, Ordering::AcqRel) {
2026 tracing::warn!(
2027 event = "cell_overload_refused",
2028 scope = %cell,
2029 node = %self.node,
2030 region = %self.region,
2031 in_flight,
2032 limit = handle.requests.limit,
2033 "refused work for a saturated cell"
2034 );
2035 }
2036 return Ok(None);
2037 };
2038 Ok(Some(AdmittedCellRequest {
2039 affiliation: handle.residency.slot().affiliate(),
2040 permit,
2041 }))
2042 }
2043
2044 /// Start one cell event and wait for its answer.
2045 ///
2046 /// The event is driven by its own task, so this future holds nothing
2047 /// while it waits: the isolate is taken and given back one turn at a
2048 /// time by `drive_cell`.
2049 async fn cell_event<T>(
2050 &self,
2051 cell: &str,
2052 job: CellJob,
2053 receive: tokio::sync::oneshot::Receiver<anyhow::Result<T>>,
2054 dropped: &'static str,
2055 ) -> anyhow::Result<T> {
2056 let isolate = self.cell_isolate(cell)?;
2057 run_cell_event(
2058 isolate,
2059 job,
2060 Some(self.alarm_reporter.clone()),
2061 receive,
2062 dropped,
2063 )
2064 .await
2065 }
2066}
2067
2068/// Drive one cell event in `isolate` on a task of its own, and wait for its
2069/// answer.
2070async fn run_cell_event<T>(
2071 isolate: crate::pool::Affiliation,
2072 job: CellJob,
2073 report: Option<AlarmReporter>,
2074 receive: tokio::sync::oneshot::Receiver<anyhow::Result<T>>,
2075 dropped: &'static str,
2076) -> anyhow::Result<T> {
2077 tokio::spawn(drive_cell(isolate, job, report, None));
2078 receive.await.context(dropped)?
2079}
2080
2081fn restored_alarm_from_persisted(
2082 _cell: &str,
2083 persisted: Option<(i64, i64, u32, u32)>,
2084 covered: impl FnOnce(i64) -> bool,
2085) -> Option<celld_logic::RestoredAlarm> {
2086 let at_ms = match persisted {
2087 Some((at_ms, ..)) => at_ms,
2088 None => -1,
2089 };
2090 if at_ms < 0 {
2091 return None;
2092 }
2093 // The restore hint grants no publication or retirement authority. The
2094 // opened SQLite connection installs the new writer identity first.
2095 Some(celld_logic::RestoredAlarm {
2096 at_ms,
2097 covered: covered(at_ms),
2098 })
2099}
2100
2101#[cfg(all(test, celld_internal_tests))]
2102pub(crate) fn restored_alarm_for_test(
2103 cell: &str,
2104 path: &std::path::Path,
2105 covered: bool,
2106) -> Option<celld_logic::RestoredAlarm> {
2107 let persisted = crate::storage::persisted_alarm(&path.to_string_lossy(), cell, None);
2108 restored_alarm_from_persisted(cell, persisted, |_| covered)
2109}
2110
2111/// The caller's trace context, when the ingress request carried one.
2112/// Malformed headers are ignored; nothing here is trusted for anything
2113/// but correlation and (under parentbased samplers, deliberately) the
2114/// sampling decision.
2115fn inbound_parent(job: &crate::WorkerJob) -> Option<crate::telemetry::ParentContext> {
2116 if !crate::telemetry::active() {
2117 return None;
2118 }
2119 let crate::WorkerJob::Fetch { headers, .. } = job else {
2120 return None;
2121 };
2122 headers
2123 .iter()
2124 .find(|(name, _)| name.eq_ignore_ascii_case("traceparent"))
2125 .and_then(|(_, value)| crate::telemetry::parse_traceparent(value))
2126}
2127
2128/// An op in flight, carrying the id of the promise it will resolve.
2129type PendingOp = std::pin::Pin<
2130 Box<dyn std::future::Future<Output = (u64, Result<asyncrt::OpOut, String>)> + Send>,
2131>;
2132
2133/// The ops one request is waiting on. Per request, not per isolate: that is
2134/// what deleting the pump means, and it is why no attribution table exists.
2135type Ops = futures_util::stream::FuturesUnordered<PendingOp>;
2136
2137fn adopt(ops: &mut Ops, started: Vec<js::Op>) {
2138 for (id, future) in started {
2139 ops.push(Box::pin(async move { (id, future.await) }));
2140 }
2141}
2142
2143/// Cancel native futures and remove their JavaScript resolvers together.
2144///
2145/// A failed handler can still own a gated reply, but none of its handler ops
2146/// can re-enter the isolate while that detached gate waiter finishes.
2147fn abort_ops(ops: &mut Ops, entry: &mut js::InFlight) {
2148 ops.clear();
2149 entry.abandon();
2150}
2151
2152/// Drive one stateless request to completion, one turn at a time.
2153///
2154/// The loop the pump used to run, owned by the request instead. Between turns
2155/// it holds no isolate — only its affiliation, which is memory rather than
2156/// CPU — so a handler awaiting I/O stops nothing else in that isolate.
2157/// This compatibility entry owns any cancellation lifetime that it creates.
2158/// A caller with an abort publisher must use
2159/// `RequestCancellationLifetime::drive_stateless_fetch` instead.
2160#[doc(hidden)]
2161pub fn drive(
2162 slot: Arc<crate::pool::Slot>,
2163 job: crate::WorkerJob,
2164 telemetry: Option<(Arc<str>, Arc<str>)>,
2165) -> impl std::future::Future<Output = ()> + Send + 'static {
2166 drive_affiliated(
2167 slot.affiliate(),
2168 StatelessWorkerJob::driver_owned(job),
2169 telemetry,
2170 )
2171}
2172
2173fn drive_affiliated(
2174 affiliation: crate::pool::Affiliation,
2175 job: StatelessWorkerJob,
2176 telemetry: Option<(Arc<str>, Arc<str>)>,
2177) -> impl std::future::Future<Output = ()> + Send + 'static {
2178 drive_affiliated_with_budget(affiliation, job, telemetry, js::handler_budget())
2179}
2180
2181fn drive_affiliated_with_budget(
2182 affiliation: crate::pool::Affiliation,
2183 job: StatelessWorkerJob,
2184 telemetry: Option<(Arc<str>, Arc<str>)>,
2185 budget: Duration,
2186) -> impl std::future::Future<Output = ()> + Send + 'static {
2187 let StatelessWorkerJob { job, cancellation } = job;
2188 let driving = drive_affiliated_inner(affiliation, job, telemetry, budget);
2189 drive_with_request_cancellation(driving, cancellation)
2190}
2191
2192#[cfg(celld_internal_tests)]
2193#[doc(hidden)]
2194pub fn drive_affiliated_with_budget_for_test(
2195 affiliation: crate::pool::Affiliation,
2196 job: crate::WorkerJob,
2197 telemetry: Option<(Arc<str>, Arc<str>)>,
2198 budget: Duration,
2199) -> impl std::future::Future<Output = ()> + Send + 'static {
2200 drive_affiliated_with_budget(
2201 affiliation,
2202 StatelessWorkerJob::driver_owned(job),
2203 telemetry,
2204 budget,
2205 )
2206}
2207
2208async fn drive_affiliated_inner(
2209 affiliation: crate::pool::Affiliation,
2210 job: crate::WorkerJob,
2211 telemetry: Option<(Arc<str>, Arc<str>)>,
2212 budget: Duration,
2213) {
2214 let slot = affiliation.slot().clone();
2215 // One sampling decision per request, shared by the SERVER span and
2216 // the turn context the handler's console/fetch children inherit. A
2217 // caller's traceparent is honored per the spec: ids adopted either
2218 // way, its sampled flag deciding only under a parentbased sampler.
2219 let remote = telemetry.as_ref().and_then(|_| inbound_parent(&job));
2220 let trace = telemetry
2221 .as_ref()
2222 .and_then(|_| crate::telemetry::start_trace_with_parent(remote.as_ref()));
2223 let recording = trace.and_then(crate::telemetry::TraceContext::recording_ids);
2224 let mut timing = telemetry.map(|(node, region)| {
2225 StatelessTiming::start(&job, slot.id, node, region, recording, remote)
2226 });
2227 // Admission created `affiliation` before returning the isolate. It stays
2228 // here for the request's whole life, so maintenance cannot free the heap
2229 // between placement and this first turn or while a promise is suspended.
2230 let _affiliation = affiliation;
2231 drive_worker(
2232 &slot,
2233 job,
2234 trace,
2235 budget,
2236 |entry| {
2237 if let Some(timing) = &mut timing {
2238 timing.answered(entry);
2239 }
2240 },
2241 |_| {},
2242 )
2243 .await;
2244}
2245
2246// Both worker placements use the same execution loop. Keep observation at
2247// each turn separate from completion: response timing excludes waitUntil,
2248// while the worker-on-cell span includes it. Neither observer owns cleanup.
2249async fn drive_worker(
2250 slot: &crate::pool::Slot,
2251 job: crate::WorkerJob,
2252 trace: Option<crate::telemetry::TraceContext>,
2253 budget: Duration,
2254 mut after_turn: impl FnMut(&js::InFlight),
2255 on_finish: impl FnOnce(&js::InFlight),
2256) {
2257 let mut ops = Ops::new();
2258
2259 let (begun, started) = slot.turn(|worker| worker.turn_begin(job, trace)).await;
2260 // Nothing is in flight; the reply already carries the error.
2261 let Some(mut entry) = begun else {
2262 drop(started);
2263 return;
2264 };
2265 if entry.keeps_native_ops() {
2266 adopt(&mut ops, started);
2267 } else {
2268 drop(started);
2269 abort_ops(&mut ops, &mut entry);
2270 }
2271 after_turn(&entry);
2272
2273 while !entry.finished() {
2274 let started = match wake_with_cross_entry_gate(&mut ops, &mut entry, budget).await {
2275 Wake::Op(op, result) => {
2276 slot.turn(|worker| worker.turn_deliver(&mut entry, op, result))
2277 .await
2278 }
2279 Wake::GatedReply(completion) => {
2280 entry.finish_gated_reply(completion);
2281 Vec::new()
2282 }
2283 Wake::CancelGatedReply => {
2284 entry.cancel_gated_reply();
2285 Vec::new()
2286 }
2287 Wake::CrossEntryGateChanged => {
2288 entry.finish_cross_entry_gates();
2289 Vec::new()
2290 }
2291 Wake::Cancelled { shutdown } => {
2292 let started = slot
2293 .turn(|worker| {
2294 if shutdown {
2295 worker.turn_cancel_for_shutdown(&mut entry)
2296 } else {
2297 worker.turn_cancel(&mut entry)
2298 }
2299 })
2300 .await;
2301 entry.cancel_gated_reply();
2302 started
2303 }
2304 Wake::Expired => {
2305 entry.time_out(budget);
2306 Vec::new()
2307 }
2308 Wake::Idle => {
2309 entry.stuck();
2310 Vec::new()
2311 }
2312 Wake::PendingEventIdle => {
2313 slot.turn(|worker| worker.turn_cancel_pending_events(&mut entry))
2314 .await
2315 }
2316 Wake::Poll => slot.turn(|worker| worker.turn_poll(&mut entry)).await,
2317 };
2318 if entry.keeps_native_ops() {
2319 adopt(&mut ops, started);
2320 } else {
2321 drop(started);
2322 abort_ops(&mut ops, &mut entry);
2323 }
2324 after_turn(&entry);
2325 }
2326
2327 on_finish(&entry);
2328 // Dropping `ops` aborts whatever is still pending, which is what a region
2329 // does on every exit path; their resolvers have to go with them.
2330 entry.finish_tail_report();
2331 entry.abandon();
2332}
2333
2334/// What next moves a suspended request.
2335enum Wake {
2336 /// One of its own ops finished.
2337 Op(u64, Result<asyncrt::OpOut, String>),
2338 /// The detached output-gate waiter sent, or abandoned, the final reply.
2339 GatedReply(Result<js::GatedReplyCompletion, tokio::sync::oneshot::error::RecvError>),
2340 /// The handler has answered, so cancel its detached reply gate without
2341 /// entering JavaScript again.
2342 CancelGatedReply,
2343 /// A cross-entry claim changed, or subscribing closed a retirement gap.
2344 CrossEntryGateChanged,
2345 /// Its client hung up, or shutdown forced the complete event to retire.
2346 Cancelled { shutdown: bool },
2347 /// It ran past the handler budget without answering.
2348 Expired,
2349 /// Nothing outstanding could ever move it.
2350 Idle,
2351 /// A nested Worker entrypoint is pending without native work. Reject that
2352 /// call inside JavaScript so the enclosing event can catch the failure.
2353 PendingEventIdle,
2354 /// Nothing of its own is outstanding, but another event of the same cell
2355 /// still could settle it. Look in and see.
2356 Poll,
2357}
2358
2359fn take_cancellation_wake(request_id: Option<js::RequestId>) -> Option<Wake> {
2360 js::take_request_cancellation(request_id).then(|| Wake::Cancelled {
2361 shutdown: js::take_shutdown_cancellation(request_id),
2362 })
2363}
2364
2365/// Wait for whichever comes first, holding no isolate.
2366///
2367/// This is the whole of what a request does between turns, and it is
2368/// deliberately the only place that waits: everything else in `drive` either
2369/// holds the isolate or is arithmetic.
2370async fn wake_with_cross_entry_gate(
2371 ops: &mut Ops,
2372 entry: &mut js::InFlight,
2373 budget: Duration,
2374) -> Wake {
2375 let wait = entry.prepare_cross_entry_gate_wait();
2376 match wait
2377 .wait(wake(ops, entry, budget), |wake| matches!(wake, Wake::Idle))
2378 .await
2379 {
2380 js::input_gate_lifecycle::WaitOutcome::StateChanged => Wake::CrossEntryGateChanged,
2381 js::input_gate_lifecycle::WaitOutcome::Ordinary(wake) => wake,
2382 }
2383}
2384
2385async fn wake(ops: &mut Ops, entry: &mut js::InFlight, budget: Duration) -> Wake {
2386 loop {
2387 // An op this event enqueued from inside another event's turn reaches
2388 // this driver here rather than through `adopt`, because the turn that
2389 // took it belongs to another entry. See `js::adopt`.
2390 adopt(ops, entry.take_handed_ops());
2391 // A WorkerEntrypoint call is its own PendingEvent. When no referenced
2392 // native operation can move it, reject that call inside JavaScript.
2393 // An unreferenced signal listener cannot make progress and must not
2394 // hide a hung call. This check precedes the answered branch because
2395 // the enclosing handler can keep the call alive through waitUntil
2396 // after its response.
2397 if !entry.has_refed_ops() && entry.has_pending_events() {
2398 return Wake::PendingEventIdle;
2399 }
2400 let Some(left) = entry.remaining(budget) else {
2401 // The handler settled, so neither its reply gate nor waitUntil
2402 // work is charged to the handler budget. Poll both because the
2403 // background can progress while the gate owns the reply.
2404 let request_id = entry.request_id();
2405 let (gated_reply, context) = entry.gated_reply_and_io_context();
2406 if let Some(gated_reply) = gated_reply {
2407 let Some(request_id) = request_id else {
2408 let next = if ops.is_empty() {
2409 asyncrt::select_biased! {
2410 "a completed gated reply wins a tie with an op another turn hands over";
2411 completion = gated_reply => Some(Wake::GatedReply(completion)),
2412 _ = context.handed_ready() => None,
2413 }
2414 } else {
2415 asyncrt::select_biased! {
2416 "a completed gated reply wins a tie with another operation wake";
2417 completion = gated_reply => Some(Wake::GatedReply(completion)),
2418 result = ops.next() => result.map(|(op, result)| Wake::Op(op, result)),
2419 _ = context.handed_ready() => None,
2420 }
2421 };
2422 match next {
2423 Some(wake) => return wake,
2424 // A hand-off, or an exhausted stream after its final
2425 // completion; take the mailbox before waiting again.
2426 None => continue,
2427 }
2428 };
2429 // The domain select is declaration-order biased. A reply that
2430 // completed wins over an op, a mailbox hand-off wins over a
2431 // cancellation tick, and cancellation is sampled immediately
2432 // after a mailbox or timer wake so continuous hand-offs cannot
2433 // starve it.
2434 let next = if ops.is_empty() {
2435 asyncrt::select_biased! {
2436 "a completed gated reply wins a tie with another request wake";
2437 completion = gated_reply => Some(Wake::GatedReply(completion)),
2438 _ = context.handed_ready() => None,
2439 _ = asyncrt::sleep(CANCELLATION_TICK) => None,
2440 }
2441 } else {
2442 asyncrt::select_biased! {
2443 "a completed gated reply wins a tie with another request wake";
2444 completion = gated_reply => Some(Wake::GatedReply(completion)),
2445 next = async {
2446 asyncrt::select_biased! {
2447 "an operation result wins a tie with another request wake";
2448 result = ops.next() => Some(match result {
2449 Some((op, result)) => Wake::Op(op, result),
2450 None => Wake::Idle,
2451 }),
2452 _ = context.handed_ready() => None,
2453 _ = asyncrt::sleep(CANCELLATION_TICK) => None,
2454 }
2455 } => next,
2456 }
2457 };
2458 if let Some(next) = next {
2459 return next;
2460 }
2461 if let Some(cancelled) = take_cancellation_wake(Some(request_id)) {
2462 return if matches!(cancelled, Wake::Cancelled { shutdown: true }) {
2463 cancelled
2464 } else {
2465 Wake::CancelGatedReply
2466 };
2467 }
2468 continue;
2469 }
2470 // The reply arrived, so only waitUntil work remains. A client
2471 // disconnect no longer matters, but a lifecycle cancellation
2472 // must still retire the background work before the runtime stops.
2473 let Some(request_id) = request_id else {
2474 let context = entry.io_context();
2475 let next = asyncrt::select_biased! {
2476 "an operation result wins a tie with an op another turn hands over";
2477 result = ops.next() => Some(result),
2478 _ = context.handed_ready() => None,
2479 };
2480 match next {
2481 Some(Some((op, result))) => return Wake::Op(op, result),
2482 Some(None) => return Wake::Idle,
2483 // Handed over; the next pass takes it.
2484 None => continue,
2485 }
2486 };
2487 let next = if ops.is_empty() {
2488 asyncrt::sleep(CANCELLATION_TICK).await;
2489 None
2490 } else {
2491 asyncrt::select_biased! {
2492 "completed waitUntil work wins a tie with periodic lifecycle cancellation sampling";
2493 result = ops.next() => Some(match result {
2494 Some((op, result)) => Wake::Op(op, result),
2495 None => Wake::Idle,
2496 }),
2497 _ = asyncrt::sleep(CANCELLATION_TICK) => None,
2498 }
2499 };
2500 if let Some(next) = next {
2501 return next;
2502 }
2503 if let Some(cancelled) = take_cancellation_wake(Some(request_id)) {
2504 if matches!(cancelled, Wake::Cancelled { shutdown: true }) {
2505 return cancelled;
2506 }
2507 }
2508 continue;
2509 };
2510 // A disconnect is raised on another thread with nothing to wake this
2511 // one, so the wait is capped and the flag re-read — as the blocking
2512 // run loop capped its own. The difference is that reading it costs no
2513 // isolate, so a request enters V8 only once the client has really gone.
2514 // An unrefed op can wake a handler that awaits it, but it cannot be
2515 // the reason this driver stops polling the isolate. A retained signal
2516 // listener otherwise hides the empty-op path that lets a loopback
2517 // entry make progress, and both events wait on each other forever.
2518 let only_unrefed = !ops.is_empty() && !entry.has_refed_ops();
2519 let capped = if entry.cancellable() || only_unrefed {
2520 left.min(CANCELLATION_TICK)
2521 } else {
2522 left
2523 };
2524 // Nothing of this entry's own is outstanding, so there is no future
2525 // to wait on — only the chance that some *other* entry in this
2526 // isolate has settled it since the last look. That is an ordinary
2527 // thing rather than a stall: a cell awaits the alarm it armed, and a
2528 // Worker awaits a Durable Object it dispatched to. Both used to
2529 // resolve inside the caller's own run loop, so there was nothing to
2530 // wait for; both are separate entries now.
2531 //
2532 // So "waiting on nothing" is a verdict the budget reaches, not one
2533 // an empty op set proves.
2534 let context = entry.io_context();
2535 if ops.is_empty() {
2536 if left.is_zero() {
2537 return Wake::Idle;
2538 }
2539 // The handed wake belongs on this path too. This entry holds no op
2540 // of its own, so without it a handed op waits out the whole
2541 // cancellation tick before the next pass can take it — the delay
2542 // this branch has no reason to add.
2543 asyncrt::select_biased! {
2544 "an op another turn hands over wins a tie with the cancellation tick";
2545 _ = context.handed_ready() => {},
2546 _ = tokio::time::sleep(capped.min(CANCELLATION_TICK)) => {},
2547 }
2548 // Re-read the flag on this path too. A request with nothing
2549 // outstanding can still have its client hang up, and only the
2550 // branch below used to look.
2551 if let Some(cancelled) = take_cancellation_wake(entry.request_id()) {
2552 return cancelled;
2553 }
2554 return Wake::Poll;
2555 }
2556 let next = tokio::time::timeout(capped, async {
2557 asyncrt::select_biased! {
2558 "an operation result wins a tie with an op another turn hands over";
2559 result = ops.next() => Some(result),
2560 _ = context.handed_ready() => None,
2561 }
2562 })
2563 .await;
2564 match next {
2565 Ok(Some(Some((op, result)))) => return Wake::Op(op, result),
2566 Ok(Some(None)) => return Wake::Idle,
2567 // Another turn handed this event an op. The next pass takes it.
2568 Ok(None) => continue,
2569 Err(_) => {
2570 if let Some(cancelled) = take_cancellation_wake(entry.request_id()) {
2571 return cancelled;
2572 }
2573 if capped == left {
2574 return Wake::Expired;
2575 }
2576 if only_unrefed {
2577 return Wake::Poll;
2578 }
2579 continue;
2580 }
2581 }
2582 }
2583}
2584
2585/// One stateless request's canonical timing event.
2586///
2587/// The phases still mean what they always did, but what they measure has
2588/// moved: `queue_wait_us` was the wait for a free worker thread and is now
2589/// the wait for admission and the isolate's async gate, and `execution_us`
2590/// spans every turn the request took rather than one uninterrupted run.
2591struct StatelessTiming {
2592 queued_at: Instant,
2593 request_id: Option<js::RequestId>,
2594 node: Arc<str>,
2595 region: Arc<str>,
2596 isolate: usize,
2597 admitted: Instant,
2598 emitted: bool,
2599 /// Sampled at creation: `None` is off or unsampled, and nothing more
2600 /// is ever built for this request.
2601 trace: Option<crate::telemetry::TraceIds>,
2602 /// The caller's span, when the request arrived with a traceparent.
2603 remote_parent: Option<crate::telemetry::ParentContext>,
2604 /// Why the handler failed, read from the entry when it was answered.
2605 failure: Option<String>,
2606 span_name: &'static str,
2607 span_kind: u8,
2608}
2609
2610impl StatelessTiming {
2611 fn start(
2612 job: &crate::WorkerJob,
2613 isolate: usize,
2614 node: Arc<str>,
2615 region: Arc<str>,
2616 trace: Option<crate::telemetry::TraceIds>,
2617 remote_parent: Option<crate::telemetry::ParentContext>,
2618 ) -> Self {
2619 let (queued_at, request_id, span_name, span_kind) = match job {
2620 crate::WorkerJob::Fetch {
2621 queued_at,
2622 request_id,
2623 ..
2624 } => (
2625 *queued_at,
2626 *request_id,
2627 "celld.fetch",
2628 crate::telemetry::KIND_SERVER,
2629 ),
2630 crate::WorkerJob::Queue { queued_at, .. } => (
2631 *queued_at,
2632 None,
2633 "celld.queue",
2634 crate::telemetry::KIND_CONSUMER,
2635 ),
2636 crate::WorkerJob::Rpc { .. } => (
2637 Instant::now(),
2638 None,
2639 "celld.fetch",
2640 crate::telemetry::KIND_SERVER,
2641 ),
2642 };
2643 StatelessTiming {
2644 queued_at,
2645 request_id,
2646 node,
2647 region,
2648 isolate,
2649 admitted: Instant::now(),
2650 emitted: false,
2651 trace,
2652 remote_parent,
2653 failure: None,
2654 span_name,
2655 span_kind,
2656 }
2657 }
2658
2659 /// Emit once, the first time the client has been answered. `waitUntil`
2660 /// work continues afterwards and is not part of the response's timing.
2661 fn answered(&mut self, entry: &js::InFlight) {
2662 if self.emitted || !entry.answered() {
2663 return;
2664 }
2665 self.emitted = true;
2666 self.failure = entry.failure().map(str::to_string);
2667 self.emit();
2668 }
2669
2670 fn emit(&self) {
2671 if let Some(ids) = self.trace {
2672 let total_us = self.queued_at.elapsed().as_micros() as i64;
2673 let mut span = crate::telemetry::Span::new(ids, self.span_name, self.span_kind);
2674 span.start_unix_us = crate::telemetry::now_unix_us() - total_us;
2675 span.duration_us = total_us;
2676 span.ok = self.failure.is_none();
2677 span.error = self.failure.clone();
2678 span.request_id = self.request_id.map(js::request_id_string);
2679 span.isolate = Some(self.isolate as u64);
2680 span.parent_span_id = self.remote_parent.map(|parent| parent.span_id);
2681 span.parent_remote = self.remote_parent.map(|_| true);
2682 span.queue_wait_us =
2683 Some(self.admitted.duration_since(self.queued_at).as_micros() as i64);
2684 crate::telemetry::record(span);
2685 }
2686 // An info!-per-request costs real throughput on the hot path, so the
2687 // `enabled!` guard skips the elapsed math and the formatting when the
2688 // target is off. The lab turns it on with RUST_LOG=info,timing=debug.
2689 let Some(request_id) = self
2690 .request_id
2691 .filter(|_| tracing::enabled!(target: "timing", tracing::Level::DEBUG))
2692 else {
2693 return;
2694 };
2695 tracing::debug!(
2696 target: "timing",
2697 event = "worker_fetch_timing",
2698 outcome = "completed",
2699 request_id = %js::request_id_string(request_id),
2700 node = %self.node,
2701 region = %self.region,
2702 runtime_version = env!("CARGO_PKG_VERSION"),
2703 total_us = self.queued_at.elapsed().as_micros() as u64,
2704 queue_wait_us = self.admitted.duration_since(self.queued_at).as_micros() as u64,
2705 execution_us = self.admitted.elapsed().as_micros() as u64,
2706 isolate = self.isolate,
2707 "stateless Worker fetch completed"
2708 );
2709 }
2710}
2711
2712/// Initialise V8, at most once.
2713///
2714/// **Must run before any thread that will enter an isolate is created.**
2715/// V8 protects its pointer tables with a memory protection key, and the
2716/// `PKRU` register granting access to that key is per-thread and inherited
2717/// at thread creation. A thread created before this runs never receives
2718/// access, so its first read of a dispatch table traps with `SEGV_PKUERR`
2719/// on any CPU that supports protection keys.
2720pub fn init_v8() {
2721 js::Engine::init();
2722}
2723
2724impl StatelessRuntime {
2725 #[doc(hidden)]
2726 pub fn start(
2727 config: Arc<WorkerConfig>,
2728 node: Arc<str>,
2729 region: Arc<str>,
2730 ) -> anyhow::Result<Self> {
2731 let build = {
2732 let config = config.clone();
2733 move || Worker::load_config(config.clone())
2734 };
2735 let isolates = Arc::new(crate::pool::Pool::new(
2736 pool_limits(),
2737 admission_wait(),
2738 Box::new(build),
2739 ));
2740 // Eagerly, so a script that does not load fails here rather than on
2741 // every request, and so the first request does not pay for compiling
2742 // it. Growth past this one stays lazy.
2743 isolates.warm().context("stateless Worker failed to load")?;
2744 // Give isolates back when the burst that grew them is over. Without
2745 // this the pool only grows, and every heap a burst created is held
2746 // for the life of the process. Long relative to a request, because
2747 // retiring is not urgent and a short period would thrash a pool that
2748 // is about to be busy again.
2749 if let Ok(handle) = tokio::runtime::Handle::try_current() {
2750 // Weak, so this loop cannot keep a superseded generation's pool
2751 // alive: it ends when the pool is dropped.
2752 let reaping = Arc::downgrade(&isolates);
2753 let reclaim = isolates.reclaim_bell();
2754 handle.spawn(async move {
2755 // `interval` fires its first tick immediately, which
2756 // reaped the isolate `warm` had just built and handed the
2757 // first request the compile cost warming exists to avoid.
2758 let mut tick = tokio::time::interval_at(
2759 tokio::time::Instant::now() + REAP_INTERVAL,
2760 REAP_INTERVAL,
2761 );
2762 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
2763 loop {
2764 let reap = crate::asyncrt::select_biased! {
2765 "the paced reap also frees, so it wins a tie with the reclaim bell";
2766 _ = tick.tick() => true,
2767 _ = reclaim.notified() => false,
2768 };
2769 let Some(mut pool) = reaping.upgrade() else {
2770 return;
2771 };
2772 if reap {
2773 pool.reap();
2774 continue;
2775 }
2776 // A condemned isolate is freed as soon as it drains, not
2777 // at the next tick. Admission holds the guard only while
2778 // it places one request, so a short retry gets it.
2779 while !pool.free_drained() {
2780 drop(pool);
2781 crate::asyncrt::sleep(RECLAIM_RETRY).await;
2782 let Some(again) = reaping.upgrade() else {
2783 return;
2784 };
2785 pool = again;
2786 }
2787 }
2788 });
2789 }
2790 Ok(Self {
2791 isolates,
2792 node,
2793 region,
2794 })
2795 }
2796
2797 /// Admit and drive one stateless event. A verb supplies only its job and
2798 /// result type, so admission, shedding, pressure, and task failure cannot
2799 /// drift between fetch, RPC, and queue dispatch.
2800 async fn dispatch<T: Send + 'static>(
2801 &self,
2802 verb: StatelessVerb,
2803 make_job: impl FnOnce(tokio::sync::oneshot::Sender<anyhow::Result<T>>) -> crate::WorkerJob,
2804 ) -> anyhow::Result<T> {
2805 let shedding = crate::ownership_store::node_is_shedding();
2806 self.dispatch_stateless(verb, shedding, move |reply| {
2807 StatelessWorkerJob::driver_owned(make_job(reply))
2808 })
2809 .await
2810 }
2811
2812 #[doc(hidden)]
2813 pub async fn dispatch_with_shedding<T: Send + 'static>(
2814 &self,
2815 verb: StatelessVerb,
2816 shedding: bool,
2817 make_job: impl FnOnce(tokio::sync::oneshot::Sender<anyhow::Result<T>>) -> crate::WorkerJob,
2818 ) -> anyhow::Result<T> {
2819 self.dispatch_stateless(verb, shedding, move |reply| {
2820 StatelessWorkerJob::driver_owned(make_job(reply))
2821 })
2822 .await
2823 }
2824
2825 async fn dispatch_stateless<T: Send + 'static>(
2826 &self,
2827 verb: StatelessVerb,
2828 shedding: bool,
2829 make_job: impl FnOnce(tokio::sync::oneshot::Sender<anyhow::Result<T>>) -> StatelessWorkerJob,
2830 ) -> anyhow::Result<T> {
2831 let affiliation = self.isolates.admit_or_wait(shedding).await?;
2832 let (reply, receive) = tokio::sync::oneshot::channel();
2833 let job = make_job(reply);
2834 // Spawned rather than awaited inline, because the response and the
2835 // event are not the same lifetime: `waitUntil` work outlives the
2836 // answer, and the driver keeps turning until it settles.
2837 let driving = tokio::spawn(drive_affiliated(
2838 affiliation,
2839 job,
2840 Some((self.node.clone(), self.region.clone())),
2841 ));
2842 match receive.await {
2843 Ok(result) => result,
2844 // The driver dropped the reply without sending. Joining it here —
2845 // and only here — turns a bare "channel closed" into the panic
2846 // that actually caused it, at no cost on the path that works.
2847 Err(_) => match driving.await {
2848 Err(error) => Err(verb.task_died(error)),
2849 Ok(()) => Err(verb.dropped_result()),
2850 },
2851 }
2852 }
2853
2854 /// Serve one stateless request, entering an isolate once per turn.
2855 ///
2856 /// The request drives itself: it is admitted and placed, runs its first
2857 /// turn, then awaits its *own* ops with no isolate held, re-entering for
2858 /// each completion. Nothing multiplexes and nothing demultiplexes, which
2859 /// is what deleting the pump buys.
2860 #[doc(hidden)]
2861 pub fn fetch(
2862 &self,
2863 url: String,
2864 method: String,
2865 body: js::RequestBody,
2866 headers: Vec<(String, String)>,
2867 cancellation: Option<Arc<RequestCancellationLifetime>>,
2868 ) -> impl std::future::Future<Output = anyhow::Result<HttpResponse>> + Send + 'static {
2869 self.fetch_target(None, url, method, body, headers, cancellation)
2870 }
2871
2872 /// Serve one default or named stateless Worker entrypoint.
2873 fn fetch_target(
2874 &self,
2875 entrypoint: Option<crate::WorkerFetchEntrypoint>,
2876 url: String,
2877 method: String,
2878 body: js::RequestBody,
2879 headers: Vec<(String, String)>,
2880 cancellation: Option<Arc<RequestCancellationLifetime>>,
2881 ) -> impl std::future::Future<Output = anyhow::Result<HttpResponse>> + Send + 'static {
2882 let runtime = self.clone();
2883 let make_job =
2884 stateless_fetch_job_factory(entrypoint, url, method, body, headers, cancellation);
2885 async move {
2886 let shedding = crate::ownership_store::node_is_shedding();
2887 runtime
2888 .dispatch_stateless(StatelessVerb::Fetch, shedding, make_job)
2889 .await
2890 }
2891 }
2892
2893 /// An entrypoint RPC, on the isolate pool like fetch.
2894 ///
2895 /// It used to go to the worker threads, because the old RPC dispatcher
2896 /// blocked while the handler awaited — and a
2897 /// blocking call cannot hold a pool slot without parking a tokio worker
2898 /// on V8. Turning it into `begin`/`drive` removes the blocking, and with
2899 /// it the last reason `WorkerPool` existed.
2900 async fn rpc(
2901 &self,
2902 entrypoint: String,
2903 props: Vec<u8>,
2904 operation: crate::WorkerRpcOperation,
2905 ) -> anyhow::Result<Vec<u8>> {
2906 self.dispatch(StatelessVerb::Rpc, move |reply| crate::WorkerJob::Rpc {
2907 entrypoint,
2908 operation,
2909 props,
2910 invocation_limits: None,
2911 reply,
2912 })
2913 .await
2914 }
2915
2916 /// Dispatch one leased queue batch through the stateless isolate pool.
2917 #[doc(hidden)]
2918 pub async fn queue(&self, batch: js::QueueBatch) -> anyhow::Result<js::QueueDispatchResult> {
2919 let queued_at = Instant::now();
2920 self.dispatch(StatelessVerb::Queue, move |reply| crate::WorkerJob::Queue {
2921 queued_at,
2922 batch,
2923 reply,
2924 })
2925 .await
2926 }
2927}
2928
2929struct CellIsolateStartupTiming {
2930 started: Instant,
2931 scope: String,
2932 node: Arc<str>,
2933 region: Arc<str>,
2934 epoch: u64,
2935 fresh: bool,
2936}
2937
2938impl CellIsolateStartupTiming {
2939 fn emit(&self, outcome: &str, failure_phase: &str) -> u64 {
2940 let total_us = self.started.elapsed().as_micros() as u64;
2941 if let Some(ids) =
2942 crate::telemetry::start_trace().and_then(crate::telemetry::TraceContext::recording_ids)
2943 {
2944 let mut span = crate::telemetry::Span::new(
2945 ids,
2946 "celld.cell_startup",
2947 crate::telemetry::KIND_INTERNAL,
2948 );
2949 span.start_unix_us = crate::telemetry::now_unix_us() - total_us as i64;
2950 span.duration_us = total_us as i64;
2951 span.ok = outcome == "ready";
2952 span.error = (!span.ok).then(|| failure_phase.to_string());
2953 span.cell = Some(self.scope.clone());
2954 span.epoch = Some(self.epoch);
2955 crate::telemetry::record(span);
2956 }
2957 tracing::info!(
2958 event = "cell_isolate_startup_timing",
2959 outcome,
2960 failure_phase,
2961 scope = %self.scope,
2962 node = %self.node,
2963 region = %self.region,
2964 runtime_version = env!("CARGO_PKG_VERSION"),
2965 epoch = self.epoch,
2966 fresh = self.fresh,
2967 total_us,
2968 "cell isolate startup completed"
2969 );
2970 total_us
2971 }
2972}
2973
2974/// Build one isolate for a Worker script's cells.
2975///
2976/// No cells yet: `Worker::own_cell` opens each cell's storage as it is
2977/// placed here, because this isolate outlives any of them.
2978fn load_cell_isolate(config: Arc<WorkerConfig>) -> anyhow::Result<Worker> {
2979 #[cfg(debug_assertions)]
2980 if let Ok(barrier) = std::env::var("CELLD_TEST_CELL_STARTUP_BARRIER") {
2981 while !Path::new(&barrier).exists() {
2982 std::thread::sleep(Duration::from_millis(10));
2983 }
2984 }
2985 #[cfg(debug_assertions)]
2986 if std::env::var("CELLD_TEST_CELL_STARTUP_FAILURE").as_deref() == Ok("1") {
2987 return Err(anyhow!("injected cell isolate startup failure"));
2988 }
2989 Worker::load_config(config).map_err(|error| error.context("cell isolate load failed"))
2990}
2991
2992/// Drive the Worker entry in a cell's isolate.
2993///
2994/// The stateless `drive` loop, with the isolate named rather than admitted:
2995/// this request must run *here*, because the cell it will route to lives here
2996/// and arriving in a warm isolate is the point.
2997async fn drive_worker_on_cell(affiliation: crate::pool::Affiliation, job: crate::WorkerJob) {
2998 // Held to the end of this function: the request's claim on the isolate
2999 // outlives every suspension, so the pool cannot free the worker under
3000 // a parked event (denoland/celld#147).
3001 let slot = affiliation.slot().clone();
3002 let remote = inbound_parent(&job);
3003 let trace = crate::telemetry::start_trace_with_parent(remote.as_ref());
3004 let recording = trace.and_then(crate::telemetry::TraceContext::recording_ids);
3005 let span_started = recording.map(|_| (Instant::now(), crate::telemetry::now_unix_us()));
3006 drive_worker(
3007 &slot,
3008 job,
3009 trace,
3010 js::handler_budget(),
3011 |_| {},
3012 |entry| {
3013 if let (Some(ids), Some((started, start_unix))) = (recording, span_started) {
3014 let mut span =
3015 crate::telemetry::Span::new(ids, "celld.fetch", crate::telemetry::KIND_SERVER);
3016 span.start_unix_us = start_unix;
3017 span.duration_us = started.elapsed().as_micros() as i64;
3018 span.ok = entry.finished() && entry.failure().is_none();
3019 span.error = entry.failure().map(str::to_string);
3020 span.parent_span_id = remote.map(|parent| parent.span_id);
3021 span.parent_remote = remote.map(|_| true);
3022 crate::telemetry::record(span);
3023 }
3024 },
3025 )
3026 .await;
3027}
3028
3029/// Report a turn's alarm moves to the host.
3030///
3031/// The host otherwise hears about a cell's alarm only when the request
3032/// finishes, because `ActivityGuard` reports it on drop. That is too late
3033/// for a handler that arms an alarm and then *awaits* it: the timer would
3034/// not be scheduled until the request ended, and the request cannot end
3035/// until the alarm fires. The blocking run loop hid this by polling
3036/// `get_alarm` between turns and firing a due alarm inline; with events as
3037/// entries, the host has to be told as soon as the arming turn returns.
3038fn report_alarm_moves(
3039 report: &Option<AlarmReporter>,
3040 moves: Vec<(String, celld_logic::wake::AlarmSnapshot)>,
3041) {
3042 if let Some(report) = report {
3043 for (scope, at_ms) in moves {
3044 report(scope, at_ms);
3045 }
3046 }
3047}
3048
3049/// Drive one cell event to completion, one turn at a time.
3050///
3051/// The same loop as `drive`, and deliberately so: what makes a cell event
3052/// different is which realm its turns enter and that it waits for the input
3053/// gate first — not how it is pumped. Between turns it holds no isolate, so
3054/// a handler awaiting I/O stops neither its own cell's next event nor any
3055/// other cell sharing the isolate.
3056#[doc(hidden)]
3057pub async fn drive_cell(
3058 affiliation: crate::pool::Affiliation,
3059 job: CellJob,
3060 report: Option<AlarmReporter>,
3061 parent: Option<crate::telemetry::TraceContext>,
3062) {
3063 let cancellation = job
3064 .request_id()
3065 .map(RequestCancellationLifetime::from_request_id);
3066 #[cfg(celld_internal_tests)]
3067 let _ = drive_cell_inner(
3068 affiliation,
3069 job,
3070 report,
3071 parent,
3072 js::handler_budget(),
3073 cancellation,
3074 DriveCellTestObservers::default(),
3075 )
3076 .await;
3077 #[cfg(not(celld_internal_tests))]
3078 let _ = drive_cell_inner(
3079 affiliation,
3080 job,
3081 report,
3082 parent,
3083 js::handler_budget(),
3084 cancellation,
3085 )
3086 .await;
3087}
3088
3089/// Let an answered alarm's leftover I/O finish on its own, and report how it
3090/// ended.
3091///
3092/// `fire_alarm` stops waiting for the drive as soon as the handler returns, so
3093/// nothing joins the task after that. Without this watcher a panic in the
3094/// leftover work, which the former `drive.await` turned into a loud process
3095/// panic, would end the task in silence.
3096fn watch_detached_alarm_drive(
3097 drive: crate::asyncrt::TaskHandle<anyhow::Result<Option<u64>>>,
3098 cell: &str,
3099 op: celld_logic::OpId,
3100) {
3101 let cell = cell.to_string();
3102 crate::asyncrt::spawn(async move {
3103 let failure = match drive.await {
3104 Ok(Ok(_)) => return,
3105 Ok(Err(error)) => format!("{error:#}"),
3106 Err(panic) => panic.to_string(),
3107 };
3108 tracing::warn!(
3109 event = "alarm_leftover_work_failed",
3110 scope = %cell,
3111 op,
3112 failure = %failure,
3113 "work an alarm handler left pending ended in a failure"
3114 );
3115 })
3116 .detach();
3117}
3118
3119/// Drive an alarm event and answer the position its final turn reached.
3120///
3121/// A handler that failed between turns, or threw before it suspended, has
3122/// its retry record written by the final alarm turn, after its error left.
3123/// That commit is as unproven as the handler's own, so `fire_alarm` gates on
3124/// the position from here. `None` when the event settled its claim itself;
3125/// its error then carries the position.
3126pub(crate) async fn drive_alarm(
3127 affiliation: crate::pool::Affiliation,
3128 job: CellJob,
3129 report: Option<AlarmReporter>,
3130) -> anyhow::Result<Option<u64>> {
3131 let cancellation = job
3132 .request_id()
3133 .map(RequestCancellationLifetime::from_request_id);
3134 drive_cell_inner(
3135 affiliation,
3136 job,
3137 report,
3138 None,
3139 js::handler_budget(),
3140 cancellation,
3141 #[cfg(celld_internal_tests)]
3142 DriveCellTestObservers::default(),
3143 )
3144 .await
3145}
3146
3147#[cfg(celld_internal_tests)]
3148#[doc(hidden)]
3149pub async fn drive_cell_with_budget_for_test(
3150 affiliation: crate::pool::Affiliation,
3151 job: CellJob,
3152 report: Option<AlarmReporter>,
3153 parent: Option<crate::telemetry::TraceContext>,
3154 budget: Duration,
3155) {
3156 let cancellation = job
3157 .request_id()
3158 .map(RequestCancellationLifetime::from_request_id);
3159 let _ = drive_cell_inner(
3160 affiliation,
3161 job,
3162 report,
3163 parent,
3164 budget,
3165 cancellation,
3166 DriveCellTestObservers::default(),
3167 )
3168 .await;
3169}
3170
3171async fn drive_cell_with_request_cancellation(
3172 affiliation: crate::pool::Affiliation,
3173 job: CellJob,
3174 report: Option<AlarmReporter>,
3175 parent: Option<crate::telemetry::TraceContext>,
3176 cancellation: Option<Arc<RequestCancellationLifetime>>,
3177) {
3178 assert_eq!(
3179 job.request_id(),
3180 cancellation.as_ref().map(|lifetime| lifetime.request_id),
3181 "a cell fetch and its cancellation lifetime must have the same request id"
3182 );
3183 #[cfg(celld_internal_tests)]
3184 let _ = drive_cell_inner(
3185 affiliation,
3186 job,
3187 report,
3188 parent,
3189 js::handler_budget(),
3190 cancellation,
3191 DriveCellTestObservers::default(),
3192 )
3193 .await;
3194 #[cfg(not(celld_internal_tests))]
3195 let _ = drive_cell_inner(
3196 affiliation,
3197 job,
3198 report,
3199 parent,
3200 js::handler_budget(),
3201 cancellation,
3202 )
3203 .await;
3204}
3205
3206#[cfg(celld_internal_tests)]
3207#[doc(hidden)]
3208pub async fn drive_cell_observing_gated_failure_for_test(
3209 affiliation: crate::pool::Affiliation,
3210 job: CellJob,
3211 gated_failure: tokio::sync::oneshot::Sender<bool>,
3212) {
3213 let cancellation = job
3214 .request_id()
3215 .map(RequestCancellationLifetime::from_request_id);
3216 let _ = drive_cell_inner(
3217 affiliation,
3218 job,
3219 None,
3220 None,
3221 js::handler_budget(),
3222 cancellation,
3223 DriveCellTestObservers {
3224 gated_failure: Some(gated_failure),
3225 ..DriveCellTestObservers::default()
3226 },
3227 )
3228 .await;
3229}
3230
3231#[cfg(celld_internal_tests)]
3232#[doc(hidden)]
3233pub async fn drive_cell_observing_gated_op_drop_for_test(
3234 affiliation: crate::pool::Affiliation,
3235 job: CellJob,
3236 gated_failure: tokio::sync::oneshot::Sender<bool>,
3237 native_op_dropped: tokio::sync::oneshot::Sender<()>,
3238) {
3239 let cancellation = job
3240 .request_id()
3241 .map(RequestCancellationLifetime::from_request_id);
3242 let _ = drive_cell_inner(
3243 affiliation,
3244 job,
3245 None,
3246 None,
3247 js::handler_budget(),
3248 cancellation,
3249 DriveCellTestObservers {
3250 gated_failure: Some(gated_failure),
3251 native_op_dropped: Some(native_op_dropped),
3252 },
3253 )
3254 .await;
3255}
3256
3257#[cfg(celld_internal_tests)]
3258#[derive(Default)]
3259struct DriveCellTestObservers {
3260 gated_failure: Option<tokio::sync::oneshot::Sender<bool>>,
3261 native_op_dropped: Option<tokio::sync::oneshot::Sender<()>>,
3262}
3263
3264#[cfg(celld_internal_tests)]
3265struct NativeOpDropProbe(Option<tokio::sync::oneshot::Sender<()>>);
3266
3267#[cfg(celld_internal_tests)]
3268impl Drop for NativeOpDropProbe {
3269 fn drop(&mut self) {
3270 if let Some(dropped) = self.0.take() {
3271 let _ = dropped.send(());
3272 }
3273 }
3274}
3275
3276#[cfg(celld_internal_tests)]
3277fn adopt_cell_ops_for_test(
3278 ops: &mut Ops,
3279 started: Vec<js::Op>,
3280 observer: &mut Option<tokio::sync::oneshot::Sender<()>>,
3281) {
3282 for (id, future) in started {
3283 let probe = observer
3284 .take()
3285 .map(|observer| NativeOpDropProbe(Some(observer)));
3286 ops.push(Box::pin(async move {
3287 let _probe = probe;
3288 (id, future.await)
3289 }));
3290 }
3291}
3292
3293#[cfg(celld_internal_tests)]
3294fn notify_gated_failure_for_test(
3295 entry: &mut js::InFlight,
3296 observer: &mut Option<tokio::sync::oneshot::Sender<bool>>,
3297) {
3298 let gated = entry.gated_reply_and_io_context().0.is_some();
3299 if let Some(observer) = observer.take() {
3300 let _ = observer.send(gated);
3301 }
3302}
3303
3304async fn drive_cell_inner(
3305 affiliation: crate::pool::Affiliation,
3306 mut job: CellJob,
3307 report: Option<AlarmReporter>,
3308 parent: Option<crate::telemetry::TraceContext>,
3309 budget: Duration,
3310 request_cancellation: Option<Arc<RequestCancellationLifetime>>,
3311 #[cfg(celld_internal_tests)] mut test_observers: DriveCellTestObservers,
3312) -> anyhow::Result<Option<u64>> {
3313 let _request_cancellation = request_cancellation.map(RequestCancellationGuard::shared);
3314 // Held to the end of this function: the event's claim on the isolate
3315 // outlives every suspension, so the pool cannot free the worker under
3316 // a parked event (denoland/celld#147).
3317 let slot = affiliation.slot().clone();
3318 let scope = job.scope().to_string();
3319 let _queue_producer = if job.is_queue_producer() {
3320 match slot.queue_producer(&scope) {
3321 Some(permit) => Some(permit),
3322 None => {
3323 job.fail(anyhow!(js::CellOverloaded));
3324 return Ok(None);
3325 }
3326 }
3327 } else {
3328 None
3329 };
3330 // Two calls a caller made back-to-back reach the cell in that order.
3331 // This is the only place that can hold it: everything upstream is a
3332 // race, and everything downstream has already been delivered. Held
3333 // until the event *begins*, not until it finishes — a handler that
3334 // waits must not stop the next call arriving, or cell events would
3335 // stop interleaving and the DO contract with them.
3336 let mut order = job.take_order();
3337 if let Some(order) = order.as_mut() {
3338 order.wait().await;
3339 }
3340 // Join the dispatching Worker's trace when there is one — the root
3341 // already made the sampling decision — else decide a fresh root.
3342 // The seed is captured before the job moves, recorded once the entry
3343 // settles.
3344 let trace = match parent.as_ref() {
3345 Some(parent) => crate::telemetry::child_of(parent),
3346 None => crate::telemetry::start_trace(),
3347 };
3348 let recording = trace.and_then(crate::telemetry::TraceContext::recording_ids);
3349 let span_seed = recording.map(|_| {
3350 let name = match &job {
3351 CellJob::Fetch { .. } => "celld.cell_fetch",
3352 CellJob::Alarm { .. } => "celld.alarm",
3353 CellJob::Rpc { .. } => "celld.rpc",
3354 CellJob::WsOpen { .. } => "celld.ws_open",
3355 CellJob::WsMessage { .. } => "celld.ws_message",
3356 CellJob::WsClosed { .. } => "celld.ws_close",
3357 #[cfg(celld_internal_tests)]
3358 CellJob::SyncErrorForTest { .. } => "celld.sync_error_test",
3359 };
3360 (
3361 name,
3362 job.scope().to_string(),
3363 Instant::now(),
3364 crate::telemetry::now_unix_us(),
3365 )
3366 });
3367 let mut ops = Ops::new();
3368 // `blockConcurrencyWhile` shuts the cell's gate, and a shut gate means no
3369 // event reaches that cell until it opens. The blocking loop left a
3370 // refused job on the channel; there is no channel now, so the event waits
3371 // here.
3372 //
3373 // Asked *inside* the turn, which is the whole of it. A handler shuts the
3374 // gate while holding the isolate, so a check made before taking the
3375 // isolate can pass and then queue behind the very block it should have
3376 // waited for. On an idle machine the blocking event always won that race
3377 // and the bug was invisible; under load it is not.
3378 //
3379 // `cell_gate_wait` checks and enqueues under the gate's own lock, so the
3380 // ticket cannot be missed by a release landing between the two. Only the
3381 // waiting happens out here, because a turn may not await.
3382 let mut pending = Some(job);
3383 let started_event = match pending.as_mut() {
3384 Some(CellJob::WsMessage { started, .. }) => started.take(),
3385 _ => None,
3386 };
3387 let (begun, started, moves) = loop {
3388 let mut waiting = None;
3389 let taken = slot
3390 .turn_cell(&scope, |worker| {
3391 let job = pending.take().expect("one job per attempt");
3392 if let Some(open) = js::cell_gate_wait(job.scope()) {
3393 waiting = Some(open);
3394 pending = Some(job);
3395 return None;
3396 }
3397 let (begun, started) = worker.turn_begin_cell(job, trace);
3398 Some((begun, started, worker.take_alarm_moves()))
3399 })
3400 .await;
3401 match taken {
3402 Some(taken) => break taken,
3403 None => match waiting {
3404 None => {}
3405 Some(open) => match open.await {
3406 // The gate opened normally; try for the isolate again.
3407 Ok(Ok(())) => {}
3408 // The critical section this event queued behind failed,
3409 // which reset the cell. Delivering now would run against
3410 // state that no longer exists, so refuse instead and say
3411 // why the caller is being refused.
3412 Ok(Err(failure)) => {
3413 if let Some(job) = pending.take() {
3414 job.fail(anyhow!(failure));
3415 }
3416 return Ok(None);
3417 }
3418 // The cell stopped while this event waited.
3419 Err(_) => return Ok(None),
3420 },
3421 },
3422 }
3423 };
3424 // Delivered. Whatever the caller sent next may go.
3425 // A socket waits for this turn, including the input gate, rather than
3426 // handler completion. Acknowledging a queued task instead can reorder
3427 // messages; awaiting completion prevents a later message cancelling it.
3428 if let Some(started) = started_event {
3429 let _ = started.send(());
3430 }
3431 if let Some(order) = order.as_mut() {
3432 order.delivered();
3433 }
3434 drop(order);
3435 report_alarm_moves(&report, moves);
3436 // Nothing is in flight; the reply already carries the error.
3437 let Some(mut entry) = begun else {
3438 drop(started);
3439 return Ok(None);
3440 };
3441 if entry.keeps_native_ops() {
3442 #[cfg(celld_internal_tests)]
3443 adopt_cell_ops_for_test(&mut ops, started, &mut test_observers.native_op_dropped);
3444 #[cfg(not(celld_internal_tests))]
3445 adopt(&mut ops, started);
3446 } else {
3447 #[cfg(celld_internal_tests)]
3448 adopt_cell_ops_for_test(&mut ops, started, &mut test_observers.native_op_dropped);
3449 #[cfg(not(celld_internal_tests))]
3450 drop(started);
3451 abort_ops(&mut ops, &mut entry);
3452 }
3453 #[cfg(celld_internal_tests)]
3454 if entry.gated_reply_and_io_context().0.is_some() {
3455 notify_gated_failure_for_test(&mut entry, &mut test_observers.gated_failure);
3456 }
3457
3458 while !entry.finished() {
3459 let (started, moves) = match wake_with_cross_entry_gate(&mut ops, &mut entry, budget).await
3460 {
3461 Wake::Op(op, result) => {
3462 slot.turn(|worker| {
3463 let started = worker.turn_deliver(&mut entry, op, result);
3464 (started, worker.take_alarm_moves())
3465 })
3466 .await
3467 }
3468 Wake::GatedReply(completion) => {
3469 entry.finish_gated_reply(completion);
3470 (Vec::new(), Vec::new())
3471 }
3472 Wake::CancelGatedReply => {
3473 entry.cancel_gated_reply();
3474 (Vec::new(), Vec::new())
3475 }
3476 Wake::CrossEntryGateChanged => {
3477 entry.finish_cross_entry_gates();
3478 (Vec::new(), Vec::new())
3479 }
3480 Wake::Cancelled { shutdown } => {
3481 let cancelled = slot
3482 .turn(|worker| {
3483 let started = if shutdown {
3484 worker.turn_cancel_for_shutdown(&mut entry)
3485 } else {
3486 worker.turn_cancel(&mut entry)
3487 };
3488 (started, worker.take_alarm_moves())
3489 })
3490 .await;
3491 entry.cancel_gated_reply();
3492 #[cfg(celld_internal_tests)]
3493 notify_gated_failure_for_test(&mut entry, &mut test_observers.gated_failure);
3494 cancelled
3495 }
3496 Wake::Expired => {
3497 entry.time_out(budget);
3498 slot.turn(|worker| worker.turn_retire_input_gates(&entry))
3499 .await;
3500 #[cfg(celld_internal_tests)]
3501 notify_gated_failure_for_test(&mut entry, &mut test_observers.gated_failure);
3502 (Vec::new(), Vec::new())
3503 }
3504 Wake::Idle => {
3505 entry.stuck();
3506 slot.turn(|worker| worker.turn_retire_input_gates(&entry))
3507 .await;
3508 #[cfg(celld_internal_tests)]
3509 notify_gated_failure_for_test(&mut entry, &mut test_observers.gated_failure);
3510 (Vec::new(), Vec::new())
3511 }
3512 Wake::PendingEventIdle => {
3513 slot.turn(|worker| {
3514 let started = worker.turn_cancel_pending_events(&mut entry);
3515 (started, worker.take_alarm_moves())
3516 })
3517 .await
3518 }
3519 Wake::Poll => {
3520 slot.turn(|worker| {
3521 let started = worker.turn_poll(&mut entry);
3522 (started, worker.take_alarm_moves())
3523 })
3524 .await
3525 }
3526 };
3527 #[cfg(celld_internal_tests)]
3528 if entry.gated_reply_and_io_context().0.is_some() {
3529 notify_gated_failure_for_test(&mut entry, &mut test_observers.gated_failure);
3530 }
3531 if entry.keeps_native_ops() {
3532 #[cfg(celld_internal_tests)]
3533 adopt_cell_ops_for_test(&mut ops, started, &mut test_observers.native_op_dropped);
3534 #[cfg(not(celld_internal_tests))]
3535 adopt(&mut ops, started);
3536 } else {
3537 drop(started);
3538 abort_ops(&mut ops, &mut entry);
3539 }
3540 // A turn that ran JS may have armed an alarm this very request is
3541 // waiting on, so the host hears about it now rather than when the
3542 // request ends.
3543 report_alarm_moves(&report, moves);
3544 }
3545
3546 // An alarm that ended without running JS again still owes its outcome —
3547 // `fail` deliberately leaves the claim, because it runs between turns
3548 // where cell storage is unreachable (denoland/celld#170) — and
3549 // recording it is storage only the isolate can reach.
3550 let mut alarm_write = Ok(None);
3551 if entry.owes_alarm() {
3552 let (moves, write) = slot
3553 .turn(|worker| {
3554 let write = worker.turn_finish_alarm(&mut entry);
3555 (worker.take_alarm_moves(), write)
3556 })
3557 .await;
3558 report_alarm_moves(&report, moves);
3559 alarm_write = write;
3560 }
3561 if let (Some(ids), Some((name, cell, started, start_unix))) = (recording, span_seed) {
3562 let kind = if name == "celld.cell_fetch" {
3563 crate::telemetry::KIND_SERVER
3564 } else {
3565 crate::telemetry::KIND_INTERNAL
3566 };
3567 let mut span = crate::telemetry::Span::new(ids, name, kind);
3568 span.start_unix_us = start_unix;
3569 span.duration_us = started.elapsed().as_micros() as i64;
3570 span.ok = entry.finished() && entry.failure().is_none();
3571 span.error = entry.failure().map(str::to_string);
3572 span.cell = Some(cell);
3573 span.parent_span_id = parent.map(|parent| parent.span_id);
3574 span.parent_remote = parent.map(|_| false);
3575 crate::telemetry::record(span);
3576 }
3577 slot.turn(|worker| worker.turn_abandon_input_gates(&entry))
3578 .await;
3579 entry.abandon();
3580 alarm_write
3581}
3582
3583fn path_text(path: &Path) -> &str {
3584 path.to_str().expect("celld data path must be UTF-8")
3585}
3586
3587/// Tell the container module which classes the current generation
3588/// attaches a container to, and warm their images off the request path.
3589/// A generation with no container class installs an empty list, so a
3590/// class dropped by a redeploy cannot start a container.
3591fn install_container_specs(generation: &Generation) {
3592 crate::container::install_specs(
3593 generation.containers.clone(),
3594 generation.fence_image.clone(),
3595 );
3596 if generation.containers.is_empty() {
3597 return;
3598 }
3599 if let Ok(handle) = tokio::runtime::Handle::try_current() {
3600 handle.spawn(crate::container::prewarm());
3601 }
3602}