| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! The serial lifecycle executor and its shell-side request drivers. |
| 4 | |
| 5 | use crate::js::{HttpResponse, WsOut}; |
| 6 | use crate::machine::{ |
| 7 | ownership_on_evict_from_environment, pressure_config_from_environment, |
| 8 | random_process_generation, DEFAULT_MAX_OUTBOUND_WEBSOCKETS, |
| 9 | }; |
| 10 | use crate::ownership_store::{now_ms, BucketOwnership}; |
| 11 | use crate::peer_auth::{self, PeerAuth}; |
| 12 | use crate::runtime::{CellHost, RuntimeManager}; |
| 13 | use anyhow::Context as _; |
| 14 | use celld_logic::{ |
| 15 | on_event, AdoptedCell, CapacityPeer, CasGuard, CasOutcome, Channel, Config, Effect, Event, |
| 16 | Failure, LeaseCasOutcome, NodeLeaseRecord, NodeLeaseSpec, OpId, OwnerRecord, OwnershipOnEvict, |
| 17 | Phase, RequestError, Route, State, StopCause, Timer, WebSocketKind, WorkerRoute, |
| 18 | }; |
| 19 | use futures_util::stream::FuturesUnordered; |
| 20 | use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; |
| 21 | use std::future::Future; |
| 22 | use std::pin::Pin; |
| 23 | use std::sync::atomic::{AtomicUsize, Ordering}; |
| 24 | use std::sync::Arc; |
| 25 | use tokio::sync::{mpsc, oneshot, watch, Mutex}; |
| 26 | use tokio_util::time::{delay_queue, DelayQueue}; |
| 27 | |
| 28 | mod production; |
| 29 | |
| 30 | const DEFAULT_OPERATION_DEADLINE_MS: u64 = 15_000; |
| 31 | |
| 32 | /// The shell's deadline for one actor operation. Queue leases include this |
| 33 | /// exact budget for their settlement call, so the actor and broker must read |
| 34 | /// one accessor rather than duplicate the environment default. |
| 35 | pub(crate) fn operation_deadline_ms() -> anyhow::Result<u64> { |
| 36 | crate::env_vars::positive_or("CELLD_OPERATION_DEADLINE_MS", DEFAULT_OPERATION_DEADLINE_MS) |
| 37 | } |
| 38 | |
| 39 | #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] |
| 40 | pub enum TimerSlot { |
| 41 | NodeLeaseRenew, |
| 42 | NodeLeaseFence, |
| 43 | CellAlarm(String), |
| 44 | /// Keyed by operation, deliberately. Every other timer here coalesces |
| 45 | /// because only its newest arming matters; a deadline is the opposite -- |
| 46 | /// each watches a different outstanding operation, and a shared slot |
| 47 | /// would let arming one silently cancel another, leaving every activation |
| 48 | /// but the most recent with nothing watching it. |
| 49 | OperationDeadline(OpId), |
| 50 | /// Keyed by cell and generation for the same reason as the deadline |
| 51 | /// above: a node parks many cells at once, and one slot per cell would |
| 52 | /// let a later parking disarm an earlier one. |
| 53 | QueuedActivation(String, u64), |
| 54 | } |
| 55 | |
| 56 | impl TimerSlot { |
| 57 | pub fn of(timer: &Timer) -> Self { |
| 58 | match timer { |
| 59 | Timer::NodeLeaseRenew { .. } => Self::NodeLeaseRenew, |
| 60 | Timer::NodeLeaseFence { .. } => Self::NodeLeaseFence, |
| 61 | Timer::CellAlarm { cell, .. } => Self::CellAlarm(cell.clone()), |
| 62 | Timer::OperationDeadline { op } => Self::OperationDeadline(*op), |
| 63 | Timer::QueuedActivation { cell, generation } => { |
| 64 | Self::QueuedActivation(cell.clone(), *generation) |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | /// One versioned timer arm emitted by an Actor step. |
| 71 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 72 | pub struct TimerArm { |
| 73 | pub slot: TimerSlot, |
| 74 | pub ordinal: u64, |
| 75 | pub timer: Timer, |
| 76 | pub at_mono_ms: u64, |
| 77 | } |
| 78 | |
| 79 | /// The shared displacement discipline for production and deterministic timers. |
| 80 | pub struct TimerSlots<V> { |
| 81 | armed: BTreeMap<TimerSlot, (u64, V)>, |
| 82 | ordinals: BTreeMap<TimerSlot, u64>, |
| 83 | } |
| 84 | |
| 85 | impl<V> Default for TimerSlots<V> { |
| 86 | fn default() -> Self { |
| 87 | Self { |
| 88 | armed: BTreeMap::new(), |
| 89 | ordinals: BTreeMap::new(), |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | impl<V> TimerSlots<V> { |
| 95 | /// Creates one arm, assigns its stable per-slot ordinal, and applies it. |
| 96 | pub fn arm(&mut self, timer: Timer, at_mono_ms: u64, value: V) -> (TimerArm, Option<V>) { |
| 97 | let slot = TimerSlot::of(&timer); |
| 98 | let ordinal = self.ordinals.entry(slot.clone()).or_default(); |
| 99 | let arm = TimerArm { |
| 100 | slot: slot.clone(), |
| 101 | ordinal: *ordinal, |
| 102 | timer, |
| 103 | at_mono_ms, |
| 104 | }; |
| 105 | *ordinal = ordinal.saturating_add(1); |
| 106 | let displaced = self.replace(&slot, arm.ordinal, value); |
| 107 | (arm, displaced) |
| 108 | } |
| 109 | |
| 110 | /// Applies an arm whose ordinal the Actor has already assigned. |
| 111 | pub fn install(&mut self, arm: &TimerArm, value: V) -> Option<V> { |
| 112 | self.replace(&arm.slot, arm.ordinal, value) |
| 113 | } |
| 114 | |
| 115 | fn replace(&mut self, slot: &TimerSlot, ordinal: u64, value: V) -> Option<V> { |
| 116 | let displaced = self |
| 117 | .armed |
| 118 | .insert(slot.clone(), (ordinal, value)) |
| 119 | .map(|(_, value)| value); |
| 120 | debug_assert!( |
| 121 | displaced.is_none() || !matches!(slot, TimerSlot::OperationDeadline(_)), |
| 122 | "an operation deadline displaced another: {slot:?}" |
| 123 | ); |
| 124 | displaced |
| 125 | } |
| 126 | |
| 127 | /// Removes the current arm only when both parts of its identity match. |
| 128 | pub fn fire(&mut self, slot: &TimerSlot, ordinal: u64) -> Option<V> { |
| 129 | if self |
| 130 | .armed |
| 131 | .get(slot) |
| 132 | .is_some_and(|(armed, _)| *armed == ordinal) |
| 133 | { |
| 134 | self.armed.remove(slot).map(|(_, value)| value) |
| 135 | } else { |
| 136 | None |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | fn clear_slot(&mut self, slot: &TimerSlot) { |
| 141 | self.armed.remove(slot); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | pub struct MemoryOwnership { |
| 146 | node: String, |
| 147 | owners: BTreeMap<String, OwnerRecord>, |
| 148 | leases: BTreeMap<String, NodeLeaseRecord>, |
| 149 | next_etag: u64, |
| 150 | } |
| 151 | |
| 152 | #[derive(Clone)] |
| 153 | pub enum Ownership { |
| 154 | Memory(Arc<Mutex<MemoryOwnership>>), |
| 155 | Bucket(Arc<BucketOwnership>), |
| 156 | } |
| 157 | |
| 158 | impl Ownership { |
| 159 | async fn read_owner(&self, cell: &str) -> Result<Option<OwnerRecord>, Failure> { |
| 160 | match self { |
| 161 | Self::Memory(memory) => Ok(memory.lock().await.owners.get(cell).cloned()), |
| 162 | Self::Bucket(bucket) => bucket.read_owner(cell).await.map_err(|error| { |
| 163 | eprintln!("celld ownership read failed: {error:#}"); |
| 164 | Failure::Definite |
| 165 | }), |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | async fn read_node_lease(&self, owner: &str) -> Result<Option<NodeLeaseRecord>, Failure> { |
| 170 | match self { |
| 171 | Self::Memory(memory) => Ok(memory.lock().await.leases.get(owner).cloned()), |
| 172 | Self::Bucket(bucket) => bucket.read_node_lease(owner).await.map_err(|error| { |
| 173 | eprintln!("celld node lease read failed: {error:#}"); |
| 174 | Failure::Definite |
| 175 | }), |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | async fn read_capacity_peers(&self) -> Result<Vec<celld_logic::CapacityPeer>, Failure> { |
| 180 | match self { |
| 181 | // The in-memory adapter is a single-node development mode. It has |
| 182 | // no external membership enumeration to offer. |
| 183 | Self::Memory(_) => Ok(Vec::new()), |
| 184 | Self::Bucket(bucket) => bucket.read_capacity_peers().await.map_err(|error| { |
| 185 | eprintln!("celld capacity peer read failed: {error:#}"); |
| 186 | Failure::Definite |
| 187 | }), |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | async fn read_self_node_lease(&self, node: &str) -> Result<Option<NodeLeaseRecord>, Failure> { |
| 192 | match self { |
| 193 | Self::Memory(memory) => Ok(memory.lock().await.leases.get(node).cloned()), |
| 194 | Self::Bucket(bucket) => bucket.read_self_node_lease(node).await.map_err(|error| { |
| 195 | eprintln!("celld self node lease read failed: {error:#}"); |
| 196 | Failure::Definite |
| 197 | }), |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | async fn cas_owner( |
| 202 | &self, |
| 203 | cell: &str, |
| 204 | guard: CasGuard, |
| 205 | epoch: u64, |
| 206 | ) -> Result<CasOutcome, Failure> { |
| 207 | match self { |
| 208 | Self::Memory(memory) => { |
| 209 | let mut memory = memory.lock().await; |
| 210 | let allowed = match guard { |
| 211 | CasGuard::Absent => !memory.owners.contains_key(cell), |
| 212 | CasGuard::Match(expected) => memory |
| 213 | .owners |
| 214 | .get(cell) |
| 215 | .is_some_and(|owner| owner.etag == expected), |
| 216 | }; |
| 217 | if allowed { |
| 218 | let etag = format!("e{}", memory.next_etag); |
| 219 | memory.next_etag += 1; |
| 220 | let node = memory.node.clone(); |
| 221 | memory.owners.insert( |
| 222 | cell.into(), |
| 223 | OwnerRecord { |
| 224 | node: Some(node), |
| 225 | epoch, |
| 226 | etag, |
| 227 | }, |
| 228 | ); |
| 229 | } |
| 230 | Ok(if allowed { |
| 231 | CasOutcome::Applied |
| 232 | } else { |
| 233 | CasOutcome::Rejected |
| 234 | }) |
| 235 | } |
| 236 | Self::Bucket(bucket) => bucket.cas_owner(cell, guard, epoch).await.map_err(|error| { |
| 237 | // Any transport or 5xx failure may have happened after the |
| 238 | // store committed. The core reconciles by reading the owner |
| 239 | // again. |
| 240 | eprintln!("celld ownership CAS ambiguous: {error:#}"); |
| 241 | Failure::Ambiguous |
| 242 | }), |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | async fn release_owner(&self, cell: &str, epoch: u64) -> Result<CasOutcome, Failure> { |
| 247 | match self { |
| 248 | Self::Memory(memory) => { |
| 249 | let mut memory = memory.lock().await; |
| 250 | let node = memory.node.clone(); |
| 251 | let releasable = memory.owners.get(cell).is_some_and(|owner| { |
| 252 | owner.node.as_deref() == Some(node.as_str()) && owner.epoch == epoch |
| 253 | }); |
| 254 | if releasable { |
| 255 | let etag = format!("e{}", memory.next_etag); |
| 256 | memory.next_etag += 1; |
| 257 | memory.owners.insert( |
| 258 | cell.into(), |
| 259 | OwnerRecord { |
| 260 | node: None, |
| 261 | epoch, |
| 262 | etag, |
| 263 | }, |
| 264 | ); |
| 265 | } |
| 266 | Ok(if releasable { |
| 267 | CasOutcome::Applied |
| 268 | } else { |
| 269 | CasOutcome::Rejected |
| 270 | }) |
| 271 | } |
| 272 | // A release that may or may not have committed needs no |
| 273 | // reconciliation: the record either still names this node, and the |
| 274 | // next eviction releases it again, or it does not, and the cell is |
| 275 | // already free. Either way nothing is owed. |
| 276 | Self::Bucket(bucket) => bucket.release_owner(cell, epoch).await.map_err(|error| { |
| 277 | eprintln!("celld ownership release failed: {error:#}"); |
| 278 | Failure::Definite |
| 279 | }), |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | async fn cas_node_lease( |
| 284 | &self, |
| 285 | guard: CasGuard, |
| 286 | mut record: NodeLeaseRecord, |
| 287 | stamped: &mut Option<celld_logic::log_tier::LogState>, |
| 288 | ) -> Result<LeaseCasOutcome, Failure> { |
| 289 | match self { |
| 290 | Self::Memory(memory) => { |
| 291 | let mut memory = memory.lock().await; |
| 292 | let current = memory.leases.get(&record.node); |
| 293 | let allowed = match guard { |
| 294 | CasGuard::Absent => current.is_none(), |
| 295 | CasGuard::Match(expected) => { |
| 296 | current.is_some_and(|lease| lease.etag == expected) |
| 297 | } |
| 298 | }; |
| 299 | if !allowed { |
| 300 | return Ok(LeaseCasOutcome::Rejected); |
| 301 | } |
| 302 | let etag = format!("e{}", memory.next_etag); |
| 303 | memory.next_etag += 1; |
| 304 | record.etag = etag.clone(); |
| 305 | *stamped = record.log_state; |
| 306 | memory.leases.insert(record.node.clone(), record); |
| 307 | Ok(LeaseCasOutcome::Applied { etag }) |
| 308 | } |
| 309 | Self::Bucket(bucket) => bucket |
| 310 | .cas_node_lease(guard, &record, stamped) |
| 311 | .await |
| 312 | .map_err(|error| { |
| 313 | eprintln!("celld node-lease CAS ambiguous: {error:#}"); |
| 314 | Failure::Ambiguous |
| 315 | }), |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | pub fn name(&self) -> &'static str { |
| 320 | match self { |
| 321 | Self::Memory(_) => "memory", |
| 322 | Self::Bucket(bucket) => bucket.storage_scheme(), |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | pub enum Message { |
| 328 | /// A periodic resource sample. The measuring is the shell's job; every |
| 329 | /// decision that follows belongs to the core. |
| 330 | SampleLoad, |
| 331 | /// The log tier changed the folded log object the next lease write |
| 332 | /// must carry (lease-fold): renew now so the change becomes durable. |
| 333 | NudgeNodeLease, |
| 334 | /// Stop new internal routing while a clean same-node reload drains. The |
| 335 | /// request shell has already stopped admission; this closes wake and |
| 336 | /// service paths that do not pass through the HTTP gate. |
| 337 | BeginPreserve, |
| 338 | /// The node adopted a new application generation. Resident cells on an |
| 339 | /// older one move to it at a safe point, or by force after `max_age_ms`; |
| 340 | /// cells of an eager class move at once. |
| 341 | GenerationChanged { |
| 342 | generation: crate::generation::GenerationId, |
| 343 | max_age_ms: u64, |
| 344 | eager_classes: Vec<String>, |
| 345 | }, |
| 346 | /// Graceful shutdown: release every owned cell's record so peers take |
| 347 | /// over immediately. The release writes run as effects inside the |
| 348 | /// shutdown drain window, and the drain waits for them to complete — |
| 349 | /// bounded by the drain deadline, so a wedged store still cannot hold |
| 350 | /// the exit hostage. |
| 351 | ReleaseAll, |
| 352 | /// Has the shutdown handoff finished? True once no cell occupies |
| 353 | /// capacity: nothing resident, restoring, or mid-eviction. The drain |
| 354 | /// loop polls this to exit as soon as the handoff completes instead of |
| 355 | /// sitting out the full drain window. |
| 356 | Drained { |
| 357 | reply: oneshot::Sender<DrainStatus>, |
| 358 | }, |
| 359 | Request { |
| 360 | request: u64, |
| 361 | cell: String, |
| 362 | capacity_handoff: bool, |
| 363 | /// Present only for the signed shutdown-handoff endpoint. The actor |
| 364 | /// settles this channel as soon as the ownership CAS is authoritative; |
| 365 | /// the ordinary route reply remains pending until it is cancelled. |
| 366 | handoff_accept: Option<HandoffAcceptWaiter>, |
| 367 | /// An event from this exact registered WebSocket can finish on a |
| 368 | /// quiescing resident. Ordinary requests carry no identity and wait |
| 369 | /// for the successor route. |
| 370 | websocket: Option<u64>, |
| 371 | reply: oneshot::Sender<Result<Routed, RequestError>>, |
| 372 | }, |
| 373 | /// A caller disappeared before routing finished. The request identity is |
| 374 | /// allocated by the shell, so the actor can remove it from either cold |
| 375 | /// admission queue immediately. |
| 376 | CancelRoute { |
| 377 | request: u64, |
| 378 | }, |
| 379 | WorkerRequest { |
| 380 | reply: oneshot::Sender<WorkerRouted>, |
| 381 | }, |
| 382 | ActivityFinished { |
| 383 | request: u64, |
| 384 | // The activity drop also observes the cell's alarm. Folded in here so a |
| 385 | // request's completion costs the serial core one message, not two — the |
| 386 | // hot path for every routed DO call. |
| 387 | cell: String, |
| 388 | alarm_at_ms: Option<i64>, |
| 389 | alarm_covered: bool, |
| 390 | }, |
| 391 | /// An outbound effect is ready to leave on `channel`. A write opens a |
| 392 | /// durability barrier, and a read trails the newest barrier already open on |
| 393 | /// its cell. The channel rides along so the release can be routed back to |
| 394 | /// whichever adapter is holding the effect. |
| 395 | Output { |
| 396 | request: u64, |
| 397 | channel: Channel, |
| 398 | position: Option<u64>, |
| 399 | reply: oneshot::Sender<Result<(), RequestError>>, |
| 400 | }, |
| 401 | /// A `webSocketMessage` finished; hand its captured outbound frames to the |
| 402 | /// cell's output gate. `write_position` present means the handler wrote, so |
| 403 | /// the frames are held behind that write until it is durable; absent means |
| 404 | /// flush them (behind any earlier still-pending write, else immediately). |
| 405 | WsOutput { |
| 406 | request: u64, |
| 407 | scope: String, |
| 408 | frames: Vec<(u64, WsOut)>, |
| 409 | write_position: Option<u64>, |
| 410 | reply: oneshot::Sender<()>, |
| 411 | }, |
| 412 | WebSocketOpened { |
| 413 | cell: String, |
| 414 | websocket: u64, |
| 415 | kind: WebSocketKind, |
| 416 | reply: oneshot::Sender<bool>, |
| 417 | }, |
| 418 | WebSocketClosed { |
| 419 | cell: String, |
| 420 | websocket: u64, |
| 421 | }, |
| 422 | AlarmObserved { |
| 423 | cell: String, |
| 424 | at_ms: Option<i64>, |
| 425 | covered: bool, |
| 426 | }, |
| 427 | WakeHint { |
| 428 | cell: String, |
| 429 | }, |
| 430 | Evict { |
| 431 | cell: String, |
| 432 | reply: oneshot::Sender<()>, |
| 433 | }, |
| 434 | InvalidateRemote { |
| 435 | cell: String, |
| 436 | node: String, |
| 437 | epoch: u64, |
| 438 | reply: oneshot::Sender<()>, |
| 439 | }, |
| 440 | Snapshot { |
| 441 | reply: oneshot::Sender<(String, Vec<celld_logic::DrainPin>, SwapCensus)>, |
| 442 | }, |
| 443 | Health { |
| 444 | reply: oneshot::Sender<bool>, |
| 445 | }, |
| 446 | Presence { |
| 447 | reply: oneshot::Sender<celld_logic::PresenceSnapshot>, |
| 448 | }, |
| 449 | ResidentEpoch { |
| 450 | cell: String, |
| 451 | reply: oneshot::Sender<Option<u64>>, |
| 452 | }, |
| 453 | } |
| 454 | |
| 455 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 456 | pub enum ShutdownMode { |
| 457 | /// The logical node is leaving. Release every owner record so another |
| 458 | /// node can take over without waiting for the node lease to expire. |
| 459 | Handoff, |
| 460 | /// The same logical node will start again at the same address. Drain the |
| 461 | /// request shell, but keep ownership and the local replica cache intact. |
| 462 | Preserve, |
| 463 | } |
| 464 | |
| 465 | pub struct Routed { |
| 466 | pub request: u64, |
| 467 | pub route: Route, |
| 468 | } |
| 469 | |
| 470 | /// A test-only receipt for three request-path outcomes. `AppHandle::request` |
| 471 | /// deliberately maps both channel failures to `NodeFenced`, so its public |
| 472 | /// result cannot identify which asynchronous seam failed. |
| 473 | #[cfg(all(test, celld_internal_tests))] |
| 474 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 475 | pub(crate) enum RequestPathReceiptForTest { |
| 476 | SubmissionFailure { |
| 477 | request: u64, |
| 478 | }, |
| 479 | ReplyChannelClosed { |
| 480 | request: u64, |
| 481 | }, |
| 482 | Returned { |
| 483 | allocated_request: u64, |
| 484 | result: Result<(u64, Route), RequestError>, |
| 485 | }, |
| 486 | } |
| 487 | |
| 488 | /// A test-only receipt for three output-gate outcomes. The public gate maps |
| 489 | /// both channel failures to `NodeFenced`, so its result cannot identify which |
| 490 | /// asynchronous seam failed. |
| 491 | #[cfg(all(test, celld_internal_tests))] |
| 492 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 493 | pub(crate) enum OutputGateReceiptForTest { |
| 494 | SubmissionFailure { |
| 495 | request: u64, |
| 496 | }, |
| 497 | ReplyChannelClosed { |
| 498 | request: u64, |
| 499 | }, |
| 500 | Returned { |
| 501 | request: u64, |
| 502 | result: Result<(), RequestError>, |
| 503 | }, |
| 504 | } |
| 505 | |
| 506 | enum RequestPathOutcome { |
| 507 | SubmissionFailure, |
| 508 | ReplyChannelClosed, |
| 509 | Returned(Result<Routed, RequestError>), |
| 510 | } |
| 511 | |
| 512 | enum OutputGateOutcome { |
| 513 | SubmissionFailure, |
| 514 | ReplyChannelClosed, |
| 515 | Returned(Result<(), RequestError>), |
| 516 | } |
| 517 | |
| 518 | #[derive(Clone, Copy, Default)] |
| 519 | pub struct DrainStatus { |
| 520 | pub occupied: usize, |
| 521 | pub activating: usize, |
| 522 | /// Resident cells reserved for shutdown handoff. New requests wait for |
| 523 | /// their successor routes while admitted work finishes. |
| 524 | pub quiescing: usize, |
| 525 | pub evicting: usize, |
| 526 | /// Ownership releases still in flight. A handoff drain waits for zero: |
| 527 | /// a released cell leaves `occupied` before its record write commits, |
| 528 | /// so exiting on occupancy alone can abort the write mid-flight and |
| 529 | /// leave a record the successor waits out the node lease for. |
| 530 | pub releasing: usize, |
| 531 | /// Released cells waiting for a successor's ownership acknowledgement. |
| 532 | /// These hold the shutdown pacing permits. |
| 533 | pub adopting: usize, |
| 534 | /// Monotonic ownership acknowledgements. A progressing handoff can |
| 535 | /// take longer than one stall interval when the node owns many cells. |
| 536 | pub handed_off: u64, |
| 537 | } |
| 538 | |
| 539 | #[derive(serde::Deserialize, serde::Serialize)] |
| 540 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 541 | pub struct HandoffRequest { |
| 542 | pub cell: String, |
| 543 | pub released_epoch: u64, |
| 544 | } |
| 545 | |
| 546 | #[derive(serde::Deserialize, serde::Serialize)] |
| 547 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 548 | pub struct HandoffResponse { |
| 549 | pub node: String, |
| 550 | pub addr: String, |
| 551 | pub epoch: u64, |
| 552 | pub peer_protocol: u16, |
| 553 | /// Whether the successor adopted the cell. It repeats what the status code |
| 554 | /// reports, and the donor accepts the reply only when the two agree: `200` |
| 555 | /// with `true` is an adoption, and `409` with `false` names the current |
| 556 | /// owner for the donor to contact instead. Every other pairing is refused, |
| 557 | /// so a disagreement between the two cannot be read as a handoff. |
| 558 | pub published: bool, |
| 559 | } |
| 560 | |
| 561 | pub struct HandoffAcceptWaiter { |
| 562 | released_epoch: u64, |
| 563 | reply: oneshot::Sender<AdoptedCell>, |
| 564 | } |
| 565 | |
| 566 | // Read only by the orphaned `worker_route`, and removed with the rest of the |
| 567 | // landing-cell machinery when that goes. |
| 568 | #[allow(dead_code)] |
| 569 | pub struct WorkerRouted { |
| 570 | pub request: u64, |
| 571 | pub route: Option<WorkerRoute>, |
| 572 | } |
| 573 | |
| 574 | /// Worker requests owned by one HTTP connection. Hyper can finish a failed |
| 575 | /// connection without dropping its service future, so the connection also |
| 576 | /// aborts these requests explicitly when its transport ends. |
| 577 | #[derive(Clone, Default)] |
| 578 | pub struct ConnectionWorkerRequests(Arc<std::sync::Mutex<BTreeSet<crate::js::RequestId>>>); |
| 579 | |
| 580 | impl ConnectionWorkerRequests { |
| 581 | pub fn register(&self, request: crate::js::RequestId) { |
| 582 | self.0.lock().unwrap().insert(request); |
| 583 | } |
| 584 | |
| 585 | pub fn complete(&self, request: crate::js::RequestId) { |
| 586 | self.0.lock().unwrap().remove(&request); |
| 587 | } |
| 588 | |
| 589 | pub fn abort_all(&self) { |
| 590 | let requests = std::mem::take(&mut *self.0.lock().unwrap()); |
| 591 | for request in requests { |
| 592 | crate::js::abort_request(request); |
| 593 | } |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | pub struct IngressAbortGuard { |
| 598 | request: Option<crate::js::RequestId>, |
| 599 | connection: ConnectionWorkerRequests, |
| 600 | } |
| 601 | |
| 602 | impl IngressAbortGuard { |
| 603 | pub fn new(request: crate::js::RequestId, connection: ConnectionWorkerRequests) -> Self { |
| 604 | connection.register(request); |
| 605 | Self { |
| 606 | request: Some(request), |
| 607 | connection, |
| 608 | } |
| 609 | } |
| 610 | |
| 611 | pub fn disarm(&mut self) { |
| 612 | if let Some(request) = self.request.take() { |
| 613 | self.connection.complete(request); |
| 614 | } |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | /// Cancels a core route when the future awaiting it is dropped. A normal |
| 619 | /// route disarms the guard before returning its result. |
| 620 | pub struct RouteCancelGuard { |
| 621 | tx: mpsc::UnboundedSender<Message>, |
| 622 | request: Option<u64>, |
| 623 | } |
| 624 | |
| 625 | impl RouteCancelGuard { |
| 626 | pub fn new(tx: mpsc::UnboundedSender<Message>, request: u64) -> Self { |
| 627 | Self { |
| 628 | tx, |
| 629 | request: Some(request), |
| 630 | } |
| 631 | } |
| 632 | |
| 633 | pub fn disarm(&mut self) { |
| 634 | self.request = None; |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | impl Drop for RouteCancelGuard { |
| 639 | fn drop(&mut self) { |
| 640 | if let Some(request) = self.request { |
| 641 | let _ = self.tx.send(Message::CancelRoute { request }); |
| 642 | } |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | impl Drop for IngressAbortGuard { |
| 647 | fn drop(&mut self) { |
| 648 | if let Some(request) = self.request.take() { |
| 649 | self.connection.complete(request); |
| 650 | crate::js::abort_request(request); |
| 651 | } |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | /// One public HTTP request admitted before shutdown closed the gate. Peer |
| 656 | /// requests do not hold this guard because the handoff must keep serving them. |
| 657 | pub struct PublicRequestGuard { |
| 658 | in_flight: Arc<AtomicUsize>, |
| 659 | } |
| 660 | |
| 661 | impl Drop for PublicRequestGuard { |
| 662 | fn drop(&mut self) { |
| 663 | self.in_flight.fetch_sub(1, Ordering::SeqCst); |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | #[derive(Clone, Default)] |
| 668 | pub struct DrainPinRegistry(Arc<std::sync::Mutex<DrainPinState>>); |
| 669 | |
| 670 | #[derive(Default)] |
| 671 | struct DrainPinState { |
| 672 | pins: BTreeMap<u64, DrainPinTrace>, |
| 673 | requests: HashMap<crate::js::RequestId, u64>, |
| 674 | } |
| 675 | |
| 676 | struct DrainPinTrace { |
| 677 | request_id: Option<crate::js::RequestId>, |
| 678 | origin: &'static str, |
| 679 | started_mono_ms: u64, |
| 680 | phase: &'static str, |
| 681 | response_headers_sent: bool, |
| 682 | response_body_active: bool, |
| 683 | durable_txid: Option<u64>, |
| 684 | output_gate_result: &'static str, |
| 685 | ack_point: &'static str, |
| 686 | cancellation_state: &'static str, |
| 687 | cancel: watch::Sender<bool>, |
| 688 | } |
| 689 | |
| 690 | #[derive(serde::Serialize)] |
| 691 | #[serde(rename_all = "camelCase")] |
| 692 | struct DrainPinView { |
| 693 | cell: String, |
| 694 | core_request_id: Option<u64>, |
| 695 | request_id: Option<String>, |
| 696 | origin: &'static str, |
| 697 | age_ms: u64, |
| 698 | phase: &'static str, |
| 699 | response_headers_sent: bool, |
| 700 | response_body_active: bool, |
| 701 | durable_txid: Option<u64>, |
| 702 | output_gate_result: &'static str, |
| 703 | ack_point: &'static str, |
| 704 | active_request_count: usize, |
| 705 | output_gate_count: usize, |
| 706 | cancellation_state: &'static str, |
| 707 | regular_websocket_count: usize, |
| 708 | outbound_websocket_count: usize, |
| 709 | } |
| 710 | |
| 711 | impl DrainPinRegistry { |
| 712 | fn begin( |
| 713 | &self, |
| 714 | core_request: u64, |
| 715 | request_id: Option<crate::js::RequestId>, |
| 716 | origin: &'static str, |
| 717 | ) -> watch::Receiver<bool> { |
| 718 | let (cancel, receive) = watch::channel(false); |
| 719 | let mut state = self.0.lock().unwrap(); |
| 720 | state.pins.insert( |
| 721 | core_request, |
| 722 | DrainPinTrace { |
| 723 | request_id, |
| 724 | origin, |
| 725 | started_mono_ms: crate::asyncrt::mono_ms(), |
| 726 | phase: "handler", |
| 727 | response_headers_sent: false, |
| 728 | response_body_active: false, |
| 729 | durable_txid: None, |
| 730 | output_gate_result: "not_applicable", |
| 731 | ack_point: "not_acknowledged", |
| 732 | cancellation_state: "not_cancelled", |
| 733 | cancel, |
| 734 | }, |
| 735 | ); |
| 736 | if let Some(request_id) = request_id { |
| 737 | state.requests.insert(request_id, core_request); |
| 738 | } |
| 739 | receive |
| 740 | } |
| 741 | |
| 742 | fn update( |
| 743 | &self, |
| 744 | core_request: u64, |
| 745 | phase: &'static str, |
| 746 | response_headers_sent: bool, |
| 747 | response_body_active: bool, |
| 748 | ) { |
| 749 | if let Some(pin) = self.0.lock().unwrap().pins.get_mut(&core_request) { |
| 750 | pin.phase = phase; |
| 751 | pin.response_headers_sent = response_headers_sent; |
| 752 | pin.response_body_active = response_body_active; |
| 753 | if response_headers_sent { |
| 754 | pin.ack_point = "response_headers_sent"; |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | fn gate_started(&self, core_request: u64, durable_txid: u64) { |
| 760 | if let Some(pin) = self.0.lock().unwrap().pins.get_mut(&core_request) { |
| 761 | pin.durable_txid = Some(durable_txid); |
| 762 | pin.output_gate_result = "pending"; |
| 763 | } |
| 764 | } |
| 765 | |
| 766 | fn gate_finished(&self, core_request: u64, proven: bool) { |
| 767 | if let Some(pin) = self.0.lock().unwrap().pins.get_mut(&core_request) { |
| 768 | pin.output_gate_result = if proven { "proven" } else { "failed" }; |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | pub fn cancel_request( |
| 773 | &self, |
| 774 | request_id: crate::js::RequestId, |
| 775 | cancellation_state: &'static str, |
| 776 | ) -> Option<&'static str> { |
| 777 | let mut state = self.0.lock().unwrap(); |
| 778 | let core_request = state.requests.get(&request_id).copied()?; |
| 779 | let pin = state.pins.get_mut(&core_request)?; |
| 780 | pin.cancellation_state = cancellation_state; |
| 781 | let _ = pin.cancel.send(true); |
| 782 | Some(pin.phase) |
| 783 | } |
| 784 | |
| 785 | fn cancel_core_request( |
| 786 | &self, |
| 787 | core_request: u64, |
| 788 | cancellation_state: &'static str, |
| 789 | ) -> Option<(Option<crate::js::RequestId>, &'static str)> { |
| 790 | let mut state = self.0.lock().unwrap(); |
| 791 | let pin = state.pins.get_mut(&core_request)?; |
| 792 | pin.cancellation_state = cancellation_state; |
| 793 | let _ = pin.cancel.send(true); |
| 794 | Some((pin.request_id, pin.phase)) |
| 795 | } |
| 796 | |
| 797 | fn finish(&self, core_request: u64) -> Option<DrainPinTrace> { |
| 798 | let mut state = self.0.lock().unwrap(); |
| 799 | let pin = state.pins.remove(&core_request)?; |
| 800 | if let Some(request_id) = pin.request_id { |
| 801 | state.requests.remove(&request_id); |
| 802 | } |
| 803 | Some(pin) |
| 804 | } |
| 805 | |
| 806 | fn snapshot(&self, pins: Vec<celld_logic::DrainPin>) -> Vec<DrainPinView> { |
| 807 | let state = self.0.lock().unwrap(); |
| 808 | pins.into_iter() |
| 809 | .map(|pin| { |
| 810 | let trace = pin.request.and_then(|request| state.pins.get(&request)); |
| 811 | DrainPinView { |
| 812 | cell: pin.cell, |
| 813 | core_request_id: pin.request, |
| 814 | request_id: trace |
| 815 | .and_then(|trace| trace.request_id) |
| 816 | .map(crate::js::request_id_string), |
| 817 | origin: trace.map_or("unknown", |trace| trace.origin), |
| 818 | age_ms: trace.map_or(0, |trace| { |
| 819 | crate::asyncrt::mono_ms().saturating_sub(trace.started_mono_ms) |
| 820 | }), |
| 821 | phase: trace.map_or("unknown", |trace| trace.phase), |
| 822 | response_headers_sent: trace.is_some_and(|trace| trace.response_headers_sent), |
| 823 | response_body_active: trace.is_some_and(|trace| trace.response_body_active), |
| 824 | durable_txid: trace.and_then(|trace| trace.durable_txid), |
| 825 | output_gate_result: trace.map_or("unknown", |trace| trace.output_gate_result), |
| 826 | ack_point: trace.map_or("unknown", |trace| trace.ack_point), |
| 827 | active_request_count: pin.active_request_count, |
| 828 | output_gate_count: pin.output_gate_count, |
| 829 | cancellation_state: trace.map_or("unknown", |trace| trace.cancellation_state), |
| 830 | regular_websocket_count: pin.regular_websocket_count, |
| 831 | outbound_websocket_count: pin.outbound_websocket_count, |
| 832 | } |
| 833 | }) |
| 834 | .collect() |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | pub struct ActivityGuard { |
| 839 | tx: mpsc::UnboundedSender<Message>, |
| 840 | request: u64, |
| 841 | runtime: Option<RuntimeManager>, |
| 842 | cell: String, |
| 843 | drain_pins: DrainPinRegistry, |
| 844 | cancellation: watch::Receiver<bool>, |
| 845 | } |
| 846 | |
| 847 | impl ActivityGuard { |
| 848 | pub fn set_phase( |
| 849 | &self, |
| 850 | phase: &'static str, |
| 851 | response_headers_sent: bool, |
| 852 | response_body_active: bool, |
| 853 | ) { |
| 854 | self.drain_pins.update( |
| 855 | self.request, |
| 856 | phase, |
| 857 | response_headers_sent, |
| 858 | response_body_active, |
| 859 | ); |
| 860 | } |
| 861 | |
| 862 | pub fn cancellation(&self) -> watch::Receiver<bool> { |
| 863 | self.cancellation.clone() |
| 864 | } |
| 865 | |
| 866 | pub fn gate_started(&self, durable_txid: u64) { |
| 867 | self.drain_pins.gate_started(self.request, durable_txid); |
| 868 | } |
| 869 | |
| 870 | pub fn gate_finished(&self, proven: bool) { |
| 871 | self.drain_pins.gate_finished(self.request, proven); |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | impl Drop for ActivityGuard { |
| 876 | fn drop(&mut self) { |
| 877 | if let Some(pin) = self.drain_pins.finish(self.request) { |
| 878 | if let Some(request_id) = pin |
| 879 | .request_id |
| 880 | .filter(|_| tracing::enabled!(target: "timing", tracing::Level::DEBUG)) |
| 881 | { |
| 882 | tracing::debug!( |
| 883 | target: "timing", |
| 884 | event = "cell_request_lifecycle", |
| 885 | core_request_id = self.request, |
| 886 | request_id = %crate::js::request_id_string(request_id), |
| 887 | scope = %self.cell, |
| 888 | origin = pin.origin, |
| 889 | age_ms = crate::asyncrt::mono_ms().saturating_sub(pin.started_mono_ms), |
| 890 | phase = pin.phase, |
| 891 | response_headers_sent = pin.response_headers_sent, |
| 892 | response_body_active = pin.response_body_active, |
| 893 | durable_txid = pin.durable_txid, |
| 894 | output_gate_result = pin.output_gate_result, |
| 895 | ack_point = pin.ack_point, |
| 896 | cancellation_state = pin.cancellation_state, |
| 897 | "cell request lifetime ended" |
| 898 | ); |
| 899 | } |
| 900 | } |
| 901 | // Read and send under the registry lock (`with_alarm`), so this |
| 902 | // report cannot carry an alarm older than one the reporter already |
| 903 | // sent — a stale fold arriving later would unarm the core and |
| 904 | // delete the wake entry (`alarm_reporter` documents the ordering). |
| 905 | let send = |tx: &mpsc::UnboundedSender<Message>, at_ms, covered| { |
| 906 | let _ = tx.send(Message::ActivityFinished { |
| 907 | request: self.request, |
| 908 | cell: self.cell.clone(), |
| 909 | alarm_at_ms: at_ms, |
| 910 | alarm_covered: covered, |
| 911 | }); |
| 912 | }; |
| 913 | match &self.runtime { |
| 914 | Some(runtime) => runtime.with_alarm(&self.cell, |at_ms| { |
| 915 | let covered = runtime.alarm_covered(&self.cell, at_ms); |
| 916 | send(&self.tx, at_ms, covered); |
| 917 | }), |
| 918 | None => send(&self.tx, None, false), |
| 919 | } |
| 920 | } |
| 921 | } |
| 922 | |
| 923 | #[derive(Clone, Copy)] |
| 924 | enum RouteStage { |
| 925 | OwnershipRead, |
| 926 | NodeLeaseLookup, |
| 927 | CapacityLookup, |
| 928 | OwnershipAcquire, |
| 929 | Restore, |
| 930 | IsolateStartup, |
| 931 | RegistryInsert, |
| 932 | } |
| 933 | |
| 934 | struct EffectTiming { |
| 935 | cell: String, |
| 936 | stage: RouteStage, |
| 937 | elapsed_us: u64, |
| 938 | } |
| 939 | |
| 940 | pub struct CompletedEffect { |
| 941 | event: Event, |
| 942 | timing: Option<EffectTiming>, |
| 943 | } |
| 944 | |
| 945 | impl CompletedEffect { |
| 946 | fn plain(event: Event) -> Self { |
| 947 | Self { |
| 948 | event, |
| 949 | timing: None, |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | fn timed(event: Event, cell: String, stage: RouteStage, started_mono_ms: u64) -> Self { |
| 954 | Self { |
| 955 | event, |
| 956 | timing: Some(EffectTiming { |
| 957 | cell, |
| 958 | stage, |
| 959 | elapsed_us: mono_elapsed_us(started_mono_ms), |
| 960 | }), |
| 961 | } |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | struct CellRouteTiming { |
| 966 | started_mono_ms: u64, |
| 967 | activation_started: bool, |
| 968 | capacity_wait_started_mono_ms: Option<u64>, |
| 969 | latch_wait_us: u64, |
| 970 | ownership_read_us: u64, |
| 971 | node_lease_lookup_us: u64, |
| 972 | capacity_lookup_us: u64, |
| 973 | capacity_wait_us: u64, |
| 974 | activation_slot_wait_us: u64, |
| 975 | lease_permit_us: u64, |
| 976 | ownership_acquire_us: u64, |
| 977 | replica_discovery_us: u64, |
| 978 | restore_us: u64, |
| 979 | isolate_startup_us: u64, |
| 980 | registry_insert_us: u64, |
| 981 | fresh: Option<bool>, |
| 982 | } |
| 983 | |
| 984 | impl CellRouteTiming { |
| 985 | fn new() -> Self { |
| 986 | Self { |
| 987 | started_mono_ms: crate::asyncrt::mono_ms(), |
| 988 | activation_started: false, |
| 989 | capacity_wait_started_mono_ms: None, |
| 990 | latch_wait_us: 0, |
| 991 | ownership_read_us: 0, |
| 992 | node_lease_lookup_us: 0, |
| 993 | capacity_lookup_us: 0, |
| 994 | capacity_wait_us: 0, |
| 995 | activation_slot_wait_us: 0, |
| 996 | lease_permit_us: 0, |
| 997 | ownership_acquire_us: 0, |
| 998 | replica_discovery_us: 0, |
| 999 | restore_us: 0, |
| 1000 | isolate_startup_us: 0, |
| 1001 | registry_insert_us: 0, |
| 1002 | fresh: None, |
| 1003 | } |
| 1004 | } |
| 1005 | |
| 1006 | fn effect_started(&mut self) { |
| 1007 | if !self.activation_started { |
| 1008 | self.activation_started = true; |
| 1009 | self.activation_slot_wait_us = mono_elapsed_us(self.started_mono_ms); |
| 1010 | } |
| 1011 | if let Some(started) = self.capacity_wait_started_mono_ms.take() { |
| 1012 | self.capacity_wait_us = self |
| 1013 | .capacity_wait_us |
| 1014 | .saturating_add(mono_elapsed_us(started)); |
| 1015 | } |
| 1016 | } |
| 1017 | |
| 1018 | fn record(&mut self, stage: RouteStage, elapsed_us: u64) { |
| 1019 | let field = match stage { |
| 1020 | RouteStage::OwnershipRead => &mut self.ownership_read_us, |
| 1021 | RouteStage::NodeLeaseLookup => &mut self.node_lease_lookup_us, |
| 1022 | RouteStage::CapacityLookup => &mut self.capacity_lookup_us, |
| 1023 | RouteStage::OwnershipAcquire => &mut self.ownership_acquire_us, |
| 1024 | RouteStage::Restore => &mut self.restore_us, |
| 1025 | RouteStage::IsolateStartup => &mut self.isolate_startup_us, |
| 1026 | RouteStage::RegistryInsert => &mut self.registry_insert_us, |
| 1027 | }; |
| 1028 | *field = field.saturating_add(elapsed_us); |
| 1029 | } |
| 1030 | } |
| 1031 | |
| 1032 | /// Report a cell's runtime stopped, but only once the host has actually let |
| 1033 | /// the cell go. |
| 1034 | /// |
| 1035 | /// A stop that failed can leave the cell's realm holding its open database, |
| 1036 | /// so reporting it stopped is what makes that dangerous: the core answers a |
| 1037 | /// stop by starting the cell again — on the current application generation |
| 1038 | /// for a swap, or on another node after a handoff — against storage the old |
| 1039 | /// realm may still have. Both stop paths therefore retry rather than report, |
| 1040 | /// and they share this loop so neither can drift into reporting first. |
| 1041 | /// |
| 1042 | /// The retry is unbounded on purpose. The core arms an operation deadline on |
| 1043 | /// the `Cleaning` phase this answers, so a host that never lets go is bounded |
| 1044 | /// there rather than by a count guessed here. |
| 1045 | async fn report_stopped_when_released<F, Fut>( |
| 1046 | op: OpId, |
| 1047 | cell: String, |
| 1048 | epoch: u64, |
| 1049 | event: &'static str, |
| 1050 | mut release: F, |
| 1051 | ) -> CompletedEffect |
| 1052 | where |
| 1053 | F: FnMut() -> Fut, |
| 1054 | Fut: std::future::Future<Output = anyhow::Result<()>>, |
| 1055 | { |
| 1056 | while let Err(error) = release().await { |
| 1057 | tracing::warn!( |
| 1058 | event, |
| 1059 | %cell, |
| 1060 | epoch, |
| 1061 | %error, |
| 1062 | "the host did not release the cell; retrying before reporting it stopped" |
| 1063 | ); |
| 1064 | crate::asyncrt::sleep(std::time::Duration::from_millis( |
| 1065 | crate::replication::CELL_RELEASE_RETRY_BASE_MS, |
| 1066 | )) |
| 1067 | .await; |
| 1068 | } |
| 1069 | CompletedEffect::plain(Event::RuntimeStopped { op }) |
| 1070 | } |
| 1071 | |
| 1072 | fn mono_elapsed_us(started_mono_ms: u64) -> u64 { |
| 1073 | crate::asyncrt::mono_ms() |
| 1074 | .saturating_sub(started_mono_ms) |
| 1075 | .saturating_mul(1_000) |
| 1076 | } |
| 1077 | |
| 1078 | pub type EffectFuture = Pin<Box<dyn Future<Output = CompletedEffect> + Send>>; |
| 1079 | pub type ConnectionFuture = Pin<Box<dyn Future<Output = ()> + Send>>; |
| 1080 | pub type DoCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>; |
| 1081 | pub type AssetCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>; |
| 1082 | pub type WebSocketFuture = Pin<Box<dyn Future<Output = ()> + Send>>; |
| 1083 | pub type CachePruneFuture = Pin< |
| 1084 | Box< |
| 1085 | dyn Future< |
| 1086 | Output = ( |
| 1087 | u64, |
| 1088 | Result<std::io::Result<(usize, usize, u64)>, crate::asyncrt::TaskPanic>, |
| 1089 | ), |
| 1090 | > + Send, |
| 1091 | >, |
| 1092 | >; |
| 1093 | |
| 1094 | /// One ready item selected for the serial Actor. |
| 1095 | pub enum ActorInput { |
| 1096 | Message(Message), |
| 1097 | Completed(CompletedEffect), |
| 1098 | TimerFired(Timer), |
| 1099 | } |
| 1100 | |
| 1101 | /// Futures and timer arms emitted by one Actor transition. |
| 1102 | #[derive(Default)] |
| 1103 | pub struct StepOutput { |
| 1104 | pub effects: Vec<EffectFuture>, |
| 1105 | pub timers: Vec<TimerArm>, |
| 1106 | } |
| 1107 | |
| 1108 | fn drain_step_output( |
| 1109 | out: &mut StepOutput, |
| 1110 | effects: &mut FuturesUnordered<EffectFuture>, |
| 1111 | delays: &mut DelayQueue<TimerArm>, |
| 1112 | timers: &mut TimerSlots<delay_queue::Key>, |
| 1113 | ) { |
| 1114 | for effect in out.effects.drain(..) { |
| 1115 | effects.push(effect); |
| 1116 | } |
| 1117 | for arm in out.timers.drain(..) { |
| 1118 | let delay = std::time::Duration::from_millis( |
| 1119 | arm.at_mono_ms.saturating_sub(crate::asyncrt::mono_ms()), |
| 1120 | ); |
| 1121 | let key = delays.insert(arm.clone(), delay); |
| 1122 | if let Some(displaced) = timers.install(&arm, key) { |
| 1123 | delays.remove(&displaced); |
| 1124 | } |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | /// The largest request body that a node accepts unless the operator lowers |
| 1129 | /// the limit. The value keeps the large git-pack ingress use case supported. |
| 1130 | pub const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1 << 30; |
| 1131 | |
| 1132 | /// The generation census `/state` reports beside the serving deployment. |
| 1133 | pub struct SwapCensus { |
| 1134 | /// Resident cells moving to the current generation right now. |
| 1135 | pub swapping: usize, |
| 1136 | /// Each resident cell and the generation its runtime started on. |
| 1137 | pub generations: Vec<(String, u64)>, |
| 1138 | } |
| 1139 | |
| 1140 | #[derive(Clone)] |
| 1141 | pub struct AppHandle { |
| 1142 | pub tx: mpsc::UnboundedSender<Message>, |
| 1143 | pub runtime: Option<RuntimeManager>, |
| 1144 | /// Asks the pointer watcher to adopt the current deployment now. Sending |
| 1145 | /// fails on a node with no pointer to watch, such as a local-script node. |
| 1146 | pub reload: crate::generation::ReloadSender, |
| 1147 | pub peer_http: reqwest::Client, |
| 1148 | pub peer_auth: Arc<PeerAuth>, |
| 1149 | pub advertise: String, |
| 1150 | pub websockets: mpsc::UnboundedSender<WebSocketFuture>, |
| 1151 | /// Whether the RPO=0 output gate is armed: hold a local write's response |
| 1152 | /// until its cell is proven durable. On by default; set `CELLD_OUTPUT_GATE=0` |
| 1153 | /// to acknowledge writes without proving them durable. The core and its DST |
| 1154 | /// are unconditional. |
| 1155 | pub output_gate: bool, |
| 1156 | /// Concurrent outbound WebSockets one cell may hold, for the refusal |
| 1157 | /// message; the core enforces it. |
| 1158 | pub max_outbound_websockets: usize, |
| 1159 | /// Set the instant a graceful shutdown begins, so `/.well-known/celld/health` reports |
| 1160 | /// unhealthy and a load balancer stops routing here before teardown. |
| 1161 | pub draining: Arc<std::sync::atomic::AtomicBool>, |
| 1162 | /// The one-shot fleet gate on the first health 200. A fresh process |
| 1163 | /// reports ready only after no peer donor is mid-handoff, or after a |
| 1164 | /// bounded wait, so a rolling update cannot advance faster than the |
| 1165 | /// fleet recovers. Fleet state never demotes readiness after the gate |
| 1166 | /// opens; peers reach owned cells directly regardless. |
| 1167 | pub fleet_ready: Arc<std::sync::atomic::AtomicBool>, |
| 1168 | /// Public requests which passed the shutdown gate and have not finished. |
| 1169 | /// This includes the complete top-level Worker call, so a cell write it |
| 1170 | /// goes on to make cannot outlive the pre-handoff durability boundary. |
| 1171 | pub public_in_flight: Arc<AtomicUsize>, |
| 1172 | /// Shell-side phases joined to the decision core's exact eviction pins. |
| 1173 | pub drain_pins: DrainPinRegistry, |
| 1174 | /// The log tier's follower store: this node holds peers' log fragments |
| 1175 | /// whatever its own durability posture. `None` without a bucket. |
| 1176 | pub follower: Option<Arc<crate::node_log::FollowerStore>>, |
| 1177 | /// Whether forwarded scheme and host headers can set `request.url`. |
| 1178 | /// The default is false because a direct client controls both headers. |
| 1179 | pub trust_forwarded_headers: bool, |
| 1180 | /// The maximum body size for public Worker ingress and direct Durable |
| 1181 | /// Object ingress. The same value must govern both entry points because a |
| 1182 | /// caller can choose either route for an ordinary Durable Object. |
| 1183 | pub max_request_body_bytes: usize, |
| 1184 | } |
| 1185 | |
| 1186 | impl AppHandle { |
| 1187 | pub async fn request(&self, cell: String) -> Result<Routed, RequestError> { |
| 1188 | self.request_with_mode(cell, false, None).await |
| 1189 | } |
| 1190 | |
| 1191 | /// Route one test request and retain which asynchronous seam produced the |
| 1192 | /// result. The shipping method keeps its compact public result, while this |
| 1193 | /// receipt prevents an inference from `NodeFenced` or an error string. |
| 1194 | #[cfg(all(test, celld_internal_tests))] |
| 1195 | pub(crate) async fn request_with_receipt_for_test( |
| 1196 | &self, |
| 1197 | cell: String, |
| 1198 | ) -> RequestPathReceiptForTest { |
| 1199 | let (request, outcome) = self.request_path(cell, false, None).await; |
| 1200 | match outcome { |
| 1201 | RequestPathOutcome::SubmissionFailure => { |
| 1202 | RequestPathReceiptForTest::SubmissionFailure { request } |
| 1203 | } |
| 1204 | RequestPathOutcome::ReplyChannelClosed => { |
| 1205 | RequestPathReceiptForTest::ReplyChannelClosed { request } |
| 1206 | } |
| 1207 | RequestPathOutcome::Returned(result) => RequestPathReceiptForTest::Returned { |
| 1208 | allocated_request: request, |
| 1209 | result: result.map(|routed| (routed.request, routed.route)), |
| 1210 | }, |
| 1211 | } |
| 1212 | } |
| 1213 | |
| 1214 | pub async fn capacity_request(&self, cell: String) -> Result<Routed, RequestError> { |
| 1215 | self.request_with_mode(cell, true, None).await |
| 1216 | } |
| 1217 | |
| 1218 | pub async fn websocket_request( |
| 1219 | &self, |
| 1220 | cell: String, |
| 1221 | websocket: u64, |
| 1222 | ) -> Result<Routed, RequestError> { |
| 1223 | self.request_with_mode(cell, false, Some(websocket)).await |
| 1224 | } |
| 1225 | |
| 1226 | async fn request_with_mode( |
| 1227 | &self, |
| 1228 | cell: String, |
| 1229 | capacity_handoff: bool, |
| 1230 | websocket: Option<u64>, |
| 1231 | ) -> Result<Routed, RequestError> { |
| 1232 | match self.request_path(cell, capacity_handoff, websocket).await.1 { |
| 1233 | RequestPathOutcome::Returned(result) => result, |
| 1234 | RequestPathOutcome::SubmissionFailure | RequestPathOutcome::ReplyChannelClosed => { |
| 1235 | Err(RequestError::NodeFenced) |
| 1236 | } |
| 1237 | } |
| 1238 | } |
| 1239 | |
| 1240 | async fn request_path( |
| 1241 | &self, |
| 1242 | cell: String, |
| 1243 | capacity_handoff: bool, |
| 1244 | websocket: Option<u64>, |
| 1245 | ) -> (u64, RequestPathOutcome) { |
| 1246 | let request = crate::asyncrt::next_core_request(); |
| 1247 | let (reply, receive) = oneshot::channel(); |
| 1248 | if self |
| 1249 | .tx |
| 1250 | .send(Message::Request { |
| 1251 | request, |
| 1252 | cell, |
| 1253 | capacity_handoff, |
| 1254 | handoff_accept: None, |
| 1255 | websocket, |
| 1256 | reply, |
| 1257 | }) |
| 1258 | .is_err() |
| 1259 | { |
| 1260 | return (request, RequestPathOutcome::SubmissionFailure); |
| 1261 | } |
| 1262 | let mut cancel = RouteCancelGuard::new(self.tx.clone(), request); |
| 1263 | let outcome = match receive.await { |
| 1264 | Ok(result) => RequestPathOutcome::Returned(result), |
| 1265 | Err(_) => RequestPathOutcome::ReplyChannelClosed, |
| 1266 | }; |
| 1267 | cancel.disarm(); |
| 1268 | (request, outcome) |
| 1269 | } |
| 1270 | |
| 1271 | /// Acquire a released cell without materializing its runtime. The donor's |
| 1272 | /// final snapshot makes a later demand-driven restore authoritative, and |
| 1273 | /// avoiding an eager restore keeps a fleet restart from becoming a cold |
| 1274 | /// start storm. |
| 1275 | pub async fn accept_handoff( |
| 1276 | &self, |
| 1277 | cell: String, |
| 1278 | released_epoch: u64, |
| 1279 | ) -> Result<HandoffAttempt, RequestError> { |
| 1280 | let request = crate::asyncrt::next_core_request(); |
| 1281 | let (route_reply, mut route_receive) = oneshot::channel(); |
| 1282 | let (accept_reply, mut accept_receive) = oneshot::channel(); |
| 1283 | if self |
| 1284 | .tx |
| 1285 | .send(Message::Request { |
| 1286 | request, |
| 1287 | cell: cell.clone(), |
| 1288 | capacity_handoff: true, |
| 1289 | handoff_accept: Some(HandoffAcceptWaiter { |
| 1290 | released_epoch, |
| 1291 | reply: accept_reply, |
| 1292 | }), |
| 1293 | websocket: None, |
| 1294 | reply: route_reply, |
| 1295 | }) |
| 1296 | .is_err() |
| 1297 | { |
| 1298 | return Err(RequestError::NodeFenced); |
| 1299 | } |
| 1300 | let mut cancel = RouteCancelGuard::new(self.tx.clone(), request); |
| 1301 | let result = crate::asyncrt::select_biased! { |
| 1302 | "a completed route wins a tie so current ownership precedes the accept acknowledgement"; |
| 1303 | routed = &mut route_receive => match routed |
| 1304 | .unwrap_or(Err(RequestError::NodeFenced))? |
| 1305 | { |
| 1306 | Routed { |
| 1307 | request, |
| 1308 | route: Route::Local, |
| 1309 | } => { |
| 1310 | // A repeated request can find the cell published already. |
| 1311 | drop(self.activity(request, cell.clone())); |
| 1312 | self.resident_epoch(cell) |
| 1313 | .await |
| 1314 | .filter(|epoch| *epoch > released_epoch) |
| 1315 | .map(|epoch| HandoffAttempt::Accepted(AdoptedCell { |
| 1316 | node: self.peer_auth.source().to_string(), |
| 1317 | addr: self.advertise.clone(), |
| 1318 | epoch, |
| 1319 | peer_protocol: peer_auth::PROTOCOL_VERSION, |
| 1320 | })) |
| 1321 | .ok_or(RequestError::AcquireFailed) |
| 1322 | } |
| 1323 | Routed { |
| 1324 | route: Route::Remote { |
| 1325 | node, |
| 1326 | addr, |
| 1327 | epoch, |
| 1328 | peer_protocol, |
| 1329 | }, |
| 1330 | .. |
| 1331 | } => Ok(HandoffAttempt::CurrentOwner(AdoptedCell { |
| 1332 | node, |
| 1333 | addr, |
| 1334 | epoch, |
| 1335 | peer_protocol, |
| 1336 | })), |
| 1337 | }, |
| 1338 | accepted = &mut accept_receive => accepted |
| 1339 | .map(HandoffAttempt::Accepted) |
| 1340 | .map_err(|_| RequestError::NodeFenced), |
| 1341 | }; |
| 1342 | // The ownership acknowledgement deliberately leaves no route waiter: |
| 1343 | // real traffic, not this synthetic request, starts materialization. |
| 1344 | cancel.disarm(); |
| 1345 | let _ = self.tx.send(Message::CancelRoute { request }); |
| 1346 | result |
| 1347 | } |
| 1348 | |
| 1349 | // Orphaned by the always-pool Worker entry below. What remains of the |
| 1350 | // landing-cell machinery -- this, `Message::WorkerRequest`, `WorkerRouted`, |
| 1351 | // `fetch_worker_on_cell`, `CellJob::WorkerFetch`, and the logic |
| 1352 | // `worker_request` -- is kept together so it can be removed in one piece |
| 1353 | // rather than unpicked here. The in-isolate dispatch it was paired with is |
| 1354 | // already gone, and with it the gate that path needed. |
| 1355 | #[allow(dead_code)] |
| 1356 | async fn worker_route(&self) -> anyhow::Result<WorkerRouted> { |
| 1357 | let (reply, receive) = oneshot::channel(); |
| 1358 | self.tx |
| 1359 | .send(Message::WorkerRequest { reply }) |
| 1360 | .map_err(|_| anyhow::anyhow!("core stopped before Worker routing"))?; |
| 1361 | receive |
| 1362 | .await |
| 1363 | .context("core stopped while routing Worker request") |
| 1364 | } |
| 1365 | |
| 1366 | pub async fn fetch_worker( |
| 1367 | &self, |
| 1368 | url: String, |
| 1369 | method: String, |
| 1370 | body: crate::js::RequestBody, |
| 1371 | headers: Vec<(String, String)>, |
| 1372 | connection: ConnectionWorkerRequests, |
| 1373 | ) -> anyhow::Result<HttpResponse> { |
| 1374 | let runtime = self |
| 1375 | .runtime |
| 1376 | .as_ref() |
| 1377 | .ok_or_else(|| anyhow::anyhow!("Worker runtime unavailable"))?; |
| 1378 | // Admission happens in the runtime, against the pool that actually |
| 1379 | // holds the requests. It used to be duplicated here against an empty |
| 1380 | // `PoolLoad` — a snapshot with no isolates and no affiliations, which |
| 1381 | // could only ever answer "yes" once pressure stopped refusing |
| 1382 | // outright. A decision made against a fake reading is not a fast path. |
| 1383 | let js_request = crate::js::next_request_id(); |
| 1384 | // The Worker entry is stateless — run it in the pool, always. Routing it |
| 1385 | // to a "landing cell" existed only to make an `env.NS.get(id)` call |
| 1386 | // resolve inline; but a cell runs one fetch at a time, so under any real |
| 1387 | // concurrency the entry can't be on the cell it calls, and the routing |
| 1388 | // round-trip is paid for nothing — on top of the DO call's own routing. |
| 1389 | // A DO call reaches its owning cell (with fencing and the output gate) on |
| 1390 | // the host path, so one routing round-trip per request, never two. |
| 1391 | let mut abort = IngressAbortGuard::new(js_request, connection); |
| 1392 | let result = runtime |
| 1393 | .fetch_worker_pool(url, method, body, headers, js_request) |
| 1394 | .await; |
| 1395 | abort.disarm(); |
| 1396 | result |
| 1397 | } |
| 1398 | |
| 1399 | pub fn activity(&self, request: u64, cell: String) -> ActivityGuard { |
| 1400 | self.activity_for(request, cell, None, "local") |
| 1401 | } |
| 1402 | |
| 1403 | pub fn activity_for( |
| 1404 | &self, |
| 1405 | request: u64, |
| 1406 | cell: String, |
| 1407 | request_id: Option<crate::js::RequestId>, |
| 1408 | origin: &'static str, |
| 1409 | ) -> ActivityGuard { |
| 1410 | let cancellation = self.drain_pins.begin(request, request_id, origin); |
| 1411 | ActivityGuard { |
| 1412 | tx: self.tx.clone(), |
| 1413 | request, |
| 1414 | runtime: self.runtime.clone(), |
| 1415 | cell, |
| 1416 | drain_pins: self.drain_pins.clone(), |
| 1417 | cancellation, |
| 1418 | } |
| 1419 | } |
| 1420 | |
| 1421 | /// Hold a response until every write it can reveal is durable. A write |
| 1422 | /// supplies its ending position. A read supplies `None` and trails the |
| 1423 | /// newest outstanding write on the same cell, if one exists. |
| 1424 | pub async fn gate_output( |
| 1425 | &self, |
| 1426 | request: u64, |
| 1427 | channel: Channel, |
| 1428 | position: Option<u64>, |
| 1429 | ) -> Result<(), RequestError> { |
| 1430 | match self.gate_output_path(request, channel, position).await { |
| 1431 | OutputGateOutcome::Returned(result) => result, |
| 1432 | OutputGateOutcome::SubmissionFailure | OutputGateOutcome::ReplyChannelClosed => { |
| 1433 | Err(RequestError::NodeFenced) |
| 1434 | } |
| 1435 | } |
| 1436 | } |
| 1437 | |
| 1438 | async fn gate_output_path( |
| 1439 | &self, |
| 1440 | request: u64, |
| 1441 | channel: Channel, |
| 1442 | position: Option<u64>, |
| 1443 | ) -> OutputGateOutcome { |
| 1444 | let started_mono_ms = crate::asyncrt::mono_ms(); |
| 1445 | let (reply, receive) = oneshot::channel(); |
| 1446 | if self |
| 1447 | .tx |
| 1448 | .send(Message::Output { |
| 1449 | request, |
| 1450 | channel, |
| 1451 | position, |
| 1452 | reply, |
| 1453 | }) |
| 1454 | .is_err() |
| 1455 | { |
| 1456 | return OutputGateOutcome::SubmissionFailure; |
| 1457 | } |
| 1458 | let outcome = match receive.await { |
| 1459 | Ok(result) => OutputGateOutcome::Returned(result), |
| 1460 | Err(_) => OutputGateOutcome::ReplyChannelClosed, |
| 1461 | }; |
| 1462 | tracing::debug!( |
| 1463 | target: "timing", |
| 1464 | event = "gate_write_timing", |
| 1465 | request, |
| 1466 | total_us = mono_elapsed_us(started_mono_ms), |
| 1467 | "output gate resolved" |
| 1468 | ); |
| 1469 | outcome |
| 1470 | } |
| 1471 | |
| 1472 | /// Run one test output gate without collapsing its two channel failures |
| 1473 | /// into a returned engine rejection. The request travels in every arm, so |
| 1474 | /// a consumer cannot attach the receipt to another caller. |
| 1475 | #[cfg(all(test, celld_internal_tests))] |
| 1476 | pub(crate) async fn gate_output_with_receipt_for_test( |
| 1477 | &self, |
| 1478 | request: u64, |
| 1479 | channel: Channel, |
| 1480 | position: Option<u64>, |
| 1481 | ) -> OutputGateReceiptForTest { |
| 1482 | match self.gate_output_path(request, channel, position).await { |
| 1483 | OutputGateOutcome::SubmissionFailure => { |
| 1484 | OutputGateReceiptForTest::SubmissionFailure { request } |
| 1485 | } |
| 1486 | OutputGateOutcome::ReplyChannelClosed => { |
| 1487 | OutputGateReceiptForTest::ReplyChannelClosed { request } |
| 1488 | } |
| 1489 | OutputGateOutcome::Returned(result) => { |
| 1490 | OutputGateReceiptForTest::Returned { request, result } |
| 1491 | } |
| 1492 | } |
| 1493 | } |
| 1494 | |
| 1495 | pub async fn gate_write(&self, request: u64, position: u64) -> Result<(), RequestError> { |
| 1496 | self.gate_output(request, Channel::Response, Some(position)) |
| 1497 | .await |
| 1498 | } |
| 1499 | |
| 1500 | /// Hand a finished `webSocketMessage`'s frames to the cell's output gate. |
| 1501 | /// Awaited so the request stays pinned until the actor has registered the |
| 1502 | /// gate (the core reads the still-active request when it opens); frames flush |
| 1503 | /// or fail asynchronously as durability resolves, not here. |
| 1504 | pub async fn ws_output( |
| 1505 | &self, |
| 1506 | request: u64, |
| 1507 | scope: String, |
| 1508 | frames: Vec<(u64, WsOut)>, |
| 1509 | write_position: Option<u64>, |
| 1510 | ) { |
| 1511 | let (reply, receive) = oneshot::channel(); |
| 1512 | if self |
| 1513 | .tx |
| 1514 | .send(Message::WsOutput { |
| 1515 | request, |
| 1516 | scope, |
| 1517 | frames, |
| 1518 | write_position, |
| 1519 | reply, |
| 1520 | }) |
| 1521 | .is_ok() |
| 1522 | { |
| 1523 | let _ = receive.await; |
| 1524 | } |
| 1525 | } |
| 1526 | |
| 1527 | pub async fn websocket_opened( |
| 1528 | &self, |
| 1529 | cell: String, |
| 1530 | websocket: u64, |
| 1531 | kind: WebSocketKind, |
| 1532 | ) -> anyhow::Result<()> { |
| 1533 | let (reply, receive) = oneshot::channel(); |
| 1534 | self.tx |
| 1535 | .send(Message::WebSocketOpened { |
| 1536 | cell, |
| 1537 | websocket, |
| 1538 | kind, |
| 1539 | reply, |
| 1540 | }) |
| 1541 | .map_err(|_| anyhow::anyhow!("core stopped before WebSocket opened"))?; |
| 1542 | let held = receive |
| 1543 | .await |
| 1544 | .context("core stopped while opening WebSocket")?; |
| 1545 | anyhow::ensure!( |
| 1546 | held, |
| 1547 | "outbound WebSocket refused: a cell may hold at most {}, and a node \ |
| 1548 | may pin at most {}% of its residency ceiling", |
| 1549 | self.max_outbound_websockets, |
| 1550 | celld_logic::pressure::MAX_OUTBOUND_PIN_PERCENT, |
| 1551 | ); |
| 1552 | Ok(()) |
| 1553 | } |
| 1554 | |
| 1555 | pub fn websocket_closed(&self, cell: String, websocket: u64) { |
| 1556 | let _ = self.tx.send(Message::WebSocketClosed { cell, websocket }); |
| 1557 | } |
| 1558 | |
| 1559 | pub async fn evict(&self, cell: String) { |
| 1560 | let (reply, receive) = oneshot::channel(); |
| 1561 | if self.tx.send(Message::Evict { cell, reply }).is_ok() { |
| 1562 | let _ = receive.await; |
| 1563 | } |
| 1564 | } |
| 1565 | |
| 1566 | pub async fn invalidate_remote(&self, cell: String, node: String, epoch: u64) { |
| 1567 | let (reply, receive) = oneshot::channel(); |
| 1568 | if self |
| 1569 | .tx |
| 1570 | .send(Message::InvalidateRemote { |
| 1571 | cell, |
| 1572 | node, |
| 1573 | epoch, |
| 1574 | reply, |
| 1575 | }) |
| 1576 | .is_ok() |
| 1577 | { |
| 1578 | let _ = receive.await; |
| 1579 | } |
| 1580 | } |
| 1581 | |
| 1582 | pub async fn snapshot(&self) -> String { |
| 1583 | let (reply, receive) = oneshot::channel(); |
| 1584 | if self.tx.send(Message::Snapshot { reply }).is_err() { |
| 1585 | return "{\"error\":\"actor_stopped\"}".into(); |
| 1586 | } |
| 1587 | let Ok((state, pins, census)) = receive.await else { |
| 1588 | return "{\"error\":\"actor_stopped\"}".into(); |
| 1589 | }; |
| 1590 | let pins = self.drain_pins.snapshot(pins); |
| 1591 | let Ok(mut state) = serde_json::from_str::<serde_json::Value>(&state) else { |
| 1592 | return state; |
| 1593 | }; |
| 1594 | if !pins.is_empty() { |
| 1595 | state["drainPins"] = |
| 1596 | serde_json::to_value(pins).unwrap_or_else(|_| serde_json::json!([])); |
| 1597 | } |
| 1598 | // Which deployment this node serves, and which ones it is still |
| 1599 | // draining. Nothing else in the process records the version, so |
| 1600 | // this is how an operator learns whether a deploy took. |
| 1601 | if let Some(runtime) = &self.runtime { |
| 1602 | let generation = runtime.generation(); |
| 1603 | state["deployment"] = serde_json::json!({ |
| 1604 | "version": generation.version(), |
| 1605 | "prefix": generation.prefix(), |
| 1606 | "generation": generation.id(), |
| 1607 | "draining": runtime |
| 1608 | .draining_generations() |
| 1609 | .into_iter() |
| 1610 | .map(|(id, version)| serde_json::json!({"generation": id, "version": version})) |
| 1611 | .collect::<Vec<_>>(), |
| 1612 | // Resident cells moving to the current generation right now, |
| 1613 | // and the generation each resident cell runs: the two numbers |
| 1614 | // an operator watches while a deployment converges. |
| 1615 | "swapping": census.swapping, |
| 1616 | "cells": census |
| 1617 | .generations |
| 1618 | .into_iter() |
| 1619 | .map(|(cell, generation)| (cell, serde_json::Value::from(generation))) |
| 1620 | .collect::<serde_json::Map<_, _>>(), |
| 1621 | }); |
| 1622 | } |
| 1623 | state.to_string() |
| 1624 | } |
| 1625 | |
| 1626 | pub fn is_draining(&self) -> bool { |
| 1627 | self.draining.load(std::sync::atomic::Ordering::Relaxed) |
| 1628 | } |
| 1629 | |
| 1630 | pub fn fleet_ready(&self) -> bool { |
| 1631 | self.fleet_ready.load(std::sync::atomic::Ordering::Relaxed) |
| 1632 | } |
| 1633 | |
| 1634 | /// Atomically cross the public shutdown gate. The second draining read |
| 1635 | /// closes the race where shutdown stores the flag between the first read |
| 1636 | /// and the counter increment: that request backs out before user code runs. |
| 1637 | pub fn admit_public(&self) -> Option<PublicRequestGuard> { |
| 1638 | if self.draining.load(Ordering::SeqCst) { |
| 1639 | return None; |
| 1640 | } |
| 1641 | self.public_in_flight.fetch_add(1, Ordering::SeqCst); |
| 1642 | if self.draining.load(Ordering::SeqCst) { |
| 1643 | self.public_in_flight.fetch_sub(1, Ordering::SeqCst); |
| 1644 | return None; |
| 1645 | } |
| 1646 | Some(PublicRequestGuard { |
| 1647 | in_flight: self.public_in_flight.clone(), |
| 1648 | }) |
| 1649 | } |
| 1650 | |
| 1651 | pub fn public_in_flight(&self) -> usize { |
| 1652 | self.public_in_flight.load(Ordering::SeqCst) |
| 1653 | } |
| 1654 | |
| 1655 | /// A dead actor has nothing left to hand off, so channel failure |
| 1656 | /// reports drained rather than wedging shutdown. |
| 1657 | pub async fn drain_status(&self) -> DrainStatus { |
| 1658 | let (reply, receive) = oneshot::channel(); |
| 1659 | if self.tx.send(Message::Drained { reply }).is_err() { |
| 1660 | return DrainStatus::default(); |
| 1661 | } |
| 1662 | receive.await.unwrap_or_default() |
| 1663 | } |
| 1664 | |
| 1665 | pub async fn healthy(&self) -> bool { |
| 1666 | let (reply, receive) = oneshot::channel(); |
| 1667 | if self.tx.send(Message::Health { reply }).is_err() { |
| 1668 | return false; |
| 1669 | } |
| 1670 | receive.await.unwrap_or(false) |
| 1671 | } |
| 1672 | |
| 1673 | pub async fn presence(&self) -> Option<celld_logic::PresenceSnapshot> { |
| 1674 | let (reply, receive) = oneshot::channel(); |
| 1675 | self.tx.send(Message::Presence { reply }).ok()?; |
| 1676 | receive.await.ok() |
| 1677 | } |
| 1678 | |
| 1679 | async fn resident_epoch(&self, cell: String) -> Option<u64> { |
| 1680 | let (reply, receive) = oneshot::channel(); |
| 1681 | self.tx.send(Message::ResidentEpoch { cell, reply }).ok()?; |
| 1682 | receive.await.ok().flatten() |
| 1683 | } |
| 1684 | } |
| 1685 | |
| 1686 | /// One cell's WebSocket output gate: an ordered queue of write barriers. |
| 1687 | #[derive(Default)] |
| 1688 | struct WsGate { |
| 1689 | barriers: VecDeque<WsBarrier>, |
| 1690 | } |
| 1691 | |
| 1692 | /// One `webSocketMessage` batch and the outbound frames held behind it. |
| 1693 | /// `settled` is `None` while the verdict is outstanding, `Some(true)` once the |
| 1694 | /// core proved every write the frames can reveal (they may flush when this |
| 1695 | /// barrier reaches the front), `Some(false)` on failure (the gate breaks). |
| 1696 | /// |
| 1697 | /// Every batch gets its own barrier, including one that wrote nothing: the core |
| 1698 | /// decides what it trails, because only the core knows the writes other |
| 1699 | /// channels have outstanding on this cell. The queue keeps them in arrival |
| 1700 | /// order and drains only from the front, so a barrier settled early cannot |
| 1701 | /// overtake one still waiting. |
| 1702 | struct WsBarrier { |
| 1703 | request: u64, |
| 1704 | settled: Option<bool>, |
| 1705 | frames: Vec<(u64, WsOut)>, |
| 1706 | } |
| 1707 | |
| 1708 | /// The shell identity for one output held by the core. |
| 1709 | /// |
| 1710 | /// One request can hold output on multiple channels. Keeping both values in |
| 1711 | /// the map key prevents a later channel from replacing the first channel's |
| 1712 | /// waiter before the core releases it. |
| 1713 | #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] |
| 1714 | struct HeldOutputKey { |
| 1715 | request: u64, |
| 1716 | channel: Channel, |
| 1717 | } |
| 1718 | |
| 1719 | impl HeldOutputKey { |
| 1720 | const fn websocket(request: u64) -> Self { |
| 1721 | Self { |
| 1722 | request, |
| 1723 | channel: Channel::WsHibernatable, |
| 1724 | } |
| 1725 | } |
| 1726 | } |
| 1727 | |
| 1728 | pub struct Actor { |
| 1729 | state: ActorState, |
| 1730 | pub ownership: Ownership, |
| 1731 | peer_http: reqwest::Client, |
| 1732 | peer_auth: Arc<PeerAuth>, |
| 1733 | paced_handoff: bool, |
| 1734 | handoff_directory: Arc<Mutex<HandoffDirectory>>, |
| 1735 | host: Option<CellHost>, |
| 1736 | drain_pins: DrainPinRegistry, |
| 1737 | /// Per-cell handoff pipeline timings, one entry per quiesce nomination. |
| 1738 | /// Each phase is measured from effect dispatch to its answering event, |
| 1739 | /// so queue time counts because that is the serial cost of the drain. |
| 1740 | handoff_timings: HashMap<String, HandoffCellTiming>, |
| 1741 | /// The in-flight pipeline step for each timed handoff operation. |
| 1742 | handoff_phase_ops: HashMap<OpId, (String, HandoffPhase, u64)>, |
| 1743 | /// The node-log manager, filled at boot once the log tier exists: |
| 1744 | /// the executor's RecoverNodeLog effect runs through it directly. |
| 1745 | pub node_log: Arc<std::sync::Mutex<Option<Arc<crate::node_log::NodeLogManager>>>>, |
| 1746 | region: String, |
| 1747 | pending: BTreeMap<u64, oneshot::Sender<Result<Routed, RequestError>>>, |
| 1748 | request_cells: BTreeMap<u64, String>, |
| 1749 | handoff_accepts: BTreeMap<u64, (String, HandoffAcceptWaiter)>, |
| 1750 | route_timings: BTreeMap<String, CellRouteTiming>, |
| 1751 | pending_workers: BTreeMap<u64, oneshot::Sender<WorkerRouted>>, |
| 1752 | eviction_waiters: BTreeMap<String, Vec<oneshot::Sender<()>>>, |
| 1753 | durability_waiters: BTreeMap<u64, (String, Vec<oneshot::Sender<()>>)>, |
| 1754 | eviction_stops: BTreeMap<u64, Vec<oneshot::Sender<()>>>, |
| 1755 | /// Outputs held by the gate, keyed by request and channel. Every output but |
| 1756 | /// a captured `WsHibernatable` frame waits here for the core's `Release`. |
| 1757 | gated_responses: BTreeMap<HeldOutputKey, oneshot::Sender<Result<(), RequestError>>>, |
| 1758 | /// Per-cell WebSocket output gate: a FIFO of write barriers, each holding |
| 1759 | /// the outbound frames produced up to it. The front drains in write order as |
| 1760 | /// durability proves, so no client ever sees a frame that trails an |
| 1761 | /// unproven write (the Cloudflare per-object output gate). |
| 1762 | ws_gates: BTreeMap<String, WsGate>, |
| 1763 | /// Gated `webSocketMessage` batches map each request-channel pair to its |
| 1764 | /// cell, so `Release` routes to the barrier queue rather than a oneshot. |
| 1765 | ws_gated: BTreeMap<HeldOutputKey, String>, |
| 1766 | published: BTreeSet<String>, |
| 1767 | fail_publish_once: bool, |
| 1768 | publishes: u64, |
| 1769 | stops: u64, |
| 1770 | pub lease_spec: NodeLeaseSpec, |
| 1771 | /// Whether to re-check every core invariant after every event. |
| 1772 | /// |
| 1773 | /// The check is a full scan of the cell table, so its cost grows with |
| 1774 | /// residency: roughly 800us per event at ten thousand resident cells, |
| 1775 | /// which would cap a busy node at about a thousand events a second in |
| 1776 | /// assertion code alone. It is a model-checking assertion, and the place |
| 1777 | /// it earns its keep is simulation, which can afford to run it after |
| 1778 | /// every event over far more schedules than production will ever see. |
| 1779 | /// Debug builds keep it. Release builds rely on the deterministic model, |
| 1780 | /// because this full-table scan is too expensive for production traffic. |
| 1781 | validate_invariants: bool, |
| 1782 | /// The counters peers rank this node by, when there is a bucket to |
| 1783 | /// publish them to. |
| 1784 | live_load: Option<Arc<crate::ownership_store::LiveLoad>>, |
| 1785 | /// The shed reason last reported to the log, so a latch that holds for |
| 1786 | /// minutes is reported once rather than on every sample. |
| 1787 | logged_shed_reason: Option<&'static str>, |
| 1788 | fence: mpsc::UnboundedSender<i32>, |
| 1789 | timer_slots: TimerSlots<()>, |
| 1790 | started: bool, |
| 1791 | preserving: bool, |
| 1792 | } |
| 1793 | |
| 1794 | /// One handoff pipeline step whose dispatch-to-completion time is measured. |
| 1795 | #[derive(Clone, Copy, PartialEq)] |
| 1796 | enum HandoffPhase { |
| 1797 | Durability, |
| 1798 | Stop, |
| 1799 | Release, |
| 1800 | Adopt, |
| 1801 | } |
| 1802 | |
| 1803 | /// The accumulating phase durations for one quiescing cell's handoff. |
| 1804 | struct HandoffCellTiming { |
| 1805 | nominated_mono_ms: u64, |
| 1806 | quiesce_us: Option<u64>, |
| 1807 | durability_us: Option<u64>, |
| 1808 | stop_us: Option<u64>, |
| 1809 | release_us: Option<u64>, |
| 1810 | } |
| 1811 | |
| 1812 | #[derive(Default)] |
| 1813 | struct HandoffDirectory { |
| 1814 | sampled_at_mono_ms: Option<u64>, |
| 1815 | peers: Vec<CapacityPeer>, |
| 1816 | } |
| 1817 | |
| 1818 | const HANDOFF_DIRECTORY_MAX_AGE_MS: u64 = 500; |
| 1819 | const HANDOFF_RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(250); |
| 1820 | |
| 1821 | /// A deterministic final tie-break spreads one concurrent batch across peers |
| 1822 | /// whose published load is equal. The load remains the primary ranking input. |
| 1823 | fn handoff_tie_break(cell: &str, node: &str) -> u64 { |
| 1824 | let mut hash = 0xcbf2_9ce4_8422_2325_u64; |
| 1825 | for byte in cell |
| 1826 | .as_bytes() |
| 1827 | .iter() |
| 1828 | .copied() |
| 1829 | .chain(std::iter::once(0xff)) |
| 1830 | .chain(node.as_bytes().iter().copied()) |
| 1831 | { |
| 1832 | hash ^= u64::from(byte); |
| 1833 | hash = hash.wrapping_mul(0x0000_0100_0000_01b3); |
| 1834 | } |
| 1835 | hash |
| 1836 | } |
| 1837 | |
| 1838 | async fn handoff_candidates( |
| 1839 | ownership: &Ownership, |
| 1840 | directory: &Arc<Mutex<HandoffDirectory>>, |
| 1841 | source: &str, |
| 1842 | cell: &str, |
| 1843 | ) -> Result<Vec<CapacityPeer>, Failure> { |
| 1844 | let mut directory = directory.lock().await; |
| 1845 | let now_mono_ms = crate::asyncrt::mono_ms(); |
| 1846 | let stale = directory |
| 1847 | .sampled_at_mono_ms |
| 1848 | .is_none_or(|sampled| now_mono_ms.saturating_sub(sampled) >= HANDOFF_DIRECTORY_MAX_AGE_MS); |
| 1849 | if stale { |
| 1850 | directory.peers = ownership.read_capacity_peers().await?; |
| 1851 | directory.sampled_at_mono_ms = Some(now_mono_ms); |
| 1852 | } |
| 1853 | let current_ms = now_ms(); |
| 1854 | let mut peers: Vec<_> = directory |
| 1855 | .peers |
| 1856 | .iter() |
| 1857 | .filter(|peer| { |
| 1858 | peer.node != source |
| 1859 | && peer.expires_ms > current_ms |
| 1860 | && !peer.addr.is_empty() |
| 1861 | && peer.peer_protocol == peer_auth::PROTOCOL_VERSION |
| 1862 | && peer.sampled_ms != 0 |
| 1863 | && !peer.pressured |
| 1864 | && peer.paced_handoff |
| 1865 | }) |
| 1866 | .cloned() |
| 1867 | .collect(); |
| 1868 | peers.sort_by_key(|peer| { |
| 1869 | ( |
| 1870 | peer.resident_cells, |
| 1871 | peer.host_websockets, |
| 1872 | peer.rss_bytes, |
| 1873 | handoff_tie_break(cell, &peer.node), |
| 1874 | peer.node.clone(), |
| 1875 | ) |
| 1876 | }); |
| 1877 | Ok(peers) |
| 1878 | } |
| 1879 | |
| 1880 | pub enum HandoffAttempt { |
| 1881 | Accepted(AdoptedCell), |
| 1882 | CurrentOwner(AdoptedCell), |
| 1883 | Refused, |
| 1884 | } |
| 1885 | |
| 1886 | async fn request_peer_handoff( |
| 1887 | http: &reqwest::Client, |
| 1888 | auth: &PeerAuth, |
| 1889 | peer: &AdoptedCell, |
| 1890 | request: &HandoffRequest, |
| 1891 | ) -> anyhow::Result<HandoffAttempt> { |
| 1892 | let path = "/peer/handoff"; |
| 1893 | let body = serde_json::to_vec(request)?; |
| 1894 | let outbound = auth.sign( |
| 1895 | http.post(format!("http://{}{path}", peer.addr)), |
| 1896 | "POST", |
| 1897 | path, |
| 1898 | &body, |
| 1899 | &peer.node, |
| 1900 | )?; |
| 1901 | let response = outbound.body(body).send().await?; |
| 1902 | peer_auth::validate_response(response.headers())?; |
| 1903 | let status = response.status(); |
| 1904 | let response: HandoffResponse = match response.json().await { |
| 1905 | Ok(response) => response, |
| 1906 | Err(_) => return Ok(HandoffAttempt::Refused), |
| 1907 | }; |
| 1908 | let owner = AdoptedCell { |
| 1909 | node: response.node, |
| 1910 | addr: response.addr, |
| 1911 | epoch: response.epoch, |
| 1912 | peer_protocol: response.peer_protocol, |
| 1913 | }; |
| 1914 | if status == reqwest::StatusCode::OK && response.published { |
| 1915 | Ok(HandoffAttempt::Accepted(owner)) |
| 1916 | } else if status == reqwest::StatusCode::CONFLICT && !response.published { |
| 1917 | Ok(HandoffAttempt::CurrentOwner(owner)) |
| 1918 | } else { |
| 1919 | Ok(HandoffAttempt::Refused) |
| 1920 | } |
| 1921 | } |
| 1922 | |
| 1923 | pub struct AdmissionLimits { |
| 1924 | pub resident: usize, |
| 1925 | pub activations: usize, |
| 1926 | pub evictions: usize, |
| 1927 | pub releases: usize, |
| 1928 | } |
| 1929 | |
| 1930 | pub struct ActorIdentity { |
| 1931 | pub node: String, |
| 1932 | pub advertise: String, |
| 1933 | pub region: String, |
| 1934 | } |
| 1935 | |
| 1936 | pub struct ActorServices { |
| 1937 | pub runtime: Option<RuntimeManager>, |
| 1938 | pub drain_pins: DrainPinRegistry, |
| 1939 | pub ownership: Option<Ownership>, |
| 1940 | pub peer_http: reqwest::Client, |
| 1941 | pub peer_auth: Arc<PeerAuth>, |
| 1942 | pub paced_handoff: bool, |
| 1943 | } |
| 1944 | |
| 1945 | struct ActorHostServices { |
| 1946 | host: Option<CellHost>, |
| 1947 | drain_pins: DrainPinRegistry, |
| 1948 | ownership: Option<Ownership>, |
| 1949 | peer_http: reqwest::Client, |
| 1950 | peer_auth: Arc<PeerAuth>, |
| 1951 | paced_handoff: bool, |
| 1952 | } |
| 1953 | |
| 1954 | impl Actor { |
| 1955 | pub async fn from_environment( |
| 1956 | limits: AdmissionLimits, |
| 1957 | fail_publish_once: bool, |
| 1958 | fence: mpsc::UnboundedSender<i32>, |
| 1959 | runtime: Option<RuntimeManager>, |
| 1960 | ownership: Option<Ownership>, |
| 1961 | identity: ActorIdentity, |
| 1962 | resume_generation: Option<String>, |
| 1963 | ) -> anyhow::Result<Self> { |
| 1964 | let peer_auth = Arc::new(PeerAuth::new([0; 32], identity.node.clone())?); |
| 1965 | Self::from_environment_with_cell_host( |
| 1966 | limits, |
| 1967 | fail_publish_once, |
| 1968 | fence, |
| 1969 | ActorHostServices { |
| 1970 | host: runtime.map(CellHost::V8), |
| 1971 | drain_pins: DrainPinRegistry::default(), |
| 1972 | ownership, |
| 1973 | peer_http: reqwest::Client::new(), |
| 1974 | peer_auth, |
| 1975 | paced_handoff: false, |
| 1976 | }, |
| 1977 | identity, |
| 1978 | resume_generation, |
| 1979 | ) |
| 1980 | .await |
| 1981 | } |
| 1982 | |
| 1983 | pub async fn from_environment_with_services( |
| 1984 | limits: AdmissionLimits, |
| 1985 | fail_publish_once: bool, |
| 1986 | fence: mpsc::UnboundedSender<i32>, |
| 1987 | services: ActorServices, |
| 1988 | identity: ActorIdentity, |
| 1989 | resume_generation: Option<String>, |
| 1990 | ) -> anyhow::Result<Self> { |
| 1991 | let ActorServices { |
| 1992 | runtime, |
| 1993 | drain_pins, |
| 1994 | ownership, |
| 1995 | peer_http, |
| 1996 | peer_auth, |
| 1997 | paced_handoff, |
| 1998 | } = services; |
| 1999 | Self::from_environment_with_cell_host( |
| 2000 | limits, |
| 2001 | fail_publish_once, |
| 2002 | fence, |
| 2003 | ActorHostServices { |
| 2004 | host: runtime.map(CellHost::V8), |
| 2005 | drain_pins, |
| 2006 | ownership, |
| 2007 | peer_http, |
| 2008 | peer_auth, |
| 2009 | paced_handoff, |
| 2010 | }, |
| 2011 | identity, |
| 2012 | resume_generation, |
| 2013 | ) |
| 2014 | .await |
| 2015 | } |
| 2016 | |
| 2017 | #[cfg(all(test, celld_internal_tests))] |
| 2018 | pub(crate) async fn from_environment_with_scripted_host( |
| 2019 | limits: AdmissionLimits, |
| 2020 | fail_publish_once: bool, |
| 2021 | fence: mpsc::UnboundedSender<i32>, |
| 2022 | host: crate::conformance_sim_cell_host::SimCellHost, |
| 2023 | ownership: Option<Ownership>, |
| 2024 | identity: ActorIdentity, |
| 2025 | resume_generation: Option<String>, |
| 2026 | ) -> anyhow::Result<Self> { |
| 2027 | let peer_auth = Arc::new(PeerAuth::new([0; 32], identity.node.clone())?); |
| 2028 | Self::from_environment_with_cell_host( |
| 2029 | limits, |
| 2030 | fail_publish_once, |
| 2031 | fence, |
| 2032 | ActorHostServices { |
| 2033 | host: Some(CellHost::Scripted(host)), |
| 2034 | drain_pins: DrainPinRegistry::default(), |
| 2035 | ownership, |
| 2036 | peer_http: reqwest::Client::new(), |
| 2037 | peer_auth, |
| 2038 | paced_handoff: false, |
| 2039 | }, |
| 2040 | identity, |
| 2041 | resume_generation, |
| 2042 | ) |
| 2043 | .await |
| 2044 | } |
| 2045 | |
| 2046 | async fn from_environment_with_cell_host( |
| 2047 | limits: AdmissionLimits, |
| 2048 | fail_publish_once: bool, |
| 2049 | fence: mpsc::UnboundedSender<i32>, |
| 2050 | services: ActorHostServices, |
| 2051 | identity: ActorIdentity, |
| 2052 | resume_generation: Option<String>, |
| 2053 | ) -> anyhow::Result<Self> { |
| 2054 | let ActorHostServices { |
| 2055 | host, |
| 2056 | drain_pins, |
| 2057 | ownership, |
| 2058 | peer_http, |
| 2059 | peer_auth, |
| 2060 | paced_handoff, |
| 2061 | } = services; |
| 2062 | let ActorIdentity { |
| 2063 | node, |
| 2064 | advertise, |
| 2065 | region, |
| 2066 | } = identity; |
| 2067 | let ownership = if let Some(ownership) = ownership { |
| 2068 | ownership |
| 2069 | } else { |
| 2070 | Ownership::Memory(Arc::new(Mutex::new(MemoryOwnership { |
| 2071 | node: node.clone(), |
| 2072 | owners: BTreeMap::new(), |
| 2073 | leases: BTreeMap::new(), |
| 2074 | next_etag: 1, |
| 2075 | }))) |
| 2076 | }; |
| 2077 | let live_load = match &ownership { |
| 2078 | Ownership::Bucket(bucket) => Some(bucket.live()), |
| 2079 | Ownership::Memory(_) => None, |
| 2080 | }; |
| 2081 | if let Some(live) = &live_load { |
| 2082 | crate::ownership_store::set_node_load(live.clone()); |
| 2083 | } |
| 2084 | let process_generation = match &ownership { |
| 2085 | Ownership::Bucket(bucket) => bucket |
| 2086 | .process_generation() |
| 2087 | .map(str::to_owned) |
| 2088 | .unwrap_or_else(random_process_generation), |
| 2089 | Ownership::Memory(_) => random_process_generation(), |
| 2090 | }; |
| 2091 | let ttl_ms = crate::env_vars::positive_or("CELLD_TTL_MS", 10_000)?; |
| 2092 | let lease_spec = NodeLeaseSpec { |
| 2093 | // Startup has already resolved the environment and CLI settings |
| 2094 | // into this validated internal address. Reading the environment |
| 2095 | // again would let CELLD_ADVERTISE override a later CLI option and |
| 2096 | // publish an address that the bound listener did not validate. |
| 2097 | addr: advertise, |
| 2098 | peer_protocol: peer_auth::PROTOCOL_VERSION, |
| 2099 | generation: std::env::var("CELLD_TEST_GENERATION").unwrap_or(process_generation), |
| 2100 | resume_generation, |
| 2101 | ttl_ms, |
| 2102 | }; |
| 2103 | Ok(Self { |
| 2104 | node_log: Arc::new(std::sync::Mutex::new(None)), |
| 2105 | state: ActorState::from(State::new( |
| 2106 | node, |
| 2107 | Config { |
| 2108 | max_resident: limits.resident, |
| 2109 | max_activations: limits.activations, |
| 2110 | max_evictions: limits.evictions, |
| 2111 | max_releases: limits.releases, |
| 2112 | alarm_resident_ms: crate::wake::resident_ms().max(0) as u64, |
| 2113 | require_node_lease: true, |
| 2114 | peer_protocol: crate::peer_auth::PROTOCOL_VERSION, |
| 2115 | operation_deadline_ms: Some(operation_deadline_ms()?), |
| 2116 | idle_evict_ms: crate::env_vars::positive::<u64>("CELLD_IDLE_EVICT_S")? |
| 2117 | .map(|seconds| seconds.saturating_mul(1_000)), |
| 2118 | pressure: pressure_config_from_environment()?, |
| 2119 | max_outbound_websockets: crate::env_vars::positive_or( |
| 2120 | "CELLD_MAX_OUTBOUND_WEBSOCKETS", |
| 2121 | DEFAULT_MAX_OUTBOUND_WEBSOCKETS, |
| 2122 | )?, |
| 2123 | ownership_on_evict: match &ownership { |
| 2124 | // Releasing a cell says "any node may take this |
| 2125 | // one", which is only true if some other node could |
| 2126 | // restore it. Without a bucket the sole copy is this |
| 2127 | // node's disk, keyed to an epoch a re-acquire will |
| 2128 | // step past, so releasing would lose the cell. |
| 2129 | Ownership::Memory(_) => OwnershipOnEvict::Sticky, |
| 2130 | Ownership::Bucket(_) => ownership_on_evict_from_environment()?, |
| 2131 | }, |
| 2132 | }, |
| 2133 | )), |
| 2134 | ownership, |
| 2135 | peer_http, |
| 2136 | peer_auth, |
| 2137 | paced_handoff, |
| 2138 | handoff_directory: Arc::new(Mutex::new(HandoffDirectory::default())), |
| 2139 | host, |
| 2140 | drain_pins, |
| 2141 | handoff_timings: HashMap::new(), |
| 2142 | handoff_phase_ops: HashMap::new(), |
| 2143 | region, |
| 2144 | pending: BTreeMap::new(), |
| 2145 | request_cells: BTreeMap::new(), |
| 2146 | handoff_accepts: BTreeMap::new(), |
| 2147 | route_timings: BTreeMap::new(), |
| 2148 | pending_workers: BTreeMap::new(), |
| 2149 | eviction_waiters: BTreeMap::new(), |
| 2150 | durability_waiters: BTreeMap::new(), |
| 2151 | gated_responses: BTreeMap::new(), |
| 2152 | ws_gates: BTreeMap::new(), |
| 2153 | ws_gated: BTreeMap::new(), |
| 2154 | eviction_stops: BTreeMap::new(), |
| 2155 | published: BTreeSet::new(), |
| 2156 | fail_publish_once, |
| 2157 | publishes: 0, |
| 2158 | stops: 0, |
| 2159 | lease_spec, |
| 2160 | live_load, |
| 2161 | logged_shed_reason: None, |
| 2162 | validate_invariants: cfg!(debug_assertions), |
| 2163 | fence, |
| 2164 | timer_slots: TimerSlots::default(), |
| 2165 | started: false, |
| 2166 | preserving: false, |
| 2167 | }) |
| 2168 | } |
| 2169 | |
| 2170 | /// Emits the exactly-once pre-loop node-lease transition. |
| 2171 | pub fn start(&mut self, out: &mut StepOutput) { |
| 2172 | assert!(!self.started, "Actor::start was called more than once"); |
| 2173 | self.started = true; |
| 2174 | self.drive( |
| 2175 | Event::StartNodeLease { |
| 2176 | now_ms: now_ms(), |
| 2177 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2178 | spec: self.lease_spec.clone(), |
| 2179 | }, |
| 2180 | out, |
| 2181 | ); |
| 2182 | } |
| 2183 | |
| 2184 | /// Handles exactly one ready mailbox item, completion, or timer. |
| 2185 | pub fn step(&mut self, input: ActorInput, out: &mut StepOutput) { |
| 2186 | assert!(self.started, "Actor::step was called before Actor::start"); |
| 2187 | match input { |
| 2188 | ActorInput::Message(message) => self.handle_message(message, out), |
| 2189 | ActorInput::Completed(completed) => { |
| 2190 | let route_cell = completed.timing.as_ref().map(|timing| timing.cell.clone()); |
| 2191 | if let Some(timing) = completed.timing { |
| 2192 | self.record_effect_timing(timing); |
| 2193 | } |
| 2194 | self.drive(completed.event, out); |
| 2195 | if let Some(cell) = route_cell { |
| 2196 | self.observe_capacity_wait(&cell); |
| 2197 | } |
| 2198 | } |
| 2199 | ActorInput::TimerFired(timer) => { |
| 2200 | self.timer_slots.clear_slot(&TimerSlot::of(&timer)); |
| 2201 | if self.preserving && matches!(timer, Timer::CellAlarm { .. }) { |
| 2202 | return; |
| 2203 | } |
| 2204 | self.drive( |
| 2205 | Event::TimerFired { |
| 2206 | timer, |
| 2207 | now_ms: now_ms(), |
| 2208 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2209 | }, |
| 2210 | out, |
| 2211 | ); |
| 2212 | } |
| 2213 | } |
| 2214 | } |
| 2215 | |
| 2216 | fn handle_message(&mut self, message: Message, out: &mut StepOutput) { |
| 2217 | match message { |
| 2218 | Message::BeginPreserve => { |
| 2219 | self.preserving = true; |
| 2220 | self.drive(Event::BeginPreserve, out); |
| 2221 | } |
| 2222 | Message::Request { reply, .. } if self.preserving => { |
| 2223 | let _ = reply.send(Err(RequestError::NodeFenced)); |
| 2224 | } |
| 2225 | Message::Request { |
| 2226 | request, |
| 2227 | cell, |
| 2228 | capacity_handoff, |
| 2229 | handoff_accept, |
| 2230 | websocket, |
| 2231 | reply, |
| 2232 | } => { |
| 2233 | let retired_durability = match self.state.phase(&cell) { |
| 2234 | Some(Phase::EnsuringDurability { op, .. }) => Some(*op), |
| 2235 | _ => None, |
| 2236 | }; |
| 2237 | self.pending.insert(request, reply); |
| 2238 | let ownership_handoff = handoff_accept.is_some(); |
| 2239 | if let Some(waiter) = handoff_accept { |
| 2240 | self.handoff_accepts.insert(request, (cell.clone(), waiter)); |
| 2241 | } |
| 2242 | self.begin_route_if_cold(&cell); |
| 2243 | self.request_cells.insert(request, cell.clone()); |
| 2244 | self.drive( |
| 2245 | if let Some(websocket) = websocket { |
| 2246 | Event::WebSocketRequestAt { |
| 2247 | request, |
| 2248 | cell: cell.clone(), |
| 2249 | websocket, |
| 2250 | now_ms: now_ms(), |
| 2251 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2252 | } |
| 2253 | } else if ownership_handoff { |
| 2254 | Event::HandoffRequestAt { |
| 2255 | request, |
| 2256 | cell: cell.clone(), |
| 2257 | now_ms: now_ms(), |
| 2258 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2259 | } |
| 2260 | } else if capacity_handoff { |
| 2261 | Event::CapacityRequestAt { |
| 2262 | request, |
| 2263 | cell: cell.clone(), |
| 2264 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2265 | } |
| 2266 | } else { |
| 2267 | Event::RequestAt { |
| 2268 | request, |
| 2269 | cell: cell.clone(), |
| 2270 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2271 | } |
| 2272 | }, |
| 2273 | out, |
| 2274 | ); |
| 2275 | self.observe_capacity_wait(&cell); |
| 2276 | if let Some(op) = retired_durability { |
| 2277 | if let Some((_, waiters)) = self.durability_waiters.remove(&op) { |
| 2278 | for waiter in waiters { |
| 2279 | let _ = waiter.send(()); |
| 2280 | } |
| 2281 | } |
| 2282 | } |
| 2283 | } |
| 2284 | Message::CancelRoute { request } => { |
| 2285 | self.pending.remove(&request); |
| 2286 | self.handoff_accepts.remove(&request); |
| 2287 | if let Some(cell) = self.request_cells.remove(&request) { |
| 2288 | self.finish_route(&cell, "cancelled", "caller_disconnected", None); |
| 2289 | } |
| 2290 | self.drive(Event::Cancel { request }, out); |
| 2291 | } |
| 2292 | Message::WorkerRequest { reply } if self.preserving => { |
| 2293 | let _ = reply.send(WorkerRouted { |
| 2294 | request: crate::asyncrt::next_core_request(), |
| 2295 | route: None, |
| 2296 | }); |
| 2297 | } |
| 2298 | Message::WorkerRequest { reply } => { |
| 2299 | let request = crate::asyncrt::next_core_request(); |
| 2300 | self.pending_workers.insert(request, reply); |
| 2301 | self.drive(Event::WorkerRequest { request }, out); |
| 2302 | } |
| 2303 | Message::ReleaseAll => self.drive(Event::ReleaseAll, out), |
| 2304 | Message::GenerationChanged { |
| 2305 | generation, |
| 2306 | max_age_ms, |
| 2307 | eager_classes, |
| 2308 | } => self.drive( |
| 2309 | Event::GenerationChanged { |
| 2310 | generation, |
| 2311 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2312 | max_age_ms, |
| 2313 | eager_classes, |
| 2314 | }, |
| 2315 | out, |
| 2316 | ), |
| 2317 | Message::Drained { reply } => { |
| 2318 | let _ = reply.send(DrainStatus { |
| 2319 | occupied: self.state.occupied(), |
| 2320 | activating: self.state.activating(), |
| 2321 | quiescing: self.state.quiescing(), |
| 2322 | evicting: self.state.evicting(), |
| 2323 | releasing: self.state.releasing(), |
| 2324 | adopting: self.state.adopting(), |
| 2325 | handed_off: self.state.handed_off(), |
| 2326 | }); |
| 2327 | } |
| 2328 | Message::ResidentEpoch { cell, reply } => { |
| 2329 | let epoch = match self.state.phase(&cell) { |
| 2330 | Some(Phase::Resident { epoch }) |
| 2331 | | Some(Phase::EnsuringDurability { epoch, .. }) => Some(*epoch), |
| 2332 | _ => None, |
| 2333 | }; |
| 2334 | let _ = reply.send(epoch); |
| 2335 | } |
| 2336 | Message::SampleLoad if self.preserving => {} |
| 2337 | Message::SampleLoad => { |
| 2338 | // Counted once: it is a walk of every cell, and the latch and |
| 2339 | // the number peers rank this node by must agree anyway. |
| 2340 | let occupied = self.state.occupied(); |
| 2341 | let metrics = crate::asyncrt::services().sample_metrics(); |
| 2342 | let cpu = metrics.cpu_percent_x100; |
| 2343 | let load = celld_logic::pressure::Load { |
| 2344 | resident_cells: occupied, |
| 2345 | rss_bytes: metrics.rss_bytes, |
| 2346 | in_use_bytes: metrics.in_use_bytes, |
| 2347 | cgroup_working_set_bytes: metrics.cgroup_working_set_bytes, |
| 2348 | cgroup_current_bytes: metrics.cgroup_current_bytes, |
| 2349 | }; |
| 2350 | let now_mono_ms = crate::asyncrt::mono_ms(); |
| 2351 | self.drive(Event::LoadSampled { load, now_mono_ms }, out); |
| 2352 | // Report a change of shed reason once. `rss-hard` retains its |
| 2353 | // established name, but in a Linux cgroup it says |
| 2354 | // `memory.current` crossed the absolute cap. |
| 2355 | let reason = self.state.shed_reason(); |
| 2356 | if reason != self.logged_shed_reason { |
| 2357 | self.logged_shed_reason = reason; |
| 2358 | // How many V8 heaps the resident cells hold open. Most of |
| 2359 | // what a cell costs is its heap, and a heap comes back |
| 2360 | // only when its last cell goes, so cells alone do not say |
| 2361 | // how much a walk down can still return. |
| 2362 | let heaps = self |
| 2363 | .state |
| 2364 | .resident_isolates() |
| 2365 | .into_iter() |
| 2366 | .collect::<BTreeSet<_>>() |
| 2367 | .len(); |
| 2368 | match reason { |
| 2369 | Some(celld_logic::pressure::SHED_RSS_HARD) => tracing::warn!( |
| 2370 | rss_bytes = load.rss_bytes, |
| 2371 | in_use_bytes = load.in_use_bytes, |
| 2372 | cgroup_working_set_bytes = load.cgroup_working_set_bytes, |
| 2373 | cgroup_current_bytes = load.cgroup_current_bytes, |
| 2374 | heaps, |
| 2375 | "shedding on the absolute memory cap" |
| 2376 | ), |
| 2377 | Some(reason) => tracing::info!( |
| 2378 | reason, |
| 2379 | rss_bytes = load.rss_bytes, |
| 2380 | in_use_bytes = load.in_use_bytes, |
| 2381 | cgroup_working_set_bytes = load.cgroup_working_set_bytes, |
| 2382 | cgroup_current_bytes = load.cgroup_current_bytes, |
| 2383 | heaps, |
| 2384 | "shedding" |
| 2385 | ), |
| 2386 | None => tracing::info!("no longer shedding"), |
| 2387 | } |
| 2388 | } |
| 2389 | // Republish what peers rank this node by. The same numbers the |
| 2390 | // latch just saw: a node that reports last tick's residency |
| 2391 | // attracts work it has already refused. |
| 2392 | if let Some(live) = &self.live_load { |
| 2393 | live.resident_cells.store(occupied, Ordering::Relaxed); |
| 2394 | live.host_websockets |
| 2395 | .store(self.state.host_websockets(), Ordering::Relaxed); |
| 2396 | live.pressured |
| 2397 | .store(self.state.shedding(), Ordering::Relaxed); |
| 2398 | live.memory_headroom |
| 2399 | .store(self.state.memory_headroom(), Ordering::Relaxed); |
| 2400 | live.cpu_percent_x100.store(cpu, Ordering::Relaxed); |
| 2401 | live.restoring |
| 2402 | .store(self.state.activation_backlog() as u64, Ordering::Relaxed); |
| 2403 | } |
| 2404 | } |
| 2405 | Message::Output { |
| 2406 | request, |
| 2407 | channel, |
| 2408 | position, |
| 2409 | reply, |
| 2410 | } => { |
| 2411 | self.gated_responses |
| 2412 | .insert(HeldOutputKey { request, channel }, reply); |
| 2413 | self.drive( |
| 2414 | Event::Output { |
| 2415 | request, |
| 2416 | channel, |
| 2417 | position, |
| 2418 | }, |
| 2419 | out, |
| 2420 | ); |
| 2421 | } |
| 2422 | Message::WsOutput { |
| 2423 | request, |
| 2424 | scope, |
| 2425 | frames, |
| 2426 | write_position, |
| 2427 | reply, |
| 2428 | } => { |
| 2429 | // Open a barrier for every batch, then let the core decide |
| 2430 | // what it trails: its own write when the handler wrote, and |
| 2431 | // otherwise the newest write still outstanding on this cell, |
| 2432 | // whichever channel made it. The queue consulted here before |
| 2433 | // was filled in one place -- the arm below that writes -- so it |
| 2434 | // held only writes a `webSocketMessage` handler made itself, |
| 2435 | // and an HTTP, RPC, or peer write on the same cell was |
| 2436 | // invisible to a batch that only read. |
| 2437 | // |
| 2438 | // Both registrations happen before the drive, and must: `drive` |
| 2439 | // runs the effects it produces synchronously, so a read with no |
| 2440 | // barrier open on its cell is released inside the call below. |
| 2441 | // Moved after it, that `Effect::Release` would find no |
| 2442 | // `ws_gated` entry, fall through to the `gated_responses` map, |
| 2443 | // match nothing, and strand these frames behind a barrier that |
| 2444 | // nothing will ever settle. |
| 2445 | self.ws_gates |
| 2446 | .entry(scope.clone()) |
| 2447 | .or_default() |
| 2448 | .barriers |
| 2449 | .push_back(WsBarrier { |
| 2450 | request, |
| 2451 | settled: None, |
| 2452 | frames, |
| 2453 | }); |
| 2454 | self.ws_gated |
| 2455 | .insert(HeldOutputKey::websocket(request), scope); |
| 2456 | // The core answers for every writer on the cell, including an |
| 2457 | // alarm: its consuming commit opens a barrier of its own, so a |
| 2458 | // read-only batch trails that too. |
| 2459 | self.drive( |
| 2460 | Event::Output { |
| 2461 | request, |
| 2462 | channel: Channel::WsHibernatable, |
| 2463 | position: write_position, |
| 2464 | }, |
| 2465 | out, |
| 2466 | ); |
| 2467 | let _ = reply.send(()); |
| 2468 | } |
| 2469 | Message::ActivityFinished { |
| 2470 | request, |
| 2471 | cell, |
| 2472 | alarm_at_ms, |
| 2473 | alarm_covered, |
| 2474 | } => { |
| 2475 | // Folded from the old AlarmObserved-then-ActivityFinished pair the |
| 2476 | // activity drop sent: observe the alarm and release any retired |
| 2477 | // durability waiters, then finish the activity — same events, same |
| 2478 | // order, one message instead of two. |
| 2479 | let retired_durability = match self.state.phase(&cell) { |
| 2480 | Some(Phase::EnsuringDurability { op, .. }) => Some(*op), |
| 2481 | _ => None, |
| 2482 | }; |
| 2483 | self.drive( |
| 2484 | Event::AlarmObserved { |
| 2485 | cell, |
| 2486 | at_ms: alarm_at_ms, |
| 2487 | covered: alarm_covered, |
| 2488 | now_ms: now_ms(), |
| 2489 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2490 | }, |
| 2491 | out, |
| 2492 | ); |
| 2493 | if let Some(op) = retired_durability { |
| 2494 | if let Some((_, waiters)) = self.durability_waiters.remove(&op) { |
| 2495 | for waiter in waiters { |
| 2496 | let _ = waiter.send(()); |
| 2497 | } |
| 2498 | } |
| 2499 | } |
| 2500 | self.drive(Event::ActivityFinished { request }, out); |
| 2501 | } |
| 2502 | Message::WebSocketOpened { |
| 2503 | cell, |
| 2504 | websocket, |
| 2505 | kind, |
| 2506 | reply, |
| 2507 | } => { |
| 2508 | self.drive( |
| 2509 | Event::WebSocketOpened { |
| 2510 | cell: cell.clone(), |
| 2511 | websocket, |
| 2512 | kind, |
| 2513 | }, |
| 2514 | out, |
| 2515 | ); |
| 2516 | // The core may decline to hold the transport. Say so, rather |
| 2517 | // than acknowledging an open and closing the socket a moment |
| 2518 | // later: an application that hit a ceiling deserves to be |
| 2519 | // told which one, not left watching a socket disappear. |
| 2520 | // Only an outbound socket can be declined, and only for a |
| 2521 | // cell the core knows: an inbound transport is never refused, |
| 2522 | // and reporting one as refused fails opens that succeeded. |
| 2523 | let refused = kind == WebSocketKind::Outbound |
| 2524 | && !self.state.holds_websocket(&cell, websocket); |
| 2525 | let _ = reply.send(!refused); |
| 2526 | } |
| 2527 | Message::WebSocketClosed { cell, websocket } => { |
| 2528 | self.drive(Event::WebSocketClosed { cell, websocket }, out); |
| 2529 | } |
| 2530 | Message::AlarmObserved { |
| 2531 | cell, |
| 2532 | at_ms, |
| 2533 | covered, |
| 2534 | } => { |
| 2535 | let retired_durability = match self.state.phase(&cell) { |
| 2536 | Some(Phase::EnsuringDurability { op, .. }) => Some(*op), |
| 2537 | _ => None, |
| 2538 | }; |
| 2539 | self.drive( |
| 2540 | Event::AlarmObserved { |
| 2541 | cell, |
| 2542 | at_ms, |
| 2543 | covered, |
| 2544 | now_ms: now_ms(), |
| 2545 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2546 | }, |
| 2547 | out, |
| 2548 | ); |
| 2549 | if let Some(op) = retired_durability { |
| 2550 | if let Some((_, waiters)) = self.durability_waiters.remove(&op) { |
| 2551 | for waiter in waiters { |
| 2552 | let _ = waiter.send(()); |
| 2553 | } |
| 2554 | } |
| 2555 | } |
| 2556 | } |
| 2557 | Message::NudgeNodeLease => { |
| 2558 | self.drive( |
| 2559 | Event::NudgeNodeLease { |
| 2560 | now_ms: now_ms(), |
| 2561 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2562 | }, |
| 2563 | out, |
| 2564 | ); |
| 2565 | } |
| 2566 | Message::WakeHint { .. } if self.preserving => {} |
| 2567 | Message::WakeHint { cell } => { |
| 2568 | self.drive( |
| 2569 | Event::WakeHintAt { |
| 2570 | cell, |
| 2571 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2572 | }, |
| 2573 | out, |
| 2574 | ); |
| 2575 | } |
| 2576 | Message::Evict { reply, .. } if self.preserving => { |
| 2577 | let _ = reply.send(()); |
| 2578 | } |
| 2579 | Message::Evict { cell, reply } if self.state.is_active(&cell) => { |
| 2580 | let _ = reply.send(()); |
| 2581 | } |
| 2582 | Message::Evict { cell, reply } => match self.state.phase(&cell) { |
| 2583 | Some(Phase::Resident { .. }) => { |
| 2584 | self.eviction_waiters |
| 2585 | .entry(cell.clone()) |
| 2586 | .or_default() |
| 2587 | .push(reply); |
| 2588 | self.drive(Event::Evict { cell }, out); |
| 2589 | } |
| 2590 | Some(Phase::EnsuringDurability { op, .. }) => { |
| 2591 | self.durability_waiters |
| 2592 | .entry(*op) |
| 2593 | .or_insert_with(|| (cell, Vec::new())) |
| 2594 | .1 |
| 2595 | .push(reply); |
| 2596 | } |
| 2597 | Some(Phase::Cleaning { |
| 2598 | op, |
| 2599 | cause: StopCause::Evict { .. }, |
| 2600 | .. |
| 2601 | }) => { |
| 2602 | self.eviction_stops.entry(*op).or_default().push(reply); |
| 2603 | } |
| 2604 | _ => { |
| 2605 | let _ = reply.send(()); |
| 2606 | } |
| 2607 | }, |
| 2608 | Message::InvalidateRemote { |
| 2609 | cell, |
| 2610 | node, |
| 2611 | epoch, |
| 2612 | reply, |
| 2613 | } => { |
| 2614 | self.drive(Event::InvalidateRemote { cell, node, epoch }, out); |
| 2615 | let _ = reply.send(()); |
| 2616 | } |
| 2617 | Message::Snapshot { reply } => { |
| 2618 | let generations = self |
| 2619 | .state |
| 2620 | .residents() |
| 2621 | .into_iter() |
| 2622 | .map(|cell| { |
| 2623 | let generation = self.state.cell_generation(&cell).unwrap_or(0); |
| 2624 | (cell, generation) |
| 2625 | }) |
| 2626 | .collect(); |
| 2627 | let census = SwapCensus { |
| 2628 | swapping: self.state.swapping(), |
| 2629 | generations, |
| 2630 | }; |
| 2631 | let _ = reply.send((self.state_json(), self.state.drain_pins(), census)); |
| 2632 | } |
| 2633 | Message::Health { reply } => { |
| 2634 | let _ = reply.send(self.state.ready_to_serve()); |
| 2635 | } |
| 2636 | Message::Presence { reply } => { |
| 2637 | let _ = reply.send(self.state.presence_snapshot()); |
| 2638 | } |
| 2639 | } |
| 2640 | } |
| 2641 | |
| 2642 | /// Settle a gated `webSocketMessage`'s durability. On success mark its |
| 2643 | /// barrier durable and flush the durable prefix in write order; on failure |
| 2644 | /// break the whole cell gate — drop every held frame and reset its sockets, |
| 2645 | /// since an unproven write must never leave an acknowledged trace. |
| 2646 | fn ws_release(&mut self, held: HeldOutputKey, ok: bool) { |
| 2647 | let Some(scope) = self.ws_gated.remove(&held) else { |
| 2648 | return; |
| 2649 | }; |
| 2650 | let mut flush = Vec::new(); |
| 2651 | let broke = { |
| 2652 | let Some(gate) = self.ws_gates.get_mut(&scope) else { |
| 2653 | return; |
| 2654 | }; |
| 2655 | if let Some(barrier) = gate.barriers.iter_mut().find(|b| b.request == held.request) { |
| 2656 | barrier.settled = Some(ok); |
| 2657 | } |
| 2658 | if gate.barriers.iter().any(|b| b.settled == Some(false)) { |
| 2659 | true |
| 2660 | } else { |
| 2661 | while gate |
| 2662 | .barriers |
| 2663 | .front() |
| 2664 | .is_some_and(|b| b.settled == Some(true)) |
| 2665 | { |
| 2666 | flush.push(gate.barriers.pop_front().unwrap().frames); |
| 2667 | } |
| 2668 | false |
| 2669 | } |
| 2670 | }; |
| 2671 | if broke { |
| 2672 | self.ws_gates.remove(&scope); |
| 2673 | self.ws_gated.retain(|_, s| *s != scope); |
| 2674 | crate::js::ws_close_scope(&scope, 1011, "durability unproven"); |
| 2675 | return; |
| 2676 | } |
| 2677 | for frames in flush { |
| 2678 | crate::js::ws_emit_batch(frames); |
| 2679 | } |
| 2680 | if self |
| 2681 | .ws_gates |
| 2682 | .get(&scope) |
| 2683 | .is_some_and(|g| g.barriers.is_empty()) |
| 2684 | { |
| 2685 | self.ws_gates.remove(&scope); |
| 2686 | } |
| 2687 | } |
| 2688 | |
| 2689 | /// Close a timed handoff pipeline step when its answering event arrives, |
| 2690 | /// and emit the cell's aggregate timing once adoption succeeds. A failed |
| 2691 | /// adoption keeps the cell entry so its retry accumulates on the same |
| 2692 | /// record; an expired operation abandons its pipeline entirely. |
| 2693 | fn close_handoff_phase(&mut self, event: &Event) { |
| 2694 | let (op, adopted) = match event { |
| 2695 | Event::DurabilityChecked { op, .. } |
| 2696 | | Event::RuntimeStopped { op } |
| 2697 | | Event::OwnerReleased { op, .. } => (*op, None), |
| 2698 | Event::SuccessorAdopted { op, result } => (*op, Some(result.is_ok())), |
| 2699 | Event::TimerFired { |
| 2700 | timer: Timer::OperationDeadline { op }, |
| 2701 | .. |
| 2702 | } => { |
| 2703 | if let Some((cell, _, _)) = self.handoff_phase_ops.remove(op) { |
| 2704 | self.handoff_timings.remove(&cell); |
| 2705 | } |
| 2706 | return; |
| 2707 | } |
| 2708 | _ => return, |
| 2709 | }; |
| 2710 | let Some((cell, phase, started_mono_ms)) = self.handoff_phase_ops.remove(&op) else { |
| 2711 | return; |
| 2712 | }; |
| 2713 | let elapsed = mono_elapsed_us(started_mono_ms); |
| 2714 | if phase == HandoffPhase::Adopt { |
| 2715 | if adopted == Some(true) { |
| 2716 | if let Some(timing) = self.handoff_timings.remove(&cell) { |
| 2717 | tracing::info!( |
| 2718 | event = "cell_handoff_timing", |
| 2719 | %cell, |
| 2720 | quiesce_us = timing.quiesce_us.unwrap_or(0), |
| 2721 | durability_us = timing.durability_us.unwrap_or(0), |
| 2722 | stop_us = timing.stop_us.unwrap_or(0), |
| 2723 | release_us = timing.release_us.unwrap_or(0), |
| 2724 | adopt_us = elapsed, |
| 2725 | total_us = mono_elapsed_us(timing.nominated_mono_ms), |
| 2726 | "handoff pipeline completed" |
| 2727 | ); |
| 2728 | } |
| 2729 | } |
| 2730 | return; |
| 2731 | } |
| 2732 | let Some(timing) = self.handoff_timings.get_mut(&cell) else { |
| 2733 | return; |
| 2734 | }; |
| 2735 | match phase { |
| 2736 | HandoffPhase::Durability => timing.durability_us = Some(elapsed), |
| 2737 | HandoffPhase::Stop => timing.stop_us = Some(elapsed), |
| 2738 | HandoffPhase::Release => timing.release_us = Some(elapsed), |
| 2739 | HandoffPhase::Adopt => {} |
| 2740 | } |
| 2741 | } |
| 2742 | |
| 2743 | fn drive(&mut self, first: Event, out: &mut StepOutput) { |
| 2744 | let mut events = VecDeque::from([first]); |
| 2745 | while let Some(event) = events.pop_front() { |
| 2746 | self.close_handoff_phase(&event); |
| 2747 | let durability = match &event { |
| 2748 | Event::DurabilityChecked { op, .. } => Some(*op), |
| 2749 | // A deadline resolves the same operation the proof would |
| 2750 | // have, so it has to release the same waiters. Without this |
| 2751 | // the core abandons the eviction and the caller that asked |
| 2752 | // for it stays blocked on a proof that is no longer coming. |
| 2753 | Event::TimerFired { |
| 2754 | timer: Timer::OperationDeadline { op }, |
| 2755 | .. |
| 2756 | } => Some(*op), |
| 2757 | _ => None, |
| 2758 | }; |
| 2759 | let stopped = match &event { |
| 2760 | Event::RuntimeStopped { op } => Some(*op), |
| 2761 | _ => None, |
| 2762 | }; |
| 2763 | let effects = apply_core_event(&mut self.state, event); |
| 2764 | if let Some(op) = durability { |
| 2765 | if let Some((_, waiters)) = self.durability_waiters.remove(&op) { |
| 2766 | let stop = effects.iter().find_map(|effect| match effect { |
| 2767 | Effect::StopRuntime { |
| 2768 | op, |
| 2769 | cause: StopCause::Evict { .. }, |
| 2770 | .. |
| 2771 | } => Some(*op), |
| 2772 | _ => None, |
| 2773 | }); |
| 2774 | if let Some(stop) = stop { |
| 2775 | self.eviction_stops.entry(stop).or_default().extend(waiters); |
| 2776 | } else { |
| 2777 | for waiter in waiters { |
| 2778 | let _ = waiter.send(()); |
| 2779 | } |
| 2780 | } |
| 2781 | } |
| 2782 | } |
| 2783 | for effect in effects { |
| 2784 | self.execute(effect, &mut events, out); |
| 2785 | } |
| 2786 | self.settle_handoff_accepts(); |
| 2787 | if let Some(op) = stopped { |
| 2788 | if let Some(waiters) = self.eviction_stops.remove(&op) { |
| 2789 | for waiter in waiters { |
| 2790 | let _ = waiter.send(()); |
| 2791 | } |
| 2792 | } |
| 2793 | } |
| 2794 | if self.validate_invariants { |
| 2795 | self.state.validate().expect("celld core invariant"); |
| 2796 | } |
| 2797 | } |
| 2798 | } |
| 2799 | |
| 2800 | fn settle_handoff_accepts(&mut self) { |
| 2801 | let accepted: Vec<_> = self |
| 2802 | .handoff_accepts |
| 2803 | .iter() |
| 2804 | .filter_map(|(request, (cell, waiter))| { |
| 2805 | self.state |
| 2806 | .accepted_epoch(cell) |
| 2807 | .filter(|epoch| *epoch > waiter.released_epoch) |
| 2808 | .map(|epoch| (*request, epoch)) |
| 2809 | }) |
| 2810 | .collect(); |
| 2811 | for (request, epoch) in accepted { |
| 2812 | let Some((_, waiter)) = self.handoff_accepts.remove(&request) else { |
| 2813 | continue; |
| 2814 | }; |
| 2815 | let _ = waiter.reply.send(AdoptedCell { |
| 2816 | node: self.state.node().to_string(), |
| 2817 | addr: self.lease_spec.addr.clone(), |
| 2818 | epoch, |
| 2819 | peer_protocol: peer_auth::PROTOCOL_VERSION, |
| 2820 | }); |
| 2821 | } |
| 2822 | } |
| 2823 | |
| 2824 | fn execute(&mut self, effect: Effect, immediate: &mut VecDeque<Event>, out: &mut StepOutput) { |
| 2825 | match effect { |
| 2826 | Effect::ScheduleTimer { timer, at_mono_ms } => { |
| 2827 | let (arm, _) = self.timer_slots.arm(timer, at_mono_ms, ()); |
| 2828 | out.timers.push(arm); |
| 2829 | } |
| 2830 | Effect::ReadSelfNodeLease { op } => { |
| 2831 | let ownership = self.ownership.clone(); |
| 2832 | let node = self.state.node().to_string(); |
| 2833 | out.effects.push(Box::pin(async move { |
| 2834 | let result = ownership.read_self_node_lease(&node).await; |
| 2835 | CompletedEffect::plain(Event::SelfNodeLeaseRead { |
| 2836 | op, |
| 2837 | now_ms: now_ms(), |
| 2838 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2839 | result, |
| 2840 | }) |
| 2841 | })); |
| 2842 | } |
| 2843 | Effect::CasNodeLease { |
| 2844 | op, |
| 2845 | guard, |
| 2846 | record, |
| 2847 | authority_expires_ms, |
| 2848 | } => { |
| 2849 | let ownership = self.ownership.clone(); |
| 2850 | out.effects.push(Box::pin(async move { |
| 2851 | let attempt_started_mono_ms = crate::asyncrt::mono_ms(); |
| 2852 | let node = record.node.clone(); |
| 2853 | let candidate_expires_ms = record.expires_ms; |
| 2854 | // Logged before the CAS: with only the completion line, a |
| 2855 | // renewal hung on a storage tail is indistinguishable from |
| 2856 | // a timer that never fired (the n6 fence, 2026-08-11). |
| 2857 | tracing::info!( |
| 2858 | event = "node_lease_attempt_started", |
| 2859 | %node, |
| 2860 | attempt = if authority_expires_ms.is_some() { |
| 2861 | "renew" |
| 2862 | } else { |
| 2863 | "acquire" |
| 2864 | }, |
| 2865 | prior_authority_headroom_ms = authority_expires_ms |
| 2866 | .map(|expires_ms| expires_ms.saturating_sub(now_ms())) |
| 2867 | .unwrap_or(0), |
| 2868 | "node lease attempt started" |
| 2869 | ); |
| 2870 | // A renewal must return while proven authority remains, |
| 2871 | // because only a returned attempt lets the ambiguity |
| 2872 | // read-back run before the watchdog. The 10:15Z R2 |
| 2873 | // brownout fenced 9 nodes whose sole hung attempt was |
| 2874 | // still inside the transport's 15 s timeout when the |
| 2875 | // 10 s TTL expired. Bound the attempt to half the |
| 2876 | // remaining authority (capped, floored) and map timeout |
| 2877 | // to Ambiguous — the same conservative outcome a lost |
| 2878 | // response already produces, so safety is unchanged. |
| 2879 | // The stamp survives a timed-out attempt: the backend |
| 2880 | // writes it through the out-parameter synchronously at |
| 2881 | // serialization, before the transport await, so even a |
| 2882 | // dropped future has reported what the possibly-landed |
| 2883 | // body carried. |
| 2884 | let mut stamped_log_state = None; |
| 2885 | let result = match authority_expires_ms { |
| 2886 | Some(expires_ms) => { |
| 2887 | let remaining = expires_ms.saturating_sub(now_ms()); |
| 2888 | let bound = |
| 2889 | std::time::Duration::from_millis((remaining / 2).clamp(250, 2_500)); |
| 2890 | match crate::asyncrt::timeout( |
| 2891 | bound, |
| 2892 | ownership.cas_node_lease(guard, record, &mut stamped_log_state), |
| 2893 | ) |
| 2894 | .await |
| 2895 | { |
| 2896 | Ok(result) => result, |
| 2897 | Err(_) => Err(Failure::Ambiguous), |
| 2898 | } |
| 2899 | } |
| 2900 | None => { |
| 2901 | ownership |
| 2902 | .cas_node_lease(guard, record, &mut stamped_log_state) |
| 2903 | .await |
| 2904 | } |
| 2905 | }; |
| 2906 | let completed_ms = now_ms(); |
| 2907 | let elapsed_ms = |
| 2908 | crate::asyncrt::mono_ms().saturating_sub(attempt_started_mono_ms); |
| 2909 | let prior_authority_headroom_ms = authority_expires_ms |
| 2910 | .map(|expires_ms| expires_ms.saturating_sub(completed_ms)) |
| 2911 | .unwrap_or(0); |
| 2912 | let candidate_headroom_ms = candidate_expires_ms.saturating_sub(completed_ms); |
| 2913 | let attempt = if authority_expires_ms.is_some() { |
| 2914 | "renew" |
| 2915 | } else { |
| 2916 | "acquire" |
| 2917 | }; |
| 2918 | let outcome = match &result { |
| 2919 | Ok(LeaseCasOutcome::Applied { .. }) => "applied", |
| 2920 | Ok(LeaseCasOutcome::Rejected) => "rejected", |
| 2921 | Err(Failure::Ambiguous) => "ambiguous", |
| 2922 | Err(Failure::Definite) => "definite_failure", |
| 2923 | }; |
| 2924 | if matches!(&result, Ok(LeaseCasOutcome::Applied { .. })) { |
| 2925 | tracing::info!( |
| 2926 | event = "node_lease_attempt", |
| 2927 | %node, |
| 2928 | attempt, |
| 2929 | outcome, |
| 2930 | elapsed_ms, |
| 2931 | prior_authority_headroom_ms, |
| 2932 | candidate_headroom_ms, |
| 2933 | "node lease attempt completed" |
| 2934 | ); |
| 2935 | } else { |
| 2936 | tracing::warn!( |
| 2937 | event = "node_lease_attempt", |
| 2938 | %node, |
| 2939 | attempt, |
| 2940 | outcome, |
| 2941 | elapsed_ms, |
| 2942 | prior_authority_headroom_ms, |
| 2943 | candidate_headroom_ms, |
| 2944 | "node lease attempt did not apply" |
| 2945 | ); |
| 2946 | } |
| 2947 | CompletedEffect::plain(Event::NodeLeaseCasCompleted { |
| 2948 | op, |
| 2949 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 2950 | result, |
| 2951 | stamped_log_state, |
| 2952 | }) |
| 2953 | })); |
| 2954 | } |
| 2955 | Effect::ReadLocalCells => { |
| 2956 | let runtime = self.host.clone(); |
| 2957 | out.effects.push(Box::pin(async move { |
| 2958 | let result = match runtime { |
| 2959 | // The host runtime's blocking pool, not a second |
| 2960 | // pool on the core's current-thread runtime. |
| 2961 | Some(runtime) => crate::asyncrt::blocking(move || { |
| 2962 | runtime.local_reload_cells().map_err(|error| { |
| 2963 | eprintln!("celld local reload scan failed: {error:#}"); |
| 2964 | Failure::Definite |
| 2965 | }) |
| 2966 | }) |
| 2967 | .await |
| 2968 | .unwrap_or(Err(Failure::Definite)), |
| 2969 | None => Err(Failure::Definite), |
| 2970 | }; |
| 2971 | CompletedEffect::plain(Event::LocalCellsRead { result }) |
| 2972 | })); |
| 2973 | } |
| 2974 | Effect::ReadOwner { op, cell } => { |
| 2975 | self.route_effect_started(&cell); |
| 2976 | let ownership = self.ownership.clone(); |
| 2977 | let timing_cell = cell.clone(); |
| 2978 | out.effects.push(Box::pin(async move { |
| 2979 | let started = crate::asyncrt::mono_ms(); |
| 2980 | let result = ownership.read_owner(&cell).await; |
| 2981 | CompletedEffect::timed( |
| 2982 | Event::OwnerRead { |
| 2983 | op, |
| 2984 | now_ms: now_ms(), |
| 2985 | result, |
| 2986 | }, |
| 2987 | timing_cell, |
| 2988 | RouteStage::OwnershipRead, |
| 2989 | started, |
| 2990 | ) |
| 2991 | })); |
| 2992 | } |
| 2993 | Effect::ReadNodeLease { op, cell, owner } => { |
| 2994 | self.route_effect_started(&cell); |
| 2995 | let ownership = self.ownership.clone(); |
| 2996 | let timing_cell = cell; |
| 2997 | out.effects.push(Box::pin(async move { |
| 2998 | let started = crate::asyncrt::mono_ms(); |
| 2999 | let result = ownership.read_node_lease(&owner).await; |
| 3000 | CompletedEffect::timed( |
| 3001 | Event::NodeLeaseRead { |
| 3002 | op, |
| 3003 | now_ms: now_ms(), |
| 3004 | result, |
| 3005 | }, |
| 3006 | timing_cell, |
| 3007 | RouteStage::NodeLeaseLookup, |
| 3008 | started, |
| 3009 | ) |
| 3010 | })); |
| 3011 | } |
| 3012 | Effect::RecoverNodeLog { op, cell, owner } => { |
| 3013 | self.route_effect_started(&cell); |
| 3014 | let interlock = self.node_log.lock().unwrap().clone(); |
| 3015 | let timing_cell = cell.clone(); |
| 3016 | out.effects.push(Box::pin(async move { |
| 3017 | let started = crate::asyncrt::mono_ms(); |
| 3018 | let result = match interlock { |
| 3019 | // No log tier on this node (no bucket): nothing to |
| 3020 | // recover, and the claim proceeds as before. |
| 3021 | None => Ok(()), |
| 3022 | Some(interlock) => interlock |
| 3023 | .ensure_recovered(Some(&owner)) |
| 3024 | .await |
| 3025 | .map_err(|error| { |
| 3026 | eprintln!( |
| 3027 | "celld node-log recovery for takeover of {cell} failed: {error:#}" |
| 3028 | ); |
| 3029 | Failure::Ambiguous |
| 3030 | }), |
| 3031 | }; |
| 3032 | CompletedEffect::timed( |
| 3033 | Event::NodeLogRecovered { op, result }, |
| 3034 | timing_cell, |
| 3035 | RouteStage::NodeLeaseLookup, |
| 3036 | started, |
| 3037 | ) |
| 3038 | })); |
| 3039 | } |
| 3040 | Effect::ReadCapacityPeers { op, cell } => { |
| 3041 | self.route_effect_started(&cell); |
| 3042 | let ownership = self.ownership.clone(); |
| 3043 | let timing_cell = cell; |
| 3044 | out.effects.push(Box::pin(async move { |
| 3045 | let started = crate::asyncrt::mono_ms(); |
| 3046 | let result = ownership.read_capacity_peers().await; |
| 3047 | CompletedEffect::timed( |
| 3048 | Event::CapacityPeersRead { |
| 3049 | op, |
| 3050 | now_ms: now_ms(), |
| 3051 | result, |
| 3052 | }, |
| 3053 | timing_cell, |
| 3054 | RouteStage::CapacityLookup, |
| 3055 | started, |
| 3056 | ) |
| 3057 | })); |
| 3058 | } |
| 3059 | Effect::CasOwner { |
| 3060 | op, |
| 3061 | cell, |
| 3062 | guard, |
| 3063 | epoch, |
| 3064 | takeover, |
| 3065 | } => { |
| 3066 | self.route_effect_started(&cell); |
| 3067 | if let Some(timing) = self.route_timings.get_mut(&cell) { |
| 3068 | timing |
| 3069 | .fresh |
| 3070 | .get_or_insert(!takeover && matches!(guard, CasGuard::Absent)); |
| 3071 | } |
| 3072 | let ownership = self.ownership.clone(); |
| 3073 | let timing_cell = cell.clone(); |
| 3074 | out.effects.push(Box::pin(async move { |
| 3075 | let started = crate::asyncrt::mono_ms(); |
| 3076 | let result = ownership.cas_owner(&cell, guard, epoch).await; |
| 3077 | CompletedEffect::timed( |
| 3078 | Event::OwnerCasCompleted { op, result }, |
| 3079 | timing_cell, |
| 3080 | RouteStage::OwnershipAcquire, |
| 3081 | started, |
| 3082 | ) |
| 3083 | })); |
| 3084 | } |
| 3085 | Effect::ReconcileWakeEntry { |
| 3086 | cell, |
| 3087 | next_alarm_ms, |
| 3088 | } => { |
| 3089 | if self.host.is_some() { |
| 3090 | // An ARMED alarm must always be reconcilable, tracked or |
| 3091 | // not: belief can be lost while the alarm stands (a |
| 3092 | // failed arm-time PUT, an entry retired under a racing |
| 3093 | // arm), and skipping here would mean it is never |
| 3094 | // re-asserted — entryless until the alarm fires or the |
| 3095 | // cell moves. Gating the CONSUME side on tracking is |
| 3096 | // what keeps alarm-less cells op-quiescent: untracked |
| 3097 | // with no alarm, there is nothing to delete. |
| 3098 | if next_alarm_ms >= 0 || crate::js::wake_entry_tracked(&cell) { |
| 3099 | // On the host runtime: this arm runs on the core |
| 3100 | // thread, and a bare spawn would schedule the S3 |
| 3101 | // round trip there too. |
| 3102 | crate::asyncrt::spawn(async move { |
| 3103 | // A consume-delete only ever follows a firing, and |
| 3104 | // the core orders it from the far side of the |
| 3105 | // output gate: `alarm_finished` gates the |
| 3106 | // consuming commit, and only a proven |
| 3107 | // DurableReached — with an ownership read behind a |
| 3108 | // bucket proof — lets the alarm settle |
| 3109 | // into this reconcile. So by the time this delete |
| 3110 | // is ordered, the proof already happened, and |
| 3111 | // nothing here decides anything. The old |
| 3112 | // sync_refused probe asked the same question a |
| 3113 | // second way and was wrong more often: it refused |
| 3114 | // for any database the replicator never |
| 3115 | // registered, leaving the entry to outlive its |
| 3116 | // alarm forever. |
| 3117 | crate::js::reconcile_wake_entry(&cell, next_alarm_ms, true).await; |
| 3118 | }) |
| 3119 | .detach(); |
| 3120 | } |
| 3121 | } |
| 3122 | } |
| 3123 | Effect::ReleaseOwner { op, cell, epoch } => { |
| 3124 | if self.handoff_timings.contains_key(&cell) { |
| 3125 | self.handoff_phase_ops.insert( |
| 3126 | op, |
| 3127 | ( |
| 3128 | cell.clone(), |
| 3129 | HandoffPhase::Release, |
| 3130 | crate::asyncrt::mono_ms(), |
| 3131 | ), |
| 3132 | ); |
| 3133 | } |
| 3134 | let ownership = self.ownership.clone(); |
| 3135 | out.effects.push(Box::pin(async move { |
| 3136 | let result = ownership.release_owner(&cell, epoch).await; |
| 3137 | CompletedEffect::plain(Event::OwnerReleased { op, result }) |
| 3138 | })); |
| 3139 | } |
| 3140 | Effect::AdoptReleased { |
| 3141 | op, |
| 3142 | cell, |
| 3143 | released_epoch, |
| 3144 | } => { |
| 3145 | // The in-memory adapter is one process, so it has no successor |
| 3146 | // to acknowledge a handoff. The feature switch is an escape |
| 3147 | // hatch for mixed operational use, not the production default. |
| 3148 | if !self.paced_handoff || matches!(&self.ownership, Ownership::Memory(_)) { |
| 3149 | immediate.push_back(Event::SuccessorAdopted { |
| 3150 | op, |
| 3151 | result: Err(Failure::Definite), |
| 3152 | }); |
| 3153 | return; |
| 3154 | } |
| 3155 | if self.handoff_timings.contains_key(&cell) { |
| 3156 | self.handoff_phase_ops.insert( |
| 3157 | op, |
| 3158 | (cell.clone(), HandoffPhase::Adopt, crate::asyncrt::mono_ms()), |
| 3159 | ); |
| 3160 | } |
| 3161 | let ownership = self.ownership.clone(); |
| 3162 | let directory = self.handoff_directory.clone(); |
| 3163 | let http = self.peer_http.clone(); |
| 3164 | let auth = self.peer_auth.clone(); |
| 3165 | let source = self.state.node().to_string(); |
| 3166 | out.effects.push(Box::pin(async move { |
| 3167 | let started_mono_ms = crate::asyncrt::mono_ms(); |
| 3168 | let request = HandoffRequest { |
| 3169 | cell: cell.clone(), |
| 3170 | released_epoch, |
| 3171 | }; |
| 3172 | let mut attempts = 0_u64; |
| 3173 | loop { |
| 3174 | let peers = handoff_candidates(&ownership, &directory, &source, &cell) |
| 3175 | .await |
| 3176 | .unwrap_or_default(); |
| 3177 | for peer in peers { |
| 3178 | let mut target = AdoptedCell { |
| 3179 | node: peer.node, |
| 3180 | addr: peer.addr, |
| 3181 | epoch: 0, |
| 3182 | peer_protocol: peer.peer_protocol, |
| 3183 | }; |
| 3184 | let mut visited = BTreeSet::new(); |
| 3185 | for _ in 0..4 { |
| 3186 | if target.node == source |
| 3187 | || target.addr.is_empty() |
| 3188 | || target.peer_protocol != peer_auth::PROTOCOL_VERSION |
| 3189 | || !visited.insert(target.node.clone()) |
| 3190 | { |
| 3191 | break; |
| 3192 | } |
| 3193 | attempts = attempts.saturating_add(1); |
| 3194 | match request_peer_handoff(&http, &auth, &target, &request).await { |
| 3195 | Ok(HandoffAttempt::Accepted(adopted)) |
| 3196 | if adopted.epoch > released_epoch => |
| 3197 | { |
| 3198 | tracing::info!( |
| 3199 | event = "cell_handoff_accepted", |
| 3200 | %cell, |
| 3201 | released_epoch, |
| 3202 | successor = %adopted.node, |
| 3203 | successor_epoch = adopted.epoch, |
| 3204 | attempts, |
| 3205 | elapsed_ms = crate::asyncrt::mono_ms() |
| 3206 | .saturating_sub(started_mono_ms), |
| 3207 | "successor acquired a released cell for demand-driven restore" |
| 3208 | ); |
| 3209 | return CompletedEffect::plain(Event::SuccessorAdopted { |
| 3210 | op, |
| 3211 | result: Ok(adopted), |
| 3212 | }); |
| 3213 | } |
| 3214 | Ok(HandoffAttempt::CurrentOwner(owner)) => { |
| 3215 | target = owner; |
| 3216 | } |
| 3217 | Ok(HandoffAttempt::Accepted(_)) |
| 3218 | | Ok(HandoffAttempt::Refused) |
| 3219 | | Err(_) => break, |
| 3220 | } |
| 3221 | } |
| 3222 | } |
| 3223 | // No peer can accept yet. Retain the core permit and |
| 3224 | // retry until the process-wide shutdown deadline. |
| 3225 | crate::asyncrt::sleep(HANDOFF_RETRY_DELAY).await; |
| 3226 | } |
| 3227 | })); |
| 3228 | } |
| 3229 | Effect::CancelCellActivity { |
| 3230 | cell, |
| 3231 | requests, |
| 3232 | websockets, |
| 3233 | keep_hibernatable, |
| 3234 | } => { |
| 3235 | self.handoff_timings |
| 3236 | .entry(cell.clone()) |
| 3237 | .or_insert(HandoffCellTiming { |
| 3238 | nominated_mono_ms: crate::asyncrt::mono_ms(), |
| 3239 | quiesce_us: None, |
| 3240 | durability_us: None, |
| 3241 | stop_us: None, |
| 3242 | release_us: None, |
| 3243 | }); |
| 3244 | for request in requests { |
| 3245 | if let Some((request_id, phase)) = self |
| 3246 | .drain_pins |
| 3247 | .cancel_core_request(request, "shutdown_quiesce") |
| 3248 | { |
| 3249 | if phase == "handler" { |
| 3250 | if let (Some(runtime), Some(request_id)) = (&self.host, request_id) { |
| 3251 | runtime.abort_fetch(&cell, request_id); |
| 3252 | } |
| 3253 | } |
| 3254 | } |
| 3255 | } |
| 3256 | if !websockets.is_empty() { |
| 3257 | if keep_hibernatable { |
| 3258 | for websocket in &websockets { |
| 3259 | crate::js::ws_close(*websocket, 1012, "service restart"); |
| 3260 | } |
| 3261 | } else { |
| 3262 | crate::js::ws_close_scope(&cell, 1012, "service restart"); |
| 3263 | } |
| 3264 | for websocket in websockets { |
| 3265 | crate::js::ws_unregister(websocket); |
| 3266 | immediate.push_back(Event::WebSocketClosed { |
| 3267 | cell: cell.clone(), |
| 3268 | websocket, |
| 3269 | }); |
| 3270 | } |
| 3271 | } |
| 3272 | } |
| 3273 | Effect::Restore { op, cell, spec } => { |
| 3274 | self.route_effect_started(&cell); |
| 3275 | if let Some(runtime) = self.host.clone() { |
| 3276 | let timing_cell = cell.clone(); |
| 3277 | // A restore downloads, merges, and fsyncs a whole |
| 3278 | // database. Poll it on the host runtime: this future |
| 3279 | // lives in `out`, which the core thread drives, |
| 3280 | // and the core owns the node lease timer. |
| 3281 | let task = crate::asyncrt::spawn(async move { |
| 3282 | let started = crate::asyncrt::mono_ms(); |
| 3283 | let result = runtime.restore_cell(&cell, &spec).await.map_err(|error| { |
| 3284 | eprintln!("celld restore failed for {cell}: {error:#}"); |
| 3285 | Failure::Definite |
| 3286 | }); |
| 3287 | CompletedEffect::timed( |
| 3288 | Event::RestoreCompleted { op, result }, |
| 3289 | timing_cell, |
| 3290 | RouteStage::Restore, |
| 3291 | started, |
| 3292 | ) |
| 3293 | }); |
| 3294 | out.effects.push(Box::pin(async move { |
| 3295 | task.await.expect("restore task panicked") |
| 3296 | })); |
| 3297 | } else { |
| 3298 | self.record_effect_timing(EffectTiming { |
| 3299 | cell, |
| 3300 | stage: RouteStage::Restore, |
| 3301 | elapsed_us: 0, |
| 3302 | }); |
| 3303 | immediate.push_back(Event::RestoreCompleted { |
| 3304 | op, |
| 3305 | result: Ok(celld_logic::RestoreOutcome { |
| 3306 | restored: false, |
| 3307 | alarm: None, |
| 3308 | }), |
| 3309 | }); |
| 3310 | } |
| 3311 | } |
| 3312 | Effect::StartRuntime { op, cell, epoch } => { |
| 3313 | self.route_effect_started(&cell); |
| 3314 | if let Some(runtime) = self.host.clone() { |
| 3315 | let fresh = self |
| 3316 | .route_timings |
| 3317 | .get(&cell) |
| 3318 | .and_then(|timing| timing.fresh) |
| 3319 | .unwrap_or(false); |
| 3320 | let timing_cell = cell.clone(); |
| 3321 | out.effects.push(Box::pin(async move { |
| 3322 | let started = crate::asyncrt::mono_ms(); |
| 3323 | let placed = runtime |
| 3324 | .start_cell(cell.clone(), epoch, fresh) |
| 3325 | .await |
| 3326 | .map_err(|error| { |
| 3327 | eprintln!("celld runtime start failed for {cell}: {error:#}"); |
| 3328 | Failure::Definite |
| 3329 | }); |
| 3330 | let isolate = placed.as_ref().ok().map(|(isolate, _)| *isolate); |
| 3331 | let generation = placed |
| 3332 | .as_ref() |
| 3333 | .ok() |
| 3334 | .map_or(0, |(_, generation)| *generation); |
| 3335 | CompletedEffect::timed( |
| 3336 | Event::RuntimeStarted { |
| 3337 | op, |
| 3338 | isolate, |
| 3339 | generation, |
| 3340 | result: placed.map(|_| ()), |
| 3341 | }, |
| 3342 | timing_cell, |
| 3343 | RouteStage::IsolateStartup, |
| 3344 | started, |
| 3345 | ) |
| 3346 | })); |
| 3347 | } else { |
| 3348 | self.record_effect_timing(EffectTiming { |
| 3349 | cell, |
| 3350 | stage: RouteStage::IsolateStartup, |
| 3351 | elapsed_us: 0, |
| 3352 | }); |
| 3353 | immediate.push_back(Event::RuntimeStarted { |
| 3354 | op, |
| 3355 | isolate: None, |
| 3356 | generation: 0, |
| 3357 | result: Ok(()), |
| 3358 | }); |
| 3359 | } |
| 3360 | } |
| 3361 | Effect::Publish { op, cell, epoch } => { |
| 3362 | self.route_effect_started(&cell); |
| 3363 | let publish_started = crate::asyncrt::mono_ms(); |
| 3364 | self.publishes += 1; |
| 3365 | let result = if self.fail_publish_once { |
| 3366 | self.fail_publish_once = false; |
| 3367 | Err(Failure::Ambiguous) |
| 3368 | } else { |
| 3369 | self.host |
| 3370 | .as_ref() |
| 3371 | .map_or(Ok(()), |runtime| runtime.publish_cell(&cell, epoch)) |
| 3372 | .map_err(|error| { |
| 3373 | eprintln!("celld runtime publication failed for {cell}: {error:#}"); |
| 3374 | Failure::Definite |
| 3375 | }) |
| 3376 | }; |
| 3377 | if result.is_ok() { |
| 3378 | self.published.insert(cell.clone()); |
| 3379 | } |
| 3380 | self.record_effect_timing(EffectTiming { |
| 3381 | cell: cell.clone(), |
| 3382 | stage: RouteStage::RegistryInsert, |
| 3383 | elapsed_us: mono_elapsed_us(publish_started), |
| 3384 | }); |
| 3385 | if result.is_ok() { |
| 3386 | let node = self.state.node().to_string(); |
| 3387 | self.finish_route(&cell, "activated", "", Some((&node, epoch))); |
| 3388 | } |
| 3389 | immediate.push_back(Event::Published { op, result }); |
| 3390 | } |
| 3391 | Effect::EnsureDurable { op, cell, epoch } => { |
| 3392 | if let Some(timing) = self.handoff_timings.get_mut(&cell) { |
| 3393 | if timing.quiesce_us.is_none() { |
| 3394 | timing.quiesce_us = Some(mono_elapsed_us(timing.nominated_mono_ms)); |
| 3395 | } |
| 3396 | self.handoff_phase_ops.insert( |
| 3397 | op, |
| 3398 | ( |
| 3399 | cell.clone(), |
| 3400 | HandoffPhase::Durability, |
| 3401 | crate::asyncrt::mono_ms(), |
| 3402 | ), |
| 3403 | ); |
| 3404 | } |
| 3405 | let waiters = self.eviction_waiters.remove(&cell).unwrap_or_default(); |
| 3406 | self.durability_waiters.insert(op, (cell.clone(), waiters)); |
| 3407 | if let Some(runtime) = self.host.clone() { |
| 3408 | out.effects.push(Box::pin(async move { |
| 3409 | let result = runtime.ensure_durable(&cell, epoch).await.map_err(|error| { |
| 3410 | eprintln!( |
| 3411 | "celld durability proof failed for {cell} epoch {epoch}: {error:#}" |
| 3412 | ); |
| 3413 | Failure::Ambiguous |
| 3414 | }); |
| 3415 | CompletedEffect::plain(Event::DurabilityChecked { op, result }) |
| 3416 | })); |
| 3417 | } else { |
| 3418 | immediate.push_back(Event::DurabilityChecked { op, result: Ok(()) }); |
| 3419 | } |
| 3420 | } |
| 3421 | // The output gate: prove the cell durable, then let the core release |
| 3422 | // the held write response. Reuses the same recency-proving primitive |
| 3423 | // as EnsureDurable — a proof issued after the write covers it. |
| 3424 | Effect::AwaitDurable { |
| 3425 | op, |
| 3426 | cell, |
| 3427 | epoch, |
| 3428 | position, |
| 3429 | } => { |
| 3430 | if let Some(runtime) = self.host.clone() { |
| 3431 | out.effects.push(Box::pin(async move { |
| 3432 | // The replicator reports the position it actually |
| 3433 | // proved durable and which mechanism proved it; the |
| 3434 | // core acks only if the position covers this write, |
| 3435 | // and decides per source whether ownership |
| 3436 | // verification must run first (Effect::VerifyOwnership). |
| 3437 | let (result, source) = |
| 3438 | match runtime.await_durable(&cell, epoch, position).await { |
| 3439 | Ok((durable, source)) => (Ok(durable), source), |
| 3440 | Err(error) => { |
| 3441 | eprintln!( |
| 3442 | "celld output-gate durability proof failed for {cell} \ |
| 3443 | epoch {epoch}: {error:#}" |
| 3444 | ); |
| 3445 | (Err(Failure::Ambiguous), celld_logic::ProofSource::Bucket) |
| 3446 | } |
| 3447 | }; |
| 3448 | CompletedEffect::plain(Event::DurableReached { op, result, source }) |
| 3449 | })); |
| 3450 | } else { |
| 3451 | immediate.push_back(Event::DurableReached { |
| 3452 | op, |
| 3453 | result: Ok(position), |
| 3454 | source: celld_logic::ProofSource::Fleet, |
| 3455 | }); |
| 3456 | } |
| 3457 | } |
| 3458 | Effect::VerifyOwnership { op, cell, epoch } => { |
| 3459 | // Verify ownership for bucket-proof acks. Durable in |
| 3460 | // `e<epoch>/` is not the same as durable: if the cell has been taken over, that |
| 3461 | // prefix is orphaned — the next owner restores a higher |
| 3462 | // epoch and this write is gone. A read is enough, and is why |
| 3463 | // this is one GET rather than a compare-and-swap: if the |
| 3464 | // record still names us, no takeover linearised before this |
| 3465 | // read; the LTX went up before it; so any later takeover |
| 3466 | // restores from a lineage that already contains the write. |
| 3467 | let ownership = self.ownership.clone(); |
| 3468 | let node = self.state.node().to_string(); |
| 3469 | out.effects.push(Box::pin(async move { |
| 3470 | let result = match ownership.read_owner(&cell).await { |
| 3471 | Ok(Some(record)) |
| 3472 | if record.node.as_deref() == Some(node.as_str()) |
| 3473 | && record.epoch == epoch => |
| 3474 | { |
| 3475 | Ok(()) |
| 3476 | } |
| 3477 | Ok(record) => { |
| 3478 | eprintln!( |
| 3479 | "celld output gate: {cell} epoch {epoch} is no longer ours \ |
| 3480 | (record: {record:?}); refusing to acknowledge a write in an \ |
| 3481 | orphaned epoch" |
| 3482 | ); |
| 3483 | Err(Failure::Definite) |
| 3484 | } |
| 3485 | Err(failure) => Err(failure), |
| 3486 | }; |
| 3487 | CompletedEffect::plain(Event::OwnershipVerified { op, result }) |
| 3488 | })); |
| 3489 | } |
| 3490 | // The shell's only per-channel code: how the effect was held, and |
| 3491 | // how it is released. Five of the six channels take a durability |
| 3492 | // ticket and wait on a oneshot, so they collapse onto one adapter. |
| 3493 | // Only `WsHibernatable` needs another, and only because a socket is |
| 3494 | // an ordered stream whose frames must drain in barrier order. |
| 3495 | // |
| 3496 | // The channel says which way the effect leaves; `ws_gated` says how |
| 3497 | // this one is being held. They agree except in one case, and there |
| 3498 | // the holding mechanism decides: a frame for a hibernatable socket |
| 3499 | // raised OUTSIDE a `webSocketMessage` handler -- from `fetch`, an |
| 3500 | // alarm, or `webSocketClose` -- is never captured, so it waits on a |
| 3501 | // ticket like every other channel rather than in the cell's barrier |
| 3502 | // queue. Routing it to the barrier queue would find no entry and |
| 3503 | // strand the task waiting on the ticket. |
| 3504 | Effect::Release { |
| 3505 | request, |
| 3506 | channel, |
| 3507 | result, |
| 3508 | } => { |
| 3509 | let held = HeldOutputKey { request, channel }; |
| 3510 | match channel { |
| 3511 | Channel::WsHibernatable if self.ws_gated.contains_key(&held) => { |
| 3512 | self.ws_release(held, result.is_ok()) |
| 3513 | } |
| 3514 | Channel::Response |
| 3515 | | Channel::Fetch |
| 3516 | | Channel::WsHibernatable |
| 3517 | | Channel::WsSelf |
| 3518 | | Channel::Service |
| 3519 | | Channel::CellRpc |
| 3520 | | Channel::Queue => { |
| 3521 | if let Some(reply) = self.gated_responses.remove(&held) { |
| 3522 | let _ = reply.send(result); |
| 3523 | } |
| 3524 | } |
| 3525 | } |
| 3526 | } |
| 3527 | Effect::StopRuntime { |
| 3528 | op, |
| 3529 | cell, |
| 3530 | epoch, |
| 3531 | cause, |
| 3532 | } => { |
| 3533 | if self.handoff_timings.contains_key(&cell) { |
| 3534 | self.handoff_phase_ops.insert( |
| 3535 | op, |
| 3536 | (cell.clone(), HandoffPhase::Stop, crate::asyncrt::mono_ms()), |
| 3537 | ); |
| 3538 | } |
| 3539 | self.stops += 1; |
| 3540 | if matches!(cause, StopCause::Swap) { |
| 3541 | // A generation swap: the cell leaves its isolate and |
| 3542 | // nothing else changes. No durability barrier, no |
| 3543 | // replica release, no local unlink -- the same epoch |
| 3544 | // starts again on the current generation as soon as the |
| 3545 | // core hears the stop. |
| 3546 | self.published.remove(&cell); |
| 3547 | if let Some(runtime) = self.host.clone() { |
| 3548 | let released = cell.clone(); |
| 3549 | let task = crate::asyncrt::spawn(report_stopped_when_released( |
| 3550 | op, |
| 3551 | cell, |
| 3552 | epoch, |
| 3553 | "generation_swap_out_retry", |
| 3554 | move || { |
| 3555 | let runtime = runtime.clone(); |
| 3556 | let cell = released.clone(); |
| 3557 | async move { runtime.swap_out_cell(&cell, epoch).await } |
| 3558 | }, |
| 3559 | )); |
| 3560 | out.effects.push(Box::pin(async move { |
| 3561 | task.await.expect("swap out task panicked") |
| 3562 | })); |
| 3563 | } else { |
| 3564 | immediate.push_back(Event::RuntimeStopped { op }); |
| 3565 | } |
| 3566 | } else { |
| 3567 | let evicting = matches!(cause, StopCause::Evict { .. }); |
| 3568 | if matches!(cause, StopCause::Fence) { |
| 3569 | // A fenced cell's wake entry belongs to whoever takes the |
| 3570 | // cell over; a retained local belief would collide with |
| 3571 | // the new owner's arm/consume traffic on the same key. |
| 3572 | crate::js::forget_wake_entry(&cell); |
| 3573 | } |
| 3574 | // Keep the persistence decision whole. A cleanup still has |
| 3575 | // authority, so it makes the closed image a proved local |
| 3576 | // base. A fence can only close in place, and a reset must |
| 3577 | // discard the database that failed its durability proof. |
| 3578 | let stop_mode = match cause { |
| 3579 | StopCause::Evict { rebalance } => crate::runtime::StopMode::Evict { |
| 3580 | preserve_local: !rebalance, |
| 3581 | }, |
| 3582 | StopCause::Cleanup => crate::runtime::StopMode::Rebase, |
| 3583 | StopCause::Fence => crate::runtime::StopMode::CloseInPlace, |
| 3584 | StopCause::Reset => crate::runtime::StopMode::Discard, |
| 3585 | StopCause::Swap => unreachable!("generation swaps return above"), |
| 3586 | }; |
| 3587 | if evicting { |
| 3588 | if let Some(live) = &self.live_load { |
| 3589 | live.shed_cells.fetch_add(1, Ordering::Relaxed); |
| 3590 | } |
| 3591 | } |
| 3592 | self.published.remove(&cell); |
| 3593 | if let Some(runtime) = self.host.clone() { |
| 3594 | // A stop closes a whole database. It fsyncs the directory |
| 3595 | // and the file, then unlinks the local copy, and it does |
| 3596 | // all of that inside one synchronous call. Poll it on the |
| 3597 | // host runtime: this future lives in `out`, which the core |
| 3598 | // thread drives in the same select as the timer queue, and |
| 3599 | // the core owns the node lease timer. A slow fsync on the |
| 3600 | // core thread starves the lease renew and the lease fence, |
| 3601 | // and the node then fences itself. |
| 3602 | let released = cell.clone(); |
| 3603 | let task = crate::asyncrt::spawn(report_stopped_when_released( |
| 3604 | op, |
| 3605 | cell, |
| 3606 | epoch, |
| 3607 | "stop_runtime_retry", |
| 3608 | move || { |
| 3609 | let runtime = runtime.clone(); |
| 3610 | let cell = released.clone(); |
| 3611 | async move { runtime.stop_cell(&cell, epoch, stop_mode).await } |
| 3612 | }, |
| 3613 | )); |
| 3614 | out.effects.push(Box::pin(async move { |
| 3615 | task.await.expect("stop runtime task panicked") |
| 3616 | })); |
| 3617 | } else { |
| 3618 | immediate.push_back(Event::RuntimeStopped { op }); |
| 3619 | } |
| 3620 | } |
| 3621 | } |
| 3622 | Effect::FireAlarm { |
| 3623 | op, |
| 3624 | cell, |
| 3625 | epoch, |
| 3626 | scheduled_ms, |
| 3627 | } => { |
| 3628 | if let Some(runtime) = self.host.clone() { |
| 3629 | out.effects.push(Box::pin(async move { |
| 3630 | // The shell reports the firing raw: the deadline that |
| 3631 | // stands after the handler, whether a wake entry |
| 3632 | // covers it, and the position of the consuming |
| 3633 | // commit. Proving that commit durable — and this node |
| 3634 | // still the owner — is the core's job: it opens the |
| 3635 | // same output gate a request's write gets, so one |
| 3636 | // question answers for every egress on the cell, and |
| 3637 | // the consume-side wake-entry delete leaves only from |
| 3638 | // the far side of the proof. On failure the core |
| 3639 | // re-arms or resets; either way the entry stays |
| 3640 | // discoverable and at-least-once holds. |
| 3641 | let result = runtime |
| 3642 | .fire_alarm(cell.clone(), scheduled_ms) |
| 3643 | .await |
| 3644 | .map_err(|error| { |
| 3645 | eprintln!("celld alarm dispatch failed: {error:#}"); |
| 3646 | Failure::Definite |
| 3647 | }); |
| 3648 | CompletedEffect::plain(Event::AlarmFinished { |
| 3649 | op, |
| 3650 | cell, |
| 3651 | epoch, |
| 3652 | now_ms: now_ms(), |
| 3653 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 3654 | result, |
| 3655 | }) |
| 3656 | })); |
| 3657 | } else { |
| 3658 | immediate.push_back(Event::AlarmFinished { |
| 3659 | op, |
| 3660 | cell, |
| 3661 | epoch, |
| 3662 | now_ms: now_ms(), |
| 3663 | now_mono_ms: crate::asyncrt::mono_ms(), |
| 3664 | result: Ok((None, true, None)), |
| 3665 | }); |
| 3666 | } |
| 3667 | } |
| 3668 | Effect::Complete { request, result } => { |
| 3669 | if let Some(cell) = self.request_cells.remove(&request) { |
| 3670 | match &result { |
| 3671 | Ok(Route::Remote { node, epoch, .. }) => { |
| 3672 | self.finish_route(&cell, "remote_owner", "", Some((node, *epoch))); |
| 3673 | // The cell lives elsewhere: its wake entry is no |
| 3674 | // longer this node's to track, and a stale local |
| 3675 | // belief would collide with the owner's own |
| 3676 | // arm/consume traffic on the same key. |
| 3677 | crate::js::forget_wake_entry(&cell); |
| 3678 | } |
| 3679 | Ok(Route::Local) => { |
| 3680 | self.finish_route(&cell, "resident_after_wait", "", None); |
| 3681 | } |
| 3682 | Err(error) => { |
| 3683 | self.finish_route( |
| 3684 | &cell, |
| 3685 | "route_error", |
| 3686 | request_error_phase(*error), |
| 3687 | None, |
| 3688 | ); |
| 3689 | } |
| 3690 | } |
| 3691 | } |
| 3692 | if let Some(reply) = self.pending.remove(&request) { |
| 3693 | let local = result == Ok(Route::Local); |
| 3694 | if reply |
| 3695 | .send(result.map(|route| Routed { request, route })) |
| 3696 | .is_err() |
| 3697 | && local |
| 3698 | { |
| 3699 | immediate.push_back(Event::ActivityFinished { request }); |
| 3700 | } |
| 3701 | } |
| 3702 | } |
| 3703 | Effect::CompleteWorker { request, route } => { |
| 3704 | if let Some(op) = route.as_ref().and_then(|route| route.retired_durability) { |
| 3705 | if let Some((_, waiters)) = self.durability_waiters.remove(&op) { |
| 3706 | for waiter in waiters { |
| 3707 | let _ = waiter.send(()); |
| 3708 | } |
| 3709 | } |
| 3710 | } |
| 3711 | if let Some(reply) = self.pending_workers.remove(&request) { |
| 3712 | let reserved = route.is_some(); |
| 3713 | if reply.send(WorkerRouted { request, route }).is_err() && reserved { |
| 3714 | immediate.push_back(Event::ActivityFinished { request }); |
| 3715 | } |
| 3716 | } |
| 3717 | } |
| 3718 | Effect::CloseWebSocket { cell, websocket } => { |
| 3719 | // The core declined to hold this transport. Drop it and tell |
| 3720 | // the core it is gone, so the cell is not left believing it |
| 3721 | // has a socket the node already closed. |
| 3722 | eprintln!( |
| 3723 | "celld refused an outbound WebSocket for {cell}: the node's \ |
| 3724 | outbound pin budget is spent" |
| 3725 | ); |
| 3726 | crate::js::ws_unregister(websocket); |
| 3727 | immediate.push_back(Event::WebSocketClosed { cell, websocket }); |
| 3728 | } |
| 3729 | Effect::Halt { code, reason } => { |
| 3730 | // Say why before going. Self-fencing is the most drastic thing |
| 3731 | // this process does, and an exit code on its own leaves an |
| 3732 | // operator to guess between a lease it could not renew, a |
| 3733 | // replicator that died, and a crash. |
| 3734 | match reason { |
| 3735 | celld_logic::HaltReason::NodeLeaseExpired => tracing::warn!( |
| 3736 | event = "node_lease_watchdog_fence", |
| 3737 | code, |
| 3738 | "SELF-FENCE: node lease not renewed within TTL — halting" |
| 3739 | ), |
| 3740 | } |
| 3741 | let _ = self.fence.send(code); |
| 3742 | } |
| 3743 | } |
| 3744 | } |
| 3745 | |
| 3746 | fn state_json(&self) -> String { |
| 3747 | let activity = self.state.presence_snapshot().activity; |
| 3748 | let residents = self |
| 3749 | .state |
| 3750 | .residents() |
| 3751 | .into_iter() |
| 3752 | .map(|cell| format!("{cell:?}")) |
| 3753 | .collect::<Vec<_>>() |
| 3754 | .join(","); |
| 3755 | let published = self |
| 3756 | .published |
| 3757 | .iter() |
| 3758 | .map(|cell| format!("{cell:?}")) |
| 3759 | .collect::<Vec<_>>() |
| 3760 | .join(","); |
| 3761 | // Both numbers: a gap between them is memory the allocator kept, which |
| 3762 | // no eviction returns. One sample, so they cannot disagree. |
| 3763 | let memory = crate::memory::sample(); |
| 3764 | // `restoring` is a sum, and a node that refuses cells for a quarter of |
| 3765 | // an hour needs its parts. `activating` holds a permit and is doing |
| 3766 | // work; `activation_waiting` is queued behind the activation ceiling; |
| 3767 | // `capacity_waiting` is queued behind residency. The census says where |
| 3768 | // every cell is, which `occupied` cannot: it counts residency, so a |
| 3769 | // node part-way through thousands of cold starts reports almost none. |
| 3770 | // Issue #50 is open because none of this was recorded at the time. |
| 3771 | let phases = self |
| 3772 | .state |
| 3773 | .phase_census() |
| 3774 | .into_iter() |
| 3775 | .map(|(phase, count)| format!("{phase:?}:{count}")) |
| 3776 | .collect::<Vec<_>>() |
| 3777 | .join(","); |
| 3778 | format!( |
| 3779 | "{{\"ownership\":{:?},\"occupied\":{},\"quiescing\":{},\"evicting\":{},\"releasing\":{},\"adopting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"handed_off\":{},\"handoff_failed\":{},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"cgroup_working_set_bytes\":{},\"cgroup_current_bytes\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}", |
| 3780 | self.ownership.name(), |
| 3781 | self.state.occupied(), |
| 3782 | self.state.quiescing(), |
| 3783 | self.state.evicting(), |
| 3784 | self.state.releasing(), |
| 3785 | self.state.adopting(), |
| 3786 | self.state.activation_backlog(), |
| 3787 | self.state.activating(), |
| 3788 | self.state.activation_waiting().len(), |
| 3789 | self.state.waiting().len(), |
| 3790 | phases, |
| 3791 | activity.handed_off, |
| 3792 | activity.handoff_failed, |
| 3793 | self.state |
| 3794 | .shed_reason() |
| 3795 | .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")), |
| 3796 | memory.rss_bytes, |
| 3797 | memory.in_use_bytes, |
| 3798 | memory |
| 3799 | .cgroup_working_set_bytes |
| 3800 | .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()), |
| 3801 | memory |
| 3802 | .cgroup_current_bytes |
| 3803 | .map_or_else(|| "null".to_string(), |bytes| bytes.to_string()), |
| 3804 | residents, |
| 3805 | published, |
| 3806 | self.publishes, |
| 3807 | self.stops |
| 3808 | ) |
| 3809 | } |
| 3810 | |
| 3811 | fn begin_route_if_cold(&mut self, cell: &str) { |
| 3812 | if !matches!( |
| 3813 | self.state.phase(cell), |
| 3814 | Some(Phase::Resident { .. } | Phase::EnsuringDurability { .. } | Phase::Remote { .. }) |
| 3815 | ) { |
| 3816 | self.route_timings |
| 3817 | .entry(cell.to_string()) |
| 3818 | .or_insert_with(CellRouteTiming::new); |
| 3819 | } |
| 3820 | } |
| 3821 | |
| 3822 | fn route_effect_started(&mut self, cell: &str) { |
| 3823 | if let Some(timing) = self.route_timings.get_mut(cell) { |
| 3824 | timing.effect_started(); |
| 3825 | } |
| 3826 | } |
| 3827 | |
| 3828 | fn observe_capacity_wait(&mut self, cell: &str) { |
| 3829 | if matches!(self.state.phase(cell), Some(Phase::WaitingCapacity)) { |
| 3830 | if let Some(timing) = self.route_timings.get_mut(cell) { |
| 3831 | timing |
| 3832 | .capacity_wait_started_mono_ms |
| 3833 | .get_or_insert_with(crate::asyncrt::mono_ms); |
| 3834 | } |
| 3835 | } |
| 3836 | } |
| 3837 | |
| 3838 | fn record_effect_timing(&mut self, completed: EffectTiming) { |
| 3839 | if let Some(timing) = self.route_timings.get_mut(&completed.cell) { |
| 3840 | timing.record(completed.stage, completed.elapsed_us); |
| 3841 | } |
| 3842 | } |
| 3843 | |
| 3844 | fn finish_route( |
| 3845 | &mut self, |
| 3846 | cell: &str, |
| 3847 | outcome: &str, |
| 3848 | failure_phase: &str, |
| 3849 | owner: Option<(&str, u64)>, |
| 3850 | ) { |
| 3851 | let Some(mut timing) = self.route_timings.remove(cell) else { |
| 3852 | return; |
| 3853 | }; |
| 3854 | if let Some(started) = timing.capacity_wait_started_mono_ms.take() { |
| 3855 | timing.capacity_wait_us = timing |
| 3856 | .capacity_wait_us |
| 3857 | .saturating_add(mono_elapsed_us(started)); |
| 3858 | } |
| 3859 | let (owner_node, epoch) = owner.unwrap_or(("", 0)); |
| 3860 | tracing::debug!( |
| 3861 | target: "timing", |
| 3862 | event = "cell_route_timing", |
| 3863 | outcome, |
| 3864 | failure_phase, |
| 3865 | scope = %cell, |
| 3866 | node = %self.state.node(), |
| 3867 | region = %self.region, |
| 3868 | runtime_version = env!("CARGO_PKG_VERSION"), |
| 3869 | owner_node, |
| 3870 | epoch, |
| 3871 | fresh = timing.fresh.unwrap_or(false), |
| 3872 | total_us = mono_elapsed_us(timing.started_mono_ms), |
| 3873 | latch_wait_us = timing.latch_wait_us, |
| 3874 | ownership_read_us = timing.ownership_read_us, |
| 3875 | node_lease_lookup_us = timing.node_lease_lookup_us, |
| 3876 | capacity_lookup_us = timing.capacity_lookup_us, |
| 3877 | capacity_wait_us = timing.capacity_wait_us, |
| 3878 | activation_slot_wait_us = timing.activation_slot_wait_us, |
| 3879 | lease_permit_us = timing.lease_permit_us, |
| 3880 | ownership_acquire_us = timing.ownership_acquire_us, |
| 3881 | replica_discovery_us = timing.replica_discovery_us, |
| 3882 | restore_us = timing.restore_us, |
| 3883 | isolate_startup_us = timing.isolate_startup_us, |
| 3884 | registry_insert_us = timing.registry_insert_us, |
| 3885 | "cell route resolved" |
| 3886 | ); |
| 3887 | } |
| 3888 | } |
| 3889 | |
| 3890 | fn request_error_phase(error: RequestError) -> &'static str { |
| 3891 | match error { |
| 3892 | RequestError::NodeUnavailable | RequestError::NodeFenced => "node_authority", |
| 3893 | RequestError::ResolveFailed | RequestError::PeerIncompatible => "ownership_lookup", |
| 3894 | RequestError::CapacityExhausted => "capacity_wait", |
| 3895 | RequestError::AcquireFailed => "ownership_acquire", |
| 3896 | RequestError::RestoreFailed => "restore", |
| 3897 | RequestError::RuntimeFailed => "isolate_startup", |
| 3898 | RequestError::PublishFailed => "registry_insert", |
| 3899 | RequestError::DurabilityUnproven => "output_gate", |
| 3900 | } |
| 3901 | } |
| 3902 | |
| 3903 | #[cfg(not(all(test, celld_internal_tests)))] |
| 3904 | type ActorState = State; |
| 3905 | |
| 3906 | #[cfg(not(all(test, celld_internal_tests)))] |
| 3907 | fn apply_core_event(state: &mut ActorState, event: Event) -> Vec<Effect> { |
| 3908 | on_event(state, event) |
| 3909 | } |
| 3910 | |
| 3911 | #[cfg(all(test, celld_internal_tests))] |
| 3912 | include!(env!("CELLD_INTERNAL_ACTOR_OBSERVERS")); |