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