Diffinery

homeflare/celldpublic

v0.3.0

- v0.3.0 adds a replicated write-behind log. Fleets of two or more nodes
  acknowledge writes after peer fsync while bucket upload finishes later. In
  testing, this delivers 10× lower write latency and over 100× fewer Class A
  S3 operations. A v0.2.1 fleet can roll forward one node at a time.

- Added support for Azure Blob Storage (`az://<BUCKET_NAME>`).

- Added support for D1 databases, including the `celld d1` CLI for migrations
  and SQL execution.

- Added support for cron triggers, with durable fleet-wide scheduling, retries
  for failed handlers, and recovery of one missed run after downtime.

- Streaming and rewrapping request bodies are up to 70× faster, and text
  decoding is up to 44× faster.

- WebSocket upgrades now work correctly for Durable Object subrequests and
  cross-script service bindings.

- `setInterval()` now works correctly.

- `celld deploy` now accepts Node built-in specifiers (E.G. `node:util`)

- Each isolate now has a configurable V8 heap limit. celld refuses new
  hibernatable WebSockets and oversized SQL materialization near that limit,
  then resumes service after memory use falls.

- Correctness fixes prevent overlapping alarm handlers, events from resuming in
  freed isolates, lost transactions at replication segment boundaries, and
  database corruption after eviction and reactivation.

- Closed issues: [#139](https://github.com/denoland/celld/issues/139),
  [#144](https://github.com/denoland/celld/issues/144),
  [#147](https://github.com/denoland/celld/issues/147),
  [#149](https://github.com/denoland/celld/issues/149),
  [#150](https://github.com/denoland/celld/issues/150),
  [#152](https://github.com/denoland/celld/issues/152),
  [#154](https://github.com/denoland/celld/issues/154),
  [#155](https://github.com/denoland/celld/issues/155),
  [#156](https://github.com/denoland/celld/issues/156),
  [#157](https://github.com/denoland/celld/issues/157), and
  [#158](https://github.com/denoland/celld/issues/158).

Co-authored-by: Bartek Iwańczuk <[email protected]>
Co-authored-by: Ben Plotnick <[email protected]>
Co-authored-by: Nathan Whitaker <[email protected]>
Co-authored-by: Yusuke Tanaka <[email protected]>
Co-authored-by: magurotuna <[email protected]>
Ryan Dahl authored signed1 parent ae8fac0commit 89e4ffc53a14ecb496d2ca5014ff9d19b0061ad9Browse files
98 files changed+38625−25245
Files (98)
modifiedCargo.lock+16−1View file
@@ -288,11 +288,12 @@
288288
289289 [[package]]
290290 name = "celld"
291-version = "0.2.1"
291+version = "0.3.0"
292292 dependencies = [
293293 "aes",
294294 "aes-gcm",
295295 "anyhow",
296+ "async-trait",
296297 "axum",
297298 "base64 0.22.1",
298299 "bytes",
@@ -313,7 +314,9 @@
313314 "hyper",
314315 "hyper-util",
315316 "libc",
317+ "lz4_flex",
316318 "md-5",
319+ "nix",
317320 "object_store",
318321 "p256",
319322 "p384",
@@ -1680,6 +1683,18 @@
16801683 ]
16811684
16821685 [[package]]
1686+name = "nix"
1687+version = "0.31.3"
1688+source = "registry+https://github.com/rust-lang/crates.io-index"
1689+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
1690+dependencies = [
1691+ "bitflags",
1692+ "cfg-if",
1693+ "cfg_aliases",
1694+ "libc",
1695+]
1696+
1697+[[package]]
16831698 name = "nom"
16841699 version = "7.1.3"
16851700 source = "registry+https://github.com/rust-lang/crates.io-index"
modifiedCargo.toml+2−1View file
@@ -46,7 +46,7 @@
4646 # unstable-split gives the read and write halves as separate objects. The
4747 # tunnel needs them: a WebSocket read is not cancel-safe, so a live read
4848 # future must survive while the same socket is written, and that is only
49-# possible when the halves are not one borrow. See tests/p0/runtime/tunnel_cancel.rs.
49+# possible when the halves are not one borrow.
5050 #
5151 # The feature is unstable by name, so a 0.8.x release can rename or drop it
5252 # without upstream calling that a break, and a caret range would take it. Deno
@@ -64,6 +64,7 @@
6464 libc = "0.2"
6565 lz4_flex = { version = "0.11", features = ["frame"] }
6666 md-5 = "0.10"
67+nix = { version = "0.31", features = ["feature", "fs"] }
6768 object_store = { version = "0.11", default-features = false }
6869 # The native column-writer API only: no `arrow` feature, so the arrow
6970 # crate stack stays out of the binary. Revisit only if the telemetry
modifiedREADME.md+59−9View file
@@ -5,12 +5,13 @@
55 celld is an open-source daemon that runs Cloudflare Workers and Durable
66 Objects on your own machines. Each object is its own SQLite database.
77 celld addresses an object by name and replicates it to a bucket that you
8-own. The bucket can be S3-compatible or Google Cloud Storage. The nodes
9-coordinate through that bucket alone, with no control plane and no
10-consensus. Because every object is its own small database,
11-applications shard by construction — the contention and blast-radius failures
12-of one shared database are designed out, not managed. A cell that no node
13-holds is inactive, and an inactive cell costs nearly nothing. Learn more at
8+own. The bucket can be S3-compatible, Google Cloud Storage, or Azure
9+Blob Storage. The nodes coordinate through that bucket alone, with no
10+control plane and no consensus. Because every object is its own small
11+database, applications shard by construction — the contention and
12+blast-radius failures of one shared database are designed out, not
13+managed. A cell that no node holds is inactive, and an inactive cell
14+costs nearly nothing. Learn more at
1415 [celld.dev](https://celld.dev) or read the
1516 [documentation](https://celld.dev/docs).
1617
@@ -18,9 +19,10 @@
1819
1920 Every `celld` node embeds V8 and executes Wrangler bundles. The fleet shares
2021 one bucket, which contains deployments, cell state, and small ownership
21-records. The bucket can be S3-compatible or Google Cloud Storage. Object-storage compare-and-swap ensures that exactly one node owns a
22-cell at a time, without a membership protocol, failure detector, or consensus
23-service.
22+records. The bucket can be S3-compatible, Google Cloud Storage, or Azure
23+Blob Storage. Object-storage compare-and-swap ensures that exactly one
24+node owns a cell at a time, without a membership protocol, failure
25+detector, or consensus service.
2426
2527 celld continuously replicates each cell's SQLite database to the bucket.
2628 When a cell moves, or when an inactive cell activates, its new owner restores
@@ -109,6 +111,27 @@
109111 --internal-listen 10.0.0.12:8081 --advertise 10.0.0.12:8081
110112 ```
111113
114+An `az://` bucket selects Azure Blob Storage, where the NAME is the
115+container. The storage account comes from `AZURE_STORAGE_ACCOUNT_NAME`.
116+celld requires exactly one storage account key, managed identity, or workload
117+identity. An AKS workload identity uses `AZURE_AUTHORITY_HOST`,
118+`AZURE_CLIENT_ID`, `AZURE_TENANT_ID`, and `AZURE_FEDERATED_TOKEN_FILE`.
119+The authority host must identify the public Azure cloud. A Microsoft Entra
120+identity needs data-plane permission to read, write, list, and delete blobs.
121+The `Storage Blob Data Contributor` role supplies these permissions. celld
122+rejects an S3 `--endpoint` for an `az://` bucket, and it ignores the storage
123+region. celld qualifies an `az://` bucket: the conditional-write contract and
124+the multipart upload path were tested against a live Azure account on
125+2026-08-18, under each of the three credential families named above. See
126+[ownership and fencing](docs/fencing.md):
127+
128+```sh
129+export AZURE_STORAGE_ACCOUNT_NAME=myaccount
130+celld deploy . --bucket az://my-cells-container
131+celld --bucket az://my-cells-container --listen 0.0.0.0:8080 \
132+ --internal-listen 10.0.0.12:8081 --advertise 10.0.0.12:8081
133+```
134+
112135 A fleet runs one application, and every node loads its
113136 latest successfully committed deployment from `deploy/current.json`. Run
114137 `celld --help` for the complete command line.
@@ -145,6 +168,14 @@
145168 WebSocket, RSS, CPU, file-descriptor, pressure, and shedding sample. Pass one
146169 or more `--peer NODE_ID` options to restrict the check.
147170
171+`celld d1` runs SQL and migrations against a deployed D1 database. It finds a
172+node through the same node leases, and that node sends the work to the node
173+that owns the database:
174+
175+```sh
176+celld d1 migrations apply ledger --bucket s3://my-cells-bucket
177+```
178+
148179 Set a hard resident-cell limit on each loaded node:
149180
150181 ```sh
@@ -175,6 +206,25 @@
175206 disables the threshold and the cap together. When celld cannot read the size of
176207 the available memory, it applies a cap of 125% of an explicit threshold.
177208
209+Each isolate also has a V8 heap limit, and this limit is separate from the
210+memory of the node. The default is 128 MB, and it matches the limit of a
211+Durable Object on Cloudflare. Set `CELLD_V8_HEAP_LIMIT_MB` to change it. The
212+limit decides how much state one isolate can hold, so it decides how many
213+hibernatable WebSocket clients a cell can carry. Each client holds state in the
214+heap. A cell holds approximately 50,000 clients with the default limit, and it
215+needs approximately 512 MB to hold 100,000 clients.
216+
217+An isolate that uses more than 90% of this limit refuses a new hibernatable
218+WebSocket, and the error names the heap. The refusal is not permanent, and the
219+isolate accepts a WebSocket again when the use of the heap falls under 90%.
220+
221+An isolate that reaches the limit stops more than an accept. It also stops the
222+materialization of a SQL result set, and that error names the heap too. celld
223+measures the heap before each event, and the isolate serves again when the use
224+of the heap falls under 75% of the limit. An idle isolate holds a dead heap
225+until something allocates again, so celld forces a collection when a
226+measurement is above that share. A restart of the process is not necessary.
227+
178228 Under pressure, celld durably replicates and fences the least-recently used idle
179229 cells. It then publishes the cells as unowned without resetting their epochs.
180230 Those cells become inactive, and celld refuses to reacquire new unowned cells.
addedclippy.toml+85−0View file
@@ -1,0 +1,85 @@
1+# The execution boundary must use celld::asyncrt. Modules which never execute
2+# in the World carry an explicit lint allow and are listed in the S0 audit.
3+disallowed-methods = [
4+ { path = "tokio::spawn", reason = "use celld::asyncrt::spawn inside the World boundary" },
5+ { path = "tokio::runtime::Handle::spawn", reason = "use celld::asyncrt::spawn inside the World boundary" },
6+ { path = "tokio::task::spawn_blocking", reason = "use celld::asyncrt::blocking inside the World boundary" },
7+ { path = "tokio::runtime::Handle::spawn_blocking", reason = "use celld::asyncrt::blocking inside the World boundary" },
8+ { path = "tokio::time::sleep", reason = "use celld::asyncrt::sleep inside the World boundary" },
9+ { path = "tokio::time::sleep_until", reason = "use celld::asyncrt::sleep_until inside the World boundary" },
10+ { path = "tokio::time::timeout", reason = "use celld::asyncrt::timeout inside the World boundary" },
11+ { path = "tokio::time::timeout_at", reason = "use celld::asyncrt::timeout_at inside the World boundary" },
12+ { path = "tokio::time::interval", reason = "use celld::asyncrt::interval inside the World boundary" },
13+ { path = "tokio::time::interval_at", reason = "use celld::asyncrt::interval_at inside the World boundary" },
14+ { path = "std::time::SystemTime::now", reason = "use the execution-domain wall clock inside the World boundary" },
15+ { path = "std::time::Instant::now", reason = "use the execution-domain monotonic clock inside the World boundary" },
16+ { path = "rand::random", reason = "use a labeled execution-domain RNG inside the World boundary" },
17+ { path = "std::process::id", reason = "use the execution-domain process tag inside the World boundary" },
18+ { path = "std::fs::read", reason = "use the injected whole-node filesystem for celld node storage" },
19+ { path = "std::fs::read_to_string", reason = "use the injected whole-node filesystem for celld node storage" },
20+ { path = "std::fs::read_dir", reason = "use the injected whole-node filesystem for celld node storage" },
21+ { path = "std::fs::metadata", reason = "use the injected whole-node filesystem for celld node storage" },
22+ { path = "std::fs::symlink_metadata", reason = "use the injected whole-node filesystem for celld node storage" },
23+ { path = "std::fs::canonicalize", reason = "use the injected whole-node filesystem for celld node storage" },
24+ { path = "std::fs::copy", reason = "use the injected whole-node filesystem for celld node storage" },
25+ { path = "std::fs::exists", reason = "use injected filesystem metadata for celld node storage" },
26+ { path = "std::fs::hard_link", reason = "use the injected whole-node filesystem for celld node storage" },
27+ { path = "std::fs::read_link", reason = "use the injected whole-node filesystem for celld node storage" },
28+ { path = "std::fs::File::create", reason = "use the injected whole-node filesystem for celld node storage" },
29+ { path = "std::fs::File::open", reason = "use the injected whole-node filesystem for celld node storage" },
30+ { path = "std::fs::File::options", reason = "use the injected whole-node filesystem for celld node storage" },
31+ { path = "std::fs::File::sync_all", reason = "use the injected whole-node filesystem for celld node storage" },
32+ { path = "std::fs::File::sync_data", reason = "use the injected whole-node filesystem for celld node storage" },
33+ { path = "std::fs::OpenOptions::new", reason = "use the injected whole-node filesystem for celld node storage" },
34+ { path = "std::fs::OpenOptions::open", reason = "use the injected whole-node filesystem for celld node storage" },
35+ { path = "std::fs::write", reason = "use the injected whole-node filesystem for celld node storage" },
36+ { path = "std::fs::rename", reason = "use the injected whole-node filesystem for celld node storage" },
37+ { path = "std::fs::remove_file", reason = "use the injected whole-node filesystem for celld node storage" },
38+ { path = "std::fs::remove_dir", reason = "use the injected whole-node filesystem for celld node storage" },
39+ { path = "std::fs::remove_dir_all", reason = "use the injected whole-node filesystem for celld node storage" },
40+ { path = "std::fs::create_dir", reason = "use the injected whole-node filesystem for celld node storage" },
41+ { path = "std::fs::create_dir_all", reason = "use the injected whole-node filesystem for celld node storage" },
42+ { path = "std::fs::set_permissions", reason = "use the injected whole-node filesystem for celld node storage" },
43+ { path = "std::path::Path::exists", reason = "use injected filesystem metadata for celld node storage" },
44+ { path = "std::path::Path::try_exists", reason = "use injected filesystem metadata for celld node storage" },
45+ { path = "std::path::Path::is_file", reason = "use injected filesystem metadata for celld node storage" },
46+ { path = "std::path::Path::is_dir", reason = "use injected filesystem metadata for celld node storage" },
47+ { path = "std::path::Path::is_symlink", reason = "use injected filesystem metadata for celld node storage" },
48+ { path = "std::path::Path::metadata", reason = "use injected filesystem metadata for celld node storage" },
49+ { path = "std::path::Path::symlink_metadata", reason = "use injected filesystem metadata for celld node storage" },
50+ { path = "std::path::Path::canonicalize", reason = "use the injected whole-node filesystem for celld node storage" },
51+ { path = "std::path::Path::read_link", reason = "use the injected whole-node filesystem for celld node storage" },
52+ { path = "std::path::Path::read_dir", reason = "use the injected whole-node filesystem for celld node storage" },
53+ { path = "tokio::fs::read", reason = "use the injected whole-node filesystem for celld node storage" },
54+ { path = "tokio::fs::read_dir", reason = "use the injected whole-node filesystem for celld node storage" },
55+ { path = "tokio::fs::read_to_string", reason = "use the injected whole-node filesystem for celld node storage" },
56+ { path = "tokio::fs::metadata", reason = "use the injected whole-node filesystem for celld node storage" },
57+ { path = "tokio::fs::symlink_metadata", reason = "use the injected whole-node filesystem for celld node storage" },
58+ { path = "tokio::fs::canonicalize", reason = "use the injected whole-node filesystem for celld node storage" },
59+ { path = "tokio::fs::copy", reason = "use the injected whole-node filesystem for celld node storage" },
60+ { path = "tokio::fs::try_exists", reason = "use injected filesystem metadata for celld node storage" },
61+ { path = "tokio::fs::hard_link", reason = "use the injected whole-node filesystem for celld node storage" },
62+ { path = "tokio::fs::read_link", reason = "use the injected whole-node filesystem for celld node storage" },
63+ { path = "tokio::fs::File::create", reason = "use the injected whole-node filesystem for celld node storage" },
64+ { path = "tokio::fs::File::open", reason = "use the injected whole-node filesystem for celld node storage" },
65+ { path = "tokio::fs::File::sync_all", reason = "use the injected whole-node filesystem for celld node storage" },
66+ { path = "tokio::fs::File::sync_data", reason = "use the injected whole-node filesystem for celld node storage" },
67+ { path = "tokio::fs::OpenOptions::new", reason = "use the injected whole-node filesystem for celld node storage" },
68+ { path = "tokio::fs::OpenOptions::open", reason = "use the injected whole-node filesystem for celld node storage" },
69+ { path = "tokio::fs::write", reason = "use the injected whole-node filesystem for celld node storage" },
70+ { path = "tokio::fs::rename", reason = "use the injected whole-node filesystem for celld node storage" },
71+ { path = "tokio::fs::remove_file", reason = "use the injected whole-node filesystem for celld node storage" },
72+ { path = "tokio::fs::remove_dir", reason = "use the injected whole-node filesystem for celld node storage" },
73+ { path = "tokio::fs::remove_dir_all", reason = "use the injected whole-node filesystem for celld node storage" },
74+ { path = "tokio::fs::create_dir", reason = "use the injected whole-node filesystem for celld node storage" },
75+ { path = "tokio::fs::create_dir_all", reason = "use the injected whole-node filesystem for celld node storage" },
76+ { path = "tokio::fs::set_permissions", reason = "use the injected whole-node filesystem for celld node storage" },
77+]
78+
79+disallowed-macros = [
80+ { path = "tokio::select", reason = "use celld::asyncrt::select with a declared priority inside the World boundary" },
81+]
82+
83+disallowed-types = [
84+ { path = "rand::rngs::OsRng", reason = "use a labeled execution-domain RNG inside the World boundary" },
85+]
modifiedcrates/celld/Cargo.toml+7−2View file
@@ -1,6 +1,6 @@
11 [package]
22 name = "celld"
3-version = "0.2.1"
3+version = "0.3.0"
44 edition = "2021"
55 rust-version = "1.94.1"
66 license = "Apache-2.0"
@@ -39,7 +39,7 @@
3939 hyper.workspace = true
4040 hyper-util.workspace = true
4141 md-5.workspace = true
42-object_store = { workspace = true, features = ["aws", "gcp"] }
42+object_store = { workspace = true, features = ["aws", "azure", "gcp"] }
4343 parquet.workspace = true
4444 percent-encoding.workspace = true
4545 p256.workspace = true
@@ -78,3 +78,8 @@
7878
7979 [target.'cfg(unix)'.dependencies]
8080 libc.workspace = true
81+nix.workspace = true
82+
83+[dev-dependencies]
84+async-trait.workspace = true
85+lz4_flex.workspace = true
addedcrates/celld/actor.rs+2658−0View file
@@ -1,0 +1,2658 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! The serial lifecycle executor and its shell-side request drivers.
4+
5+#![warn(clippy::disallowed_macros)]
6+
7+use crate::assets::AssetResolver;
8+use crate::js::{HttpResponse, WsOut};
9+use crate::machine::{
10+ ownership_on_evict_from_environment, pressure_config_from_environment,
11+ random_process_generation, DEFAULT_MAX_OUTBOUND_WEBSOCKETS,
12+};
13+use crate::ownership_store::{now_ms, BucketOwnership};
14+use crate::peer_auth::{self, PeerAuth};
15+use crate::runtime::{CellHost, RuntimeManager};
16+use anyhow::Context as _;
17+use celld_logic::{
18+ on_event, CasGuard, CasOutcome, Config, Effect, Event, Failure, LeaseCasOutcome,
19+ NodeLeaseRecord, NodeLeaseSpec, OpId, OwnerRecord, OwnershipOnEvict, Phase, RequestError,
20+ Route, State, StopCause, Timer, WebSocketKind, WorkerRoute,
21+};
22+use futures_util::stream::FuturesUnordered;
23+use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
24+use std::future::Future;
25+use std::pin::Pin;
26+use std::sync::atomic::Ordering;
27+use std::sync::Arc;
28+use tokio::sync::{mpsc, oneshot, Mutex};
29+use tokio_util::time::{delay_queue, DelayQueue};
30+
31+mod production;
32+
33+const DEFAULT_OPERATION_DEADLINE_MS: u64 = 15_000;
34+
35+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
36+pub enum TimerSlot {
37+ NodeLeaseRenew,
38+ NodeLeaseFence,
39+ CellAlarm(String),
40+ /// Keyed by operation, deliberately. Every other timer here coalesces
41+ /// because only its newest arming matters; a deadline is the opposite --
42+ /// each watches a different outstanding operation, and a shared slot
43+ /// would let arming one silently cancel another, leaving every activation
44+ /// but the most recent with nothing watching it.
45+ OperationDeadline(OpId),
46+ /// Keyed by cell and generation for the same reason as the deadline
47+ /// above: a node parks many cells at once, and one slot per cell would
48+ /// let a later parking disarm an earlier one.
49+ QueuedActivation(String, u64),
50+}
51+
52+impl TimerSlot {
53+ pub fn of(timer: &Timer) -> Self {
54+ match timer {
55+ Timer::NodeLeaseRenew { .. } => Self::NodeLeaseRenew,
56+ Timer::NodeLeaseFence { .. } => Self::NodeLeaseFence,
57+ Timer::CellAlarm { cell, .. } => Self::CellAlarm(cell.clone()),
58+ Timer::OperationDeadline { op } => Self::OperationDeadline(*op),
59+ Timer::QueuedActivation { cell, generation } => {
60+ Self::QueuedActivation(cell.clone(), *generation)
61+ }
62+ }
63+ }
64+}
65+
66+/// One versioned timer arm emitted by an Actor step.
67+#[derive(Clone, Debug, PartialEq, Eq)]
68+pub struct TimerArm {
69+ pub slot: TimerSlot,
70+ pub ordinal: u64,
71+ pub timer: Timer,
72+ pub at_mono_ms: u64,
73+}
74+
75+/// The shared displacement discipline for production and deterministic timers.
76+pub struct TimerSlots<V> {
77+ armed: BTreeMap<TimerSlot, (u64, V)>,
78+ ordinals: BTreeMap<TimerSlot, u64>,
79+}
80+
81+impl<V> Default for TimerSlots<V> {
82+ fn default() -> Self {
83+ Self {
84+ armed: BTreeMap::new(),
85+ ordinals: BTreeMap::new(),
86+ }
87+ }
88+}
89+
90+impl<V> TimerSlots<V> {
91+ /// Creates one arm, assigns its stable per-slot ordinal, and applies it.
92+ pub fn arm(&mut self, timer: Timer, at_mono_ms: u64, value: V) -> (TimerArm, Option<V>) {
93+ let slot = TimerSlot::of(&timer);
94+ let ordinal = self.ordinals.entry(slot.clone()).or_default();
95+ let arm = TimerArm {
96+ slot: slot.clone(),
97+ ordinal: *ordinal,
98+ timer,
99+ at_mono_ms,
100+ };
101+ *ordinal = ordinal.saturating_add(1);
102+ let displaced = self.replace(&slot, arm.ordinal, value);
103+ (arm, displaced)
104+ }
105+
106+ /// Applies an arm whose ordinal the Actor has already assigned.
107+ pub fn install(&mut self, arm: &TimerArm, value: V) -> Option<V> {
108+ self.replace(&arm.slot, arm.ordinal, value)
109+ }
110+
111+ fn replace(&mut self, slot: &TimerSlot, ordinal: u64, value: V) -> Option<V> {
112+ let displaced = self
113+ .armed
114+ .insert(slot.clone(), (ordinal, value))
115+ .map(|(_, value)| value);
116+ debug_assert!(
117+ displaced.is_none() || !matches!(slot, TimerSlot::OperationDeadline(_)),
118+ "an operation deadline displaced another: {slot:?}"
119+ );
120+ displaced
121+ }
122+
123+ /// Removes the current arm only when both parts of its identity match.
124+ pub fn fire(&mut self, slot: &TimerSlot, ordinal: u64) -> Option<V> {
125+ if self
126+ .armed
127+ .get(slot)
128+ .is_some_and(|(armed, _)| *armed == ordinal)
129+ {
130+ self.armed.remove(slot).map(|(_, value)| value)
131+ } else {
132+ None
133+ }
134+ }
135+
136+ fn clear_slot(&mut self, slot: &TimerSlot) {
137+ self.armed.remove(slot);
138+ }
139+}
140+
141+pub struct MemoryOwnership {
142+ node: String,
143+ owners: BTreeMap<String, OwnerRecord>,
144+ leases: BTreeMap<String, NodeLeaseRecord>,
145+ next_etag: u64,
146+}
147+
148+#[derive(Clone)]
149+pub enum Ownership {
150+ Memory(Arc<Mutex<MemoryOwnership>>),
151+ Bucket(Arc<BucketOwnership>),
152+}
153+
154+impl Ownership {
155+ async fn read_owner(&self, cell: &str) -> Result<Option<OwnerRecord>, Failure> {
156+ match self {
157+ Self::Memory(memory) => Ok(memory.lock().await.owners.get(cell).cloned()),
158+ Self::Bucket(bucket) => bucket.read_owner(cell).await.map_err(|error| {
159+ eprintln!("celld ownership read failed: {error:#}");
160+ Failure::Definite
161+ }),
162+ }
163+ }
164+
165+ async fn read_node_lease(&self, owner: &str) -> Result<Option<NodeLeaseRecord>, Failure> {
166+ match self {
167+ Self::Memory(memory) => Ok(memory.lock().await.leases.get(owner).cloned()),
168+ Self::Bucket(bucket) => bucket.read_node_lease(owner).await.map_err(|error| {
169+ eprintln!("celld node lease read failed: {error:#}");
170+ Failure::Definite
171+ }),
172+ }
173+ }
174+
175+ async fn read_capacity_peers(&self) -> Result<Vec<celld_logic::CapacityPeer>, Failure> {
176+ match self {
177+ // The in-memory adapter is a single-node development mode. It has
178+ // no external membership enumeration to offer.
179+ Self::Memory(_) => Ok(Vec::new()),
180+ Self::Bucket(bucket) => bucket.read_capacity_peers().await.map_err(|error| {
181+ eprintln!("celld capacity peer read failed: {error:#}");
182+ Failure::Definite
183+ }),
184+ }
185+ }
186+
187+ async fn read_self_node_lease(&self, node: &str) -> Result<Option<NodeLeaseRecord>, Failure> {
188+ match self {
189+ Self::Memory(memory) => Ok(memory.lock().await.leases.get(node).cloned()),
190+ Self::Bucket(bucket) => bucket.read_self_node_lease(node).await.map_err(|error| {
191+ eprintln!("celld self node lease read failed: {error:#}");
192+ Failure::Definite
193+ }),
194+ }
195+ }
196+
197+ async fn cas_owner(
198+ &self,
199+ cell: &str,
200+ guard: CasGuard,
201+ epoch: u64,
202+ ) -> Result<CasOutcome, Failure> {
203+ match self {
204+ Self::Memory(memory) => {
205+ let mut memory = memory.lock().await;
206+ let allowed = match guard {
207+ CasGuard::Absent => !memory.owners.contains_key(cell),
208+ CasGuard::Match(expected) => memory
209+ .owners
210+ .get(cell)
211+ .is_some_and(|owner| owner.etag == expected),
212+ };
213+ if allowed {
214+ let etag = format!("e{}", memory.next_etag);
215+ memory.next_etag += 1;
216+ let node = memory.node.clone();
217+ memory.owners.insert(
218+ cell.into(),
219+ OwnerRecord {
220+ node: Some(node),
221+ epoch,
222+ etag,
223+ },
224+ );
225+ }
226+ Ok(if allowed {
227+ CasOutcome::Applied
228+ } else {
229+ CasOutcome::Rejected
230+ })
231+ }
232+ Self::Bucket(bucket) => bucket.cas_owner(cell, guard, epoch).await.map_err(|error| {
233+ // Any transport or 5xx failure may have happened after the
234+ // store committed. The core reconciles by reading the owner
235+ // again.
236+ eprintln!("celld ownership CAS ambiguous: {error:#}");
237+ Failure::Ambiguous
238+ }),
239+ }
240+ }
241+
242+ async fn release_owner(&self, cell: &str, epoch: u64) -> Result<CasOutcome, Failure> {
243+ match self {
244+ Self::Memory(memory) => {
245+ let mut memory = memory.lock().await;
246+ let node = memory.node.clone();
247+ let releasable = memory.owners.get(cell).is_some_and(|owner| {
248+ owner.node.as_deref() == Some(node.as_str()) && owner.epoch == epoch
249+ });
250+ if releasable {
251+ let etag = format!("e{}", memory.next_etag);
252+ memory.next_etag += 1;
253+ memory.owners.insert(
254+ cell.into(),
255+ OwnerRecord {
256+ node: None,
257+ epoch,
258+ etag,
259+ },
260+ );
261+ }
262+ Ok(if releasable {
263+ CasOutcome::Applied
264+ } else {
265+ CasOutcome::Rejected
266+ })
267+ }
268+ // A release that may or may not have committed needs no
269+ // reconciliation: the record either still names this node, and the
270+ // next eviction releases it again, or it does not, and the cell is
271+ // already free. Either way nothing is owed.
272+ Self::Bucket(bucket) => bucket.release_owner(cell, epoch).await.map_err(|error| {
273+ eprintln!("celld ownership release failed: {error:#}");
274+ Failure::Definite
275+ }),
276+ }
277+ }
278+
279+ async fn cas_node_lease(
280+ &self,
281+ guard: CasGuard,
282+ mut record: NodeLeaseRecord,
283+ stamped: &mut Option<celld_logic::log_tier::LogState>,
284+ ) -> Result<LeaseCasOutcome, Failure> {
285+ match self {
286+ Self::Memory(memory) => {
287+ let mut memory = memory.lock().await;
288+ let current = memory.leases.get(&record.node);
289+ let allowed = match guard {
290+ CasGuard::Absent => current.is_none(),
291+ CasGuard::Match(expected) => {
292+ current.is_some_and(|lease| lease.etag == expected)
293+ }
294+ };
295+ if !allowed {
296+ return Ok(LeaseCasOutcome::Rejected);
297+ }
298+ let etag = format!("e{}", memory.next_etag);
299+ memory.next_etag += 1;
300+ record.etag = etag.clone();
301+ *stamped = record.log_state;
302+ memory.leases.insert(record.node.clone(), record);
303+ Ok(LeaseCasOutcome::Applied { etag })
304+ }
305+ Self::Bucket(bucket) => bucket
306+ .cas_node_lease(guard, &record, stamped)
307+ .await
308+ .map_err(|error| {
309+ eprintln!("celld node-lease CAS ambiguous: {error:#}");
310+ Failure::Ambiguous
311+ }),
312+ }
313+ }
314+
315+ pub fn name(&self) -> &'static str {
316+ match self {
317+ Self::Memory(_) => "memory",
318+ Self::Bucket(bucket) => bucket.storage_scheme(),
319+ }
320+ }
321+}
322+
323+pub enum Message {
324+ /// A periodic resource sample. The measuring is the shell's job; every
325+ /// decision that follows belongs to the core.
326+ SampleLoad,
327+ /// The log tier changed the folded log object the next lease write
328+ /// must carry (lease-fold): renew now so the change becomes durable.
329+ NudgeNodeLease,
330+ /// Stop new internal routing while a clean same-node reload drains. The
331+ /// request shell has already stopped admission; this closes wake and
332+ /// service paths that do not pass through the HTTP gate.
333+ BeginPreserve,
334+ /// Graceful shutdown: release every owned cell's record so peers take
335+ /// over immediately. The release writes run as effects inside the
336+ /// shutdown drain window, and the drain waits for them to complete —
337+ /// bounded by the drain deadline, so a wedged store still cannot hold
338+ /// the exit hostage.
339+ ReleaseAll,
340+ /// Has the shutdown handoff finished? True once no cell occupies
341+ /// capacity: nothing resident, restoring, or mid-eviction. The drain
342+ /// loop polls this to exit as soon as the handoff completes instead of
343+ /// sitting out the full drain window.
344+ Drained {
345+ reply: oneshot::Sender<DrainStatus>,
346+ },
347+ Request {
348+ request: u64,
349+ cell: String,
350+ capacity_handoff: bool,
351+ reply: oneshot::Sender<Result<Routed, RequestError>>,
352+ },
353+ /// A caller disappeared before routing finished. The request identity is
354+ /// allocated by the shell, so the actor can remove it from either cold
355+ /// admission queue immediately.
356+ CancelRoute {
357+ request: u64,
358+ },
359+ WorkerRequest {
360+ reply: oneshot::Sender<WorkerRouted>,
361+ },
362+ ActivityFinished {
363+ request: u64,
364+ // The activity drop also observes the cell's alarm. Folded in here so a
365+ // request's completion costs the serial core one message, not two — the
366+ // hot path for every routed DO call.
367+ cell: String,
368+ alarm_at_ms: Option<i64>,
369+ alarm_covered: bool,
370+ },
371+ /// A local response is ready. A write opens a durability barrier, and a
372+ /// read trails the newest barrier already open on its cell.
373+ GateWrite {
374+ request: u64,
375+ position: Option<u64>,
376+ reply: oneshot::Sender<Result<(), RequestError>>,
377+ },
378+ /// A `webSocketMessage` finished; hand its captured outbound frames to the
379+ /// cell's output gate. `write_position` present means the handler wrote, so
380+ /// the frames are held behind that write until it is durable; absent means
381+ /// flush them (behind any earlier still-pending write, else immediately).
382+ WsOutput {
383+ request: u64,
384+ scope: String,
385+ frames: Vec<(u64, WsOut)>,
386+ write_position: Option<u64>,
387+ reply: oneshot::Sender<()>,
388+ },
389+ WebSocketOpened {
390+ cell: String,
391+ websocket: u64,
392+ kind: WebSocketKind,
393+ reply: oneshot::Sender<bool>,
394+ },
395+ WebSocketClosed {
396+ cell: String,
397+ websocket: u64,
398+ },
399+ AlarmObserved {
400+ cell: String,
401+ at_ms: Option<i64>,
402+ covered: bool,
403+ },
404+ WakeHint {
405+ cell: String,
406+ },
407+ Evict {
408+ cell: String,
409+ reply: oneshot::Sender<()>,
410+ },
411+ InvalidateRemote {
412+ cell: String,
413+ node: String,
414+ epoch: u64,
415+ reply: oneshot::Sender<()>,
416+ },
417+ Snapshot {
418+ reply: oneshot::Sender<String>,
419+ },
420+ Health {
421+ reply: oneshot::Sender<bool>,
422+ },
423+ Presence {
424+ reply: oneshot::Sender<celld_logic::PresenceSnapshot>,
425+ },
426+}
427+
428+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
429+pub enum ShutdownMode {
430+ /// The logical node is leaving. Release every owner record so another
431+ /// node can take over without waiting for the node lease to expire.
432+ Handoff,
433+ /// The same logical node will start again at the same address. Drain the
434+ /// request shell, but keep ownership and the local replica cache intact.
435+ Preserve,
436+}
437+
438+pub struct Routed {
439+ pub request: u64,
440+ pub route: Route,
441+}
442+
443+#[derive(Clone, Copy, Default)]
444+pub struct DrainStatus {
445+ pub occupied: usize,
446+ pub activating: usize,
447+ pub evicting: usize,
448+ /// Ownership releases still in flight. A handoff drain waits for zero:
449+ /// a released cell leaves `occupied` before its record write commits,
450+ /// so exiting on occupancy alone can abort the write mid-flight and
451+ /// leave a record the successor waits out the node lease for.
452+ pub releasing: usize,
453+}
454+
455+// Read only by the orphaned `worker_route`; removed with the landing-cell
456+// machinery in the DO-dispatch refactor ([[designs/do-fast-path]]).
457+#[allow(dead_code)]
458+pub struct WorkerRouted {
459+ pub request: u64,
460+ pub route: Option<WorkerRoute>,
461+}
462+
463+/// Worker requests owned by one HTTP connection. Hyper can finish a failed
464+/// connection without dropping its service future, so the connection also
465+/// aborts these requests explicitly when its transport ends.
466+#[derive(Clone, Default)]
467+pub struct ConnectionWorkerRequests(Arc<std::sync::Mutex<BTreeSet<crate::js::RequestId>>>);
468+
469+impl ConnectionWorkerRequests {
470+ pub fn register(&self, request: crate::js::RequestId) {
471+ self.0.lock().unwrap().insert(request);
472+ }
473+
474+ pub fn complete(&self, request: crate::js::RequestId) {
475+ self.0.lock().unwrap().remove(&request);
476+ }
477+
478+ pub fn abort_all(&self) {
479+ let requests = std::mem::take(&mut *self.0.lock().unwrap());
480+ for request in requests {
481+ crate::js::abort_request(request);
482+ }
483+ }
484+}
485+
486+pub struct IngressAbortGuard {
487+ request: Option<crate::js::RequestId>,
488+ connection: ConnectionWorkerRequests,
489+}
490+
491+impl IngressAbortGuard {
492+ pub fn new(request: crate::js::RequestId, connection: ConnectionWorkerRequests) -> Self {
493+ connection.register(request);
494+ Self {
495+ request: Some(request),
496+ connection,
497+ }
498+ }
499+
500+ pub fn disarm(&mut self) {
501+ if let Some(request) = self.request.take() {
502+ self.connection.complete(request);
503+ }
504+ }
505+}
506+
507+/// Cancels a core route when the future awaiting it is dropped. A normal
508+/// route disarms the guard before returning its result.
509+pub struct RouteCancelGuard {
510+ tx: mpsc::UnboundedSender<Message>,
511+ request: Option<u64>,
512+}
513+
514+impl RouteCancelGuard {
515+ pub fn new(tx: mpsc::UnboundedSender<Message>, request: u64) -> Self {
516+ Self {
517+ tx,
518+ request: Some(request),
519+ }
520+ }
521+
522+ pub fn disarm(&mut self) {
523+ self.request = None;
524+ }
525+}
526+
527+impl Drop for RouteCancelGuard {
528+ fn drop(&mut self) {
529+ if let Some(request) = self.request {
530+ let _ = self.tx.send(Message::CancelRoute { request });
531+ }
532+ }
533+}
534+
535+impl Drop for IngressAbortGuard {
536+ fn drop(&mut self) {
537+ if let Some(request) = self.request.take() {
538+ self.connection.complete(request);
539+ crate::js::abort_request(request);
540+ }
541+ }
542+}
543+
544+pub struct ActivityGuard {
545+ tx: mpsc::UnboundedSender<Message>,
546+ request: u64,
547+ runtime: Option<RuntimeManager>,
548+ cell: String,
549+}
550+
551+impl Drop for ActivityGuard {
552+ fn drop(&mut self) {
553+ // Read and send under the registry lock (`with_alarm`), so this
554+ // report cannot carry an alarm older than one the reporter already
555+ // sent — a stale fold arriving later would unarm the core and
556+ // delete the wake entry (`alarm_reporter` documents the ordering).
557+ let send = |tx: &mpsc::UnboundedSender<Message>, at_ms, covered| {
558+ let _ = tx.send(Message::ActivityFinished {
559+ request: self.request,
560+ cell: self.cell.clone(),
561+ alarm_at_ms: at_ms,
562+ alarm_covered: covered,
563+ });
564+ };
565+ match &self.runtime {
566+ Some(runtime) => runtime.with_alarm(&self.cell, |at_ms| {
567+ let covered = runtime.alarm_covered(&self.cell, at_ms);
568+ send(&self.tx, at_ms, covered);
569+ }),
570+ None => send(&self.tx, None, false),
571+ }
572+ }
573+}
574+
575+#[derive(Clone, Copy)]
576+enum RouteStage {
577+ OwnershipRead,
578+ NodeLeaseLookup,
579+ CapacityLookup,
580+ OwnershipAcquire,
581+ Restore,
582+ IsolateStartup,
583+ RegistryInsert,
584+}
585+
586+struct EffectTiming {
587+ cell: String,
588+ stage: RouteStage,
589+ elapsed_us: u64,
590+}
591+
592+pub struct CompletedEffect {
593+ event: Event,
594+ timing: Option<EffectTiming>,
595+}
596+
597+impl CompletedEffect {
598+ fn plain(event: Event) -> Self {
599+ Self {
600+ event,
601+ timing: None,
602+ }
603+ }
604+
605+ fn timed(event: Event, cell: String, stage: RouteStage, started_mono_ms: u64) -> Self {
606+ Self {
607+ event,
608+ timing: Some(EffectTiming {
609+ cell,
610+ stage,
611+ elapsed_us: mono_elapsed_us(started_mono_ms),
612+ }),
613+ }
614+ }
615+}
616+
617+struct CellRouteTiming {
618+ started_mono_ms: u64,
619+ activation_started: bool,
620+ capacity_wait_started_mono_ms: Option<u64>,
621+ latch_wait_us: u64,
622+ ownership_read_us: u64,
623+ node_lease_lookup_us: u64,
624+ capacity_lookup_us: u64,
625+ capacity_wait_us: u64,
626+ activation_slot_wait_us: u64,
627+ lease_permit_us: u64,
628+ ownership_acquire_us: u64,
629+ replica_discovery_us: u64,
630+ restore_us: u64,
631+ isolate_startup_us: u64,
632+ registry_insert_us: u64,
633+ fresh: Option<bool>,
634+}
635+
636+impl CellRouteTiming {
637+ fn new() -> Self {
638+ Self {
639+ started_mono_ms: crate::asyncrt::mono_ms(),
640+ activation_started: false,
641+ capacity_wait_started_mono_ms: None,
642+ latch_wait_us: 0,
643+ ownership_read_us: 0,
644+ node_lease_lookup_us: 0,
645+ capacity_lookup_us: 0,
646+ capacity_wait_us: 0,
647+ activation_slot_wait_us: 0,
648+ lease_permit_us: 0,
649+ ownership_acquire_us: 0,
650+ replica_discovery_us: 0,
651+ restore_us: 0,
652+ isolate_startup_us: 0,
653+ registry_insert_us: 0,
654+ fresh: None,
655+ }
656+ }
657+
658+ fn effect_started(&mut self) {
659+ if !self.activation_started {
660+ self.activation_started = true;
661+ self.activation_slot_wait_us = mono_elapsed_us(self.started_mono_ms);
662+ }
663+ if let Some(started) = self.capacity_wait_started_mono_ms.take() {
664+ self.capacity_wait_us = self
665+ .capacity_wait_us
666+ .saturating_add(mono_elapsed_us(started));
667+ }
668+ }
669+
670+ fn record(&mut self, stage: RouteStage, elapsed_us: u64) {
671+ let field = match stage {
672+ RouteStage::OwnershipRead => &mut self.ownership_read_us,
673+ RouteStage::NodeLeaseLookup => &mut self.node_lease_lookup_us,
674+ RouteStage::CapacityLookup => &mut self.capacity_lookup_us,
675+ RouteStage::OwnershipAcquire => &mut self.ownership_acquire_us,
676+ RouteStage::Restore => &mut self.restore_us,
677+ RouteStage::IsolateStartup => &mut self.isolate_startup_us,
678+ RouteStage::RegistryInsert => &mut self.registry_insert_us,
679+ };
680+ *field = field.saturating_add(elapsed_us);
681+ }
682+}
683+
684+fn mono_elapsed_us(started_mono_ms: u64) -> u64 {
685+ crate::asyncrt::mono_ms()
686+ .saturating_sub(started_mono_ms)
687+ .saturating_mul(1_000)
688+}
689+
690+pub type EffectFuture = Pin<Box<dyn Future<Output = CompletedEffect> + Send>>;
691+pub type ConnectionFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
692+pub type DoCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
693+pub type AssetCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
694+pub type WebSocketFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
695+pub type CachePruneFuture = Pin<
696+ Box<
697+ dyn Future<
698+ Output = (
699+ u64,
700+ Result<std::io::Result<(usize, usize, u64)>, crate::asyncrt::TaskPanic>,
701+ ),
702+ > + Send,
703+ >,
704+>;
705+
706+/// One ready item selected for the serial Actor.
707+pub enum ActorInput {
708+ Message(Message),
709+ Completed(CompletedEffect),
710+ TimerFired(Timer),
711+}
712+
713+/// Futures and timer arms emitted by one Actor transition.
714+#[derive(Default)]
715+pub struct StepOutput {
716+ pub effects: Vec<EffectFuture>,
717+ pub timers: Vec<TimerArm>,
718+}
719+
720+fn drain_step_output(
721+ out: &mut StepOutput,
722+ effects: &mut FuturesUnordered<EffectFuture>,
723+ delays: &mut DelayQueue<TimerArm>,
724+ timers: &mut TimerSlots<delay_queue::Key>,
725+) {
726+ for effect in out.effects.drain(..) {
727+ effects.push(effect);
728+ }
729+ for arm in out.timers.drain(..) {
730+ let delay = std::time::Duration::from_millis(
731+ arm.at_mono_ms.saturating_sub(crate::asyncrt::mono_ms()),
732+ );
733+ let key = delays.insert(arm.clone(), delay);
734+ if let Some(displaced) = timers.install(&arm, key) {
735+ delays.remove(&displaced);
736+ }
737+ }
738+}
739+
740+#[derive(Clone)]
741+pub struct AppHandle {
742+ pub tx: mpsc::UnboundedSender<Message>,
743+ pub runtime: Option<RuntimeManager>,
744+ pub assets: Arc<HashMap<String, AssetResolver>>,
745+ pub asset_script: Option<Arc<str>>,
746+ pub peer_http: reqwest::Client,
747+ pub peer_auth: Arc<PeerAuth>,
748+ pub advertise: String,
749+ pub websockets: mpsc::UnboundedSender<WebSocketFuture>,
750+ /// Whether the RPO=0 output gate is armed: hold a local write's response
751+ /// until its cell is proven durable. On by default; set `CELLD_OUTPUT_GATE=0`
752+ /// to acknowledge writes without proving them durable. The core and its DST
753+ /// are unconditional.
754+ pub output_gate: bool,
755+ /// Concurrent outbound WebSockets one cell may hold, for the refusal
756+ /// message; the core enforces it.
757+ pub max_outbound_websockets: usize,
758+ /// Set the instant a graceful shutdown begins, so `/__celld/health` reports
759+ /// unhealthy and a load balancer stops routing here before teardown.
760+ pub draining: Arc<std::sync::atomic::AtomicBool>,
761+ /// The log tier's follower store: this node holds peers' log fragments
762+ /// whatever its own durability posture. `None` without a bucket.
763+ pub follower: Option<Arc<crate::node_log::FollowerStore>>,
764+ /// Whether forwarded scheme and host headers can set `request.url`.
765+ /// The default is false because a direct client controls both headers.
766+ pub trust_forwarded_headers: bool,
767+}
768+
769+impl AppHandle {
770+ pub async fn request(&self, cell: String) -> Result<Routed, RequestError> {
771+ self.request_with_mode(cell, false).await
772+ }
773+
774+ pub async fn capacity_request(&self, cell: String) -> Result<Routed, RequestError> {
775+ self.request_with_mode(cell, true).await
776+ }
777+
778+ async fn request_with_mode(
779+ &self,
780+ cell: String,
781+ capacity_handoff: bool,
782+ ) -> Result<Routed, RequestError> {
783+ let request = crate::asyncrt::next_core_request();
784+ let (reply, receive) = oneshot::channel();
785+ if self
786+ .tx
787+ .send(Message::Request {
788+ request,
789+ cell,
790+ capacity_handoff,
791+ reply,
792+ })
793+ .is_err()
794+ {
795+ return Err(RequestError::NodeFenced);
796+ }
797+ let mut cancel = RouteCancelGuard::new(self.tx.clone(), request);
798+ let result = receive.await.unwrap_or(Err(RequestError::NodeFenced));
799+ cancel.disarm();
800+ result
801+ }
802+
803+ // Orphaned by the always-pool Worker entry below. The whole landing-cell
804+ // machinery (this, `Message::WorkerRequest`, `WorkerRouted`,
805+ // `fetch_worker_on_cell`, `CellJob::WorkerFetch`, the logic `worker_request`,
806+ // and the inline co-hosted-write gate) is removed together in the DO-dispatch
807+ // refactor ([[designs/do-fast-path]]) so the RPO=0 co-hosted path is reworked
808+ // coherently rather than unpicked here.
809+ #[allow(dead_code)]
810+ async fn worker_route(&self) -> anyhow::Result<WorkerRouted> {
811+ let (reply, receive) = oneshot::channel();
812+ self.tx
813+ .send(Message::WorkerRequest { reply })
814+ .map_err(|_| anyhow::anyhow!("core stopped before Worker routing"))?;
815+ receive
816+ .await
817+ .context("core stopped while routing Worker request")
818+ }
819+
820+ pub async fn fetch_worker(
821+ &self,
822+ url: String,
823+ method: String,
824+ body: crate::js::RequestBody,
825+ headers: Vec<(String, String)>,
826+ connection: ConnectionWorkerRequests,
827+ ) -> anyhow::Result<HttpResponse> {
828+ let runtime = self
829+ .runtime
830+ .as_ref()
831+ .ok_or_else(|| anyhow::anyhow!("Worker runtime unavailable"))?;
832+ // Admission happens in the runtime, against the pool that actually
833+ // holds the requests. It used to be duplicated here against an empty
834+ // `PoolLoad` — a snapshot with no isolates and no affiliations, which
835+ // could only ever answer "yes" once pressure stopped refusing
836+ // outright. A decision made against a fake reading is not a fast path.
837+ let js_request = crate::js::next_request_id();
838+ // The Worker entry is stateless — run it in the pool, always. Routing it
839+ // to a "landing cell" existed only to make an `env.NS.get(id)` call
840+ // resolve inline; but a cell runs one fetch at a time, so under any real
841+ // concurrency the entry can't be on the cell it calls, and the routing
842+ // round-trip is paid for nothing — on top of the DO call's own routing.
843+ // A DO call reaches its owning cell (with fencing and the output gate) on
844+ // the host path, so one routing round-trip per request, never two.
845+ let mut abort = IngressAbortGuard::new(js_request, connection);
846+ let result = runtime
847+ .fetch_worker_pool(url, method, body, headers, js_request)
848+ .await;
849+ abort.disarm();
850+ result
851+ }
852+
853+ pub fn activity(&self, request: u64, cell: String) -> ActivityGuard {
854+ ActivityGuard {
855+ tx: self.tx.clone(),
856+ request,
857+ runtime: self.runtime.clone(),
858+ cell,
859+ }
860+ }
861+
862+ /// Hold a response until every write it can reveal is durable. A write
863+ /// supplies its ending position. A read supplies `None` and trails the
864+ /// newest outstanding write on the same cell, if one exists.
865+ pub async fn gate_output(
866+ &self,
867+ request: u64,
868+ position: Option<u64>,
869+ ) -> Result<(), RequestError> {
870+ let started_mono_ms = crate::asyncrt::mono_ms();
871+ let (reply, receive) = oneshot::channel();
872+ if self
873+ .tx
874+ .send(Message::GateWrite {
875+ request,
876+ position,
877+ reply,
878+ })
879+ .is_err()
880+ {
881+ return Err(RequestError::NodeFenced);
882+ }
883+ let result = receive.await.unwrap_or(Err(RequestError::NodeFenced));
884+ tracing::debug!(
885+ target: "timing",
886+ event = "gate_write_timing",
887+ request,
888+ total_us = mono_elapsed_us(started_mono_ms),
889+ "output gate resolved"
890+ );
891+ result
892+ }
893+
894+ pub async fn gate_write(&self, request: u64, position: u64) -> Result<(), RequestError> {
895+ self.gate_output(request, Some(position)).await
896+ }
897+
898+ /// Hand a finished `webSocketMessage`'s frames to the cell's output gate.
899+ /// Awaited so the request stays pinned until the actor has registered the
900+ /// gate (the core reads the still-active request when it opens); frames flush
901+ /// or fail asynchronously as durability resolves, not here.
902+ pub async fn ws_output(
903+ &self,
904+ request: u64,
905+ scope: String,
906+ frames: Vec<(u64, WsOut)>,
907+ write_position: Option<u64>,
908+ ) {
909+ let (reply, receive) = oneshot::channel();
910+ if self
911+ .tx
912+ .send(Message::WsOutput {
913+ request,
914+ scope,
915+ frames,
916+ write_position,
917+ reply,
918+ })
919+ .is_ok()
920+ {
921+ let _ = receive.await;
922+ }
923+ }
924+
925+ pub async fn websocket_opened(
926+ &self,
927+ cell: String,
928+ websocket: u64,
929+ kind: WebSocketKind,
930+ ) -> anyhow::Result<()> {
931+ let (reply, receive) = oneshot::channel();
932+ self.tx
933+ .send(Message::WebSocketOpened {
934+ cell,
935+ websocket,
936+ kind,
937+ reply,
938+ })
939+ .map_err(|_| anyhow::anyhow!("core stopped before WebSocket opened"))?;
940+ let held = receive
941+ .await
942+ .context("core stopped while opening WebSocket")?;
943+ anyhow::ensure!(
944+ held,
945+ "outbound WebSocket refused: a cell may hold at most {}, and a node \
946+ may pin at most {}% of its residency ceiling",
947+ self.max_outbound_websockets,
948+ celld_logic::pressure::MAX_OUTBOUND_PIN_PERCENT,
949+ );
950+ Ok(())
951+ }
952+
953+ pub fn websocket_closed(&self, cell: String, websocket: u64) {
954+ let _ = self.tx.send(Message::WebSocketClosed { cell, websocket });
955+ }
956+
957+ pub async fn evict(&self, cell: String) {
958+ let (reply, receive) = oneshot::channel();
959+ if self.tx.send(Message::Evict { cell, reply }).is_ok() {
960+ let _ = receive.await;
961+ }
962+ }
963+
964+ pub async fn invalidate_remote(&self, cell: String, node: String, epoch: u64) {
965+ let (reply, receive) = oneshot::channel();
966+ if self
967+ .tx
968+ .send(Message::InvalidateRemote {
969+ cell,
970+ node,
971+ epoch,
972+ reply,
973+ })
974+ .is_ok()
975+ {
976+ let _ = receive.await;
977+ }
978+ }
979+
980+ pub async fn snapshot(&self) -> String {
981+ let (reply, receive) = oneshot::channel();
982+ if self.tx.send(Message::Snapshot { reply }).is_err() {
983+ return "{\"error\":\"actor_stopped\"}".into();
984+ }
985+ receive
986+ .await
987+ .unwrap_or_else(|_| "{\"error\":\"actor_stopped\"}".into())
988+ }
989+
990+ pub fn is_draining(&self) -> bool {
991+ self.draining.load(std::sync::atomic::Ordering::Relaxed)
992+ }
993+
994+ /// A dead actor has nothing left to hand off, so channel failure
995+ /// reports drained rather than wedging shutdown.
996+ pub async fn drain_status(&self) -> DrainStatus {
997+ let (reply, receive) = oneshot::channel();
998+ if self.tx.send(Message::Drained { reply }).is_err() {
999+ return DrainStatus::default();
1000+ }
1001+ receive.await.unwrap_or_default()
1002+ }
1003+
1004+ pub async fn healthy(&self) -> bool {
1005+ let (reply, receive) = oneshot::channel();
1006+ if self.tx.send(Message::Health { reply }).is_err() {
1007+ return false;
1008+ }
1009+ receive.await.unwrap_or(false)
1010+ }
1011+
1012+ pub async fn presence(&self) -> Option<celld_logic::PresenceSnapshot> {
1013+ let (reply, receive) = oneshot::channel();
1014+ self.tx.send(Message::Presence { reply }).ok()?;
1015+ receive.await.ok()
1016+ }
1017+}
1018+
1019+/// One cell's WebSocket output gate: an ordered queue of write barriers.
1020+#[derive(Default)]
1021+struct WsGate {
1022+ barriers: VecDeque<WsBarrier>,
1023+}
1024+
1025+/// One `webSocketMessage` batch and the outbound frames held behind it.
1026+/// `settled` is `None` while the verdict is outstanding, `Some(true)` once the
1027+/// core proved every write the frames can reveal (they may flush when this
1028+/// barrier reaches the front), `Some(false)` on failure (the gate breaks).
1029+///
1030+/// Every batch gets its own barrier, including one that wrote nothing: the core
1031+/// decides what it trails, because only the core knows the writes other
1032+/// channels have outstanding on this cell. The queue keeps them in arrival
1033+/// order and drains only from the front, so a barrier settled early cannot
1034+/// overtake one still waiting.
1035+struct WsBarrier {
1036+ request: u64,
1037+ settled: Option<bool>,
1038+ frames: Vec<(u64, WsOut)>,
1039+}
1040+
1041+pub struct Actor {
1042+ state: State,
1043+ pub ownership: Ownership,
1044+ host: Option<CellHost>,
1045+ /// The node-log manager, filled at boot once the log tier exists:
1046+ /// the executor's RecoverNodeLog effect runs through it directly.
1047+ pub node_log: Arc<std::sync::Mutex<Option<Arc<crate::node_log::NodeLogManager>>>>,
1048+ region: String,
1049+ pending: BTreeMap<u64, oneshot::Sender<Result<Routed, RequestError>>>,
1050+ request_cells: BTreeMap<u64, String>,
1051+ route_timings: BTreeMap<String, CellRouteTiming>,
1052+ pending_workers: BTreeMap<u64, oneshot::Sender<WorkerRouted>>,
1053+ eviction_waiters: BTreeMap<String, Vec<oneshot::Sender<()>>>,
1054+ durability_waiters: BTreeMap<u64, (String, Vec<oneshot::Sender<()>>)>,
1055+ eviction_stops: BTreeMap<u64, Vec<oneshot::Sender<()>>>,
1056+ /// Local write responses held open by the output gate, keyed by request,
1057+ /// released when the core emits `ReleaseResponse`.
1058+ gated_responses: BTreeMap<u64, oneshot::Sender<Result<(), RequestError>>>,
1059+ /// Per-cell WebSocket output gate: a FIFO of write barriers, each holding
1060+ /// the outbound frames produced up to it. The front drains in write order as
1061+ /// durability proves, so no client ever sees a frame that trails an
1062+ /// unproven write (the Cloudflare per-object output gate).
1063+ ws_gates: BTreeMap<String, WsGate>,
1064+ /// Gated `webSocketMessage` requests, mapping each to its cell so a
1065+ /// `ReleaseResponse` routes to the WebSocket gate rather than an HTTP reply.
1066+ ws_gated: BTreeMap<u64, String>,
1067+ published: BTreeSet<String>,
1068+ fail_publish_once: bool,
1069+ publishes: u64,
1070+ stops: u64,
1071+ pub lease_spec: NodeLeaseSpec,
1072+ /// Whether to re-check every core invariant after every event.
1073+ ///
1074+ /// The check is a full scan of the cell table, so its cost grows with
1075+ /// residency: roughly 800us per event at ten thousand resident cells,
1076+ /// which would cap a busy node at about a thousand events a second in
1077+ /// assertion code alone. It is a model-checking assertion, and the place
1078+ /// it earns its keep is simulation, which can afford to run it after
1079+ /// every event over far more schedules than production will ever see.
1080+ /// Debug builds keep it. Release builds rely on the deterministic model,
1081+ /// because this full-table scan is too expensive for production traffic.
1082+ validate_invariants: bool,
1083+ /// The counters peers rank this node by, when there is a bucket to
1084+ /// publish them to.
1085+ live_load: Option<Arc<crate::ownership_store::LiveLoad>>,
1086+ /// The shed reason last reported to the log, so a latch that holds for
1087+ /// minutes is reported once rather than on every sample.
1088+ logged_shed_reason: Option<&'static str>,
1089+ fence: mpsc::UnboundedSender<i32>,
1090+ timer_slots: TimerSlots<()>,
1091+ started: bool,
1092+ preserving: bool,
1093+}
1094+
1095+pub struct AdmissionLimits {
1096+ pub resident: usize,
1097+ pub activations: usize,
1098+ pub evictions: usize,
1099+ pub releases: usize,
1100+}
1101+
1102+pub struct ActorIdentity {
1103+ pub node: String,
1104+ pub advertise: String,
1105+ pub region: String,
1106+}
1107+
1108+impl Actor {
1109+ pub async fn from_environment(
1110+ limits: AdmissionLimits,
1111+ fail_publish_once: bool,
1112+ fence: mpsc::UnboundedSender<i32>,
1113+ runtime: Option<RuntimeManager>,
1114+ ownership: Option<Ownership>,
1115+ identity: ActorIdentity,
1116+ resume_generation: Option<String>,
1117+ ) -> anyhow::Result<Self> {
1118+ Self::from_environment_with_cell_host(
1119+ limits,
1120+ fail_publish_once,
1121+ fence,
1122+ runtime.map(CellHost::V8),
1123+ ownership,
1124+ identity,
1125+ resume_generation,
1126+ )
1127+ .await
1128+ }
1129+
1130+ #[cfg(all(test, celld_internal_tests))]
1131+ pub(crate) async fn from_environment_with_scripted_host(
1132+ limits: AdmissionLimits,
1133+ fail_publish_once: bool,
1134+ fence: mpsc::UnboundedSender<i32>,
1135+ host: crate::conformance_sim_cell_host::SimCellHost,
1136+ ownership: Option<Ownership>,
1137+ identity: ActorIdentity,
1138+ resume_generation: Option<String>,
1139+ ) -> anyhow::Result<Self> {
1140+ Self::from_environment_with_cell_host(
1141+ limits,
1142+ fail_publish_once,
1143+ fence,
1144+ Some(CellHost::Scripted(host)),
1145+ ownership,
1146+ identity,
1147+ resume_generation,
1148+ )
1149+ .await
1150+ }
1151+
1152+ async fn from_environment_with_cell_host(
1153+ limits: AdmissionLimits,
1154+ fail_publish_once: bool,
1155+ fence: mpsc::UnboundedSender<i32>,
1156+ host: Option<CellHost>,
1157+ ownership: Option<Ownership>,
1158+ identity: ActorIdentity,
1159+ resume_generation: Option<String>,
1160+ ) -> anyhow::Result<Self> {
1161+ let ActorIdentity {
1162+ node,
1163+ advertise,
1164+ region,
1165+ } = identity;
1166+ let ownership = if let Some(ownership) = ownership {
1167+ ownership
1168+ } else {
1169+ Ownership::Memory(Arc::new(Mutex::new(MemoryOwnership {
1170+ node: node.clone(),
1171+ owners: BTreeMap::new(),
1172+ leases: BTreeMap::new(),
1173+ next_etag: 1,
1174+ })))
1175+ };
1176+ let live_load = match &ownership {
1177+ Ownership::Bucket(bucket) => Some(bucket.live()),
1178+ Ownership::Memory(_) => None,
1179+ };
1180+ if let Some(live) = &live_load {
1181+ crate::ownership_store::set_node_load(live.clone());
1182+ }
1183+ let process_generation = match &ownership {
1184+ Ownership::Bucket(bucket) => bucket
1185+ .process_generation()
1186+ .map(str::to_owned)
1187+ .unwrap_or_else(random_process_generation),
1188+ Ownership::Memory(_) => random_process_generation(),
1189+ };
1190+ let ttl_ms = crate::env_vars::positive_or("CELLD_TTL_MS", 10_000)?;
1191+ let lease_spec = NodeLeaseSpec {
1192+ // Startup has already resolved the environment and CLI settings
1193+ // into this validated internal address. Reading the environment
1194+ // again would let CELLD_ADVERTISE override a later CLI option and
1195+ // publish an address that the bound listener did not validate.
1196+ addr: advertise,
1197+ peer_protocol: peer_auth::PROTOCOL_VERSION,
1198+ generation: std::env::var("CELLD_TEST_GENERATION").unwrap_or(process_generation),
1199+ resume_generation,
1200+ ttl_ms,
1201+ };
1202+ Ok(Self {
1203+ node_log: Arc::new(std::sync::Mutex::new(None)),
1204+ state: State::new(
1205+ node,
1206+ Config {
1207+ max_resident: limits.resident,
1208+ max_activations: limits.activations,
1209+ max_evictions: limits.evictions,
1210+ max_releases: limits.releases,
1211+ alarm_resident_ms: crate::wake::resident_ms().max(0) as u64,
1212+ require_node_lease: true,
1213+ peer_protocol: crate::peer_auth::PROTOCOL_VERSION,
1214+ operation_deadline_ms: Some(crate::env_vars::positive_or(
1215+ "CELLD_OPERATION_DEADLINE_MS",
1216+ DEFAULT_OPERATION_DEADLINE_MS,
1217+ )?),
1218+ idle_evict_ms: crate::env_vars::positive::<u64>("CELLD_IDLE_EVICT_S")?
1219+ .map(|seconds| seconds.saturating_mul(1_000)),
1220+ pressure: pressure_config_from_environment()?,
1221+ max_outbound_websockets: crate::env_vars::positive_or(
1222+ "CELLD_MAX_OUTBOUND_WEBSOCKETS",
1223+ DEFAULT_MAX_OUTBOUND_WEBSOCKETS,
1224+ )?,
1225+ ownership_on_evict: match &ownership {
1226+ // Releasing a cell says "any node may take this
1227+ // one", which is only true if some other node could
1228+ // restore it. Without a bucket the sole copy is this
1229+ // node's disk, keyed to an epoch a re-acquire will
1230+ // step past, so releasing would lose the cell.
1231+ Ownership::Memory(_) => OwnershipOnEvict::Sticky,
1232+ Ownership::Bucket(_) => ownership_on_evict_from_environment()?,
1233+ },
1234+ },
1235+ ),
1236+ ownership,
1237+ host,
1238+ region,
1239+ pending: BTreeMap::new(),
1240+ request_cells: BTreeMap::new(),
1241+ route_timings: BTreeMap::new(),
1242+ pending_workers: BTreeMap::new(),
1243+ eviction_waiters: BTreeMap::new(),
1244+ durability_waiters: BTreeMap::new(),
1245+ gated_responses: BTreeMap::new(),
1246+ ws_gates: BTreeMap::new(),
1247+ ws_gated: BTreeMap::new(),
1248+ eviction_stops: BTreeMap::new(),
1249+ published: BTreeSet::new(),
1250+ fail_publish_once,
1251+ publishes: 0,
1252+ stops: 0,
1253+ lease_spec,
1254+ live_load,
1255+ logged_shed_reason: None,
1256+ validate_invariants: cfg!(debug_assertions),
1257+ fence,
1258+ timer_slots: TimerSlots::default(),
1259+ started: false,
1260+ preserving: false,
1261+ })
1262+ }
1263+
1264+ /// Emits the exactly-once pre-loop node-lease transition.
1265+ pub fn start(&mut self, out: &mut StepOutput) {
1266+ assert!(!self.started, "Actor::start was called more than once");
1267+ self.started = true;
1268+ self.drive(
1269+ Event::StartNodeLease {
1270+ now_ms: now_ms(),
1271+ now_mono_ms: crate::asyncrt::mono_ms(),
1272+ spec: self.lease_spec.clone(),
1273+ },
1274+ out,
1275+ );
1276+ }
1277+
1278+ /// Handles exactly one ready mailbox item, completion, or timer.
1279+ pub fn step(&mut self, input: ActorInput, out: &mut StepOutput) {
1280+ assert!(self.started, "Actor::step was called before Actor::start");
1281+ match input {
1282+ ActorInput::Message(message) => self.handle_message(message, out),
1283+ ActorInput::Completed(completed) => {
1284+ #[cfg(all(test, celld_internal_tests))]
1285+ if crate::asyncrt::sabotage_active(
1286+ crate::host_services::EngineSabotage::SuppressReleasingDecrement,
1287+ ) && matches!(&completed.event, Event::OwnerReleased { .. })
1288+ {
1289+ return;
1290+ }
1291+ let route_cell = completed.timing.as_ref().map(|timing| timing.cell.clone());
1292+ if let Some(timing) = completed.timing {
1293+ self.record_effect_timing(timing);
1294+ }
1295+ self.drive(completed.event, out);
1296+ if let Some(cell) = route_cell {
1297+ self.observe_capacity_wait(&cell);
1298+ }
1299+ }
1300+ ActorInput::TimerFired(timer) => {
1301+ self.timer_slots.clear_slot(&TimerSlot::of(&timer));
1302+ if self.preserving && matches!(timer, Timer::CellAlarm { .. }) {
1303+ return;
1304+ }
1305+ self.drive(
1306+ Event::TimerFired {
1307+ timer,
1308+ now_ms: now_ms(),
1309+ now_mono_ms: crate::asyncrt::mono_ms(),
1310+ },
1311+ out,
1312+ );
1313+ }
1314+ }
1315+ }
1316+
1317+ fn handle_message(&mut self, message: Message, out: &mut StepOutput) {
1318+ match message {
1319+ Message::BeginPreserve => {
1320+ self.preserving = true;
1321+ self.drive(Event::BeginPreserve, out);
1322+ }
1323+ Message::Request { reply, .. } if self.preserving => {
1324+ let _ = reply.send(Err(RequestError::NodeFenced));
1325+ }
1326+ Message::Request {
1327+ request,
1328+ cell,
1329+ capacity_handoff,
1330+ reply,
1331+ } => {
1332+ let retired_durability = match self.state.phase(&cell) {
1333+ Some(Phase::EnsuringDurability { op, .. }) => Some(*op),
1334+ _ => None,
1335+ };
1336+ self.pending.insert(request, reply);
1337+ self.begin_route_if_cold(&cell);
1338+ self.request_cells.insert(request, cell.clone());
1339+ self.drive(
1340+ if capacity_handoff {
1341+ Event::CapacityRequestAt {
1342+ request,
1343+ cell: cell.clone(),
1344+ now_mono_ms: crate::asyncrt::mono_ms(),
1345+ }
1346+ } else {
1347+ Event::RequestAt {
1348+ request,
1349+ cell: cell.clone(),
1350+ now_mono_ms: crate::asyncrt::mono_ms(),
1351+ }
1352+ },
1353+ out,
1354+ );
1355+ self.observe_capacity_wait(&cell);
1356+ if let Some(op) = retired_durability {
1357+ if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
1358+ for waiter in waiters {
1359+ let _ = waiter.send(());
1360+ }
1361+ }
1362+ }
1363+ }
1364+ Message::CancelRoute { request } => {
1365+ self.pending.remove(&request);
1366+ if let Some(cell) = self.request_cells.remove(&request) {
1367+ self.finish_route(&cell, "cancelled", "caller_disconnected", None);
1368+ }
1369+ self.drive(Event::Cancel { request }, out);
1370+ }
1371+ Message::WorkerRequest { reply } if self.preserving => {
1372+ let _ = reply.send(WorkerRouted {
1373+ request: crate::asyncrt::next_core_request(),
1374+ route: None,
1375+ });
1376+ }
1377+ Message::WorkerRequest { reply } => {
1378+ let request = crate::asyncrt::next_core_request();
1379+ self.pending_workers.insert(request, reply);
1380+ self.drive(Event::WorkerRequest { request }, out);
1381+ }
1382+ Message::ReleaseAll => self.drive(Event::ReleaseAll, out),
1383+ Message::Drained { reply } => {
1384+ let _ = reply.send(DrainStatus {
1385+ occupied: self.state.occupied(),
1386+ activating: self.state.activating(),
1387+ evicting: self.state.evicting(),
1388+ releasing: self.state.releasing(),
1389+ });
1390+ }
1391+ Message::SampleLoad if self.preserving => {}
1392+ Message::SampleLoad => {
1393+ // Counted once: it is a walk of every cell, and the latch and
1394+ // the number peers rank this node by must agree anyway.
1395+ let occupied = self.state.occupied();
1396+ let metrics = crate::asyncrt::services().sample_metrics();
1397+ let cpu = metrics.cpu_percent_x100;
1398+ let load = celld_logic::pressure::Load {
1399+ resident_cells: occupied,
1400+ rss_bytes: metrics.rss_bytes,
1401+ in_use_bytes: metrics.in_use_bytes,
1402+ };
1403+ let now_mono_ms = crate::asyncrt::mono_ms();
1404+ self.drive(Event::LoadSampled { load, now_mono_ms }, out);
1405+ // Report a change of shed reason once. `rss-hard` is the one
1406+ // that needs an operator: it says the resident set size crossed
1407+ // the absolute cap, so the allocator is holding memory that
1408+ // shedding may not return, and the process is near a kill.
1409+ let reason = self.state.shed_reason();
1410+ if reason != self.logged_shed_reason {
1411+ self.logged_shed_reason = reason;
1412+ // How many V8 heaps the resident cells hold open. Most of
1413+ // what a cell costs is its heap, and a heap comes back
1414+ // only when its last cell goes, so cells alone do not say
1415+ // how much a walk down can still return.
1416+ let heaps = self
1417+ .state
1418+ .resident_isolates()
1419+ .into_iter()
1420+ .collect::<BTreeSet<_>>()
1421+ .len();
1422+ match reason {
1423+ Some(celld_logic::pressure::SHED_RSS_HARD) => tracing::warn!(
1424+ rss_bytes = load.rss_bytes,
1425+ in_use_bytes = load.in_use_bytes,
1426+ heaps,
1427+ "shedding on the absolute resident-set cap: the \
1428+ allocator holds memory that shedding cannot return"
1429+ ),
1430+ Some(reason) => tracing::info!(
1431+ reason,
1432+ rss_bytes = load.rss_bytes,
1433+ in_use_bytes = load.in_use_bytes,
1434+ heaps,
1435+ "shedding"
1436+ ),
1437+ None => tracing::info!("no longer shedding"),
1438+ }
1439+ }
1440+ // Republish what peers rank this node by. The same numbers the
1441+ // latch just saw: a node that reports last tick's residency
1442+ // attracts work it has already refused.
1443+ if let Some(live) = &self.live_load {
1444+ live.resident_cells.store(occupied, Ordering::Relaxed);
1445+ live.host_websockets
1446+ .store(self.state.host_websockets(), Ordering::Relaxed);
1447+ live.pressured
1448+ .store(self.state.shedding(), Ordering::Relaxed);
1449+ live.cpu_percent_x100.store(cpu, Ordering::Relaxed);
1450+ live.restoring
1451+ .store(self.state.activation_backlog() as u64, Ordering::Relaxed);
1452+ }
1453+ }
1454+ Message::GateWrite {
1455+ request,
1456+ position,
1457+ reply,
1458+ } => {
1459+ self.gated_responses.insert(request, reply);
1460+ self.drive(
1461+ match position {
1462+ Some(position) => Event::Wrote { request, position },
1463+ None => Event::ReadOutput { request },
1464+ },
1465+ out,
1466+ );
1467+ }
1468+ Message::WsOutput {
1469+ request,
1470+ scope,
1471+ frames,
1472+ write_position,
1473+ reply,
1474+ } => {
1475+ // Open a barrier for every batch, then let the core decide
1476+ // what it trails: its own write when the handler wrote, and
1477+ // otherwise the newest write still outstanding on this cell,
1478+ // whichever channel made it. The queue consulted here before
1479+ // was filled in one place -- the arm below that writes -- so it
1480+ // held only writes a `webSocketMessage` handler made itself,
1481+ // and an HTTP, RPC, or peer write on the same cell was
1482+ // invisible to a batch that only read.
1483+ //
1484+ // Both registrations happen before the drive, and must: `drive`
1485+ // runs the effects it produces synchronously, so a read with no
1486+ // barrier open on its cell is released inside the call below.
1487+ // Moved after it, that `Effect::ReleaseResponse` would find no
1488+ // `ws_gated` entry, fall through to the `gated_responses` map,
1489+ // match nothing, and strand these frames behind a barrier that
1490+ // nothing will ever settle.
1491+ self.ws_gates
1492+ .entry(scope.clone())
1493+ .or_default()
1494+ .barriers
1495+ .push_back(WsBarrier {
1496+ request,
1497+ settled: None,
1498+ frames,
1499+ });
1500+ self.ws_gated.insert(request, scope);
1501+ self.drive(
1502+ match write_position {
1503+ Some(position) => Event::Wrote { request, position },
1504+ // A known gap remains on the other side of this
1505+ // question: an alarm handler proves its own write
1506+ // durable inline and registers no barrier with the
1507+ // core, so a frame revealing one is released early.
1508+ None => Event::ReadOutput { request },
1509+ },
1510+ out,
1511+ );
1512+ let _ = reply.send(());
1513+ }
1514+ Message::ActivityFinished {
1515+ request,
1516+ cell,
1517+ alarm_at_ms,
1518+ alarm_covered,
1519+ } => {
1520+ // Folded from the old AlarmObserved-then-ActivityFinished pair the
1521+ // activity drop sent: observe the alarm and release any retired
1522+ // durability waiters, then finish the activity — same events, same
1523+ // order, one message instead of two.
1524+ let retired_durability = match self.state.phase(&cell) {
1525+ Some(Phase::EnsuringDurability { op, .. }) => Some(*op),
1526+ _ => None,
1527+ };
1528+ self.drive(
1529+ Event::AlarmObserved {
1530+ cell,
1531+ at_ms: alarm_at_ms,
1532+ covered: alarm_covered,
1533+ now_ms: now_ms(),
1534+ now_mono_ms: crate::asyncrt::mono_ms(),
1535+ },
1536+ out,
1537+ );
1538+ if let Some(op) = retired_durability {
1539+ if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
1540+ for waiter in waiters {
1541+ let _ = waiter.send(());
1542+ }
1543+ }
1544+ }
1545+ self.drive(Event::ActivityFinished { request }, out);
1546+ }
1547+ Message::WebSocketOpened {
1548+ cell,
1549+ websocket,
1550+ kind,
1551+ reply,
1552+ } => {
1553+ self.drive(
1554+ Event::WebSocketOpened {
1555+ cell: cell.clone(),
1556+ websocket,
1557+ kind,
1558+ },
1559+ out,
1560+ );
1561+ // The core may decline to hold the transport. Say so, rather
1562+ // than acknowledging an open and closing the socket a moment
1563+ // later: an application that hit a ceiling deserves to be
1564+ // told which one, not left watching a socket disappear.
1565+ // Only an outbound socket can be declined, and only for a
1566+ // cell the core knows: an inbound transport is never refused,
1567+ // and reporting one as refused fails opens that succeeded.
1568+ let refused = kind == WebSocketKind::Outbound
1569+ && !self.state.holds_websocket(&cell, websocket);
1570+ let _ = reply.send(!refused);
1571+ }
1572+ Message::WebSocketClosed { cell, websocket } => {
1573+ self.drive(Event::WebSocketClosed { cell, websocket }, out);
1574+ }
1575+ Message::AlarmObserved {
1576+ cell,
1577+ at_ms,
1578+ covered,
1579+ } => {
1580+ let retired_durability = match self.state.phase(&cell) {
1581+ Some(Phase::EnsuringDurability { op, .. }) => Some(*op),
1582+ _ => None,
1583+ };
1584+ self.drive(
1585+ Event::AlarmObserved {
1586+ cell,
1587+ at_ms,
1588+ covered,
1589+ now_ms: now_ms(),
1590+ now_mono_ms: crate::asyncrt::mono_ms(),
1591+ },
1592+ out,
1593+ );
1594+ if let Some(op) = retired_durability {
1595+ if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
1596+ for waiter in waiters {
1597+ let _ = waiter.send(());
1598+ }
1599+ }
1600+ }
1601+ }
1602+ Message::NudgeNodeLease => {
1603+ self.drive(
1604+ Event::NudgeNodeLease {
1605+ now_ms: now_ms(),
1606+ now_mono_ms: crate::asyncrt::mono_ms(),
1607+ },
1608+ out,
1609+ );
1610+ }
1611+ Message::WakeHint { .. } if self.preserving => {}
1612+ Message::WakeHint { cell } => {
1613+ self.drive(
1614+ Event::WakeHintAt {
1615+ cell,
1616+ now_mono_ms: crate::asyncrt::mono_ms(),
1617+ },
1618+ out,
1619+ );
1620+ }
1621+ Message::Evict { reply, .. } if self.preserving => {
1622+ let _ = reply.send(());
1623+ }
1624+ Message::Evict { cell, reply } if self.state.is_active(&cell) => {
1625+ let _ = reply.send(());
1626+ }
1627+ Message::Evict { cell, reply } => match self.state.phase(&cell) {
1628+ Some(Phase::Resident { .. }) => {
1629+ self.eviction_waiters
1630+ .entry(cell.clone())
1631+ .or_default()
1632+ .push(reply);
1633+ self.drive(Event::Evict { cell }, out);
1634+ }
1635+ Some(Phase::EnsuringDurability { op, .. }) => {
1636+ self.durability_waiters
1637+ .entry(*op)
1638+ .or_insert_with(|| (cell, Vec::new()))
1639+ .1
1640+ .push(reply);
1641+ }
1642+ Some(Phase::Cleaning {
1643+ op,
1644+ cause: StopCause::Evict { .. },
1645+ ..
1646+ }) => {
1647+ self.eviction_stops.entry(*op).or_default().push(reply);
1648+ }
1649+ _ => {
1650+ let _ = reply.send(());
1651+ }
1652+ },
1653+ Message::InvalidateRemote {
1654+ cell,
1655+ node,
1656+ epoch,
1657+ reply,
1658+ } => {
1659+ self.drive(Event::InvalidateRemote { cell, node, epoch }, out);
1660+ let _ = reply.send(());
1661+ }
1662+ Message::Snapshot { reply } => {
1663+ let _ = reply.send(self.state_json());
1664+ }
1665+ Message::Health { reply } => {
1666+ let _ = reply.send(self.state.ready_to_serve());
1667+ }
1668+ Message::Presence { reply } => {
1669+ let _ = reply.send(self.state.presence_snapshot());
1670+ }
1671+ }
1672+ }
1673+
1674+ /// Settle a gated `webSocketMessage`'s durability. On success mark its
1675+ /// barrier durable and flush the durable prefix in write order; on failure
1676+ /// break the whole cell gate — drop every held frame and reset its sockets,
1677+ /// since an unproven write must never leave an acknowledged trace.
1678+ fn ws_release(&mut self, request: u64, ok: bool) {
1679+ let Some(scope) = self.ws_gated.remove(&request) else {
1680+ return;
1681+ };
1682+ let mut flush = Vec::new();
1683+ let broke = {
1684+ let Some(gate) = self.ws_gates.get_mut(&scope) else {
1685+ return;
1686+ };
1687+ if let Some(barrier) = gate.barriers.iter_mut().find(|b| b.request == request) {
1688+ barrier.settled = Some(ok);
1689+ }
1690+ if gate.barriers.iter().any(|b| b.settled == Some(false)) {
1691+ true
1692+ } else {
1693+ while gate
1694+ .barriers
1695+ .front()
1696+ .is_some_and(|b| b.settled == Some(true))
1697+ {
1698+ flush.push(gate.barriers.pop_front().unwrap().frames);
1699+ }
1700+ false
1701+ }
1702+ };
1703+ if broke {
1704+ self.ws_gates.remove(&scope);
1705+ self.ws_gated.retain(|_, s| *s != scope);
1706+ crate::js::ws_close_scope(&scope, 1011, "durability unproven");
1707+ return;
1708+ }
1709+ for frames in flush {
1710+ crate::js::ws_emit_batch(frames);
1711+ }
1712+ if self
1713+ .ws_gates
1714+ .get(&scope)
1715+ .is_some_and(|g| g.barriers.is_empty())
1716+ {
1717+ self.ws_gates.remove(&scope);
1718+ }
1719+ }
1720+
1721+ fn drive(&mut self, first: Event, out: &mut StepOutput) {
1722+ let mut events = VecDeque::from([first]);
1723+ while let Some(event) = events.pop_front() {
1724+ let durability = match &event {
1725+ Event::DurabilityChecked { op, .. } => Some(*op),
1726+ // A deadline resolves the same operation the proof would
1727+ // have, so it has to release the same waiters. Without this
1728+ // the core abandons the eviction and the caller that asked
1729+ // for it stays blocked on a proof that is no longer coming.
1730+ Event::TimerFired {
1731+ timer: Timer::OperationDeadline { op },
1732+ ..
1733+ } => Some(*op),
1734+ _ => None,
1735+ };
1736+ let stopped = match &event {
1737+ Event::RuntimeStopped { op } => Some(*op),
1738+ _ => None,
1739+ };
1740+ let effects = on_event(&mut self.state, event);
1741+ if let Some(op) = durability {
1742+ if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
1743+ let stop = effects.iter().find_map(|effect| match effect {
1744+ Effect::StopRuntime {
1745+ op,
1746+ cause: StopCause::Evict { .. },
1747+ ..
1748+ } => Some(*op),
1749+ _ => None,
1750+ });
1751+ if let Some(stop) = stop {
1752+ self.eviction_stops.entry(stop).or_default().extend(waiters);
1753+ } else {
1754+ for waiter in waiters {
1755+ let _ = waiter.send(());
1756+ }
1757+ }
1758+ }
1759+ }
1760+ for effect in effects {
1761+ self.execute(effect, &mut events, out);
1762+ }
1763+ if let Some(op) = stopped {
1764+ if let Some(waiters) = self.eviction_stops.remove(&op) {
1765+ for waiter in waiters {
1766+ let _ = waiter.send(());
1767+ }
1768+ }
1769+ }
1770+ if self.validate_invariants {
1771+ self.state.validate().expect("celld core invariant");
1772+ }
1773+ }
1774+ }
1775+
1776+ fn execute(&mut self, effect: Effect, immediate: &mut VecDeque<Event>, out: &mut StepOutput) {
1777+ match effect {
1778+ Effect::ScheduleTimer { timer, at_mono_ms } => {
1779+ #[cfg(all(test, celld_internal_tests))]
1780+ if matches!(
1781+ timer,
1782+ Timer::NodeLeaseFence { .. } | Timer::CellAlarm { .. }
1783+ ) && crate::asyncrt::sabotage_active(
1784+ crate::host_services::EngineSabotage::DropTimerArm,
1785+ ) {
1786+ return;
1787+ }
1788+ let (arm, _) = self.timer_slots.arm(timer, at_mono_ms, ());
1789+ out.timers.push(arm);
1790+ }
1791+ Effect::ReadSelfNodeLease { op } => {
1792+ let ownership = self.ownership.clone();
1793+ let node = self.state.node().to_string();
1794+ out.effects.push(Box::pin(async move {
1795+ let result = ownership.read_self_node_lease(&node).await;
1796+ CompletedEffect::plain(Event::SelfNodeLeaseRead {
1797+ op,
1798+ now_ms: now_ms(),
1799+ now_mono_ms: crate::asyncrt::mono_ms(),
1800+ result,
1801+ })
1802+ }));
1803+ }
1804+ Effect::CasNodeLease {
1805+ op,
1806+ guard,
1807+ record,
1808+ authority_expires_ms,
1809+ } => {
1810+ let ownership = self.ownership.clone();
1811+ out.effects.push(Box::pin(async move {
1812+ let attempt_started_mono_ms = crate::asyncrt::mono_ms();
1813+ let node = record.node.clone();
1814+ let candidate_expires_ms = record.expires_ms;
1815+ // Logged before the CAS: with only the completion line, a
1816+ // renewal hung on a storage tail is indistinguishable from
1817+ // a timer that never fired (the n6 fence, 2026-08-11).
1818+ tracing::info!(
1819+ event = "node_lease_attempt_started",
1820+ %node,
1821+ attempt = if authority_expires_ms.is_some() {
1822+ "renew"
1823+ } else {
1824+ "acquire"
1825+ },
1826+ prior_authority_headroom_ms = authority_expires_ms
1827+ .map(|expires_ms| expires_ms.saturating_sub(now_ms()))
1828+ .unwrap_or(0),
1829+ "node lease attempt started"
1830+ );
1831+ // A renewal must return while proven authority remains,
1832+ // because only a returned attempt lets the ambiguity
1833+ // read-back run before the watchdog. The 10:15Z R2
1834+ // brownout fenced 9 nodes whose sole hung attempt was
1835+ // still inside the transport's 15 s timeout when the
1836+ // 10 s TTL expired. Bound the attempt to half the
1837+ // remaining authority (capped, floored) and map timeout
1838+ // to Ambiguous — the same conservative outcome a lost
1839+ // response already produces, so safety is unchanged.
1840+ // The stamp survives a timed-out attempt: the backend
1841+ // writes it through the out-parameter synchronously at
1842+ // serialization, before the transport await, so even a
1843+ // dropped future has reported what the possibly-landed
1844+ // body carried.
1845+ let mut stamped_log_state = None;
1846+ let result = match authority_expires_ms {
1847+ Some(expires_ms) => {
1848+ let remaining = expires_ms.saturating_sub(now_ms());
1849+ let bound =
1850+ std::time::Duration::from_millis((remaining / 2).clamp(250, 2_500));
1851+ match crate::asyncrt::timeout(
1852+ bound,
1853+ ownership.cas_node_lease(guard, record, &mut stamped_log_state),
1854+ )
1855+ .await
1856+ {
1857+ Ok(result) => result,
1858+ Err(_) => Err(Failure::Ambiguous),
1859+ }
1860+ }
1861+ None => {
1862+ ownership
1863+ .cas_node_lease(guard, record, &mut stamped_log_state)
1864+ .await
1865+ }
1866+ };
1867+ let completed_ms = now_ms();
1868+ let elapsed_ms =
1869+ crate::asyncrt::mono_ms().saturating_sub(attempt_started_mono_ms);
1870+ let prior_authority_headroom_ms = authority_expires_ms
1871+ .map(|expires_ms| expires_ms.saturating_sub(completed_ms))
1872+ .unwrap_or(0);
1873+ let candidate_headroom_ms = candidate_expires_ms.saturating_sub(completed_ms);
1874+ let attempt = if authority_expires_ms.is_some() {
1875+ "renew"
1876+ } else {
1877+ "acquire"
1878+ };
1879+ let outcome = match &result {
1880+ Ok(LeaseCasOutcome::Applied { .. }) => "applied",
1881+ Ok(LeaseCasOutcome::Rejected) => "rejected",
1882+ Err(Failure::Ambiguous) => "ambiguous",
1883+ Err(Failure::Definite) => "definite_failure",
1884+ };
1885+ if matches!(&result, Ok(LeaseCasOutcome::Applied { .. })) {
1886+ tracing::info!(
1887+ event = "node_lease_attempt",
1888+ %node,
1889+ attempt,
1890+ outcome,
1891+ elapsed_ms,
1892+ prior_authority_headroom_ms,
1893+ candidate_headroom_ms,
1894+ "node lease attempt completed"
1895+ );
1896+ } else {
1897+ tracing::warn!(
1898+ event = "node_lease_attempt",
1899+ %node,
1900+ attempt,
1901+ outcome,
1902+ elapsed_ms,
1903+ prior_authority_headroom_ms,
1904+ candidate_headroom_ms,
1905+ "node lease attempt did not apply"
1906+ );
1907+ }
1908+ CompletedEffect::plain(Event::NodeLeaseCasCompleted {
1909+ op,
1910+ now_mono_ms: crate::asyncrt::mono_ms(),
1911+ result,
1912+ stamped_log_state,
1913+ })
1914+ }));
1915+ }
1916+ Effect::ReadLocalCells => {
1917+ let runtime = self.host.clone();
1918+ out.effects.push(Box::pin(async move {
1919+ let result = match runtime {
1920+ // The host runtime's blocking pool, not a second
1921+ // pool on the core's current-thread runtime.
1922+ Some(runtime) => crate::asyncrt::blocking(move || {
1923+ runtime.local_reload_cells().map_err(|error| {
1924+ eprintln!("celld local reload scan failed: {error:#}");
1925+ Failure::Definite
1926+ })
1927+ })
1928+ .await
1929+ .unwrap_or(Err(Failure::Definite)),
1930+ None => Err(Failure::Definite),
1931+ };
1932+ CompletedEffect::plain(Event::LocalCellsRead { result })
1933+ }));
1934+ }
1935+ Effect::ReadOwner { op, cell } => {
1936+ self.route_effect_started(&cell);
1937+ let ownership = self.ownership.clone();
1938+ let timing_cell = cell.clone();
1939+ out.effects.push(Box::pin(async move {
1940+ let started = crate::asyncrt::mono_ms();
1941+ let result = ownership.read_owner(&cell).await;
1942+ CompletedEffect::timed(
1943+ Event::OwnerRead {
1944+ op,
1945+ now_ms: now_ms(),
1946+ result,
1947+ },
1948+ timing_cell,
1949+ RouteStage::OwnershipRead,
1950+ started,
1951+ )
1952+ }));
1953+ }
1954+ Effect::ReadNodeLease { op, cell, owner } => {
1955+ self.route_effect_started(&cell);
1956+ let ownership = self.ownership.clone();
1957+ let timing_cell = cell;
1958+ out.effects.push(Box::pin(async move {
1959+ let started = crate::asyncrt::mono_ms();
1960+ let result = ownership.read_node_lease(&owner).await;
1961+ CompletedEffect::timed(
1962+ Event::NodeLeaseRead {
1963+ op,
1964+ now_ms: now_ms(),
1965+ result,
1966+ },
1967+ timing_cell,
1968+ RouteStage::NodeLeaseLookup,
1969+ started,
1970+ )
1971+ }));
1972+ }
1973+ Effect::RecoverNodeLog { op, cell, owner } => {
1974+ self.route_effect_started(&cell);
1975+ #[cfg(all(test, celld_internal_tests))]
1976+ let interlock = if crate::asyncrt::sabotage_active(
1977+ crate::host_services::EngineSabotage::SkipTakeoverInterlock,
1978+ ) {
1979+ None
1980+ } else {
1981+ self.node_log.lock().unwrap().clone()
1982+ };
1983+ #[cfg(not(all(test, celld_internal_tests)))]
1984+ let interlock = self.node_log.lock().unwrap().clone();
1985+ let timing_cell = cell.clone();
1986+ out.effects.push(Box::pin(async move {
1987+ let started = crate::asyncrt::mono_ms();
1988+ let result = match interlock {
1989+ // No log tier on this node (no bucket): nothing to
1990+ // recover, and the claim proceeds as before.
1991+ None => Ok(()),
1992+ Some(interlock) => interlock
1993+ .ensure_recovered(Some(&owner))
1994+ .await
1995+ .map_err(|error| {
1996+ eprintln!(
1997+ "celld node-log recovery for takeover of {cell} failed: {error:#}"
1998+ );
1999+ Failure::Ambiguous
2000+ }),
2001+ };
2002+ CompletedEffect::timed(
2003+ Event::NodeLogRecovered { op, result },
2004+ timing_cell,
2005+ RouteStage::NodeLeaseLookup,
2006+ started,
2007+ )
2008+ }));
2009+ }
2010+ Effect::ReadCapacityPeers { op, cell } => {
2011+ self.route_effect_started(&cell);
2012+ let ownership = self.ownership.clone();
2013+ let timing_cell = cell;
2014+ out.effects.push(Box::pin(async move {
2015+ let started = crate::asyncrt::mono_ms();
2016+ let result = ownership.read_capacity_peers().await;
2017+ CompletedEffect::timed(
2018+ Event::CapacityPeersRead {
2019+ op,
2020+ now_ms: now_ms(),
2021+ result,
2022+ },
2023+ timing_cell,
2024+ RouteStage::CapacityLookup,
2025+ started,
2026+ )
2027+ }));
2028+ }
2029+ Effect::CasOwner {
2030+ op,
2031+ cell,
2032+ guard,
2033+ epoch,
2034+ takeover,
2035+ } => {
2036+ self.route_effect_started(&cell);
2037+ if let Some(timing) = self.route_timings.get_mut(&cell) {
2038+ timing
2039+ .fresh
2040+ .get_or_insert(!takeover && matches!(guard, CasGuard::Absent));
2041+ }
2042+ let ownership = self.ownership.clone();
2043+ let timing_cell = cell.clone();
2044+ out.effects.push(Box::pin(async move {
2045+ let started = crate::asyncrt::mono_ms();
2046+ let result = ownership.cas_owner(&cell, guard, epoch).await;
2047+ CompletedEffect::timed(
2048+ Event::OwnerCasCompleted { op, result },
2049+ timing_cell,
2050+ RouteStage::OwnershipAcquire,
2051+ started,
2052+ )
2053+ }));
2054+ }
2055+ Effect::ReconcileWakeEntry {
2056+ cell,
2057+ next_alarm_ms,
2058+ } => {
2059+ if self.host.is_some() {
2060+ // An ARMED alarm must always be reconcilable, tracked or
2061+ // not: belief can be lost while the alarm stands (a
2062+ // failed arm-time PUT, an entry retired under a racing
2063+ // arm), and skipping here would mean it is never
2064+ // re-asserted — entryless until the alarm fires or the
2065+ // cell moves. Gating the CONSUME side on tracking is
2066+ // what keeps alarm-less cells op-quiescent: untracked
2067+ // with no alarm, there is nothing to delete.
2068+ if next_alarm_ms >= 0 || crate::js::wake_entry_tracked(&cell) {
2069+ // On the host runtime: this arm runs on the core
2070+ // thread, and a bare spawn would schedule the S3
2071+ // round trip there too.
2072+ crate::asyncrt::spawn(async move {
2073+ // A consume-delete only ever follows a firing, and
2074+ // the core orders it from the far side of the
2075+ // output gate: `alarm_finished` gates the
2076+ // consuming commit, and only a proven
2077+ // DurableReached — with C1's ownership read
2078+ // behind a bucket proof — lets the alarm settle
2079+ // into this reconcile. So by the time this delete
2080+ // is ordered, the proof already happened, and
2081+ // nothing here decides anything. The old
2082+ // sync_refused probe asked the same question a
2083+ // second way and was wrong more often: it refused
2084+ // for any database the replicator never
2085+ // registered, leaving the entry to outlive its
2086+ // alarm forever.
2087+ crate::js::reconcile_wake_entry(&cell, next_alarm_ms, true).await;
2088+ })
2089+ .detach();
2090+ }
2091+ }
2092+ }
2093+ Effect::ReleaseOwner { op, cell, epoch } => {
2094+ let ownership = self.ownership.clone();
2095+ out.effects.push(Box::pin(async move {
2096+ let result = ownership.release_owner(&cell, epoch).await;
2097+ CompletedEffect::plain(Event::OwnerReleased { op, result })
2098+ }));
2099+ }
2100+ Effect::Restore { op, cell, spec } => {
2101+ self.route_effect_started(&cell);
2102+ if let Some(runtime) = self.host.clone() {
2103+ let timing_cell = cell.clone();
2104+ // A restore downloads, merges, and fsyncs a whole
2105+ // database. Poll it on the host runtime: this future
2106+ // lives in `out`, which the core thread drives,
2107+ // and the core owns the node lease timer.
2108+ let task = crate::asyncrt::spawn(async move {
2109+ let started = crate::asyncrt::mono_ms();
2110+ let result = runtime.restore_cell(&cell, &spec).await.map_err(|error| {
2111+ eprintln!("celld restore failed for {cell}: {error:#}");
2112+ Failure::Definite
2113+ });
2114+ CompletedEffect::timed(
2115+ Event::RestoreCompleted { op, result },
2116+ timing_cell,
2117+ RouteStage::Restore,
2118+ started,
2119+ )
2120+ });
2121+ out.effects.push(Box::pin(async move {
2122+ task.await.expect("restore task panicked")
2123+ }));
2124+ } else {
2125+ self.record_effect_timing(EffectTiming {
2126+ cell,
2127+ stage: RouteStage::Restore,
2128+ elapsed_us: 0,
2129+ });
2130+ immediate.push_back(Event::RestoreCompleted {
2131+ op,
2132+ result: Ok(celld_logic::RestoreOutcome {
2133+ restored: false,
2134+ alarm: None,
2135+ }),
2136+ });
2137+ }
2138+ }
2139+ Effect::StartRuntime { op, cell, epoch } => {
2140+ self.route_effect_started(&cell);
2141+ if let Some(runtime) = self.host.clone() {
2142+ let fresh = self
2143+ .route_timings
2144+ .get(&cell)
2145+ .and_then(|timing| timing.fresh)
2146+ .unwrap_or(false);
2147+ let timing_cell = cell.clone();
2148+ out.effects.push(Box::pin(async move {
2149+ let started = crate::asyncrt::mono_ms();
2150+ let placed = runtime
2151+ .start_cell(cell.clone(), epoch, fresh)
2152+ .await
2153+ .map_err(|error| {
2154+ eprintln!("celld runtime start failed for {cell}: {error:#}");
2155+ Failure::Definite
2156+ });
2157+ let isolate = placed.as_ref().ok().copied();
2158+ CompletedEffect::timed(
2159+ Event::RuntimeStarted {
2160+ op,
2161+ isolate,
2162+ result: placed.map(|_| ()),
2163+ },
2164+ timing_cell,
2165+ RouteStage::IsolateStartup,
2166+ started,
2167+ )
2168+ }));
2169+ } else {
2170+ self.record_effect_timing(EffectTiming {
2171+ cell,
2172+ stage: RouteStage::IsolateStartup,
2173+ elapsed_us: 0,
2174+ });
2175+ immediate.push_back(Event::RuntimeStarted {
2176+ op,
2177+ isolate: None,
2178+ result: Ok(()),
2179+ });
2180+ }
2181+ }
2182+ Effect::Publish { op, cell, epoch } => {
2183+ self.route_effect_started(&cell);
2184+ let publish_started = crate::asyncrt::mono_ms();
2185+ self.publishes += 1;
2186+ let result = if self.fail_publish_once {
2187+ self.fail_publish_once = false;
2188+ Err(Failure::Ambiguous)
2189+ } else {
2190+ self.host
2191+ .as_ref()
2192+ .map_or(Ok(()), |runtime| runtime.publish_cell(&cell, epoch))
2193+ .map_err(|error| {
2194+ eprintln!("celld runtime publication failed for {cell}: {error:#}");
2195+ Failure::Definite
2196+ })
2197+ };
2198+ if result.is_ok() {
2199+ self.published.insert(cell.clone());
2200+ }
2201+ self.record_effect_timing(EffectTiming {
2202+ cell: cell.clone(),
2203+ stage: RouteStage::RegistryInsert,
2204+ elapsed_us: mono_elapsed_us(publish_started),
2205+ });
2206+ if result.is_ok() {
2207+ let node = self.state.node().to_string();
2208+ self.finish_route(&cell, "activated", "", Some((&node, epoch)));
2209+ }
2210+ immediate.push_back(Event::Published { op, result });
2211+ }
2212+ Effect::EnsureDurable { op, cell, epoch } => {
2213+ let waiters = self.eviction_waiters.remove(&cell).unwrap_or_default();
2214+ self.durability_waiters.insert(op, (cell.clone(), waiters));
2215+ if let Some(runtime) = self.host.clone() {
2216+ out.effects.push(Box::pin(async move {
2217+ let result = runtime.ensure_durable(&cell, epoch).await.map_err(|error| {
2218+ eprintln!(
2219+ "celld durability proof failed for {cell} epoch {epoch}: {error:#}"
2220+ );
2221+ Failure::Ambiguous
2222+ });
2223+ CompletedEffect::plain(Event::DurabilityChecked { op, result })
2224+ }));
2225+ } else {
2226+ immediate.push_back(Event::DurabilityChecked { op, result: Ok(()) });
2227+ }
2228+ }
2229+ // The output gate: prove the cell durable, then let the core release
2230+ // the held write response. Reuses the same recency-proving primitive
2231+ // as EnsureDurable — a proof issued after the write covers it.
2232+ Effect::AwaitDurable {
2233+ op,
2234+ cell,
2235+ epoch,
2236+ position,
2237+ } => {
2238+ if let Some(runtime) = self.host.clone() {
2239+ out.effects.push(Box::pin(async move {
2240+ // The replicator reports the position it actually
2241+ // proved durable and which mechanism proved it; the
2242+ // core acks only if the position covers this write,
2243+ // and decides per source whether C1's ownership
2244+ // verification must run first (Effect::VerifyOwnership).
2245+ let (result, source) =
2246+ match runtime.await_durable(&cell, epoch, position).await {
2247+ Ok((durable, source)) => {
2248+ #[cfg(all(test, celld_internal_tests))]
2249+ let durable = if crate::asyncrt::sabotage_active(
2250+ crate::host_services::EngineSabotage::MisreportGatePosition,
2251+ ) {
2252+ durable.saturating_sub(1)
2253+ } else {
2254+ durable
2255+ };
2256+ (Ok(durable), source)
2257+ }
2258+ Err(error) => {
2259+ eprintln!(
2260+ "celld output-gate durability proof failed for {cell} \
2261+ epoch {epoch}: {error:#}"
2262+ );
2263+ (Err(Failure::Ambiguous), celld_logic::ProofSource::Bucket)
2264+ }
2265+ };
2266+ CompletedEffect::plain(Event::DurableReached { op, result, source })
2267+ }));
2268+ } else {
2269+ immediate.push_back(Event::DurableReached {
2270+ op,
2271+ result: Ok(position),
2272+ source: celld_logic::ProofSource::Fleet,
2273+ });
2274+ }
2275+ }
2276+ Effect::VerifyOwnership { op, cell, epoch } => {
2277+ // C1 for bucket-proof acks. Durable in `e<epoch>/` is not
2278+ // the same as durable: if the cell has been taken over, that
2279+ // prefix is orphaned — the next owner restores a higher
2280+ // epoch and this write is gone. A read is enough, and is why
2281+ // this is one GET rather than a compare-and-swap: if the
2282+ // record still names us, no takeover linearised before this
2283+ // read; the LTX went up before it; so any later takeover
2284+ // restores from a lineage that already contains the write.
2285+ let ownership = self.ownership.clone();
2286+ let node = self.state.node().to_string();
2287+ out.effects.push(Box::pin(async move {
2288+ #[cfg(all(test, celld_internal_tests))]
2289+ if crate::asyncrt::sabotage_active(
2290+ crate::host_services::EngineSabotage::SkipBucketProofOwnershipRead,
2291+ ) {
2292+ return CompletedEffect::plain(Event::OwnershipVerified {
2293+ op,
2294+ result: Ok(()),
2295+ });
2296+ }
2297+ let result = match ownership.read_owner(&cell).await {
2298+ Ok(Some(record))
2299+ if record.node.as_deref() == Some(node.as_str())
2300+ && record.epoch == epoch =>
2301+ {
2302+ Ok(())
2303+ }
2304+ Ok(record) => {
2305+ eprintln!(
2306+ "celld output gate: {cell} epoch {epoch} is no longer ours \
2307+ (record: {record:?}); refusing to acknowledge a write in an \
2308+ orphaned epoch"
2309+ );
2310+ Err(Failure::Definite)
2311+ }
2312+ Err(failure) => Err(failure),
2313+ };
2314+ CompletedEffect::plain(Event::OwnershipVerified { op, result })
2315+ }));
2316+ }
2317+ Effect::ReleaseResponse { request, result } => {
2318+ if self.ws_gated.contains_key(&request) {
2319+ self.ws_release(request, result.is_ok());
2320+ } else if let Some(reply) = self.gated_responses.remove(&request) {
2321+ let _ = reply.send(result);
2322+ }
2323+ }
2324+ Effect::StopRuntime {
2325+ op,
2326+ cell,
2327+ epoch,
2328+ cause,
2329+ } => {
2330+ #[cfg(all(test, celld_internal_tests))]
2331+ if matches!(cause, StopCause::Reset)
2332+ && crate::asyncrt::sabotage_active(
2333+ crate::host_services::EngineSabotage::SuppressResetStop,
2334+ )
2335+ {
2336+ return;
2337+ }
2338+ self.stops += 1;
2339+ let evicting = matches!(cause, StopCause::Evict { .. });
2340+ if matches!(cause, StopCause::Fence) {
2341+ // A fenced cell's wake entry belongs to whoever takes the
2342+ // cell over; a retained local belief would collide with
2343+ // the new owner's arm/consume traffic on the same key.
2344+ crate::js::forget_wake_entry(&cell);
2345+ }
2346+ // Handing the cell away makes the local snapshot dead weight;
2347+ // keeping it is the whole point of an idle eviction. A
2348+ // reset must keep nothing: the local database is precisely
2349+ // what could not be proved durable, so the next activation has
2350+ // to come from the bucket.
2351+ let preserve_local = !matches!(
2352+ cause,
2353+ StopCause::Evict { rebalance: true } | StopCause::Reset
2354+ );
2355+ if evicting {
2356+ if let Some(live) = &self.live_load {
2357+ live.shed_cells.fetch_add(1, Ordering::Relaxed);
2358+ }
2359+ }
2360+ self.published.remove(&cell);
2361+ if let Some(runtime) = self.host.clone() {
2362+ out.effects.push(Box::pin(async move {
2363+ runtime
2364+ .stop_cell(&cell, epoch, evicting, preserve_local)
2365+ .await;
2366+ CompletedEffect::plain(Event::RuntimeStopped { op })
2367+ }));
2368+ } else {
2369+ immediate.push_back(Event::RuntimeStopped { op });
2370+ }
2371+ }
2372+ Effect::FireAlarm {
2373+ op,
2374+ cell,
2375+ epoch,
2376+ scheduled_ms,
2377+ } => {
2378+ if let Some(runtime) = self.host.clone() {
2379+ out.effects.push(Box::pin(async move {
2380+ // The shell reports the firing raw: the deadline that
2381+ // stands after the handler, whether a wake entry
2382+ // covers it, and the position of the consuming
2383+ // commit. Proving that commit durable — and this node
2384+ // still the owner — is the core's job: it opens the
2385+ // same output gate a request's write gets, so one
2386+ // question answers for every egress on the cell, and
2387+ // the consume-side wake-entry delete leaves only from
2388+ // the far side of the proof. On failure the core
2389+ // re-arms or resets; either way the entry stays
2390+ // discoverable and at-least-once holds.
2391+ let result = runtime
2392+ .fire_alarm(cell.clone(), scheduled_ms)
2393+ .await
2394+ .map_err(|error| {
2395+ eprintln!("celld alarm dispatch failed: {error:#}");
2396+ Failure::Definite
2397+ });
2398+ // The tooth for the gate the core opens below. It
2399+ // restores the shape this change replaced: prove the
2400+ // commit here, privately, and tell the core nothing —
2401+ // so the proof still runs, and every reader of the
2402+ // cell is still released against it.
2403+ #[cfg(all(test, celld_internal_tests))]
2404+ let result = if crate::asyncrt::sabotage_active(
2405+ crate::host_services::EngineSabotage::SkipAlarmWriteGate,
2406+ ) {
2407+ if let Ok((_, _, Some(position))) = result {
2408+ let _ = runtime.await_durable(&cell, epoch, position).await;
2409+ }
2410+ result.map(|(at_ms, covered, _)| (at_ms, covered, None))
2411+ } else {
2412+ result
2413+ };
2414+ CompletedEffect::plain(Event::AlarmFinished {
2415+ op,
2416+ cell,
2417+ epoch,
2418+ now_ms: now_ms(),
2419+ now_mono_ms: crate::asyncrt::mono_ms(),
2420+ result,
2421+ })
2422+ }));
2423+ } else {
2424+ immediate.push_back(Event::AlarmFinished {
2425+ op,
2426+ cell,
2427+ epoch,
2428+ now_ms: now_ms(),
2429+ now_mono_ms: crate::asyncrt::mono_ms(),
2430+ result: Ok((None, true, None)),
2431+ });
2432+ }
2433+ }
2434+ Effect::Complete { request, result } => {
2435+ if let Some(cell) = self.request_cells.remove(&request) {
2436+ match &result {
2437+ Ok(Route::Remote { node, epoch, .. }) => {
2438+ self.finish_route(&cell, "remote_owner", "", Some((node, *epoch)));
2439+ // The cell lives elsewhere: its wake entry is no
2440+ // longer this node's to track, and a stale local
2441+ // belief would collide with the owner's own
2442+ // arm/consume traffic on the same key.
2443+ crate::js::forget_wake_entry(&cell);
2444+ }
2445+ Ok(Route::Local) => {
2446+ self.finish_route(&cell, "resident_after_wait", "", None);
2447+ }
2448+ Err(error) => {
2449+ self.finish_route(
2450+ &cell,
2451+ "route_error",
2452+ request_error_phase(*error),
2453+ None,
2454+ );
2455+ }
2456+ }
2457+ }
2458+ if let Some(reply) = self.pending.remove(&request) {
2459+ let local = result == Ok(Route::Local);
2460+ if reply
2461+ .send(result.map(|route| Routed { request, route }))
2462+ .is_err()
2463+ && local
2464+ {
2465+ immediate.push_back(Event::ActivityFinished { request });
2466+ }
2467+ }
2468+ }
2469+ Effect::CompleteWorker { request, route } => {
2470+ if let Some(op) = route.as_ref().and_then(|route| route.retired_durability) {
2471+ if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
2472+ for waiter in waiters {
2473+ let _ = waiter.send(());
2474+ }
2475+ }
2476+ }
2477+ if let Some(reply) = self.pending_workers.remove(&request) {
2478+ let reserved = route.is_some();
2479+ if reply.send(WorkerRouted { request, route }).is_err() && reserved {
2480+ immediate.push_back(Event::ActivityFinished { request });
2481+ }
2482+ }
2483+ }
2484+ Effect::CloseWebSocket { cell, websocket } => {
2485+ // The core declined to hold this transport. Drop it and tell
2486+ // the core it is gone, so the cell is not left believing it
2487+ // has a socket the node already closed.
2488+ eprintln!(
2489+ "celld refused an outbound WebSocket for {cell}: the node's \
2490+ outbound pin budget is spent"
2491+ );
2492+ crate::js::ws_unregister(websocket);
2493+ immediate.push_back(Event::WebSocketClosed { cell, websocket });
2494+ }
2495+ Effect::Halt { code, reason } => {
2496+ // Say why before going. Self-fencing is the most drastic thing
2497+ // this process does, and an exit code on its own leaves an
2498+ // operator to guess between a lease it could not renew, a
2499+ // replicator that died, and a crash.
2500+ match reason {
2501+ celld_logic::HaltReason::NodeLeaseExpired => tracing::warn!(
2502+ event = "node_lease_watchdog_fence",
2503+ code,
2504+ "SELF-FENCE: node lease not renewed within TTL — halting"
2505+ ),
2506+ }
2507+ let _ = self.fence.send(code);
2508+ }
2509+ }
2510+ }
2511+
2512+ fn state_json(&self) -> String {
2513+ let residents = self
2514+ .state
2515+ .residents()
2516+ .into_iter()
2517+ .map(|cell| format!("{cell:?}"))
2518+ .collect::<Vec<_>>()
2519+ .join(",");
2520+ let published = self
2521+ .published
2522+ .iter()
2523+ .map(|cell| format!("{cell:?}"))
2524+ .collect::<Vec<_>>()
2525+ .join(",");
2526+ // Both numbers: a gap between them is memory the allocator kept, which
2527+ // no eviction returns. One sample, so they cannot disagree.
2528+ let memory = crate::memory::sample();
2529+ // `restoring` is a sum, and a node that refuses cells for a quarter of
2530+ // an hour needs its parts. `activating` holds a permit and is doing
2531+ // work; `activation_waiting` is queued behind the activation ceiling;
2532+ // `capacity_waiting` is queued behind residency. The census says where
2533+ // every cell is, which `occupied` cannot: it counts residency, so a
2534+ // node part-way through thousands of cold starts reports almost none.
2535+ // Issue #50 is open because none of this was recorded at the time.
2536+ let phases = self
2537+ .state
2538+ .phase_census()
2539+ .into_iter()
2540+ .map(|(phase, count)| format!("{phase:?}:{count}"))
2541+ .collect::<Vec<_>>()
2542+ .join(",");
2543+ format!(
2544+ "{{\"ownership\":{:?},\"occupied\":{},\"evicting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}",
2545+ self.ownership.name(),
2546+ self.state.occupied(),
2547+ self.state.evicting(),
2548+ self.state.activation_backlog(),
2549+ self.state.activating(),
2550+ self.state.activation_waiting().len(),
2551+ self.state.waiting().len(),
2552+ phases,
2553+ self.state
2554+ .shed_reason()
2555+ .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")),
2556+ memory.rss_bytes,
2557+ memory.in_use_bytes,
2558+ residents,
2559+ published,
2560+ self.publishes,
2561+ self.stops
2562+ )
2563+ }
2564+
2565+ fn begin_route_if_cold(&mut self, cell: &str) {
2566+ if !matches!(
2567+ self.state.phase(cell),
2568+ Some(Phase::Resident { .. } | Phase::EnsuringDurability { .. } | Phase::Remote { .. })
2569+ ) {
2570+ self.route_timings
2571+ .entry(cell.to_string())
2572+ .or_insert_with(CellRouteTiming::new);
2573+ }
2574+ }
2575+
2576+ fn route_effect_started(&mut self, cell: &str) {
2577+ if let Some(timing) = self.route_timings.get_mut(cell) {
2578+ timing.effect_started();
2579+ }
2580+ }
2581+
2582+ fn observe_capacity_wait(&mut self, cell: &str) {
2583+ if matches!(self.state.phase(cell), Some(Phase::WaitingCapacity)) {
2584+ if let Some(timing) = self.route_timings.get_mut(cell) {
2585+ timing
2586+ .capacity_wait_started_mono_ms
2587+ .get_or_insert_with(crate::asyncrt::mono_ms);
2588+ }
2589+ }
2590+ }
2591+
2592+ fn record_effect_timing(&mut self, completed: EffectTiming) {
2593+ if let Some(timing) = self.route_timings.get_mut(&completed.cell) {
2594+ timing.record(completed.stage, completed.elapsed_us);
2595+ }
2596+ }
2597+
2598+ fn finish_route(
2599+ &mut self,
2600+ cell: &str,
2601+ outcome: &str,
2602+ failure_phase: &str,
2603+ owner: Option<(&str, u64)>,
2604+ ) {
2605+ let Some(mut timing) = self.route_timings.remove(cell) else {
2606+ return;
2607+ };
2608+ if let Some(started) = timing.capacity_wait_started_mono_ms.take() {
2609+ timing.capacity_wait_us = timing
2610+ .capacity_wait_us
2611+ .saturating_add(mono_elapsed_us(started));
2612+ }
2613+ let (owner_node, epoch) = owner.unwrap_or(("", 0));
2614+ tracing::debug!(
2615+ target: "timing",
2616+ event = "cell_route_timing",
2617+ outcome,
2618+ failure_phase,
2619+ scope = %cell,
2620+ node = %self.state.node(),
2621+ region = %self.region,
2622+ runtime_version = env!("CARGO_PKG_VERSION"),
2623+ owner_node,
2624+ epoch,
2625+ fresh = timing.fresh.unwrap_or(false),
2626+ total_us = mono_elapsed_us(timing.started_mono_ms),
2627+ latch_wait_us = timing.latch_wait_us,
2628+ ownership_read_us = timing.ownership_read_us,
2629+ node_lease_lookup_us = timing.node_lease_lookup_us,
2630+ capacity_lookup_us = timing.capacity_lookup_us,
2631+ capacity_wait_us = timing.capacity_wait_us,
2632+ activation_slot_wait_us = timing.activation_slot_wait_us,
2633+ lease_permit_us = timing.lease_permit_us,
2634+ ownership_acquire_us = timing.ownership_acquire_us,
2635+ replica_discovery_us = timing.replica_discovery_us,
2636+ restore_us = timing.restore_us,
2637+ isolate_startup_us = timing.isolate_startup_us,
2638+ registry_insert_us = timing.registry_insert_us,
2639+ "cell route resolved"
2640+ );
2641+ }
2642+}
2643+
2644+fn request_error_phase(error: RequestError) -> &'static str {
2645+ match error {
2646+ RequestError::NodeUnavailable | RequestError::NodeFenced => "node_authority",
2647+ RequestError::ResolveFailed | RequestError::PeerIncompatible => "ownership_lookup",
2648+ RequestError::CapacityExhausted => "capacity_wait",
2649+ RequestError::AcquireFailed => "ownership_acquire",
2650+ RequestError::RestoreFailed => "restore",
2651+ RequestError::RuntimeFailed => "isolate_startup",
2652+ RequestError::PublishFailed => "registry_insert",
2653+ RequestError::DurabilityUnproven => "output_gate",
2654+ }
2655+}
2656+
2657+#[cfg(all(test, celld_internal_tests))]
2658+include!(env!("CELLD_INTERNAL_ACTOR_OBSERVERS"));
addedcrates/celld/actor/production.rs+44−0View file
@@ -1,0 +1,44 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+//! The production selector which the deterministic World replaces.
4+
5+#![allow(clippy::disallowed_macros)]
6+
7+use super::*;
8+use futures_util::StreamExt as _;
9+
10+impl Actor {
11+ /// Runs the production start-select-step loop.
12+ ///
13+ /// This selector stays unbiased because production has always permitted
14+ /// every ready-input order. The World calls [`Actor::start`] and
15+ /// [`Actor::step`] directly, so it never executes this raw Tokio select.
16+ pub async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Message>) {
17+ let mut effects = FuturesUnordered::new();
18+ let mut delays = DelayQueue::new();
19+ let mut timer_slots = TimerSlots::<delay_queue::Key>::default();
20+ let mut out = StepOutput::default();
21+ self.start(&mut out);
22+ drain_step_output(&mut out, &mut effects, &mut delays, &mut timer_slots);
23+ loop {
24+ tokio::select! {
25+ message = rx.recv() => {
26+ let Some(message) = message else {
27+ break;
28+ };
29+ self.step(ActorInput::Message(message), &mut out);
30+ }
31+ Some(completed) = effects.next(), if !effects.is_empty() => {
32+ self.step(ActorInput::Completed(completed), &mut out);
33+ }
34+ Some(expired) = delays.next(), if !delays.is_empty() => {
35+ let arm = expired.into_inner();
36+ if timer_slots.fire(&arm.slot, arm.ordinal).is_some() {
37+ self.step(ActorInput::TimerFired(arm.timer), &mut out);
38+ }
39+ }
40+ }
41+ drain_step_output(&mut out, &mut effects, &mut delays, &mut timer_slots);
42+ }
43+ }
44+}
modifiedcrates/celld/assets.rs+4−0View file
@@ -1,5 +1,9 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3+// Asset download and cache maintenance execute in the V8/process arm, which
4+// the World replaces with scripted client and cell-host boundaries.
5+#![allow(clippy::disallowed_methods, clippy::disallowed_types)]
6+
37 use crate::bucket::Bucket;
48 use crate::js;
59 use crate::protocol::{asset_blob_key, AssetEntry, AssetIndex, AssetManifestRef, RunWorkerFirst};
modifiedcrates/celld/asyncrt.rs+329−37View file
@@ -1,30 +1,303 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3-//! Async operations started by JavaScript.
3+// This module owns the ambient production primitives which the boundary lint
4+// prohibits elsewhere.
5+#![allow(clippy::disallowed_methods, clippy::disallowed_types)]
6+#![warn(clippy::disallowed_macros)]
7+
8+//! The production execution facade for celld.
49 //!
5-//! An op is enqueued during a synchronous isolate turn. The request driver
6-//! takes those futures when the turn ends, polls them on celld's shared Tokio
7-//! runtime, and re-enters the isolate only to deliver a completed result.
10+//! This module delegates tasks and timers to Tokio and obtains nondeterministic
11+//! process values from the host. The private conformance build replaces this
12+//! module with its deterministic execution backend.
13+
14+use crate::host_services::HostServices;
15+use rand::{CryptoRng, RngCore};
816 use std::cell::RefCell;
9-use std::future::Future;
17+use std::fmt;
18+use std::future::{poll_fn, Future};
1019 use std::pin::Pin;
1120 use std::sync::atomic::{AtomicU64, Ordering};
12-use std::sync::OnceLock;
21+use std::sync::{Arc, OnceLock};
22+use std::task::{Context, Poll};
23+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
1324
14-static NEXT_ID: AtomicU64 = AtomicU64::new(1);
15-static HOST_RT: OnceLock<tokio::runtime::Handle> = OnceLock::new();
25+static PROCESS_DOMAIN: OnceLock<ProductionDomain> = OnceLock::new();
26+static FALLBACK_SERVICES: OnceLock<Arc<HostServices>> = OnceLock::new();
1627
17-/// What an async op resolves its JS promise with: a string, or raw bytes
18-/// (delivered as a `Uint8Array` — the structured-clone RPC payloads).
28+thread_local! {
29+ static SPAWNS: RefCell<Vec<(u64, OpFuture)>> = const { RefCell::new(Vec::new()) };
30+}
31+
32+struct ProductionDomain {
33+ handle: tokio::runtime::Handle,
34+ started_at: Instant,
35+ services: Arc<HostServices>,
36+ filesystem: Arc<dyn celld_ltx::FileSystem>,
37+ next_core_request: AtomicU64,
38+ next_async_op: AtomicU64,
39+ process_tag: u64,
40+}
41+
42+impl ProductionDomain {
43+ fn new(handle: tokio::runtime::Handle) -> Self {
44+ Self {
45+ handle,
46+ started_at: Instant::now(),
47+ services: Arc::new(HostServices::production()),
48+ filesystem: Arc::new(celld_ltx::DirectFileSystem),
49+ next_core_request: AtomicU64::new(1),
50+ next_async_op: AtomicU64::new(1),
51+ process_tag: u64::from(std::process::id()),
52+ }
53+ }
54+}
55+
56+fn current_domain() -> &'static ProductionDomain {
57+ PROCESS_DOMAIN.get_or_init(|| ProductionDomain::new(tokio::runtime::Handle::current()))
58+}
59+
60+/// A normalized task panic returned by a typed task handle.
61+#[derive(Clone, Debug, PartialEq, Eq)]
62+pub struct TaskPanic {
63+ pub message: String,
64+}
65+
66+impl fmt::Display for TaskPanic {
67+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
68+ formatter.write_str(&self.message)
69+ }
70+}
71+
72+impl std::error::Error for TaskPanic {}
73+
74+/// A typed join handle for one production task.
75+pub struct TaskHandle<T> {
76+ inner: tokio::task::JoinHandle<T>,
77+}
78+
79+impl<T> Unpin for TaskHandle<T> {}
80+
81+impl<T> TaskHandle<T> {
82+ /// Detach the task from its join handle.
83+ pub fn detach(self) {}
84+}
85+
86+impl<T> Future for TaskHandle<T> {
87+ type Output = Result<T, TaskPanic>;
88+
89+ fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
90+ Pin::new(&mut self.get_mut().inner)
91+ .poll(context)
92+ .map(|result| {
93+ result.map_err(|error| TaskPanic {
94+ message: error.to_string(),
95+ })
96+ })
97+ }
98+}
99+
100+/// Install the process runtime handle.
101+pub fn set_host_handle(handle: tokio::runtime::Handle) {
102+ let _ = PROCESS_DOMAIN.set(ProductionDomain::new(handle));
103+}
104+
105+/// Return the Tokio handle for the V8 arm.
106+pub fn op_handle() -> tokio::runtime::Handle {
107+ current_domain().handle.clone()
108+}
109+
110+pub fn spawn<T, F>(future: F) -> TaskHandle<T>
111+where
112+ T: Send + 'static,
113+ F: Future<Output = T> + Send + 'static,
114+{
115+ TaskHandle {
116+ inner: current_domain().handle.spawn(future),
117+ }
118+}
119+
120+pub fn blocking<T, F>(operation: F) -> TaskHandle<T>
121+where
122+ T: Send + 'static,
123+ F: FnOnce() -> T + Send + 'static,
124+{
125+ TaskHandle {
126+ inner: current_domain().handle.spawn_blocking(operation),
127+ }
128+}
129+
130+pub fn block_on<F>(future: F) -> F::Output
131+where
132+ F: Future + Send + 'static,
133+ F::Output: Send + 'static,
134+{
135+ current_domain().handle.block_on(future)
136+}
137+
138+/// Return the local filesystem for the process.
139+pub fn fs() -> Arc<dyn celld_ltx::FileSystem> {
140+ current_domain().filesystem.clone()
141+}
142+
143+/// Return the maximum component length for the filesystem at `path`.
144+pub fn filesystem_name_max(path: &std::path::Path) -> std::io::Result<Option<i64>> {
145+ let directory = std::fs::File::open(path)?;
146+ nix::unistd::fpathconf(&directory, nix::unistd::PathconfVar::NAME_MAX).map_err(Into::into)
147+}
148+
149+pub fn wall_ms() -> i64 {
150+ SystemTime::now()
151+ .duration_since(UNIX_EPOCH)
152+ .unwrap_or_default()
153+ .as_millis() as i64
154+}
155+
156+pub fn mono_ms() -> u64 {
157+ current_domain().started_at.elapsed().as_millis() as u64
158+}
159+
160+pub fn rng(consumer: &'static str) -> rng::Stream {
161+ let _ = consumer;
162+ rng::Stream::production()
163+}
164+
165+pub fn process_tag() -> u64 {
166+ current_domain().process_tag
167+}
168+
169+pub fn next_core_request() -> u64 {
170+ current_domain()
171+ .next_core_request
172+ .fetch_add(1, Ordering::Relaxed)
173+}
174+
175+pub fn services() -> Arc<HostServices> {
176+ PROCESS_DOMAIN
177+ .get()
178+ .map(|domain| domain.services.clone())
179+ .unwrap_or_else(|| {
180+ FALLBACK_SERVICES
181+ .get_or_init(|| Arc::new(HostServices::production()))
182+ .clone()
183+ })
184+}
185+
186+pub type Sleep = Pin<Box<dyn Future<Output = ()> + Send>>;
187+
188+pub fn sleep_until(deadline_ms: u64) -> Sleep {
189+ let wait = Duration::from_millis(deadline_ms.saturating_sub(mono_ms()));
190+ Box::pin(tokio::time::sleep(wait))
191+}
192+
193+pub fn sleep(duration: Duration) -> Sleep {
194+ sleep_until(mono_ms().saturating_add(duration.as_millis() as u64))
195+}
196+
197+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
198+pub struct Elapsed;
199+
200+impl fmt::Display for Elapsed {
201+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
202+ formatter.write_str("deadline elapsed")
203+ }
204+}
205+
206+impl std::error::Error for Elapsed {}
207+
208+pub async fn timeout_at<F>(deadline_ms: u64, future: F) -> Result<F::Output, Elapsed>
209+where
210+ F: Future,
211+{
212+ let mut future = Box::pin(future);
213+ let mut deadline = sleep_until(deadline_ms);
214+ poll_fn(move |context| {
215+ if let Poll::Ready(output) = future.as_mut().poll(context) {
216+ return Poll::Ready(Ok(output));
217+ }
218+ if mono_ms() >= deadline_ms {
219+ return Poll::Ready(Err(Elapsed));
220+ }
221+ if deadline.as_mut().poll(context).is_ready() {
222+ return Poll::Ready(Err(Elapsed));
223+ }
224+ Poll::Pending
225+ })
226+ .await
227+}
228+
229+pub async fn timeout<F>(duration: Duration, future: F) -> Result<F::Output, Elapsed>
230+where
231+ F: Future,
232+{
233+ timeout_at(
234+ mono_ms().saturating_add(duration.as_millis() as u64),
235+ future,
236+ )
237+ .await
238+}
239+
240+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
241+pub enum MissedTickBehavior {
242+ Burst,
243+ Delay,
244+ Skip,
245+}
246+
247+pub struct Interval {
248+ next_ms: u64,
249+ period_ms: u64,
250+ behavior: MissedTickBehavior,
251+}
252+
253+impl Interval {
254+ pub fn set_missed_tick_behavior(&mut self, behavior: MissedTickBehavior) {
255+ self.behavior = behavior;
256+ }
257+
258+ pub async fn tick(&mut self) {
259+ sleep_until(self.next_ms).await;
260+ let now = mono_ms();
261+ self.next_ms = match self.behavior {
262+ MissedTickBehavior::Burst => self.next_ms.saturating_add(self.period_ms),
263+ MissedTickBehavior::Delay => now.saturating_add(self.period_ms),
264+ MissedTickBehavior::Skip => {
265+ let missed = now.saturating_sub(self.next_ms) / self.period_ms.max(1);
266+ self.next_ms
267+ .saturating_add(missed.saturating_add(1).saturating_mul(self.period_ms))
268+ }
269+ };
270+ }
271+}
272+
273+pub fn interval(period: Duration) -> Interval {
274+ Interval {
275+ next_ms: mono_ms(),
276+ period_ms: period.as_millis().max(1) as u64,
277+ behavior: MissedTickBehavior::Burst,
278+ }
279+}
280+
281+pub fn interval_at(start_ms: u64, period: Duration) -> Interval {
282+ Interval {
283+ next_ms: start_ms,
284+ period_ms: period.as_millis().max(1) as u64,
285+ behavior: MissedTickBehavior::Burst,
286+ }
287+}
288+
289+/// The output of one asynchronous JavaScript operation.
19290 pub enum OpOut {
20291 Str(String),
21292 Bytes(Vec<u8>),
22293 }
294+
23295 impl From<String> for OpOut {
24296 fn from(value: String) -> Self {
25297 Self::Str(value)
26298 }
27299 }
300+
28301 impl From<Vec<u8>> for OpOut {
29302 fn from(value: Vec<u8>) -> Self {
30303 Self::Bytes(value)
@@ -33,37 +306,56 @@
33306
34307 pub type OpFuture = Pin<Box<dyn Future<Output = Result<OpOut, String>> + Send>>;
35308
36-thread_local! {
37- // Ops push (id, future); the turn driver drains and owns them.
38- static SPAWNS: RefCell<Vec<(u64, OpFuture)>> = const { RefCell::new(Vec::new()) };
39-}
40-
41-/// Install celld's shared Tokio runtime for host I/O. Futures remain owned by
42-/// each request driver, but polling network work on the shared runtime lets a
43-/// reqwest response body move into Axum and continue streaming after the JS
44-/// handler has returned.
45-pub fn set_host_handle(handle: tokio::runtime::Handle) {
46- let _ = HOST_RT.set(handle);
47-}
48-
49-pub fn op_handle() -> tokio::runtime::Handle {
50- HOST_RT
51- .get()
52- .cloned()
53- .unwrap_or_else(tokio::runtime::Handle::current)
54-}
55-
56-/// Register an async op's future; returns its promise id. NOT spawned here — the
57-/// request driver owns polling, so a task is never detached.
309+/// Register an asynchronous operation. The request driver polls the operation.
58310 pub fn enqueue<T: Into<OpOut>>(
59- fut: impl Future<Output = Result<T, String>> + Send + 'static,
311+ future: impl Future<Output = Result<T, String>> + Send + 'static,
60312 ) -> u64 {
61- let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
62- let fut: OpFuture = Box::pin(async move { fut.await.map(Into::into) });
63- SPAWNS.with(|s| s.borrow_mut().push((id, fut)));
313+ let id = current_domain()
314+ .next_async_op
315+ .fetch_add(1, Ordering::Relaxed);
316+ let future: OpFuture = Box::pin(async move { future.await.map(Into::into) });
317+ SPAWNS.with(|spawns| spawns.borrow_mut().push((id, future)));
64318 id
65319 }
66320
67321 pub fn drain_spawns() -> Vec<(u64, OpFuture)> {
68- SPAWNS.with(|s| s.borrow_mut().drain(..).collect())
322+ SPAWNS.with(|spawns| spawns.borrow_mut().drain(..).collect())
69323 }
324+
325+pub use crate::__celld_domain_select as select;
326+
327+pub mod rng {
328+ use super::*;
329+
330+ /// A random stream for one production consumer.
331+ pub struct Stream {
332+ _private: (),
333+ }
334+
335+ impl Stream {
336+ pub(super) fn production() -> Self {
337+ Self { _private: () }
338+ }
339+ }
340+
341+ impl RngCore for Stream {
342+ fn next_u32(&mut self) -> u32 {
343+ rand::rngs::OsRng.next_u32()
344+ }
345+
346+ fn next_u64(&mut self) -> u64 {
347+ rand::rngs::OsRng.next_u64()
348+ }
349+
350+ fn fill_bytes(&mut self, destination: &mut [u8]) {
351+ rand::rngs::OsRng.fill_bytes(destination);
352+ }
353+
354+ fn try_fill_bytes(&mut self, destination: &mut [u8]) -> Result<(), rand::Error> {
355+ self.fill_bytes(destination);
356+ Ok(())
357+ }
358+ }
359+
360+ impl CryptoRng for Stream {}
361+}
modifiedcrates/celld/bucket.rs+417−86View file
@@ -1,16 +1,20 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3+#![warn(clippy::disallowed_macros)]
4+
35 //! The engine's single object-store client: the `object_store` crate
46 //! `celld-ltx` already links, bound to one bucket. Replaces aws-sdk-s3.
57 //! No call site streamed a body, so everything is in-memory `Bytes`.
68 //!
79 //! Two conditional-write dialects share the surface. An `s3://` (or
810 //! bare) spec speaks the S3 dialect: the CAS token is the etag, sent as
9-//! If-Match / If-None-Match with SigV4 credentials. A `gs://` spec
10-//! speaks the Cloud Storage XML API dialect: the CAS token is the
11-//! object generation, sent as x-goog-if-generation-match with OAuth
12-//! credentials. The distinction is the dialect, not the endpoint — GCS
13-//! accepts S3-style requests on the same host but does not apply
11+//! If-Match / If-None-Match with SigV4 credentials. An `az://` spec
12+//! speaks the same etag dialect on Azure Blob Storage: Put Blob honors
13+//! both headers, so only the client and the credentials differ. A
14+//! `gs://` spec speaks the Cloud Storage XML API dialect: the CAS token
15+//! is the object generation, sent as x-goog-if-generation-match with
16+//! OAuth credentials. The distinction is the dialect, not the endpoint —
17+//! GCS accepts S3-style requests on the same host but does not apply
1418 //! If-Match to a PUT, so only the generation dialect can fence there.
1519 //! Callers never see the difference: the token is an opaque `String` a
1620 //! read answers and a conditional write consumes.
@@ -27,6 +31,9 @@
2731 use futures_util::StreamExt;
2832 use object_store::aws::AmazonS3Builder;
2933 use object_store::aws::S3ConditionalPut;
34+use object_store::azure::authority_hosts;
35+use object_store::azure::AzureConfigKey;
36+use object_store::azure::MicrosoftAzureBuilder;
3037 use object_store::gcp::GoogleCloudStorageBuilder;
3138 use object_store::path::Path;
3239 use object_store::Attribute;
@@ -54,13 +61,17 @@
5461 }
5562
5663 /// Which conditional-write dialect the bucket speaks, and therefore
57-/// what the opaque CAS token holds: the etag on S3, the object
58-/// generation on GCS. GCS ignores etags on writes, so its tokens must
59-/// come from the generation everywhere — reads, heads, and put results.
64+/// what the opaque CAS token holds: the etag on S3 and on Azure Blob
65+/// Storage, the object generation on GCS. GCS ignores etags on writes,
66+/// so its tokens must come from the generation everywhere — reads,
67+/// heads, and put results. Azure needs no third dialect: Put Blob
68+/// applies If-None-Match and If-Match to the etag, exactly as S3 does,
69+/// so the two share [`Self::token`] and [`Self::update`].
6070 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
6171 pub(crate) enum StorageBackend {
6272 S3,
6373 Gcs,
74+ Azure,
6475 }
6576
6677 impl StorageBackend {
@@ -68,6 +79,7 @@
6879 match self {
6980 StorageBackend::S3 => "s3",
7081 StorageBackend::Gcs => "gs",
82+ StorageBackend::Azure => "az",
7183 }
7284 }
7385
@@ -77,7 +89,7 @@
7789 /// conditional write would send as a real precondition.
7890 fn token(self, e_tag: Option<String>, version: Option<String>) -> anyhow::Result<String> {
7991 let (token, header) = match self {
80- StorageBackend::S3 => (e_tag, "ETag"),
92+ StorageBackend::S3 | StorageBackend::Azure => (e_tag, "ETag"),
8193 StorageBackend::Gcs => (version, "x-goog-generation"),
8294 };
8395 match token {
@@ -91,7 +103,7 @@
91103 /// The precondition a conditional update sends for a held token.
92104 fn update(self, token: &str) -> UpdateVersion {
93105 match self {
94- StorageBackend::S3 => UpdateVersion {
106+ StorageBackend::S3 | StorageBackend::Azure => UpdateVersion {
95107 e_tag: Some(token.to_string()),
96108 version: None,
97109 },
@@ -108,7 +120,7 @@
108120 /// wrong place.
109121 fn precondition(self) -> &'static str {
110122 match self {
111- StorageBackend::S3 => "If-Match / If-None-Match",
123+ StorageBackend::S3 | StorageBackend::Azure => "If-Match / If-None-Match",
112124 StorageBackend::Gcs => "x-goog-if-generation-match",
113125 }
114126 }
@@ -134,15 +146,32 @@
134146 pub prefix: String,
135147 }
136148
137-/// Split a `[s3://|gs://]NAME[/PREFIX]` bucket spec into the backend, the
138-/// bucket name and a normalized key prefix: empty, or slash-terminated. A
139-/// spec without a scheme stays S3-compatible, and a spec without a PREFIX
140-/// keeps every key at the bucket root, so a fleet provisioned before
141-/// either existed never moves its objects.
149+/// Whether a conditional write reached a provider-enforced conflict.
150+/// Azure reports a failed `If-None-Match` as `Precondition`, while some
151+/// stores report the same create conflict as `AlreadyExists`. Both are a
152+/// clean lost race. Every other error remains ambiguous.
153+fn is_clean_cas_rejection(error: &Error) -> bool {
154+ matches!(
155+ error,
156+ Error::Precondition { .. } | Error::AlreadyExists { .. }
157+ )
158+}
159+
160+/// Split a `[s3://|gs://|az://]NAME[/PREFIX]` bucket spec into the
161+/// backend, the bucket name and a normalized key prefix: empty, or
162+/// slash-terminated. A spec without a scheme stays S3-compatible, and a
163+/// spec without a PREFIX keeps every key at the bucket root, so a fleet
164+/// provisioned before either existed never moves its objects.
165+///
166+/// On `az://` the NAME is the container, and the storage account comes
167+/// from `AZURE_STORAGE_ACCOUNT_NAME`. The second path segment is the key
168+/// prefix on all three schemes, so the account cannot live there without
169+/// making `az://` parse differently from the other two.
142170 fn split_spec(spec: &str) -> (StorageBackend, &str, String) {
143- let (backend, spec) = match spec.strip_prefix("gs://") {
144- Some(rest) => (StorageBackend::Gcs, rest),
145- None => (StorageBackend::S3, spec.trim_start_matches("s3://")),
171+ let (backend, spec) = match (spec.strip_prefix("gs://"), spec.strip_prefix("az://")) {
172+ (Some(rest), _) => (StorageBackend::Gcs, rest),
173+ (_, Some(rest)) => (StorageBackend::Azure, rest),
174+ _ => (StorageBackend::S3, spec.trim_start_matches("s3://")),
146175 };
147176 let (name, prefix) = spec.split_once('/').unwrap_or((spec, ""));
148177 let parts = prefix.split('/').filter(|part| !part.is_empty());
@@ -154,8 +183,26 @@
154183 }
155184
156185 impl Bucket {
157- /// `bucket` is `[s3://|gs://]NAME[/PREFIX]`. With a PREFIX every key
158- /// this client reads or writes lives under `PREFIX/`, so several
186+ /// Builds a bucket over injected ordinary and conditional-write stores.
187+ #[cfg(all(test, celld_internal_tests))]
188+ pub(crate) fn with_stores(
189+ store: Arc<dyn ObjectStore>,
190+ cas_store: Arc<dyn ObjectStore>,
191+ backend: StorageBackend,
192+ name: String,
193+ prefix: String,
194+ ) -> Self {
195+ Self {
196+ store,
197+ cas_store,
198+ backend,
199+ name,
200+ prefix,
201+ }
202+ }
203+
204+ /// `bucket` is `[s3://|gs://|az://]NAME[/PREFIX]`. With a PREFIX every
205+ /// key this client reads or writes lives under `PREFIX/`, so several
159206 /// fleets can share one bucket without colliding.
160207 ///
161208 /// A `gs://` bucket authenticates through Google Application Default
@@ -163,6 +210,11 @@
163210 /// takes no S3 endpoint, static credentials, or region — the bucket
164211 /// carries its own location.
165212 ///
213+ /// An `az://` bucket names an Azure Blob Storage container, takes its
214+ /// account from `AZURE_STORAGE_ACCOUNT_NAME`, and authenticates with a
215+ /// storage account key, a managed identity, or a workload identity. It
216+ /// takes no S3 endpoint, static credentials, or region either.
217+ ///
166218 /// `app` labels this client's traffic in the User-Agent (the aws
167219 /// AppName format, `app/<name>`), keeping e.g. the lease safety lane
168220 /// observable in black-box storage traces.
@@ -173,27 +225,32 @@
173225 credentials: Option<StaticCredentials>,
174226 app: Option<&str>,
175227 ) -> anyhow::Result<Bucket> {
176- Self::open_with_gcs_builder(
228+ Self::open_with_sources(
177229 bucket,
178230 endpoint,
179231 region,
180232 credentials,
181233 app,
182- GoogleCloudStorageBuilder::from_env(),
234+ CloudSources::from_process(),
183235 )
184236 }
185237
186- /// The body of [`Self::open`], taking the base GCS builder instead of
187- /// deriving it from the `GOOGLE_*` environment. A caller that passes
188- /// an explicit builder is independent of that environment.
189- fn open_with_gcs_builder(
238+ /// The body of [`Self::open`], taking the cloud configuration instead
239+ /// of deriving it from the `GOOGLE_*` and `AZURE_*` environments. A
240+ /// caller that passes explicit sources is independent of that
241+ /// environment.
242+ fn open_with_sources(
190243 bucket: &str,
191244 endpoint: Option<&str>,
192245 region: &str,
193246 credentials: Option<StaticCredentials>,
194247 app: Option<&str>,
195- gcs_builder: GoogleCloudStorageBuilder,
248+ sources: CloudSources,
196249 ) -> anyhow::Result<Bucket> {
250+ let CloudSources {
251+ gcs: gcs_builder,
252+ azure: azure_env,
253+ } = sources;
197254 let (backend, bucket, prefix) = split_spec(bucket);
198255 // The prefix is spliced into keys as plain text and stripped off
199256 // listed keys the same way. A character `object_store` would
@@ -286,6 +343,33 @@
286343 Arc::new(cas_builder.build().context("build gcs cas client")?),
287344 )
288345 }
346+ StorageBackend::Azure => {
347+ // The etag dialect again — Put Blob applies If-None-Match
348+ // and If-Match — but a different client and different
349+ // credentials. So an S3 endpoint or S3 static credentials
350+ // with az:// is a configuration error, exactly as it is
351+ // with gs://, and not something to quietly reinterpret.
352+ if endpoint.is_some() {
353+ anyhow::bail!(
354+ "an az:// bucket takes no S3 endpoint; unset --endpoint / S3_ENDPOINT"
355+ );
356+ }
357+ if credentials.is_some() {
358+ anyhow::bail!(
359+ "an az:// bucket cannot use S3 static credentials; it authenticates \
360+ with an Azure storage account key, a managed identity, or a \
361+ workload identity"
362+ );
363+ }
364+ let builder = azure_builder_for(&azure_env, bucket)?
365+ .with_retry(retry)
366+ .with_client_options(options);
367+ let cas_builder = builder.clone().with_retry(cas_retry);
368+ (
369+ Arc::new(builder.build().context("build azure client")?),
370+ Arc::new(cas_builder.build().context("build azure cas client")?),
371+ )
372+ }
289373 };
290374 Ok(Bucket {
291375 store,
@@ -296,7 +380,7 @@
296380 })
297381 }
298382
299- /// The bucket's URL scheme, `s3` or `gs`, for operator-facing
383+ /// The bucket's URL scheme, `s3`, `gs` or `az`, for operator-facing
300384 /// messages.
301385 pub fn scheme(&self) -> &'static str {
302386 self.backend.scheme()
@@ -426,8 +510,9 @@
426510 }
427511
428512 /// Conditional write. `token: None` requires the key to be absent;
429- /// `Some` requires the current CAS token — the etag on S3 (If-Match),
430- /// the generation on GCS (x-goog-if-generation-match).
513+ /// `Some` requires the current CAS token — the etag on S3 and on
514+ /// Azure Blob Storage (If-Match), the generation on GCS
515+ /// (x-goog-if-generation-match).
431516 /// `Ok(Some(new_token))` applied, `Ok(None)` cleanly rejected; any
432517 /// other failure is ambiguous and stays an error.
433518 pub async fn put_cas(
@@ -441,6 +526,15 @@
441526 None => PutMode::Create,
442527 Some(token) => PutMode::Update(self.backend.update(token)),
443528 };
529+ #[cfg(all(test, celld_internal_tests))]
530+ let mode = if token.is_none()
531+ && crate::asyncrt::sabotage_active(
532+ crate::host_services::EngineSabotage::FreshCreateOverwrites,
533+ ) {
534+ PutMode::Overwrite
535+ } else {
536+ mode
537+ };
444538 match self
445539 .cas_store
446540 .put_opts(
@@ -466,7 +560,7 @@
466560 })?;
467561 Ok(Some(token))
468562 }
469- Err(Error::Precondition { .. } | Error::AlreadyExists { .. }) => Ok(None),
563+ Err(error) if is_clean_cas_rejection(&error) => Ok(None),
470564 Err(error) => Err(anyhow!(error).context(format!(
471565 "conditional write {}://{}/{key} may have committed",
472566 self.scheme(),
@@ -488,6 +582,34 @@
488582 }
489583 }
490584
585+ /// Batched delete: the S3-family backends fold this into DeleteObjects
586+ /// requests (up to 1,000 keys per class A operation) — the lab priced
587+ /// bundle GC's one-key-at-a-time deletes at 9k operations an hour.
588+ /// Returns the keys that are now gone; an absent key counts as gone,
589+ /// and a key that fails stays listed for the next pass.
590+ pub async fn delete_many(&self, keys: &[String]) -> Vec<String> {
591+ let locations = futures_util::stream::iter(
592+ keys.iter()
593+ .map(|key| Ok(Path::from(self.key(key).as_str())))
594+ .collect::<Vec<_>>(),
595+ )
596+ .boxed();
597+ let mut gone = Vec::with_capacity(keys.len());
598+ let mut results = self.store.delete_stream(locations);
599+ while let Some(result) = results.next().await {
600+ match result {
601+ Ok(path) => gone.push(self.unkey(path.as_ref()).to_string()),
602+ Err(Error::NotFound { path, .. }) => {
603+ gone.push(self.unkey(&path).to_string());
604+ }
605+ Err(error) => {
606+ tracing::warn!(%error, "batched delete left a key for the next pass");
607+ }
608+ }
609+ }
610+ gone
611+ }
612+
491613 /// Every object under `prefix/`; the client paginates internally.
492614 /// Listed keys come back the way the caller wrote them, because the
493615 /// caller parses them and knows nothing of the fleet's prefix.
@@ -566,10 +688,7 @@
566688 /// fault, a rejected credential — and a retry can clear it, so a
567689 /// caller that must not fail on a transient blip keeps serving.
568690 pub(crate) async fn probe_cas_steps(&self) -> anyhow::Result<CasVerdict> {
569- let nanos = std::time::SystemTime::now()
570- .duration_since(std::time::UNIX_EPOCH)
571- .map(|since| since.as_nanos())
572- .unwrap_or_default();
691+ let nanos = crate::asyncrt::wall_ms().max(0) as u128 * 1_000_000;
573692 // Unique per probe, so several nodes probing at once touch
574693 // disjoint keys and no probe reads another one's object as the
575694 // store misbehaving — a collision surfaces as a false `Violation`,
@@ -578,8 +697,8 @@
578697 // leaves `nanos` at zero.
579698 let key = format!(
580699 "probe/cas-{nanos}-{}-{:016x}",
581- std::process::id(),
582- rand::random::<u64>()
700+ crate::asyncrt::process_tag(),
701+ rand::RngCore::next_u64(&mut crate::asyncrt::rng("cas_probe"))
583702 );
584703 let verdict = self.cas_contract(&key).await;
585704 // The object is debris on every path, so retire it before the
@@ -684,15 +803,14 @@
684803 /// The replica-lane store for a `gs://` fleet bucket: its own transport
685804 /// and connection pool, authenticated like [`Bucket::open`]'s gs:// path
686805 /// (OAuth via Application Default Credentials or the `GOOGLE_*` env),
687-/// with the same default retry policy the S3 replica lane gets from its
688-/// litestream-ported config in `ltx_repl`. Replica writes are plain puts,
689-/// so retries stay on.
806+/// with the same bounded retry policy the S3 replica lane uses. Replica
807+/// writes are plain puts, so retries stay on.
690808 pub(crate) fn gcs_replica_store(bucket: &str) -> anyhow::Result<Arc<dyn ObjectStore>> {
691809 gcs_replica_store_with_builder(GoogleCloudStorageBuilder::from_env(), bucket)
692810 }
693811
694812 /// The body of [`gcs_replica_store`], taking the base builder for the same
695-/// reason [`Bucket::open_with_gcs_builder`] does.
813+/// reason [`Bucket::open_with_sources`] does.
696814 fn gcs_replica_store_with_builder(
697815 builder: GoogleCloudStorageBuilder,
698816 bucket: &str,
@@ -700,11 +818,268 @@
700818 Ok(Arc::new(
701819 builder
702820 .with_bucket_name(bucket)
821+ .with_retry(celld_ltx::client::object_store::replica_retry_config())
703822 .build()
704823 .context("build gcs replica store")?,
705824 ))
706825 }
707826
827+/// The replica-lane store for an `az://` fleet bucket: its own transport
828+/// and connection pool, authenticated like [`Bucket::open`]'s az:// path,
829+/// with the same bounded retry policy the S3 replica lane uses. Replica
830+/// writes are plain puts, so retries stay on.
831+pub(crate) fn azure_replica_store(container: &str) -> anyhow::Result<Arc<dyn ObjectStore>> {
832+ azure_replica_store_with_env(&AzureEnv::from_process(), container)
833+}
834+
835+/// The body of [`azure_replica_store`], taking the environment for the
836+/// same reason [`Bucket::open_with_sources`] does.
837+fn azure_replica_store_with_env(
838+ env: &AzureEnv,
839+ container: &str,
840+) -> anyhow::Result<Arc<dyn ObjectStore>> {
841+ Ok(Arc::new(
842+ azure_builder_for(env, container)?
843+ .with_retry(celld_ltx::client::object_store::replica_retry_config())
844+ .build()
845+ .context("build azure replica store")?,
846+ ))
847+}
848+
849+/// The `AZURE_*` variables an `az://` bucket can inspect. celld captures
850+/// them instead of letting `MicrosoftAzureBuilder::from_env` read the
851+/// process environment, because the fleet client must decide which
852+/// recognized settings it honors, and a test must be able to supply a
853+/// set of its own. Names that `AzureConfigKey` does not parse are inert
854+/// and stay ignored, as they are in `from_env`.
855+#[derive(Clone, Default)]
856+pub(crate) struct AzureEnv {
857+ variables: Vec<(String, String)>,
858+}
859+
860+impl AzureEnv {
861+ /// Every `AZURE_*` variable in the process environment.
862+ fn from_process() -> AzureEnv {
863+ AzureEnv::from_pairs(std::env::vars().filter(|(name, _)| name.starts_with("AZURE_")))
864+ }
865+
866+ fn from_pairs<K, V>(pairs: impl IntoIterator<Item = (K, V)>) -> AzureEnv
867+ where
868+ K: Into<String>,
869+ V: Into<String>,
870+ {
871+ AzureEnv {
872+ variables: pairs
873+ .into_iter()
874+ .map(|(name, value)| (name.into(), value.into()))
875+ .filter(|(_, value)| !value.is_empty())
876+ .collect(),
877+ }
878+ }
879+}
880+
881+/// The cloud configuration [`Bucket::open`] derives from the process
882+/// environment: the GCS builder, and the `AZURE_*` variables. Bundled so
883+/// the seam that makes construction environment-independent stays one
884+/// parameter as backends are added.
885+pub(crate) struct CloudSources {
886+ gcs: GoogleCloudStorageBuilder,
887+ azure: AzureEnv,
888+}
889+
890+impl CloudSources {
891+ fn from_process() -> CloudSources {
892+ CloudSources {
893+ gcs: GoogleCloudStorageBuilder::from_env(),
894+ azure: AzureEnv::from_process(),
895+ }
896+ }
897+}
898+
899+/// Is this a setting an `az://` bucket accepts? celld supports three
900+/// credential families — a storage account key, a managed identity, and
901+/// a workload identity — on the public Azure cloud, and no other
902+/// recognized Azure setting.
903+///
904+/// This is an allowlist, and the wildcard arm is the point of it.
905+/// `AzureConfigKey` is `#[non_exhaustive]`, so a key that a later
906+/// `object_store` adds falls to `false` and refuses, instead of reaching
907+/// the client unexamined. A denylist gave the opposite default and let
908+/// three settings through: `AZURE_USE_FABRIC_ENDPOINT` retargets the
909+/// client at OneLake, the four `AZURE_FABRIC_*` variables form a fourth
910+/// credential that wins ahead of the account key, and
911+/// `AZURE_SKIP_SIGNATURE` makes every request anonymous.
912+fn accepts_azure_config_key(key: &AzureConfigKey) -> bool {
913+ matches!(
914+ key,
915+ // The account, and the account-key credential.
916+ AzureConfigKey::AccountName
917+ | AzureConfigKey::AccessKey
918+ // A managed identity: the defaults reach IMDS, and any one
919+ // of these three selects a user-assigned identity.
920+ | AzureConfigKey::ClientId
921+ | AzureConfigKey::ObjectId
922+ | AzureConfigKey::MsiResourceId
923+ // A workload identity, with ClientId above.
924+ | AzureConfigKey::AuthorityId
925+ | AzureConfigKey::AuthorityHost
926+ | AzureConfigKey::FederatedTokenFile
927+ // Azurite, handled separately below.
928+ | AzureConfigKey::UseEmulator
929+ )
930+}
931+
932+/// Build the Azure client configuration for `container` from the accepted
933+/// part of `env`, and refuse every other recognized Azure setting.
934+///
935+/// `object_store`'s builder accepts every source the Azure chain offers.
936+/// celld accepts three, which mirrors the deliberate narrowness of the S3
937+/// path, where celld reads the `AWS_*` environment but no `~/.aws`
938+/// profile and no SSO login. Both the fleet client and the replica store
939+/// come through here, so they cannot narrow differently.
940+///
941+/// A refused variable fails at startup with a message that names it. A
942+/// silently ignored credential surfaces much later as a permission
943+/// error, and it points at the container instead of the configuration.
944+fn azure_builder_for(env: &AzureEnv, container: &str) -> anyhow::Result<MicrosoftAzureBuilder> {
945+ let mut parsed: Vec<(AzureConfigKey, &str, &str)> = Vec::new();
946+ let mut seen: Vec<(AzureConfigKey, &str)> = Vec::new();
947+ for (name, value) in &env.variables {
948+ // `from_env` parses each AZURE_* name into a config key and drops
949+ // the ones that do not parse, so a name this parse rejects is a
950+ // name object_store would have ignored anyway.
951+ let Ok(key) = name.to_ascii_lowercase().parse::<AzureConfigKey>() else {
952+ continue;
953+ };
954+ if !accepts_azure_config_key(&key) {
955+ anyhow::bail!(
956+ "an az:// bucket does not accept {name}; celld authenticates with an Azure \
957+ storage account key, a managed identity, or a workload identity on the \
958+ public Azure cloud, and it refuses every other Azure setting"
959+ );
960+ }
961+ let value = if key == AzureConfigKey::AuthorityHost {
962+ let public = authority_hosts::AZURE_PUBLIC_CLOUD;
963+ if value != public && value != &format!("{public}/") {
964+ anyhow::bail!(
965+ "an az:// bucket accepts {name} only for the public Azure authority \
966+ {public}; sovereign and custom authority hosts are not supported"
967+ );
968+ }
969+ // The webhook value has a trailing slash, but object_store
970+ // inserts its own separator. Pass one canonical spelling.
971+ public
972+ } else {
973+ value.as_str()
974+ };
975+ if let Some((_, first)) = seen.iter().find(|(candidate, _)| *candidate == key) {
976+ anyhow::bail!(
977+ "an az:// bucket does not accept both {first} and {name}; they are aliases for \
978+ the same Azure setting"
979+ );
980+ }
981+ seen.push((key, name));
982+ parsed.push((key, name.as_str(), value));
983+ }
984+
985+ let has = |wanted| seen.iter().any(|(key, _)| *key == wanted);
986+ let account_key = has(AzureConfigKey::AccessKey);
987+ let client_id = has(AzureConfigKey::ClientId);
988+ let workload_specific = has(AzureConfigKey::AuthorityId)
989+ || has(AzureConfigKey::AuthorityHost)
990+ || has(AzureConfigKey::FederatedTokenFile);
991+ let managed_specific = has(AzureConfigKey::ObjectId) || has(AzureConfigKey::MsiResourceId);
992+ let managed_selectors: Vec<&str> = seen
993+ .iter()
994+ .filter(|(key, _)| {
995+ matches!(
996+ key,
997+ AzureConfigKey::ClientId | AzureConfigKey::ObjectId | AzureConfigKey::MsiResourceId
998+ )
999+ })
1000+ .map(|(_, name)| *name)
1001+ .collect();
1002+
1003+ if (account_key && (client_id || workload_specific || managed_specific))
1004+ || (workload_specific && managed_specific)
1005+ {
1006+ anyhow::bail!(
1007+ "an az:// bucket does not accept mixed Azure credential families; select exactly \
1008+ one storage account key, workload identity, or managed identity"
1009+ );
1010+ }
1011+ // Two selectors inside the managed-identity family are not an alias
1012+ // pair, so the duplicate check above does not see them. object_store
1013+ // resolves them by precedence instead — client_id, then object_id,
1014+ // then msi_res_id (`azure/credential.rs`) — so the node authenticates
1015+ // as an identity the operator did not choose, and the mistake
1016+ // surfaces as a permission error against the container. That is the
1017+ // late, misdirected failure this whole seam exists to prevent.
1018+ if !workload_specific && managed_selectors.len() > 1 {
1019+ anyhow::bail!(
1020+ "an az:// bucket accepts one managed-identity selector, but {} name different \
1021+ identities; set exactly one of AZURE_CLIENT_ID, AZURE_OBJECT_ID, or \
1022+ AZURE_MSI_RESOURCE_ID",
1023+ managed_selectors.join(" and ")
1024+ );
1025+ }
1026+ if workload_specific
1027+ && !(client_id
1028+ && has(AzureConfigKey::AuthorityId)
1029+ && has(AzureConfigKey::FederatedTokenFile))
1030+ {
1031+ anyhow::bail!(
1032+ "an Azure workload identity requires AZURE_CLIENT_ID, AZURE_TENANT_ID, and \
1033+ AZURE_FEDERATED_TOKEN_FILE"
1034+ );
1035+ }
1036+
1037+ let mut builder = MicrosoftAzureBuilder::new();
1038+ let mut account = false;
1039+ let mut emulator = None;
1040+ for (key, name, value) in parsed {
1041+ match key {
1042+ // Never handed on as a string. object_store would parse it
1043+ // itself, and its parse accepts y/n as well as true/false, so
1044+ // a second parse here could disagree with it — and a
1045+ // disagreement over this key means celld validates a
1046+ // production configuration while the client talks to a local
1047+ // Azurite. Two such nodes each own every cell. The name
1048+ // travels with the value so the refusal below names what the
1049+ // operator set. Today one AZURE_ spelling parses to this key,
1050+ // so the two can not differ; carrying the name keeps that
1051+ // true if object_store adds an alias.
1052+ AzureConfigKey::UseEmulator => emulator = Some((name, value)),
1053+ AzureConfigKey::AccountName => {
1054+ account = true;
1055+ builder = builder.with_config(key, value);
1056+ }
1057+ _ => builder = builder.with_config(key, value),
1058+ }
1059+ }
1060+ // Azurite is the one endpoint override celld allows, and it arrives
1061+ // as a parsed bool, so object_store re-parses nothing. Its
1062+ // conditional-write behavior is not qualified for a production fleet.
1063+ if let Some((name, value)) = emulator {
1064+ let on = match value.to_ascii_lowercase().as_str() {
1065+ "true" | "1" => true,
1066+ "false" | "0" => false,
1067+ other => anyhow::bail!("{name} accepts true or false, not {other:?}"),
1068+ };
1069+ builder = builder.with_use_emulator(on);
1070+ if on {
1071+ return Ok(builder.with_container_name(container));
1072+ }
1073+ }
1074+ if !account {
1075+ anyhow::bail!(
1076+ "an az:// bucket names a container, so the storage account must come from \
1077+ AZURE_STORAGE_ACCOUNT_NAME"
1078+ );
1079+ }
1080+ Ok(builder.with_container_name(container))
1081+}
1082+
7081083 /// Was this a 401/403 — the credential itself rejected? Used by the managed
7091084 /// path to report a revoked credential rather than a flaky bucket.
7101085 pub fn is_unauthorized(error: &anyhow::Error) -> bool {
@@ -722,50 +1097,6 @@
7221097 })
7231098 }
7241099
725-#[cfg(test)]
726-mod live_cas {
727- use super::{Bucket, StaticCredentials};
728-
729- // Live CAS contract against a real bucket (R2 or GCS). Gated on
730- // CELLD_CAS_LIVE=1 so it never runs in CI; a mock cannot answer whether
731- // object_store maps the provider's precondition failures to Ok(None)
732- // (the fencing contract) rather than Err. Run:
733- // CELLD_CAS_LIVE=1 CELLD_CAS_BUCKET=<b> CELLD_CAS_ENDPOINT=<ep> AWS_*=... \
734- // cargo test -p celld put_cas_contract -- --nocapture
735- // or against GCS (Application Default Credentials, no endpoint):
736- // CELLD_CAS_LIVE=1 CELLD_CAS_BUCKET=gs://<b> \
737- // cargo test -p celld put_cas_contract -- --nocapture
738- #[tokio::test]
739- async fn put_cas_contract_against_real_bucket() {
740- if std::env::var("CELLD_CAS_LIVE").as_deref() != Ok("1") {
741- return;
742- }
743- let name = std::env::var("CELLD_CAS_BUCKET").expect("CELLD_CAS_BUCKET");
744- let endpoint = std::env::var("CELLD_CAS_ENDPOINT").ok();
745- let region = std::env::var("AWS_REGION").unwrap_or_else(|_| "auto".into());
746- let creds = std::env::var("AWS_ACCESS_KEY_ID")
747- .ok()
748- .map(|access_key_id| StaticCredentials {
749- access_key_id,
750- secret_access_key: std::env::var("AWS_SECRET_ACCESS_KEY")
751- .expect("AWS_SECRET_ACCESS_KEY"),
752- session_token: std::env::var("AWS_SESSION_TOKEN").ok(),
753- });
754- let bucket = Bucket::open(&name, endpoint.as_deref(), &region, creds, Some("cas-test"))
755- .expect("open bucket");
756-
757- // The four steps live in `Bucket::probe_cas`, which `celld
758- // diagnose` and node startup run against an operator's bucket.
759- // This test points the same code at a real provider, which is the
760- // one question a mock cannot answer.
761- bucket
762- .probe_cas()
763- .await
764- .expect("the store must keep the conditional-write contract");
765- eprintln!("CAS verified on {name}: create / reject-create / update / reject-stale");
766- }
767-}
768-
7691100 #[cfg(all(test, celld_internal_tests))]
7701101 mod conformance_bucket_tests {
7711102 include!(env!("CELLD_CONFORMANCE_BUCKET_TESTS"));
modifiedcrates/celld/control_plane.rs+54−51View file
@@ -1,5 +1,12 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3+// Managed control-plane sessions do not execute in the engine World.
4+#![allow(
5+ clippy::disallowed_macros,
6+ clippy::disallowed_methods,
7+ clippy::disallowed_types
8+)]
9+
310 use crate::bucket::Bucket;
411 use crate::protocol::{asset_blob_key, AssetIndex, DeployPointer, Manifest};
512 use anyhow::{anyhow, Context};
@@ -983,11 +990,6 @@
983990 if let Some(observation) = lease_shadow {
984991 message["lease_shadow"] = observation;
985992 }
986- if !snapshot.lazy_lease_shadow.decisions.is_empty()
987- || snapshot.lazy_lease_shadow.dropped > 0
988- {
989- message["lazy_lease_shadow"] = lazy_lease_shadow_json(&snapshot.lazy_lease_shadow);
990- }
991993 Ok(message.to_string())
992994 },
993995 move |text| async move {
@@ -1034,7 +1036,7 @@
10341036 /// loses the header. The next read then treats a payload byte as a frame header
10351037 /// and the stream never realigns. An earlier version of this session read the
10361038 /// socket in the same `tokio::select!` as the heartbeat timer, so every tick
1037-/// dropped a read in progress; `tests/p0/runtime/presence_cancel.rs` fails
1039+/// dropped a read in progress; a test that cancels a read mid-payload fails
10381040 /// against that shape.
10391041 ///
10401042 /// One async block therefore owns each direction, and the socket is split so
@@ -1133,49 +1135,6 @@
11331135 }
11341136 }
11351137
1136-fn lazy_lease_shadow_json(batch: &celld_logic::LeaseLifecycleShadowBatch) -> serde_json::Value {
1137- let decisions = batch
1138- .decisions
1139- .iter()
1140- .map(|decision| {
1141- let snapshot = &decision.snapshot;
1142- let mode = match snapshot.mode {
1143- celld_logic::NodeLeaseMode::Continuous => "continuous",
1144- celld_logic::NodeLeaseMode::Shadow => "shadow",
1145- celld_logic::NodeLeaseMode::Lazy => "lazy",
1146- };
1147- let authority_action = match decision.expected.authority_action {
1148- celld_logic::NodeLeaseAuthorityAction::Hold => "hold",
1149- celld_logic::NodeLeaseAuthorityAction::Renew => "renew",
1150- };
1151- serde_json::json!({
1152- "sequence": decision.sequence,
1153- "observed_at_ms": decision.observed_at_ms,
1154- "snapshot": {
1155- "mode": mode,
1156- "active_cells": snapshot.active_cells,
1157- "serving_cells": snapshot.serving_cells,
1158- "idle_ms": snapshot.idle_ms,
1159- "linger_ms": snapshot.linger_ms,
1160- "lease_active": snapshot.lease_active,
1161- "elapsed_since_ok_ms": snapshot.elapsed_since_ok_ms,
1162- "elapsed_since_renew_ms": snapshot.elapsed_since_renew_ms,
1163- "ttl_ms": snapshot.ttl_ms,
1164- "shadow_release_reported": snapshot.shadow_release_reported,
1165- },
1166- "expected": {
1167- "shadow_release": decision.expected.shadow_release,
1168- "authority_action": authority_action,
1169- },
1170- })
1171- })
1172- .collect::<Vec<_>>();
1173- serde_json::json!({
1174- "dropped": batch.dropped,
1175- "decisions": decisions,
1176- })
1177-}
1178-
11791138 /// Independently observe bucket truth for rollout comparison. This is an
11801139 /// off-by-default management diagnostic: it never feeds the lease record back
11811140 /// into the core or changes whether the node serves.
@@ -1206,6 +1165,16 @@
12061165 }
12071166 }
12081167
1168+/// How long a read-only exploration can spend in object storage.
1169+///
1170+/// A person waits for this answer in the Managed Control Plane, and the
1171+/// presence read loop runs the handler inline, so an exploration that never
1172+/// finishes holds every later presence message behind it. The bounded replica
1173+/// retry policy already keeps an ordinary failure well under this, therefore
1174+/// reaching this deadline means the store stopped answering rather than
1175+/// answering with an error.
1176+const EXPLORER_STORAGE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5);
1177+
12091178 async fn handle_explorer_request(
12101179 message: &serde_json::Value,
12111180 runtime: &PresenceRuntime,
@@ -1231,7 +1200,23 @@
12311200 }
12321201 _ => return explorer_error(request_id, "invalid_request"),
12331202 };
1234- list_durable_cells(&runtime.s3, cursor).await
1203+ match tokio::time::timeout(
1204+ EXPLORER_STORAGE_DEADLINE,
1205+ list_durable_cells(&runtime.s3, cursor),
1206+ )
1207+ .await
1208+ {
1209+ Ok(result) => result,
1210+ Err(_) => {
1211+ warn!(
1212+ event = "control_plane_explorer_deadline",
1213+ request_id,
1214+ operation = "list_cells",
1215+ "read-only exploration passed its storage deadline"
1216+ );
1217+ return explorer_error(request_id, "inspection_timed_out");
1218+ }
1219+ }
12351220 }
12361221 Some("inspect_cell") => {
12371222 let Some(cell) = message
@@ -1279,7 +1264,25 @@
12791264 Err(error) => Err(anyhow!("active inspection task failed: {error}")),
12801265 }
12811266 } else {
1282- match replication.restore_snapshot(cell).await {
1267+ let restored = match tokio::time::timeout(
1268+ EXPLORER_STORAGE_DEADLINE,
1269+ replication.restore_snapshot(cell),
1270+ )
1271+ .await
1272+ {
1273+ Ok(result) => result,
1274+ Err(_) => {
1275+ warn!(
1276+ event = "control_plane_explorer_deadline",
1277+ request_id,
1278+ operation = "inspect_cell",
1279+ cell,
1280+ "read-only exploration passed its storage deadline"
1281+ );
1282+ return explorer_error(request_id, "inspection_timed_out");
1283+ }
1284+ };
1285+ match restored {
12831286 Ok(Some(snapshot)) => {
12841287 let cell = cell.to_string();
12851288 match tokio::task::spawn_blocking(move || {
addedcrates/celld/d1_cli.rs+657−0View file
@@ -1,0 +1,657 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+// The D1 CLI reads operator input and migration files outside node storage.
4+#![allow(clippy::disallowed_methods)]
5+
6+//! `celld d1` — run SQL and migrations against a deployed D1 database.
7+//!
8+//! A D1 database is a cell, so it is only reachable through the node that owns
9+//! it. This command finds the fleet the way `celld diagnose` does — it walks
10+//! the node leases in the bucket, and it reads the same shared secret — and
11+//! then sends the SQL to a live node's `/__d1/` route, which forwards to the
12+//! owner. The CLI therefore holds no ownership logic and no SQLite: it reaches
13+//! the database over the dispatch a Worker's `env.DB` reaches it over.
14+//!
15+//! The route is authenticated. A D1 database holds application data and
16+//! answers arbitrary SQL, and its scope is an HMAC over the database identity
17+//! rather than a secret, so the unauthenticated `/do/` route
18+//! refuses a D1 scope and sends the caller here.
19+
20+use std::path::PathBuf;
21+use std::time::Duration;
22+
23+use anyhow::{anyhow, bail, Context};
24+use serde_json::Value;
25+
26+use crate::bucket::Bucket;
27+
28+pub async fn run(arguments: Vec<String>) -> anyhow::Result<()> {
29+ let Some(command) = Command::parse(arguments)? else {
30+ print_help();
31+ return Ok(());
32+ };
33+ let project = crate::deploy::read_d1_project(command.project.clone())?;
34+ // The declaration, not just the name: `migrations_dir` belongs to the
35+ // binding, so the directory has to come from the database the command
36+ // names or one database's migrations reach another.
37+ let declaration = project
38+ .databases
39+ .iter()
40+ .find(|database| database.database_name == command.database)
41+ .ok_or_else(|| {
42+ anyhow!(
43+ "the project declares no D1 database named {:?}; it declares {}",
44+ command.database,
45+ if project.databases.is_empty() {
46+ "none".to_string()
47+ } else {
48+ project
49+ .databases
50+ .iter()
51+ .map(|database| format!("{:?}", database.database_name))
52+ .collect::<Vec<_>>()
53+ .join(", ")
54+ }
55+ )
56+ })?;
57+ let scope = crate::js::d1_cell_scope(&declaration.database_identity);
58+ let database = Reachable::open(&command, scope).await?;
59+
60+ match command.action {
61+ Action::Execute { command: sql, file } => {
62+ let source = match (sql, file) {
63+ (Some(sql), _) => sql,
64+ (None, Some(file)) => std::fs::read_to_string(&file)
65+ .with_context(|| format!("read {}", file.display()))?,
66+ (None, None) => unreachable!("parse refuses neither --command nor --file"),
67+ };
68+ let result = database.exec(&source).await?;
69+ // The rows, not only the count: an operator running a SELECT is
70+ // asking for its result, and `wrangler d1 execute` prints it.
71+ for set in result
72+ .get("results")
73+ .and_then(Value::as_array)
74+ .into_iter()
75+ .flatten()
76+ {
77+ let columns: Vec<&str> = set
78+ .get("columns")
79+ .and_then(Value::as_array)
80+ .into_iter()
81+ .flatten()
82+ .filter_map(Value::as_str)
83+ .collect();
84+ let shaped: Vec<Value> = set
85+ .get("rows")
86+ .and_then(Value::as_array)
87+ .into_iter()
88+ .flatten()
89+ .filter_map(Value::as_array)
90+ .map(|row| {
91+ Value::Object(
92+ columns
93+ .iter()
94+ .zip(row)
95+ .map(|(column, value)| (column.to_string(), value.clone()))
96+ .collect(),
97+ )
98+ })
99+ .collect();
100+ println!(
101+ "{}",
102+ serde_json::to_string_pretty(&Value::Array(shaped))
103+ .context("encode the result rows")?
104+ );
105+ }
106+ println!(
107+ "Executed {} statement(s) in {:.2} sec",
108+ result
109+ .get("count")
110+ .and_then(Value::as_u64)
111+ .unwrap_or_default(),
112+ result
113+ .get("duration")
114+ .and_then(Value::as_f64)
115+ .unwrap_or_default()
116+ / 1000.0
117+ );
118+ }
119+ Action::MigrationsList => {
120+ let pending = database.pending(declaration).await?;
121+ if pending.is_empty() {
122+ println!("No migrations to apply.");
123+ return Ok(());
124+ }
125+ println!("Migrations to be applied:");
126+ for migration in &pending {
127+ println!(" {}", migration.name);
128+ }
129+ }
130+ Action::MigrationsApply => {
131+ let pending = database.pending(declaration).await?;
132+ if pending.is_empty() {
133+ println!("No migrations to apply.");
134+ return Ok(());
135+ }
136+ for migration in pending {
137+ database
138+ .apply(&migration, &declaration.migrations_table)
139+ .await?;
140+ println!("Applied {}", migration.name);
141+ }
142+ }
143+ }
144+ Ok(())
145+}
146+
147+struct Migration {
148+ name: String,
149+ sql: String,
150+}
151+
152+/// One entrance into the fleet: a node's address and the identity a request
153+/// to it must be signed for.
154+struct Entrance {
155+ node: String,
156+ url: String,
157+ path: String,
158+}
159+
160+/// A database resolved to the nodes that can carry SQL to it.
161+struct Reachable {
162+ http: reqwest::Client,
163+ /// The fleet's shared peer secret, read from the bucket. `/__d1/` refuses
164+ /// an unsigned request, because a D1 database holds application data and
165+ /// answers arbitrary SQL.
166+ auth: crate::peer_auth::PeerAuth,
167+ /// Every node with a live lease. Any one of them forwards to the owner, so
168+ /// the list is a set of equal entrances and not a route: it stays correct
169+ /// even when the cell moves between calls.
170+ entrances: Vec<Entrance>,
171+}
172+
173+impl Reachable {
174+ async fn open(command: &Command, scope: String) -> anyhow::Result<Self> {
175+ let bucket = crate::fleet::bucket_client(
176+ &command.bucket,
177+ command.endpoint.as_deref(),
178+ &command.region,
179+ )?;
180+ let nodes = live_nodes(&bucket, command.unsafe_public_advertise).await?;
181+ // The same secret and the same source shape `celld diagnose` uses.
182+ let auth =
183+ crate::peer_auth::PeerAuth::new(crate::peer_auth::load_existing(&bucket).await?, "d1")?;
184+ let http = reqwest::Client::builder()
185+ .connect_timeout(Duration::from_secs(5))
186+ // A migration on a large table is not a diagnostic ping, so this
187+ // budget is the handler budget's order rather than the probe's.
188+ .timeout(Duration::from_secs(120))
189+ .build()
190+ .context("build the D1 client")?;
191+ let path = format!("/__d1/{scope}");
192+ Ok(Self {
193+ http,
194+ auth,
195+ entrances: nodes
196+ .into_iter()
197+ .map(|(node, addr)| Entrance {
198+ node,
199+ url: format!("http://{addr}{path}"),
200+ path: path.clone(),
201+ })
202+ .collect(),
203+ })
204+ }
205+
206+ /// A lease outlives the node that wrote it, and a node that drains keeps
207+ /// its lease while it refuses work, so the first entrance in the list is
208+ /// not always usable. Move to the next one when a node cannot be reached
209+ /// or is draining, because in both cases the request provably did not run.
210+ /// Nothing else is retried: a timeout is not evidence that the work was
211+ /// refused, and re-sending a migration that in fact ran would apply it
212+ /// twice.
213+ async fn call(&self, body: Value) -> anyhow::Result<Value> {
214+ // Signed per entrance, because the signature binds the node it is
215+ // addressed to: a signature for one node is not replayable at another.
216+ let payload = serde_json::to_vec(&body).context("encode the request")?;
217+ let mut refused = Vec::new();
218+ for (index, entrance) in self.entrances.iter().enumerate() {
219+ let last = index + 1 == self.entrances.len();
220+ let url = &entrance.url;
221+ let request = self
222+ .auth
223+ .sign(
224+ self.http.post(url).body(payload.clone()),
225+ "POST",
226+ &entrance.path,
227+ &payload,
228+ &entrance.node,
229+ )
230+ .with_context(|| format!("sign the request to {}", entrance.node))?;
231+ let response = match request.send().await {
232+ Ok(response) => response,
233+ Err(error) if error.is_connect() && !last => {
234+ refused.push(format!("{url}: {error}"));
235+ continue;
236+ }
237+ Err(error) => {
238+ return Err(anyhow::Error::new(error)).with_context(|| {
239+ format!("reach the database at {url}{}", report(&refused))
240+ });
241+ }
242+ };
243+ let status = response.status();
244+ let text = response.text().await.context("read the database reply")?;
245+ if status == reqwest::StatusCode::SERVICE_UNAVAILABLE
246+ && text.contains("\"draining\"")
247+ && !last
248+ {
249+ refused.push(format!("{url}: the node is draining"));
250+ continue;
251+ }
252+ // The dispatcher refusing at the door is the doc comment's
253+ // criterion exactly: the request provably did not run, so the
254+ // next entrance is safe to try where a timeout would not be.
255+ if status == reqwest::StatusCode::SERVICE_UNAVAILABLE
256+ && text.contains("dispatcher unavailable")
257+ && !last
258+ {
259+ refused.push(format!("{url}: the node's dispatcher is unavailable"));
260+ continue;
261+ }
262+ let value: Value = serde_json::from_str(&text)
263+ .with_context(|| format!("decode the database reply ({status}): {text}"))?;
264+ if let Some(error) = value.get("error").and_then(Value::as_str) {
265+ bail!("{error}{}", report(&refused));
266+ }
267+ if !status.is_success() {
268+ bail!(
269+ "the database refused the request ({status}): {text}{}",
270+ report(&refused)
271+ );
272+ }
273+ return value.get("result").cloned().ok_or_else(|| {
274+ anyhow!(
275+ "the database reply carried no result: {text}{}",
276+ report(&refused)
277+ )
278+ });
279+ }
280+ bail!("no node in the fleet answered{}", report(&refused))
281+ }
282+
283+ async fn exec(&self, source: &str) -> anyhow::Result<Value> {
284+ // `rows: true` is the CLI's difference from the Worker binding's
285+ // exec(): the operator asked to see the result, not only the count.
286+ self.call(serde_json::json!({ "exec": { "sql": source, "rows": true } }))
287+ .await
288+ }
289+
290+ /// Rows for one statement, as `all()` would shape them.
291+ async fn query(&self, sql: &str) -> anyhow::Result<Vec<Vec<Value>>> {
292+ let result = self
293+ .call(serde_json::json!({ "statements": [{ "sql": sql, "params": [] }] }))
294+ .await?;
295+ let rows = result
296+ .get(0)
297+ .and_then(|first| first.get("rows"))
298+ .and_then(Value::as_array)
299+ .ok_or_else(|| anyhow!("the database reply carried no rows"))?;
300+ Ok(rows
301+ .iter()
302+ .filter_map(|row| row.as_array().cloned())
303+ .collect())
304+ }
305+
306+ /// Every migration file the database has not recorded, in wrangler's
307+ /// order. The bookkeeping table is the binding's `migrations_table`,
308+ /// validated at config read, so the name joined into this SQL is a plain
309+ /// identifier and nothing else.
310+ async fn pending(
311+ &self,
312+ declaration: &crate::deploy::D1Declaration,
313+ ) -> anyhow::Result<Vec<Migration>> {
314+ let on_disk = read_migrations(&declaration.migrations_dir)?;
315+ let table = &declaration.migrations_table;
316+ self.exec(&format!(
317+ "CREATE TABLE IF NOT EXISTS \"{table}\" (\
318+ id INTEGER PRIMARY KEY AUTOINCREMENT, \
319+ name TEXT UNIQUE, \
320+ applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP);"
321+ ))
322+ .await?;
323+ let applied = self
324+ .query(&format!("SELECT name FROM \"{table}\""))
325+ .await?
326+ .into_iter()
327+ .filter_map(|row| row.first().and_then(Value::as_str).map(str::to_string))
328+ .collect::<std::collections::BTreeSet<_>>();
329+ Ok(on_disk
330+ .into_iter()
331+ .filter(|migration| !applied.contains(&migration.name))
332+ .collect())
333+ }
334+
335+ /// The cell applies the file and records it in one transaction, so a
336+ /// migration that fails part-way rolls back whole and a re-run starts
337+ /// clean. The CLI sends the file and the name separately and joins no SQL:
338+ /// the name reaches the bookkeeping row as a bound parameter, and a file
339+ /// that ends in a comment or an unterminated statement is refused by the
340+ /// cell rather than repaired by a guess here.
341+ async fn apply(&self, migration: &Migration, table: &str) -> anyhow::Result<()> {
342+ self.call(serde_json::json!({
343+ "migrate": { "name": migration.name, "sql": migration.sql, "table": table },
344+ }))
345+ .await
346+ .with_context(|| format!("apply {}", migration.name))?;
347+ Ok(())
348+ }
349+}
350+
351+fn read_migrations(directory: &std::path::Path) -> anyhow::Result<Vec<Migration>> {
352+ if !directory.exists() {
353+ bail!(
354+ "no migrations directory at {}; create it, or set `migrations_dir` \
355+ on the d1_databases entry",
356+ directory.display()
357+ );
358+ }
359+ let mut migrations = Vec::new();
360+ for entry in
361+ std::fs::read_dir(directory).with_context(|| format!("read {}", directory.display()))?
362+ {
363+ let path = entry?.path();
364+ // A directory is never a migration, whatever it is named — but a
365+ // directory HOLDING migrations is a layout this command does not
366+ // read, and skipping it silently would apply half a schema.
367+ if path.is_dir() {
368+ let nested = std::fs::read_dir(&path)
369+ .map(|entries| {
370+ entries.flatten().any(|entry| {
371+ entry
372+ .path()
373+ .extension()
374+ .is_some_and(|extension| extension == "sql")
375+ })
376+ })
377+ .unwrap_or(false);
378+ if nested {
379+ bail!(
380+ "{} holds .sql files, and celld reads migrations from a flat \
381+ directory only; move them into {} itself",
382+ path.display(),
383+ directory.display()
384+ );
385+ }
386+ continue;
387+ }
388+ if path.extension().is_none_or(|extension| extension != "sql") {
389+ continue;
390+ }
391+ let name = path
392+ .file_name()
393+ .and_then(|name| name.to_str())
394+ .ok_or_else(|| anyhow!("migration {} has a non-UTF-8 name", path.display()))?
395+ .to_string();
396+ let sql =
397+ std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
398+ migrations.push(Migration { name, sql });
399+ }
400+ // Wrangler orders migrations by their numeric prefix, not by the file
401+ // name as text: `10_` runs after `9_`, where a text sort runs it first
402+ // and the ALTERs land before the CREATE they depend on. A file without
403+ // the prefix has no place in that order, so it is refused rather than
404+ // guessed about.
405+ let mut ordered = Vec::with_capacity(migrations.len());
406+ for migration in migrations {
407+ let digits: String = migration
408+ .name
409+ .chars()
410+ .take_while(char::is_ascii_digit)
411+ .collect();
412+ if digits.is_empty() {
413+ bail!(
414+ "migration {:?} has no numeric prefix; wrangler names migrations \
415+ NNNN_description.sql, and the prefix is the application order",
416+ migration.name
417+ );
418+ }
419+ // A parse failure past this point is overflow, not absence: 20 or
420+ // more digits do not fit a u64. Reporting that as "no numeric
421+ // prefix" sent the operator to rename a file that plainly starts
422+ // with digits.
423+ let number: u64 = digits.parse().map_err(|_| {
424+ anyhow!(
425+ "migration {:?} has a numeric prefix that does not fit in an \
426+ unsigned 64-bit number; use a shorter prefix",
427+ migration.name
428+ )
429+ })?;
430+ ordered.push((number, migration));
431+ }
432+ ordered.sort_by(|left, right| (left.0, &left.1.name).cmp(&(right.0, &right.1.name)));
433+ Ok(ordered
434+ .into_iter()
435+ .map(|(_, migration)| migration)
436+ .collect())
437+}
438+
439+/// Every node with an unexpired lease and a usable address, as (id, address).
440+/// The id is not decoration: a peer signature binds the node it is addressed
441+/// to. Any of them will do, because the route forwards to the owner, so the
442+/// CLI does not resolve ownership and cannot race a cell that moves while it
443+/// works. They are all returned rather than only the first, because a lease
444+/// outlives the node that wrote it and a draining node keeps its lease while
445+/// it refuses work.
446+async fn live_nodes(
447+ bucket: &Bucket,
448+ unsafe_public_advertise: bool,
449+) -> anyhow::Result<Vec<(String, String)>> {
450+ let nodes = crate::fleet::node_lease_ids(bucket).await?;
451+ if nodes.is_empty() {
452+ bail!("no node leases in the bucket; celld d1 needs a running fleet");
453+ }
454+ let mut reachable = Vec::new();
455+ let mut refused = Vec::new();
456+ for node in &nodes {
457+ let lease = match crate::fleet::live_node_lease(bucket, node).await {
458+ Ok(Some(lease)) => lease,
459+ Ok(None) => continue,
460+ Err(error) => {
461+ refused.push(format!("{node}: {error}"));
462+ continue;
463+ }
464+ };
465+ let advertise = match crate::startup::parse_advertise(&lease.addr) {
466+ Ok(advertise) => advertise,
467+ Err(error) => {
468+ refused.push(format!(
469+ "{node}: malformed address {:?}: {error}",
470+ lease.addr
471+ ));
472+ continue;
473+ }
474+ };
475+ if advertise.is_public_ip() && !unsafe_public_advertise {
476+ refused.push(format!(
477+ "{node}: public advertise address {}; use a private overlay or \
478+ --unsafe-public-advertise",
479+ lease.addr
480+ ));
481+ continue;
482+ }
483+ reachable.push((node.clone(), lease.addr.clone()));
484+ }
485+ if reachable.is_empty() {
486+ bail!(
487+ "no node in the fleet is reachable; every lease is expired or refused{}",
488+ report(&refused)
489+ );
490+ }
491+ Ok(reachable)
492+}
493+
494+/// Indented detail under a refusal, or nothing when there is none to give.
495+fn report(refused: &[String]) -> String {
496+ if refused.is_empty() {
497+ String::new()
498+ } else {
499+ format!("\n {}", refused.join("\n "))
500+ }
501+}
502+
503+enum Action {
504+ /// Exactly one of the two, enforced at parse.
505+ Execute {
506+ command: Option<String>,
507+ file: Option<PathBuf>,
508+ },
509+ MigrationsList,
510+ MigrationsApply,
511+}
512+
513+struct Command {
514+ action: Action,
515+ database: String,
516+ project: Option<PathBuf>,
517+ bucket: String,
518+ endpoint: Option<String>,
519+ region: String,
520+ unsafe_public_advertise: bool,
521+}
522+
523+impl Command {
524+ fn parse(arguments: Vec<String>) -> anyhow::Result<Option<Self>> {
525+ let mut arguments = arguments.into_iter().peekable();
526+ let Some(first) = arguments.next() else {
527+ return Ok(None);
528+ };
529+ let action = match first.as_str() {
530+ "--help" | "-h" | "help" => return Ok(None),
531+ "execute" => None,
532+ // An option in the subcommand slot means the subcommand is
533+ // missing, not that the option names one. Reporting `--bucket` as
534+ // an unknown subcommand would send an operator looking for a
535+ // spelling mistake they did not make.
536+ "migrations" => match arguments.next().as_deref() {
537+ Some("apply") => Some(Action::MigrationsApply),
538+ Some("list") => Some(Action::MigrationsList),
539+ Some(other) if !other.starts_with('-') => {
540+ bail!("unknown `celld d1 migrations` subcommand: {other}")
541+ }
542+ _ => bail!("`celld d1 migrations` needs `apply` or `list`"),
543+ },
544+ other => bail!("unknown `celld d1` subcommand: {other}"),
545+ };
546+ let database = arguments
547+ .next()
548+ .filter(|value| !value.starts_with('-'))
549+ .ok_or_else(|| anyhow!("celld d1 needs a database name"))?;
550+
551+ let env = |name: &str| {
552+ std::env::var(name)
553+ .ok()
554+ .filter(|value| !value.trim().is_empty())
555+ };
556+ let mut sql = None;
557+ let mut file = None;
558+ let mut project = None;
559+ let mut bucket = env("CELLD_BUCKET");
560+ let mut endpoint = env("S3_ENDPOINT");
561+ let mut region = env("AWS_REGION").or_else(|| env("AWS_DEFAULT_REGION"));
562+ let mut unsafe_public_advertise = false;
563+ while let Some(argument) = arguments.next() {
564+ let mut value = |flag: &str| {
565+ arguments
566+ .next()
567+ .ok_or_else(|| anyhow!("{flag} requires a value"))
568+ };
569+ match argument.as_str() {
570+ "--command" => sql = Some(value("--command")?),
571+ "--file" => file = Some(PathBuf::from(value("--file")?)),
572+ "--bucket" => {
573+ bucket = Some(value("--bucket")?.trim_start_matches("s3://").to_string());
574+ }
575+ "--endpoint" => endpoint = Some(value("--endpoint")?),
576+ "--region" => region = Some(value("--region")?),
577+ "--unsafe-public-advertise" => unsafe_public_advertise = true,
578+ "--help" | "-h" => return Ok(None),
579+ other if other.starts_with('-') => {
580+ bail!("unknown option: {other}; run `celld d1 --help` for usage")
581+ }
582+ other => project = Some(PathBuf::from(other)),
583+ }
584+ }
585+ let action = match action {
586+ Some(action) => {
587+ // Accepting the flag and ignoring it would tell an operator
588+ // their SQL ran when nothing read it.
589+ if sql.is_some() || file.is_some() {
590+ bail!(
591+ "`celld d1 migrations` takes no --command or --file; \
592+ migrations come from the migrations directory"
593+ );
594+ }
595+ action
596+ }
597+ None => {
598+ if sql.is_some() == file.is_some() {
599+ bail!("celld d1 execute requires exactly one of --command or --file");
600+ }
601+ Action::Execute { command: sql, file }
602+ }
603+ };
604+ let bucket = bucket.ok_or_else(|| {
605+ anyhow!("celld d1 requires --bucket [s3://|gs://|az://]NAME (or CELLD_BUCKET)")
606+ })?;
607+ Ok(Some(Self {
608+ action,
609+ database,
610+ project,
611+ bucket,
612+ endpoint,
613+ region: region.unwrap_or_else(|| "us-east-1".to_string()),
614+ unsafe_public_advertise,
615+ }))
616+ }
617+}
618+
619+pub fn print_help() {
620+ println!(
621+ r#"celld d1 — run SQL and migrations against a deployed D1 database
622+
623+USAGE:
624+ celld d1 execute DATABASE (--command SQL | --file PATH) [PROJECT] --bucket NAME
625+ celld d1 migrations apply DATABASE [PROJECT] --bucket NAME
626+ celld d1 migrations list DATABASE [PROJECT] --bucket NAME
627+
628+DATABASE is a `database_name` the project declares in `d1_databases`. PROJECT
629+is the directory holding wrangler.jsonc, and defaults to the working directory.
630+The `database_id` is the stable database identity when the declaration has one.
631+Otherwise, celld uses the `database_name` as the identity.
632+
633+celld d1 needs a running fleet. It finds a node through the bucket's node
634+leases and sends the SQL to that node, which forwards it to the node that owns
635+the database. It signs each request with the fleet's shared secret, which it
636+reads from the bucket, so it needs the same bucket credentials celld deploy
637+needs.
638+
639+Migration files are `NNNN_description.sql` in `migrations/`, applied in the
640+order of their numeric prefixes as wrangler applies them. `migrations_dir` on
641+the d1_databases entry moves the directory, and `migrations_table` renames the
642+bookkeeping table. celld records applied migrations in that table
643+(`d1_migrations` by default), the same table and columns
644+`wrangler d1 migrations` uses.
645+
646+OPTIONS:
647+ --command SQL SQL to run; several statements are permitted
648+ --file PATH Read the SQL from a file instead
649+ --bucket [s3://|gs://|az://]NAME[/PREFIX]
650+ Fleet bucket; same as CELLD_BUCKET
651+ --endpoint URL S3-compatible endpoint; same as S3_ENDPOINT
652+ --region REGION Storage region (default: AWS_REGION or us-east-1)
653+ --unsafe-public-advertise
654+ Permit a node whose advertised address is a public IP
655+ -h, --help Show this help"#
656+ );
657+}
modifiedcrates/celld/dead_node_gc.rs+63−22View file
@@ -1,5 +1,7 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3+#![warn(clippy::disallowed_macros)]
4+
35 //! Compatibility garbage collection for dead celld process generations.
46 //!
57 //! Wake entries and lazy ownership takeover provide serving correctness.
@@ -11,8 +13,8 @@
1113 use futures_util::stream::{self, StreamExt as _};
1214 use serde::Deserialize;
1315 use serde::Serialize;
14-use std::collections::{HashMap, HashSet};
15-use std::time::{Duration, Instant};
16+use std::collections::{BTreeMap, BTreeSet};
17+use std::time::Duration;
1618 use tracing::{info, warn};
1719
1820 const MARKER_GC_CONCURRENCY: usize = 64;
@@ -23,6 +25,16 @@
2325 expires_ms: u64,
2426 #[serde(default, rename = "ownership_index_generation")]
2527 generation: String,
28+ /// The folded node log: this record IS
29+ /// the fleet log's root of truth, so retirement must respect its
30+ /// state and the tombstone must carry it through unchanged.
31+ #[serde(default, skip_serializing_if = "Option::is_none")]
32+ log: Option<serde_json::Value>,
33+ /// Every other lease field, preserved verbatim: a crash between the
34+ /// tombstone and the delete must never publish a record poorer than
35+ /// the one it fences.
36+ #[serde(flatten)]
37+ rest: serde_json::Map<String, serde_json::Value>,
2638 }
2739
2840 #[derive(Clone, Debug)]
@@ -50,8 +62,8 @@
5062 /// remains, while `retries` bounds a persistently failing marker store.
5163 #[derive(Default)]
5264 pub struct DeadNodeGc {
53- swept: HashSet<String>,
54- retries: HashMap<String, (String, u32, Instant)>,
65+ swept: BTreeSet<String>,
66+ retries: BTreeMap<String, (String, u32, u64)>,
5567 }
5668
5769 impl DeadNodeGc {
@@ -72,14 +84,13 @@
7284 }
7385
7486 let renew_ms = (lease_ttl_ms / 3).max(1);
75- let mut renewal = tokio::time::interval(Duration::from_millis(renew_ms));
76- renewal.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
87+ let mut renewal = crate::asyncrt::interval(Duration::from_millis(renew_ms));
88+ renewal.set_missed_tick_behavior(crate::asyncrt::MissedTickBehavior::Delay);
7789 renewal.tick().await;
7890 let pass = self.run_pass(bucket, tick_ms);
7991 tokio::pin!(pass);
8092 loop {
81- tokio::select! {
82- _ = &mut pass => return,
93+ crate::asyncrt::select! {
8394 _ = renewal.tick() => {
8495 if !crate::wake::try_hold_waker(
8596 bucket,
@@ -90,7 +101,8 @@
90101 warn!("waker lease renewal failed; cancelling dead-node GC");
91102 return;
92103 }
93- }
104+ },
105+ _ = &mut pass => return,
94106 }
95107 }
96108 }
@@ -98,13 +110,13 @@
98110 async fn run_pass(&mut self, bucket: &Bucket, tick_ms: u64) {
99111 let observed_ms = crate::ownership_store::now_ms();
100112 let dead = dead_nodes(bucket, observed_ms).await;
101- let dead_names: HashSet<&str> = dead.iter().map(|record| record.node.as_str()).collect();
113+ let dead_names: BTreeSet<&str> = dead.iter().map(|record| record.node.as_str()).collect();
102114 self.swept.retain(|node| dead_names.contains(node.as_str()));
103115 self.retries
104116 .retain(|node, _| dead_names.contains(node.as_str()));
105117
106- let retry_now = Instant::now();
107- let indexed: HashMap<String, String> = dead
118+ let retry_now = crate::asyncrt::mono_ms();
119+ let indexed: BTreeMap<String, String> = dead
108120 .iter()
109121 .filter(|record| {
110122 !self.swept.contains(&record.node)
@@ -120,7 +132,7 @@
120132 .collect();
121133
122134 let indexed = if indexed.is_empty() {
123- Some(HashMap::new())
135+ Some(BTreeMap::new())
124136 } else {
125137 match cells_indexed_by_nodes(bucket, &indexed).await {
126138 Ok(indexed) => Some(indexed),
@@ -132,7 +144,7 @@
132144 };
133145 let mut summaries = match indexed {
134146 Some(indexed) => gc_markers(bucket, indexed).await,
135- None => HashMap::new(),
147+ None => BTreeMap::new(),
136148 };
137149
138150 for record in dead {
@@ -176,7 +188,7 @@
176188 (
177189 generation,
178190 failure_count,
179- Instant::now() + Duration::from_millis(retry_ms),
191+ crate::asyncrt::mono_ms().saturating_add(retry_ms),
180192 ),
181193 );
182194 continue;
@@ -185,9 +197,10 @@
185197 self.swept.insert(node.clone());
186198 }
187199 match retire_dead_node(bucket, &node, observed_ms).await {
188- Ok(_) => {
200+ Ok(true) => {
189201 self.swept.remove(&node);
190202 }
203+ Ok(false) => {}
191204 Err(error) => warn!(%node, %error, "dead-node lease retirement failed"),
192205 }
193206 }
@@ -234,9 +247,9 @@
234247
235248 async fn cells_indexed_by_nodes(
236249 bucket: &Bucket,
237- nodes: &HashMap<String, String>,
238-) -> anyhow::Result<HashMap<String, IndexedOwnership>> {
239- let mut indexed: HashMap<String, IndexedOwnership> = nodes
250+ nodes: &BTreeMap<String, String>,
251+) -> anyhow::Result<BTreeMap<String, IndexedOwnership>> {
252+ let mut indexed: BTreeMap<String, IndexedOwnership> = nodes
240253 .keys()
241254 .cloned()
242255 .map(|node| (node, IndexedOwnership::default()))
@@ -255,9 +268,9 @@
255268
256269 async fn gc_markers(
257270 bucket: &Bucket,
258- indexed: HashMap<String, IndexedOwnership>,
259-) -> HashMap<String, MarkerGcSummary> {
260- let mut summaries = HashMap::new();
271+ indexed: BTreeMap<String, IndexedOwnership>,
272+) -> BTreeMap<String, MarkerGcSummary> {
273+ let mut summaries = BTreeMap::new();
261274 let mut work = Vec::new();
262275 for (node, indexed) in indexed {
263276 summaries
@@ -304,6 +317,34 @@
304317 ) {
305318 return Ok(false);
306319 }
320+ // A folded record is never deleted (lease-fold, second cold review,
321+ // finding 1). Two reasons compose. An unsealed log is the fleet's
322+ // only pointer to an unrecovered tail, so the record must outlive
323+ // recovery — the dead-leader sweep seals it, and a later pass
324+ // retires it here. And object_store has no conditional delete, so
325+ // an unconditional delete can land arbitrarily late — after the
326+ // node's successor generation reinstalled the key and activated its
327+ // log — and erase an acked tail. So a dead folded record's terminal
328+ // state is the tombstone: still dead, still sealed, expiry zero.
329+ // Node keys are stable across restarts, so retained tombstones
330+ // number the decommissioned nodes, not the restarts, and the
331+ // dead-leader sweep can always find a sealed session to GC its
332+ // bundles. `Ok(false)` keeps the marker latch held: the record
333+ // remains listed, and only true deletion clears the latch.
334+ if let Some(log) = record.log.as_ref() {
335+ if log.get("state").and_then(|state| state.as_str()) != Some("sealed") {
336+ return Ok(false);
337+ }
338+ if record.expires_ms == 0 {
339+ return Ok(false);
340+ }
341+ let tombstone = serde_json::to_vec(&NodeWire {
342+ expires_ms: 0,
343+ ..record
344+ })?;
345+ bucket.put_cas(&key, tombstone, Some(&etag)).await?;
346+ return Ok(false);
347+ }
307348 // No conditional delete in object_store: fence with a CAS tombstone
308349 // (`expires_ms: 0`, still a dead record), then delete. A crash between
309350 // the two leaves a record that still reads as dead and retires on the
modifiedcrates/celld/deploy.rs+282−7View file
@@ -1,5 +1,8 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3+// Deployment is an operator control-plane path outside the engine World.
4+#![allow(clippy::disallowed_methods)]
5+
36 //! `celld deploy` — build a Wrangler project and write it to the fleet bucket.
47 //!
58 //! Bundling is esbuild's job; this module does config, identity, and durable
@@ -9,8 +12,8 @@
912 use crate::bucket::Bucket;
1013 use crate::protocol::{
1114 asset_blob_key, AssetConfig, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest,
12- ModuleKind, ModuleRef, Rollout, RunWorkerFirst, FEATURE_ASSETS_V1, FEATURE_SQLITE_VEC_V1,
13- FEATURE_WASM_V1,
15+ ModuleKind, ModuleRef, Rollout, RunWorkerFirst, FEATURE_ASSETS_V1, FEATURE_CRON_V1,
16+ FEATURE_D1_V1, FEATURE_SQLITE_VEC_V1, FEATURE_WASM_V1,
1417 };
1518 use anyhow::{anyhow, bail, Context};
1619 use flate2::write::GzEncoder;
@@ -37,10 +40,29 @@
3740 "migrations",
3841 "assets",
3942 "services",
43+ "triggers",
4044 "vars",
45+ "d1_databases",
4146 "no_bundle",
4247 ];
4348
49+/// The Durable Object class every D1 database runs as. It is supplied by the
50+/// runtime, not by the worker, so a config naming it in `durable_objects` or
51+/// `migrations` is refused: the harness registers this class in every isolate,
52+/// and a user binding onto it would silently reach a D1 database cell instead
53+/// of the user's class. A bare module export of this name is not refused —
54+/// the loader skips it rather than let it shadow the built-in.
55+pub const D1_CLASS: &str = "__D1Database";
56+
57+/// Whether a cell scope names a D1 database. The unauthenticated operator
58+/// route uses this to refuse one: a D1 cell answers arbitrary SQL, and its
59+/// scope is derivable from the project's config rather than secret.
60+pub fn is_d1_scope(scope: &str) -> bool {
61+ scope
62+ .strip_prefix(D1_CLASS)
63+ .is_some_and(|rest| rest.starts_with(':'))
64+}
65+
4466 const MAX_ASSET_FILES: usize = 20_000;
4567 const MAX_ASSET_BYTES: u64 = 1024 * 1024 * 1024;
4668 const MAX_ASSET_FILE_BYTES: u64 = 25 * 1024 * 1024;
@@ -58,12 +80,13 @@
5880 pub fn print_help() {
5981 println!(
6082 "celld deploy — build a Worker with esbuild and write it to the fleet bucket\n\n\
61-USAGE:\n celld deploy [PROJECT] --bucket [s3://|gs://]NAME[/PREFIX] [OPTIONS]\n\n\
83+USAGE:\n celld deploy [PROJECT] --bucket [s3://|gs://|az://]NAME[/PREFIX] [OPTIONS]\n\n\
6284 PROJECT is a directory or a Wrangler config; it defaults to the working\n\
6385 directory, where celld looks for wrangler.jsonc or wrangler.json.\n\n\
64-OPTIONS:\n --config PATH Same as passing PROJECT positionally\n --bucket [s3://|gs://]NAME[/PREFIX]\n Fleet bucket and prefix; defaults to CELLD_BUCKET.\n gs:// selects a Google Cloud Storage bucket; celld\n then rejects --endpoint and ignores --region\n --endpoint URL S3-compatible endpoint; defaults to S3_ENDPOINT\n --region REGION Storage region; defaults to AWS_REGION\n --dry-run Bundle and print the version without writing\n -h, --help Show this help\n\n\
65-Credentials come from the standard AWS credential chain, or from Google\n\
66-Application Default Credentials for a gs:// bucket.\n\n\
86+OPTIONS:\n --config PATH Same as passing PROJECT positionally\n --bucket [s3://|gs://|az://]NAME[/PREFIX]\n Fleet bucket and prefix; defaults to CELLD_BUCKET.\n gs:// selects a Google Cloud Storage bucket, az://\n an Azure Blob Storage container with its account in\n AZURE_STORAGE_ACCOUNT_NAME; celld then rejects\n --endpoint and ignores --region\n --endpoint URL S3-compatible endpoint; defaults to S3_ENDPOINT\n --region REGION Storage region; defaults to AWS_REGION\n --dry-run Bundle and print the version without writing\n -h, --help Show this help\n\n\
87+Credentials come from the standard AWS credential chain, from Google\n\
88+Application Default Credentials for a gs:// bucket, or from an Azure storage\n\
89+account key, managed identity, or workload identity for an az:// bucket.\n\n\
6790 Worker projects require `esbuild` on PATH; asset-only projects do not. Static\n\
6891 assets, service bindings, and string vars are supported. Routes are not; use\n\
6992 Wrangler for route configuration.\n\
@@ -127,6 +150,7 @@
127150 metadata: Value,
128151 do_classes: Vec<String>,
129152 sqlite_classes: Vec<String>,
153+ crons: Vec<String>,
130154 }
131155
132156 struct ProjectAssets {
@@ -239,6 +263,10 @@
239263 );
240264 Some((format!("env.{name} (Service)"), target))
241265 }
266+ Some("d1") => {
267+ let database = binding.get("database_name").and_then(Value::as_str)?;
268+ Some((format!("env.{name} (D1)"), database.to_string()))
269+ }
242270 Some("plain_text") => Some((
243271 format!("env.{name} (Text)"),
244272 "Environment Variable".to_string(),
@@ -328,6 +356,7 @@
328356 .get("compatibility_flags")
329357 .and_then(Value::as_array)
330358 .is_some_and(|flags| flags.iter().any(|flag| flag.as_str() == Some("sqlite_vec")));
359+ let uses_d1 = project.do_classes.iter().any(|class| class == D1_CLASS);
331360 let manifest = Manifest {
332361 schema_version: if asset_reference.is_some() { 2 } else { 1 },
333362 version: version.clone(),
@@ -345,6 +374,7 @@
345374 })
346375 .collect(),
347376 assets: asset_reference,
377+ crons: project.crons.clone(),
348378 // Each capability the manifest depends on is named here, so a node
349379 // that predates it rejects the deployment up front instead of
350380 // partially deserializing the manifest and failing at worker load.
@@ -353,6 +383,12 @@
353383 if built_assets.is_some() {
354384 features.push(FEATURE_ASSETS_V1.to_string());
355385 }
386+ if !project.crons.is_empty() {
387+ features.push(FEATURE_CRON_V1.to_string());
388+ }
389+ if uses_d1 {
390+ features.push(FEATURE_D1_V1.to_string());
391+ }
356392 if sqlite_vec {
357393 features.push(FEATURE_SQLITE_VEC_V1.to_string());
358394 }
@@ -454,6 +490,136 @@
454490 }
455491 }
456492
493+/// What `celld d1` needs out of a project: the declared databases, so a name
494+/// the project never declared fails here instead of creating an empty one.
495+pub struct D1Project {
496+ /// One entry per declaration, in config order.
497+ pub databases: Vec<D1Declaration>,
498+}
499+
500+pub struct D1Declaration {
501+ pub database_name: String,
502+ /// Cloudflare's stable resource ID when present, otherwise the database
503+ /// name for a celld-only project.
504+ pub database_identity: String,
505+ /// Wrangler scopes `migrations_dir` to the binding, so this is per
506+ /// database and never shared. A single shared directory would apply one
507+ /// database's migrations to another.
508+ pub migrations_dir: PathBuf,
509+ /// The bookkeeping table, per binding as on wrangler
510+ /// (`migrations_table`). Hard-coding `d1_migrations` here made celld
511+ /// read an empty table on a project that had renamed it, and every
512+ /// already-applied migration re-ran.
513+ pub migrations_table: String,
514+}
515+
516+/// Read a project's D1 declarations. This reads the same config `build` reads,
517+/// but it does not bundle: `celld d1` acts on a database that is already
518+/// deployed, and a project that fails to build must still be migratable.
519+pub fn read_d1_project(given: Option<PathBuf>) -> anyhow::Result<D1Project> {
520+ let path = resolve_config(given)?;
521+ let root = path.parent().unwrap_or(Path::new(".")).to_path_buf();
522+ let source =
523+ std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
524+ let config: Value = serde_json::from_str(&strip_jsonc(&source))
525+ .with_context(|| format!("parse {}", path.display()))?;
526+ let object = config
527+ .as_object()
528+ .ok_or_else(|| anyhow!("{} is not a JSON object", path.display()))?;
529+ object
530+ .get("name")
531+ .and_then(Value::as_str)
532+ .ok_or_else(|| anyhow!("{} has no `name`", path.display()))?;
533+ let mut databases = Vec::new();
534+ if let Some(Value::Array(entries)) = object.get("d1_databases") {
535+ for entry in entries {
536+ let Some(name) = entry.get("database_name").and_then(Value::as_str) else {
537+ continue;
538+ };
539+ // Wrangler discovers migrations through more knobs than the two
540+ // celld reads. An unread knob must be a refusal, not a silent
541+ // default: honoring half of a project's migration config applies
542+ // the wrong files in the wrong order.
543+ if entry.get("migrations_pattern").is_some() {
544+ bail!(
545+ "d1 database {name:?} sets `migrations_pattern`, which celld \
546+ does not support; celld reads `*.sql` from `migrations_dir`"
547+ );
548+ }
549+ let migrations_table = match entry.get("migrations_table") {
550+ None => "d1_migrations".to_string(),
551+ Some(Value::String(table)) => table.clone(),
552+ Some(_) => bail!("d1 database {name:?} has a non-string `migrations_table`"),
553+ };
554+ // The table name is joined into SQL as an identifier, both here
555+ // and in the cell, so anything but a plain identifier is refused
556+ // before it can reach either.
557+ let mut characters = migrations_table.chars();
558+ let plain = characters
559+ .next()
560+ .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
561+ && characters.all(|c| c.is_ascii_alphanumeric() || c == '_');
562+ if !plain {
563+ bail!(
564+ "d1 database {name:?} has a `migrations_table` that is not a \
565+ plain identifier: {migrations_table:?}"
566+ );
567+ }
568+ let database_identity = match entry.get("database_id") {
569+ None => name.to_string(),
570+ Some(Value::String(identity)) if !identity.is_empty() => identity.clone(),
571+ Some(_) => bail!("d1 database {name:?} has an invalid `database_id`"),
572+ };
573+ databases.push(D1Declaration {
574+ database_name: name.to_string(),
575+ database_identity,
576+ migrations_dir: entry
577+ .get("migrations_dir")
578+ .and_then(Value::as_str)
579+ .map_or_else(|| root.join("migrations"), |dir| root.join(dir)),
580+ migrations_table,
581+ });
582+ }
583+ }
584+ let mut unique = Vec::<D1Declaration>::new();
585+ for declaration in databases {
586+ if let Some(previous) = unique
587+ .iter()
588+ .find(|candidate| candidate.database_name == declaration.database_name)
589+ {
590+ if previous.database_identity != declaration.database_identity
591+ || previous.migrations_dir != declaration.migrations_dir
592+ || previous.migrations_table != declaration.migrations_table
593+ {
594+ bail!(
595+ "d1 database {:?} has ambiguous aliases with different database_id, \
596+ migrations_dir, or migrations_table values",
597+ declaration.database_name
598+ );
599+ }
600+ continue;
601+ }
602+ if let Some(previous) = unique
603+ .iter()
604+ .find(|candidate| candidate.database_identity == declaration.database_identity)
605+ {
606+ if previous.migrations_dir != declaration.migrations_dir
607+ || previous.migrations_table != declaration.migrations_table
608+ {
609+ bail!(
610+ "d1 database identity {:?} has ambiguous aliases {:?} and {:?} with \
611+ different migrations_dir or migrations_table values",
612+ declaration.database_identity,
613+ previous.database_name,
614+ declaration.database_name
615+ );
616+ }
617+ }
618+ unique.push(declaration);
619+ }
620+ Ok(D1Project { databases: unique })
621+}
622+
457623 /// A path may name the config itself or the directory holding it; with no
458624 /// path at all, the working directory.
459625 fn resolve_config(given: Option<PathBuf>) -> anyhow::Result<PathBuf> {
@@ -551,7 +717,14 @@
551717 bail!("an asset-only project cannot set `assets.run_worker_first`");
552718 }
553719
554- let sqlite_classes = read_sqlite_classes(object)?;
720+ let mut sqlite_classes = read_sqlite_classes(object)?;
721+ if sqlite_classes.iter().any(|class| class == D1_CLASS) {
722+ bail!("`{D1_CLASS}` is reserved for D1; remove it from `migrations`");
723+ }
724+ let crons = read_crons(object)?;
725+ if !crons.is_empty() && main.is_none() {
726+ bail!("config sets `triggers.crons` without `main`; a cron trigger needs a `scheduled` handler to call");
727+ }
555728
556729 // Wrangler-shaped upload metadata, so a manifest written here and one
557730 // written by the control plane describe a deployment the same way.
@@ -616,6 +789,60 @@
616789 bindings.push(encoded);
617790 service_count += 1;
618791 }
792+ let d1_databases = match object.get("d1_databases") {
793+ None => &[][..],
794+ Some(Value::Array(databases)) => databases.as_slice(),
795+ Some(_) => bail!("config `d1_databases` must be an array"),
796+ };
797+ // The reserved class must be refused whether or not the project declares
798+ // any `d1_databases`: the harness registers its own `__D1Database` class
799+ // in every isolate, so a durable_objects binding naming it would silently
800+ // resolve to the D1 database cell instead of the user's class.
801+ if do_classes.iter().any(|class| class == D1_CLASS) {
802+ bail!("`{D1_CLASS}` is reserved for D1; rename the Durable Object class");
803+ }
804+ let mut d1_binding_names = BTreeSet::new();
805+ for database in d1_databases {
806+ let binding = database
807+ .get("binding")
808+ .and_then(Value::as_str)
809+ .ok_or_else(|| anyhow!("d1 database has no `binding`"))?;
810+ if !valid_binding(binding) {
811+ bail!("invalid d1 binding name: {binding:?}");
812+ }
813+ if !d1_binding_names.insert(binding.to_string()) {
814+ bail!("duplicate d1 binding name: {binding:?}");
815+ }
816+ let database_name = database
817+ .get("database_name")
818+ .and_then(Value::as_str)
819+ .ok_or_else(|| {
820+ anyhow!("d1 binding {binding} has no `database_name`; celld uses the name to select the database from the CLI")
821+ })?;
822+ if database_name.is_empty() {
823+ bail!("d1 binding {binding} has an empty `database_name`");
824+ }
825+ let mut encoded = json!({
826+ "type": "d1",
827+ "name": binding,
828+ "database_name": database_name,
829+ });
830+ if let Some(database_id) = database.get("database_id") {
831+ let database_id = database_id
832+ .as_str()
833+ .filter(|database_id| !database_id.is_empty())
834+ .ok_or_else(|| anyhow!("d1 binding {binding} has an invalid `database_id`"))?;
835+ encoded["database_id"] = json!(database_id);
836+ }
837+ bindings.push(encoded);
838+ }
839+ if !d1_databases.is_empty() {
840+ // A D1 database is a cell of a runtime-supplied class. Declaring it
841+ // here is what registers its namespace key and marks it SQLite-backed;
842+ // it is never a worker export, so it stays out of `ctx.exports`.
843+ do_classes.push(D1_CLASS.to_string());
844+ sqlite_classes.push(D1_CLASS.to_string());
845+ }
619846 let vars = match object.get("vars") {
620847 None => None,
621848 Some(Value::Object(vars)) => Some(vars),
@@ -653,6 +880,21 @@
653880 "name": binding,
654881 }));
655882 }
883+ // A name declared as a D1 binding and as anything else would deploy
884+ // cleanly and then resolve to whichever `env` assignment ran last, so a
885+ // Worker reading `env.DB` could get a service stub where it expected a
886+ // database. Collisions between the other binding types are still not
887+ // refused here — a known gap, left for a check over every binding type.
888+ for binding in &bindings {
889+ let name = binding.get("name").and_then(Value::as_str).unwrap_or("");
890+ let kind = binding.get("type").and_then(Value::as_str).unwrap_or("");
891+ if kind != "d1" && d1_binding_names.contains(name) {
892+ bail!(
893+ "binding name {name:?} is declared both in `d1_databases` and as a \
894+ {kind} binding; every binding needs its own name"
895+ );
896+ }
897+ }
656898 let mut metadata = Map::new();
657899 if main.is_some() {
658900 metadata.insert("main_module".into(), json!("index.js"));
@@ -682,9 +924,37 @@
682924 metadata: Value::Object(metadata),
683925 do_classes,
684926 sqlite_classes,
927+ crons,
685928 })
686929 }
687930
931+/// `triggers.crons`, validated here so a malformed expression stops the deploy
932+/// the developer is watching instead of an activation an hour later. Wrangler
933+/// accepts `triggers` with other keys we do not model; only `crons` is read.
934+fn read_crons(project: &Map<String, Value>) -> anyhow::Result<Vec<String>> {
935+ let Some(value) = project.get("triggers") else {
936+ return Ok(Vec::new());
937+ };
938+ let triggers = value
939+ .as_object()
940+ .ok_or_else(|| anyhow!("config `triggers` must be an object"))?;
941+ let Some(value) = triggers.get("crons") else {
942+ return Ok(Vec::new());
943+ };
944+ let entries = value
945+ .as_array()
946+ .ok_or_else(|| anyhow!("config `triggers.crons` must be an array of strings"))?;
947+ let mut crons = Vec::new();
948+ for entry in entries {
949+ let expression = entry
950+ .as_str()
951+ .ok_or_else(|| anyhow!("config `triggers.crons` must be an array of strings"))?;
952+ celld_logic::cron::parse(expression).map_err(|error| anyhow!("{error}"))?;
953+ crons.push(expression.trim().to_string());
954+ }
955+ Ok(crons)
956+}
957+
688958 fn read_sqlite_classes(project: &Map<String, Value>) -> anyhow::Result<Vec<String>> {
689959 let Some(value) = project.get("migrations") else {
690960 return Ok(Vec::new());
@@ -1149,6 +1419,11 @@
11491419 .arg("--conditions=workerd,worker,browser")
11501420 .arg("--external:node:*")
11511421 .arg("--external:cloudflare:*")
1422+ .args(
1423+ crate::js::BARE_NODE_BUILTINS
1424+ .iter()
1425+ .map(|specifier| format!("--external:{specifier}")),
1426+ )
11521427 // Wasm becomes a sibling module (Wrangler's CompiledWasm rule). The
11531428 // `copy` loader makes esbuild resolve each wasm import like any other
11541429 // import (importer-relative, node_modules, deduplicated) and rewrite
modifiedcrates/celld/env_vars.rs+0−6View file
@@ -52,7 +52,6 @@
5252 "CELLD_ADMISSION_WAIT_MS",
5353 "CELLD_ALARM_RESIDENT_MS",
5454 "CELLD_ASSET_CACHE_BYTES",
55- "CELLD_LEASE_LINGER_MS",
5655 "CELLD_LOCAL_CACHE_MAX_BYTES",
5756 "CELLD_MAX_RESIDENT_CELLS",
5857 "CELLD_MAX_RSS_MB",
@@ -72,11 +71,6 @@
7271 }
7372 }
7473
75- if let Some(value) = value("CELLD_LAZY_NODE_LEASE")? {
76- if !matches!(value.as_str(), "continuous" | "lazy" | "shadow") {
77- bail!("CELLD_LAZY_NODE_LEASE must be continuous, lazy, or shadow, not {value:?}");
78- }
79- }
8074 if let Some(value) = value("CELLD_PRESSURE_OWNERSHIP")? {
8175 if !matches!(value.as_str(), "release" | "sticky") {
8276 bail!("CELLD_PRESSURE_OWNERSHIP must be release or sticky, not {value:?}");
deletedcrates/celld/fault.rs+0−288
@@ -1,288 +1,0 @@
1-// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2-
3-//! Test-only SQLite fault injection: a wrapper VFS that delegates to the
4-//! process default VFS but fails writes with `SQLITE_IOERR` while the current
5-//! thread has armed the fault. Compiled only into test builds —
6-//! production binaries contain none of this code and no seam for it.
7-use rusqlite::ffi;
8-use std::cell::Cell;
9-use std::ffi::c_char;
10-use std::ffi::c_int;
11-use std::ffi::c_void;
12-use std::mem::size_of;
13-use std::sync::Once;
14-
15-const FAULT_VFS_NAME: &std::ffi::CStr = c"cells-fault-vfs";
16-
17-thread_local! {
18- static WRITE_FAULT: Cell<bool> = const { Cell::new(false) };
19-}
20-
21-pub fn set_write_fault(enabled: bool) {
22- WRITE_FAULT.with(|flag| flag.set(enabled));
23-}
24-
25-fn write_fault_armed() -> bool {
26- WRITE_FAULT.try_with(Cell::get).unwrap_or(false)
27-}
28-
29-/// The shim's per-file state: SQLite allocates `szOsFile` bytes, we use the
30-/// front for this header and hand the tail to the real VFS as its file.
31-#[repr(C)]
32-struct ShimFile {
33- base: ffi::sqlite3_file,
34- real: *mut ffi::sqlite3_file,
35-}
36-
37-unsafe fn real_file(file: *mut ffi::sqlite3_file) -> *mut ffi::sqlite3_file {
38- (*file.cast::<ShimFile>()).real
39-}
40-
41-unsafe fn real_vfs(vfs: *mut ffi::sqlite3_vfs) -> *mut ffi::sqlite3_vfs {
42- (*vfs).pAppData.cast()
43-}
44-
45-macro_rules! file_delegate {
46- ($file:ident, $method:ident $(, $arg:expr)*) => {{
47- let real = real_file($file);
48- ((*(*real).pMethods).$method.expect("real io method"))(real $(, $arg)*)
49- }};
50-}
51-
52-macro_rules! vfs_delegate {
53- ($vfs:ident, $method:ident $(, $arg:expr)*) => {{
54- let real = real_vfs($vfs);
55- ((*real).$method.expect("real vfs method"))(real $(, $arg)*)
56- }};
57-}
58-
59-unsafe extern "C" fn shim_close(file: *mut ffi::sqlite3_file) -> c_int {
60- file_delegate!(file, xClose)
61-}
62-unsafe extern "C" fn shim_read(
63- file: *mut ffi::sqlite3_file,
64- buf: *mut c_void,
65- amt: c_int,
66- offset: i64,
67-) -> c_int {
68- file_delegate!(file, xRead, buf, amt, offset)
69-}
70-unsafe extern "C" fn shim_write(
71- file: *mut ffi::sqlite3_file,
72- buf: *const c_void,
73- amt: c_int,
74- offset: i64,
75-) -> c_int {
76- if write_fault_armed() {
77- return ffi::SQLITE_IOERR;
78- }
79- file_delegate!(file, xWrite, buf, amt, offset)
80-}
81-unsafe extern "C" fn shim_truncate(file: *mut ffi::sqlite3_file, size: i64) -> c_int {
82- file_delegate!(file, xTruncate, size)
83-}
84-unsafe extern "C" fn shim_sync(file: *mut ffi::sqlite3_file, flags: c_int) -> c_int {
85- file_delegate!(file, xSync, flags)
86-}
87-unsafe extern "C" fn shim_file_size(file: *mut ffi::sqlite3_file, size: *mut i64) -> c_int {
88- file_delegate!(file, xFileSize, size)
89-}
90-unsafe extern "C" fn shim_lock(file: *mut ffi::sqlite3_file, level: c_int) -> c_int {
91- file_delegate!(file, xLock, level)
92-}
93-unsafe extern "C" fn shim_unlock(file: *mut ffi::sqlite3_file, level: c_int) -> c_int {
94- file_delegate!(file, xUnlock, level)
95-}
96-unsafe extern "C" fn shim_check_reserved_lock(
97- file: *mut ffi::sqlite3_file,
98- out: *mut c_int,
99-) -> c_int {
100- file_delegate!(file, xCheckReservedLock, out)
101-}
102-unsafe extern "C" fn shim_file_control(
103- file: *mut ffi::sqlite3_file,
104- op: c_int,
105- arg: *mut c_void,
106-) -> c_int {
107- file_delegate!(file, xFileControl, op, arg)
108-}
109-unsafe extern "C" fn shim_sector_size(file: *mut ffi::sqlite3_file) -> c_int {
110- file_delegate!(file, xSectorSize)
111-}
112-unsafe extern "C" fn shim_device_characteristics(file: *mut ffi::sqlite3_file) -> c_int {
113- file_delegate!(file, xDeviceCharacteristics)
114-}
115-unsafe extern "C" fn shim_shm_map(
116- file: *mut ffi::sqlite3_file,
117- region: c_int,
118- size: c_int,
119- extend: c_int,
120- out: *mut *mut c_void,
121-) -> c_int {
122- file_delegate!(file, xShmMap, region, size, extend, out)
123-}
124-unsafe extern "C" fn shim_shm_lock(
125- file: *mut ffi::sqlite3_file,
126- offset: c_int,
127- count: c_int,
128- flags: c_int,
129-) -> c_int {
130- file_delegate!(file, xShmLock, offset, count, flags)
131-}
132-unsafe extern "C" fn shim_shm_barrier(file: *mut ffi::sqlite3_file) {
133- file_delegate!(file, xShmBarrier)
134-}
135-unsafe extern "C" fn shim_shm_unmap(file: *mut ffi::sqlite3_file, delete_flag: c_int) -> c_int {
136- file_delegate!(file, xShmUnmap, delete_flag)
137-}
138-unsafe extern "C" fn shim_fetch(
139- file: *mut ffi::sqlite3_file,
140- offset: i64,
141- amt: c_int,
142- out: *mut *mut c_void,
143-) -> c_int {
144- file_delegate!(file, xFetch, offset, amt, out)
145-}
146-unsafe extern "C" fn shim_unfetch(
147- file: *mut ffi::sqlite3_file,
148- offset: i64,
149- page: *mut c_void,
150-) -> c_int {
151- file_delegate!(file, xUnfetch, offset, page)
152-}
153-
154-static SHIM_IO_METHODS: ffi::sqlite3_io_methods = ffi::sqlite3_io_methods {
155- iVersion: 3,
156- xClose: Some(shim_close),
157- xRead: Some(shim_read),
158- xWrite: Some(shim_write),
159- xTruncate: Some(shim_truncate),
160- xSync: Some(shim_sync),
161- xFileSize: Some(shim_file_size),
162- xLock: Some(shim_lock),
163- xUnlock: Some(shim_unlock),
164- xCheckReservedLock: Some(shim_check_reserved_lock),
165- xFileControl: Some(shim_file_control),
166- xSectorSize: Some(shim_sector_size),
167- xDeviceCharacteristics: Some(shim_device_characteristics),
168- xShmMap: Some(shim_shm_map),
169- xShmLock: Some(shim_shm_lock),
170- xShmBarrier: Some(shim_shm_barrier),
171- xShmUnmap: Some(shim_shm_unmap),
172- xFetch: Some(shim_fetch),
173- xUnfetch: Some(shim_unfetch),
174-};
175-
176-unsafe extern "C" fn shim_open(
177- vfs: *mut ffi::sqlite3_vfs,
178- name: *const c_char,
179- file: *mut ffi::sqlite3_file,
180- flags: c_int,
181- out_flags: *mut c_int,
182-) -> c_int {
183- let real = real_vfs(vfs);
184- let shim = file.cast::<ShimFile>();
185- let inner = file.cast::<u8>().add(size_of::<ShimFile>()).cast();
186- (*shim).base.pMethods = std::ptr::null();
187- (*shim).real = inner;
188- let open = (*real).xOpen.expect("real vfs xOpen");
189- let rc = open(real, name, inner, flags, out_flags);
190- if !(*inner).pMethods.is_null() {
191- (*shim).base.pMethods = &SHIM_IO_METHODS;
192- }
193- rc
194-}
195-unsafe extern "C" fn shim_delete(
196- vfs: *mut ffi::sqlite3_vfs,
197- name: *const c_char,
198- sync_dir: c_int,
199-) -> c_int {
200- vfs_delegate!(vfs, xDelete, name, sync_dir)
201-}
202-unsafe extern "C" fn shim_access(
203- vfs: *mut ffi::sqlite3_vfs,
204- name: *const c_char,
205- flags: c_int,
206- out: *mut c_int,
207-) -> c_int {
208- vfs_delegate!(vfs, xAccess, name, flags, out)
209-}
210-unsafe extern "C" fn shim_full_pathname(
211- vfs: *mut ffi::sqlite3_vfs,
212- name: *const c_char,
213- length: c_int,
214- out: *mut c_char,
215-) -> c_int {
216- vfs_delegate!(vfs, xFullPathname, name, length, out)
217-}
218-unsafe extern "C" fn shim_randomness(
219- vfs: *mut ffi::sqlite3_vfs,
220- length: c_int,
221- out: *mut c_char,
222-) -> c_int {
223- vfs_delegate!(vfs, xRandomness, length, out)
224-}
225-unsafe extern "C" fn shim_sleep(vfs: *mut ffi::sqlite3_vfs, microseconds: c_int) -> c_int {
226- vfs_delegate!(vfs, xSleep, microseconds)
227-}
228-unsafe extern "C" fn shim_current_time(vfs: *mut ffi::sqlite3_vfs, out: *mut f64) -> c_int {
229- vfs_delegate!(vfs, xCurrentTime, out)
230-}
231-unsafe extern "C" fn shim_get_last_error(
232- vfs: *mut ffi::sqlite3_vfs,
233- length: c_int,
234- out: *mut c_char,
235-) -> c_int {
236- vfs_delegate!(vfs, xGetLastError, length, out)
237-}
238-unsafe extern "C" fn shim_current_time_int64(vfs: *mut ffi::sqlite3_vfs, out: *mut i64) -> c_int {
239- vfs_delegate!(vfs, xCurrentTimeInt64, out)
240-}
241-
242-fn install() {
243- static INSTALL: Once = Once::new();
244- INSTALL.call_once(|| {
245- // SAFETY: the default VFS outlives the process; the shim is leaked so
246- // SQLite may hold it forever. Registration is not made the default,
247- // so only connections opened by name route through the shim.
248- unsafe {
249- let real = ffi::sqlite3_vfs_find(std::ptr::null());
250- assert!(!real.is_null(), "no default SQLite VFS");
251- let vfs = Box::leak(Box::new(ffi::sqlite3_vfs {
252- iVersion: 2,
253- szOsFile: (*real).szOsFile + size_of::<ShimFile>() as c_int,
254- mxPathname: (*real).mxPathname,
255- pNext: std::ptr::null_mut(),
256- zName: FAULT_VFS_NAME.as_ptr(),
257- pAppData: real.cast(),
258- xOpen: Some(shim_open),
259- xDelete: Some(shim_delete),
260- xAccess: Some(shim_access),
261- xFullPathname: Some(shim_full_pathname),
262- xDlOpen: None,
263- xDlError: None,
264- xDlSym: None,
265- xDlClose: None,
266- xRandomness: Some(shim_randomness),
267- xSleep: Some(shim_sleep),
268- xCurrentTime: Some(shim_current_time),
269- xGetLastError: Some(shim_get_last_error),
270- xCurrentTimeInt64: Some(shim_current_time_int64),
271- xSetSystemCall: None,
272- xGetSystemCall: None,
273- xNextSystemCall: None,
274- }));
275- assert_eq!(ffi::sqlite3_vfs_register(vfs, 0), ffi::SQLITE_OK);
276- }
277- });
278-}
279-
280-/// Open `path` through the fault-injection VFS.
281-pub fn open_database(path: &str) -> rusqlite::Result<rusqlite::Connection> {
282- install();
283- rusqlite::Connection::open_with_flags_and_vfs(
284- path,
285- rusqlite::OpenFlags::default(),
286- FAULT_VFS_NAME.to_str().unwrap(),
287- )
288-}
modifiedcrates/celld/fleet.rs+34−5View file
@@ -1,5 +1,8 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3+// Fleet CLI and peer-diagnostic work is outside the Actor-backed World.
4+#![allow(clippy::disallowed_methods)]
5+
36 //! Production bucket deployment adapters reused by the clean-sheet host.
47
58 use crate::bucket::{Bucket, CasVerdict};
@@ -216,7 +219,7 @@
216219
217220 let enumerated = peers.is_empty();
218221 let peers = if enumerated {
219- let peers = diagnostic_node_ids(bucket).await?;
222+ let peers = node_lease_ids(bucket).await?;
220223 println!("ok fleet {} node lease(s) enumerated", peers.len());
221224 peers
222225 } else {
@@ -238,7 +241,7 @@
238241 let mut failures = 0_usize;
239242 let mut expired = 0_usize;
240243 for peer in peers {
241- let node = match diagnostic_node(bucket, &peer).await {
244+ let node = match live_node_lease(bucket, &peer).await {
242245 Ok(Some(node)) => node,
243246 Ok(None) if enumerated => {
244247 expired += 1;
@@ -332,7 +335,10 @@
332335 Ok(())
333336 }
334337
335-async fn diagnostic_node(bucket: &Bucket, peer: &str) -> anyhow::Result<Option<NodeLeaseWire>> {
338+pub(crate) async fn live_node_lease(
339+ bucket: &Bucket,
340+ peer: &str,
341+) -> anyhow::Result<Option<NodeLeaseWire>> {
336342 let key = format!("nodes/{peer}.json");
337343 let node: NodeLeaseWire = serde_json::from_str(&get_string(bucket, &key).await?)
338344 .with_context(|| format!("decode {}://{}/{key}", bucket.scheme(), bucket.name))?;
@@ -351,7 +357,7 @@
351357 Ok(Some(node))
352358 }
353359
354-async fn diagnostic_node_ids(bucket: &Bucket) -> anyhow::Result<Vec<String>> {
360+pub(crate) async fn node_lease_ids(bucket: &Bucket) -> anyhow::Result<Vec<String>> {
355361 let mut nodes = Vec::new();
356362 for object in bucket
357363 .list("nodes/")
@@ -393,7 +399,10 @@
393399 options.endpoint = env("S3_ENDPOINT");
394400 }
395401 if !options.dry_run && options.bucket.is_none() {
396- bail!("celld deploy requires --bucket s3://NAME or gs://NAME (or CELLD_BUCKET)");
402+ bail!(
403+ "celld deploy requires --bucket s3://NAME, gs://NAME or az://CONTAINER \
404+ (or CELLD_BUCKET)"
405+ );
397406 }
398407 let built = deploy::build(&options)?;
399408 built.report();
@@ -522,6 +531,21 @@
522531 let r2_bindings = bindings(&manifest, "r2_bucket")
523532 .filter_map(|binding| binding.get("name")?.as_str().map(str::to_string))
524533 .collect();
534+ // (env name, stable database identity). A Cloudflare database_id survives
535+ // Worker renames and lets several Workers share the resource. A celld-only
536+ // config without one falls back to the database name.
537+ let d1_bindings = bindings(&manifest, "d1")
538+ .filter_map(|binding| {
539+ Some((
540+ binding.get("name")?.as_str()?.to_string(),
541+ binding
542+ .get("database_id")
543+ .or_else(|| binding.get("database_name"))?
544+ .as_str()?
545+ .to_string(),
546+ ))
547+ })
548+ .collect();
525549 let ai_binding = configured_ai_binding(
526550 bindings(&manifest, "ai")
527551 .find_map(|binding| binding.get("name")?.as_str().map(str::to_string)),
@@ -546,6 +570,7 @@
546570 .and_then(crate::assets::AssetResolver::binding_name)
547571 .map(str::to_string);
548572 let script_name = manifest.script_name.clone();
573+ let crons = manifest.crons.clone();
549574 Ok(LoadedDeployment {
550575 options: WorkerConfigOptions {
551576 src,
@@ -553,6 +578,7 @@
553578 do_classes: manifest.do_classes,
554579 bindings: do_bindings,
555580 r2_bindings,
581+ d1_bindings,
556582 ai_binding,
557583 vars,
558584 node,
@@ -563,6 +589,7 @@
563589 asset_binding,
564590 assets,
565591 services,
592+ crons,
566593 })
567594 }
568595
@@ -579,6 +606,8 @@
579606 pub asset_binding: Option<String>,
580607 pub assets: Option<crate::assets::AssetResolver>,
581608 pub services: Vec<(String, String, Option<String>)>,
609+ /// `triggers.crons` from the manifest, driving the reserved cron cell.
610+ pub crons: Vec<String>,
582611 }
583612
584613 fn bindings<'a>(
addedcrates/celld/host_services.rs+209−0View file
@@ -1,0 +1,209 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+#![warn(clippy::disallowed_macros)]
4+
5+//! Process services that an engine incarnation can observe.
6+//!
7+//! Production installs one service set. A deterministic domain installs one
8+//! set per simulated node, so co-hosted incarnations do not share counters or
9+//! host measurements.
10+
11+use crate::ownership_store::LiveLoad;
12+#[cfg(all(test, celld_internal_tests))]
13+use std::collections::BTreeSet;
14+use std::sync::{Arc, Mutex, OnceLock};
15+
16+/// Test-only faults planted in production adapter transitions. Each value is
17+/// scoped to one simulation domain, so parallel corpus tests cannot arm one
18+/// another's teeth.
19+#[cfg(all(test, celld_internal_tests))]
20+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
21+pub enum EngineSabotage {
22+ SuppressResetStop,
23+ CoverTicketEarly,
24+ MisreportGatePosition,
25+ RestoreSupersededEpoch,
26+ FreshCreateOverwrites,
27+ DropCompactionInput,
28+ HideDirtyCell,
29+ DropTimerArm,
30+ IgnoreTookOver,
31+ SkipArmTimeWakePut,
32+ IgnoreAlarmConsumeOnRestore,
33+ SuppressReleasingDecrement,
34+ SkipBucketProofOwnershipRead,
35+ SkipTakeoverInterlock,
36+ SkipBundleCreditRecordRead,
37+ SkipObserveLogEpoch,
38+ ClearShipInFlightEarly,
39+ DeleteUncoveredBundle,
40+ CollectOpenFragment,
41+ GracefulSealUsesCreditedCoverage,
42+ AcceptAppendPastSeal,
43+ FilterRecoveryBundlesByRecordEpoch,
44+ SealAmnesiacWithoutLossRecord,
45+ SkipActivationFenceCas,
46+ SkipAlarmWriteGate,
47+}
48+
49+/// One resource observation used by the pressure path.
50+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
51+pub struct HostMetricsSample {
52+ pub cpu_percent_x100: u64,
53+ pub rss_bytes: u64,
54+ pub in_use_bytes: u64,
55+}
56+
57+enum MetricsBackend {
58+ Production(Mutex<ProcessLoadSampler>),
59+ #[cfg(all(test, celld_internal_tests))]
60+ Scripted(Mutex<HostMetricsSample>),
61+}
62+
63+/// All process-like services owned by one execution domain.
64+pub struct HostServices {
65+ node_load: OnceLock<Arc<LiveLoad>>,
66+ wake_entry: crate::js::WakeEntryService,
67+ websockets: crate::js::WebSocketService,
68+ metrics: MetricsBackend,
69+ #[cfg(all(test, celld_internal_tests))]
70+ sabotages: Mutex<BTreeSet<EngineSabotage>>,
71+}
72+
73+impl HostServices {
74+ pub(crate) fn production() -> Self {
75+ Self {
76+ node_load: OnceLock::new(),
77+ wake_entry: crate::js::WakeEntryService::default(),
78+ websockets: crate::js::WebSocketService::default(),
79+ metrics: MetricsBackend::Production(Mutex::new(ProcessLoadSampler::default())),
80+ #[cfg(all(test, celld_internal_tests))]
81+ sabotages: Mutex::new(BTreeSet::new()),
82+ }
83+ }
84+
85+ #[cfg(all(test, celld_internal_tests))]
86+ pub fn scripted() -> Self {
87+ Self {
88+ node_load: OnceLock::new(),
89+ wake_entry: crate::js::WakeEntryService::default(),
90+ websockets: crate::js::WebSocketService::default(),
91+ metrics: MetricsBackend::Scripted(Mutex::new(HostMetricsSample::default())),
92+ sabotages: Mutex::new(BTreeSet::new()),
93+ }
94+ }
95+
96+ pub fn set_node_load(&self, load: Arc<LiveLoad>) {
97+ let _ = self.node_load.set(load);
98+ }
99+
100+ pub fn node_load(&self) -> Option<Arc<LiveLoad>> {
101+ self.node_load.get().cloned()
102+ }
103+
104+ pub(crate) fn wake_entry(&self) -> &crate::js::WakeEntryService {
105+ &self.wake_entry
106+ }
107+
108+ pub(crate) fn websockets(&self) -> &crate::js::WebSocketService {
109+ &self.websockets
110+ }
111+
112+ pub fn sample_metrics(&self) -> HostMetricsSample {
113+ match &self.metrics {
114+ MetricsBackend::Production(sampler) => {
115+ let mut sampler = sampler.lock().unwrap();
116+ let memory = crate::memory::sample();
117+ HostMetricsSample {
118+ cpu_percent_x100: sampler.sample_cpu_percent_x100(),
119+ rss_bytes: memory.rss_bytes,
120+ in_use_bytes: memory.in_use_bytes,
121+ }
122+ }
123+ #[cfg(all(test, celld_internal_tests))]
124+ MetricsBackend::Scripted(sample) => *sample.lock().unwrap(),
125+ }
126+ }
127+
128+ #[cfg(all(test, celld_internal_tests))]
129+ pub fn set_scripted_metrics(&self, sample: HostMetricsSample) {
130+ let MetricsBackend::Scripted(current) = &self.metrics else {
131+ panic!("scripted metrics require a simulation HostServices instance");
132+ };
133+ *current.lock().unwrap() = sample;
134+ }
135+
136+ #[cfg(all(test, celld_internal_tests))]
137+ pub fn arm_sabotage(&self, sabotage: EngineSabotage) {
138+ self.sabotages.lock().unwrap().insert(sabotage);
139+ }
140+
141+ #[cfg(all(test, celld_internal_tests))]
142+ pub(crate) fn sabotage_active(&self, sabotage: EngineSabotage) -> bool {
143+ self.sabotages.lock().unwrap().contains(&sabotage)
144+ }
145+}
146+
147+#[derive(Default)]
148+struct ProcessLoadSampler {
149+ previous_cpu_ticks: Option<u64>,
150+ previous_sample: Option<std::time::Instant>,
151+}
152+
153+impl ProcessLoadSampler {
154+ // This is the production metrics arm. A simulation HostServices returns a
155+ // scripted sample and never calls this host-clock sampler.
156+ #[allow(clippy::disallowed_methods)]
157+ fn sample_cpu_percent_x100(&mut self) -> u64 {
158+ let Some(ticks) = process_cpu_ticks() else {
159+ return 0;
160+ };
161+ let now = std::time::Instant::now();
162+ let value = match (self.previous_cpu_ticks, self.previous_sample) {
163+ (Some(previous_ticks), Some(previous_sample)) => {
164+ let elapsed = previous_sample.elapsed().as_secs_f64();
165+ let ticks_per_second = clock_ticks_per_second() as f64;
166+ if elapsed > 0.0 && ticks_per_second > 0.0 {
167+ (((ticks.saturating_sub(previous_ticks)) as f64 / ticks_per_second / elapsed)
168+ * 10_000.0) as u64
169+ } else {
170+ 0
171+ }
172+ }
173+ _ => 0,
174+ };
175+ self.previous_cpu_ticks = Some(ticks);
176+ self.previous_sample = Some(now);
177+ value
178+ }
179+}
180+
181+#[cfg(target_os = "linux")]
182+#[allow(clippy::disallowed_methods)] // `/proc` is host telemetry, not node storage.
183+fn process_cpu_ticks() -> Option<u64> {
184+ let stat = std::fs::read_to_string("/proc/self/stat").ok()?;
185+ let fields = stat
186+ .get(stat.rfind(')')? + 2..)?
187+ .split_whitespace()
188+ .collect::<Vec<_>>();
189+ Some(fields.get(11)?.parse::<u64>().ok()? + fields.get(12)?.parse::<u64>().ok()?)
190+}
191+
192+#[cfg(not(target_os = "linux"))]
193+fn process_cpu_ticks() -> Option<u64> {
194+ None
195+}
196+
197+#[cfg(unix)]
198+fn clock_ticks_per_second() -> u64 {
199+ let ticks = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
200+ u64::try_from(ticks)
201+ .ok()
202+ .filter(|ticks| *ticks > 0)
203+ .unwrap_or(100)
204+}
205+
206+#[cfg(not(unix))]
207+fn clock_ticks_per_second() -> u64 {
208+ 100
209+}
modifiedcrates/celld/js.rs+677−122View file
@@ -1,5 +1,13 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3+// The raw V8 adapter and its child modules remain outside the World. The
4+// Actor-reachable wake and WebSocket state is injected through HostServices.
5+#![allow(
6+ clippy::disallowed_macros,
7+ clippy::disallowed_methods,
8+ clippy::disallowed_types
9+)]
10+
311 //! The JS engine: rusty_v8 directly. One isolate per cell.
412 //!
513 //! This slice runs actual Durable Objects: the worker's default-export `fetch`
@@ -20,6 +28,50 @@
2028 use std::time::{Duration, Instant};
2129 use v8::{ValueDeserializerHelper, ValueSerializerHelper};
2230
31+/// Bare Node builtin specifiers that the bundler leaves for the runtime.
32+/// Root entries also match subpaths in esbuild and in module resolution.
33+pub(crate) const BARE_NODE_BUILTINS: &[&str] = &[
34+ "assert",
35+ "async_hooks",
36+ "buffer",
37+ "child_process",
38+ "cluster",
39+ "constants",
40+ "crypto",
41+ "dgram",
42+ "diagnostics_channel",
43+ "dns",
44+ "events",
45+ "fs",
46+ "fs/promises",
47+ "http",
48+ "http2",
49+ "https",
50+ "inspector",
51+ "module",
52+ "net",
53+ "os",
54+ "path",
55+ "perf_hooks",
56+ "process",
57+ "punycode",
58+ "querystring",
59+ "readline",
60+ "sqlite",
61+ "stream",
62+ "string_decoder",
63+ "timers",
64+ "tls",
65+ "tty",
66+ "url",
67+ "util",
68+ "util/types",
69+ "v8",
70+ "vm",
71+ "worker_threads",
72+ "zlib",
73+];
74+
2375 /// The pending exception text from a TryCatch scope (a macro so it needs no
2476 /// bound on the crate-private scope traits).
2577 macro_rules! exc {
@@ -182,12 +234,11 @@
182234 /// An output-gate request for the co-hosted (same-isolate) Durable Object fast
183235 /// path. That path runs a resident DO's `fetch` inline, bypassing
184236 /// `dispatch_do_call` where the gate lives; the inline handler samples the
185-/// cell's committed-write position and, on a write, asks the actor to hold the
186-/// inline response here until the cell is durable. `position` is the sampled
187-/// committed-write position (the same signal the routed gate uses).
237+/// cell's committed-write position and asks the actor whether the response can
238+/// leave. `position` is present for a write and absent for a read.
188239 pub struct GateReq {
189240 pub scope: String,
190- pub position: u64,
241+ pub position: Option<u64>,
191242 pub reply: tokio::sync::oneshot::Sender<Result<(), celld_logic::RequestError>>,
192243 }
193244 static GATE_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<GateReq>> = OnceLock::new();
@@ -264,14 +315,26 @@
264315 pub bucket: crate::bucket::Bucket,
265316 pub flusher: Arc<crate::wake::WakeFlusher>,
266317 }
267-static ARM_GATE: OnceLock<ArmGate> = OnceLock::new();
318+
319+type ArmGateRx = tokio::sync::oneshot::Receiver<Result<(), String>>;
320+
321+#[derive(Default)]
322+pub(crate) struct WakeEntryService {
323+ gate: OnceLock<ArmGate>,
324+ pending: Mutex<HashMap<String, Vec<ArmGateRx>>>,
325+}
326+
268327 pub fn set_arm_gate(gate: ArmGate) {
269- let _ = ARM_GATE.set(gate);
328+ let _ = asyncrt::services().wake_entry().gate.set(gate);
270329 }
271330
272331 /// Whether this node still holds a wake entry for `cell`.
273332 pub fn wake_entry_tracked(cell: &str) -> bool {
274- ARM_GATE.get().is_some_and(|gate| gate.flusher.tracks(cell))
333+ asyncrt::services()
334+ .wake_entry()
335+ .gate
336+ .get()
337+ .is_some_and(|gate| gate.flusher.tracks(cell))
275338 }
276339
277340 /// Drop this node's belief about `cell`'s wake entry — the cell fenced or
@@ -279,7 +342,8 @@
279342 /// Defined since the wake audit and now actually called (it was dead code,
280343 /// which meant a node that lost a cell kept believing in its entry).
281344 pub fn forget_wake_entry(cell: &str) {
282- if let Some(gate) = ARM_GATE.get() {
345+ let services = asyncrt::services();
346+ if let Some(gate) = services.wake_entry().gate.get() {
283347 gate.flusher.forget(cell);
284348 }
285349 }
@@ -287,7 +351,8 @@
287351 /// Adopt the wake entry a restored alarm implies, so consuming that alarm
288352 /// deletes it rather than orphaning it.
289353 pub fn adopt_wake_entry(cell: &str, at_ms: i64) {
290- if let Some(gate) = ARM_GATE.get() {
354+ let services = asyncrt::services();
355+ if let Some(gate) = services.wake_entry().gate.get() {
291356 gate.flusher.adopt(cell, at_ms);
292357 }
293358 }
@@ -301,7 +366,8 @@
301366 /// while the commit that consumed the alarm is still only local would lose
302367 /// both the alarm and the record that could have revived it.
303368 pub async fn reconcile_wake_entry(cell: &str, next_alarm_ms: i64, consume_durable: bool) {
304- let Some(gate) = ARM_GATE.get() else {
369+ let services = asyncrt::services();
370+ let Some(gate) = services.wake_entry().gate.get() else {
305371 return;
306372 };
307373 gate.flusher
@@ -309,24 +375,25 @@
309375 .await;
310376 }
311377
312-type ArmGateRx = tokio::sync::oneshot::Receiver<Result<(), String>>;
313-static PENDING_ARM_GATES: OnceLock<Mutex<HashMap<String, Vec<ArmGateRx>>>> = OnceLock::new();
314-fn pending_arm_gates() -> &'static Mutex<HashMap<String, Vec<ArmGateRx>>> {
315- PENDING_ARM_GATES.get_or_init(Default::default)
316-}
317-
318378 /// A committed alarm tightened the durable wake bound: launch the entry PUT
319379 /// and register it against the cell's output gate. No-op when the bound
320380 /// already covers it or no gate is configured (unit tests).
321381 fn spawn_arm_gate(cell: &str, at_ms: i64) {
322- let Some(gate) = ARM_GATE.get() else { return };
382+ #[cfg(all(test, celld_internal_tests))]
383+ if asyncrt::sabotage_active(crate::host_services::EngineSabotage::SkipArmTimeWakePut) {
384+ return;
385+ }
386+ let services = asyncrt::services();
387+ let Some(gate) = services.wake_entry().gate.get() else {
388+ return;
389+ };
323390 let Some(celld_logic::wake::Op::Put { key, due_ms }) = gate.flusher.arm_op(cell, at_ms) else {
324391 return;
325392 };
326393 let cell_ = cell.to_string();
327394 let (tx, rx) = tokio::sync::oneshot::channel();
328395 {
329- let mut pending = pending_arm_gates().lock().unwrap();
396+ let mut pending = services.wake_entry().pending.lock().unwrap();
330397 let gates = pending.entry(cell_.clone()).or_default();
331398 // Arms with no response edge to drain them (alarm handlers,
332399 // WebSocket events) must not accumulate: drop already-settled gates.
@@ -338,13 +405,15 @@
338405 });
339406 gates.push(rx);
340407 }
341- asyncrt::op_handle().spawn(async move {
342- let gate = ARM_GATE.get().unwrap();
343- // The core may have demanded this PUT because the tracked entry's
344- // consume-delete is already on the wire; the PUT must land after
345- // that delete, not race it (S3 orders concurrent same-key writes
346- // arbitrarily).
347- gate.flusher.await_no_inflight_delete(&cell_).await;
408+ asyncrt::spawn(async move {
409+ let gate = services.wake_entry().gate.get().unwrap();
410+ // A delete of this exact key may already be on the wire — the tracked
411+ // entry's consume-delete, or the move-delete of a key this arm is
412+ // about to re-PUT. Either way the PUT must land after that delete,
413+ // not race it (S3 orders concurrent same-key writes arbitrarily).
414+ // Deletes of the cell's OTHER keys cannot touch this PUT, and waiting
415+ // on them would hold the response behind unrelated store latency.
416+ gate.flusher.await_key_deletable(&cell_, &key).await;
348417 let body = format!("{{\"cell\":{cell_:?},\"due_ms\":{due_ms}}}");
349418 let result = gate
350419 .bucket
@@ -353,15 +422,22 @@
353422 .map(|_| gate.flusher.confirm_arm(&cell_, due_ms, key))
354423 .map_err(|e| format!("setAlarm wake entry: {e}"));
355424 let _ = tx.send(result);
356- });
425+ })
426+ .detach();
357427 }
358428
429+#[cfg(all(test, celld_internal_tests))]
430+pub(crate) fn spawn_arm_gate_for_test(cell: &str, at_ms: i64) {
431+ spawn_arm_gate(cell, at_ms);
432+}
433+
359434 /// Await the cell's pending wake-entry PUTs — the output-gate drain a
360435 /// response edge performs before releasing its reply. An error means an arm
361436 /// the response would acknowledge is not durably covered; the caller must
362437 /// fail the response rather than lie (the flusher retries the entry).
363438 pub async fn drain_arm_gates(cell: &str) -> Result<(), String> {
364- let gates = pending_arm_gates().lock().unwrap().remove(cell);
439+ let services = asyncrt::services();
440+ let gates = services.wake_entry().pending.lock().unwrap().remove(cell);
365441 let Some(gates) = gates else { return Ok(()) };
366442 for gate in gates {
367443 match gate.await {
@@ -479,6 +555,12 @@
479555 /// A `fetch()` upgrade wants the whole handshake outcome, including the
480556 /// ordinary response a server that declines to upgrade sent instead.
481557 pub want_response: bool,
558+ /// A socket already upgraded in this process, which this request joins
559+ /// instead of dialing `url`. It is the cell end of a Durable Object
560+ /// subrequest whose caller kept the client end, so there is no handshake
561+ /// to run and no connection to open: the host only has to carry frames
562+ /// between two isolates.
563+ pub target: Option<WsTarget>,
482564 pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>,
483565 }
484566
@@ -508,6 +590,13 @@
508590 TIMER_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
509591 }
510592 static NEXT_HTTP_STREAM_ID: AtomicU64 = AtomicU64::new(1);
593+/// What `__http_stream_read` resolves with at end of stream.
594+///
595+/// The reader identifies the end by type, not by value. A chunk always
596+/// resolves as a `Uint8Array`, therefore body bytes can never look like
597+/// this marker. The value stays distinctive, so a reader that does compare
598+/// the value cannot match a plausible body.
599+const HTTP_STREAM_DONE: &str = "__celld_http_stream_end__";
511600 enum HttpStreamSource {
512601 Response(reqwest::Response),
513602 Receiver(tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>),
@@ -564,7 +653,8 @@
564653 /// Encode a host response for the JS side. A text body crosses as a
565654 /// JS string (cheap, lossless), binary as a byte array, and a streaming body
566655 /// by id — serializing a Vec<u8> as a JSON number array is the dominant cost
567-/// for real DO responses. `ws_target` is carried only by the DO path.
656+/// for real DO responses. `ws_target` is carried by the paths that can answer
657+/// with a WebSocket upgrade: a Durable Object call and a service-binding call.
568658 fn encode_http_response(mut response: HttpResponse, ws_target: bool) -> String {
569659 let mut obj = serde_json::json!({
570660 "status": response.status,
@@ -722,6 +812,7 @@
722812 }
723813
724814 mod websocket;
815+pub(crate) use websocket::WebSocketService;
725816 pub use websocket::*;
726817 use websocket::{ws_capture_begin, ws_capture_take};
727818
@@ -743,28 +834,74 @@
743834 EgressGateScope
744835 }
745836
746-/// What an outbound effect must wait for, if the running handler has written
747-/// anything this event. `None` means there is nothing outstanding and the
748-/// effect may go straight out -- the ordinary read-only case, which must not
749-/// pay a durability round trip.
750-fn egress_gate_pending() -> Option<(String, u64)> {
837+/// What an outbound effect must trail before it leaves the process.
838+///
839+/// The three cases are named rather than nested inside one another because
840+/// two of them once shared a representation, and that is what issue #144 was:
841+/// a reader that starts after another request committed samples the new
842+/// position as its own baseline and advances nothing, so a two-state gate read
843+/// it as code that owns no cell at all and let its side effect out ungated.
844+/// A variant per case makes the distinction one the compiler keeps.
845+enum EgressGate {
846+ /// No cell event is running. Stateless Worker code owns no cell state, so
847+ /// its egress reveals nothing that can still be lost and leaves directly.
848+ NoCell,
849+ /// This event wrote through the position. The effect waits for that write.
850+ Wrote(String, u64),
851+ /// A read-only output. It reveals whatever the cell holds, so it trails
852+ /// the newest write barrier still open on the cell. Only the core knows
853+ /// which writes are outstanding, so this asks rather than guesses.
854+ ReadOnly(String),
855+}
856+
857+impl EgressGate {
858+ /// Whether the effect must consult the gate before it leaves. True for a
859+ /// read as well as a write: a read whose cell has no barrier is released
860+ /// at once, but only the core can say so.
861+ fn is_gated(&self) -> bool {
862+ !matches!(self, EgressGate::NoCell)
863+ }
864+}
865+
866+/// Sample what the running handler's outbound effects must trail. Answers for
867+/// every active cell event, including a read whose core lookup can settle
868+/// immediately.
869+fn egress_gate_request() -> EgressGate {
751870 let context = current_context();
752871 let stack = context.egress.lock().unwrap();
753- let (cell, before) = stack.last()?;
754- let position = storage::write_position(cell)?;
755- (position > *before).then(|| (cell.clone(), position))
872+ let Some((cell, before)) = stack.last() else {
873+ return EgressGate::NoCell;
874+ };
875+ match storage::write_position(cell).filter(|position| position > before) {
876+ Some(position) => EgressGate::Wrote(cell.clone(), position),
877+ // A read-only output in a process that configured no output gate has
878+ // nothing to trail. Such a process cannot acknowledge a write either
879+ // -- `op_gate_write` refuses one for want of the same channel -- so no
880+ // committed-but-unproven write exists for a read to reveal. Answer as
881+ // if no cell event were running, which keeps the effect on the direct,
882+ // synchronous path it has always taken; a WebSocket frame in
883+ // particular must not join a deferred queue whose flush needs a gate
884+ // to release it. A write still takes a ticket and still fails closed.
885+ None if GATE_TX.get().is_none() => EgressGate::NoCell,
886+ None => EgressGate::ReadOnly(cell.clone()),
887+ }
756888 }
757889
758-/// Wait for the cell's outstanding write to be proven durable before an
759-/// outbound effect leaves the process.
890+/// Wait for the writes an outbound effect can reveal to be proven durable
891+/// before it leaves the process.
760892 ///
761893 /// This is the output gate applied to egress rather than to the response.
762894 /// It cannot deadlock the handler that is awaiting it: the ticket is served by
763895 /// `dispatch_gate` on the host's own loop and resolved by the replicator's
764896 /// independent task, neither of which needs the isolate's event loop to run.
765-async fn await_egress_gate(pending: Option<(String, u64)>) -> std::result::Result<(), String> {
766- let Some((cell, position)) = pending else {
767- return Ok(());
897+/// A read-only ticket carries `None` and the core releases it at once when the
898+/// cell has no barrier open, so an ordinary read pays one actor hop and no
899+/// replica write.
900+async fn await_egress_gate(gate: EgressGate) -> std::result::Result<(), String> {
901+ let (cell, position) = match gate {
902+ EgressGate::NoCell => return Ok(()),
903+ EgressGate::Wrote(cell, position) => (cell, Some(position)),
904+ EgressGate::ReadOnly(cell) => (cell, None),
768905 };
769906 let (tx, receive) = tokio::sync::oneshot::channel();
770907 let sent = GATE_TX
@@ -798,7 +935,7 @@
798935 /// leave first -- the request would already be on its way while the caller
799936 /// waited for a durability answer that no longer decides anything.
800937 async fn gated_channel_send<T>(
801- gate: Option<(String, u64)>,
938+ gate: EgressGate,
802939 channel: &'static OnceLock<tokio::sync::mpsc::UnboundedSender<T>>,
803940 request: T,
804941 missing: &'static str,
@@ -1128,6 +1265,9 @@
11281265 do_classes: Vec<String>,
11291266 bindings: Vec<(String, String)>,
11301267 r2_bindings: Vec<String>,
1268+ /// `d1_databases`: (environment name, stable database identity). The
1269+ /// identity addresses the cell that holds the database; see [[d1]].
1270+ d1_bindings: Vec<(String, String)>,
11311271 ai_binding: Option<String>,
11321272 vars: Vec<(String, String)>,
11331273 node: String,
@@ -1146,6 +1286,9 @@
11461286 /// Extra `env` values a loaded worker was handed, as a JSON object string
11471287 /// merged onto its `env`. Loader-only; empty for normal workers.
11481288 loader_env: Option<String>,
1289+ /// `triggers.crons` from the deployment. Empty for a loaded worker and for
1290+ /// any script without cron triggers.
1291+ pub crons: Vec<String>,
11491292 }
11501293
11511294 pub struct WorkerConfigOptions {
@@ -1154,6 +1297,7 @@
11541297 pub do_classes: Vec<String>,
11551298 pub bindings: Vec<(String, String)>,
11561299 pub r2_bindings: Vec<String>,
1300+ pub d1_bindings: Vec<(String, String)>,
11571301 pub ai_binding: Option<String>,
11581302 pub vars: Vec<(String, String)>,
11591303 pub node: String,
@@ -1169,6 +1313,7 @@
11691313 do_classes,
11701314 bindings,
11711315 r2_bindings,
1316+ d1_bindings,
11721317 ai_binding,
11731318 vars,
11741319 node,
@@ -1181,6 +1326,7 @@
11811326 do_classes,
11821327 bindings,
11831328 r2_bindings,
1329+ d1_bindings,
11841330 ai_binding,
11851331 vars,
11861332 node,
@@ -1191,9 +1337,16 @@
11911337 loader_binding: None,
11921338 egress: EgressPolicy::Allow,
11931339 loader_env: None,
1340+ crons: Vec::new(),
11941341 }
11951342 }
11961343
1344+ /// Give this Worker the deployment's cron trigger expressions.
1345+ pub fn with_crons(mut self, crons: Vec<String>) -> Self {
1346+ self.crons = crons;
1347+ self
1348+ }
1349+
11971350 /// Grant this Worker a Worker Loader binding at `env` name `binding`.
11981351 pub fn with_loader(mut self, binding: Option<String>) -> Self {
11991352 self.loader_binding = binding;
@@ -1279,6 +1432,49 @@
12791432 (self.isolate.lock(), self.cells.install())
12801433 }
12811434
1435+ /// Lift condemnation from an isolate whose heap has drained.
1436+ ///
1437+ /// `near_heap_limit` latches a flag that nothing used to clear, so a cell
1438+ /// that reached its limit once stayed condemned until the process
1439+ /// restarted. The flag is re-read here, between turns rather than inside
1440+ /// one, because a handler must not see the isolate recover halfway
1441+ /// through.
1442+ ///
1443+ /// A heap still over the line buys one `low_memory_notification` and a
1444+ /// second reading. V8 stops collecting once it is past the limit, so a
1445+ /// drained isolate holds the dead heap until something allocates again —
1446+ /// without the forced collection the reading that decides recovery is a
1447+ /// reading of garbage. `HEAP_GC_NUDGE_INTERVAL` bounds the cost.
1448+ ///
1449+ /// Removing the callback with the original limit puts back the limit
1450+ /// `near_heap_limit` raised; re-adding it re-arms the guard.
1451+ fn recover_heap(&self, locker: &mut v8::Locker<'_>) {
1452+ let Some(state) = locker.get_slot::<Arc<HeapLimitState>>().cloned() else {
1453+ return;
1454+ };
1455+ if !state.excessively_exceeded.load(Ordering::Relaxed) {
1456+ return;
1457+ }
1458+ if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE {
1459+ if !state.due_for_gc_nudge() {
1460+ return;
1461+ }
1462+ locker.low_memory_notification();
1463+ if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE {
1464+ return;
1465+ }
1466+ }
1467+ state.excessively_exceeded.store(false, Ordering::Relaxed);
1468+ let data = Arc::as_ptr(&state) as *mut HeapLimitState as *mut std::ffi::c_void;
1469+ locker.remove_near_heap_limit_callback(near_heap_limit, state.limit);
1470+ locker.add_near_heap_limit_callback(near_heap_limit, data);
1471+ tracing::info!(
1472+ event = "isolate_heap_recovered",
1473+ limit_bytes = state.limit,
1474+ "isolate heap fell back under its limit, so it serves again"
1475+ );
1476+ }
1477+
12821478 /// Localise the realm for one turn.
12831479 ///
12841480 /// **Taking the scope is the point.** Reaching a realm means touching
@@ -1321,11 +1517,66 @@
13211517 const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024;
13221518 const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024;
13231519
1324-#[derive(Default)]
1520+/// Share of the heap limit past which an isolate takes on no more retained
1521+/// state. It sits below the near-limit callback on purpose: this refuses one
1522+/// hibernatable socket while the isolate still works, where the callback
1523+/// fires once it no longer does.
1524+const HEAP_ADMISSION_SHARE: f64 = 0.9;
1525+
1526+/// Share of the heap limit under which a condemned isolate is condemned no
1527+/// more. Under `HEAP_ADMISSION_SHARE` by enough that recovery does not
1528+/// immediately re-admit into a heap that is about to fail again.
1529+const HEAP_RECOVERY_SHARE: f64 = 0.75;
1530+
1531+/// The shortest gap between two collections forced by `recover_heap`. A full
1532+/// collection of a 128 MB heap costs tens of milliseconds and a loaded cell
1533+/// begins many turns each second, so an unbounded nudge would spend more of a
1534+/// condemned isolate on collecting than on serving.
1535+const HEAP_GC_NUDGE_INTERVAL: Duration = Duration::from_secs(1);
1536+
13251537 struct HeapLimitState {
13261538 excessively_exceeded: AtomicBool,
1539+ /// The limit V8 gave this isolate, before any emergency extension.
1540+ /// Recovery measures against this one because `near_heap_limit` raises
1541+ /// the current one.
1542+ limit: usize,
1543+ last_gc_nudge: Mutex<Option<Instant>>,
1544+ /// Test-only: a real heap over the admission share is unreachable from a
1545+ /// test, and the condemnation flag cannot stand in for it because
1546+ /// recovery clears that one at the next turn.
1547+ #[cfg(all(test, celld_internal_tests))]
1548+ forced_admission_refusal: AtomicBool,
13271549 }
13281550
1551+impl HeapLimitState {
1552+ /// Whether a condemned isolate can pay for another forced collection.
1553+ ///
1554+ /// Rate-limited rather than once for each condemnation: the load can
1555+ /// still be live at the first reading and gone by the second, so a
1556+ /// one-shot nudge would leave the cell condemned exactly as before.
1557+ fn due_for_gc_nudge(&self) -> bool {
1558+ let Ok(mut last) = self.last_gc_nudge.lock() else {
1559+ return false;
1560+ };
1561+ let now = Instant::now();
1562+ if last.is_some_and(|at| now.duration_since(at) < HEAP_GC_NUDGE_INTERVAL) {
1563+ return false;
1564+ }
1565+ *last = Some(now);
1566+ true
1567+ }
1568+}
1569+
1570+#[cfg(all(test, celld_internal_tests))]
1571+fn admission_refusal_forced(state: &HeapLimitState) -> bool {
1572+ state.forced_admission_refusal.load(Ordering::Relaxed)
1573+}
1574+
1575+#[cfg(not(all(test, celld_internal_tests)))]
1576+fn admission_refusal_forced(_state: &HeapLimitState) -> bool {
1577+ false
1578+}
1579+
13291580 type SerializedPut = (String, Vec<u8>);
13301581 type PendingPuts = HashMap<String, Vec<SerializedPut>>;
13311582
@@ -1433,9 +1684,27 @@
14331684 state.excessively_exceeded.store(true, Ordering::Relaxed);
14341685 // V8 fatally aborts the process if a near-limit callback does not extend
14351686 // the limit. This reserve lets JS observe condemnation and unwind.
1436- current_heap_limit.saturating_add(V8_HEAP_EMERGENCY_BYTES)
1687+ //
1688+ // The extension must also cover one allocation as large as the limit
1689+ // itself: flattening a 128 MiB cons string asks V8 for a single 128 MiB
1690+ // block, and V8 re-invokes this callback across last-resort GC rounds
1691+ // only unreliably (under parallel load it often stops after one round
1692+ // and aborts the process). Doubling the original limit makes the first
1693+ // invocation sufficient on its own; `recover_heap` and `Drop` still
1694+ // restore the original limit, so nothing else changes.
1695+ current_heap_limit
1696+ .saturating_add(V8_HEAP_EMERGENCY_BYTES)
1697+ .max(state.limit.saturating_mul(2))
14371698 }
14381699
1700+/// Live heap use, as a share of `limit`.
1701+fn heap_share(isolate: &mut v8::Isolate, limit: usize) -> f64 {
1702+ if limit == 0 {
1703+ return 0.0;
1704+ }
1705+ isolate.get_heap_statistics().used_heap_size() as f64 / limit as f64
1706+}
1707+
14391708 fn v8_heap_limit_bytes() -> usize {
14401709 crate::env_vars::positive::<usize>("CELLD_V8_HEAP_LIMIT_MB")
14411710 .expect("validated CELLD_V8_HEAP_LIMIT_MB")
@@ -1867,6 +2136,7 @@
18672136 return (None, Vec::new());
18682137 };
18692138 let (mut locker, _cells) = inner.lock();
2139+ inner.recover_heap(&mut locker);
18702140 v8::scope!(let hs, &mut *locker);
18712141 let realm = inner.realm(hs);
18722142 let context = realm.context;
@@ -2631,13 +2901,13 @@
26312901 fetch: v8::Local<'s, v8::Function>,
26322902 url: &str,
26332903 method: &str,
2634- body: &[u8],
2904+ body: &RequestBody,
26352905 headers: &[(String, String)],
26362906 request_id: Option<RequestId>,
26372907 ) -> Result<Started<'s>> {
26382908 let req = match request_id {
26392909 Some(_) => make_incoming_request(tc, url, method, body, headers),
2640- None => make_request(tc, url, method, body, headers),
2910+ None => make_request(tc, url, method, body.bytes(), headers),
26412911 }?;
26422912 let env = harness_env(tc)?;
26432913 let recv = v8::undefined(tc).into();
@@ -2714,7 +2984,13 @@
27142984 // Dynamic `import()` of builtin specifiers; per-import()-call only.
27152985 isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically);
27162986 let original_heap_limit = isolate.get_heap_statistics().heap_size_limit();
2717- let heap_limit_state = Arc::new(HeapLimitState::default());
2987+ let heap_limit_state = Arc::new(HeapLimitState {
2988+ excessively_exceeded: AtomicBool::new(false),
2989+ limit: original_heap_limit,
2990+ last_gc_nudge: Mutex::new(None),
2991+ #[cfg(all(test, celld_internal_tests))]
2992+ forced_admission_refusal: AtomicBool::new(false),
2993+ });
27182994 let runtime_state = Arc::new(ActorRuntimeState {
27192995 promises: std::sync::Mutex::new(PromiseMap::new()),
27202996 egress: config.egress,
@@ -2790,6 +3066,13 @@
27903066
27913067 // register each exported DO class into the harness registry
27923068 for cn in do_classes {
3069+ // The D1 class is the runtime's own and is never a worker
3070+ // export. It is in `do_classes` so that it gets a namespace
3071+ // key; reading it off the module namespace would find
3072+ // `undefined` and overwrite the harness's registration.
3073+ if cn == crate::deploy::D1_CLASS {
3074+ continue;
3075+ }
27933076 let key = v8::String::new(scope, cn).unwrap();
27943077 let cls = ns
27953078 .get(scope, key.into())
@@ -2797,6 +3080,7 @@
27973080 register_class(scope, cn, cls)?;
27983081 }
27993082 inject_namespace_keys(scope, script_name, do_classes)?;
3083+ inject_crons(scope, &config.crons)?;
28003084 populate_cf_exports(scope, ns, do_classes)?;
28013085 register_entrypoints(scope, ns)?;
28023086 // build env from bindings and stash it in the harness
@@ -2986,6 +3270,7 @@
29863270 return (None, Vec::new());
29873271 };
29883272 let (mut locker, _cells) = inner.lock();
3273+ inner.recover_heap(&mut locker);
29893274 v8::scope!(let hs, &mut *locker);
29903275 let realm = inner.realm(hs);
29913276 let context = realm.context;
@@ -3071,6 +3356,7 @@
30713356 ops! { scope, global,
30723357 "__heap_limit_excessively_exceeded" =>
30733358 op_heap_limit_excessively_exceeded,
3359+ "__heap_over_admission_share" => op_heap_over_admission_share,
30743360 "__ws_send" => websocket::op_ws_send,
30753361 "__ws_send_binary" => websocket::op_ws_send_binary,
30763362 "__ws_close" => websocket::op_ws_close,
@@ -3083,6 +3369,7 @@
30833369 "__ws_auto_response_get" => websocket::op_ws_auto_response_get,
30843370 "__ws_auto_response_ts" => websocket::op_ws_auto_response_ts,
30853371 "__ws_connect" => websocket::op_ws_connect,
3372+ "__ws_bind_target" => websocket::op_ws_bind_target,
30863373 "__ws_next" => websocket::op_ws_next,
30873374 "__ws_upgrade" => websocket::op_ws_upgrade,
30883375 "__storage_get" => storage_ops::op_storage_get,
@@ -3093,6 +3380,7 @@
30933380 "__sql_cursor_next" => storage_ops::op_sql_cursor_next,
30943381 "__sql_cursor_close" => storage_ops::op_sql_cursor_close,
30953382 "__sql_database_size" => storage_ops::op_sql_database_size,
3383+ "__d1_run" => storage_ops::op_d1_run,
30963384 "__storage_transaction_control" => storage_ops::op_storage_transaction_control,
30973385 "__log" => op_log,
30983386 "__storage_put" => storage_ops::op_storage_put,
@@ -3104,6 +3392,7 @@
31043392 "__storage_flush_pending_puts" => storage_ops::op_storage_flush_pending_puts,
31053393 "__storage_cancel_pending_puts" => storage_ops::op_storage_cancel_pending_puts,
31063394 "__actor_abort" => op_actor_abort,
3395+ "__cron_plan" => op_cron_plan,
31073396 "__process_exit" => op_process_exit,
31083397 "__storage_delete" => storage_ops::op_storage_delete,
31093398 "__storage_delete_many" => storage_ops::op_storage_delete_many,
@@ -3119,6 +3408,7 @@
31193408 "$$textDecoderLabel" => op_text_decoder_label,
31203409 "$$textDecoderNew" => op_text_decoder_new,
31213410 "$$textDecoderDecode" => op_text_decoder_decode,
3411+ "$$textDecoderDecodeOnce" => op_text_decoder_decode_once,
31223412 "$$textDecoderFree" => op_text_decoder_free,
31233413 "__alarm_set" => op_alarm_set,
31243414 "__alarm_get" => op_alarm_get,
@@ -3188,6 +3478,9 @@
31883478 "__loader_count" => op_loader_count,
31893479 "__test_set_heap_limit_excessively_exceeded" =>
31903480 op_test_set_heap_limit_excessively_exceeded,
3481+ "__test_force_heap_admission_refusal" =>
3482+ op_test_force_heap_admission_refusal,
3483+ "__test_heap_share" => op_test_heap_share,
31913484 "__sql_set_max_page_count_for_test" =>
31923485 storage_ops::op_sql_set_max_page_count_for_test,
31933486 "__sql_set_write_fault_for_test" => storage_ops::op_sql_set_write_fault_for_test,
@@ -3222,7 +3515,7 @@
32223515 let method = args.get(2).to_rust_string_lossy(scope);
32233516 let call_args = view_bytes(args.get(3)).unwrap_or_default();
32243517 let (tx, rx) = tokio::sync::oneshot::channel();
3225- let gate = egress_gate_pending();
3518+ let gate = egress_gate_request();
32263519 let request = SvcRpcReq {
32273520 script,
32283521 entrypoint,
@@ -3290,7 +3583,7 @@
32903583 } else {
32913584 (None, None, None)
32923585 };
3293- let gate = egress_gate_pending();
3586+ let gate = egress_gate_request();
32943587 let request = SvcCallReq {
32953588 cancel,
32963589 script,
@@ -3304,7 +3597,7 @@
33043597 let mut cancel_guard = cancel_guard;
33053598 gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?;
33063599 let result = match rx.await {
3307- Ok(Ok(response)) => Ok(encode_http_response(response, false)),
3600+ Ok(Ok(response)) => Ok(encode_http_response(response, true)),
33083601 Ok(Err(error)) => Err(format!("{error}")),
33093602 Err(error) => Err(format!("service dropped: {error}")),
33103603 };
@@ -3525,6 +3818,9 @@
35253818 do_classes: Vec::new(),
35263819 bindings: Vec::new(),
35273820 r2_bindings: Vec::new(),
3821+ // A loaded worker reaches D1 only if its parent injects a stub;
3822+ // ambient bindings are exactly what Code Mode withholds.
3823+ d1_bindings: Vec::new(),
35283824 ai_binding: None,
35293825 vars: Vec::new(),
35303826 node: String::new(),
@@ -3576,7 +3872,7 @@
35763872 queued_at: Instant::now(),
35773873 url,
35783874 method,
3579- body,
3875+ body: body.into(),
35803876 headers,
35813877 request_id: None,
35823878 reply,
@@ -3649,17 +3945,6 @@
36493945 }
36503946 }
36513947
3652-/// `__loader_count()` -> live loaded-worker count, for eviction tests.
3653-#[cfg(all(test, celld_internal_tests))]
3654-fn op_loader_count(
3655- scope: &mut v8::PinScope,
3656- _args: v8::FunctionCallbackArguments,
3657- mut rv: v8::ReturnValue<v8::Value>,
3658-) {
3659- let n = loader_registry().lock().unwrap().len();
3660- rv.set(v8::Number::new(scope, n as f64).into());
3661-}
3662-
36633948 /// `__writePosition(scope)` -> the cell's committed-write position (a number),
36643949 /// or `null` when the scope has no open connection. The co-hosted DO fast path
36653950 /// samples this around an inline `fetch` to tell a write from a read.
@@ -3675,22 +3960,20 @@
36753960 }
36763961 }
36773962
3678-/// `__gateWrite(scope, position)` -> a promise that resolves once the cell is
3679-/// durable and rejects if durability cannot be proved. The co-hosted DO fast
3680-/// path awaits this before returning an inline write's response, so the caller
3681-/// never observes a write the node cannot prove durable — the routed output
3682-/// gate, applied where the inline write actually happens.
3963+/// `__gateWrite(scope, positionOrNull)` -> a promise that resolves once every
3964+/// write the response can reveal is durable. A null position identifies a
3965+/// read-only response, which trails any barrier already open for the cell.
36833966 fn op_gate_write(
36843967 scope: &mut v8::PinScope,
36853968 args: v8::FunctionCallbackArguments,
36863969 mut rv: v8::ReturnValue<v8::Value>,
36873970 ) {
36883971 let cell = args.get(0).to_rust_string_lossy(scope);
3689- let position = args
3690- .get(1)
3691- .to_integer(scope)
3692- .map(|n| n.value() as u64)
3693- .unwrap_or(0);
3972+ let value = args.get(1);
3973+ let position = (!value.is_null_or_undefined())
3974+ .then(|| value.to_integer(scope).map(|n| n.value() as u64))
3975+ .flatten();
3976+ let read_only = position.is_none();
36943977 let (tx, receive) = tokio::sync::oneshot::channel();
36953978 let sent = GATE_TX
36963979 .get()
@@ -3705,6 +3988,9 @@
37053988 .unwrap_or(false);
37063989 let id = asyncrt::enqueue(async move {
37073990 if !sent {
3991+ if read_only {
3992+ return Ok(String::new());
3993+ }
37083994 return Err("no output-gate channel".into());
37093995 }
37103996 match receive.await {
@@ -3760,7 +4046,7 @@
37604046 .unwrap()
37614047 .insert(request_id, cancel_sender);
37624048 let mut cancel_guard = DoCallCancelGuard::new(request_id);
3763- let gate = egress_gate_pending();
4049+ let gate = egress_gate_request();
37644050 let request = DoCallReq {
37654051 request_id: Some(request_id),
37664052 cancel: Some(cancel),
@@ -3823,7 +4109,7 @@
38234109 let method = args.get(2).to_rust_string_lossy(scope);
38244110 let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default());
38254111 let (tx, rx) = tokio::sync::oneshot::channel();
3826- let gate = egress_gate_pending();
4112+ let gate = egress_gate_request();
38274113 let request = RpcCallReq {
38284114 scope: cell,
38294115 name,
@@ -3893,10 +4179,11 @@
38934179 }
38944180 }
38954181 let span_url = trace.as_ref().map(|_| url.clone());
3896- // Whatever this handler has written must be durable before the request
3897- // leaves: a third party that has acted on a write celld then loses cannot
3898- // be told to un-act.
3899- let gate = egress_gate_pending();
4182+ // Whatever this request can reveal must be durable before it leaves: a
4183+ // third party that has acted on a write celld then loses cannot be told to
4184+ // un-act. That covers a write this handler made and a value it only read,
4185+ // because the third party cannot tell the two apart.
4186+ let gate = egress_gate_request();
39004187 let id = asyncrt::enqueue(async move {
39014188 let span_started = trace.as_ref().map(|_| crate::telemetry::now_unix_us());
39024189 let mut span = trace.as_ref().zip(child).map(|(parent, child)| {
@@ -4082,24 +4369,24 @@
40824369 });
40834370 let id = asyncrt::enqueue(async move {
40844371 let Some((mut source, mut cancelled)) = source else {
4085- return Ok(serde_json::json!({ "done": true }).to_string());
4372+ return Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into()));
40864373 };
40874374 let next = tokio::select! {
40884375 result = next_http_stream_chunk(&mut source) => Some(result),
40894376 _ = cancelled.changed() => None,
40904377 };
40914378 match next {
4092- None => Ok(serde_json::json!({ "done": true }).to_string()),
4379+ None => Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())),
40934380 Some(Ok(Some(bytes))) => {
40944381 if let Some(stream) = http_streams().lock().unwrap().get_mut(&stream_id) {
40954382 stream.created = Instant::now();
40964383 stream.source = Some(source);
40974384 }
4098- Ok(serde_json::json!({ "done": false, "bytes": bytes }).to_string())
4385+ Ok(asyncrt::OpOut::Bytes(bytes))
40994386 }
41004387 Some(Ok(None)) => {
41014388 http_streams().lock().unwrap().remove(&stream_id);
4102- Ok(serde_json::json!({ "done": true }).to_string())
4389+ Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into()))
41034390 }
41044391 Some(Err(error)) => {
41054392 http_streams().lock().unwrap().remove(&stream_id);
@@ -4259,6 +4546,43 @@
42594546 http_chunk_stream(HttpStreamSource::Response(response))
42604547 }
42614548
4549+/// Hand a request body to the isolate as a stream rather than as bytes.
4550+/// The returned id names the stream for `__http_stream_read`, so the
4551+/// Worker pulls each chunk off the socket as it asks for it and the host
4552+/// never holds the whole body.
4553+pub fn register_body_stream(stream: HttpChunkStream) -> u64 {
4554+ let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
4555+ register_http_stream(stream_id, HttpStreamSource::Stream(stream));
4556+ stream_id
4557+}
4558+
4559+/// How an incoming request body reaches the isolate.
4560+///
4561+/// A small body crosses as bytes. This costs one copy and no asynchronous
4562+/// operations, so a common request pays nothing for a stream that it does
4563+/// not need. A large body, or a body of unknown length, crosses as a
4564+/// stream id. The peak cost of that body is one chunk, not its length.
4565+pub enum RequestBody {
4566+ Bytes(Vec<u8>),
4567+ Stream(u64),
4568+}
4569+
4570+impl RequestBody {
4571+ /// The bytes already in hand, for the paths that hold a whole body.
4572+ pub fn bytes(&self) -> &[u8] {
4573+ match self {
4574+ Self::Bytes(bytes) => bytes,
4575+ Self::Stream(_) => &[],
4576+ }
4577+ }
4578+}
4579+
4580+impl From<Vec<u8>> for RequestBody {
4581+ fn from(bytes: Vec<u8>) -> Self {
4582+ Self::Bytes(bytes)
4583+ }
4584+}
4585+
42624586 /// Timer op behind `setTimeout`: a promise resolving after `ms`.
42634587 fn op_timer(
42644588 scope: &mut v8::PinScope,
@@ -4497,6 +4821,28 @@
44974821 id
44984822 }
44994823
4824+/// The key a Durable Object namespace derives its IDs from. D1 uses one
4825+/// fleet-wide namespace because the database is a resource that several
4826+/// Workers can bind, and a Worker rename must not rename that database.
4827+const D1_NAMESPACE_KEY: &str = "cells:v1:d1:__D1Database";
4828+
4829+pub(crate) fn namespace_key(script_name: &str, class_name: &str) -> String {
4830+ if class_name == crate::deploy::D1_CLASS {
4831+ D1_NAMESPACE_KEY.to_string()
4832+ } else {
4833+ format!("cells:v1:{}:{script_name}:{class_name}", script_name.len())
4834+ }
4835+}
4836+
4837+/// The cell scope a D1 database lives at, for a caller outside any isolate.
4838+/// `celld d1` addresses a database over the operator route, which takes a
4839+/// scope, so this derives what `getByName` derives in the harness, from the
4840+/// same key and the same HMAC.
4841+pub fn d1_cell_scope(database_identity: &str) -> String {
4842+ let id = durable_object_id_for_name(D1_NAMESPACE_KEY, database_identity);
4843+ format!("{}:{}", crate::deploy::D1_CLASS, durable_object_id_hex(&id))
4844+}
4845+
45004846 fn durable_object_id_hex(bytes: &[u8; 32]) -> String {
45014847 const HEX: &[u8; 16] = b"0123456789abcdef";
45024848 let mut output = String::with_capacity(64);
@@ -4771,6 +5117,26 @@
47715117 .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed));
47725118 rv.set(v8::Boolean::new(scope, exceeded).into());
47735119 }
5120+/// Whether this isolate is too close to its heap limit to retain more state.
5121+fn op_heap_over_admission_share(
5122+ scope: &mut v8::PinScope,
5123+ _args: v8::FunctionCallbackArguments,
5124+ mut rv: v8::ReturnValue<v8::Value>,
5125+) {
5126+ let state = scope.get_slot::<Arc<HeapLimitState>>().cloned();
5127+ let over = match state {
5128+ // A condemned isolate admits nothing, whatever the heap now reads.
5129+ Some(state)
5130+ if state.excessively_exceeded.load(Ordering::Relaxed)
5131+ || admission_refusal_forced(&state) =>
5132+ {
5133+ true
5134+ }
5135+ Some(state) => heap_share(scope, state.limit) >= HEAP_ADMISSION_SHARE,
5136+ None => false,
5137+ };
5138+ rv.set(v8::Boolean::new(scope, over).into());
5139+}
47745140 #[cfg(all(test, celld_internal_tests))]
47755141 fn op_test_set_heap_limit_excessively_exceeded(
47765142 scope: &mut v8::PinScope,
@@ -4784,6 +5150,18 @@
47845150 }
47855151 }
47865152 #[cfg(all(test, celld_internal_tests))]
5153+fn op_test_force_heap_admission_refusal(
5154+ scope: &mut v8::PinScope,
5155+ args: v8::FunctionCallbackArguments,
5156+ _rv: v8::ReturnValue<v8::Value>,
5157+) {
5158+ if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() {
5159+ state
5160+ .forced_admission_refusal
5161+ .store(args.get(0).boolean_value(scope), Ordering::Relaxed);
5162+ }
5163+}
5164+#[cfg(all(test, celld_internal_tests))]
47875165 fn op_test_gc(
47885166 scope: &mut v8::PinScope,
47895167 _args: v8::FunctionCallbackArguments,
@@ -5368,6 +5746,91 @@
53685746 }
53695747 }
53705748
5749+/// The reserved cron cell's whole schedule decision, in one call so the policy
5750+/// has one home in `celld_logic::cron` rather than a JavaScript copy that can
5751+/// drift from it.
5752+///
5753+/// `firedMs` is the occurrence being handled, or negative when the cell is
5754+/// only arming. Returns `{ matching, armAt, armIsRetry }`: which expressions
5755+/// the occurrence belongs to, by index into the list passed in, when to arm
5756+/// next — `null` when the schedule is exhausted and the cell should retire —
5757+/// and whether that deadline is the failure backoff rather than the next
5758+/// occurrence.
5759+fn op_cron_plan(
5760+ scope: &mut v8::PinScope,
5761+ args: v8::FunctionCallbackArguments,
5762+ mut rv: v8::ReturnValue<v8::Value>,
5763+) {
5764+ let Ok(list) = v8::Local::<v8::Array>::try_from(args.get(0)) else {
5765+ return;
5766+ };
5767+ let mut crons = Vec::with_capacity(list.length() as usize);
5768+ // Where each parsed expression sits in the list the caller passed. A
5769+ // malformed expression is already refused by `celld deploy`, but the
5770+ // control plane checks only the field count, so one can still arrive here.
5771+ // Skipping it keeps one bad entry from silencing a script's other crons,
5772+ // and this map is what keeps the skip from renumbering them: the caller
5773+ // reports `controller.cron` by index, so a shifted index names the wrong
5774+ // expression for every entry after the bad one.
5775+ let mut positions = Vec::with_capacity(list.length() as usize);
5776+ for index in 0..list.length() {
5777+ let Some(value) = list.get_index(scope, index) else {
5778+ continue;
5779+ };
5780+ if let Ok(cron) = celld_logic::cron::parse(&value.to_rust_string_lossy(scope)) {
5781+ crons.push(cron);
5782+ positions.push(index as usize);
5783+ }
5784+ }
5785+ let fired_ms = args.get(1).number_value(scope).unwrap_or(-1.0) as i64;
5786+ let now_ms = args.get(2).number_value(scope).unwrap_or(0.0) as i64;
5787+ let retry = args.get(3).number_value(scope).unwrap_or(0.0) as i64;
5788+ let failed = args.get(4).boolean_value(scope);
5789+
5790+ let matching = if fired_ms >= 0 {
5791+ celld_logic::cron::matching(&crons, fired_ms)
5792+ } else {
5793+ Vec::new()
5794+ };
5795+ let next = celld_logic::cron::next_across(&crons, now_ms);
5796+ // The retry backoff is `alarm::alarm_retry`'s, not a second schedule:
5797+ // a cron that fails behaves like any other failing alarm, except that
5798+ // `cron_rearm` never lets the backoff outlast the next occurrence.
5799+ let retry_at = failed
5800+ .then(|| celld_logic::alarm::alarm_retry(now_ms, retry, retry, true))
5801+ .flatten();
5802+ let arm_at = celld_logic::cron::cron_rearm(next, retry_at);
5803+ // Which of the two the deadline belongs to. `cron_rearm` takes the earlier
5804+ // and gives a tie to the occurrence, so `armAt` alone cannot say — and the
5805+ // caller has to know, because a retry owes the expressions of the
5806+ // occurrence that failed, while a deadline that is an occurrence owes the
5807+ // expressions that match it.
5808+ let arm_is_retry = match (arm_at, next) {
5809+ (Some(at), Some(occurrence)) => at < occurrence,
5810+ (Some(_), None) => true,
5811+ (None, _) => false,
5812+ };
5813+
5814+ let indices = v8::Array::new(scope, matching.len() as i32);
5815+ for (slot, index) in matching.iter().enumerate() {
5816+ let value = v8::Number::new(scope, positions[*index] as f64);
5817+ indices.set_index(scope, slot as u32, value.into());
5818+ }
5819+ let result = v8::Object::new(scope);
5820+ let key = v8::String::new(scope, "matching").unwrap();
5821+ result.set(scope, key.into(), indices.into());
5822+ let key = v8::String::new(scope, "armAt").unwrap();
5823+ let value: v8::Local<v8::Value> = match arm_at {
5824+ Some(at) => v8::Number::new(scope, at as f64).into(),
5825+ None => v8::null(scope).into(),
5826+ };
5827+ result.set(scope, key.into(), value);
5828+ let key = v8::String::new(scope, "armIsRetry").unwrap();
5829+ let value = v8::Boolean::new(scope, arm_is_retry);
5830+ result.set(scope, key.into(), value.into());
5831+ rv.set(result.into());
5832+}
5833+
53715834 fn op_btoa(
53725835 scope: &mut v8::PinScope,
53735836 args: v8::FunctionCallbackArguments,
@@ -5380,28 +5843,59 @@
53805843 rv.set(v8::String::new(scope, &s).unwrap().into());
53815844 }
53825845
5383-// ---- WHATWG legacy text decoders (encoding_rs) ----
5846+// ---- WHATWG text decoders (encoding_rs) ----
53845847 //
5385-// TextDecoder's utf-8/utf-16 hot path stays pure JS in
5386-// src/js/text_encoding.js; these ops back every other WHATWG label
5387-// (windows-1252, Big5, GBK/GB18030, ISO-2022-JP, x-user-defined, …).
5388-// Streaming decoders live in a thread-local table keyed by id; JS frees
5848+// These ops back every TextDecoder decode. src/js/text_encoding.js
5849+// resolves the label and owns the decoder's lifetime, and encoding_rs
5850+// does the decoding — for utf-8 and utf-16 as much as for every other
5851+// WHATWG label (windows-1252, Big5, GBK/GB18030, ISO-2022-JP,
5852+// x-user-defined, …). Previous utf-8 and utf-16 JS decoders were slower
5853+// than these ops at every measured size.
5854+// Streaming decoders live in a per-isolate table keyed by id; JS frees
53895855 // one on the final decode (last=true), on a fatal error (encoding_rs
53905856 // poisons an errored decoder), or via FinalizationRegistry when a
53915857 // mid-stream decoder is abandoned. Ids are never reused, so a late
53925858 // finalizer free of an already-closed id is a no-op.
53935859
5394-/// Live streaming decoders, keyed by an id JS holds across awaits.
5860+/// Live streaming decoders for one isolate, keyed by an id JS holds across
5861+/// awaits.
53955862 ///
5396-/// Process-wide for the same reason as [`zlib_streams`]: a `TextDecoder` in
5397-/// streaming mode outlives the turn that made it, and under D1 the next turn
5398-/// can run on a different tokio worker. A per-thread counter would also hand
5399-/// the same id to two requests.
5400-static TEXT_DECODERS: OnceLock<Mutex<HashMap<u64, encoding_rs::Decoder>>> = OnceLock::new();
5863+/// An isolate slot rather than a process-wide `Mutex<HashMap<..>>` like
5864+/// [`zlib_streams`]. The reason that one is process-wide holds here too — a
5865+/// `TextDecoder` in streaming mode outlives the turn that made it, and the
5866+/// next turn can run on a different tokio worker — but it argues against a
5867+/// *thread-local*, not against this. A `TextDecoder` is a JS object, so it
5868+/// never leaves the isolate that made it, and every op that touches its
5869+/// decoder runs under that isolate's `v8::Locker`. The lock the embedder
5870+/// already holds is what makes the access exclusive, which `&mut Isolate`
5871+/// on the slot then proves. A second lock inside it buys nothing.
5872+///
5873+/// This removes a ceiling rather than a measured regression, and the
5874+/// difference matters. In isolation the pattern does collapse: replayed on
5875+/// its own — remove, decode outside the lock, insert — 256-byte chunks
5876+/// peaked at two threads and then went *backwards*, 8 threads serving
5877+/// 0.46x what 1 thread served against 6.7x for the same decoding with no
5878+/// table. But celld end to end shows no difference between the two, at any
5879+/// concurrency this hardware can drive, because a chunk costs about 42us
5880+/// of stream and turn machinery around a lock held for about 100ns. So the
5881+/// mutex was not what any cell was waiting on. It was a process-wide
5882+/// serialisation point on a path that every stream now takes, and it went
5883+/// because it does not need to exist, not because it was costing anything
5884+/// yet.
5885+///
5886+/// Dropping the isolate drops the table, so a decoder abandoned by a cell
5887+/// that goes away needs no finalizer to run.
5888+#[derive(Default)]
5889+struct TextDecoders(HashMap<u64, encoding_rs::Decoder>);
5890+
54015891 static TEXT_DECODER_NEXT: AtomicU64 = AtomicU64::new(1);
54025892
5403-fn text_decoders() -> &'static Mutex<HashMap<u64, encoding_rs::Decoder>> {
5404- TEXT_DECODERS.get_or_init(|| Mutex::new(HashMap::new()))
5893+/// The calling isolate's decoder table, created on first use.
5894+fn text_decoders<'a>(scope: &'a mut v8::PinScope) -> &'a mut HashMap<u64, encoding_rs::Decoder> {
5895+ if scope.get_slot::<TextDecoders>().is_none() {
5896+ scope.set_slot(TextDecoders::default());
5897+ }
5898+ &mut scope.get_slot_mut::<TextDecoders>().expect("just set").0
54055899 }
54065900
54075901 /// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined
@@ -5433,7 +5927,7 @@
54335927 enc.new_decoder_with_bom_removal()
54345928 };
54355929 let id = TEXT_DECODER_NEXT.fetch_add(1, Ordering::Relaxed);
5436- text_decoders().lock().unwrap().insert(id, dec);
5930+ text_decoders(scope).insert(id, dec);
54375931 rv.set(v8::Number::new(scope, id as f64).into());
54385932 }
54395933
@@ -5457,39 +5951,85 @@
54575951 rv.set(v8::String::empty(scope).into());
54585952 return;
54595953 }
5460- let mut dec = text_decoders()
5461- .lock()
5462- .unwrap()
5954+ let mut dec = text_decoders(scope)
54635955 .remove(&id)
54645956 .expect("JS holds the only live id");
5957+ let Ok(out) = run_decoder(&mut dec, &bytes, fatal, last) else {
5958+ throw_invalid_encoded_data(scope);
5959+ return;
5960+ };
5961+ if !last {
5962+ text_decoders(scope).insert(id, dec);
5963+ }
5964+ rv.set(v8::String::new(scope, &out).unwrap().into());
5965+}
5966+
5967+/// `$$textDecoderDecodeOnce(name, view, fatal, ignoreBOM)` -> string, for
5968+/// a complete buffer.
5969+///
5970+/// The whole decode is one call, so the decoder never outlives it and
5971+/// never reaches [`text_decoders`]. That saves an insert and a remove,
5972+/// and it keeps every non-streaming decode on the node off a table that
5973+/// is one mutex for the whole process — which is most decodes, because
5974+/// `request.text()` and `response.text()` are not streams. A stream
5975+/// still takes that lock twice per chunk, which is a cost per chunk
5976+/// rather than per byte, and it has not been measured under load;
5977+/// sharding the table is the answer if it ever shows.
5978+fn op_text_decoder_decode_once(
5979+ scope: &mut v8::PinScope,
5980+ args: v8::FunctionCallbackArguments,
5981+ mut rv: v8::ReturnValue<v8::Value>,
5982+) {
5983+ let name = args.get(0).to_rust_string_lossy(scope);
5984+ let bytes = view_bytes(args.get(1)).unwrap_or_default();
5985+ let fatal = args.get(2).boolean_value(scope);
5986+ let ignore_bom = args.get(3).boolean_value(scope);
5987+ let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label");
5988+ let mut dec = if ignore_bom {
5989+ enc.new_decoder_without_bom_handling()
5990+ } else {
5991+ enc.new_decoder_with_bom_removal()
5992+ };
5993+ match run_decoder(&mut dec, &bytes, fatal, true) {
5994+ Ok(out) => rv.set(v8::String::new(scope, &out).unwrap().into()),
5995+ Err(()) => throw_invalid_encoded_data(scope),
5996+ }
5997+}
5998+
5999+/// Feeds `bytes` to `dec` and answers the text. `Err` means `fatal` was
6000+/// set and the input was malformed.
6001+fn run_decoder(
6002+ dec: &mut encoding_rs::Decoder,
6003+ bytes: &[u8],
6004+ fatal: bool,
6005+ last: bool,
6006+) -> Result<String, ()> {
54656007 let mut out = String::new();
5466- let ok = if fatal {
6008+ if fatal {
54676009 let cap = dec
54686010 .max_utf8_buffer_length_without_replacement(bytes.len())
54696011 .unwrap();
54706012 out.reserve(cap);
5471- matches!(
5472- dec.decode_to_string_without_replacement(&bytes, &mut out, last),
6013+ if !matches!(
6014+ dec.decode_to_string_without_replacement(bytes, &mut out, last),
54736015 (encoding_rs::DecoderResult::InputEmpty, _),
5474- )
6016+ ) {
6017+ return Err(());
6018+ }
54756019 } else {
54766020 let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap();
54776021 out.reserve(cap);
5478- let _ = dec.decode_to_string(&bytes, &mut out, last);
5479- true
5480- };
5481- if !ok {
5482- let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap();
5483- let exc = v8::Exception::type_error(scope, msg);
5484- scope.throw_exception(exc);
5485- return;
6022+ let _ = dec.decode_to_string(bytes, &mut out, last);
54866023 }
5487- if !last {
5488- text_decoders().lock().unwrap().insert(id, dec);
5489- }
5490- rv.set(v8::String::new(scope, &out).unwrap().into());
6024+ Ok(out)
54916025 }
54926026
6027+fn throw_invalid_encoded_data(scope: &mut v8::PinScope) {
6028+ let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap();
6029+ let exc = v8::Exception::type_error(scope, msg);
6030+ scope.throw_exception(exc);
6031+}
6032+
54936033 /// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder
54946034 /// abandoned mid-stream.
54956035 fn op_text_decoder_free(
@@ -5498,7 +6038,7 @@
54986038 _rv: v8::ReturnValue<v8::Value>,
54996039 ) {
55006040 let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
5501- text_decoders().lock().unwrap().remove(&id);
6041+ text_decoders(scope).remove(&id);
55026042 }
55036043
55046044 // ---- the JS harness: Web API + the DO object model ----
@@ -5507,7 +6047,7 @@
55076047 mod modules;
55086048 use bootstrap::{
55096049 adopt_cell, begin_event_context, build_env, end_event_context, harness_env,
5510- inject_compatibility_flags, inject_namespace_keys, inject_routing,
6050+ inject_compatibility_flags, inject_crons, inject_namespace_keys, inject_routing,
55116051 inject_storage_compatibility, install_harness, install_prelude, populate_cf_exports,
55126052 register_class, register_entrypoints,
55136053 };
@@ -5523,7 +6063,7 @@
55236063 tc: &mut v8::PinScope<'s, '_>,
55246064 url: &str,
55256065 method: &str,
5526- body: &[u8],
6066+ body: &RequestBody,
55276067 headers: &[(String, String)],
55286068 ) -> Result<v8::Local<'s, v8::Value>> {
55296069 let global = tc.get_current_context().global(tc);
@@ -5535,15 +6075,27 @@
55356075 .map_err(|_| anyhow!("not fn"))?;
55366076 let url = v8::String::new(tc, url).unwrap();
55376077 let method = v8::String::new(tc, method).unwrap();
5538- let body = bytes_value(tc, body.to_vec());
55396078 let headers = v8::String::new(
55406079 tc,
55416080 &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()),
55426081 )
55436082 .unwrap();
6083+ // A streamed body passes its id, and the harness builds the body
6084+ // stream around that id. A held body passes the bytes.
6085+ let (body, stream_id) = match body {
6086+ RequestBody::Bytes(bytes) => (bytes_value(tc, bytes.clone()), v8::undefined(tc).into()),
6087+ RequestBody::Stream(id) => (
6088+ v8::undefined(tc).into(),
6089+ v8::Number::new(tc, *id as f64).into(),
6090+ ),
6091+ };
55446092 let recv = v8::undefined(tc).into();
5545- f.call(tc, recv, &[url.into(), method.into(), body, headers.into()])
5546- .ok_or_else(|| anyhow!("__makeIncomingRequest threw"))
6093+ f.call(
6094+ tc,
6095+ recv,
6096+ &[url.into(), method.into(), body, headers.into(), stream_id],
6097+ )
6098+ .ok_or_else(|| anyhow!("__makeIncomingRequest threw"))
55476099 }
55486100
55496101 fn register_incoming_request(
@@ -5690,9 +6242,12 @@
56906242 });
56916243 }
56926244
6245+#[cfg(all(test, celld_internal_tests))]
6246+include!(env!("CELLD_INTERNAL_JS_OBSERVERS"));
6247+
56936248 /// Externally injected Web-platform tests.
56946249 #[cfg(all(test, celld_internal_tests))]
5695-mod conformance_runtime_tests {
6250+pub(crate) mod conformance_runtime_tests {
56966251 include!(env!("CELLD_CONFORMANCE_JS_RUNTIME_TESTS"));
56976252 }
56986253
modifiedcrates/celld/js/bootstrap.rs+49−3View file
@@ -200,7 +200,7 @@
200200 cell.set(scope, script_key.into(), script_value.into());
201201 for class_name in do_classes {
202202 let class_key = v8::String::new(scope, class_name).unwrap();
203- let namespace_key = format!("cells:v1:{}:{script_name}:{class_name}", script_name.len(),);
203+ let namespace_key = super::namespace_key(script_name, class_name);
204204 let namespace_key = v8::String::new(scope, &namespace_key).unwrap();
205205 if !keys
206206 .set(scope, class_key.into(), namespace_key.into())
@@ -212,6 +212,28 @@
212212 Ok(())
213213 }
214214
215+/// `__cell.crons`: the deployment's cron trigger expressions, verbatim as the
216+/// developer wrote them. The reserved cron cell reads them at each activation,
217+/// so a schedule change arrives with the deployment and needs no migration of
218+/// an alarm the previous deployment armed. Absent `triggers.crons`, the list
219+/// is empty and the cron cell retires itself.
220+pub(super) fn inject_crons(scope: &mut v8::PinScope, crons: &[String]) -> Result<()> {
221+ let context = scope.get_current_context();
222+ let global = context.global(scope);
223+ let cell = global
224+ .get(scope, v8::String::new(scope, "__cell").unwrap().into())
225+ .and_then(|value| value.to_object(scope))
226+ .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
227+ let list = v8::Array::new(scope, crons.len() as i32);
228+ for (index, cron) in crons.iter().enumerate() {
229+ let value = v8::String::new(scope, cron).ok_or_else(|| anyhow!("cron expression"))?;
230+ list.set_index(scope, index as u32, value.into());
231+ }
232+ let key = v8::String::new(scope, "crons").unwrap();
233+ cell.set(scope, key.into(), list.into());
234+ Ok(())
235+}
236+
215237 /// `globalThis.Cloudflare.compatibilityFlags`. Only flags Cells actually
216238 /// honours are listed; a flag Cells does not model is absent (falsy) rather
217239 /// than reported as enabled.
@@ -257,6 +279,7 @@
257279 let script_name = config.script_name.as_str();
258280 let bindings = config.bindings.as_slice();
259281 let r2_bindings = config.r2_bindings.as_slice();
282+ let d1_bindings = config.d1_bindings.as_slice();
260283 let ai_binding = config.ai_binding.as_deref();
261284 let vars = config.vars.as_slice();
262285 let services = config.services.as_slice();
@@ -273,6 +296,12 @@
273296 for name in r2_bindings {
274297 lines.push_str(&format!("e[{:?}] = __makeR2Bucket({:?});\n", name, name));
275298 }
299+ for (name, database) in d1_bindings {
300+ lines.push_str(&format!(
301+ "e[{:?}] = __makeD1Database({:?});\n",
302+ name, database
303+ ));
304+ }
276305 if let (Some(name), Ok(url)) = (ai_binding, std::env::var("CELLD_AI_URL")) {
277306 lines.push_str(&format!("e[{:?}] = __makeAiBinding({:?});\n", name, url));
278307 }
@@ -436,7 +465,8 @@
436465 Ok(())
437466 }
438467
439-/// Amend `inject_routing` for one cell, and restore its id name.
468+/// Amend `inject_routing` for one cell, release its instance, and restore its
469+/// id name.
440470 ///
441471 /// The isolate-side half of taking a cell in or giving it back. Kept beside
442472 /// `inject_routing` because it edits the table that function builds.
@@ -466,7 +496,23 @@
466496 // before they shared isolates. Re-enabling the fast path needs the
467497 // target checked against what is already on the stack; correctness
468498 // first.
469- let source = format!("(() => {{ delete __cell.owned[{cell:?}]; }})();");
499+ //
500+ // The script also releases everything the isolate holds for this cell's
501+ // residency, on both edges: the give-back frees what the application left
502+ // behind — memory the node cannot shed, because the cell has left
503+ // residency — and the take-in stops state spanning two epochs, which
504+ // corrupts rather than leaks. `__cell.release` lives in the harness
505+ // because what a residency owns is decided by the maps that hold it; this
506+ // side only says when.
507+ //
508+ // The release loses nothing the cell needs back: `register_actor_name`
509+ // persists the id name before writing it here, so the take-in below reads
510+ // it back.
511+ let source = format!(
512+ "(() => {{ const s = {cell:?}; \
513+ delete __cell.owned[s]; \
514+ __cell.release(s); }})();"
515+ );
470516 let code = v8::String::new(tc, &source).unwrap();
471517 let script = v8::Script::compile(tc, code, None).ok_or_else(|| anyhow!("adopt compile"))?;
472518 script.run(tc).ok_or_else(|| anyhow!("adopt run"))?;
modifiedcrates/celld/js/crypto.rs+73−7View file
@@ -146,6 +146,51 @@
146146 .map_err(|_| anyhow!("invalid JWK {name}"))
147147 }
148148
149+/// Salt length OpenSSL uses for a PBES2 export, which is what Node inherits.
150+const PBES2_SALT_LEN: usize = 8;
151+/// PBKDF2 iteration count OpenSSL uses for a PBES2 export. Node inherits it,
152+/// so an encrypted key celld writes costs a reader the same as a Node one.
153+///
154+/// This is far weaker than the scrypt cost `pkcs5` reaches for on its own, and
155+/// deliberately so: an encrypted key is only as strong as the reader that has
156+/// to open it, and every Node and OpenSSL reader expects these parameters. Do
157+/// not raise it to harden the KDF -- that hardens celld's keys against celld
158+/// alone and desyncs the format from the one the ecosystem writes.
159+const PBES2_ITERATIONS: u32 = 2048;
160+
161+/// PBES2 parameters for an encrypted PKCS#8 export.
162+///
163+/// `pkcs8::PrivateKeyInfo::encrypt` picks scrypt at its recommended cost
164+/// (2^15 rounds over 32 MiB) and AES-256-CBC, and it ignores the cipher the
165+/// caller asked for. Node derives with PBKDF2-HMAC-SHA256 over 2048
166+/// iterations and honours the cipher, so celld builds the parameters itself.
167+/// The scrypt default also made an export cost seconds, which is why the two
168+/// crypto suites were slow.
169+///
170+/// The cipher name arrives lower-cased from `node_crypto.js`, which is also
171+/// where an unwritable cipher is refused. A name that reaches the fallback
172+/// arm here is a bug on that side, not caller input.
173+fn pbes2_parameters<'a>(
174+ cipher: &str,
175+ salt: &'a [u8],
176+ iv: &'a [u8; 16],
177+) -> Result<pkcs8::pkcs5::pbes2::Parameters<'a>> {
178+ use pkcs8::pkcs5::pbes2::{EncryptionScheme, Parameters, Pbkdf2Params};
179+
180+ let encryption = match cipher {
181+ "aes-128-cbc" => EncryptionScheme::Aes128Cbc { iv },
182+ "aes-192-cbc" => EncryptionScheme::Aes192Cbc { iv },
183+ "aes-256-cbc" => EncryptionScheme::Aes256Cbc { iv },
184+ other => return Err(anyhow!("unsupported cipher {other}")),
185+ };
186+ let kdf = Pbkdf2Params::hmac_with_sha256(PBES2_ITERATIONS, salt)
187+ .map_err(|_| anyhow!("invalid PBKDF2 parameters"))?;
188+ Ok(Parameters {
189+ kdf: kdf.into(),
190+ encryption,
191+ })
192+}
193+
149194 /// Identify an already-normalized PKCS#8 or SPKI blob and describe it. Node
150195 /// reports `asymmetricKeyType` and `asymmetricKeyDetails` from exactly this.
151196 fn describe_key(der: &[u8], private: bool) -> Result<ParsedKey> {
@@ -792,14 +837,14 @@
792837 } else {
793838 let key = crypto_bytes(args, "key")?;
794839 let stated = args.get("type").and_then(serde_json::Value::as_str);
840+ let passphrase = args
841+ .get("passphrase")
842+ .filter(|value| !value.is_null())
843+ .map(|_| crypto_bytes(args, "passphrase"))
844+ .transpose()?;
795845 if format == "pem" {
796846 let text = std::str::from_utf8(&key)
797847 .map_err(|_| anyhow!("PEM key is not valid UTF-8"))?;
798- let passphrase = args
799- .get("passphrase")
800- .filter(|value| !value.is_null())
801- .map(|_| crypto_bytes(args, "passphrase"))
802- .transpose()?;
803848 if text.contains("ENCRYPTED PRIVATE KEY") {
804849 let passphrase = passphrase
805850 .ok_or_else(|| anyhow!("Passphrase required for encrypted key"))?;
@@ -813,6 +858,18 @@
813858 .map_err(|_| anyhow!("invalid PEM key"))?;
814859 normalize_key(document.as_bytes(), pem_structure(label)?)?
815860 }
861+ } else if let Ok(sealed) = pkcs8::EncryptedPrivateKeyInfo::try_from(key.as_slice())
862+ {
863+ // An encrypted PKCS#8 blob is its own structure, so it is
864+ // recognized before the sniffer runs: the sniffer would
865+ // read it as an unknown key and report a parse failure
866+ // rather than a missing or wrong passphrase.
867+ let passphrase = passphrase
868+ .ok_or_else(|| anyhow!("Passphrase required for encrypted key"))?;
869+ let document = sealed
870+ .decrypt(&passphrase)
871+ .map_err(|_| anyhow!("Failed to decrypt private key"))?;
872+ (document.as_bytes().to_vec(), true)
816873 } else {
817874 (
818875 normalize_key_sniffing(&key, stated, want_private)?,
@@ -989,9 +1046,18 @@
9891046 }
9901047 let info = pkcs8::PrivateKeyInfo::try_from(der.as_slice())
9911048 .map_err(|_| anyhow!("invalid PKCS#8 private key"))?;
992- let mut rng = rand::rngs::OsRng;
1049+ let cipher = args
1050+ .get("cipher")
1051+ .and_then(serde_json::Value::as_str)
1052+ .ok_or_else(|| anyhow!("an encrypted export needs a cipher"))?;
1053+ use rand::RngCore as _;
1054+ let mut salt = [0u8; PBES2_SALT_LEN];
1055+ let mut iv = [0u8; 16];
1056+ rand::rngs::OsRng.fill_bytes(&mut salt);
1057+ rand::rngs::OsRng.fill_bytes(&mut iv);
1058+ let params = pbes2_parameters(cipher, &salt, &iv)?;
9931059 let document = info
994- .encrypt(&mut rng, &passphrase)
1060+ .encrypt_with_params(params, &passphrase)
9951061 .map_err(|_| anyhow!("could not encrypt the private key"))?;
9961062 let pem = args
9971063 .get("format")
modifiedcrates/celld/js/harness.js+609−25View file
@@ -153,7 +153,9 @@
153153 offset += chunk.byteLength;
154154 }
155155 target._bodyBytes = bytes;
156- target._body = new TextDecoder().decode(bytes);
156+ // text() memoizes into _body on demand. Decoding here charges every
157+ // binary passthrough the cost of a string it never reads.
158+ target._body = undefined;
157159 return bytes;
158160 }
159161 class CelldBodyStream extends ReadableStream {
@@ -205,9 +207,11 @@
205207 const id = Number(streamId);
206208 super({
207209 async pull(controller) {
208- const chunk = JSON.parse(await __http_stream_read(id));
209- if (chunk.done) controller.close();
210- else controller.enqueue(Uint8Array.from(chunk.bytes || []));
210+ // A chunk arrives as a Uint8Array. The host moves it in without
211+ // a copy. The end of the stream arrives as a string.
212+ const chunk = await __http_stream_read(id);
213+ if (typeof chunk === "string") controller.close();
214+ else controller.enqueue(chunk);
211215 },
212216 cancel() { __http_stream_cancel(id); },
213217 }, { highWaterMark: 0 });
@@ -584,24 +588,50 @@
584588 return response.json();
585589 },
586590 });
591+// A host timer op resolves once, so an interval arms a new one after every
592+// round. `__timers` maps the id the caller holds to the op that is armed
593+// right now: for a timeout that is the same id, and for an interval it is a
594+// fresh id each round. Clearing therefore cancels the armed op, not the id.
587595 const __timers = new Map();
596+const __clearTimer = (id) => {
597+ const armed = __timers.get(id);
598+ if (armed === undefined) return;
599+ __timers.delete(id);
600+ __timer_cancel(armed);
601+};
588602 globalThis.setTimeout = (cb, ms, ...a) => {
589603 const id = __timer_alloc();
590- __timers.set(id, true);
604+ __timers.set(id, id);
591605 __op_timer(id, ms | 0).then(() => {
592606 if (!__timers.delete(id)) return;
593607 cb(...a);
594608 });
595609 return id;
596610 };
597-globalThis.clearTimeout = (id) => {
598- if (!__timers.delete(id)) return;
599- __timer_cancel(id);
611+globalThis.setInterval = (cb, ms, ...a) => {
612+ const id = __timer_alloc();
613+ const delay = ms | 0;
614+ const arm = (armed) => {
615+ __timers.set(id, armed);
616+ __op_timer(armed, delay).then(() => {
617+ // Cancelling drops the entry and cancelling then re-arming replaces
618+ // it, so a round whose op is no longer the armed one is dead and
619+ // stops here. A cancelled op still resolves, which is why this test
620+ // is on identity and not on the op alone.
621+ if (__timers.get(id) !== armed) return;
622+ // Arm the next round before the callback runs. A `clearInterval`
623+ // inside the callback must end the interval, and arming after the
624+ // callback would undo it.
625+ arm(__timer_alloc());
626+ cb(...a);
627+ });
628+ };
629+ arm(id);
630+ return id;
600631 };
601-globalThis.setInterval = () => {
602- throw new Error("setInterval is not implemented in celld");
603-};
604-globalThis.clearInterval = () => {};
632+// One id space and one cancel, because a caller can cross the two.
633+globalThis.clearTimeout = __clearTimer;
634+globalThis.clearInterval = __clearTimer;
605635
606636 const __sqlCursorFinalizer = typeof FinalizationRegistry === "function"
607637 ? new FinalizationRegistry((cursorId) => __sql_cursor_close(cursorId))
@@ -696,7 +726,9 @@
696726 if (result.done) return rows;
697727 rows.push(result.value);
698728 if (__heap_limit_excessively_exceeded())
699- throw new Error("result set is too large to fit in memory");
729+ throw new Error(
730+ "the isolate is over its V8 heap limit, so it stopped " +
731+ "materializing a result set (see CELLD_V8_HEAP_LIMIT_MB)");
700732 }
701733 }
702734 one() {
@@ -1271,6 +1303,10 @@
12711303 return JSON.parse(__ws_list(this._scope, tag)).map((row) => __socketFromRow(row));
12721304 }
12731305 acceptWebSocket(ws, tags = []) {
1306+ if (__heap_over_admission_share())
1307+ throw new Error(
1308+ "the isolate is near its V8 heap limit, so it refused a " +
1309+ "WebSocket (see CELLD_V8_HEAP_LIMIT_MB)");
12741310 ws._target = { id: ws._id, scope: this._scope };
12751311 if (ws._peer) ws._peer._target = ws._target;
12761312 ws._hibernatable = true;
@@ -1451,6 +1487,15 @@
14511487 510: "Not Extended", 511: "Network Authentication Required",
14521488 };
14531489 const __wrapServiceResponse = (res, url) => {
1490+ // A 101 that crossed isolates carries a target rather than a socket: the
1491+ // pair's other end is in the isolate that answered, and the two cannot be
1492+ // linked the way the loopback below links them. Give the caller a client
1493+ // end the host can join to that target, on the same terms as a Durable
1494+ // Object subrequest -- nothing binds until `accept()`, so a response
1495+ // passed straight back out keeps the direct route to the real client.
1496+ const bound = !res.webSocket && res._wsTarget && res.status === 101
1497+ ? new WebSocket(undefined, [], res._wsTarget)
1498+ : undefined;
14541499 const wrapped = new Response(
14551500 // Buffered bodies re-stream (an empty buffer still yields a
14561501 // stream, as over real HTTP); a streaming body passes through.
@@ -1460,7 +1505,7 @@
14601505 statusText:
14611506 res.statusText || __STATUS_TEXT[res.status] || "",
14621507 headers: res.headers,
1463- webSocket: res.webSocket,
1508+ webSocket: res.webSocket || bound,
14641509 __wsTarget: res._wsTarget,
14651510 },
14661511 );
@@ -1697,7 +1742,9 @@
16971742 ? r.body
16981743 : Uint8Array.from(r.bodyBytes || []);
16991744 return __wrapServiceResponse(
1700- new Response(body, { status: r.status, headers: r.headers }),
1745+ new Response(body, {
1746+ status: r.status, headers: r.headers, __wsTarget: r.wsTarget,
1747+ }),
17011748 req.url);
17021749 },
17031750 // Workerd's test-visible Fetcher.scheduled(): invoke the target's
@@ -1924,6 +1971,44 @@
19241971 if (entry.scope === scope)
19251972 __ctxAbort(entry.ctx, new __ActorAbort(reason));
19261973 };
1974+// Everything this isolate holds for one cell scope that belongs to the
1975+// cell's residency rather than to the isolate, so a fresh instance
1976+// inherits none of it. `adopt_cell` calls this on both edges: the
1977+// give-back frees it, the take-in guarantees that no epoch spans.
1978+// Storage is not here — `stop_cell` closes it host-side — and sockets
1979+// live in the host registry, so a hibernated cell keeps them.
1980+const __cellRelease = (scope) => {
1981+ delete __cell.instances[scope];
1982+ delete __cell.idNames[scope];
1983+ __brokenActors.delete(scope);
1984+ // An abandoned block never runs `__blockLeave`, leaving `shut` above
1985+ // zero for a scope with no critical section. This is an invariant
1986+ // rather than a fix: an eviction cannot abandon a block, because the
1987+ // block holds the cell's gate and a cell with an event in flight is
1988+ // not given back. Only a stop that waits for nobody -- a fence, a
1989+ // reset, a clean reload -- reaches it, and by then the only reader
1990+ // left is a stub minted in the next epoch, which reads `holder` for
1991+ // one microtask before the next acquire overwrites it. Cheap to hold,
1992+ // and it keeps the rule whole: the release drops everything this
1993+ // isolate keys by the scope.
1994+ __cellBlocks.delete(scope);
1995+ // An entry holds `target`, which can be an object the released
1996+ // instance owns. Dropping it ends that reachability; `released` is
1997+ // what an already-revived handle reads, since it holds its entry
1998+ // directly and never looks in this map again.
1999+ for (const entry of __stubEntries.values()) {
2000+ if (entry.scope !== scope) continue;
2001+ entry.released = true;
2002+ __stubEntries.delete(entry.id);
2003+ // Break in-flight ops as an abort would, but not through
2004+ // `__actorBreak`: that records the scope broken for the life of the
2005+ // isolate, which is the state this function drops.
2006+ __ctxAbort(entry.ctx, new __ActorAbort(__releasedStubError()));
2007+ }
2008+};
2009+const __releasedStubError = () => new Error(
2010+ "The Durable Object that returned this RPC stub no longer runs on " +
2011+ "this node.");
19272012 const __disposeStub = (meta) => {
19282013 if (meta.disposed) return;
19292014 meta.disposed = true;
@@ -2449,6 +2534,10 @@
24492534 const __stubOp = (meta, path, args) => {
24502535 if (meta.disposed) return Promise.reject(__stubDisposedError());
24512536 const entry = meta.entry;
2537+ // The cell that minted this stub left residency, so `entry.target`
2538+ // belongs to an instance this node released. The stub fails here
2539+ // rather than calling into it.
2540+ if (entry.released) return Promise.reject(__releasedStubError());
24522541 // A stub rooted in an aborted context is broken: reject with the
24532542 // abort reason, before and after the dispatch (the target may
24542543 // abort its own context mid-call). Gated on one field read.
@@ -3055,8 +3144,18 @@
30553144 : r.body !== undefined
30563145 ? r.body
30573146 : Uint8Array.from(r.bodyBytes || []);
3147+ // An upgrade the cell answered with. The pair straddles two isolates,
3148+ // so the client end cannot be the peer object itself -- it is a new
3149+ // socket the host joins to the cell's on `accept()`. A caller that
3150+ // returns this response instead of accepting keeps the direct route
3151+ // `__wsTarget` already describes, and binds nothing.
30583152 return new Response(body, {
3059- status: r.status, headers: r.headers, __wsTarget: r.wsTarget,
3153+ status: r.status,
3154+ headers: r.headers,
3155+ __wsTarget: r.wsTarget,
3156+ webSocket: r.status === 101 && r.wsTarget
3157+ ? new WebSocket(undefined, [], r.wsTarget)
3158+ : undefined,
30603159 });
30613160 };
30623161 const stub = new Proxy(target, { get: (_target, prop) => {
@@ -3139,10 +3238,16 @@
31393238 // A top-level (non-actor) request whose signal can be aborted by id, so a
31403239 // disconnected HTTP or service-binding caller reaches the target's
31413240 // `request.signal`.
3241+// A large body, or a body of unknown length, arrives as a stream id and
3242+// not as bytes. The handler then pulls the body off the socket as it
3243+// reads, so the whole body is never resident. `request.body` is a stream
3244+// in both cases.
31423245 globalThis.__makeIncomingRequest = (
3143- url, method, body, headersJson,
3246+ url, method, body, headersJson, streamId,
31443247 ) => __makeRequest(
3145- url, method, body, headersJson, undefined, true);
3248+ url, method,
3249+ streamId === undefined ? body : new CelldHttpBodyStream(streamId),
3250+ headersJson, undefined, true);
31463251 globalThis.__dispatchTo = async (
31473252 scope, url, method, body, headersJson, requestId = null, inline = false,
31483253 callerSignal = null,
@@ -3209,7 +3314,8 @@
32093314 // as zero — a write advances past it, a read leaves it there.
32103315 if (inline) {
32113316 const after = __writePosition(scope);
3212- if (after !== null && after > (gateBefore ?? 0)) await __gateWrite(scope, after);
3317+ const wrote = after !== null && after > (gateBefore ?? 0);
3318+ await __gateWrite(scope, wrote ? after : null);
32133319 }
32143320 return response;
32153321 } finally {
@@ -3532,11 +3638,123 @@
35323638 __actorEventStack.pop();
35333639 }
35343640 };
3641+// The reserved cron cell. It is not a user class: celld registers it under
3642+// `.cron` for every deployment that declares `triggers.crons`, and one cell
3643+// per script carries that script's whole schedule. Ownership CAS on that one
3644+// name is what makes a cron trigger fire once per fleet rather than once per
3645+// node -- the same arbiter an alarm already relies on, with nothing added.
3646+//
3647+// The schedule itself is never stored here. `__cell.crons` comes from the
3648+// deployment the cell is running under, so changing a cron expression takes
3649+// effect on the next activation and needs no migration of an armed alarm.
3650+class CelldCronSchedule {
3651+ constructor(state) {
3652+ this._state = state;
3653+ // Failures within one occurrence. Held in memory on purpose: losing the
3654+ // count to an eviction only makes the next retry sooner, and every retry
3655+ // is capped at the next occurrence anyway, so it need not be durable.
3656+ this._retry = 0;
3657+ // What a pending retry owes: the occurrence, the expressions of it that
3658+ // failed, and the deadline the retry was armed for. A retry deadline is a
3659+ // backoff instant and not an occurrence, so nothing about it can be
3660+ // recovered from the deadline itself -- without this record the wake
3661+ // matches no expression, runs nothing, and drops the failed tick in
3662+ // silence. Held in memory beside `_retry` and for the same reason: an
3663+ // eviction costs the retry, never the next occurrence.
3664+ this._owed = null;
3665+ }
3666+ // celld calls this once per node after a deployment loads, because a cron
3667+ // cell has no client to wake it. Arming is idempotent -- the same schedule
3668+ // and the same clock give the same answer -- so it does not matter which
3669+ // node wins the cell.
3670+ async fetch() {
3671+ // A pending retry is a deadline this cell already owes, and re-arming
3672+ // would move it to the next occurrence and lose the tick it owes with it.
3673+ if (this._owed !== null) return new Response(null, { status: 204 });
3674+ const armed = await this._state.storage.getAlarm();
3675+ // An alarm already due is a tick that is late, not one that is wrong.
3676+ // Leaving it alone is what makes a fleet that was down fire the missed
3677+ // occurrence once, instead of skipping it by re-arming into the future.
3678+ if (armed === null || armed > Date.now()) await this._arm(null, [], false);
3679+ return new Response(null, { status: 204 });
3680+ }
3681+ async alarm(info) {
3682+ const crons = __cell.crons || [];
3683+ // A retry wake carries the backoff instant as its deadline, so what to run
3684+ // and what time to report both come from the record the failure left. Only
3685+ // a deadline that is not a retry is an occurrence to match against.
3686+ const owed = this._owed !== null && this._owed.armedFor === info.scheduledTime
3687+ ? this._owed
3688+ : null;
3689+ const occurrence = owed === null ? info.scheduledTime : owed.at;
3690+ // One deadline can belong to several expressions, and each is its own
3691+ // invocation with its own controller.cron, as on Cloudflare. A retry
3692+ // repeats only the expressions that failed, because the ones that
3693+ // succeeded already ran for this occurrence.
3694+ const due = owed === null
3695+ ? __cron_plan(crons, info.scheduledTime, Date.now(), 0, false).matching
3696+ : owed.indices;
3697+ const failed = [];
3698+ for (const index of due) {
3699+ let noRetry = false;
3700+ const controller = {
3701+ // The occurrence, never the instant this attempt started, so a late
3702+ // run and a retry both report the minute they were scheduled for.
3703+ scheduledTime: occurrence,
3704+ cron: crons[index],
3705+ noRetry() { noRetry = true; },
3706+ };
3707+ const ctx = __beginEvent();
3708+ try {
3709+ if (typeof __cell.selfScheduled !== "function")
3710+ throw new Error(
3711+ "a cron trigger needs the Worker to export a `scheduled` handler");
3712+ await __cell.selfScheduled(controller, __cell.env, ctx);
3713+ } catch (error) {
3714+ // Swallowed on purpose: this handler owns the re-arm below, so
3715+ // throwing would hand the deadline to the generic alarm retry and
3716+ // lose the next occurrence with it.
3717+ console.error(
3718+ `scheduled handler for cron ${JSON.stringify(crons[index])} failed:`,
3719+ error);
3720+ if (!noRetry) failed.push(index);
3721+ } finally {
3722+ __endEvent();
3723+ }
3724+ }
3725+ await this._arm(occurrence, failed, owed !== null);
3726+ }
3727+ // `occurrence` is the tick just handled, or null when the cell is only
3728+ // arming, `failed` holds the expressions of it still owed, and `retried`
3729+ // says the deadline just handled was a backoff rather than an occurrence.
3730+ async _arm(occurrence, failed, retried) {
3731+ const crons = __cell.crons || [];
3732+ // The count is failures within one occurrence, so a fresh occurrence
3733+ // starts at one however the last one ended. Carrying it across would
3734+ // spend `alarm_retry`'s ceiling once and leave every later occurrence
3735+ // with no retry at all, which is a budget for the schedule and not for
3736+ // the tick.
3737+ this._retry = failed.length ? (retried ? this._retry + 1 : 1) : 0;
3738+ // A negative first argument means "arming only, nothing fired".
3739+ const plan = __cron_plan(crons, -1, Date.now(), this._retry, failed.length > 0);
3740+ // The next occurrence beats the backoff whenever it is sooner, and it then
3741+ // cancels the retry rather than queueing behind it, so the record the
3742+ // retry needed goes when the retry does.
3743+ this._owed = plan.armIsRetry
3744+ ? { at: occurrence, indices: failed, armedFor: plan.armAt }
3745+ : null;
3746+ // No expression matches again and nothing is owed: the deployment dropped
3747+ // its crons, so the cell retires rather than waking forever.
3748+ if (plan.armAt === null) await this._state.storage.deleteAlarm();
3749+ else await this._state.storage.setAlarm(plan.armAt);
3750+ }
3751+}
35353752 globalThis.__cell = {
35363753 entrypoints: {},
35373754 objectEntrypoints: {},
35383755 doExports: {},
3539- classes: {},
3756+ classes: { ".cron": CelldCronSchedule },
3757+ crons: [],
35403758 instances: {},
35413759 env: {},
35423760 owned: {},
@@ -3546,7 +3764,348 @@
35463764 deleteAllDeletesAlarm: false,
35473765 compat: { jsRpc: false, fetcherGetPutDelete: false },
35483766 makeNamespace,
3767+ release: __cellRelease,
35493768 };
3769+// ---- D1 -----------------------------------------------------------------
3770+// A D1 database is a cell of a runtime-supplied Durable Object class, so it
3771+// inherits ownership, fencing, LTX replication, RPO=0 acknowledgement and
3772+// pressure shedding from the cell it already is. This half is the server;
3773+// `__makeD1Database` below is the client the binding hands to a Worker.
3774+//
3775+// Everything SQL goes through the one `__d1_run` op. The engine owns the
3776+// statement walk, the row and byte caps, and the meta snapshot, all inside
3777+// one execution — the previous shape assembled these from the general
3778+// SqlStorage ops, and every seam between them was a contract only convention
3779+// enforced.
3780+
3781+// The error families applications match on. A message that already carries
3782+// one must pass through unwrapped: wrapping again would bury the family the
3783+// application is matching under a second D1_ERROR prefix.
3784+const __d1IsFamilyError = (message) =>
3785+ /^D1_([A-Z]+_)*(ERROR|NOTFOUND): /.test(String(message));
3786+
3787+const __d1Error = (message, cause) => {
3788+ const error = new Error("D1_ERROR: " + String(message));
3789+ error.cause = cause !== undefined ? cause : new Error(String(message));
3790+ return error;
3791+};
3792+
3793+// A typed refusal from the engine: `{family, message}` becomes the Error the
3794+// application sees, with `.cause` carrying the bare message as upstream does.
3795+const __d1Failure = (failure) => {
3796+ const error = new Error(failure.family + ": " + failure.message);
3797+ error.cause = new Error(failure.message);
3798+ return error;
3799+};
3800+
3801+const __d1Run = (scope, request) => {
3802+ const response = JSON.parse(__d1_run(scope, JSON.stringify(request)));
3803+ if (response.error) throw __d1Failure(response.error);
3804+ return response.ok;
3805+};
3806+
3807+class __D1DatabaseCell {
3808+ constructor(ctx) {
3809+ this.ctx = ctx;
3810+ }
3811+ // Takes an array so that `batch()` can ride this same method, and the
3812+ // same turn, when it lands.
3813+ __d1Query(statements) {
3814+ const scope = this.ctx.storage.sql._scope;
3815+ return statements.map((statement) =>
3816+ __d1Run(scope, {
3817+ mode: "prepared",
3818+ sql: String(statement.sql),
3819+ params: statement.params || [],
3820+ first: !!statement.first,
3821+ })
3822+ );
3823+ }
3824+ __d1Batch(statements) {
3825+ return __d1Run(this.ctx.storage.sql._scope, {
3826+ mode: "batch",
3827+ statements: statements.map((statement) => ({
3828+ sql: String(statement.sql),
3829+ params: statement.params || [],
3830+ })),
3831+ });
3832+ }
3833+ // The CLI's way in. `celld d1` signs each request with the fleet secret
3834+ // and sends it to a live node's `/__d1/<scope>` route, which verifies the
3835+ // signature and then forwards to the owner over the same dispatch `/do/`
3836+ // uses — so the CLI needs no ownership logic and the database is reached
3837+ // the way a Worker reaches it. The unauthenticated `/do/` route refuses a
3838+ // D1 scope outright: this cell answers arbitrary SQL, and its scope is an
3839+ // HMAC over names that sit in the project's config, so the scope itself
3840+ // is no secret.
3841+ async fetch(request) {
3842+ let body;
3843+ try {
3844+ body = await request.json();
3845+ } catch {
3846+ return Response.json({ error: "D1_ERROR: invalid request body" }, { status: 400 });
3847+ }
3848+ try {
3849+ let result;
3850+ if (body.migrate !== undefined) {
3851+ result = this.__d1Migrate(
3852+ String(body.migrate.name),
3853+ String(body.migrate.sql),
3854+ String(body.migrate.table || "d1_migrations"),
3855+ );
3856+ } else if (body.exec !== undefined) {
3857+ // The CLI asks for rows; the Worker binding's exec() never does.
3858+ result = __d1Run(this.ctx.storage.sql._scope, {
3859+ mode: "exec",
3860+ sql: String(body.exec.sql),
3861+ rows: !!body.exec.rows,
3862+ });
3863+ } else {
3864+ result = this.__d1Query(body.statements || []);
3865+ }
3866+ return Response.json({ result });
3867+ } catch (error) {
3868+ return Response.json({ error: String(error && error.message || error) }, { status: 400 });
3869+ }
3870+ }
3871+ __d1Exec(source) {
3872+ const result = __d1Run(this.ctx.storage.sql._scope, {
3873+ mode: "exec",
3874+ sql: String(source),
3875+ rows: false,
3876+ });
3877+ return { count: result.count, duration: result.duration };
3878+ }
3879+ // Apply one migration and record it. The engine runs the file, the
3880+ // bookkeeping insert (the name is a bound parameter, so a file name never
3881+ // reaches SQL text) and the BEGIN IMMEDIATE .. COMMIT bracket in one
3882+ // request, so a migration that fails part-way rolls back whole and the
3883+ // operator fixes the file and re-runs. Without the transaction the
3884+ // statements that DID land are exactly the ones a re-run trips over.
3885+ __d1Migrate(name, source, table) {
3886+ return __d1Run(this.ctx.storage.sql._scope, {
3887+ mode: "migrate",
3888+ name,
3889+ sql: source,
3890+ table,
3891+ });
3892+ }
3893+}
3894+
3895+__cell.classes.__D1Database = __D1DatabaseCell;
3896+// RPC on a stub needs `extends DurableObject` or the js_rpc flag. This class
3897+// is the runtime's own, so grant it here instead of making every D1 user set
3898+// a compatibility flag to reach their database.
3899+__cell.doExports.__D1Database = true;
3900+
3901+// Validate and encode bind values once, at the public boundary, exactly as
3902+// upstream does (workerd d1-api.ts). Byte-shaped values become byte arrays —
3903+// the wire format for a BLOB bind — and anything unsupported throws
3904+// D1_TYPE_ERROR here, before any SQL runs. The first version deferred this
3905+// to a JSON round-trip whose fallthrough was SQL NULL, so a Uint8Array bind
3906+// stored NULL and nothing said so.
3907+const __d1BindValue = (value) => {
3908+ const kind = typeof value;
3909+ if (kind === "number") {
3910+ // A non-finite number has no JSON form, so it crosses as null and
3911+ // stores SQL NULL. Upstream does the same (bind(NaN) selects typeof
3912+ // "null"); making it explicit here turns the conversion from an
3913+ // accident of JSON.stringify into a pinned decision.
3914+ return Number.isFinite(value) ? value : null;
3915+ }
3916+ if (kind === "string") return value;
3917+ if (kind === "boolean") return value ? 1 : 0;
3918+ if (kind === "object") {
3919+ if (value === null) return value;
3920+ if (
3921+ Array.isArray(value) &&
3922+ value.every((byte) => typeof byte === "number" && byte >= 0 && byte < 256)
3923+ ) {
3924+ return value;
3925+ }
3926+ if (value instanceof ArrayBuffer) {
3927+ return Array.from(new Uint8Array(value));
3928+ }
3929+ // A typed view binds its ELEMENT values, each truncated to a byte —
3930+ // Int8Array([-1]) stores 0xff, Float32Array([1.5]) stores 0x01 — not
3931+ // its underlying byte window, so Uint16Array([65, 66]) stores 2 bytes
3932+ // and not 4. Upstream behaves this way (verified against workerd's D1;
3933+ // the differential suite pins it), and the bare Array.from that
3934+ // preceded this produced elements the engine then refused as bytes.
3935+ if (ArrayBuffer.isView(value)) return Array.from(Uint8Array.from(value));
3936+ }
3937+ const error = new Error(
3938+ `D1_TYPE_ERROR: Type '${kind}' not supported for value '${value}'`,
3939+ );
3940+ error.cause = new Error(`Type '${kind}' not supported for value '${value}'`);
3941+ throw error;
3942+};
3943+
3944+class D1PreparedStatement {
3945+ constructor(database, sql, params) {
3946+ Object.defineProperty(this, "_database", { value: database });
3947+ Object.defineProperty(this, "_sql", { value: sql });
3948+ Object.defineProperty(this, "_params", { value: params });
3949+ }
3950+ bind(...values) {
3951+ return new D1PreparedStatement(
3952+ this._database,
3953+ this._sql,
3954+ values.map(__d1BindValue),
3955+ );
3956+ }
3957+ async _run(first) {
3958+ const results = await this._database._query([
3959+ { sql: this._sql, params: this._params, first },
3960+ ]);
3961+ return results[0];
3962+ }
3963+ async all() {
3964+ const result = await this._run();
3965+ return {
3966+ success: true,
3967+ meta: result.meta,
3968+ results: result.rows.map((row) => __d1Shape(result.columns, row)),
3969+ };
3970+ }
3971+ async run() {
3972+ return await this.all();
3973+ }
3974+ async first(column) {
3975+ // `first: true` keeps one row on the cell side, so only that row crosses
3976+ // the isolate boundary and the row cap cannot fire for a first().
3977+ const result = await this._run(true);
3978+ if (result.rows.length === 0) return null;
3979+ const row = __d1Shape(result.columns, result.rows[0]);
3980+ if (column === undefined) return row;
3981+ // The check runs on the shaped object, as upstream's does, so a column
3982+ // named like an Object.prototype member behaves the same here as there.
3983+ if (row[column] === undefined) {
3984+ const error = new Error(
3985+ `D1_COLUMN_NOTFOUND: Column not found (${column})`,
3986+ );
3987+ error.cause = new Error("Column not found");
3988+ throw error;
3989+ }
3990+ return row[column];
3991+ }
3992+ async raw(options) {
3993+ const result = await this._run();
3994+ return options && options.columnNames
3995+ ? [result.columns, ...result.rows]
3996+ : result.rows;
3997+ }
3998+}
3999+
4000+// Object.fromEntries, not property assignment: assigning to a column named
4001+// `__proto__` would walk the prototype chain and silently drop the value,
4002+// while fromEntries defines an own property whatever the name.
4003+const __d1Shape = (columns, row) =>
4004+ Object.fromEntries(row.map((value, index) => [columns[index], value]));
4005+
4006+const __d1PublicResult = (result) => ({
4007+ success: true,
4008+ meta: result.meta,
4009+ results: result.rows.map((row) => __d1Shape(result.columns, row)),
4010+});
4011+
4012+// celld has one primary and no replicas, so every completed query satisfies
4013+// every earlier session constraint. One stable opaque token states that fact
4014+// without pretending an isolate-local counter is a durable database position.
4015+const __d1PrimaryBookmark = "celld:primary";
4016+
4017+class D1DatabaseSession {
4018+ constructor(database, constraintOrBookmark) {
4019+ Object.defineProperty(this, "_database", { value: database });
4020+ const value = constraintOrBookmark == null
4021+ ? "first-unconstrained"
4022+ : String(constraintOrBookmark).trim();
4023+ if (!value) {
4024+ throw new Error("D1_SESSION_ERROR: invalid bookmark or constraint");
4025+ }
4026+ Object.defineProperty(this, "_bookmark", {
4027+ value: value === "first-primary" || value === "first-unconstrained" ? null : value,
4028+ writable: true,
4029+ });
4030+ }
4031+ _advanceBookmark() {
4032+ this._bookmark = __d1PrimaryBookmark;
4033+ }
4034+ async _query(statements) {
4035+ const results = await this._database._query(statements);
4036+ this._advanceBookmark();
4037+ return results;
4038+ }
4039+ prepare(sql) {
4040+ return new D1PreparedStatement(this, String(sql), []);
4041+ }
4042+ async batch(statements) {
4043+ const results = await this._database._batch(statements);
4044+ this._advanceBookmark();
4045+ return results;
4046+ }
4047+ getBookmark() {
4048+ return this._bookmark;
4049+ }
4050+}
4051+
4052+// Named so SDKs that sniff a binding by `constructor.name` recognise it.
4053+class D1Database {
4054+ constructor(databaseName) {
4055+ Object.defineProperty(this, "_databaseName", { value: databaseName });
4056+ }
4057+ // Resolved per call rather than cached: a cell can move between calls, and
4058+ // `getByName` is the same cost the Durable Object path already pays.
4059+ get _stub() {
4060+ return __cell.makeNamespace("__D1Database").getByName(this._databaseName);
4061+ }
4062+ async _query(statements) {
4063+ try {
4064+ return await this._stub.__d1Query(statements);
4065+ } catch (error) {
4066+ if (__d1IsFamilyError(error && error.message)) throw error;
4067+ throw __d1Error(String(error && error.message || error), error);
4068+ }
4069+ }
4070+ async _batch(statements) {
4071+ try {
4072+ const encoded = statements.map((statement) => ({
4073+ sql: statement._sql,
4074+ params: statement._params,
4075+ }));
4076+ const results = await this._stub.__d1Batch(encoded);
4077+ return results.map(__d1PublicResult);
4078+ } catch (error) {
4079+ if (__d1IsFamilyError(error && error.message)) throw error;
4080+ throw __d1Error(String(error && error.message || error), error);
4081+ }
4082+ }
4083+ prepare(sql) {
4084+ return new D1PreparedStatement(this, String(sql), []);
4085+ }
4086+ async exec(sql) {
4087+ try {
4088+ return await this._stub.__d1Exec(String(sql));
4089+ } catch (error) {
4090+ if (__d1IsFamilyError(error && error.message)) throw error;
4091+ throw __d1Error(String(error && error.message || error), error);
4092+ }
4093+ }
4094+ async batch(statements) {
4095+ return await this._batch(statements);
4096+ }
4097+ withSession(constraintOrBookmark) {
4098+ return new D1DatabaseSession(this, constraintOrBookmark);
4099+ }
4100+ async dump() {
4101+ throw __d1Error(
4102+ "dump() is not implemented in celld; the database is a SQLite file in " +
4103+ "your own bucket",
4104+ );
4105+ }
4106+}
4107+
4108+globalThis.__makeD1Database = (databaseName) => new D1Database(databaseName);
35504109 // `cloudflare:workers` module surface. The DO base class sets ctx/env the
35514110 // way `class X extends DurableObject` expects; env aliases the cell env.
35524111 globalThis.__cf = {
@@ -4251,10 +4810,17 @@
42514810 static READY_STATE_OPEN = 1;
42524811 static READY_STATE_CLOSING = 2;
42534812 static READY_STATE_CLOSED = 3;
4254- constructor(id, protocols = []) {
4813+ constructor(id, protocols = [], boundTarget = null) {
42554814 super();
4256- const outbound = typeof id === "string";
4815+ const dialed = typeof id === "string";
4816+ // A socket bound to a Durable Object's socket behaves like a dialed one
4817+ // in every way that matters here: the host carries its frames, so every
4818+ // operation goes out through `__ws_*` on this id rather than to a peer
4819+ // in this heap.
4820+ const outbound = dialed || boundTarget !== null;
42574821 this._outbound = outbound;
4822+ this._boundTarget = boundTarget;
4823+ this._bound = false;
42584824 this._pendingClose = null;
42594825 this._id = outbound ? __ws_alloc() : Number(id);
42604826 this._attachment = undefined;
@@ -4271,11 +4837,19 @@
42714837 ? "blob"
42724838 : "arraybuffer";
42734839 // A server-side socket has no URL, and reports null rather than an empty
4274- // string -- workerd's inspect output pins this.
4275- this.url = outbound ? id : null;
4840+ // string -- workerd's inspect output pins this. A socket that came back
4841+ // from an upgrade has none either: nothing in this isolate dialed it.
4842+ this.url = dialed ? id : null;
42764843 this.protocol = "";
42774844 this.extensions = "";
4278- if (outbound) {
4845+ if (boundTarget !== null) {
4846+ // The caller drives this socket itself, exactly as a Worker drives one
4847+ // it opened. The host pipe is not built until `accept()`, so a
4848+ // response passed straight back out is left alone.
4849+ this._polled = true;
4850+ this._target = boundTarget;
4851+ }
4852+ if (dialed) {
42794853 // workerd validates the URL in the constructor and throws
42804854 // synchronously; letting the connector reject later would surface a
42814855 // scheme mistake as a network failure instead of a TypeError.
@@ -4413,6 +4987,16 @@
44134987 // A socket obtained from a `fetch()` upgrade is already connected and
44144988 // delivers nothing until it is accepted; this is where it starts.
44154989 if (this._outbound && this.readyState === WebSocket.READY_STATE_CONNECTING) {
4990+ // Bind before the pump: the op registers this socket's queue on this
4991+ // thread, so the first `__ws_next` cannot run ahead of it.
4992+ if (this._boundTarget !== null && !this._bound) {
4993+ this._bound = true;
4994+ __ws_bind_target(
4995+ this._id,
4996+ JSON.stringify(this._boundTarget),
4997+ __actorEventStack[__actorEventStack.length - 1] || "",
4998+ );
4999+ }
44165000 this.readyState = WebSocket.READY_STATE_OPEN;
44175001 if (this._polled) this._startPump();
44185002 }
modifiedcrates/celld/js/modules.rs+2−42View file
@@ -60,52 +60,12 @@
6060 /// builtin)? esbuild bundles every npm dep inline and leaves only builtins
6161 /// external, so a remaining bare specifier is a node builtin.
6262 fn is_external(spec: &str) -> bool {
63- const BARE: &[&str] = &[
64- "path",
65- "os",
66- "fs",
67- "fs/promises",
68- "crypto",
69- "stream",
70- "util",
71- "util/types",
72- "assert",
73- "module",
74- "process",
75- "tty",
76- "url",
77- "v8",
78- "constants",
79- "buffer",
80- "events",
81- "zlib",
82- "child_process",
83- "http",
84- "https",
85- "http2",
86- "net",
87- "tls",
88- "dns",
89- "readline",
90- "string_decoder",
91- "querystring",
92- "async_hooks",
93- "perf_hooks",
94- "worker_threads",
95- "vm",
96- "diagnostics_channel",
97- "timers",
98- "inspector",
99- "dgram",
100- "cluster",
101- "punycode",
102- "sqlite",
103- ];
10463 if spec.starts_with("node:") || spec.starts_with("cloudflare:") {
10564 return true;
10665 }
10766 // bare builtin, or a builtin submodule like `stream/promises`
108- BARE.contains(&spec) || BARE.contains(&spec.split('/').next().unwrap_or(""))
67+ BARE_NODE_BUILTINS.contains(&spec)
68+ || BARE_NODE_BUILTINS.contains(&spec.split('/').next().unwrap_or(""))
10969 }
11070
11171 fn scan_external_imports(
modifiedcrates/celld/js/node_crypto.js+34−4View file
@@ -495,6 +495,12 @@
495495 return asU8(bytes);
496496 };
497497
498+ // The ciphers celld can seal a PKCS#8 export under. Node reaches every
499+ // cipher OpenSSL carries, so this list is the short one, and a name outside
500+ // it is refused by name -- a silent fall back to one of these would seal the
501+ // key under a cipher the caller never asked for.
502+ const PKCS8_CIPHERS = ["aes-128-cbc", "aes-192-cbc", "aes-256-cbc"];
503+
498504 function validateExportOptions(options, type, name = "options") {
499505 validateObject(options, name);
500506 if (options.format !== undefined)
@@ -505,12 +511,30 @@
505511 if (type === "private" && "cipher" in options &&
506512 options.cipher !== undefined) {
507513 validateString(options.cipher, `${name}.cipher`);
514+ // OpenSSL resolves a cipher name case-insensitively, so Node takes
515+ // "AES-256-CBC" as readily as the lower-case spelling. The host matches
516+ // the lower-case name only, so normalize here, once, for both callers.
517+ options.cipher = options.cipher.toLowerCase();
518+ if (!PKCS8_CIPHERS.includes(options.cipher))
519+ throw ERR_METHOD_NOT_IMPLEMENTED(`${name}.cipher ${options.cipher}`);
520+ // Encryption here is the PKCS#8 wrapper and nothing else. For sec1 and
521+ // pkcs1 Node writes a traditional PEM instead -- an "EC PRIVATE KEY"
522+ // body behind Proc-Type and DEK-Info headers -- which celld cannot
523+ // produce, so it is refused rather than answered with a PKCS#8 key
524+ // under a header the caller did not ask for.
525+ if (options.type !== undefined && options.type !== "pkcs8")
526+ throw ERR_METHOD_NOT_IMPLEMENTED(`an encrypted ${options.type} export`);
508527 if (typeof options.passphrase === "string")
509528 options.passphrase = Buffer.from(options.passphrase, options.encoding);
510529 if (!isUint8Array(options.passphrase)) {
511530 throw ERR_INVALID_ARG_TYPE(
512531 `${name}.passphrase`, ["string", "Uint8Array"], options.passphrase);
513532 }
533+ } else if (type === "private" && options.passphrase !== undefined) {
534+ // A passphrase with no cipher named nothing to encrypt under. Node
535+ // refuses it, and so must celld: the alternative is to pick a cipher
536+ // the caller never asked for, or to write the key out in the clear.
537+ throw ERR_INVALID_ARG_VALUE(`${name}.cipher`, options.cipher);
514538 }
515539 }
516540
@@ -561,9 +585,9 @@
561585 visibility: this.type,
562586 format: options.format,
563587 type: options.type,
564- // A passphrase makes this an encrypted PKCS#8 export. The cipher
565- // name is accepted but not honoured -- pkcs5 picks its own scheme,
566- // and the result re-imports either way.
588+ // A passphrase makes this an encrypted PKCS#8 export, and the
589+ // cipher names the scheme the host encrypts under.
590+ cipher: options.cipher,
567591 passphrase: options.passphrase === undefined ? null : Array.from(
568592 asU8(typeof options.passphrase === "string"
569593 ? Buffer.from(options.passphrase)
@@ -905,12 +929,18 @@
905929 { keyType: pair.keyType, der, details: pair.details }, visibility);
906930 }
907931 // With an encoding, Node returns the encoded key itself rather than a
908- // KeyObject: a string for pem, a Buffer for der.
932+ // KeyObject: a string for pem, a Buffer for der. A private encoding
933+ // can carry a cipher and a passphrase, which seal the key the same way
934+ // `KeyObject.export` does -- celld dropped them before, so a caller
935+ // that asked for an encrypted key got a plaintext one.
909936 const out = keyOp("asym-key-reencode", {
910937 der,
911938 visibility,
912939 format: encoding.format,
913940 type: encoding.type,
941+ cipher: encoding.cipher,
942+ passphrase: encoding.passphrase === undefined ? null : Array.from(
943+ asU8(encoding.passphrase)),
914944 });
915945 return out.pem !== undefined ? out.pem : Buffer.from(out.der);
916946 };
modifiedcrates/celld/js/storage_ops.rs+14−0View file
@@ -326,6 +326,20 @@
326326 Err(error) => throw_storage_error(scope, "sql.databaseSize", error),
327327 }
328328 }
329+/// `__d1_run(cell, request)` — the D1 adapter's one op. The request and the
330+/// reply are the typed structures in `storage::d1_run`; nothing D1 crosses
331+/// this boundary through the general SQL ops, so the D1 contract cannot
332+/// drift apart from itself one op at a time.
333+pub(super) fn op_d1_run(
334+ scope: &mut v8::PinScope,
335+ args: v8::FunctionCallbackArguments,
336+ mut rv: v8::ReturnValue<v8::Value>,
337+) {
338+ let cell = args.get(0).to_rust_string_lossy(scope);
339+ let request = args.get(1).to_rust_string_lossy(scope);
340+ let out = storage::d1_run_json(&cell, &request);
341+ rv.set(v8::String::new(scope, &out).unwrap().into());
342+}
329343 #[cfg(all(test, celld_internal_tests))]
330344 pub(super) fn op_sql_set_max_page_count_for_test(
331345 scope: &mut v8::PinScope,
modifiedcrates/celld/js/text_encoding.js+59−228View file
@@ -2,20 +2,40 @@
22 // Extracted module from the bootstrap.js IIFE.
33 //
44 // TextEncoder always emits UTF-8 (per spec). TextDecoder
5-// decodes utf-8 / utf-16le / utf-16be in pure JS — the
6-// hot path, no host ops. Every other WHATWG label
7-// (windows-1252, big5, gbk/gb18030, iso-2022-jp,
8-// x-user-defined, …) is the slow path: encoding_rs on
9-// the host via the $$textDecoder* ops, one call per
10-// decode() with native streaming state per decoder.
5+// decodes nothing itself: every label, utf-8 and utf-16
6+// included, goes to encoding_rs on the host via the
7+// $$textDecoder* ops, one call per decode() with native
8+// streaming state per decoder. This file resolves the
9+// label and owns the decoder's lifetime.
10+//
11+// Previous utf-8 and utf-16 hand-written JS decoders kept a
12+// host call off a small `request.text()`, but measurement did
13+// not support that design: the host was faster at every size
14+// down to 16 bytes,
15+// and what a JS decode cost depended on the decodes that
16+// ran before it. A cell that decoded a few hundred small
17+// or malformed bodies first spent 48ms per MiB on a bulk
18+// decode, against 5ms for the same binary that decoded
19+// one large body first. The order was the only
20+// difference, the effect was sticky, and the ratio was
21+// the ratio between V8's interpreter and its optimizing
22+// tier. The mechanism was not traced further, so no claim
23+// is made about which feedback caused it — but the
24+// traffic that provoked it was ordinary, and no shape of
25+// the JS decoder resisted it. Two decoders for one
26+// encoding also owe a byte-for-byte equivalence proof,
27+// and that debt had already shipped one bug: a utf-16
28+// buffer ending in an unpaired lead surrogate and an odd
29+// byte yielded two U+FFFD in JS and one on the host.
1130 (function () {
1231 const _tdLabel = $$textDecoderLabel;
1332 const _tdNew = $$textDecoderNew;
1433 const _tdDecode = $$textDecoderDecode;
34+ const _tdDecodeOnce = $$textDecoderDecodeOnce;
1535 const _tdFree = $$textDecoderFree;
1636 // Frees native decoders abandoned mid-stream. Ids
1737 // are never reused, so a late free is a no-op.
18- // Created on first legacy stream, not at boot.
38+ // Created on the first stream, not at boot.
1939 let _tdRegistry;
2040 const _tdTrack = (target, id) => {
2141 if (_tdRegistry === undefined) {
@@ -133,21 +153,22 @@
133153 #encoding;
134154 #fatal;
135155 #ignoreBOM;
136- #pending = [];
137- #bomSeen = false;
138- // Live native decoder id while a legacy-encoding
139- // stream is in flight; undefined otherwise.
140- #legacyId;
156+ // Live native decoder id while a stream is in
157+ // flight; undefined otherwise.
158+ #nativeId;
141159 constructor(label = 'utf-8', options = {}) {
142160 // Per WHATWG encoding: strip ASCII whitespace
143161 // only (not Unicode — \v, NBSP, etc. stay).
144162 label = String(label)
145163 .replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g, '')
146164 .toLowerCase();
147- // The full WHATWG label set for the pure-JS encodings. A miss
148- // here (e.g. 'ansi_x3.4-1968', which the standard maps to
149- // windows-1252 rather than utf-8) resolves through the host's
150- // encoding_rs label table instead.
165+ // The WHATWG label set for utf-8 and utf-16, resolved here to
166+ // keep a host call out of `new TextDecoder()` — which every
167+ // `request.text()` makes. A miss (e.g. 'ansi_x3.4-1968',
168+ // which the standard maps to windows-1252 rather than utf-8)
169+ // resolves through the host's encoding_rs label table
170+ // instead. Both answers are encoding_rs labels, so the
171+ // decode itself does not care which way the name arrived.
151172 const aliases = {
152173 'utf-8': 'utf-8', 'utf8': 'utf-8',
153174 'unicode-1-1-utf-8': 'utf-8',
@@ -168,8 +189,8 @@
168189 if (!enc) {
169190 // undefined covers unknown labels and the replacement
170191 // encoding — both RangeError per spec. A resolved name
171- // is canonical lowercase; route utf names (all already
172- // aliases keys) back to the pure-JS path.
192+ // is canonical lowercase, and the alias lookup then
193+ // normalizes the utf names to the spelling above.
173194 const name = _tdLabel(label);
174195 if (name === undefined) throw new RangeError(
175196 `The encoding label` +
@@ -217,227 +238,37 @@
217238 + " a BufferSource",
218239 );
219240 }
220- // Prepend any pending bytes.
221- if (this.#pending.length > 0) {
222- const merged = new Uint8Array(
223- this.#pending.length + b.length);
224- merged.set(this.#pending);
225- merged.set(b, this.#pending.length);
226- b = merged;
227- this.#pending = [];
228- }
229- if (this.#encoding === 'utf-8') {
230- return this._decode8(b, stream);
231- }
232- if (this.#encoding === 'utf-16le' ||
233- this.#encoding === 'utf-16be') {
234- return this._decode16(b, stream);
235- }
236- return this._decodeLegacy(b, stream);
241+ return this._decodeNative(b, stream);
237242 }
238- // Legacy WHATWG encodings: one host op per decode(). Streaming
239- // state (multibyte carry-over, ISO-2022-JP mode) lives in the
240- // native decoder; a fatal error frees it, matching Workerd —
241- // the next decode starts clean.
242- _decodeLegacy(b, stream) {
243- let id = this.#legacyId;
243+ // One op per decode(), for every label. Streaming state (a split
244+ // multibyte sequence, a BOM, ISO-2022-JP mode) lives in the
245+ // native decoder; a fatal error frees it, matching Workerd — the
246+ // next decode starts clean.
247+ _decodeNative(b, stream) {
248+ let id = this.#nativeId;
249+ // A complete buffer with no stream around it
250+ // needs no decoder that outlives the call, so
251+ // it takes the one-shot op and never reaches
252+ // the host's decoder table.
253+ if (id === undefined && !stream) {
254+ return _tdDecodeOnce(
255+ this.#encoding, b, this.#fatal,
256+ this.#ignoreBOM);
257+ }
244258 if (id === undefined) {
245259 id = _tdNew(this.#encoding, this.#ignoreBOM);
246- if (stream) {
247- this.#legacyId = id;
248- _tdTrack(this, id);
249- }
260+ this.#nativeId = id;
261+ _tdTrack(this, id);
250262 } else if (!stream) {
251- this.#legacyId = undefined;
263+ this.#nativeId = undefined;
252264 }
253265 try {
254266 return _tdDecode(id, b, this.#fatal, !stream);
255267 } catch (e) {
256- this.#legacyId = undefined;
268+ this.#nativeId = undefined;
257269 throw e;
258270 }
259271 }
260- _decode8(b, stream) {
261- const fatal = this.#fatal;
262- const fail = () => {
263- if (fatal) throw new TypeError(
264- 'The encoded data is not valid.');
265- return '�';
266- };
267- const isCont = (x) =>
268- x !== undefined && (x & 0xC0) === 0x80;
269- // Expected byte count for lead byte.
270- const seqLen = (c) => {
271- if (c < 0x80) return 1;
272- if ((c & 0xE0) === 0xC0) return 2;
273- if ((c & 0xF0) === 0xE0) return 3;
274- if ((c & 0xF8) === 0xF0) return 4;
275- return 0; // invalid
276- };
277- let s = '', i = 0;
278- if (!this.#bomSeen && !this.#ignoreBOM &&
279- b.length >= 3 && b[0]===0xEF &&
280- b[1]===0xBB && b[2]===0xBF) {
281- i = 3;
282- this.#bomSeen = true;
283- }
284- while (i < b.length) {
285- const c0 = b[i];
286- const need = seqLen(c0);
287- if (need === 0) {
288- s += fail(); i++; continue;
289- }
290- if (need === 1) {
291- s += String.fromCharCode(c0);
292- i++; continue;
293- }
294- // Early reject invalid lead bytes.
295- if (need === 2 && c0 < 0xC2)
296- { s += fail(); i++; continue; }
297- if (need === 4 && c0 > 0xF4)
298- { s += fail(); i++; continue; }
299- // Find how many valid cont bytes follow.
300- let valid = 0;
301- for (let j = 1; j < need &&
302- i + j < b.length; j++) {
303- if (!isCont(b[i+j])) break;
304- valid++;
305- }
306- const have = 1 + valid;
307- // Range checks on partial data.
308- let rangeOk = true;
309- if (valid >= 1 && need >= 3) {
310- const b1 = b[i+1];
311- if (need===3 && c0===0xE0 && b1<0xA0)
312- rangeOk = false;
313- if (need===3 && c0===0xED && b1>=0xA0)
314- rangeOk = false;
315- if (need===4 && c0===0xF0 && b1<0x90)
316- rangeOk = false;
317- if (need===4 && c0===0xF4 && b1>=0x90)
318- rangeOk = false;
319- }
320- if (!rangeOk) {
321- s += fail(); i++; continue;
322- }
323- if (have < need) {
324- // Buffer only if we're at end of
325- // input and all bytes so far are
326- // valid continuations.
327- if (stream &&
328- i + have === b.length) {
329- this.#pending =
330- Array.from(b.slice(i));
331- break;
332- }
333- // Emit one FFFD, skip past valid
334- // continuation bytes.
335- s += fail();
336- i += have;
337- continue;
338- }
339- if (need === 2) {
340- s += String.fromCharCode(
341- ((c0&0x1F)<<6)
342- |(b[i+1]&0x3F));
343- i += 2;
344- } else if (need === 3) {
345- const cp = ((c0&0x0F)<<12)
346- |((b[i+1]&0x3F)<<6)
347- |(b[i+2]&0x3F);
348- if (cp < 0x800 ||
349- (cp>=0xD800 && cp<=0xDFFF))
350- { s += fail(); i++; continue; }
351- s += String.fromCharCode(cp);
352- i += 3;
353- } else {
354- const cp = ((c0&0x07)<<18)
355- |((b[i+1]&0x3F)<<12)
356- |((b[i+2]&0x3F)<<6)
357- |(b[i+3]&0x3F);
358- if (cp < 0x10000 || cp > 0x10FFFF)
359- { s += fail(); i++; continue; }
360- s += String.fromCodePoint(cp);
361- i += 4;
362- }
363- }
364- // A non-stream decode ends the sequence: the
365- // next call starts a fresh decoder, so BOM
366- // stripping applies again (spec step 1).
367- if (!stream) {
368- this.#pending = [];
369- this.#bomSeen = false;
370- }
371- return s;
372- }
373- _decode16(b, stream) {
374- const be = this.#encoding === 'utf-16be';
375- const fatal = this.#fatal;
376- const fail = () => {
377- if (fatal) throw new TypeError(
378- 'The encoded data is not valid.');
379- return '�';
380- };
381- let s = '', i = 0;
382- if (!this.#bomSeen && !this.#ignoreBOM &&
383- b.length >= 2) {
384- if (b[0]===0xFF && b[1]===0xFE && !be) {
385- i = 2; this.#bomSeen = true;
386- } else if (b[0]===0xFE &&
387- b[1]===0xFF && be) {
388- i = 2; this.#bomSeen = true;
389- }
390- }
391- while (i + 1 < b.length) {
392- const unitStart = i;
393- const lo = be ? b[i+1] : b[i];
394- const hi = be ? b[i] : b[i+1];
395- const code = lo | (hi << 8);
396- i += 2;
397- if (code >= 0xD800 && code <= 0xDBFF) {
398- // Lead surrogate — look for trail.
399- if (i + 1 < b.length) {
400- const lo2 = be ? b[i+1] : b[i];
401- const hi2 = be ? b[i] : b[i+1];
402- const trail = lo2 | (hi2 << 8);
403- if (trail >= 0xDC00
404- && trail <= 0xDFFF) {
405- const cp =
406- ((code - 0xD800) << 10)
407- + (trail - 0xDC00)
408- + 0x10000;
409- i += 2;
410- s += String.fromCodePoint(cp);
411- continue;
412- }
413- s += fail();
414- continue;
415- }
416- if (stream) {
417- i = unitStart;
418- break;
419- }
420- s += fail();
421- } else if (code >= 0xDC00
422- && code <= 0xDFFF) {
423- s += fail();
424- } else {
425- s += String.fromCharCode(code);
426- }
427- }
428- if (i < b.length) {
429- if (stream) {
430- this.#pending =
431- Array.from(b.slice(i));
432- } else if (this.#fatal) {
433- throw new TypeError(
434- 'The encoded data is not valid.'
435- );
436- }
437- }
438- if (!stream) this.#bomSeen = false;
439- return s;
440- }
441272 };
442273 // Web IDL toStringTag.
443274 Object.defineProperty(globalThis.TextEncoder.prototype,
modifiedcrates/celld/js/websocket.rs+213−29View file
@@ -186,15 +186,31 @@
186186 }
187187 }
188188 }
189-static WS_REGISTRY: OnceLock<std::sync::Mutex<WsRegistry>> = OnceLock::new();
190-static REGULAR_WS_COUNTS: OnceLock<std::sync::Mutex<HashMap<String, usize>>> = OnceLock::new();
191-static NEXT_WS_ID: AtomicU64 = AtomicU64::new(1);
192-fn ws_registry() -> &'static std::sync::Mutex<WsRegistry> {
193- WS_REGISTRY.get_or_init(|| std::sync::Mutex::new(WsRegistry::default()))
189+pub(crate) struct WebSocketService {
190+ registry: Arc<std::sync::Mutex<WsRegistry>>,
191+ regular_counts: Arc<std::sync::Mutex<HashMap<String, usize>>>,
192+ next_id: AtomicU64,
193+ auto_responses: Arc<std::sync::Mutex<HashMap<String, (String, String)>>>,
194194 }
195-fn regular_ws_counts() -> &'static std::sync::Mutex<HashMap<String, usize>> {
196- REGULAR_WS_COUNTS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
195+
196+impl Default for WebSocketService {
197+ fn default() -> Self {
198+ Self {
199+ registry: Arc::new(std::sync::Mutex::new(WsRegistry::default())),
200+ regular_counts: Arc::new(std::sync::Mutex::new(HashMap::new())),
201+ next_id: AtomicU64::new(1),
202+ auto_responses: Arc::new(std::sync::Mutex::new(HashMap::new())),
203+ }
204+ }
197205 }
206+
207+fn ws_registry() -> Arc<std::sync::Mutex<WsRegistry>> {
208+ asyncrt::services().websockets().registry.clone()
209+}
210+
211+fn regular_ws_counts() -> Arc<std::sync::Mutex<HashMap<String, usize>>> {
212+ asyncrt::services().websockets().regular_counts.clone()
213+}
198214 fn increment_regular_ws(scope: &str) {
199215 *regular_ws_counts()
200216 .lock()
@@ -203,7 +219,8 @@
203219 .or_default() += 1;
204220 }
205221 fn decrement_regular_ws(scope: &str) {
206- let mut counts = regular_ws_counts().lock().unwrap();
222+ let counts = regular_ws_counts();
223+ let mut counts = counts.lock().unwrap();
207224 let Some(count) = counts.get_mut(scope) else {
208225 return;
209226 };
@@ -223,11 +240,8 @@
223240 /// `state.setWebSocketAutoResponse`. Shell state, like the socket registry:
224241 /// the whole point of the feature is answering a matched message while the
225242 /// cell is not resident, so the isolate cannot hold it.
226-static WS_AUTO_RESPONSE: OnceLock<std::sync::Mutex<HashMap<String, (String, String)>>> =
227- OnceLock::new();
228-
229-fn ws_auto_responses() -> &'static std::sync::Mutex<HashMap<String, (String, String)>> {
230- WS_AUTO_RESPONSE.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
243+fn ws_auto_responses() -> Arc<std::sync::Mutex<HashMap<String, (String, String)>>> {
244+ asyncrt::services().websockets().auto_responses.clone()
231245 }
232246
233247 /// The shell's read path asks here before dispatching a text frame. A match
@@ -237,14 +251,16 @@
237251 /// lives in the hibernation manager's read loop.
238252 pub fn ws_auto_response(scope: &str, id: u64, text: &str) -> Option<String> {
239253 let response = {
240- let pairs = ws_auto_responses().lock().unwrap();
254+ let pairs = ws_auto_responses();
255+ let pairs = pairs.lock().unwrap();
241256 let (request, response) = pairs.get(scope)?;
242257 if request != text {
243258 return None;
244259 }
245260 response.clone()
246261 };
247- let mut registry = ws_registry().lock().unwrap();
262+ let registry = ws_registry();
263+ let mut registry = registry.lock().unwrap();
248264 let meta = registry.metadata.get_mut(&id)?;
249265 if !meta.hibernatable {
250266 return None;
@@ -254,10 +270,7 @@
254270 }
255271
256272 fn unix_ms() -> f64 {
257- std::time::SystemTime::now()
258- .duration_since(std::time::UNIX_EPOCH)
259- .unwrap()
260- .as_millis() as f64
273+ asyncrt::wall_ms() as f64
261274 }
262275
263276 pub fn ws_hibernatable(id: u64) -> Option<bool> {
@@ -269,14 +282,41 @@
269282 .map(|meta| meta.hibernatable)
270283 }
271284 pub fn ws_next_id() -> u64 {
272- NEXT_WS_ID.fetch_add(1, Ordering::Relaxed)
285+ asyncrt::services()
286+ .websockets()
287+ .next_id
288+ .fetch_add(1, Ordering::Relaxed)
273289 }
274290 pub fn ws_register(id: u64, tx: tokio::sync::mpsc::UnboundedSender<WsOut>) {
275291 ws_registry().lock().unwrap().register(id, tx);
276292 }
293+
294+/// Install one hibernatable socket in a private deterministic World.
295+#[cfg(all(test, celld_internal_tests))]
296+pub(crate) fn ws_register_hibernatable_for_test(
297+ id: u64,
298+ scope: &str,
299+ tx: tokio::sync::mpsc::UnboundedSender<WsOut>,
300+) {
301+ let registry = ws_registry();
302+ let mut registry = registry.lock().unwrap();
303+ registry.register(id, tx);
304+ registry.metadata.insert(
305+ id,
306+ WsMeta {
307+ scope: scope.to_string(),
308+ hibernatable: true,
309+ tags: Vec::new(),
310+ attachment: None,
311+ pending: Vec::new(),
312+ auto_response_at: None,
313+ },
314+ );
315+}
277316 pub fn ws_register_outbound(id: u64, scope: &str) {
278317 let inserted = {
279- let mut registry = ws_registry().lock().unwrap();
318+ let registry = ws_registry();
319+ let mut registry = registry.lock().unwrap();
280320 if let std::collections::hash_map::Entry::Vacant(entry) = registry.metadata.entry(id) {
281321 entry.insert(WsMeta {
282322 scope: scope.to_string(),
@@ -328,7 +368,8 @@
328368 /// the loop never finishes, so the frame is never released. Frames from those
329369 /// sockets go straight out, as they did before the gate existed.
330370 fn ws_gate_may_hold(id: u64) -> bool {
331- let registry = ws_registry().lock().unwrap();
371+ let registry = ws_registry();
372+ let registry = registry.lock().unwrap();
332373 registry
333374 .metadata
334375 .get(&id)
@@ -354,6 +395,67 @@
354395 WS_DEFERRED.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
355396 }
356397
398+static WS_FLUSHES: OnceLock<std::sync::Mutex<HashMap<u64, usize>>> = OnceLock::new();
399+
400+/// How many flushes still hold frames for a socket. A count, not a flag: one
401+/// flush can finish and drain its queue while a later frame starts another.
402+fn ws_flushes() -> &'static std::sync::Mutex<HashMap<u64, usize>> {
403+ WS_FLUSHES.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
404+}
405+
406+static WS_FLUSH_DONE: OnceLock<tokio::sync::Notify> = OnceLock::new();
407+fn ws_flush_done() -> &'static tokio::sync::Notify {
408+ WS_FLUSH_DONE.get_or_init(tokio::sync::Notify::new)
409+}
410+
411+/// Counts one flush out on every exit path, including the ones that run no
412+/// code: a flush spawned onto a runtime that is already shutting down is
413+/// dropped unpolled, and a panic unwinds through it. A count left behind by
414+/// either would park the socket's teardown. Held by the flush, so the count
415+/// falls whether it finished, failed, or never ran. It cannot help a flush
416+/// that is merely parked -- nothing drops, so nothing runs -- which is what
417+/// the teardown wait is bounded for.
418+struct WsFlushGuard(u64);
419+
420+impl Drop for WsFlushGuard {
421+ fn drop(&mut self) {
422+ {
423+ let mut flushes = ws_flushes().lock().unwrap();
424+ if let Some(count) = flushes.get_mut(&self.0) {
425+ *count -= 1;
426+ if *count == 0 {
427+ flushes.remove(&self.0);
428+ }
429+ }
430+ }
431+ ws_flush_done().notify_waiters();
432+ }
433+}
434+
435+/// Wait until no flush holds frames for `id` any more.
436+///
437+/// The socket's own teardown calls this. Closing reads the handler's output
438+/// with a non-blocking drain and, finding none, answers the peer with the
439+/// protocol echo of the close the peer itself sent -- so a close frame still
440+/// behind the gate is not merely late, it is replaced. The wait is bounded by
441+/// the gate: a cell with no barrier answers at once, a barrier settles when
442+/// its proof does, and an unprovable one still resolves the flush through its
443+/// fail-closed arm.
444+pub async fn ws_await_flushes(id: u64) {
445+ loop {
446+ // Registered before the count is read. A flush that finishes in
447+ // between must find a waiter to wake, or this parks forever on a
448+ // notification that already happened.
449+ let notified = ws_flush_done().notified();
450+ tokio::pin!(notified);
451+ notified.as_mut().enable();
452+ if !ws_flushes().lock().unwrap().contains_key(&id) {
453+ return;
454+ }
455+ notified.await;
456+ }
457+}
458+
357459 fn ws_emit(id: u64, out: WsOut) {
358460 let context = current_context();
359461 let mut capture = context.ws_capture.lock().unwrap();
@@ -368,15 +470,23 @@
368470 // held. Waiting on the DURABILITY ticket instead has no such cycle -- it
369471 // is resolved by the replicator, which does not need this event loop -- so
370472 // the frame can be held without deadlocking the script that sent it.
371- let pending = egress_gate_pending();
473+ let gate = egress_gate_request();
372474 // Held until this frame is either queued or sent. A flush runs on another
373475 // thread, so releasing here would let it drain its queue between the test
374476 // below and the send, putting a later frame ahead of an earlier one.
375477 let mut deferred = ws_deferred().lock().unwrap();
376478 let already_deferring = deferred.contains_key(&id);
377- if pending.is_some() || already_deferring {
479+ // Gated for a read-only frame as well, and deliberately: the frame reveals
480+ // what the cell holds, so it has to ask the core whether a barrier is open
481+ // rather than assume its own event opened one. A cell with nothing
482+ // outstanding answers at once and the queue flushes on the same tick.
483+ if gate.is_gated() || already_deferring {
378484 deferred.entry(id).or_default().push(out);
379485 if !already_deferring {
486+ // Counted in while `deferred` is held, so a teardown that reads
487+ // the count cannot observe a queued frame with no flush behind it.
488+ *ws_flushes().lock().unwrap().entry(id).or_default() += 1;
489+ let counted = WsFlushGuard(id);
380490 // Detached onto the HOST runtime (`op_handle`) deliberately:
381491 // this flush exists precisely to outlive the dispatch that
382492 // produced the frames — a writing connect handler's ready frame,
@@ -388,7 +498,8 @@
388498 // dispatch returns. Either way the frames never left the
389499 // process.
390500 asyncrt::op_handle().spawn(async move {
391- let held = await_egress_gate(pending).await;
501+ let _counted = counted;
502+ let held = await_egress_gate(gate).await;
392503 let mut deferred = ws_deferred().lock().unwrap();
393504 let frames = deferred.remove(&id).unwrap_or_default();
394505 match held {
@@ -428,7 +539,8 @@
428539 /// Flush frames the output gate held: send each to its socket's task. Called
429540 /// from the actor thread once the gating write is proved durable.
430541 pub fn ws_emit_batch(frames: Vec<(u64, WsOut)>) {
431- let mut registry = ws_registry().lock().unwrap();
542+ let registry = ws_registry();
543+ let mut registry = registry.lock().unwrap();
432544 for (id, out) in frames {
433545 registry.emit(id, out);
434546 }
@@ -441,7 +553,8 @@
441553 // A reset cell is a new actor; workerd's hibernation manager dies with
442554 // the old one and takes the auto-response pair with it.
443555 ws_auto_responses().lock().unwrap().remove(scope);
444- let mut registry = ws_registry().lock().unwrap();
556+ let registry = ws_registry();
557+ let mut registry = registry.lock().unwrap();
445558 let ids: Vec<u64> = registry
446559 .metadata
447560 .iter()
@@ -545,6 +658,7 @@
545658 pull,
546659 headers,
547660 want_response: true,
661+ target: None,
548662 reply: tx,
549663 })
550664 .is_ok()
@@ -643,6 +757,7 @@
643757 pull,
644758 headers: Vec::new(),
645759 want_response: false,
760+ target: None,
646761 reply: tx,
647762 })
648763 .is_ok()
@@ -659,6 +774,73 @@
659774 });
660775 rv.set(promise_for(scope, async_id));
661776 }
777+
778+/// Join this isolate's client socket to a Durable Object socket that a
779+/// subrequest already upgraded. The cell end lives in another isolate, so
780+/// the host carries each direction: it is the same route an external client
781+/// takes, with a pull queue in place of a TCP connection.
782+///
783+/// Called from `accept()`, never from the upgrade itself. A Worker that
784+/// passes the response straight back out never accepts the socket, and the
785+/// host binds that 101 to the real client instead — binding here as well
786+/// would give one cell socket two readers.
787+pub(super) fn op_ws_bind_target(
788+ scope: &mut v8::PinScope,
789+ args: v8::FunctionCallbackArguments,
790+ _rv: v8::ReturnValue<v8::Value>,
791+) {
792+ let id = args
793+ .get(0)
794+ .to_integer(scope)
795+ .map(|n| n.value() as u64)
796+ .unwrap_or(0);
797+ let Ok(target) = serde_json::from_str::<WsTarget>(&args.get(1).to_rust_string_lossy(scope))
798+ else {
799+ return loader_throw(scope, "WebSocket target is not valid");
800+ };
801+ // The caller's scope, which is empty for a Worker — the socket is
802+ // accounted against the isolate holding it, exactly as `op_ws_connect`
803+ // accounts an outbound one.
804+ let cell = args.get(2).to_rust_string_lossy(scope);
805+ let (pull_tx, pull_rx) = tokio::sync::mpsc::unbounded_channel();
806+ ws_pull_register(id, pull_rx);
807+ ws_region_track(id);
808+ // Registered here, on the JS thread, so a frame sent between this op and
809+ // the pipe task buffers as a pending frame instead of being dropped for
810+ // a socket the registry has never heard of. `accept()` opens the socket
811+ // synchronously, so that window is reachable by an ordinary `send()`.
812+ ws_register_outbound(id, &cell);
813+ let (tx, rx) = tokio::sync::oneshot::channel();
814+ let sent = OUTBOUND_WS_TX.get().is_some_and(|sender| {
815+ sender
816+ .send(OutboundWsReq {
817+ scope: target.scope.clone(),
818+ id,
819+ url: String::new(),
820+ protocols: Vec::new(),
821+ pull: Some(pull_tx),
822+ headers: Vec::new(),
823+ want_response: false,
824+ target: Some(target),
825+ reply: tx,
826+ })
827+ .is_ok()
828+ });
829+ // Nothing observes the outcome: the socket is already open, so there is
830+ // no handshake for JS to await. The task keeps the reply receiver alive
831+ // until the connector answers. A bind failure drops the pull sender, so
832+ // `op_ws_next` reports the caller socket as abnormally closed.
833+ asyncrt::enqueue(async move {
834+ if !sent {
835+ return Err::<String, String>("no outbound WebSocket channel".into());
836+ }
837+ match rx.await {
838+ Ok(Ok(_)) => Ok(String::new()),
839+ Ok(Err(error)) => Err(format!("WebSocket bind failed: {error}")),
840+ Err(error) => Err(format!("WebSocket connector dropped: {error}")),
841+ }
842+ });
843+}
662844 pub(super) fn op_ws_accept(
663845 scope: &mut v8::PinScope,
664846 args: v8::FunctionCallbackArguments,
@@ -673,7 +855,8 @@
673855 let tags: Vec<String> =
674856 serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)).unwrap_or_default();
675857 let replaced_regular_scope = {
676- let mut registry = ws_registry().lock().unwrap();
858+ let registry = ws_registry();
859+ let mut registry = registry.lock().unwrap();
677860 let sockets = &mut registry.metadata;
678861 let replaced_regular_scope = sockets
679862 .get(&id)
@@ -713,7 +896,8 @@
713896 .unwrap_or(0);
714897 let cell = args.get(1).to_rust_string_lossy(scope);
715898 let inserted = {
716- let mut registry = ws_registry().lock().unwrap();
899+ let registry = ws_registry();
900+ let mut registry = registry.lock().unwrap();
717901 let sockets = &mut registry.metadata;
718902 if let std::collections::hash_map::Entry::Vacant(entry) = sockets.entry(id) {
719903 entry.insert(WsMeta {
modifiedcrates/celld/lib.rs+115−9View file
@@ -1,30 +1,77 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3+#![warn(clippy::disallowed_methods, clippy::disallowed_types)]
4+#![allow(clippy::disallowed_macros)]
5+
36 //! Effect adapters for the clean-sheet core.
47 //!
58 //! The executable owns one serial actor which is the only caller of
69 //! `celld_logic::on_event`. Adapter futures never borrow core state; they send
710 //! versioned completion events back through its mailbox.
811
12+#[macro_export]
13+macro_rules! __celld_domain_select {
14+ (
15+ $first_pattern:pat = $first_future:expr => $first_output:expr,
16+ $second_pattern:pat = $second_future:expr => $second_output:expr $(,)?
17+ ) => {{
18+ let mut first = std::pin::pin!($first_future);
19+ let mut second = std::pin::pin!($second_future);
20+ let selected = std::future::poll_fn(|context| {
21+ if let std::task::Poll::Ready(value) =
22+ std::future::Future::poll(first.as_mut(), context)
23+ {
24+ return std::task::Poll::Ready(futures_util::future::Either::Left(value));
25+ }
26+ if let std::task::Poll::Ready(value) =
27+ std::future::Future::poll(second.as_mut(), context)
28+ {
29+ return std::task::Poll::Ready(futures_util::future::Either::Right(value));
30+ }
31+ std::task::Poll::Pending
32+ })
33+ .await;
34+ match selected {
35+ futures_util::future::Either::Left($first_pattern) => $first_output,
36+ futures_util::future::Either::Right($second_pattern) => $second_output,
37+ }
38+ }};
39+}
40+
41+pub mod actor;
942 pub mod assets;
43+#[cfg(not(all(test, celld_internal_tests)))]
1044 pub mod asyncrt;
45+#[cfg(all(test, celld_internal_tests))]
46+#[allow(clippy::disallowed_methods, clippy::disallowed_types)]
47+#[warn(clippy::disallowed_macros)]
48+pub mod asyncrt {
49+ include!(env!("CELLD_INTERNAL_ASYNCRT"));
50+}
1151 pub mod bucket;
1252 pub mod control_plane;
53+pub mod d1_cli;
1354 pub mod dead_node_gc;
1455 pub mod deploy;
1556 pub mod env_vars;
16-/// Test-only SQLite fault injection, ported from celld unchanged.
57+/// Test-only SQLite VFS fault and persistence instrumentation.
1758 ///
18-/// Gated to an external conformance build rather than merely `#[cfg(test)]`:
19-/// celld reaches it only from `open_with_fault_vfs_for_test`, which carries
20-/// the same gate, so an ordinary build compiles none of it and offers no seam
21-/// for it.
59+/// The external conformance build owns every caller, and the same gate covers
60+/// each test control. An ordinary build compiles none of this module and
61+/// offers no control seam.
2262 #[cfg(all(test, celld_internal_tests))]
23-mod fault;
63+// The fault harness materializes private crash fixtures outside production.
64+#[allow(clippy::disallowed_methods)]
65+mod fault {
66+ include!(env!("CELLD_INTERNAL_SQLITE_FAULT"));
67+}
2468 pub mod fleet;
69+pub mod host_services;
2570 pub mod js;
2671 pub mod ltx_repl;
72+pub mod machine;
2773 pub mod memory;
74+pub mod node_log;
2875 mod otlp;
2976 pub mod ownership_store;
3077 pub mod peer_auth;
@@ -45,10 +92,69 @@
4592 }
4693
4794 #[cfg(all(test, celld_internal_tests))]
48-mod conformance_replication_tests {
49- include!(env!("CELLD_CONFORMANCE_REPLICATION_TESTS"));
95+mod conformance_world_tests {
96+ include!(env!("CELLD_CONFORMANCE_WORLD_TESTS"));
5097 }
5198
99+#[cfg(all(test, celld_internal_tests))]
100+pub(crate) mod conformance_sim_store {
101+ include!(env!("CELLD_CONFORMANCE_SIM_STORE_TESTS"));
102+}
103+
104+#[cfg(all(test, celld_internal_tests))]
105+// The private CellHost test inspects its materialized SQLite files.
106+#[allow(clippy::disallowed_methods)]
107+pub(crate) mod conformance_sim_cell_host {
108+ include!(env!("CELLD_CONFORMANCE_SIM_CELL_HOST_TESTS"));
109+}
110+
111+#[cfg(all(test, celld_internal_tests))]
112+// The private oracle reads and writes independent file-format fixtures.
113+#[allow(clippy::disallowed_methods)]
114+pub(crate) mod conformance_o3_oracle {
115+ include!(env!("CELLD_CONFORMANCE_O3_ORACLE_TESTS"));
116+}
117+
118+#[cfg(all(test, celld_internal_tests))]
119+// The World test persists explicit replay and SQLite oracle artifacts.
120+#[allow(clippy::disallowed_methods)]
121+pub(crate) mod conformance_world_s1_tests {
122+ include!(env!("CELLD_CONFORMANCE_WORLD_S1_TESTS"));
123+}
124+
125+#[cfg(all(test, celld_internal_tests))]
126+// The World test copies and inspects deliberate crash images.
127+#[allow(clippy::disallowed_methods)]
128+mod conformance_world_s2_tests {
129+ include!(env!("CELLD_CONFORMANCE_WORLD_S2_TESTS"));
130+}
131+
132+#[cfg(all(test, celld_internal_tests))]
133+// The World test copies and inspects deliberate fleet-disk images.
134+#[allow(clippy::disallowed_methods)]
135+mod conformance_world_s3_tests {
136+ include!(env!("CELLD_CONFORMANCE_WORLD_S3_TESTS"));
137+}
138+
139+#[cfg(all(test, celld_internal_tests))]
140+// The World test owns the materialized SQLite persistence oracle.
141+#[allow(clippy::disallowed_methods)]
142+mod conformance_world_s5a_tests {
143+ include!(env!("CELLD_CONFORMANCE_WORLD_S5A_TESTS"));
144+}
145+
146+#[cfg(all(test, celld_internal_tests))]
147+// The World model owns and inspects its materialized filesystem images.
148+#[allow(clippy::disallowed_methods)]
149+mod conformance_world_s5b_tests {
150+ include!(env!("CELLD_CONFORMANCE_WORLD_S5B_TESTS"));
151+}
152+
153+#[cfg(all(test, celld_internal_tests))]
154+mod conformance_ltx_eviction_tests {
155+ include!(env!("CELLD_CONFORMANCE_LTX_EVICTION_TESTS"));
156+}
157+
52158 /// Completion token for a resident-isolate reservation made by the decision
53159 /// core. Dropping the queued/running job reports that the cell is idle again;
54160 /// the token contains no selection or lifecycle policy of its own.
@@ -77,7 +183,7 @@
77183 queued_at: std::time::Instant,
78184 url: String,
79185 method: String,
80- body: Vec<u8>,
186+ body: js::RequestBody,
81187 headers: Vec<(String, String)>,
82188 request_id: Option<js::RequestId>,
83189 reply: tokio::sync::oneshot::Sender<anyhow::Result<js::HttpResponse>>,
modifiedcrates/celld/ltx_repl.rs+1918−1101View file
@@ -1,1104 +1,1921 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3-//! In-process replication backend built on `celld-ltx`.
4-//!
5-//! One shared `object_store` client for the whole node, and a managed
6-//! `celld_ltx::Db` per resident cell that captures the cell's committed WAL
7-//! and uploads it on demand. No external process, no directory-watch lag — a
8-//! just-written cell is registered the instant it activates, so the output
9-//! gate can prove a fresh cell durable with no cold-start window.
10-//!
11-//! The object layout is `cells/<cell>/ltx/e<epoch>/` in the bucket, mirroring
12-//! the local `<watch>/<cell>/ltx/e<epoch>/db.sqlite` tree. This backend builds
13-//! its own object-store clients rather than going through `bucket::Bucket`, so
14-//! it carries the fleet's key prefix itself: without that, two fleets sharing
15-//! one bucket would replicate over each other.
16-
17-use std::collections::HashMap;
18-use std::path::Path;
19-use std::path::PathBuf;
20-use std::sync::atomic::AtomicBool;
21-use std::sync::atomic::AtomicU64;
22-use std::sync::atomic::Ordering;
23-use std::sync::Arc;
24-use std::sync::Mutex;
25-use std::sync::Weak;
26-use std::time::Duration;
27-use std::time::Instant;
28-
29-use anyhow::anyhow;
30-use celld_ltx::object_store::ObjectStore;
31-use celld_ltx::replica;
32-use celld_ltx::replica_compactor::ReplicaCompactor;
33-use celld_ltx::Db;
34-use celld_ltx::ObjectStoreClient;
35-use celld_ltx::ObjectStoreConfig;
36-use celld_ltx::Replica;
37-use celld_ltx::TXID;
38-use tokio::sync::mpsc;
39-use tokio::sync::Notify;
40-use tokio::sync::Semaphore;
41-use tracing::info;
42-use tracing::warn;
43-
44-use crate::replication::prune_watch;
45-use crate::replication::sqlite_snapshot;
46-use crate::replication::ActivationOptions;
47-use crate::replication::ActivationResult;
48-use crate::replication::RestoredSnapshot;
49-use crate::replication::StorageCredentials;
50-use crate::replication::SyncWait;
51-
52-/// Max cells uploading concurrently across the node. Caps blocking-pool threads
53-/// and in-flight object-store requests under high write fan-out.
54-const SYNC_CONCURRENCY: usize = 64;
55-
56-/// Max LTX object downloads across every restore on this node. A hot cell can
57-/// contain thousands of L0 files, so serial reads turn a takeover into minutes
58-/// of terminal failures. This shared ceiling hides round-trip latency without
59-/// multiplying the bound by the activation count.
60-const RESTORE_DOWNLOAD_CONCURRENCY: usize = 64;
61-
62-/// One attempt consumes at most this many source objects. This bound keeps a
63-/// first compaction of an old, write-hot cell from reading its complete L0
64-/// history into memory.
65-const COMPACTION_MAX_FILES: usize = 256;
66-
67-/// The current `ReplicaClient` interface buffers objects, so bound the complete
68-/// input set until the client gains a streaming read and write surface.
69-const COMPACTION_MAX_INPUT_BYTES: u64 = 64 * 1024 * 1024;
70-
71-#[derive(Debug, Clone, Copy)]
72-struct CompactionConfig {
73- min_txids: u64,
74- concurrency: usize,
75-}
76-
77-struct CellCompaction {
78- cell: String,
79- epoch: u64,
80- client: ObjectStoreClient,
81- local_path: PathBuf,
82- queue: mpsc::UnboundedSender<CompactionWork>,
83- min_txids: u64,
84- compacted_txid: AtomicU64,
85- queued: AtomicBool,
86- cancelled: AtomicBool,
87- cancel: Notify,
88-}
89-
90-struct CompactionWork {
91- cell: Weak<Cell>,
92- queued_at: Instant,
93-}
94-
95-/// One resident cell's replication state: the `celld_ltx::Db` shadowing its WAL
96-/// (behind a `std::sync::Mutex` because the `rusqlite` handle is `!Sync` and
97-/// must never cross an `.await`, so every capture+upload runs inside a
98-/// `spawn_blocking` closure) plus the durability tickets the output gate waits
99-/// on. `req_seq` counts durability requests; `synced_seq` is the highest ticket
100-/// a completed background sync captured. A write waits for `synced_seq >= its
101-/// ticket`, so concurrent writes to one cell ride a single batched upload —
102-/// and, because a sync credits only tickets whose writes committed before it
103-/// started (which the sync's `db.sync` captures), never one it did not upload.
104-struct Cell {
105- replica: Mutex<Replica<ObjectStoreClient>>,
106- req_seq: AtomicU64,
107- synced_seq: AtomicU64,
108- durable_txid: AtomicU64,
109- /// Set while a sync for this cell is in flight, so the loop never runs two
110- /// at once for one cell (they would serialize on the mutex and waste work).
111- syncing: AtomicBool,
112- /// Notified when `synced_seq` advances (or a sync fails), waking waiters.
113- ready: Notify,
114- compaction: Option<CellCompaction>,
115-}
116-type CellHandle = Arc<Cell>;
117-
118-pub struct LtxRepl {
119- /// Local root: cell dbs live at `watch/<cell>/ltx/e<epoch>/db.sqlite`.
120- watch: PathBuf,
121- bucket: String,
122- /// The bucket spec's key prefix: empty, or slash-terminated.
123- prefix: String,
124- endpoint: Option<String>,
125- region: String,
126- credentials: Option<StorageCredentials>,
127- /// One connection pool for the whole node, shared by every cell client.
128- store: Arc<dyn ObjectStore>,
129- cells: Arc<Mutex<HashMap<(String, u64), CellHandle>>>,
130- /// Woken when a cell's `committed` advances, so the background loop syncs
131- /// without polling; a slow tick backstops any missed notification.
132- dirty: Arc<Notify>,
133- /// Shared by every activation, so the restore bound is per node, not per
134- /// cell. The generic LTX restore keeps its sequential compatibility path.
135- restore_slots: Arc<Semaphore>,
136- compaction_queue: Option<mpsc::UnboundedSender<CompactionWork>>,
137- compaction_min_txids: u64,
138-}
139-
140-impl LtxRepl {
141- /// Private-corpus constructor over an injected store, so the epoch-seal
142- /// protocol runs against an in-memory bucket instead of S3.
143- #[cfg(all(test, celld_internal_tests))]
144- pub fn start_with_store_for_test(watch: &Path, store: Arc<dyn ObjectStore>) -> Self {
145- let cells: Arc<Mutex<HashMap<(String, u64), CellHandle>>> = Arc::default();
146- let dirty = Arc::new(Notify::new());
147- let slots = Arc::new(Semaphore::new(SYNC_CONCURRENCY));
148- tokio::spawn(sync_loop(cells.clone(), dirty.clone(), slots));
149- Self {
150- watch: watch.to_path_buf(),
151- bucket: "test".into(),
152- prefix: String::new(),
153- endpoint: None,
154- region: "auto".into(),
155- credentials: None,
156- store,
157- cells,
158- dirty,
159- restore_slots: Arc::new(Semaphore::new(RESTORE_DOWNLOAD_CONCURRENCY)),
160- compaction_queue: None,
161- compaction_min_txids: 0,
162- }
163- }
164-
165- /// Private-corpus constructor with additive L1 compaction enabled.
166- #[cfg(all(test, celld_internal_tests))]
167- pub fn start_with_compaction_for_test(
168- watch: &Path,
169- store: Arc<dyn ObjectStore>,
170- min_txids: u64,
171- concurrency: usize,
172- ) -> Self {
173- let cells: Arc<Mutex<HashMap<(String, u64), CellHandle>>> = Arc::default();
174- let dirty = Arc::new(Notify::new());
175- let sync_slots = Arc::new(Semaphore::new(SYNC_CONCURRENCY));
176- tokio::spawn(sync_loop(cells.clone(), dirty.clone(), sync_slots));
177- let config = CompactionConfig {
178- min_txids,
179- concurrency,
180- };
181- let queue = start_compaction_loop(config);
182- Self {
183- watch: watch.to_path_buf(),
184- bucket: "test".into(),
185- prefix: String::new(),
186- endpoint: None,
187- region: "auto".into(),
188- credentials: None,
189- store,
190- cells,
191- dirty,
192- restore_slots: Arc::new(Semaphore::new(RESTORE_DOWNLOAD_CONCURRENCY)),
193- compaction_queue: Some(queue),
194- compaction_min_txids: min_txids,
195- }
196- }
197-
198- pub(crate) fn start(
199- watch: &Path,
200- backend: crate::bucket::StorageBackend,
201- bucket: String,
202- prefix: String,
203- endpoint: Option<String>,
204- region: String,
205- credentials: Option<StorageCredentials>,
206- ) -> anyhow::Result<Self> {
207- let compaction = compaction_config_from_env()?;
208- // Everything downstream of the store is backend-agnostic already,
209- // so the dialect decides construction and nothing else.
210- let store = match backend {
211- crate::bucket::StorageBackend::Gcs => crate::bucket::gcs_replica_store(&bucket)?,
212- crate::bucket::StorageBackend::S3 => {
213- node_config(&bucket, endpoint.as_deref(), &region, credentials.as_ref())
214- .build_store()
215- .map_err(|error| anyhow!("build shared object store: {error}"))?
216- }
217- };
218- let cells: Arc<Mutex<HashMap<(String, u64), CellHandle>>> = Arc::default();
219- let dirty = Arc::new(Notify::new());
220- // Bound how many cells upload at once so one slow cell cannot stall the
221- // others and a thousand hot cells cannot open a thousand uploads.
222- let slots = Arc::new(Semaphore::new(SYNC_CONCURRENCY));
223- tokio::spawn(sync_loop(cells.clone(), dirty.clone(), slots));
224- let compaction_queue = compaction.map(start_compaction_loop);
225- Ok(Self {
226- watch: watch.to_path_buf(),
227- bucket,
228- prefix,
229- endpoint,
230- region,
231- credentials,
232- store,
233- cells,
234- dirty,
235- restore_slots: Arc::new(Semaphore::new(RESTORE_DOWNLOAD_CONCURRENCY)),
236- compaction_queue,
237- compaction_min_txids: compaction.map_or(0, |config| config.min_txids),
238- })
239- }
240-
241- fn db_path(&self, cell: &str, epoch: u64) -> PathBuf {
242- self.watch
243- .join(cell)
244- .join("ltx")
245- .join(format!("e{epoch}"))
246- .join("db.sqlite")
247- }
248-
249- /// A per-cell client over the shared store, keyed to the cell's epoch
250- /// prefix. `cells/<cell>/ltx/e<epoch>` matches [`Self::db_path`]'s remote
251- /// twin so the same coordinates address local and replica state.
252- fn client_for(&self, cell: &str, epoch: u64) -> ObjectStoreClient {
253- let mut config = node_config(
254- &self.bucket,
255- self.endpoint.as_deref(),
256- &self.region,
257- self.credentials.as_ref(),
258- );
259- config.path = format!("{}cells/{cell}/ltx/e{epoch}", self.prefix);
260- ObjectStoreClient::with_store(config, self.store.clone())
261- }
262-
263- /// Highest epoch under `cells/<cell>/ltx/` that holds any LTX — the newest
264- /// durable copy to restore on takeover.
265- async fn highest_nonempty_epoch(&self, cell: &str) -> anyhow::Result<Option<u64>> {
266- use celld_ltx::object_store::path::Path as ObjPath;
267- let base = ObjPath::from(format!("{}cells/{cell}/ltx", self.prefix));
268- let listing = self.store.list_with_delimiter(Some(&base)).await?;
269- let mut best: Option<u64> = None;
270- for prefix in listing.common_prefixes {
271- if let Some(epoch) = prefix
272- .filename()
273- .and_then(|name| name.strip_prefix('e'))
274- .and_then(|value| value.parse::<u64>().ok())
275- {
276- best = Some(best.map_or(epoch, |current| current.max(epoch)));
277- }
278- }
279- Ok(best)
280- }
281-
282- /// The seal for a restore-source epoch: a file *beside* the epoch
283- /// directories (`cells/<cell>/ltx/e<from>.seal.json`), so nothing that
284- /// lists an epoch's LTX contents parses it, and `highest_nonempty_epoch`'s
285- /// prefix listing never mistakes it for an epoch.
286- fn seal_key(&self, cell: &str, epoch: u64) -> String {
287- format!("{}cells/{cell}/ltx/e{epoch}.seal.json", self.prefix)
288- }
289-
290- /// Read the source epoch's seal, writing it first if this activation is
291- /// the first to restore from `from` (Cellarium §5.6).
292- ///
293- /// Restore's rule is "highest non-empty epoch", so if a takeover's new
294- /// epoch stays empty (it dies before its first sync) while the fenced old
295- /// owner keeps uploading into the old prefix — its PUTs are unconditional
296- /// and the bucket checks nothing — the *next* activation restores the old prefix
297- /// again, now including the zombie's tail: writes no client was ever
298- /// acknowledged (the ownership re-read refuses the zombie's acks), and
299- /// possibly writes a client was told had definitively failed, resurrect.
300- ///
301- /// The seal closes this by fixing, before the first restore reads a byte,
302- /// the TXID every restore of this epoch may read through. Ordering makes
303- /// it safe for acknowledged writes: an ack requires the ownership record
304- /// to still name the writer, the takeover's record CAS precedes this seal,
305- /// and the acked write's upload preceded its ownership read — so every
306- /// acked write is at or below the sealed TXID. Conversely a fenced owner's
307- /// later uploads land above the seal and are never restored again.
308- /// First-writer-wins (conditional create) keeps every later restorer on
309- /// the same cut. A seal-write failure fails the activation: restoring an
310- /// unsealed prefix reopens the hole.
311- async fn read_or_seal(
312- &self,
313- cell: &str,
314- from: u64,
315- by_epoch: u64,
316- client: &ObjectStoreClient,
317- ) -> anyhow::Result<u64> {
318- use celld_ltx::object_store::path::Path as ObjPath;
319- use celld_ltx::object_store::PutMode;
320- use celld_ltx::object_store::PutOptions;
321- use celld_ltx::object_store::PutPayload;
322-
323- #[derive(serde::Serialize, serde::Deserialize)]
324- struct EpochSeal {
325- max_txid: u64,
326- sealed_by_epoch: u64,
327- }
328-
329- let key = ObjPath::from(self.seal_key(cell, from));
330- let existing = |bytes: Vec<u8>| -> anyhow::Result<u64> {
331- let seal: EpochSeal = serde_json::from_slice(&bytes)?;
332- Ok(seal.max_txid)
333- };
334- match self.store.get(&key).await {
335- Ok(get) => return existing(get.bytes().await?.to_vec()),
336- Err(celld_ltx::object_store::Error::NotFound { .. }) => {}
337- Err(error) => return Err(anyhow!("read seal for {cell} e{from}: {error}")),
338- }
339- let plan = replica::calc_restore_plan(client, TXID(0))
340- .await
341- .map_err(|error| anyhow!("plan seal for {cell} e{from}: {error}"))?;
342- let cap = plan
343- .iter()
344- .map(|info| info.max_txid.0)
345- .max()
346- .ok_or_else(|| anyhow!("seal target {cell} e{from} is empty"))?;
347- let seal = EpochSeal {
348- max_txid: cap,
349- sealed_by_epoch: by_epoch,
350- };
351- let put = PutOptions {
352- mode: PutMode::Create,
353- ..Default::default()
354- };
355- match self
356- .store
357- .put_opts(&key, PutPayload::from(serde_json::to_vec(&seal)?), put)
358- .await
359- {
360- Ok(_) => {
361- info!(cell, from, to = by_epoch, cap, "sealed restore source");
362- Ok(cap)
363- }
364- Err(celld_ltx::object_store::Error::AlreadyExists { .. }) => {
365- // A racing claimant sealed first; its cut is the one every
366- // restore must share.
367- let get = self
368- .store
369- .get(&key)
370- .await
371- .map_err(|error| anyhow!("reread seal for {cell} e{from}: {error}"))?;
372- existing(get.bytes().await?.to_vec())
373- }
374- Err(error) => Err(anyhow!("seal {cell} e{from}: {error}")),
375- }
376- }
377-
378- /// Does the bucket hold any LTX for this cell at this epoch? The fail-closed
379- /// eviction gate: never delete the last local copy of state the bucket
380- /// cannot restore.
381- pub async fn epoch_replicated(&self, cell: &str, epoch: u64) -> bool {
382- let client = self.client_for(cell, epoch);
383- matches!(
384- replica::calc_restore_plan(&client, TXID(0)).await,
385- Ok(plan) if !plan.is_empty()
386- )
387- }
388-
389- pub async fn activate(
390- &self,
391- options: ActivationOptions<'_>,
392- ) -> anyhow::Result<ActivationResult> {
393- let ActivationOptions {
394- cell,
395- epoch,
396- fresh,
397- took_over,
398- resume_local,
399- } = options;
400- let dst = self.db_path(cell, epoch);
401- std::fs::create_dir_all(dst.parent().unwrap())?;
402-
403- // Reuse a preserved local eviction snapshot when it is safe to: the
404- // same epoch always, the previous epoch only when we did not take the
405- // cell from another node.
406- // `.evicted` is the current name; `.hibernated` is what releases
407- // before 2026-08-05 wrote. Accept both, so an upgrade reuses the
408- // snapshots already on disk instead of restoring every cell from the
409- // bucket. Writes always use the new name, so the old one dies out.
410- let legacy = |path: &PathBuf| path.with_extension("hibernated");
411- let same_epoch = dst.with_extension("evicted");
412- let previous = celld_logic::restore::previous_epoch_reusable(epoch, took_over)
413- .then(|| self.db_path(cell, epoch - 1).with_extension("evicted"));
414- let is_file = |path: &PathBuf| path.is_file();
415- let first_present = |path: PathBuf| {
416- if path.is_file() {
417- Some(path)
418- } else {
419- Some(legacy(&path)).filter(is_file)
420- }
421- };
422- let local_snapshot = (!fresh && !resume_local)
423- .then(|| first_present(same_epoch.clone()).or_else(|| previous.and_then(first_present)))
424- .flatten();
425-
426- let mut restored = resume_local;
427- if resume_local {
428- anyhow::ensure!(
429- dst.is_file(),
430- "clean reload database is missing: {}",
431- dst.display()
432- );
433- info!(cell, epoch, "resumed clean local replica");
434- } else if let Some(snapshot) = local_snapshot {
435- std::fs::rename(&snapshot, &dst)?;
436- info!(cell, epoch, "reused local eviction snapshot");
437- restored = true;
438- } else if !fresh {
439- // Restore the newest durable epoch into this epoch's path — up to
440- // its seal, never past it. Sealing before reading fixes the cut
441- // every later restore of this prefix shares, so a fenced owner's
442- // late uploads into it can never resurrect (see `read_or_seal`).
443- if let Some(from) = self.highest_nonempty_epoch(cell).await? {
444- let client = self.client_for(cell, from);
445- let cap = self.read_or_seal(cell, from, epoch, &client).await?;
446- let _ = std::fs::remove_file(&dst);
447- let stats = replica::restore_with_download_slots(
448- &client,
449- &dst,
450- TXID(cap),
451- self.restore_slots.clone(),
452- )
453- .await
454- .map_err(|error| anyhow!("restore {cell} e{from}@{cap}: {error}"))?;
455- let levels = stats
456- .by_level
457- .iter()
458- .map(|(level, count)| format!("L{level}:{count}"))
459- .collect::<Vec<_>>()
460- .join(" ");
461- info!(
462- event = "restore_plan",
463- cell,
464- epoch = from,
465- objects = stats.objects,
466- bytes = stats.bytes,
467- %levels,
468- "computed restore plan"
469- );
470- info!(cell, from, to = epoch, cap, "restored remote replica");
471- restored = true;
472- }
473- }
474-
475- // Open the managed Db (creates a fresh WAL db when nothing was restored)
476- // and pair it with this epoch's client. Registration is immediate: the
477- // cell can be proved durable on its very first write. The just-opened
478- // db's position is the replica's seed -- 0 for a fresh cell, the
479- // restored max otherwise, and equal to the remote under epoch fencing --
480- // so the first sync skips the `calc_pos` listing that otherwise storms a
481- // rate-limiting store. On the rare decode error we leave it unseeded and
482- // fall back to that listing.
483- let dst_ = dst.clone();
484- let (db, seed) = tokio::task::spawn_blocking(move || {
485- let mut db = Db::open(&dst_)?;
486- let seed = db.pos().ok();
487- anyhow::Ok((db, seed))
488- })
489- .await?
490- .map_err(|error| anyhow!("open managed db {}: {error}", dst.display()))?;
491- let mut replica = Replica::new(db, self.client_for(cell, epoch));
492- if let Some(pos) = seed {
493- replica.seed_pos(pos);
494- }
495- let handle = Arc::new(Cell {
496- replica: Mutex::new(replica),
497- req_seq: AtomicU64::new(0),
498- synced_seq: AtomicU64::new(0),
499- durable_txid: AtomicU64::new(seed.map_or(0, |pos| pos.txid.0)),
500- syncing: AtomicBool::new(false),
501- ready: Notify::new(),
502- compaction: self.compaction_queue.as_ref().map(|queue| CellCompaction {
503- cell: cell.to_string(),
504- epoch,
505- client: self.client_for(cell, epoch),
506- local_path: Db::meta_path_for_path(&dst),
507- queue: queue.clone(),
508- min_txids: self.compaction_min_txids,
509- compacted_txid: AtomicU64::new(0),
510- queued: AtomicBool::new(false),
511- cancelled: AtomicBool::new(false),
512- cancel: Notify::new(),
513- }),
514- });
515- self.cells
516- .lock()
517- .unwrap()
518- .insert((cell.to_string(), epoch), handle.clone());
519- if let Some(pos) = seed {
520- maybe_queue_compaction(&handle, pos.txid.0);
521- }
522-
523- Ok(ActivationResult {
524- path: dst,
525- restored,
526- })
527- }
528-
529- /// The output gate's primitive: take a durability ticket and return once a
530- /// background sync that captured this write has completed, coalescing
531- /// concurrent writes to one cell into a single upload. The write committed
532- /// before this call, so any sync starting after our ticket captures it —
533- /// we wait for `synced_seq >= my ticket`, not for a position, sidestepping
534- /// the total_changes↔LTX-txid mismatch that a position compare would hit.
535- /// Returns `position` (which the completed sync provably covered) for the
536- /// core's coverage check.
537- pub async fn await_durable(
538- &self,
539- cell: &str,
540- epoch: u64,
541- position: u64,
542- ) -> anyhow::Result<u64> {
543- let Some(handle) = self
544- .cells
545- .lock()
546- .unwrap()
547- .get(&(cell.to_string(), epoch))
548- .cloned()
549- else {
550- anyhow::bail!("ltx cell not resident: {cell} epoch {epoch}");
551- };
552- let ticket = handle.req_seq.fetch_add(1, Ordering::SeqCst) + 1;
553- self.dirty.notify_one();
554- let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
555- loop {
556- // Register the waiter before checking, so a sync that completes
557- // between the check and the await is not missed.
558- let ready = handle.ready.notified();
559- if handle.synced_seq.load(Ordering::SeqCst) >= ticket {
560- return Ok(position);
561- }
562- if tokio::time::timeout_at(deadline, ready).await.is_err() {
563- anyhow::bail!("ltx durability timed out for {cell} epoch {epoch}");
564- }
565- }
566- }
567-
568- /// A direct, synchronous durability pass for the rare eviction
569- /// gates (not the hot write path). Also advances the cell's durable position
570- /// so any output-gate waiters ride it.
571- pub async fn sync_wait(&self, cell: &str, epoch: u64, _timeout: Duration) -> SyncWait {
572- let Some(handle) = self
573- .cells
574- .lock()
575- .unwrap()
576- .get(&(cell.to_string(), epoch))
577- .cloned()
578- else {
579- return SyncWait::Unsupported;
580- };
581- match sync_cell(handle).await {
582- Some(true) => SyncWait::Durable,
583- Some(false) => SyncWait::Failed,
584- None => SyncWait::Unsupported,
585- }
586- }
587-
588- pub async fn evict(&self, cell: &str, epoch: u64, preserve_local: bool) {
589- // A final durability pass so no acknowledged write is stranded, then
590- // drop the managed Db (releasing the WAL) before touching the file.
591- let _ = self.sync_wait(cell, epoch, Duration::from_secs(10)).await;
592- let removed = self
593- .cells
594- .lock()
595- .unwrap()
596- .remove(&(cell.to_string(), epoch));
597- if let Some(handle) = removed {
598- cancel_compaction(&handle);
599- }
600- let db = self.db_path(cell, epoch);
601- if preserve_local {
602- let preserved = db.with_extension("evicted");
603- if let Err(error) = std::fs::rename(&db, &preserved) {
604- warn!(cell, epoch, %error, "preserve local snapshot failed");
605- }
606- }
607- // Clear the WAL/meta siblings and the live db regardless: a reactivation
608- // restores or reuses the `.hibernated` copy.
609- for suffix in ["-wal", "-shm"] {
610- let mut sibling = db.clone().into_os_string();
611- sibling.push(suffix);
612- let _ = std::fs::remove_file(PathBuf::from(sibling));
613- }
614- let _ = std::fs::remove_dir_all(Db::meta_path_for_path(&db));
615- if !preserve_local {
616- let _ = std::fs::remove_file(&db);
617- }
618- }
619-
620- /// Copy the live epoch into a private read-only snapshot for inspection.
621- pub fn snapshot_active(
622- &self,
623- cell: &str,
624- epoch: u64,
625- ) -> anyhow::Result<Option<RestoredSnapshot>> {
626- let source = self.db_path(cell, epoch);
627- if !source.is_file() {
628- return Ok(None);
629- }
630- let directory = self.watch.join(format!(".inspect-{cell}-e{epoch}"));
631- let _ = std::fs::remove_dir_all(&directory);
632- std::fs::create_dir_all(&directory)?;
633- let path = directory.join("db.sqlite");
634- sqlite_snapshot(&source, &path)?;
635- Ok(Some(RestoredSnapshot::new(epoch, path, directory)))
636- }
637-
638- /// Restore the newest durable replica into a private snapshot without
639- /// claiming or activating the cell.
640- pub async fn restore_snapshot(&self, cell: &str) -> anyhow::Result<Option<RestoredSnapshot>> {
641- let Some(epoch) = self.highest_nonempty_epoch(cell).await? else {
642- return Ok(None);
643- };
644- let directory = self.watch.join(format!(".restore-{cell}"));
645- let _ = std::fs::remove_dir_all(&directory);
646- std::fs::create_dir_all(&directory)?;
647- let path = directory.join("db.sqlite");
648- replica::restore_with_download_slots(
649- &self.client_for(cell, epoch),
650- &path,
651- TXID(0),
652- self.restore_slots.clone(),
653- )
654- .await
655- .map_err(|error| anyhow!("restore snapshot {cell} e{epoch}: {error}"))?;
656- Ok(Some(RestoredSnapshot::new(epoch, path, directory)))
657- }
658-
659- pub fn prune_local_cache(&self, max_bytes: u64) -> (usize, usize, u64) {
660- prune_watch(&self.watch, max_bytes)
661- }
662-
663- /// Close the replicator handle while retaining the live database and WAL
664- /// exactly where the local path encodes them.
665- pub fn close_for_reload(&self, cell: &str, epoch: u64) -> anyhow::Result<()> {
666- let removed = self
667- .cells
668- .lock()
669- .unwrap()
670- .remove(&(cell.to_string(), epoch));
671- if let Some(handle) = removed {
672- cancel_compaction(&handle);
673- }
674- let path = self.db_path(cell, epoch);
675- anyhow::ensure!(
676- path.is_file(),
677- "resident database is missing: {}",
678- path.display()
679- );
680- Ok(())
681- }
682-
683- /// Enumerate live-named databases. Cached `.evicted` files are separate
684- /// and remain under the ordinary cache byte limit.
685- pub fn local_cells(&self) -> Vec<celld_logic::LocalCell> {
686- let mut cells = Vec::new();
687- let Ok(cell_dirs) = std::fs::read_dir(&self.watch) else {
688- return cells;
689- };
690- for cell_dir in cell_dirs.flatten() {
691- let Ok(kind) = cell_dir.file_type() else {
692- continue;
693- };
694- if !kind.is_dir() {
695- continue;
696- }
697- let Some(cell) = cell_dir.file_name().to_str().map(str::to_owned) else {
698- continue;
699- };
700- let Ok(epochs) = std::fs::read_dir(cell_dir.path().join("ltx")) else {
701- continue;
702- };
703- for epoch_dir in epochs.flatten() {
704- let Some(epoch) = epoch_dir
705- .file_name()
706- .to_str()
707- .and_then(|name| name.strip_prefix('e'))
708- .and_then(|epoch| epoch.parse::<u64>().ok())
709- else {
710- continue;
711- };
712- if epoch_dir.path().join("db.sqlite").is_file() {
713- cells.push(celld_logic::LocalCell {
714- id: cell.clone(),
715- epoch,
716- });
717- }
718- }
719- }
720- cells.sort();
721- cells.dedup();
722- cells
723- }
724-
725- /// Delete stale live-named epochs after the runtime has identified and
726- /// closed its exact resident set. Remote replicas remain authoritative.
727- pub fn prune_stale_live(
728- &self,
729- keep: &std::collections::BTreeSet<(String, u64)>,
730- ) -> anyhow::Result<usize> {
731- let stale: Vec<_> = self
732- .local_cells()
733- .into_iter()
734- .filter(|cell| !keep.contains(&(cell.id.clone(), cell.epoch)))
735- .collect();
736- for cell in &stale {
737- if let Some(parent) = self.db_path(&cell.id, cell.epoch).parent() {
738- std::fs::remove_dir_all(parent)?;
739- }
740- }
741- let remaining: std::collections::BTreeSet<_> = self
742- .local_cells()
743- .into_iter()
744- .map(|cell| (cell.id, cell.epoch))
745- .collect();
746- anyhow::ensure!(
747- &remaining == keep,
748- "clean reload inventory mismatch after pruning: expected {}, found {}",
749- keep.len(),
750- remaining.len()
751- );
752- Ok(stale.len())
753- }
754-
755- /// No external process to watch: the in-process replicator is healthy as
756- /// long as celld is running.
757- pub fn process_status(&self) -> std::io::Result<Option<std::process::ExitStatus>> {
758- Ok(None)
759- }
760-}
761-
762-/// One capture+upload for a cell: advance its durable position on success and
763-/// wake its waiters. Everything committed before the capture is durable once
764-/// uploaded, so the target is read before `db.sync`. The `rusqlite` handle is
765-/// `!Sync`, so the whole pass runs on a blocking thread with `block_on` for the
766-/// async upload. `Some(true)` means success, `Some(false)` means failure, and
767-/// `None` means that the replica lost its database.
768-async fn sync_cell(handle: CellHandle) -> Option<bool> {
769- let runtime = tokio::runtime::Handle::current();
770- tokio::task::spawn_blocking(move || {
771- // Tickets taken before the capture: their writes committed before
772- // `db.sync` runs, so it captures them. Read before the capture so a
773- // ticket taken during the sync is credited by the next one, not this.
774- let captured = handle.req_seq.load(Ordering::SeqCst);
775- let mut replica = handle.replica.lock().unwrap();
776- let db = replica.db_mut()?;
777- if let Err(error) = db.sync() {
778- warn!(%error, "ltx wal capture failed");
779- handle.ready.notify_waiters();
780- return Some(false);
781- }
782- let durable_txid = match runtime.block_on(replica.sync()) {
783- Ok(()) => Some(replica.pos().txid.0),
784- Err(error) => {
785- warn!(%error, "ltx upload failed");
786- None
787- }
788- };
789- drop(replica);
790- if let Some(durable_txid) = durable_txid {
791- handle.synced_seq.fetch_max(captured, Ordering::SeqCst);
792- handle.durable_txid.store(durable_txid, Ordering::SeqCst);
793- maybe_queue_compaction(&handle, durable_txid);
794- }
795- handle.ready.notify_waiters();
796- Some(durable_txid.is_some())
797- })
798- .await
799- .unwrap_or(Some(false))
800-}
801-
802-fn maybe_queue_compaction(handle: &CellHandle, durable_txid: u64) {
803- let Some(compaction) = &handle.compaction else {
804- return;
805- };
806- if compaction.cancelled.load(Ordering::SeqCst)
807- || durable_txid.saturating_sub(compaction.compacted_txid.load(Ordering::SeqCst))
808- < compaction.min_txids
809- || compaction
810- .queued
811- .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
812- .is_err()
813- {
814- return;
815- }
816- if compaction
817- .queue
818- .send(CompactionWork {
819- cell: Arc::downgrade(handle),
820- queued_at: Instant::now(),
821- })
822- .is_err()
823- {
824- compaction.queued.store(false, Ordering::SeqCst);
825- }
826-}
827-
828-fn cancel_compaction(handle: &CellHandle) {
829- let Some(compaction) = &handle.compaction else {
830- return;
831- };
832- compaction.cancelled.store(true, Ordering::SeqCst);
833- compaction.cancel.notify_waiters();
834-}
835-
836-fn start_compaction_loop(config: CompactionConfig) -> mpsc::UnboundedSender<CompactionWork> {
837- let (queue, mut work) = mpsc::unbounded_channel::<CompactionWork>();
838- let slots = Arc::new(Semaphore::new(config.concurrency));
839- tokio::spawn(async move {
840- while let Some(work) = work.recv().await {
841- let Ok(permit) = slots.clone().acquire_owned().await else {
842- break;
843- };
844- let Some(cell) = work.cell.upgrade() else {
845- continue;
846- };
847- tokio::spawn(async move {
848- let _permit = permit;
849- compact_cell(cell, work.queued_at).await;
850- });
851- }
852- });
853- queue
854-}
855-
856-async fn compact_cell(handle: CellHandle, queued_at: Instant) {
857- let Some(compaction) = &handle.compaction else {
858- return;
859- };
860- let cancelled = compaction.cancel.notified();
861- tokio::pin!(cancelled);
862- if compaction.cancelled.load(Ordering::SeqCst) {
863- return;
864- }
865-
866- let queue_ms = queued_at.elapsed().as_millis() as u64;
867- let started = Instant::now();
868- let compactor = ReplicaCompactor::new(&compaction.client)
869- .with_verification(true)
870- .with_local_path(&compaction.local_path)
871- .with_limits(COMPACTION_MAX_FILES, COMPACTION_MAX_INPUT_BYTES);
872- let worker = compactor.compact(1);
873- tokio::pin!(worker);
874- let result = tokio::select! {
875- biased;
876- _ = &mut cancelled => None,
877- result = &mut worker => Some(result),
878- };
879-
880- let mut completed = false;
881- match result {
882- Some(Ok(Some(output))) => {
883- let info = output.info;
884- compaction
885- .compacted_txid
886- .store(info.max_txid.0, Ordering::SeqCst);
887- completed = true;
888- info!(
889- event = "ltx_compaction",
890- cell = %compaction.cell,
891- epoch = compaction.epoch,
892- source_level = 0,
893- destination_level = info.level,
894- min_txid = info.min_txid.0,
895- max_txid = info.max_txid.0,
896- input_objects = output.input_files,
897- input_bytes = output.input_bytes,
898- local_input_objects = output.local_input_files,
899- remote_input_objects = output.input_files - output.local_input_files,
900- output_bytes = info.size,
901- queue_ms,
902- elapsed_ms = started.elapsed().as_millis() as u64,
903- result = "ok",
904- "compacted an additive LTX level"
905- );
906- }
907- Some(Ok(None)) => {
908- compaction
909- .compacted_txid
910- .store(handle.durable_txid.load(Ordering::SeqCst), Ordering::SeqCst);
911- completed = true;
912- info!(
913- event = "ltx_compaction",
914- cell = %compaction.cell,
915- epoch = compaction.epoch,
916- source_level = 0,
917- destination_level = 1,
918- queue_ms,
919- elapsed_ms = started.elapsed().as_millis() as u64,
920- result = "no_work",
921- "the additive LTX level is current"
922- );
923- }
924- Some(Err(error)) => {
925- warn!(
926- event = "ltx_compaction",
927- cell = %compaction.cell,
928- epoch = compaction.epoch,
929- source_level = 0,
930- destination_level = 1,
931- queue_ms,
932- elapsed_ms = started.elapsed().as_millis() as u64,
933- result = "error",
934- %error,
935- "additive LTX compaction failed"
936- );
937- }
938- None => {
939- info!(
940- event = "ltx_compaction",
941- cell = %compaction.cell,
942- epoch = compaction.epoch,
943- source_level = 0,
944- destination_level = 1,
945- queue_ms,
946- elapsed_ms = started.elapsed().as_millis() as u64,
947- result = "cancelled",
948- "cancelled an additive LTX compaction"
949- );
950- }
951- }
952- compaction.queued.store(false, Ordering::SeqCst);
953-
954- if completed && !compaction.cancelled.load(Ordering::SeqCst) {
955- // Pace consecutive rounds for one cell: a restart with a large tail
956- // otherwise drains back-to-back for minutes. The pause matches the
957- // round it follows (capped), so a cell compacts at half duty cycle
958- // while the worker slot frees for other cells immediately — this
959- // task detaches and does not hold the concurrency permit.
960- let pause = started.elapsed().min(std::time::Duration::from_secs(2));
961- let handle_ = handle.clone();
962- tokio::spawn(async move {
963- tokio::time::sleep(pause).await;
964- let durable_txid = handle_.durable_txid.load(Ordering::SeqCst);
965- maybe_queue_compaction(&handle_, durable_txid);
966- });
967- }
968-}
969-
970-fn compaction_config_from_env() -> anyhow::Result<Option<CompactionConfig>> {
971- // On by default. A mixed fleet must set `0` until every node can read
972- // v0.5.2 block objects. An old reader cannot take over a cell after its
973- // first L1 publication.
974- let enabled = crate::env_vars::flag("CELLD_LTX_COMPACTION", true)?;
975- if !enabled {
976- return Ok(None);
977- }
978-
979- let min_txids = crate::env_vars::with_default("CELLD_LTX_COMPACTION_MIN_TXIDS", 256)?;
980- let concurrency = crate::env_vars::with_default("CELLD_LTX_COMPACTIONS", 2)?;
981- anyhow::ensure!(
982- min_txids >= 2,
983- "CELLD_LTX_COMPACTION_MIN_TXIDS must be at least 2"
984- );
985- anyhow::ensure!(concurrency > 0, "CELLD_LTX_COMPACTIONS must be positive");
986- Ok(Some(CompactionConfig {
987- min_txids: min_txids as u64,
988- concurrency,
989- }))
990-}
991-
992-/// The node's background sync loop: wake on a dirty cell (or a slow tick) and
993-/// launch a sync for every cell whose committed position runs ahead of its
994-/// durable one. Each cell's sync is an independent, self-rescheduling task —
995-/// the loop does *not* wait for the batch to finish — so one slow cell's upload
996-/// never stalls the others (a cell keeps its own cadence up to the concurrency
997-/// bound). A cell's writes reported between its syncs still clear on one upload:
998-/// the batching win, without the cross-cell head-of-line blocking.
999-async fn sync_loop(
1000- cells: Arc<Mutex<HashMap<(String, u64), CellHandle>>>,
1001- dirty: Arc<Notify>,
1002- slots: Arc<Semaphore>,
1003-) {
1004- loop {
1005- tokio::select! {
1006- _ = dirty.notified() => {}
1007- _ = tokio::time::sleep(Duration::from_millis(25)) => {}
1008- }
1009- let work: Vec<CellHandle> = {
1010- let map = cells.lock().unwrap();
1011- map.values()
1012- .filter(|c| c.req_seq.load(Ordering::SeqCst) > c.synced_seq.load(Ordering::SeqCst))
1013- .cloned()
1014- .collect()
1015- };
1016- for cell in work {
1017- // Claim the cell; skip if a sync is already in flight for it.
1018- if cell
1019- .syncing
1020- .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
1021- .is_err()
1022- {
1023- continue;
1024- }
1025- let slots = slots.clone();
1026- let dirty = dirty.clone();
1027- tokio::spawn(async move {
1028- // Keep syncing this cell while it stays dirty, rather than
1029- // notifying the main loop to re-scan every completion — that made
1030- // the loop wake O(cells) times and starved throughput as cells
1031- // accumulated. This is not a busy loop: each iteration awaits an
1032- // object-store upload (~one round-trip). A *failed* sync would
1033- // not, so it backs off, keeping the only tight iterations the
1034- // ones that actually uploaded.
1035- loop {
1036- let ok = {
1037- let _permit = slots.acquire().await;
1038- sync_cell(cell.clone()).await
1039- };
1040- if cell.req_seq.load(Ordering::SeqCst) <= cell.synced_seq.load(Ordering::SeqCst)
1041- {
1042- break;
1043- }
1044- if ok != Some(true) {
1045- tokio::time::sleep(Duration::from_millis(50)).await;
1046- }
1047- }
1048- cell.syncing.store(false, Ordering::SeqCst);
1049- // A write landing in the clear window is picked up next tick;
1050- // nudge the loop so it does not wait the full interval.
1051- if cell.req_seq.load(Ordering::SeqCst) > cell.synced_seq.load(Ordering::SeqCst) {
1052- dirty.notify_one();
1053- }
1054- });
1055- }
1056- }
1057-}
1058-
1059-/// Node-level object-store config (no per-cell prefix). `build_store` on this
1060-/// yields the one shared client; per-cell clients set only `path`.
1061-fn node_config(
1062- bucket: &str,
1063- endpoint: Option<&str>,
1064- region: &str,
1065- credentials: Option<&StorageCredentials>,
1066-) -> ObjectStoreConfig {
1067- let endpoint = endpoint.unwrap_or_default().to_string();
1068- // Static credentials come from the managed control plane when present,
1069- // else the `AWS_*` env the node already carries. Without this,
1070- // `build_store` sees empty keys and object_store falls back to the
1071- // instance credential provider, which off-EC2 sends unsigned requests (R2
1072- // answers "404 page not found").
1073- let env = |key: &str| std::env::var(key).ok().filter(|value| !value.is_empty());
1074- let access_key_id = credentials
1075- .map(|c| c.access_key_id.clone())
1076- .filter(|value| !value.is_empty())
1077- .or_else(|| env("AWS_ACCESS_KEY_ID"))
1078- .unwrap_or_default();
1079- let secret_access_key = credentials
1080- .map(|c| c.secret_access_key.clone())
1081- .filter(|value| !value.is_empty())
1082- .or_else(|| env("AWS_SECRET_ACCESS_KEY"))
1083- .unwrap_or_default();
1084- // Temporary R2/STS credentials require the session token, or signing fails.
1085- let session_token = credentials
1086- .and_then(|c| c.session_token.clone())
1087- .filter(|value| !value.is_empty())
1088- .or_else(|| env("AWS_SESSION_TOKEN"))
1089- .unwrap_or_default();
1090- ObjectStoreConfig {
1091- bucket: bucket.to_string(),
1092- path: String::new(),
1093- region: region.to_string(),
1094- // A custom endpoint (R2/MinIO) uses path-style addressing, matching
1095- // `ObjectStoreConfig::from_url`'s default for non-AWS hosts.
1096- force_path_style: !endpoint.is_empty(),
1097- endpoint,
1098- access_key_id,
1099- secret_access_key,
1100- session_token,
1101- skip_verify: false,
1102- part_size: 0,
1103- }
3+#![warn(clippy::disallowed_macros)]
4+
5+//! In-process replication backend built on `celld-ltx`.
6+//!
7+//! One shared `object_store` client for the whole node, and a managed
8+//! `celld_ltx::Db` per resident cell that captures the cell's committed WAL
9+//! and uploads it on demand. No external process, no directory-watch lag — a
10+//! just-written cell is registered the instant it activates, so the output
11+//! gate can prove a fresh cell durable with no cold-start window.
12+//!
13+//! The object layout is `cells/<cell>/ltx/e<epoch>/` in the bucket, mirroring
14+//! the local `<watch>/<cell>/ltx/e<epoch>/db.sqlite` tree. This backend builds
15+//! its own object-store clients rather than going through `bucket::Bucket`, so
16+//! it carries the fleet's key prefix itself: without that, two fleets sharing
17+//! one bucket would replicate over each other.
18+
19+use std::collections::BTreeMap;
20+use std::path::Path;
21+use std::path::PathBuf;
22+use std::sync::atomic::AtomicBool;
23+use std::sync::atomic::AtomicU64;
24+use std::sync::atomic::Ordering;
25+use std::sync::Arc;
26+use std::sync::Mutex;
27+use std::sync::Weak;
28+use std::time::Duration;
29+
30+use anyhow::anyhow;
31+use celld_ltx::object_store::ObjectStore;
32+use celld_ltx::replica;
33+use celld_ltx::replica_compactor::ReplicaCompactor;
34+use celld_ltx::Db;
35+use celld_ltx::HostTaskError;
36+use celld_ltx::LtxHost;
37+use celld_ltx::ObjectStoreClient;
38+use celld_ltx::ObjectStoreConfig;
39+use celld_ltx::Pos;
40+use celld_ltx::Replica;
41+use celld_ltx::ReplicaClient;
42+use celld_ltx::TimestampMetadataKey;
43+use celld_ltx::TXID;
44+use tokio::sync::mpsc;
45+use tokio::sync::Notify;
46+use tokio::sync::Semaphore;
47+use tracing::info;
48+use tracing::warn;
49+
50+use crate::asyncrt;
51+use crate::replication::sqlite_snapshot;
52+use crate::replication::ActivationOptions;
53+use crate::replication::ActivationResult;
54+use crate::replication::RestoredSnapshot;
55+use crate::replication::StorageCredentials;
56+use crate::replication::SyncWait;
57+
58+/// Max cells uploading concurrently across the node. Caps blocking-pool threads
59+/// and in-flight object-store requests under high write fan-out.
60+const SYNC_CONCURRENCY: usize = 64;
61+
62+/// Max LTX object downloads across every restore on this node. A hot cell can
63+/// contain thousands of L0 files, so serial reads turn a takeover into minutes
64+/// of terminal failures. This shared ceiling hides round-trip latency without
65+/// multiplying the bound by the activation count.
66+const RESTORE_DOWNLOAD_CONCURRENCY: usize = 64;
67+
68+/// One attempt consumes at most this many source objects. This bound keeps a
69+/// first compaction of an old, write-hot cell from reading its complete L0
70+/// history into memory.
71+const COMPACTION_MAX_FILES: usize = 256;
72+
73+/// The current `ReplicaClient` interface buffers objects, so bound the complete
74+/// input set until the client gains a streaming read and write surface.
75+const COMPACTION_MAX_INPUT_BYTES: u64 = 64 * 1024 * 1024;
76+
77+/// One captured-but-not-yet-uploaded L0 segment, the log tier's
78+/// replication unit (`crate::node_log`).
79+pub struct ShipEntry {
80+ pub cell: String,
81+ pub epoch: u64,
82+ pub txid: u64,
83+ pub bytes: Vec<u8>,
84+}
85+
86+/// The fleet shipper the log tier installs: one in-flight batch, all-member
87+/// fsync confirmation. `false` means the batch is not fleet-durable and the
88+/// gate must ride the bucket upload instead.
89+pub trait Shipper: Send + Sync + 'static {
90+ /// Ship one batch; `covered_seq` is the highest sequence whose frames
91+ /// are all bucket-covered, which followers may truncate behind.
92+ /// `Some(last_seq)` means every member confirmed the whole batch.
93+ fn ship<'a>(
94+ &'a self,
95+ batch: &'a [ShipEntry],
96+ covered_seq: u64,
97+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Option<u64>> + Send + 'a>>;
98+
99+ /// Called by the ship loop AFTER the shipped credits are applied: the
100+ /// capture-to-credit interval must read as in-flight to the
101+ /// reconfigure and seal barriers as one piece (fidelity audit,
102+ /// DRIFTED #1). Default no-op for shippers with no such window.
103+ fn batch_credited(&self) {}
104+ /// A degraded shipper refuses instantly; the ship loop skips capture.
105+ fn active(&self) -> bool;
106+ /// The log epoch this shipper writes. Sequences restart at zero each
107+ /// epoch, so the ship loop's truncation ledger must reset with it — a
108+ /// stale covered watermark from the previous epoch would tell fresh
109+ /// followers to delete entries they just fsync'd.
110+ fn epoch(&self) -> u64;
111+}
112+
113+/// The bundle sink (`crate::node_log`): one PUT per node per flush
114+/// interval, carrying every dirty cell's captured L0 segments verbatim
115+/// (`crate::bundle`). `true` means the bundle is durable in the bucket and
116+/// every included frame may credit its cell's bucket coverage. Inactive
117+/// (or absent) means the per-cell upload path owns tiering, exactly as
118+/// before bundles existed.
119+pub trait BundleSink: Send + Sync + 'static {
120+ fn put_bundle<'a>(
121+ &'a self,
122+ entries: Vec<celld_ltx::bundle::BundleEntry>,
123+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + 'a>>;
124+ fn active(&self) -> bool;
125+ /// The un-drained rows for one cell-epoch, from the leader's own
126+ /// index of the bundles it wrote. Empty when bundles are off.
127+ fn rows_for(&self, cell: &str, epoch: u64) -> Vec<celld_ltx::LocatedRow>;
128+ /// One bundle object's complete bytes, for slicing rows out of.
129+ fn fetch_bundle<'a>(
130+ &'a self,
131+ source: &'a str,
132+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<Vec<u8>>> + Send + 'a>>;
133+}
134+
135+/// The compactor-facing fetcher: one cell-epoch's view over whatever sink
136+/// is currently installed. Reading the slot per call makes activation
137+/// order irrelevant — a cell activated before the sink existed still sees
138+/// bundles once it does.
139+struct SinkFetcher {
140+ slot: Arc<Mutex<Option<Arc<dyn BundleSink>>>>,
141+ cell: String,
142+ epoch: u64,
143+}
144+
145+impl celld_ltx::BundleFetcher for SinkFetcher {
146+ fn rows<'a>(
147+ &'a self,
148+ ) -> std::pin::Pin<
149+ Box<
150+ dyn std::future::Future<Output = celld_ltx::Result<Vec<celld_ltx::LocatedRow>>>
151+ + Send
152+ + 'a,
153+ >,
154+ > {
155+ Box::pin(async move {
156+ let sink = self.slot.lock().unwrap().clone();
157+ Ok(sink.map_or_else(Vec::new, |sink| sink.rows_for(&self.cell, self.epoch)))
158+ })
159+ }
160+
161+ fn fetch<'a>(
162+ &'a self,
163+ located: &'a celld_ltx::LocatedRow,
164+ ) -> std::pin::Pin<Box<dyn std::future::Future<Output = celld_ltx::Result<Vec<u8>>> + Send + 'a>>
165+ {
166+ Box::pin(async move {
167+ let sink = self.slot.lock().unwrap().clone();
168+ let Some(sink) = sink else {
169+ return Err(celld_ltx::Error::Other("no bundle sink".into()));
170+ };
171+ let bytes = sink
172+ .fetch_bundle(&located.source)
173+ .await
174+ .map_err(|e| celld_ltx::Error::Other(e.to_string().into()))?;
175+ Ok(celld_ltx::bundle::slice(&bytes, &located.row)?.to_vec())
176+ })
177+ }
178+}
179+
180+#[derive(Debug, Clone, Copy)]
181+pub struct CompactionConfig {
182+ pub min_txids: u64,
183+ pub concurrency: usize,
184+}
185+
186+struct CellCompaction {
187+ cell: String,
188+ epoch: u64,
189+ client: celld_ltx::BundleOverlayClient<ObjectStoreClient>,
190+ local_path: PathBuf,
191+ host: LtxHost,
192+ queue: mpsc::UnboundedSender<CompactionWork>,
193+ min_txids: u64,
194+ compacted_txid: AtomicU64,
195+ queued: AtomicBool,
196+ cancelled: AtomicBool,
197+ cancel: Notify,
198+}
199+
200+struct CompactionWork {
201+ cell: Weak<Cell>,
202+ queued_at_mono_ms: u64,
203+}
204+
205+/// One resident cell's replication state: the `celld_ltx::Db` shadowing its WAL
206+/// (behind a `std::sync::Mutex` because the `rusqlite` handle is `!Sync` and
207+/// must never cross an `.await`, so every capture+upload runs inside a
208+/// `spawn_blocking` closure) plus the durability tickets the output gate waits
209+/// on. `req_seq` counts durability requests; `synced_seq` is the highest ticket
210+/// a completed background sync captured. A write waits for `synced_seq >= its
211+/// ticket`, so concurrent writes to one cell ride a single batched upload —
212+/// and, because a sync credits only tickets whose writes committed before it
213+/// started (which the sync's `db.sync` captures), never one it did not upload.
214+struct Cell {
215+ replica: Mutex<Replica<ObjectStoreClient>>,
216+ /// The same epoch-prefix client the replica holds, for uploads that run
217+ /// off the replica mutex.
218+ client: ObjectStoreClient,
219+ req_seq: AtomicU64,
220+ synced_seq: AtomicU64,
221+ /// Highest ticket whose write is fsync'd on every ensemble member —
222+ /// the log tier's proof. The gate accepts either proof, so this stays 0
223+ /// forever when no shipper is installed.
224+ shipped_seq: AtomicU64,
225+ /// Highest TXID handed to the shipper; frames at or below it are on the
226+ /// followers (or in the bucket, which restored them).
227+ shipped_txid: AtomicU64,
228+ durable_txid: AtomicU64,
229+ /// Set while a sync for this cell is in flight, so the loop never runs two
230+ /// at once for one cell (they would serialize on the mutex and waste work).
231+ syncing: AtomicBool,
232+ /// Wall-clock ms of the last completed sync, the pacing anchor: with a
233+ /// healthy shipper the bucket runs at most one upload per flush interval
234+ /// behind, which is the tier's stated lag budget.
235+ last_sync_ms: AtomicU64,
236+ /// Notified when `synced_seq` advances (or a sync fails), waking waiters.
237+ ready: Notify,
238+ compaction: Option<CellCompaction>,
239+}
240+type CellHandle = Arc<Cell>;
241+
242+pub struct LtxRepl {
243+ /// Local root: cell dbs live at `watch/<cell>/ltx/e<epoch>/db.sqlite`.
244+ watch: PathBuf,
245+ /// The object-metadata name for an LTX header timestamp. Azure refuses
246+ /// a hyphen in a metadata name, so the fleet bucket's dialect picks it.
247+ timestamp_metadata_key: TimestampMetadataKey,
248+ bucket: String,
249+ /// The bucket spec's key prefix: empty, or slash-terminated.
250+ prefix: String,
251+ endpoint: Option<String>,
252+ region: String,
253+ credentials: Option<StorageCredentials>,
254+ /// One connection pool for the whole node, shared by every cell client.
255+ store: Arc<dyn ObjectStore>,
256+ ltx_host: LtxHost,
257+ /// An explicit SQLite VFS for both managed connections. Production keeps
258+ /// this unset; the deterministic World selects its host-callback shim.
259+ vfs_name: Option<String>,
260+ cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>,
261+ /// Woken when a cell's `committed` advances, so the background loop syncs
262+ /// without polling; a slow tick backstops any missed notification.
263+ dirty: Arc<Notify>,
264+ /// Shared by every activation, so the restore bound is per node, not per
265+ /// cell. The generic LTX restore keeps its sequential compatibility path.
266+ restore_slots: Arc<Semaphore>,
267+ compaction_queue: Option<mpsc::UnboundedSender<CompactionWork>>,
268+ compaction_min_txids: u64,
269+ /// Preserved eviction snapshots, tracked in memory so the local-cache
270+ /// prune answers without walking the data directory. See
271+ /// [`crate::replication::PreservedCache`].
272+ preserved: Mutex<crate::replication::PreservedCache>,
273+ /// Woken when a gate ticket arrives, so the ship loop group-commits
274+ /// without polling.
275+ dirty_ship: Arc<Notify>,
276+ shipper: Arc<Mutex<Option<Arc<dyn Shipper>>>>,
277+ bundle_sink: Arc<Mutex<Option<Arc<dyn BundleSink>>>>,
278+}
279+
280+impl LtxRepl {
281+ /// Internal test constructor over an injected store, so the shipping
282+ /// restore and replication path runs against an in-memory bucket.
283+ #[cfg(all(test, celld_internal_tests))]
284+ pub fn start_with_store_for_test(watch: &Path, store: Arc<dyn ObjectStore>) -> Self {
285+ Self::start_with_store(watch, store, None, 0)
286+ }
287+
288+ /// Build the production loop topology over an injected object store.
289+ #[cfg(all(test, celld_internal_tests))]
290+ pub fn start_with_store(
291+ watch: &Path,
292+ store: Arc<dyn ObjectStore>,
293+ compaction: Option<CompactionConfig>,
294+ flush_ms: u64,
295+ ) -> Self {
296+ Self::start_with_store_and_optional_vfs(watch, store, compaction, flush_ms, None)
297+ }
298+
299+ /// Build the same loop topology and route managed SQLite through `vfs`.
300+ #[cfg(all(test, celld_internal_tests))]
301+ pub fn start_with_store_on_vfs(
302+ watch: &Path,
303+ store: Arc<dyn ObjectStore>,
304+ compaction: Option<CompactionConfig>,
305+ flush_ms: u64,
306+ vfs: &str,
307+ ) -> Self {
308+ Self::start_with_store_and_optional_vfs(
309+ watch,
310+ store,
311+ compaction,
312+ flush_ms,
313+ Some(vfs.to_string()),
314+ )
315+ }
316+
317+ #[cfg(all(test, celld_internal_tests))]
318+ fn start_with_store_and_optional_vfs(
319+ watch: &Path,
320+ store: Arc<dyn ObjectStore>,
321+ compaction: Option<CompactionConfig>,
322+ flush_ms: u64,
323+ vfs_name: Option<String>,
324+ ) -> Self {
325+ Self::assemble(
326+ watch,
327+ store,
328+ TimestampMetadataKey::default(),
329+ "test".into(),
330+ String::new(),
331+ None,
332+ "auto".into(),
333+ None,
334+ compaction,
335+ flush_ms,
336+ deterministic_ltx_host(),
337+ vfs_name,
338+ )
339+ }
340+
341+ /// Internal test constructor with additive L1 compaction enabled.
342+ #[cfg(all(test, celld_internal_tests))]
343+ pub fn start_with_compaction_for_test(
344+ watch: &Path,
345+ store: Arc<dyn ObjectStore>,
346+ min_txids: u64,
347+ concurrency: usize,
348+ ) -> Self {
349+ Self::assemble(
350+ watch,
351+ store,
352+ TimestampMetadataKey::default(),
353+ "test".into(),
354+ String::new(),
355+ None,
356+ "auto".into(),
357+ None,
358+ Some(CompactionConfig {
359+ min_txids,
360+ concurrency,
361+ }),
362+ 0,
363+ deterministic_ltx_host(),
364+ None,
365+ )
366+ }
367+
368+ pub(crate) fn start(
369+ watch: &Path,
370+ backend: crate::bucket::StorageBackend,
371+ bucket: String,
372+ prefix: String,
373+ endpoint: Option<String>,
374+ region: String,
375+ credentials: Option<StorageCredentials>,
376+ ) -> anyhow::Result<Self> {
377+ let compaction = compaction_config_from_env()?;
378+ // Everything downstream of the store is backend-agnostic already,
379+ // so the dialect decides construction and the metadata name, and
380+ // nothing else.
381+ let store = match backend {
382+ crate::bucket::StorageBackend::Gcs => crate::bucket::gcs_replica_store(&bucket)?,
383+ crate::bucket::StorageBackend::Azure => crate::bucket::azure_replica_store(&bucket)?,
384+ crate::bucket::StorageBackend::S3 => {
385+ node_config(&bucket, endpoint.as_deref(), &region, credentials.as_ref())
386+ .build_store()
387+ .map_err(|error| anyhow!("build shared object store: {error}"))?
388+ }
389+ };
390+ // Azure blob metadata names must be C# identifiers, so the standard
391+ // Litestream key cannot carry its hyphen there. External Litestream
392+ // tooling reads that key, therefore an az:// replica gives up
393+ // Litestream-tool timestamp restore. celld never reads it back.
394+ let timestamp_metadata_key = match backend {
395+ crate::bucket::StorageBackend::Azure => TimestampMetadataKey::Underscore,
396+ _ => TimestampMetadataKey::Litestream,
397+ };
398+ // The tiering flush interval: with a healthy shipper, at most one
399+ // upload per cell per interval; it is simultaneously the bucket lag
400+ // budget. 0 disables pacing.
401+ let flush_ms = crate::env_vars::with_default("CELLD_LOG_FLUSH_MS", 2000)? as u64;
402+ Ok(Self::assemble(
403+ watch,
404+ store,
405+ timestamp_metadata_key,
406+ bucket,
407+ prefix,
408+ endpoint,
409+ region,
410+ credentials,
411+ compaction,
412+ flush_ms,
413+ production_ltx_host(),
414+ None,
415+ ))
416+ }
417+
418+ /// The one constructor body: every field and every background loop,
419+ /// shared by production `start` and the test constructor so the two
420+ /// can never drift.
421+ #[allow(clippy::too_many_arguments)]
422+ fn assemble(
423+ watch: &Path,
424+ store: Arc<dyn ObjectStore>,
425+ timestamp_metadata_key: TimestampMetadataKey,
426+ bucket: String,
427+ prefix: String,
428+ endpoint: Option<String>,
429+ region: String,
430+ credentials: Option<StorageCredentials>,
431+ compaction: Option<CompactionConfig>,
432+ flush_ms: u64,
433+ ltx_host: LtxHost,
434+ vfs_name: Option<String>,
435+ ) -> Self {
436+ let cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>> = Arc::default();
437+ let dirty = Arc::new(Notify::new());
438+ let dirty_ship = Arc::new(Notify::new());
439+ let shipper: Arc<Mutex<Option<Arc<dyn Shipper>>>> = Arc::default();
440+ let bundle_sink: Arc<Mutex<Option<Arc<dyn BundleSink>>>> = Arc::default();
441+ let preserved = Mutex::new(crate::replication::PreservedCache::new(
442+ ltx_host.filesystem(),
443+ ));
444+ // Bound how many cells upload at once so one slow cell cannot stall the
445+ // others and a thousand hot cells cannot open a thousand uploads.
446+ asyncrt::spawn(sync_loop(
447+ cells.clone(),
448+ dirty.clone(),
449+ Arc::new(Semaphore::new(SYNC_CONCURRENCY)),
450+ shipper.clone(),
451+ bundle_sink.clone(),
452+ flush_ms,
453+ ))
454+ .detach();
455+ asyncrt::spawn(ship_loop(
456+ cells.clone(),
457+ dirty_ship.clone(),
458+ shipper.clone(),
459+ ))
460+ .detach();
461+ asyncrt::spawn(bundle_loop(cells.clone(), bundle_sink.clone(), flush_ms)).detach();
462+ Self {
463+ watch: watch.to_path_buf(),
464+ timestamp_metadata_key,
465+ bucket,
466+ prefix,
467+ endpoint,
468+ region,
469+ credentials,
470+ store,
471+ ltx_host,
472+ vfs_name,
473+ cells,
474+ dirty,
475+ restore_slots: Arc::new(Semaphore::new(RESTORE_DOWNLOAD_CONCURRENCY)),
476+ compaction_queue: compaction.map(start_compaction_loop),
477+ compaction_min_txids: compaction.map_or(0, |config| config.min_txids),
478+ preserved,
479+ dirty_ship,
480+ shipper,
481+ bundle_sink,
482+ }
483+ }
484+
485+ /// Install the fleet shipper. Fleet-durable proofs begin only after the
486+ /// log record is open in the bucket — the caller guarantees the order.
487+ pub fn set_shipper(&self, shipper: Arc<dyn Shipper>) {
488+ *self.shipper.lock().unwrap() = Some(shipper);
489+ self.dirty_ship.notify_one();
490+ }
491+
492+ /// Install the bundle sink. Bundled tiering engages only while both
493+ /// the shipper and the sink report active; every other state keeps the
494+ /// per-cell upload path.
495+ pub fn set_bundle_sink(&self, sink: Arc<dyn BundleSink>) {
496+ *self.bundle_sink.lock().unwrap() = Some(sink);
497+ }
498+
499+ /// The ensemble-change barrier: every frame ever handed to a shipper is
500+ /// durable in the bucket. Old followers' fragments are abandonable
501+ /// garbage exactly when this holds.
502+ pub fn all_shipped_tiered(&self) -> bool {
503+ self.cells.lock().unwrap().values().all(|cell| {
504+ cell.durable_txid.load(Ordering::SeqCst) >= cell.shipped_txid.load(Ordering::SeqCst)
505+ })
506+ }
507+
508+ /// Recovery's primitive: PUT one gathered L0 segment to the exact key
509+ /// the dead leader's own upload would have used. Idempotent by key.
510+ /// The highest TXID the cell's per-cell prefix already covers, over
511+ /// every level. Recovery uses it to skip re-uploading rows the drain
512+ /// points (compaction, eviction sync) have already folded in — one
513+ /// LIST per cell instead of one PUT per historical row.
514+ pub async fn covered_txid(&self, cell: &str, epoch: u64) -> u64 {
515+ let client = self.client_for(cell, epoch);
516+ let mut covered = 0_u64;
517+ for level in 0..=1 {
518+ if let Ok(files) = client.ltx_files(level, TXID(0)).await {
519+ for file in files {
520+ covered = covered.max(file.max_txid.0);
521+ }
522+ }
523+ }
524+ covered
525+ }
526+
527+ pub async fn upload_raw_l0(
528+ &self,
529+ cell: &str,
530+ epoch: u64,
531+ min_txid: u64,
532+ max_txid: u64,
533+ bytes: &[u8],
534+ ) -> anyhow::Result<()> {
535+ self.client_for(cell, epoch)
536+ .write_ltx_file(0, TXID(min_txid), TXID(max_txid), bytes)
537+ .await
538+ .map_err(|error| {
539+ anyhow!("upload recovered l0 {cell} e{epoch} t{min_txid}-{max_txid}: {error}")
540+ })?;
541+ Ok(())
542+ }
543+
544+ /// Merge contiguous single-transaction LTX segments into one segment
545+ /// covering the whole range. Recovery uses it to upload each cell's
546+ /// gathered tail as ONE object instead of one per row: the lab's chaos
547+ /// soak measured per-kill outages growing 133 s -> 353 s because every
548+ /// crash added hundreds of single-row L0 objects for the object
549+ /// store's same-key throttling to fight and the next restore plan to
550+ /// read. Returns None when the rows are not a contiguous ascending
551+ /// chain — the caller falls back to per-row uploads, never guessing.
552+ pub fn merge_l0_rows(rows: &[(u64, Vec<u8>)]) -> Option<Vec<u8>> {
553+ if rows.len() < 2 {
554+ return None;
555+ }
556+ if rows.windows(2).any(|pair| pair[1].0 != pair[0].0 + 1) {
557+ return None;
558+ }
559+ let readers: Vec<std::io::Cursor<&[u8]>> = rows
560+ .iter()
561+ .map(|(_, bytes)| std::io::Cursor::new(bytes.as_slice()))
562+ .collect();
563+ let mut compactor = celld_ltx::compactor::Compactor::new(Vec::new(), readers);
564+ // The gathered frames are no-checksum WAL-segment files, so the
565+ // merged header must be too — a checksummed output header fails
566+ // encode validation against checksum-less inputs (the same flag
567+ // ReplicaCompactor sets for the L0->L1 fold).
568+ compactor.header_flags = celld_ltx::ltx::HEADER_FLAG_NO_CHECKSUM;
569+ match compactor.compact() {
570+ Ok(()) => Some(compactor.into_writer()),
571+ Err(error) => {
572+ // The fallback is safe (per-row uploads) but must never be
573+ // silent again: a swallowed error here hid a dead merge
574+ // through a full fleet round.
575+ warn!(%error, rows = rows.len(), "recovery tail merge failed; per-row fallback");
576+ None
577+ }
578+ }
579+ }
580+
581+ fn db_path(&self, cell: &str, epoch: u64) -> PathBuf {
582+ self.watch
583+ .join(cell)
584+ .join("ltx")
585+ .join(format!("e{epoch}"))
586+ .join("db.sqlite")
587+ }
588+
589+ /// A per-cell client over the shared store, keyed to the cell's epoch
590+ /// prefix. `cells/<cell>/ltx/e<epoch>` matches [`Self::db_path`]'s remote
591+ /// twin so the same coordinates address local and replica state.
592+ fn client_for(&self, cell: &str, epoch: u64) -> ObjectStoreClient {
593+ let mut config = node_config(
594+ &self.bucket,
595+ self.endpoint.as_deref(),
596+ &self.region,
597+ self.credentials.as_ref(),
598+ );
599+ config.path = format!("{}cells/{cell}/ltx/e{epoch}", self.prefix);
600+ config.timestamp_metadata_key = self.timestamp_metadata_key;
601+ ObjectStoreClient::with_store(config, self.store.clone())
602+ }
603+
604+ /// Highest epoch under `cells/<cell>/ltx/` that holds any LTX — the newest
605+ /// durable copy to restore on takeover.
606+ async fn highest_nonempty_epoch(&self, cell: &str) -> anyhow::Result<Option<u64>> {
607+ use celld_ltx::object_store::path::Path as ObjPath;
608+ let base = ObjPath::from(format!("{}cells/{cell}/ltx", self.prefix));
609+ let listing = self.store.list_with_delimiter(Some(&base)).await?;
610+ let mut best: Option<u64> = None;
611+ #[cfg(all(test, celld_internal_tests))]
612+ let restore_superseded =
613+ asyncrt::sabotage_active(crate::host_services::EngineSabotage::RestoreSupersededEpoch);
614+ #[cfg(not(all(test, celld_internal_tests)))]
615+ let restore_superseded = false;
616+ for prefix in listing.common_prefixes {
617+ if let Some(epoch) = prefix
618+ .filename()
619+ .and_then(|name| name.strip_prefix('e'))
620+ .and_then(|value| value.parse::<u64>().ok())
621+ {
622+ best = Some(best.map_or(epoch, |current| {
623+ if restore_superseded {
624+ current.min(epoch)
625+ } else {
626+ current.max(epoch)
627+ }
628+ }));
629+ }
630+ }
631+ Ok(best)
632+ }
633+
634+ /// Does the bucket hold any LTX for this cell at this epoch? The fail-closed
635+ /// eviction gate: never delete the last local copy of state the bucket
636+ /// cannot restore.
637+ pub async fn epoch_replicated(&self, cell: &str, epoch: u64) -> bool {
638+ let client = self.client_for(cell, epoch);
639+ matches!(
640+ replica::calc_restore_plan(&client, TXID(0)).await,
641+ Ok(plan) if !plan.is_empty()
642+ )
643+ }
644+
645+ pub async fn activate(
646+ &self,
647+ options: ActivationOptions<'_>,
648+ ) -> anyhow::Result<ActivationResult> {
649+ let ActivationOptions {
650+ cell,
651+ epoch,
652+ fresh,
653+ took_over,
654+ resume_local,
655+ // Consumed by the interlock before the fold; the field stays
656+ // on the options because the core's claim still names it.
657+ prior: _,
658+ } = options;
659+ let dst = self.db_path(cell, epoch);
660+ self.ltx_host.create_dir_all(dst.parent().unwrap())?;
661+
662+ // The takeover interlock moved OUT of this path (lease-fold): the
663+ // decision core gates foreign takeovers on the folded lease state
664+ // it already reads (Effect::RecoverNodeLog), and the boot order
665+ // recovers this node's own predecessor before the lease installs,
666+ // so by the time any activation reaches here the bucket is
667+ // provably complete for both the takeover and the named-me path.
668+
669+ // Reuse a preserved local eviction snapshot only as the previous
670+ // epoch's baseline. Eviction removes the LTX metadata, so reopening
671+ // that SQLite image starts a new writer generation at TXID 1. Pairing
672+ // it with the same remote epoch would mix that new lineage with the
673+ // old tail (#158). A clean process reload is the separate
674+ // `resume_local` path: it retains both the live database and its LTX
675+ // metadata, so it can safely continue the existing epoch.
676+ // `.evicted` is the current name; `.hibernated` is what releases
677+ // before 2026-08-05 wrote. Accept both, so an upgrade reuses the
678+ // snapshots already on disk instead of restoring every cell from the
679+ // bucket. Writes always use the new name, so the old one dies out.
680+ let legacy = |path: &PathBuf| path.with_extension("hibernated");
681+ #[cfg(all(test, celld_internal_tests))]
682+ let took_over_for_reuse = took_over
683+ && !asyncrt::sabotage_active(crate::host_services::EngineSabotage::IgnoreTookOver);
684+ #[cfg(not(all(test, celld_internal_tests)))]
685+ let took_over_for_reuse = took_over;
686+ let previous = celld_logic::restore::previous_epoch_reusable(epoch, took_over_for_reuse)
687+ .then(|| self.db_path(cell, epoch - 1).with_extension("evicted"));
688+ let is_file = |path: &PathBuf| {
689+ self.ltx_host
690+ .metadata(path)
691+ .is_ok_and(|metadata| metadata.is_file)
692+ };
693+ let first_present = |path: PathBuf| {
694+ if is_file(&path) {
695+ Some(path)
696+ } else {
697+ Some(legacy(&path)).filter(is_file)
698+ }
699+ };
700+ let local_snapshot = (!fresh && !resume_local)
701+ .then(|| previous.and_then(first_present))
702+ .flatten();
703+
704+ let mut restored = resume_local;
705+ if resume_local {
706+ anyhow::ensure!(
707+ is_file(&dst),
708+ "clean reload database is missing: {}",
709+ dst.display()
710+ );
711+ info!(cell, epoch, "resumed clean local replica");
712+ } else if let Some(snapshot) = local_snapshot {
713+ self.ltx_host.rename(&snapshot, &dst)?;
714+ self.preserved
715+ .lock()
716+ .expect("preserved cache poisoned")
717+ .forget(&snapshot);
718+ info!(cell, epoch, "reused local eviction snapshot");
719+ restored = true;
720+ } else if !fresh {
721+ // Restore the newest durable epoch's full contiguous chain. The
722+ // epoch seal that once capped this read is deleted: the
723+ // cut it fixed defended only never-acked resurrection — not a
724+ // promise anyone holds — and under the log tier late arrival of
725+ // ACKED rows into a per-cell prefix is normal (recovery gathers,
726+ // the drain folds, the healing pass repairs), so a permanent cap
727+ // turned ordering slips into permanent loss. Without it the
728+ // healed rows are simply picked up here.
729+ if let Some(from) = self.highest_nonempty_epoch(cell).await? {
730+ anyhow::ensure!(
731+ from < epoch,
732+ "refusing to restore {cell} from used epoch {from} into writer epoch {epoch}"
733+ );
734+ let client = self.client_for(cell, from);
735+ let _ = self.ltx_host.remove_file(&dst);
736+ let stats = replica::restore_with_host_and_download_slots(
737+ &client,
738+ &dst,
739+ TXID(0),
740+ self.ltx_host.clone(),
741+ self.restore_slots.clone(),
742+ )
743+ .await
744+ .map_err(|error| anyhow!("restore {cell} e{from}: {error}"))?;
745+ let levels = stats
746+ .by_level
747+ .iter()
748+ .map(|(level, count)| format!("L{level}:{count}"))
749+ .collect::<Vec<_>>()
750+ .join(" ");
751+ info!(
752+ event = "restore_plan",
753+ cell,
754+ epoch = from,
755+ objects = stats.objects,
756+ bytes = stats.bytes,
757+ %levels,
758+ "computed restore plan"
759+ );
760+ info!(cell, from, to = epoch, "restored remote replica");
761+ restored = true;
762+ }
763+ }
764+
765+ // Open the managed Db (creates a fresh WAL db when nothing was restored)
766+ // and pair it with this epoch's client. Registration is immediate: the
767+ // cell can be proved durable on its very first write. The just-opened
768+ // db's position is the replica's seed -- 0 for a fresh cell, the
769+ // restored max otherwise, and equal to the remote under epoch fencing --
770+ // so the first sync skips the `calc_pos` listing that otherwise storms a
771+ // rate-limiting store. On the rare decode error we leave it unseeded and
772+ // fall back to that listing.
773+ let dst_ = dst.clone();
774+ let ltx_host = self.ltx_host.clone();
775+ let vfs_name = self.vfs_name.clone();
776+ let (db, seed) = asyncrt::blocking(move || {
777+ #[cfg(all(test, celld_internal_tests))]
778+ let mut db =
779+ crate::fault::with_connection_role("celld_ltx_db", || match vfs_name.as_deref() {
780+ Some(vfs_name) => Db::open_with_host_and_vfs(&dst_, ltx_host, vfs_name),
781+ None => Db::open_with_host(&dst_, ltx_host),
782+ })?;
783+ #[cfg(not(all(test, celld_internal_tests)))]
784+ let mut db = {
785+ debug_assert!(vfs_name.is_none());
786+ Db::open_with_host(&dst_, ltx_host)?
787+ };
788+ let seed = db.pos().ok();
789+ anyhow::Ok((db, seed))
790+ })
791+ .await?
792+ .map_err(|error| anyhow!("open managed db {}: {error}", dst.display()))?;
793+ let mut replica = Replica::new(db, self.client_for(cell, epoch));
794+ if let Some(pos) = seed {
795+ replica.seed_pos(pos);
796+ }
797+ let handle = Arc::new(Cell {
798+ replica: Mutex::new(replica),
799+ client: self.client_for(cell, epoch),
800+ req_seq: AtomicU64::new(0),
801+ synced_seq: AtomicU64::new(0),
802+ shipped_seq: AtomicU64::new(0),
803+ // Frames at or below the seed came from the bucket (or a proven
804+ // snapshot); the followers only ever need what follows.
805+ shipped_txid: AtomicU64::new(seed.map_or(0, |pos| pos.txid.0)),
806+ last_sync_ms: AtomicU64::new(asyncrt::wall_ms().max(0) as u64),
807+ durable_txid: AtomicU64::new(seed.map_or(0, |pos| pos.txid.0)),
808+ syncing: AtomicBool::new(false),
809+ ready: Notify::new(),
810+ compaction: self.compaction_queue.as_ref().map(|queue| CellCompaction {
811+ cell: cell.to_string(),
812+ epoch,
813+ // The overlay lets compaction read bundle-resident frames
814+ // beside the per-cell objects; its output stays pure
815+ // per-cell L1s, which is the continuous drain.
816+ client: celld_ltx::BundleOverlayClient::new(
817+ self.client_for(cell, epoch),
818+ Some(Arc::new(SinkFetcher {
819+ slot: self.bundle_sink.clone(),
820+ cell: cell.to_string(),
821+ epoch,
822+ })),
823+ ),
824+ local_path: Db::meta_path_for_path(&dst),
825+ host: self.ltx_host.clone(),
826+ queue: queue.clone(),
827+ min_txids: self.compaction_min_txids,
828+ compacted_txid: AtomicU64::new(0),
829+ queued: AtomicBool::new(false),
830+ cancelled: AtomicBool::new(false),
831+ cancel: Notify::new(),
832+ }),
833+ });
834+ self.cells
835+ .lock()
836+ .unwrap()
837+ .insert((cell.to_string(), epoch), handle.clone());
838+ if let Some(pos) = seed {
839+ maybe_queue_compaction(&handle, pos.txid.0);
840+ }
841+
842+ Ok(ActivationResult {
843+ path: dst,
844+ restored,
845+ })
846+ }
847+
848+ /// The output gate's primitive: take a durability ticket and return once a
849+ /// background sync that captured this write has completed, coalescing
850+ /// concurrent writes to one cell into a single upload. The write committed
851+ /// before this call, so any sync starting after our ticket captures it —
852+ /// we wait for `synced_seq >= my ticket`, not for a position, sidestepping
853+ /// the total_changes↔LTX-txid mismatch that a position compare would hit.
854+ /// Returns `position` (which the completed sync provably covered) for the
855+ /// core's coverage check.
856+ pub async fn await_durable(
857+ &self,
858+ cell: &str,
859+ epoch: u64,
860+ position: u64,
861+ ) -> anyhow::Result<(u64, celld_logic::ProofSource)> {
862+ let Some(handle) = self
863+ .cells
864+ .lock()
865+ .unwrap()
866+ .get(&(cell.to_string(), epoch))
867+ .cloned()
868+ else {
869+ anyhow::bail!("ltx cell not resident: {cell} epoch {epoch}");
870+ };
871+ let ticket = handle.req_seq.fetch_add(1, Ordering::SeqCst) + 1;
872+ #[cfg(all(test, celld_internal_tests))]
873+ if asyncrt::sabotage_active(crate::host_services::EngineSabotage::CoverTicketEarly) {
874+ return Ok((position, celld_logic::ProofSource::Bucket));
875+ }
876+ self.dirty.notify_one();
877+ self.dirty_ship.notify_one();
878+ let started = asyncrt::mono_ms();
879+ let deadline = started.saturating_add(Duration::from_secs(10).as_millis() as u64);
880+ loop {
881+ // Register the waiter before checking, so a sync that completes
882+ // between the check and the await is not missed. Either proof
883+ // releases the gate: the bucket upload, or every ensemble
884+ // member's fsync — whichever lands first.
885+ let ready = handle.ready.notified();
886+ // Prefer the fleet proof when both hold: it is the arbitrated
887+ // one, and it spares the caller C1's ownership read.
888+ let shipped = handle.shipped_seq.load(Ordering::SeqCst) >= ticket;
889+ if handle.synced_seq.load(Ordering::SeqCst) >= ticket || shipped {
890+ let source = if shipped {
891+ celld_logic::ProofSource::Fleet
892+ } else {
893+ celld_logic::ProofSource::Bucket
894+ };
895+ tracing::debug!(
896+ target: "timing",
897+ event = "durable_wait",
898+ cell,
899+ wait_us = asyncrt::mono_ms().saturating_sub(started).saturating_mul(1_000),
900+ proof = if shipped { "fleet" } else { "bucket" },
901+ "durability proof reached"
902+ );
903+ return Ok((position, source));
904+ }
905+ if asyncrt::timeout_at(deadline, ready).await.is_err() {
906+ anyhow::bail!("ltx durability timed out for {cell} epoch {epoch}");
907+ }
908+ }
909+ }
910+
911+ /// A direct, synchronous durability pass for the rare eviction
912+ /// gates (not the hot write path). Also advances the cell's durable position
913+ /// so any output-gate waiters ride it.
914+ pub async fn sync_wait(&self, cell: &str, epoch: u64, _timeout: Duration) -> SyncWait {
915+ let Some(handle) = self
916+ .cells
917+ .lock()
918+ .unwrap()
919+ .get(&(cell.to_string(), epoch))
920+ .cloned()
921+ else {
922+ return SyncWait::Unsupported;
923+ };
924+ match sync_cell(handle).await {
925+ Some(true) => SyncWait::Durable,
926+ Some(false) => SyncWait::Failed,
927+ None => SyncWait::Unsupported,
928+ }
929+ }
930+
931+ /// Drop this cell's replication handle, leaving every file in place.
932+ ///
933+ /// The handle owns the replica, and the replica holds two open SQLite
934+ /// connections -- one of them inside a long-running read transaction that
935+ /// pins pages -- so a stop that does not release it keeps that memory for
936+ /// the life of the process. Every stop has to reach this, because a stop
937+ /// is where the activation ends.
938+ ///
939+ /// No durability pass here, deliberately. This runs on the stops that are
940+ /// not an orderly handoff, and a fenced node has lost the authority that
941+ /// would make writing more of this cell's history safe. `evict` below
942+ /// still syncs, and still refuses to drop a handle whose final pass
943+ /// failed, because that is the path where the node keeps the cell and is
944+ /// giving it up on purpose.
945+ pub fn release(&self, cell: &str, epoch: u64) {
946+ let removed = self
947+ .cells
948+ .lock()
949+ .unwrap()
950+ .remove(&(cell.to_string(), epoch));
951+ if let Some(handle) = removed {
952+ cancel_compaction(&handle);
953+ }
954+ }
955+
956+ pub async fn evict(&self, cell: &str, epoch: u64, preserve_local: bool) {
957+ // A final durability pass so no acknowledged write is stranded —
958+ // and a FAILED pass refuses the eviction outright (fidelity
959+ // audit, DRIFTED #3): removing the handle on failure hid a cell
960+ // with shipped-but-unuploaded frames from all_shipped_tiered and
961+ // the drain, and let a preserved snapshot later re-seed
962+ // durable_txid past the truth. On refusal the handle stays
963+ // registered (the barriers keep counting it, the sync loop keeps
964+ // retrying) and the files stay put for a retried eviction or a
965+ // local reactivation.
966+ if matches!(
967+ self.sync_wait(cell, epoch, Duration::from_secs(10)).await,
968+ SyncWait::Failed
969+ ) {
970+ warn!(
971+ cell,
972+ epoch, "eviction refused: the final durability pass failed; the cell stays managed"
973+ );
974+ return;
975+ }
976+ self.remove_local(cell, epoch, preserve_local);
977+ }
978+
979+ /// Discard a reset runtime without another durability attempt.
980+ ///
981+ /// The proof that triggered Reset already failed. Retrying it here can keep
982+ /// the unproved database resident and contradicts Reset's keep-nothing
983+ /// contract, so this path removes the handle and every live local file.
984+ pub(crate) fn discard(&self, cell: &str, epoch: u64) {
985+ self.remove_local(cell, epoch, false);
986+ }
987+
988+ fn remove_local(&self, cell: &str, epoch: u64, preserve_local: bool) {
989+ let removed = self
990+ .cells
991+ .lock()
992+ .unwrap()
993+ .remove(&(cell.to_string(), epoch));
994+ if let Some(handle) = removed {
995+ cancel_compaction(&handle);
996+ }
997+ let db = self.db_path(cell, epoch);
998+ if preserve_local {
999+ let preserved = db.with_extension("evicted");
1000+ if let Err(error) = self.ltx_host.rename(&db, &preserved) {
1001+ warn!(cell, epoch, %error, "preserve local snapshot failed");
1002+ } else {
1003+ if let Err(error) = self
1004+ .preserved
1005+ .lock()
1006+ .expect("preserved cache poisoned")
1007+ .insert(preserved)
1008+ {
1009+ warn!(cell, epoch, %error, "index preserved local snapshot failed");
1010+ }
1011+ }
1012+ }
1013+ // Clear the WAL/meta siblings and the live db regardless: a reactivation
1014+ // restores or reuses the `.hibernated` copy.
1015+ for suffix in ["-wal", "-shm"] {
1016+ let mut sibling = db.clone().into_os_string();
1017+ sibling.push(suffix);
1018+ let _ = self.ltx_host.remove_file(&PathBuf::from(sibling));
1019+ }
1020+ let _ = self.ltx_host.remove_dir_all(&Db::meta_path_for_path(&db));
1021+ if !preserve_local {
1022+ let _ = self.ltx_host.remove_file(&db);
1023+ }
1024+ }
1025+
1026+ /// Copy the live epoch into a private read-only snapshot for inspection.
1027+ pub fn snapshot_active(
1028+ &self,
1029+ cell: &str,
1030+ epoch: u64,
1031+ ) -> anyhow::Result<Option<RestoredSnapshot>> {
1032+ let source = self.db_path(cell, epoch);
1033+ if !self
1034+ .ltx_host
1035+ .metadata(&source)
1036+ .is_ok_and(|metadata| metadata.is_file)
1037+ {
1038+ return Ok(None);
1039+ }
1040+ let directory = self.watch.join(format!(".inspect-{cell}-e{epoch}"));
1041+ let _ = self.ltx_host.remove_dir_all(&directory);
1042+ self.ltx_host.create_dir_all(&directory)?;
1043+ let path = directory.join("db.sqlite");
1044+ sqlite_snapshot(&source, &path, self.vfs_name.as_deref())?;
1045+ Ok(Some(RestoredSnapshot::new(
1046+ epoch,
1047+ path,
1048+ directory,
1049+ self.ltx_host.filesystem(),
1050+ )))
1051+ }
1052+
1053+ /// Restore the newest durable replica into a private snapshot without
1054+ /// claiming or activating the cell.
1055+ pub async fn restore_snapshot(&self, cell: &str) -> anyhow::Result<Option<RestoredSnapshot>> {
1056+ let Some(epoch) = self.highest_nonempty_epoch(cell).await? else {
1057+ return Ok(None);
1058+ };
1059+ let directory = self.watch.join(format!(".restore-{cell}"));
1060+ let _ = self.ltx_host.remove_dir_all(&directory);
1061+ self.ltx_host.create_dir_all(&directory)?;
1062+ let path = directory.join("db.sqlite");
1063+ replica::restore_with_host_and_download_slots(
1064+ &self.client_for(cell, epoch),
1065+ &path,
1066+ TXID(0),
1067+ self.ltx_host.clone(),
1068+ self.restore_slots.clone(),
1069+ )
1070+ .await
1071+ .map_err(|error| anyhow!("restore snapshot {cell} e{epoch}: {error}"))?;
1072+ Ok(Some(RestoredSnapshot::new(
1073+ epoch,
1074+ path,
1075+ directory,
1076+ self.ltx_host.filesystem(),
1077+ )))
1078+ }
1079+
1080+ pub fn prune_local_cache(&self, max_bytes: u64) -> std::io::Result<(usize, usize, u64)> {
1081+ self.preserved
1082+ .lock()
1083+ .expect("preserved cache poisoned")
1084+ .prune(&self.watch, max_bytes)
1085+ }
1086+
1087+ /// Close the replicator handle while retaining the live database and WAL
1088+ /// exactly where the local path encodes them.
1089+ pub fn close_for_reload(&self, cell: &str, epoch: u64) -> anyhow::Result<()> {
1090+ let removed = self
1091+ .cells
1092+ .lock()
1093+ .unwrap()
1094+ .remove(&(cell.to_string(), epoch));
1095+ if let Some(handle) = removed {
1096+ cancel_compaction(&handle);
1097+ }
1098+ let path = self.db_path(cell, epoch);
1099+ anyhow::ensure!(
1100+ self.ltx_host
1101+ .metadata(&path)
1102+ .is_ok_and(|metadata| metadata.is_file),
1103+ "resident database is missing: {}",
1104+ path.display()
1105+ );
1106+ Ok(())
1107+ }
1108+
1109+ /// Enumerate live-named databases. Cached `.evicted` files are separate
1110+ /// and remain under the ordinary cache byte limit.
1111+ pub fn local_cells(&self) -> Vec<celld_logic::LocalCell> {
1112+ let mut cells = Vec::new();
1113+ let filesystem = self.ltx_host.filesystem();
1114+ let Ok(cell_dirs) = filesystem.read_dir(&self.watch) else {
1115+ return cells;
1116+ };
1117+ for cell_dir in cell_dirs {
1118+ if !cell_dir.is_dir {
1119+ continue;
1120+ }
1121+ let Some(cell) = cell_dir.file_name.to_str().map(str::to_owned) else {
1122+ continue;
1123+ };
1124+ let Ok(epochs) = filesystem.read_dir(&cell_dir.path.join("ltx")) else {
1125+ continue;
1126+ };
1127+ for epoch_dir in epochs {
1128+ let Some(epoch) = epoch_dir
1129+ .file_name
1130+ .to_str()
1131+ .and_then(|name| name.strip_prefix('e'))
1132+ .and_then(|epoch| epoch.parse::<u64>().ok())
1133+ else {
1134+ continue;
1135+ };
1136+ if filesystem
1137+ .metadata(&epoch_dir.path.join("db.sqlite"))
1138+ .is_ok_and(|metadata| metadata.is_file)
1139+ {
1140+ cells.push(celld_logic::LocalCell {
1141+ id: cell.clone(),
1142+ epoch,
1143+ });
1144+ }
1145+ }
1146+ }
1147+ cells.sort();
1148+ cells.dedup();
1149+ cells
1150+ }
1151+
1152+ /// Delete stale live-named epochs after the runtime has identified and
1153+ /// closed its exact resident set. Remote replicas remain authoritative.
1154+ pub fn prune_stale_live(
1155+ &self,
1156+ keep: &std::collections::BTreeSet<(String, u64)>,
1157+ ) -> anyhow::Result<usize> {
1158+ let stale: Vec<_> = self
1159+ .local_cells()
1160+ .into_iter()
1161+ .filter(|cell| !keep.contains(&(cell.id.clone(), cell.epoch)))
1162+ .collect();
1163+ for cell in &stale {
1164+ let db = self.db_path(&cell.id, cell.epoch);
1165+ if let Some(parent) = db.parent() {
1166+ self.ltx_host.remove_dir_all(parent)?;
1167+ let mut preserved = self.preserved.lock().expect("preserved cache poisoned");
1168+ preserved.forget(&db.with_extension("evicted"));
1169+ preserved.forget(&db.with_extension("hibernated"));
1170+ }
1171+ }
1172+ let remaining: std::collections::BTreeSet<_> = self
1173+ .local_cells()
1174+ .into_iter()
1175+ .map(|cell| (cell.id, cell.epoch))
1176+ .collect();
1177+ anyhow::ensure!(
1178+ &remaining == keep,
1179+ "clean reload inventory mismatch after pruning: expected {}, found {}",
1180+ keep.len(),
1181+ remaining.len()
1182+ );
1183+ Ok(stale.len())
1184+ }
1185+
1186+ /// There is no external process, so the in-process replicator is healthy while celld runs.
1187+ pub fn process_status(&self) -> std::io::Result<Option<std::process::ExitStatus>> {
1188+ Ok(None)
1189+ }
1190+}
1191+
1192+/// One capture+upload for a cell: advance its durable position on success and
1193+/// wake its waiters. Everything committed before the capture is durable once
1194+/// uploaded, so the target is read before `db.sync`.
1195+///
1196+/// The capture runs under the replica mutex on a blocking thread; the upload
1197+/// runs OFF the mutex. A slow bucket PUT held the lock for its whole round
1198+/// trip, and the log tier's ship capture queued behind it — the lab measured
1199+/// 4-6 s ack spikes at every flush collision. Uploads are idempotent
1200+/// overwrites keyed by TXID, and `syncing` already guarantees one pass per
1201+/// cell, so staging then uploading lock-free is the same protocol
1202+/// `Replica::sync` runs, minus the contention.
1203+///
1204+/// `Some(true)` means success, `Some(false)` means failure, and `None` means
1205+/// that the replica lost its database.
1206+async fn sync_cell(handle: CellHandle) -> Option<bool> {
1207+ // Tickets taken before the capture: their writes committed before
1208+ // `db.sync` runs, so it captures them. Read before the capture so a
1209+ // ticket taken during the sync is credited by the next one, not this.
1210+ type Staged = (u64, Vec<(u64, Vec<u8>)>);
1211+ let handle_ = handle.clone();
1212+ let staged: Option<Result<Staged, ()>> = asyncrt::blocking(move || {
1213+ let captured = handle_.req_seq.load(Ordering::SeqCst);
1214+ let mut replica = handle_.replica.lock().unwrap();
1215+ let from = replica.pos().txid.0 + 1;
1216+ let db = replica.db_mut()?;
1217+ if let Err(error) = db.sync() {
1218+ warn!(%error, "ltx wal capture failed");
1219+ return Some(Err(()));
1220+ }
1221+ let dpos = match db.pos() {
1222+ Ok(pos) => pos,
1223+ Err(error) => {
1224+ warn!(%error, "ltx position read failed");
1225+ return Some(Err(()));
1226+ }
1227+ };
1228+ let mut files = Vec::new();
1229+ for txid in from..=dpos.txid.0 {
1230+ match db.read_ltx_file(0, TXID(txid), TXID(txid)) {
1231+ Ok(bytes) => files.push((txid, bytes)),
1232+ Err(error) => {
1233+ warn!(%error, txid, "read staged l0 failed");
1234+ return Some(Err(()));
1235+ }
1236+ }
1237+ }
1238+ Some(Ok((captured, files)))
1239+ })
1240+ .await
1241+ .unwrap_or(Some(Err(())));
1242+ let (captured, files) = match staged {
1243+ None => return None,
1244+ Some(Err(())) => {
1245+ handle.ready.notify_waiters();
1246+ return Some(false);
1247+ }
1248+ Some(Ok(staged)) => staged,
1249+ };
1250+ let last = files.last().map(|(txid, _)| *txid);
1251+ for (txid, bytes) in &files {
1252+ if let Err(error) = handle
1253+ .client
1254+ .write_ltx_file(0, TXID(*txid), TXID(*txid), bytes)
1255+ .await
1256+ {
1257+ warn!(%error, txid, "ltx upload failed");
1258+ handle
1259+ .last_sync_ms
1260+ .store(asyncrt::wall_ms().max(0) as u64, Ordering::SeqCst);
1261+ handle.ready.notify_waiters();
1262+ return Some(false);
1263+ }
1264+ }
1265+ if let Some(last) = last {
1266+ // Advance the replica's uploaded watermark; `syncing` serializes
1267+ // passes, so nothing else moved it meanwhile.
1268+ handle
1269+ .replica
1270+ .lock()
1271+ .unwrap()
1272+ .seed_pos(Pos::new(TXID(last), 0));
1273+ handle.durable_txid.fetch_max(last, Ordering::SeqCst);
1274+ }
1275+ handle.synced_seq.fetch_max(captured, Ordering::SeqCst);
1276+ maybe_queue_compaction(&handle, handle.durable_txid.load(Ordering::SeqCst));
1277+ handle
1278+ .last_sync_ms
1279+ .store(asyncrt::wall_ms().max(0) as u64, Ordering::SeqCst);
1280+ handle.ready.notify_waiters();
1281+ Some(true)
1282+}
1283+
1284+fn maybe_queue_compaction(handle: &CellHandle, durable_txid: u64) {
1285+ let Some(compaction) = &handle.compaction else {
1286+ return;
1287+ };
1288+ if compaction.cancelled.load(Ordering::SeqCst)
1289+ || durable_txid.saturating_sub(compaction.compacted_txid.load(Ordering::SeqCst))
1290+ < compaction.min_txids
1291+ || compaction
1292+ .queued
1293+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
1294+ .is_err()
1295+ {
1296+ return;
1297+ }
1298+ if compaction
1299+ .queue
1300+ .send(CompactionWork {
1301+ cell: Arc::downgrade(handle),
1302+ queued_at_mono_ms: asyncrt::mono_ms(),
1303+ })
1304+ .is_err()
1305+ {
1306+ compaction.queued.store(false, Ordering::SeqCst);
1307+ }
1308+}
1309+
1310+fn cancel_compaction(handle: &CellHandle) {
1311+ let Some(compaction) = &handle.compaction else {
1312+ return;
1313+ };
1314+ compaction.cancelled.store(true, Ordering::SeqCst);
1315+ compaction.cancel.notify_waiters();
1316+}
1317+
1318+fn start_compaction_loop(config: CompactionConfig) -> mpsc::UnboundedSender<CompactionWork> {
1319+ let (queue, mut work) = mpsc::unbounded_channel::<CompactionWork>();
1320+ let slots = Arc::new(Semaphore::new(config.concurrency));
1321+ asyncrt::spawn(async move {
1322+ while let Some(work) = work.recv().await {
1323+ let Ok(permit) = slots.clone().acquire_owned().await else {
1324+ break;
1325+ };
1326+ let Some(cell) = work.cell.upgrade() else {
1327+ continue;
1328+ };
1329+ asyncrt::spawn(async move {
1330+ let _permit = permit;
1331+ compact_cell(cell, work.queued_at_mono_ms).await;
1332+ })
1333+ .detach();
1334+ }
1335+ })
1336+ .detach();
1337+ queue
1338+}
1339+
1340+async fn compact_cell(handle: CellHandle, queued_at_mono_ms: u64) {
1341+ let Some(compaction) = &handle.compaction else {
1342+ return;
1343+ };
1344+ let cancelled = compaction.cancel.notified();
1345+ tokio::pin!(cancelled);
1346+ if compaction.cancelled.load(Ordering::SeqCst) {
1347+ return;
1348+ }
1349+
1350+ let queue_ms = asyncrt::mono_ms().saturating_sub(queued_at_mono_ms);
1351+ let started = asyncrt::mono_ms();
1352+ let compactor = ReplicaCompactor::new(&compaction.client)
1353+ .with_host(compaction.host.clone())
1354+ .with_verification(true)
1355+ .with_local_path(&compaction.local_path)
1356+ .with_limits(COMPACTION_MAX_FILES, COMPACTION_MAX_INPUT_BYTES);
1357+ let worker = compactor.compact(1);
1358+ tokio::pin!(worker);
1359+ let result = asyncrt::select! {
1360+ _ = &mut cancelled => None,
1361+ result = &mut worker => Some(result),
1362+ };
1363+
1364+ let mut completed = false;
1365+ match result {
1366+ Some(Ok(Some(output))) => {
1367+ let info = output.info;
1368+ compaction
1369+ .compacted_txid
1370+ .store(info.max_txid.0, Ordering::SeqCst);
1371+ completed = true;
1372+ info!(
1373+ event = "ltx_compaction",
1374+ cell = %compaction.cell,
1375+ epoch = compaction.epoch,
1376+ source_level = 0,
1377+ destination_level = info.level,
1378+ min_txid = info.min_txid.0,
1379+ max_txid = info.max_txid.0,
1380+ input_objects = output.input_files,
1381+ input_bytes = output.input_bytes,
1382+ local_input_objects = output.local_input_files,
1383+ remote_input_objects = output.input_files - output.local_input_files,
1384+ output_bytes = info.size,
1385+ queue_ms,
1386+ elapsed_ms = asyncrt::mono_ms().saturating_sub(started),
1387+ result = "ok",
1388+ "compacted an additive LTX level"
1389+ );
1390+ }
1391+ Some(Ok(None)) => {
1392+ compaction
1393+ .compacted_txid
1394+ .store(handle.durable_txid.load(Ordering::SeqCst), Ordering::SeqCst);
1395+ completed = true;
1396+ info!(
1397+ event = "ltx_compaction",
1398+ cell = %compaction.cell,
1399+ epoch = compaction.epoch,
1400+ source_level = 0,
1401+ destination_level = 1,
1402+ queue_ms,
1403+ elapsed_ms = asyncrt::mono_ms().saturating_sub(started),
1404+ result = "no_work",
1405+ "the additive LTX level is current"
1406+ );
1407+ }
1408+ Some(Err(error)) => {
1409+ warn!(
1410+ event = "ltx_compaction",
1411+ cell = %compaction.cell,
1412+ epoch = compaction.epoch,
1413+ source_level = 0,
1414+ destination_level = 1,
1415+ queue_ms,
1416+ elapsed_ms = asyncrt::mono_ms().saturating_sub(started),
1417+ result = "error",
1418+ %error,
1419+ "additive LTX compaction failed"
1420+ );
1421+ }
1422+ None => {
1423+ info!(
1424+ event = "ltx_compaction",
1425+ cell = %compaction.cell,
1426+ epoch = compaction.epoch,
1427+ source_level = 0,
1428+ destination_level = 1,
1429+ queue_ms,
1430+ elapsed_ms = asyncrt::mono_ms().saturating_sub(started),
1431+ result = "cancelled",
1432+ "cancelled an additive LTX compaction"
1433+ );
1434+ }
1435+ }
1436+ compaction.queued.store(false, Ordering::SeqCst);
1437+
1438+ if completed && !compaction.cancelled.load(Ordering::SeqCst) {
1439+ // Pace consecutive rounds for one cell: a restart with a large tail
1440+ // otherwise drains back-to-back for minutes. The pause matches the
1441+ // round it follows (capped), so a cell compacts at half duty cycle
1442+ // while the worker slot frees for other cells immediately — this
1443+ // task detaches and does not hold the concurrency permit.
1444+ let pause = Duration::from_millis(asyncrt::mono_ms().saturating_sub(started))
1445+ .min(Duration::from_secs(2));
1446+ let handle_ = handle.clone();
1447+ asyncrt::spawn(async move {
1448+ asyncrt::sleep(pause).await;
1449+ let durable_txid = handle_.durable_txid.load(Ordering::SeqCst);
1450+ maybe_queue_compaction(&handle_, durable_txid);
1451+ })
1452+ .detach();
1453+ }
1454+}
1455+
1456+fn compaction_config_from_env() -> anyhow::Result<Option<CompactionConfig>> {
1457+ // On by default. A mixed fleet must set `0` until every node can read
1458+ // v0.5.2 block objects. An old reader cannot take over a cell after its
1459+ // first L1 publication.
1460+ let enabled = crate::env_vars::flag("CELLD_LTX_COMPACTION", true)?;
1461+ if !enabled {
1462+ return Ok(None);
1463+ }
1464+
1465+ let min_txids = crate::env_vars::with_default("CELLD_LTX_COMPACTION_MIN_TXIDS", 256)?;
1466+ let concurrency = crate::env_vars::with_default("CELLD_LTX_COMPACTIONS", 2)?;
1467+ anyhow::ensure!(
1468+ min_txids >= 2,
1469+ "CELLD_LTX_COMPACTION_MIN_TXIDS must be at least 2"
1470+ );
1471+ anyhow::ensure!(concurrency > 0, "CELLD_LTX_COMPACTIONS must be positive");
1472+ Ok(Some(CompactionConfig {
1473+ min_txids: min_txids as u64,
1474+ concurrency,
1475+ }))
1476+}
1477+
1478+/// The node's background sync loop: wake on a dirty cell (or a slow tick) and
1479+/// launch a sync for every cell whose committed position runs ahead of its
1480+/// durable one. Each cell's sync is an independent, self-rescheduling task —
1481+/// the loop does *not* wait for the batch to finish — so one slow cell's upload
1482+/// never stalls the others (a cell keeps its own cadence up to the concurrency
1483+/// bound). A cell's writes reported between its syncs still clear on one upload:
1484+/// the batching win, without the cross-cell head-of-line blocking.
1485+async fn sync_loop(
1486+ cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>,
1487+ dirty: Arc<Notify>,
1488+ slots: Arc<Semaphore>,
1489+ shipper: Arc<Mutex<Option<Arc<dyn Shipper>>>>,
1490+ bundle_sink: Arc<Mutex<Option<Arc<dyn BundleSink>>>>,
1491+ flush_ms: u64,
1492+) {
1493+ loop {
1494+ asyncrt::select! {
1495+ _ = dirty.notified() => {},
1496+ _ = asyncrt::sleep(Duration::from_millis(25)) => {},
1497+ }
1498+ // The upload-cadence dial. With a healthy shipper installed, acks
1499+ // ride the followers, so uploads become tiering and are PACED: an
1500+ // immediate upload would hold the replica mutex for a bucket round
1501+ // trip and the ship capture would queue behind it, putting the
1502+ // bucket back on the ack path — the lab measured exactly that.
1503+ // Without a shipper (or degraded), uploads run immediately: they
1504+ // are the ack path again.
1505+ let paced = flush_ms > 0
1506+ && shipper
1507+ .lock()
1508+ .unwrap()
1509+ .as_ref()
1510+ .is_some_and(|shipper| shipper.active());
1511+ // With an active bundle sink, the bundle loop owns paced tiering
1512+ // entirely — one PUT per node-flush instead of one per cell. This
1513+ // loop then serves only the unpaced (degraded) mode and the direct
1514+ // sync_wait callers, which are the drain points.
1515+ let bundling = paced
1516+ && bundle_sink
1517+ .lock()
1518+ .unwrap()
1519+ .as_ref()
1520+ .is_some_and(|sink| sink.active());
1521+ let now = asyncrt::wall_ms().max(0) as u64;
1522+ let work: Vec<CellHandle> = {
1523+ let map = cells.lock().unwrap();
1524+ map.values()
1525+ .filter(|c| {
1526+ #[cfg(all(test, celld_internal_tests))]
1527+ if asyncrt::sabotage_active(crate::host_services::EngineSabotage::HideDirtyCell)
1528+ {
1529+ return false;
1530+ }
1531+ c.req_seq.load(Ordering::SeqCst) > c.synced_seq.load(Ordering::SeqCst)
1532+ && !bundling
1533+ && (!paced
1534+ || now.saturating_sub(c.last_sync_ms.load(Ordering::SeqCst))
1535+ >= flush_ms)
1536+ })
1537+ .cloned()
1538+ .collect()
1539+ };
1540+ for cell in work {
1541+ // Claim the cell; skip if a sync is already in flight for it.
1542+ if cell
1543+ .syncing
1544+ .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
1545+ .is_err()
1546+ {
1547+ continue;
1548+ }
1549+ let slots = slots.clone();
1550+ let dirty = dirty.clone();
1551+ asyncrt::spawn(async move {
1552+ // Keep syncing this cell while it stays dirty, rather than
1553+ // notifying the main loop to re-scan every completion — that made
1554+ // the loop wake O(cells) times and starved throughput as cells
1555+ // accumulated. This is not a busy loop: each iteration awaits an
1556+ // object-store upload (~one round-trip). A *failed* sync would
1557+ // not, so it backs off, keeping the only tight iterations the
1558+ // ones that actually uploaded.
1559+ loop {
1560+ let ok = {
1561+ let _permit = slots.acquire().await;
1562+ sync_cell(cell.clone()).await
1563+ };
1564+ if cell.req_seq.load(Ordering::SeqCst) <= cell.synced_seq.load(Ordering::SeqCst)
1565+ {
1566+ break;
1567+ }
1568+ // Under pacing, one upload per wake: the next round waits
1569+ // for the flush interval instead of re-syncing here.
1570+ if paced {
1571+ break;
1572+ }
1573+ if ok != Some(true) {
1574+ asyncrt::sleep(Duration::from_millis(50)).await;
1575+ }
1576+ }
1577+ cell.syncing.store(false, Ordering::SeqCst);
1578+ // A write landing in the clear window is picked up next tick;
1579+ // nudge the loop so it does not wait the full interval.
1580+ if cell.req_seq.load(Ordering::SeqCst) > cell.synced_seq.load(Ordering::SeqCst) {
1581+ dirty.notify_one();
1582+ }
1583+ })
1584+ .detach();
1585+ }
1586+ }
1587+}
1588+
1589+/// The bundle loop: paced like the per-cell tiering it replaces, but the
1590+/// unit is the node, not the cell. Every dirty cell's captured L0 segments
1591+/// go up as ONE object per flush interval — the Class A collapse — and the
1592+/// per-cell prefixes stay untouched until a drain point needs them. The
1593+/// crediting mirrors sync_cell: `durable_txid` means bucket-covered,
1594+/// whether by a per-cell object or a bundle row; the replica's own
1595+/// position deliberately does NOT advance, so the direct sync_wait drain
1596+/// still knows exactly which frames lack per-cell objects.
1597+async fn bundle_loop(
1598+ cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>,
1599+ sink: Arc<Mutex<Option<Arc<dyn BundleSink>>>>,
1600+ flush_ms: u64,
1601+) {
1602+ if flush_ms == 0 {
1603+ return;
1604+ }
1605+ let mut tick = asyncrt::interval(Duration::from_millis(flush_ms));
1606+ tick.set_missed_tick_behavior(asyncrt::MissedTickBehavior::Delay);
1607+ loop {
1608+ tick.tick().await;
1609+ let installed = sink.lock().unwrap().clone();
1610+ let Some(active) = installed.filter(|sink| sink.active()) else {
1611+ continue;
1612+ };
1613+ let work: Vec<((String, u64), CellHandle)> = {
1614+ let map = cells.lock().unwrap();
1615+ map.iter()
1616+ .filter(|(_, cell)| {
1617+ cell.req_seq.load(Ordering::SeqCst) > cell.synced_seq.load(Ordering::SeqCst)
1618+ })
1619+ .map(|(key, cell)| (key.clone(), cell.clone()))
1620+ .collect()
1621+ };
1622+ if work.is_empty() {
1623+ continue;
1624+ }
1625+ type Credits = Vec<(CellHandle, u64, u64)>;
1626+ let (entries, credits): (Vec<celld_ltx::bundle::BundleEntry>, Credits) =
1627+ asyncrt::blocking(move || {
1628+ let mut entries = Vec::new();
1629+ let mut credits = Vec::new();
1630+ for ((cell, epoch), handle) in work {
1631+ let tickets = handle.req_seq.load(Ordering::SeqCst);
1632+ let mut replica = handle.replica.lock().unwrap();
1633+ let Some(db) = replica.db_mut() else { continue };
1634+ if db.sync().is_err() {
1635+ continue;
1636+ }
1637+ let Ok(pos) = db.pos() else { continue };
1638+ let from = handle.durable_txid.load(Ordering::SeqCst) + 1;
1639+ let mut complete = true;
1640+ for txid in from..=pos.txid.0 {
1641+ match db.read_ltx_file(0, TXID(txid), TXID(txid)) {
1642+ Ok(bytes) => entries.push(celld_ltx::bundle::BundleEntry {
1643+ cell: cell.clone(),
1644+ cell_epoch: epoch,
1645+ txid,
1646+ bytes,
1647+ }),
1648+ Err(error) => {
1649+ warn!(%error, txid, "read staged l0 for bundle failed");
1650+ complete = false;
1651+ break;
1652+ }
1653+ }
1654+ }
1655+ drop(replica);
1656+ if complete {
1657+ credits.push((handle, tickets, pos.txid.0));
1658+ }
1659+ }
1660+ (entries, credits)
1661+ })
1662+ .await
1663+ .unwrap_or_default();
1664+ if credits.is_empty() {
1665+ continue;
1666+ }
1667+ let count = entries.len();
1668+ if entries.is_empty() || active.put_bundle(entries).await {
1669+ if count > 0 {
1670+ info!(
1671+ event = "log_bundle_flush",
1672+ entries = count,
1673+ cells = credits.len(),
1674+ "flushed a bundle"
1675+ );
1676+ }
1677+ for (handle, tickets, position) in credits {
1678+ handle.durable_txid.fetch_max(position, Ordering::SeqCst);
1679+ handle.synced_seq.fetch_max(tickets, Ordering::SeqCst);
1680+ handle
1681+ .last_sync_ms
1682+ .store(asyncrt::wall_ms().max(0) as u64, Ordering::SeqCst);
1683+ // The compactor's overlay client sees bundle rows, so
1684+ // bundle credits queue compaction like per-cell uploads do
1685+ // — compaction is the continuous drain into pure layout.
1686+ maybe_queue_compaction(&handle, position);
1687+ handle.ready.notify_waiters();
1688+ }
1689+ }
1690+ }
1691+}
1692+
1693+/// The log tier's group-commit loop, `sync_loop`'s fleet twin: wake on a
1694+/// gate ticket, capture every dirty cell's new L0 segments in one blocking
1695+/// pass, ship them as one batch, and credit the tickets the capture
1696+/// covered. One batch in flight is what keeps every follower's fragment
1697+/// contiguous, and nothing on this path waits for the bucket.
1698+async fn ship_loop(
1699+ cells: Arc<Mutex<BTreeMap<(String, u64), CellHandle>>>,
1700+ dirty_ship: Arc<Notify>,
1701+ shipper: Arc<Mutex<Option<Arc<dyn Shipper>>>>,
1702+) {
1703+ // The truncation ledger is a core decision
1704+ // (celld_logic::log_tier::ShipLedger): outstanding batches carry the
1705+ // cells and top TXIDs, a batch is covered once every cell's durable
1706+ // position passes its top TXID — bundle credits do this within a
1707+ // flush interval — and the covered watermark rides the next append as
1708+ // the followers' truncate_to. This is what bounds follower disks, and
1709+ // the ledger's epoch reset is what keeps a stale watermark from
1710+ // truncating a fresh fragment.
1711+ let mut ledger: celld_logic::log_tier::ShipLedger<Vec<(CellHandle, u64)>> =
1712+ celld_logic::log_tier::ShipLedger::default();
1713+ loop {
1714+ asyncrt::select! {
1715+ _ = dirty_ship.notified() => {},
1716+ _ = asyncrt::sleep(Duration::from_millis(25)) => {},
1717+ }
1718+ let installed = shipper.lock().unwrap().clone();
1719+ let Some(active) = installed.filter(|shipper| shipper.active()) else {
1720+ continue;
1721+ };
1722+ #[cfg(all(test, celld_internal_tests))]
1723+ let skip_observe_epoch =
1724+ asyncrt::sabotage_active(crate::host_services::EngineSabotage::SkipObserveLogEpoch);
1725+ #[cfg(not(all(test, celld_internal_tests)))]
1726+ let skip_observe_epoch = false;
1727+ if !skip_observe_epoch {
1728+ ledger.observe_epoch(active.epoch());
1729+ }
1730+ let work: Vec<((String, u64), CellHandle)> = {
1731+ let map = cells.lock().unwrap();
1732+ map.iter()
1733+ .filter(|(_, cell)| {
1734+ let req = cell.req_seq.load(Ordering::SeqCst);
1735+ req > cell.shipped_seq.load(Ordering::SeqCst)
1736+ && req > cell.synced_seq.load(Ordering::SeqCst)
1737+ })
1738+ .map(|(key, cell)| (key.clone(), cell.clone()))
1739+ .collect()
1740+ };
1741+ if work.is_empty() {
1742+ continue;
1743+ }
1744+ let round = asyncrt::mono_ms();
1745+ type Credits = Vec<(CellHandle, u64, u64)>;
1746+ let (entries, credits): (Vec<ShipEntry>, Credits) = asyncrt::blocking(move || {
1747+ let mut entries = Vec::new();
1748+ let mut credits = Vec::new();
1749+ for ((cell, epoch), handle) in work {
1750+ // Tickets taken before the capture are covered by it —
1751+ // the same discipline as sync_cell.
1752+ let tickets = handle.req_seq.load(Ordering::SeqCst);
1753+ let mut replica = handle.replica.lock().unwrap();
1754+ let Some(db) = replica.db_mut() else { continue };
1755+ if db.sync().is_err() {
1756+ continue;
1757+ }
1758+ let Ok(pos) = db.pos() else { continue };
1759+ let from = handle.shipped_txid.load(Ordering::SeqCst) + 1;
1760+ let mut complete = true;
1761+ for txid in from..=pos.txid.0 {
1762+ match db.read_ltx_file(0, TXID(txid), TXID(txid)) {
1763+ Ok(bytes) => entries.push(ShipEntry {
1764+ cell: cell.clone(),
1765+ epoch,
1766+ txid,
1767+ bytes,
1768+ }),
1769+ // A pruned L0 the bucket already holds is not a
1770+ // gap the followers need filled; anything else
1771+ // leaves the cell uncredited for this round.
1772+ Err(_) if txid <= handle.durable_txid.load(Ordering::SeqCst) => {}
1773+ Err(_) => {
1774+ complete = false;
1775+ break;
1776+ }
1777+ }
1778+ }
1779+ drop(replica);
1780+ if complete {
1781+ credits.push((handle, tickets, pos.txid.0));
1782+ }
1783+ }
1784+ (entries, credits)
1785+ })
1786+ .await
1787+ .unwrap_or_default();
1788+ if credits.is_empty() {
1789+ continue;
1790+ }
1791+ ledger.advance(|cells| {
1792+ cells
1793+ .iter()
1794+ .all(|(handle, txid)| handle.durable_txid.load(Ordering::SeqCst) >= *txid)
1795+ });
1796+ let covered_seq = ledger.covered_seq();
1797+ let captured_ms = asyncrt::mono_ms().saturating_sub(round);
1798+ let shipped = if entries.is_empty() {
1799+ Some(covered_seq)
1800+ } else {
1801+ active.ship(&entries, covered_seq).await
1802+ };
1803+ if let Some(last_seq) = shipped {
1804+ if last_seq > covered_seq {
1805+ ledger.shipped(
1806+ last_seq,
1807+ credits
1808+ .iter()
1809+ .map(|(handle, _, position)| (handle.clone(), *position))
1810+ .collect(),
1811+ );
1812+ }
1813+ info!(
1814+ event = "log_ship_round",
1815+ entries = entries.len(),
1816+ cells = credits.len(),
1817+ capture_ms = captured_ms,
1818+ ship_ms = asyncrt::mono_ms()
1819+ .saturating_sub(round)
1820+ .saturating_sub(captured_ms),
1821+ "shipped a log batch"
1822+ );
1823+ for (handle, tickets, position) in credits {
1824+ handle.shipped_txid.fetch_max(position, Ordering::SeqCst);
1825+ handle.shipped_seq.fetch_max(tickets, Ordering::SeqCst);
1826+ handle.ready.notify_waiters();
1827+ }
1828+ active.batch_credited();
1829+ }
1830+ }
1831+}
1832+
1833+/// Node-level object-store config (no per-cell prefix). `build_store` on this
1834+/// yields the one shared client; per-cell clients set only `path`.
1835+fn node_config(
1836+ bucket: &str,
1837+ endpoint: Option<&str>,
1838+ region: &str,
1839+ credentials: Option<&StorageCredentials>,
1840+) -> ObjectStoreConfig {
1841+ let endpoint = endpoint.unwrap_or_default().to_string();
1842+ // Static credentials come from the managed control plane when present,
1843+ // else the `AWS_*` env the node already carries. Without this,
1844+ // `build_store` sees empty keys and object_store falls back to the
1845+ // instance credential provider, which off-EC2 sends unsigned requests (R2
1846+ // answers "404 page not found").
1847+ let env = |key: &str| std::env::var(key).ok().filter(|value| !value.is_empty());
1848+ let access_key_id = credentials
1849+ .map(|c| c.access_key_id.clone())
1850+ .filter(|value| !value.is_empty())
1851+ .or_else(|| env("AWS_ACCESS_KEY_ID"))
1852+ .unwrap_or_default();
1853+ let secret_access_key = credentials
1854+ .map(|c| c.secret_access_key.clone())
1855+ .filter(|value| !value.is_empty())
1856+ .or_else(|| env("AWS_SECRET_ACCESS_KEY"))
1857+ .unwrap_or_default();
1858+ // Temporary R2/STS credentials require the session token, or signing fails.
1859+ let session_token = credentials
1860+ .and_then(|c| c.session_token.clone())
1861+ .filter(|value| !value.is_empty())
1862+ .or_else(|| env("AWS_SESSION_TOKEN"))
1863+ .unwrap_or_default();
1864+ ObjectStoreConfig {
1865+ bucket: bucket.to_string(),
1866+ path: String::new(),
1867+ region: region.to_string(),
1868+ // A custom endpoint (R2/MinIO) uses path-style addressing, matching
1869+ // `ObjectStoreConfig::from_url`'s default for non-AWS hosts.
1870+ force_path_style: !endpoint.is_empty(),
1871+ endpoint,
1872+ access_key_id,
1873+ secret_access_key,
1874+ session_token,
1875+ skip_verify: false,
1876+ part_size: 0,
1877+ timestamp_metadata_key: TimestampMetadataKey::default(),
1878+ }
1879+}
1880+
1881+fn production_ltx_host() -> LtxHost {
1882+ execution_domain_ltx_host()
1883+}
1884+
1885+#[cfg(all(test, celld_internal_tests))]
1886+fn deterministic_ltx_host() -> LtxHost {
1887+ execution_domain_ltx_host().with_compaction_input_drop(|| {
1888+ asyncrt::sabotage_active(crate::host_services::EngineSabotage::DropCompactionInput)
1889+ })
1890+}
1891+
1892+fn execution_domain_ltx_host() -> LtxHost {
1893+ let filesystem = asyncrt::fs();
1894+ let age_filesystem = filesystem.clone();
1895+ let read_filesystem = filesystem.clone();
1896+ LtxHost::new(
1897+ asyncrt::wall_ms,
1898+ move |path| file_age(age_filesystem.as_ref(), path),
1899+ move |path| {
1900+ let filesystem = read_filesystem.clone();
1901+ async move {
1902+ asyncrt::blocking(move || filesystem.read(&path))
1903+ .await
1904+ .map_err(|error| std::io::Error::other(error.to_string()))?
1905+ }
1906+ },
1907+ |job| async move {
1908+ asyncrt::blocking(job)
1909+ .await
1910+ .map_err(|error| HostTaskError::new(error.to_string()))
1911+ },
1912+ )
1913+ .with_filesystem(filesystem)
1914+}
1915+
1916+fn file_age(filesystem: &dyn celld_ltx::FileSystem, path: &Path) -> std::io::Result<Duration> {
1917+ let modified = filesystem.metadata(path)?.modified_unix_millis;
1918+ Ok(Duration::from_millis(
1919+ asyncrt::wall_ms().saturating_sub(modified).max(0) as u64,
1920+ ))
11041921 }
addedcrates/celld/machine.rs+151−0View file
@@ -1,0 +1,151 @@
1+// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2+
3+#![warn(clippy::disallowed_macros)]
4+
5+//! What the process can learn about where it is running.
6+//!
7+//! Two kinds of fact, both read once at startup or sampled on a timer:
8+//! the environment the operator set, and the machine underneath — memory,
9+//! CPU ticks, page size — which is per-platform and therefore duplicated
10+//! behind `cfg` for each one.
11+use celld_logic::OwnershipOnEvict;
12+use rand::RngCore as _;
13+
14+pub fn random_node_session_id() -> String {
15+ let mut bytes = [0_u8; 16];
16+ crate::asyncrt::rng("session").fill_bytes(&mut bytes);
17+ let suffix = bytes
18+ .iter()
19+ .map(|byte| format!("{byte:02x}"))
20+ .collect::<String>();
21+ format!("node_{suffix}")
22+}
23+
24+pub fn random_peer_key() -> [u8; 32] {
25+ let mut key = [0_u8; 32];
26+ crate::asyncrt::rng("peer_key").fill_bytes(&mut key);
27+ key
28+}
29+
30+pub fn random_process_generation() -> String {
31+ let mut generation = [0_u8; 32];
32+ crate::asyncrt::rng("generation").fill_bytes(&mut generation);
33+ generation
34+ .iter()
35+ .map(|byte| format!("{byte:02x}"))
36+ .collect()
37+}
38+
39+/// Watermarks from celld's public environment contract.
40+/// `CELLD_PRESSURE_OWNERSHIP`: `release` (the default) or `sticky`.
41+/// The lease lifetime, as the capacity listing needs it to decide which node
42+/// records are stale enough to skip reading. Same variable and default the
43+/// lease itself uses.
44+/// Concurrent outbound WebSockets one cell may hold
45+/// (`CELLD_MAX_OUTBOUND_WEBSOCKETS`).
46+pub const DEFAULT_MAX_OUTBOUND_WEBSOCKETS: usize = 32;
47+
48+pub const DEFAULT_LOCAL_CACHE_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
49+
50+/// Matches the fleet and ownership-store clients. Long enough to survive a
51+/// slow but live peer, short enough that a stale address does not hold a
52+/// request for the kernel's own connect timeout.
53+pub const PEER_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);
54+
55+pub fn lease_ttl_ms_from_environment() -> u64 {
56+ crate::env_vars::positive_or("CELLD_TTL_MS", 10_000).expect("validated CELLD_TTL_MS")
57+}
58+
59+pub fn ownership_on_evict_from_environment() -> anyhow::Result<OwnershipOnEvict> {
60+ match std::env::var("CELLD_PRESSURE_OWNERSHIP") {
61+ Err(_) => Ok(OwnershipOnEvict::Release),
62+ Ok(value) => match value.trim() {
63+ "release" => Ok(OwnershipOnEvict::Release),
64+ "sticky" => Ok(OwnershipOnEvict::Sticky),
65+ other => Err(anyhow::anyhow!(
66+ "CELLD_PRESSURE_OWNERSHIP must be `release` or `sticky`, not `{other}`"
67+ )),
68+ },
69+ }
70+}
71+
72+/// Total memory this process may use: the cgroup limit when one applies
73+/// (containers), the machine otherwise.
74+#[cfg(target_os = "linux")]
75+#[allow(clippy::disallowed_methods)] // cgroup and `/proc` files describe the host.
76+fn total_memory_bytes() -> Option<u64> {
77+ for path in [
78+ "/sys/fs/cgroup/memory.max",
79+ "/sys/fs/cgroup/memory/memory.limit_in_bytes",
80+ ] {
81+ if let Ok(raw) = std::fs::read_to_string(path) {
82+ if let Ok(limit) = raw.trim().parse::<u64>() {
83+ // cgroup v1 reports "no limit" as a huge page-rounded
84+ // number; anything at or above 1 PiB means unlimited.
85+ if limit < (1 << 50) {
86+ return Some(limit);
87+ }
88+ }
89+ }
90+ }
91+ let meminfo = std::fs::read_to_string("/proc/meminfo").ok()?;
92+ let kb = meminfo
93+ .lines()
94+ .find(|line| line.starts_with("MemTotal:"))?
95+ .split_whitespace()
96+ .nth(1)?
97+ .parse::<u64>()
98+ .ok()?;
99+ Some(kb.saturating_mul(1024))
100+}
101+
102+#[cfg(target_os = "macos")]
103+fn total_memory_bytes() -> Option<u64> {
104+ let mut size: u64 = 0;
105+ let mut len = std::mem::size_of::<u64>();
106+ let ok = unsafe {
107+ libc::sysctlbyname(
108+ c"hw.memsize".as_ptr(),
109+ (&raw mut size).cast(),
110+ &mut len,
111+ std::ptr::null_mut(),
112+ 0,
113+ )
114+ };
115+ (ok == 0 && size > 0).then_some(size)
116+}
117+
118+#[cfg(not(any(target_os = "linux", target_os = "macos")))]
119+fn total_memory_bytes() -> Option<u64> {
120+ None
121+}
122+
123+pub fn pressure_config_from_environment() -> anyhow::Result<celld_logic::pressure::PressureConfig> {
124+ // Residency is a hard cap (`CELLD_MAX_RESIDENT_CELLS` -> `Config::max_resident`),
125+ // enforced at admission -- not a pressure watermark, so it is not built here.
126+ // Memory shedding is on by default: a node that runs into its memory ceiling
127+ // must give cells back, not be killed. The arithmetic lives in the core,
128+ // where it is tested; the shell supplies only the two facts it can read.
129+ let config = celld_logic::pressure::PressureConfig::from_limits(
130+ total_memory_bytes(),
131+ crate::env_vars::optional::<u64>("CELLD_MAX_RSS_MB")?,
132+ );
133+ if config.ceiling_above_cap() {
134+ tracing::warn!(
135+ high_bytes = config.high_bytes,
136+ rss_hard_bytes = config.rss_hard_bytes,
137+ "CELLD_MAX_RSS_MB is at or above the absolute cap, so the node \
138+ decides on its resident set size and cannot recover from allocator \
139+ retention alone"
140+ );
141+ }
142+ Ok(config)
143+}
144+
145+pub fn local_cache_max_bytes_from_environment() -> anyhow::Result<Option<u64>> {
146+ let bytes = crate::env_vars::with_default(
147+ "CELLD_LOCAL_CACHE_MAX_BYTES",
148+ DEFAULT_LOCAL_CACHE_MAX_BYTES,
149+ )?;
150+ Ok((bytes > 0).then_some(bytes))
151+}
modifiedcrates/celld/main.rs+3206−5093View file
@@ -1,5098 +1,3211 @@
11 // Copyright 2026 Deno Land Inc. Apache-2.0 license.
22
3-//! Runnable celld vertical slice.
4-//!
5-//! One actor serializes every event through `celld-logic`; the actor polls its
6-//! mailbox, timers, and in-flight effect futures together. This is the
7-//! execution shape required for monotonic lease ticks to fence the node even
8-//! when a storage operation remains hung, without spawning a task per effect.
9-
10-use anyhow::Context as _;
11-use base64::Engine as _;
12-use celld::assets::AssetResolver;
13-use celld::fleet;
14-use celld::js::{
15- ArmGate, AssetCallReq, Compat, DoCallReq, HttpResponse, RpcCallReq, SvcCallReq, SvcRpcReq,
16- WorkerConfigOptions, WsOut,
17-};
18-use celld::ownership_store::{now_ms, BucketOwnership};
19-use celld::peer_auth::{self, PeerAuth};
20-use celld::runtime::{CohostedWorker, Replication, RuntimeFetch, RuntimeManager, RuntimeOptions};
21-use celld_logic::{
22- on_event, CasGuard, CasOutcome, Config, Effect, Event, Failure, LeaseCasOutcome, NodeLeaseMode,
23- NodeLeaseRecord, NodeLeaseSpec, OpId, OwnerRecord, OwnershipOnEvict, Phase, RequestError,
24- Route, State, StopCause, Timer, WebSocketKind, WorkerRoute,
25-};
26-use futures_util::stream::{FuturesUnordered, StreamExt};
27-use http_body_util::combinators::UnsyncBoxBody;
28-use http_body_util::{BodyExt, Full, StreamBody};
29-use hyper::body::{Bytes, Frame, Incoming};
30-use hyper::server::conn::http1;
31-use hyper::service::service_fn;
32-use hyper::{Request, Response, StatusCode};
33-use hyper_util::rt::TokioIo;
34-use rand::RngCore;
35-use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
36-use std::convert::Infallible;
37-use std::future::Future;
38-use std::pin::Pin;
39-use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
40-use std::sync::Arc;
41-use std::time::Instant;
42-use tokio::sync::{mpsc, oneshot, watch, Mutex};
43-use tokio_util::time::{delay_queue, DelayQueue};
44-
45-// glibc's malloc serializes its arenas behind futexes, and under load the
46-// sixteen worker threads spent up to half a millisecond blocked per
47-// acquisition. On a 16-core host jemalloc measured 20% more hello-world
48-// throughput than glibc (mimalloc 11%), and returned the ~7% of the machine
49-// that arena-lock sleeps reported as idle.
50-#[global_allocator]
51-static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
52-
53-/// Process-wide request identities shared by the HTTP shell and the actor.
54-/// The shell allocates an identity before it submits a cold route, so dropping
55-/// that route can cancel the exact core request without waiting for routing to
56-/// finish first.
57-static NEXT_CORE_REQUEST: AtomicU64 = AtomicU64::new(1);
58-
59-/// Let an admitted HTTP request finish, then close the transport even when a
60-/// response stream or a client keep-alive does not settle. The semantic drain
61-/// continues after this bound, so durability and resident activity still use
62-/// the complete shutdown grace.
63-const CONNECTION_DRAIN_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
64-
65-/// The lossy stdout writer's flush handle. Every exit path uses
66-/// `std::process::exit`, which skips destructors — but the last lines before
67-/// an exit are the fence forensics, exactly the lines that must survive.
68-static LOG_GUARD: std::sync::Mutex<Option<tracing_appender::non_blocking::WorkerGuard>> =
69- std::sync::Mutex::new(None);
70-
71-fn exit_flushed(code: i32) -> ! {
72- drop(LOG_GUARD.lock().unwrap().take());
73- std::process::exit(code);
74-}
75-
76-fn next_core_request() -> u64 {
77- NEXT_CORE_REQUEST.fetch_add(1, Ordering::Relaxed)
78-}
79-
80-#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
81-enum TimerSlot {
82- NodeLeaseRenew,
83- NodeLeaseFence,
84- CellAlarm(String),
85- /// Keyed by operation, deliberately. Every other timer here coalesces
86- /// because only its newest arming matters; a deadline is the opposite --
87- /// each watches a different outstanding operation, and a shared slot
88- /// would let arming one silently cancel another, leaving every activation
89- /// but the most recent with nothing watching it.
90- OperationDeadline(OpId),
91-}
92-
93-impl TimerSlot {
94- fn of(timer: &Timer) -> Self {
95- match timer {
96- Timer::NodeLeaseRenew { .. } => Self::NodeLeaseRenew,
97- Timer::NodeLeaseFence { .. } => Self::NodeLeaseFence,
98- Timer::CellAlarm { cell, .. } => Self::CellAlarm(cell.clone()),
99- Timer::OperationDeadline { op } => Self::OperationDeadline(*op),
100- }
101- }
102-}
103-
104-struct MemoryOwnership {
105- node: String,
106- owners: BTreeMap<String, OwnerRecord>,
107- leases: BTreeMap<String, NodeLeaseRecord>,
108- next_etag: u64,
109-}
110-
111-#[derive(Clone)]
112-enum Ownership {
113- Memory(Arc<Mutex<MemoryOwnership>>),
114- Bucket(Arc<BucketOwnership>),
115-}
116-
117-impl Ownership {
118- async fn read_owner(&self, cell: &str) -> Result<Option<OwnerRecord>, Failure> {
119- match self {
120- Self::Memory(memory) => Ok(memory.lock().await.owners.get(cell).cloned()),
121- Self::Bucket(bucket) => bucket.read_owner(cell).await.map_err(|error| {
122- eprintln!("celld ownership read failed: {error:#}");
123- Failure::Definite
124- }),
125- }
126- }
127-
128- async fn read_node_lease(&self, owner: &str) -> Result<Option<NodeLeaseRecord>, Failure> {
129- match self {
130- Self::Memory(memory) => Ok(memory.lock().await.leases.get(owner).cloned()),
131- Self::Bucket(bucket) => bucket.read_node_lease(owner).await.map_err(|error| {
132- eprintln!("celld node lease read failed: {error:#}");
133- Failure::Definite
134- }),
135- }
136- }
137-
138- async fn read_capacity_peers(&self) -> Result<Vec<celld_logic::CapacityPeer>, Failure> {
139- match self {
140- // The in-memory adapter is a single-node development mode. It has
141- // no external membership enumeration to offer.
142- Self::Memory(_) => Ok(Vec::new()),
143- Self::Bucket(bucket) => bucket.read_capacity_peers().await.map_err(|error| {
144- eprintln!("celld capacity peer read failed: {error:#}");
145- Failure::Definite
146- }),
147- }
148- }
149-
150- async fn read_self_node_lease(&self, node: &str) -> Result<Option<NodeLeaseRecord>, Failure> {
151- match self {
152- Self::Memory(memory) => Ok(memory.lock().await.leases.get(node).cloned()),
153- Self::Bucket(bucket) => bucket.read_self_node_lease(node).await.map_err(|error| {
154- eprintln!("celld self node lease read failed: {error:#}");
155- Failure::Definite
156- }),
157- }
158- }
159-
160- async fn cas_owner(
161- &self,
162- cell: &str,
163- guard: CasGuard,
164- epoch: u64,
165- ) -> Result<CasOutcome, Failure> {
166- match self {
167- Self::Memory(memory) => {
168- let mut memory = memory.lock().await;
169- let allowed = match guard {
170- CasGuard::Absent => !memory.owners.contains_key(cell),
171- CasGuard::Match(expected) => memory
172- .owners
173- .get(cell)
174- .is_some_and(|owner| owner.etag == expected),
175- };
176- if allowed {
177- let etag = format!("e{}", memory.next_etag);
178- memory.next_etag += 1;
179- let node = memory.node.clone();
180- memory.owners.insert(
181- cell.into(),
182- OwnerRecord {
183- node: Some(node),
184- epoch,
185- etag,
186- },
187- );
188- }
189- Ok(if allowed {
190- CasOutcome::Applied
191- } else {
192- CasOutcome::Rejected
193- })
194- }
195- Self::Bucket(bucket) => bucket.cas_owner(cell, guard, epoch).await.map_err(|error| {
196- // Any transport or 5xx failure may have happened after the
197- // store committed. The core reconciles by reading the owner
198- // again.
199- eprintln!("celld ownership CAS ambiguous: {error:#}");
200- Failure::Ambiguous
201- }),
202- }
203- }
204-
205- async fn release_owner(&self, cell: &str, epoch: u64) -> Result<CasOutcome, Failure> {
206- match self {
207- Self::Memory(memory) => {
208- let mut memory = memory.lock().await;
209- let node = memory.node.clone();
210- let releasable = memory.owners.get(cell).is_some_and(|owner| {
211- owner.node.as_deref() == Some(node.as_str()) && owner.epoch == epoch
212- });
213- if releasable {
214- let etag = format!("e{}", memory.next_etag);
215- memory.next_etag += 1;
216- memory.owners.insert(
217- cell.into(),
218- OwnerRecord {
219- node: None,
220- epoch,
221- etag,
222- },
223- );
224- }
225- Ok(if releasable {
226- CasOutcome::Applied
227- } else {
228- CasOutcome::Rejected
229- })
230- }
231- // A release that may or may not have committed needs no
232- // reconciliation: the record either still names this node, and the
233- // next eviction releases it again, or it does not, and the cell is
234- // already free. Either way nothing is owed.
235- Self::Bucket(bucket) => bucket.release_owner(cell, epoch).await.map_err(|error| {
236- eprintln!("celld ownership release failed: {error:#}");
237- Failure::Definite
238- }),
239- }
240- }
241-
242- async fn cas_node_lease(
243- &self,
244- guard: CasGuard,
245- mut record: NodeLeaseRecord,
246- ) -> Result<LeaseCasOutcome, Failure> {
247- match self {
248- Self::Memory(memory) => {
249- let mut memory = memory.lock().await;
250- let current = memory.leases.get(&record.node);
251- let allowed = match guard {
252- CasGuard::Absent => current.is_none(),
253- CasGuard::Match(expected) => {
254- current.is_some_and(|lease| lease.etag == expected)
255- }
256- };
257- if !allowed {
258- return Ok(LeaseCasOutcome::Rejected);
259- }
260- let etag = format!("e{}", memory.next_etag);
261- memory.next_etag += 1;
262- record.etag = etag.clone();
263- memory.leases.insert(record.node.clone(), record);
264- Ok(LeaseCasOutcome::Applied { etag })
265- }
266- Self::Bucket(bucket) => bucket
267- .cas_node_lease(guard, &record)
268- .await
269- .map_err(|error| {
270- eprintln!("celld node-lease CAS ambiguous: {error:#}");
271- Failure::Ambiguous
272- }),
273- }
274- }
275-
276- fn name(&self) -> &'static str {
277- match self {
278- Self::Memory(_) => "memory",
279- Self::Bucket(bucket) => bucket.storage_scheme(),
280- }
281- }
282-}
283-
284-enum Message {
285- /// A periodic resource sample. The measuring is the shell's job; every
286- /// decision that follows belongs to the core.
287- SampleLoad,
288- /// Stop new internal routing while a clean same-node reload drains. The
289- /// request shell has already stopped admission; this closes wake and
290- /// service paths that do not pass through the HTTP gate.
291- BeginPreserve,
292- /// Graceful shutdown: release every owned cell's record so peers take
293- /// over immediately. The release writes run as effects inside the
294- /// shutdown drain window, and the drain waits for them to complete —
295- /// bounded by the drain deadline, so a wedged store still cannot hold
296- /// the exit hostage.
297- ReleaseAll,
298- /// Has the shutdown handoff finished? True once no cell occupies
299- /// capacity: nothing resident, restoring, or mid-eviction. The drain
300- /// loop polls this to exit as soon as the handoff completes instead of
301- /// sitting out the full drain window.
302- Drained {
303- reply: oneshot::Sender<DrainStatus>,
304- },
305- Request {
306- request: u64,
307- cell: String,
308- capacity_handoff: bool,
309- reply: oneshot::Sender<Result<Routed, RequestError>>,
310- },
311- /// A caller disappeared before routing finished. The request identity is
312- /// allocated by the shell, so the actor can remove it from either cold
313- /// admission queue immediately.
314- CancelRoute {
315- request: u64,
316- },
317- WorkerRequest {
318- reply: oneshot::Sender<WorkerRouted>,
319- },
320- ActivityFinished {
321- request: u64,
322- // The activity drop also observes the cell's alarm. Folded in here so a
323- // request's completion costs the serial core one message, not two — the
324- // hot path for every routed DO call.
325- cell: String,
326- alarm_at_ms: Option<i64>,
327- alarm_covered: bool,
328- },
329- /// A local request whose handler advanced its cell's committed-write
330- /// position wrote: open the output gate and hold the response until durable.
331- GateWrite {
332- request: u64,
333- position: u64,
334- reply: oneshot::Sender<Result<(), RequestError>>,
335- },
336- /// A `webSocketMessage` finished; hand its captured outbound frames to the
337- /// cell's output gate. `write_position` present means the handler wrote, so
338- /// the frames are held behind that write until it is durable; absent means
339- /// flush them (behind any earlier still-pending write, else immediately).
340- WsOutput {
341- request: u64,
342- scope: String,
343- frames: Vec<(u64, WsOut)>,
344- write_position: Option<u64>,
345- reply: oneshot::Sender<()>,
346- },
347- WebSocketOpened {
348- cell: String,
349- websocket: u64,
350- kind: WebSocketKind,
351- reply: oneshot::Sender<bool>,
352- },
353- WebSocketClosed {
354- cell: String,
355- websocket: u64,
356- },
357- AlarmObserved {
358- cell: String,
359- at_ms: Option<i64>,
360- covered: bool,
361- },
362- WakeHint {
363- cell: String,
364- },
365- Evict {
366- cell: String,
367- reply: oneshot::Sender<()>,
368- },
369- InvalidateRemote {
370- cell: String,
371- node: String,
372- epoch: u64,
373- reply: oneshot::Sender<()>,
374- },
375- Snapshot {
376- reply: oneshot::Sender<String>,
377- },
378- Health {
379- reply: oneshot::Sender<bool>,
380- },
381- Presence {
382- reply: oneshot::Sender<celld_logic::PresenceSnapshot>,
383- },
384-}
385-
386-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
387-enum ShutdownMode {
388- /// The logical node is leaving. Release every owner record so another
389- /// node can take over without waiting for the node lease to expire.
390- Handoff,
391- /// The same logical node will start again at the same address. Drain the
392- /// request shell, but keep ownership and the local replica cache intact.
393- Preserve,
394-}
395-
396-struct Routed {
397- request: u64,
398- route: Route,
399-}
400-
401-#[derive(Clone, Copy, Default)]
402-struct DrainStatus {
403- occupied: usize,
404- activating: usize,
405- evicting: usize,
406- /// Ownership releases still in flight. A handoff drain waits for zero:
407- /// a released cell leaves `occupied` before its record write commits,
408- /// so exiting on occupancy alone can abort the write mid-flight and
409- /// leave a record the successor waits out the node lease for.
410- releasing: usize,
411-}
412-
413-// Read only by the orphaned `worker_route`; removed with the landing-cell
414-// machinery in the DO-dispatch refactor ([[designs/do-fast-path]]).
415-#[allow(dead_code)]
416-struct WorkerRouted {
417- request: u64,
418- route: Option<WorkerRoute>,
419-}
420-
421-/// Worker requests owned by one HTTP connection. Hyper can finish a failed
422-/// connection without dropping its service future, so the connection also
423-/// aborts these requests explicitly when its transport ends.
424-#[derive(Clone, Default)]
425-struct ConnectionWorkerRequests(Arc<std::sync::Mutex<BTreeSet<celld::js::RequestId>>>);
426-
427-impl ConnectionWorkerRequests {
428- fn register(&self, request: celld::js::RequestId) {
429- self.0.lock().unwrap().insert(request);
430- }
431-
432- fn complete(&self, request: celld::js::RequestId) {
433- self.0.lock().unwrap().remove(&request);
434- }
435-
436- fn abort_all(&self) {
437- let requests = std::mem::take(&mut *self.0.lock().unwrap());
438- for request in requests {
439- celld::js::abort_request(request);
440- }
441- }
442-}
443-
444-struct IngressAbortGuard {
445- request: Option<celld::js::RequestId>,
446- connection: ConnectionWorkerRequests,
447-}
448-
449-impl IngressAbortGuard {
450- fn new(request: celld::js::RequestId, connection: ConnectionWorkerRequests) -> Self {
451- connection.register(request);
452- Self {
453- request: Some(request),
454- connection,
455- }
456- }
457-
458- fn disarm(&mut self) {
459- if let Some(request) = self.request.take() {
460- self.connection.complete(request);
461- }
462- }
463-}
464-
465-/// Cancels a core route when the future awaiting it is dropped. A normal
466-/// route disarms the guard before returning its result.
467-struct RouteCancelGuard {
468- tx: mpsc::UnboundedSender<Message>,
469- request: Option<u64>,
470-}
471-
472-impl RouteCancelGuard {
473- fn new(tx: mpsc::UnboundedSender<Message>, request: u64) -> Self {
474- Self {
475- tx,
476- request: Some(request),
477- }
478- }
479-
480- fn disarm(&mut self) {
481- self.request = None;
482- }
483-}
484-
485-impl Drop for RouteCancelGuard {
486- fn drop(&mut self) {
487- if let Some(request) = self.request {
488- let _ = self.tx.send(Message::CancelRoute { request });
489- }
490- }
491-}
492-
493-impl Drop for IngressAbortGuard {
494- fn drop(&mut self) {
495- if let Some(request) = self.request.take() {
496- self.connection.complete(request);
497- celld::js::abort_request(request);
498- }
499- }
500-}
501-
502-struct ActivityGuard {
503- tx: mpsc::UnboundedSender<Message>,
504- request: u64,
505- runtime: Option<RuntimeManager>,
506- cell: String,
507-}
508-
509-impl Drop for ActivityGuard {
510- fn drop(&mut self) {
511- // Read and send under the registry lock (`with_alarm`), so this
512- // report cannot carry an alarm older than one the reporter already
513- // sent — a stale fold arriving later would unarm the core and
514- // delete the wake entry (`alarm_reporter` documents the ordering).
515- let send = |tx: &mpsc::UnboundedSender<Message>, at_ms, covered| {
516- let _ = tx.send(Message::ActivityFinished {
517- request: self.request,
518- cell: self.cell.clone(),
519- alarm_at_ms: at_ms,
520- alarm_covered: covered,
521- });
522- };
523- match &self.runtime {
524- Some(runtime) => runtime.with_alarm(&self.cell, |at_ms| {
525- let covered = runtime.alarm_covered(&self.cell, at_ms);
526- send(&self.tx, at_ms, covered);
527- }),
528- None => send(&self.tx, None, false),
529- }
530- }
531-}
532-
533-#[derive(Clone, Copy)]
534-enum RouteStage {
535- OwnershipRead,
536- NodeLeaseLookup,
537- CapacityLookup,
538- OwnershipAcquire,
539- Restore,
540- IsolateStartup,
541- RegistryInsert,
542-}
543-
544-struct EffectTiming {
545- cell: String,
546- stage: RouteStage,
547- elapsed_us: u64,
548-}
549-
550-struct CompletedEffect {
551- event: Event,
552- timing: Option<EffectTiming>,
553-}
554-
555-impl CompletedEffect {
556- fn plain(event: Event) -> Self {
557- Self {
558- event,
559- timing: None,
560- }
561- }
562-
563- fn timed(event: Event, cell: String, stage: RouteStage, started: Instant) -> Self {
564- Self {
565- event,
566- timing: Some(EffectTiming {
567- cell,
568- stage,
569- elapsed_us: started.elapsed().as_micros() as u64,
570- }),
571- }
572- }
573-}
574-
575-struct CellRouteTiming {
576- started: Instant,
577- activation_started: bool,
578- capacity_wait_started: Option<Instant>,
579- latch_wait_us: u64,
580- ownership_read_us: u64,
581- node_lease_lookup_us: u64,
582- capacity_lookup_us: u64,
583- capacity_wait_us: u64,
584- activation_slot_wait_us: u64,
585- lease_permit_us: u64,
586- ownership_acquire_us: u64,
587- replica_discovery_us: u64,
588- restore_us: u64,
589- isolate_startup_us: u64,
590- registry_insert_us: u64,
591- fresh: Option<bool>,
592-}
593-
594-impl CellRouteTiming {
595- fn new() -> Self {
596- Self {
597- started: Instant::now(),
598- activation_started: false,
599- capacity_wait_started: None,
600- latch_wait_us: 0,
601- ownership_read_us: 0,
602- node_lease_lookup_us: 0,
603- capacity_lookup_us: 0,
604- capacity_wait_us: 0,
605- activation_slot_wait_us: 0,
606- lease_permit_us: 0,
607- ownership_acquire_us: 0,
608- replica_discovery_us: 0,
609- restore_us: 0,
610- isolate_startup_us: 0,
611- registry_insert_us: 0,
612- fresh: None,
613- }
614- }
615-
616- fn effect_started(&mut self) {
617- if !self.activation_started {
618- self.activation_started = true;
619- self.activation_slot_wait_us = self.started.elapsed().as_micros() as u64;
620- }
621- if let Some(started) = self.capacity_wait_started.take() {
622- self.capacity_wait_us = self
623- .capacity_wait_us
624- .saturating_add(started.elapsed().as_micros() as u64);
625- }
626- }
627-
628- fn record(&mut self, stage: RouteStage, elapsed_us: u64) {
629- let field = match stage {
630- RouteStage::OwnershipRead => &mut self.ownership_read_us,
631- RouteStage::NodeLeaseLookup => &mut self.node_lease_lookup_us,
632- RouteStage::CapacityLookup => &mut self.capacity_lookup_us,
633- RouteStage::OwnershipAcquire => &mut self.ownership_acquire_us,
634- RouteStage::Restore => &mut self.restore_us,
635- RouteStage::IsolateStartup => &mut self.isolate_startup_us,
636- RouteStage::RegistryInsert => &mut self.registry_insert_us,
637- };
638- *field = field.saturating_add(elapsed_us);
639- }
640-}
641-
642-type EffectFuture = Pin<Box<dyn Future<Output = CompletedEffect> + Send>>;
643-type ConnectionFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
644-type DoCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
645-type AssetCallFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
646-type WebSocketFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
647-type CachePruneFuture = Pin<
648- Box<dyn Future<Output = (u64, Result<(usize, usize, u64), tokio::task::JoinError>)> + Send>,
649->;
650-
651-#[derive(Clone)]
652-struct AppHandle {
653- tx: mpsc::UnboundedSender<Message>,
654- runtime: Option<RuntimeManager>,
655- assets: Arc<HashMap<String, AssetResolver>>,
656- asset_script: Option<Arc<str>>,
657- peer_http: reqwest::Client,
658- peer_auth: Arc<PeerAuth>,
659- advertise: String,
660- websockets: mpsc::UnboundedSender<WebSocketFuture>,
661- /// Whether the RPO=0 output gate is armed: hold a local write's response
662- /// until its cell is proven durable. On by default; set `CELLD_OUTPUT_GATE=0`
663- /// to acknowledge writes without proving them durable. The core and its DST
664- /// are unconditional.
665- output_gate: bool,
666- /// Concurrent outbound WebSockets one cell may hold, for the refusal
667- /// message; the core enforces it.
668- max_outbound_websockets: usize,
669- /// Set the instant a graceful shutdown begins, so `/__celld/health` reports
670- /// unhealthy and a load balancer stops routing here before teardown.
671- draining: Arc<std::sync::atomic::AtomicBool>,
672- /// Whether forwarded scheme and host headers can set `request.url`.
673- /// The default is false because a direct client controls both headers.
674- trust_forwarded_headers: bool,
675-}
676-
677-impl AppHandle {
678- async fn request(&self, cell: String) -> Result<Routed, RequestError> {
679- self.request_with_mode(cell, false).await
680- }
681-
682- async fn capacity_request(&self, cell: String) -> Result<Routed, RequestError> {
683- self.request_with_mode(cell, true).await
684- }
685-
686- async fn request_with_mode(
687- &self,
688- cell: String,
689- capacity_handoff: bool,
690- ) -> Result<Routed, RequestError> {
691- let request = next_core_request();
692- let (reply, receive) = oneshot::channel();
693- if self
694- .tx
695- .send(Message::Request {
696- request,
697- cell,
698- capacity_handoff,
699- reply,
700- })
701- .is_err()
702- {
703- return Err(RequestError::NodeFenced);
704- }
705- let mut cancel = RouteCancelGuard::new(self.tx.clone(), request);
706- let result = receive.await.unwrap_or(Err(RequestError::NodeFenced));
707- cancel.disarm();
708- result
709- }
710-
711- // Orphaned by the always-pool Worker entry below. The whole landing-cell
712- // machinery (this, `Message::WorkerRequest`, `WorkerRouted`,
713- // `fetch_worker_on_cell`, `CellJob::WorkerFetch`, the logic `worker_request`,
714- // and the inline co-hosted-write gate) is removed together in the DO-dispatch
715- // refactor ([[designs/do-fast-path]]) so the RPO=0 co-hosted path is reworked
716- // coherently rather than unpicked here.
717- #[allow(dead_code)]
718- async fn worker_route(&self) -> anyhow::Result<WorkerRouted> {
719- let (reply, receive) = oneshot::channel();
720- self.tx
721- .send(Message::WorkerRequest { reply })
722- .map_err(|_| anyhow::anyhow!("core stopped before Worker routing"))?;
723- receive
724- .await
725- .context("core stopped while routing Worker request")
726- }
727-
728- async fn fetch_worker(
729- &self,
730- url: String,
731- method: String,
732- body: Vec<u8>,
733- headers: Vec<(String, String)>,
734- connection: ConnectionWorkerRequests,
735- ) -> anyhow::Result<HttpResponse> {
736- let runtime = self
737- .runtime
738- .as_ref()
739- .ok_or_else(|| anyhow::anyhow!("Worker runtime unavailable"))?;
740- // Admission happens in the runtime, against the pool that actually
741- // holds the requests. It used to be duplicated here against an empty
742- // `PoolLoad` — a snapshot with no isolates and no affiliations, which
743- // could only ever answer "yes" once pressure stopped refusing
744- // outright. A decision made against a fake reading is not a fast path.
745- let js_request = celld::js::next_request_id();
746- // The Worker entry is stateless — run it in the pool, always. Routing it
747- // to a "landing cell" existed only to make an `env.NS.get(id)` call
748- // resolve inline; but a cell runs one fetch at a time, so under any real
749- // concurrency the entry can't be on the cell it calls, and the routing
750- // round-trip is paid for nothing — on top of the DO call's own routing.
751- // A DO call reaches its owning cell (with fencing and the output gate) on
752- // the host path, so one routing round-trip per request, never two.
753- let mut abort = IngressAbortGuard::new(js_request, connection);
754- let result = runtime
755- .fetch_worker_pool(url, method, body, headers, js_request)
756- .await;
757- abort.disarm();
758- result
759- }
760-
761- fn activity(&self, request: u64, cell: String) -> ActivityGuard {
762- ActivityGuard {
763- tx: self.tx.clone(),
764- request,
765- runtime: self.runtime.clone(),
766- cell,
767- }
768- }
769-
770- /// The output gate. The caller invokes this only for a request whose
771- /// handler advanced the cell's committed position, so the response is held
772- /// until the core proves the cell durable; `Ok(())` releases it, `Err`
773- /// fails it. Called before the activity guard drops, so the request stays
774- /// pinned across the wait.
775- async fn gate_write(&self, request: u64, position: u64) -> Result<(), RequestError> {
776- let (reply, receive) = oneshot::channel();
777- if self
778- .tx
779- .send(Message::GateWrite {
780- request,
781- position,
782- reply,
783- })
784- .is_err()
785- {
786- return Err(RequestError::NodeFenced);
787- }
788- receive.await.unwrap_or(Err(RequestError::NodeFenced))
789- }
790-
791- /// Hand a finished `webSocketMessage`'s frames to the cell's output gate.
792- /// Awaited so the request stays pinned until the actor has registered the
793- /// gate (the core reads the still-active request when it opens); frames flush
794- /// or fail asynchronously as durability resolves, not here.
795- async fn ws_output(
796- &self,
797- request: u64,
798- scope: String,
799- frames: Vec<(u64, WsOut)>,
800- write_position: Option<u64>,
801- ) {
802- let (reply, receive) = oneshot::channel();
803- if self
804- .tx
805- .send(Message::WsOutput {
806- request,
807- scope,
808- frames,
809- write_position,
810- reply,
811- })
812- .is_ok()
813- {
814- let _ = receive.await;
815- }
816- }
817-
818- async fn websocket_opened(
819- &self,
820- cell: String,
821- websocket: u64,
822- kind: WebSocketKind,
823- ) -> anyhow::Result<()> {
824- let (reply, receive) = oneshot::channel();
825- self.tx
826- .send(Message::WebSocketOpened {
827- cell,
828- websocket,
829- kind,
830- reply,
831- })
832- .map_err(|_| anyhow::anyhow!("core stopped before WebSocket opened"))?;
833- let held = receive
834- .await
835- .context("core stopped while opening WebSocket")?;
836- anyhow::ensure!(
837- held,
838- "outbound WebSocket refused: a cell may hold at most {}, and a node \
839- may pin at most {}% of its residency ceiling",
840- self.max_outbound_websockets,
841- celld_logic::pressure::MAX_OUTBOUND_PIN_PERCENT,
842- );
843- Ok(())
844- }
845-
846- fn websocket_closed(&self, cell: String, websocket: u64) {
847- let _ = self.tx.send(Message::WebSocketClosed { cell, websocket });
848- }
849-
850- async fn evict(&self, cell: String) {
851- let (reply, receive) = oneshot::channel();
852- if self.tx.send(Message::Evict { cell, reply }).is_ok() {
853- let _ = receive.await;
854- }
855- }
856-
857- async fn invalidate_remote(&self, cell: String, node: String, epoch: u64) {
858- let (reply, receive) = oneshot::channel();
859- if self
860- .tx
861- .send(Message::InvalidateRemote {
862- cell,
863- node,
864- epoch,
865- reply,
866- })
867- .is_ok()
868- {
869- let _ = receive.await;
870- }
871- }
872-
873- async fn snapshot(&self) -> String {
874- let (reply, receive) = oneshot::channel();
875- if self.tx.send(Message::Snapshot { reply }).is_err() {
876- return "{\"error\":\"actor_stopped\"}".into();
877- }
878- receive
879- .await
880- .unwrap_or_else(|_| "{\"error\":\"actor_stopped\"}".into())
881- }
882-
883- fn is_draining(&self) -> bool {
884- self.draining.load(std::sync::atomic::Ordering::Relaxed)
885- }
886-
887- /// A dead actor has nothing left to hand off, so channel failure
888- /// reports drained rather than wedging shutdown.
889- async fn drain_status(&self) -> DrainStatus {
890- let (reply, receive) = oneshot::channel();
891- if self.tx.send(Message::Drained { reply }).is_err() {
892- return DrainStatus::default();
893- }
894- receive.await.unwrap_or_default()
895- }
896-
897- async fn healthy(&self) -> bool {
898- let (reply, receive) = oneshot::channel();
899- if self.tx.send(Message::Health { reply }).is_err() {
900- return false;
901- }
902- receive.await.unwrap_or(false)
903- }
904-
905- async fn presence(&self) -> Option<celld_logic::PresenceSnapshot> {
906- let (reply, receive) = oneshot::channel();
907- self.tx.send(Message::Presence { reply }).ok()?;
908- receive.await.ok()
909- }
910-}
911-
912-/// One cell's WebSocket output gate: an ordered queue of write barriers.
913-#[derive(Default)]
914-struct WsGate {
915- barriers: VecDeque<WsBarrier>,
916-}
917-
918-/// A gated write and the outbound frames held behind it. `settled` is `None`
919-/// while the write's durability is unproven, `Some(true)` once proven (its
920-/// frames may flush when it reaches the front), `Some(false)` on failure (the
921-/// gate breaks). Frames from later non-writing messages accrete onto the
922-/// newest barrier's `frames`, so they never overtake the write they trail.
923-struct WsBarrier {
924- request: u64,
925- settled: Option<bool>,
926- frames: Vec<(u64, WsOut)>,
927-}
928-
929-struct Actor {
930- state: State,
931- ownership: Ownership,
932- runtime: Option<RuntimeManager>,
933- region: String,
934- pending: BTreeMap<u64, oneshot::Sender<Result<Routed, RequestError>>>,
935- request_cells: BTreeMap<u64, String>,
936- route_timings: BTreeMap<String, CellRouteTiming>,
937- pending_workers: BTreeMap<u64, oneshot::Sender<WorkerRouted>>,
938- eviction_waiters: BTreeMap<String, Vec<oneshot::Sender<()>>>,
939- durability_waiters: BTreeMap<u64, (String, Vec<oneshot::Sender<()>>)>,
940- eviction_stops: BTreeMap<u64, Vec<oneshot::Sender<()>>>,
941- /// Local write responses held open by the output gate, keyed by request,
942- /// released when the core emits `ReleaseResponse`.
943- gated_responses: BTreeMap<u64, oneshot::Sender<Result<(), RequestError>>>,
944- /// Per-cell WebSocket output gate: a FIFO of write barriers, each holding
945- /// the outbound frames produced up to it. The front drains in write order as
946- /// durability proves, so no client ever sees a frame that trails an
947- /// unproven write (the Cloudflare per-object output gate).
948- ws_gates: BTreeMap<String, WsGate>,
949- /// Gated `webSocketMessage` requests, mapping each to its cell so a
950- /// `ReleaseResponse` routes to the WebSocket gate rather than an HTTP reply.
951- ws_gated: BTreeMap<u64, String>,
952- published: BTreeSet<String>,
953- fail_publish_once: bool,
954- publishes: u64,
955- stops: u64,
956- lease_spec: NodeLeaseSpec,
957- /// Whether to re-check every core invariant after every event.
958- ///
959- /// The check is a full scan of the cell table, so its cost grows with
960- /// residency: roughly 800us per event at ten thousand resident cells,
961- /// which would cap a busy node at about a thousand events a second in
962- /// assertion code alone. It is a model-checking assertion, and the place
963- /// it earns its keep is simulation, which can afford to run it after
964- /// every event over far more schedules than production will ever see.
965- /// Debug builds keep it. Release builds rely on the deterministic model,
966- /// because this full-table scan is too expensive for production traffic.
967- validate_invariants: bool,
968- /// Carries the previous CPU tick reading; a rate needs two samples.
969- load_sampler: ProcessLoadSampler,
970- /// The counters peers rank this node by, when there is a bucket to
971- /// publish them to.
972- live_load: Option<Arc<celld::ownership_store::LiveLoad>>,
973- /// The shed reason last reported to the log, so a latch that holds for
974- /// minutes is reported once rather than on every sample.
975- logged_shed_reason: Option<&'static str>,
976- started_at: Instant,
977- fence: mpsc::UnboundedSender<i32>,
978- timers: DelayQueue<Timer>,
979- timer_keys: BTreeMap<TimerSlot, delay_queue::Key>,
980- preserving: bool,
981-}
982-
983-struct AdmissionLimits {
984- resident: usize,
985- activations: usize,
986- evictions: usize,
987- releases: usize,
988-}
989-
990-struct ActorIdentity {
991- node: String,
992- advertise: String,
993- region: String,
994- managed: bool,
995-}
996-
997-impl Actor {
998- async fn from_environment(
999- limits: AdmissionLimits,
1000- fail_publish_once: bool,
1001- fence: mpsc::UnboundedSender<i32>,
1002- runtime: Option<RuntimeManager>,
1003- ownership: Option<Ownership>,
1004- identity: ActorIdentity,
1005- resume_generation: Option<String>,
1006- ) -> anyhow::Result<Self> {
1007- let ActorIdentity {
1008- node,
1009- advertise,
1010- region,
1011- managed,
1012- } = identity;
1013- let ownership = if let Some(ownership) = ownership {
1014- ownership
1015- } else {
1016- Ownership::Memory(Arc::new(Mutex::new(MemoryOwnership {
1017- node: node.clone(),
1018- owners: BTreeMap::new(),
1019- leases: BTreeMap::new(),
1020- next_etag: 1,
1021- })))
1022- };
1023- let live_load = match &ownership {
1024- Ownership::Bucket(bucket) => Some(bucket.live()),
1025- Ownership::Memory(_) => None,
1026- };
1027- if let Some(live) = &live_load {
1028- celld::ownership_store::set_node_load(live.clone());
1029- }
1030- let process_generation = match &ownership {
1031- Ownership::Bucket(bucket) => bucket
1032- .process_generation()
1033- .map(str::to_owned)
1034- .unwrap_or_else(random_process_generation),
1035- Ownership::Memory(_) => random_process_generation(),
1036- };
1037- let ttl_ms = celld::env_vars::positive_or("CELLD_TTL_MS", 10_000)?;
1038- let lease_mode_value = celld::env_vars::value("CELLD_LAZY_NODE_LEASE")?;
1039- let lease_mode = match lease_mode_value.as_deref() {
1040- Some("lazy") => NodeLeaseMode::Lazy,
1041- Some("shadow") => NodeLeaseMode::Shadow,
1042- Some("continuous") | None => NodeLeaseMode::Continuous,
1043- Some(value) => anyhow::bail!(
1044- "CELLD_LAZY_NODE_LEASE must be continuous, lazy, or shadow, not {value:?}"
1045- ),
1046- };
1047- let lease_linger_ms = celld::env_vars::with_default(
1048- "CELLD_LEASE_LINGER_MS",
1049- if managed { 0 } else { ttl_ms },
1050- )?;
1051- let lease_spec = NodeLeaseSpec {
1052- // Startup has already resolved the environment and CLI settings
1053- // into this validated internal address. Reading the environment
1054- // again would let CELLD_ADVERTISE override a later CLI option and
1055- // publish an address that the bound listener did not validate.
1056- addr: advertise,
1057- peer_protocol: peer_auth::PROTOCOL_VERSION,
1058- generation: std::env::var("CELLD_TEST_GENERATION").unwrap_or(process_generation),
1059- resume_generation,
1060- ttl_ms,
1061- mode: lease_mode,
1062- linger_ms: lease_linger_ms,
1063- };
1064- Ok(Self {
1065- state: State::new(
1066- node,
1067- Config {
1068- max_resident: limits.resident,
1069- max_activations: limits.activations,
1070- max_evictions: limits.evictions,
1071- max_releases: limits.releases,
1072- alarm_resident_ms: celld::wake::resident_ms().max(0) as u64,
1073- require_node_lease: true,
1074- peer_protocol: celld::peer_auth::PROTOCOL_VERSION,
1075- operation_deadline_ms: Some(celld::env_vars::positive_or(
1076- "CELLD_OPERATION_DEADLINE_MS",
1077- DEFAULT_OPERATION_DEADLINE_MS,
1078- )?),
1079- idle_evict_ms: celld::env_vars::positive::<u64>("CELLD_IDLE_EVICT_S")?
1080- .map(|seconds| seconds.saturating_mul(1_000)),
1081- pressure: pressure_config_from_environment()?,
1082- max_outbound_websockets: celld::env_vars::positive_or(
1083- "CELLD_MAX_OUTBOUND_WEBSOCKETS",
1084- DEFAULT_MAX_OUTBOUND_WEBSOCKETS,
1085- )?,
1086- ownership_on_evict: match &ownership {
1087- // Releasing a cell says "any node may take this
1088- // one", which is only true if some other node could
1089- // restore it. Without a bucket the sole copy is this
1090- // node's disk, keyed to an epoch a re-acquire will
1091- // step past, so releasing would lose the cell.
1092- Ownership::Memory(_) => OwnershipOnEvict::Sticky,
1093- Ownership::Bucket(_) => ownership_on_evict_from_environment()?,
1094- },
1095- },
1096- ),
1097- ownership,
1098- runtime,
1099- region,
1100- pending: BTreeMap::new(),
1101- request_cells: BTreeMap::new(),
1102- route_timings: BTreeMap::new(),
1103- pending_workers: BTreeMap::new(),
1104- eviction_waiters: BTreeMap::new(),
1105- durability_waiters: BTreeMap::new(),
1106- gated_responses: BTreeMap::new(),
1107- ws_gates: BTreeMap::new(),
1108- ws_gated: BTreeMap::new(),
1109- eviction_stops: BTreeMap::new(),
1110- published: BTreeSet::new(),
1111- fail_publish_once,
1112- publishes: 0,
1113- stops: 0,
1114- lease_spec,
1115- live_load,
1116- logged_shed_reason: None,
1117- load_sampler: ProcessLoadSampler::default(),
1118- validate_invariants: cfg!(debug_assertions),
1119- started_at: Instant::now(),
1120- fence,
1121- timers: DelayQueue::new(),
1122- timer_keys: BTreeMap::new(),
1123- preserving: false,
1124- })
1125- }
1126-
1127- async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Message>) {
1128- let mut in_flight = FuturesUnordered::new();
1129- self.drive(
1130- Event::StartNodeLease {
1131- now_ms: now_ms(),
1132- spec: self.lease_spec.clone(),
1133- },
1134- &mut in_flight,
1135- );
1136- loop {
1137- tokio::select! {
1138- message = rx.recv() => {
1139- let Some(message) = message else {
1140- break;
1141- };
1142- self.handle_message(message, &mut in_flight);
1143- }
1144- Some(completed) = in_flight.next(), if !in_flight.is_empty() => {
1145- let route_cell = completed
1146- .timing
1147- .as_ref()
1148- .map(|timing| timing.cell.clone());
1149- if let Some(timing) = completed.timing {
1150- self.record_effect_timing(timing);
1151- }
1152- self.drive(completed.event, &mut in_flight);
1153- if let Some(cell) = route_cell {
1154- self.observe_capacity_wait(&cell);
1155- }
1156- }
1157- Some(expired) = self.timers.next(), if !self.timers.is_empty() => {
1158- let timer = expired.into_inner();
1159- self.timer_keys.remove(&TimerSlot::of(&timer));
1160- if self.preserving && matches!(timer, Timer::CellAlarm { .. }) {
1161- continue;
1162- }
1163- self.drive(Event::TimerFired {
1164- timer,
1165- now_ms: now_ms(),
1166- now_mono_ms: self.started_at.elapsed().as_millis() as u64,
1167- }, &mut in_flight);
1168- }
1169- }
1170- }
1171- }
1172-
1173- fn schedule_timer(&mut self, timer: Timer, at_mono_ms: u64) {
1174- let slot = TimerSlot::of(&timer);
1175- let displaced = self.timer_keys.remove(&slot);
1176- // Displacing is the point for the coalescing slots and a bug for the
1177- // per-operation ones: two live deadlines sharing a slot means one
1178- // operation is no longer watched, which is invisible until something
1179- // hangs forever in production.
1180- debug_assert!(
1181- displaced.is_none() || !matches!(slot, TimerSlot::OperationDeadline(_)),
1182- "an operation deadline displaced another: {slot:?}"
1183- );
1184- if let Some(key) = displaced {
1185- self.timers.remove(&key);
1186- }
1187- let delay = std::time::Duration::from_millis(
1188- at_mono_ms.saturating_sub(self.started_at.elapsed().as_millis() as u64),
1189- );
1190- let key = self.timers.insert(timer, delay);
1191- self.timer_keys.insert(slot, key);
1192- }
1193-
1194- fn handle_message(&mut self, message: Message, in_flight: &mut FuturesUnordered<EffectFuture>) {
1195- match message {
1196- Message::BeginPreserve => {
1197- self.preserving = true;
1198- self.drive(Event::BeginPreserve, in_flight);
1199- }
1200- Message::Request { reply, .. } if self.preserving => {
1201- let _ = reply.send(Err(RequestError::NodeFenced));
1202- }
1203- Message::Request {
1204- request,
1205- cell,
1206- capacity_handoff,
1207- reply,
1208- } => {
1209- let retired_durability = match self.state.phase(&cell) {
1210- Some(Phase::EnsuringDurability { op, .. }) => Some(*op),
1211- _ => None,
1212- };
1213- self.pending.insert(request, reply);
1214- self.begin_route_if_cold(&cell);
1215- self.request_cells.insert(request, cell.clone());
1216- self.drive(
1217- if capacity_handoff {
1218- Event::CapacityRequestAt {
1219- request,
1220- cell: cell.clone(),
1221- now_ms: now_ms(),
1222- now_mono_ms: self.started_at.elapsed().as_millis() as u64,
1223- }
1224- } else {
1225- Event::RequestAt {
1226- request,
1227- cell: cell.clone(),
1228- now_ms: now_ms(),
1229- now_mono_ms: self.started_at.elapsed().as_millis() as u64,
1230- }
1231- },
1232- in_flight,
1233- );
1234- self.observe_capacity_wait(&cell);
1235- if let Some(op) = retired_durability {
1236- if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
1237- for waiter in waiters {
1238- let _ = waiter.send(());
1239- }
1240- }
1241- }
1242- }
1243- Message::CancelRoute { request } => {
1244- self.pending.remove(&request);
1245- if let Some(cell) = self.request_cells.remove(&request) {
1246- self.finish_route(&cell, "cancelled", "caller_disconnected", None);
1247- }
1248- self.drive(Event::Cancel { request }, in_flight);
1249- }
1250- Message::WorkerRequest { reply } if self.preserving => {
1251- let _ = reply.send(WorkerRouted {
1252- request: next_core_request(),
1253- route: None,
1254- });
1255- }
1256- Message::WorkerRequest { reply } => {
1257- let request = next_core_request();
1258- self.pending_workers.insert(request, reply);
1259- self.drive(Event::WorkerRequest { request }, in_flight);
1260- }
1261- Message::ReleaseAll => self.drive(Event::ReleaseAll, in_flight),
1262- Message::Drained { reply } => {
1263- let _ = reply.send(DrainStatus {
1264- occupied: self.state.occupied(),
1265- activating: self.state.activating(),
1266- evicting: self.state.evicting(),
1267- releasing: self.state.releasing(),
1268- });
1269- }
1270- Message::SampleLoad if self.preserving => {}
1271- Message::SampleLoad => {
1272- // Counted once: it is a walk of every cell, and the latch and
1273- // the number peers rank this node by must agree anyway.
1274- let occupied = self.state.occupied();
1275- let cpu = self.load_sampler.sample_cpu_percent_x100();
1276- let memory = celld::memory::sample();
1277- let load = celld_logic::pressure::Load {
1278- resident_cells: occupied,
1279- rss_bytes: memory.rss_bytes,
1280- in_use_bytes: memory.in_use_bytes,
1281- };
1282- let now_mono_ms = self.started_at.elapsed().as_millis() as u64;
1283- self.drive(Event::LoadSampled { load, now_mono_ms }, in_flight);
1284- // Report a change of shed reason once. `rss-hard` is the one
1285- // that needs an operator: it says the resident set size crossed
1286- // the absolute cap, so the allocator is holding memory that
1287- // shedding may not return, and the process is near a kill.
1288- let reason = self.state.shed_reason();
1289- if reason != self.logged_shed_reason {
1290- self.logged_shed_reason = reason;
1291- match reason {
1292- Some(celld_logic::pressure::SHED_RSS_HARD) => tracing::warn!(
1293- rss_bytes = load.rss_bytes,
1294- in_use_bytes = load.in_use_bytes,
1295- "shedding on the absolute resident-set cap: the \
1296- allocator holds memory that shedding cannot return"
1297- ),
1298- Some(reason) => tracing::info!(
1299- reason,
1300- rss_bytes = load.rss_bytes,
1301- in_use_bytes = load.in_use_bytes,
1302- "shedding"
1303- ),
1304- None => tracing::info!("no longer shedding"),
1305- }
1306- }
1307- // Republish what peers rank this node by. The same numbers the
1308- // latch just saw: a node that reports last tick's residency
1309- // attracts work it has already refused.
1310- if let Some(live) = &self.live_load {
1311- live.resident_cells.store(occupied, Ordering::Relaxed);
1312- live.host_websockets
1313- .store(self.state.host_websockets(), Ordering::Relaxed);
1314- live.pressured
1315- .store(self.state.shedding(), Ordering::Relaxed);
1316- live.cpu_percent_x100.store(cpu, Ordering::Relaxed);
1317- live.restoring
1318- .store(self.state.activation_backlog() as u64, Ordering::Relaxed);
1319- }
1320- }
1321- Message::GateWrite {
1322- request,
1323- position,
1324- reply,
1325- } => {
1326- // The dispatch path only asks to gate a request whose handler
1327- // advanced the cell's committed position, so this is always a
1328- // write: hold the response until the core proves it durable.
1329- self.gated_responses.insert(request, reply);
1330- self.drive(Event::Wrote { request, position }, in_flight);
1331- }
1332- Message::WsOutput {
1333- request,
1334- scope,
1335- frames,
1336- write_position,
1337- reply,
1338- } => {
1339- match write_position {
1340- // The handler wrote: open a barrier holding these frames and
1341- // gate on durability. A later `ReleaseResponse` settles it.
1342- Some(position) => {
1343- self.ws_gates
1344- .entry(scope.clone())
1345- .or_default()
1346- .barriers
1347- .push_back(WsBarrier {
1348- request,
1349- settled: None,
1350- frames,
1351- });
1352- self.ws_gated.insert(request, scope);
1353- self.drive(Event::Wrote { request, position }, in_flight);
1354- }
1355- // No write: trail the newest pending write if one is open,
1356- // else the gate is open — flush now.
1357- None => match self.ws_gates.get_mut(&scope) {
1358- Some(gate) if !gate.barriers.is_empty() => {
1359- gate.barriers.back_mut().unwrap().frames.extend(frames);
1360- }
1361- _ => celld::js::ws_emit_batch(frames),
1362- },
1363- }
1364- let _ = reply.send(());
1365- }
1366- Message::ActivityFinished {
1367- request,
1368- cell,
1369- alarm_at_ms,
1370- alarm_covered,
1371- } => {
1372- // Folded from the old AlarmObserved-then-ActivityFinished pair the
1373- // activity drop sent: observe the alarm and release any retired
1374- // durability waiters, then finish the activity — same events, same
1375- // order, one message instead of two.
1376- let retired_durability = match self.state.phase(&cell) {
1377- Some(Phase::EnsuringDurability { op, .. }) => Some(*op),
1378- _ => None,
1379- };
1380- self.drive(
1381- Event::AlarmObserved {
1382- cell,
1383- at_ms: alarm_at_ms,
1384- covered: alarm_covered,
1385- now_ms: now_ms(),
1386- now_mono_ms: self.started_at.elapsed().as_millis() as u64,
1387- },
1388- in_flight,
1389- );
1390- if let Some(op) = retired_durability {
1391- if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
1392- for waiter in waiters {
1393- let _ = waiter.send(());
1394- }
1395- }
1396- }
1397- self.drive(Event::ActivityFinished { request }, in_flight);
1398- }
1399- Message::WebSocketOpened {
1400- cell,
1401- websocket,
1402- kind,
1403- reply,
1404- } => {
1405- self.drive(
1406- Event::WebSocketOpened {
1407- cell: cell.clone(),
1408- websocket,
1409- kind,
1410- },
1411- in_flight,
1412- );
1413- // The core may decline to hold the transport. Say so, rather
1414- // than acknowledging an open and closing the socket a moment
1415- // later: an application that hit a ceiling deserves to be
1416- // told which one, not left watching a socket disappear.
1417- // Only an outbound socket can be declined, and only for a
1418- // cell the core knows: an inbound transport is never refused,
1419- // and reporting one as refused fails opens that succeeded.
1420- let refused = kind == WebSocketKind::Outbound
1421- && !self.state.holds_websocket(&cell, websocket);
1422- let _ = reply.send(!refused);
1423- }
1424- Message::WebSocketClosed { cell, websocket } => {
1425- self.drive(Event::WebSocketClosed { cell, websocket }, in_flight);
1426- }
1427- Message::AlarmObserved {
1428- cell,
1429- at_ms,
1430- covered,
1431- } => {
1432- let retired_durability = match self.state.phase(&cell) {
1433- Some(Phase::EnsuringDurability { op, .. }) => Some(*op),
1434- _ => None,
1435- };
1436- self.drive(
1437- Event::AlarmObserved {
1438- cell,
1439- at_ms,
1440- covered,
1441- now_ms: now_ms(),
1442- now_mono_ms: self.started_at.elapsed().as_millis() as u64,
1443- },
1444- in_flight,
1445- );
1446- if let Some(op) = retired_durability {
1447- if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
1448- for waiter in waiters {
1449- let _ = waiter.send(());
1450- }
1451- }
1452- }
1453- }
1454- Message::WakeHint { .. } if self.preserving => {}
1455- Message::WakeHint { cell } => {
1456- self.drive(
1457- Event::WakeHintAt {
1458- cell,
1459- now_ms: now_ms(),
1460- now_mono_ms: self.started_at.elapsed().as_millis() as u64,
1461- },
1462- in_flight,
1463- );
1464- }
1465- Message::Evict { reply, .. } if self.preserving => {
1466- let _ = reply.send(());
1467- }
1468- Message::Evict { cell, reply } if self.state.is_active(&cell) => {
1469- let _ = reply.send(());
1470- }
1471- Message::Evict { cell, reply } => match self.state.phase(&cell) {
1472- Some(Phase::Resident { .. }) => {
1473- self.eviction_waiters
1474- .entry(cell.clone())
1475- .or_default()
1476- .push(reply);
1477- self.drive(Event::Evict { cell }, in_flight);
1478- }
1479- Some(Phase::EnsuringDurability { op, .. }) => {
1480- self.durability_waiters
1481- .entry(*op)
1482- .or_insert_with(|| (cell, Vec::new()))
1483- .1
1484- .push(reply);
1485- }
1486- Some(Phase::Cleaning {
1487- op,
1488- cause: StopCause::Evict { .. },
1489- ..
1490- }) => {
1491- self.eviction_stops.entry(*op).or_default().push(reply);
1492- }
1493- _ => {
1494- let _ = reply.send(());
1495- }
1496- },
1497- Message::InvalidateRemote {
1498- cell,
1499- node,
1500- epoch,
1501- reply,
1502- } => {
1503- self.drive(Event::InvalidateRemote { cell, node, epoch }, in_flight);
1504- let _ = reply.send(());
1505- }
1506- Message::Snapshot { reply } => {
1507- let _ = reply.send(self.state_json());
1508- }
1509- Message::Health { reply } => {
1510- let _ = reply.send(self.state.ready_to_serve());
1511- }
1512- Message::Presence { reply } => {
1513- let _ = reply.send(self.state.presence_snapshot());
1514- }
1515- }
1516- }
1517-
1518- /// Settle a gated `webSocketMessage`'s durability. On success mark its
1519- /// barrier durable and flush the durable prefix in write order; on failure
1520- /// break the whole cell gate — drop every held frame and reset its sockets,
1521- /// since an unproven write must never leave an acknowledged trace.
1522- fn ws_release(&mut self, request: u64, ok: bool) {
1523- let Some(scope) = self.ws_gated.remove(&request) else {
1524- return;
1525- };
1526- let mut flush = Vec::new();
1527- let broke = {
1528- let Some(gate) = self.ws_gates.get_mut(&scope) else {
1529- return;
1530- };
1531- if let Some(barrier) = gate.barriers.iter_mut().find(|b| b.request == request) {
1532- barrier.settled = Some(ok);
1533- }
1534- if gate.barriers.iter().any(|b| b.settled == Some(false)) {
1535- true
1536- } else {
1537- while gate
1538- .barriers
1539- .front()
1540- .is_some_and(|b| b.settled == Some(true))
1541- {
1542- flush.push(gate.barriers.pop_front().unwrap().frames);
1543- }
1544- false
1545- }
1546- };
1547- if broke {
1548- self.ws_gates.remove(&scope);
1549- self.ws_gated.retain(|_, s| *s != scope);
1550- celld::js::ws_close_scope(&scope, 1011, "durability unproven");
1551- return;
1552- }
1553- for frames in flush {
1554- celld::js::ws_emit_batch(frames);
1555- }
1556- if self
1557- .ws_gates
1558- .get(&scope)
1559- .is_some_and(|g| g.barriers.is_empty())
1560- {
1561- self.ws_gates.remove(&scope);
1562- }
1563- }
1564-
1565- fn drive(&mut self, first: Event, in_flight: &mut FuturesUnordered<EffectFuture>) {
1566- let mut events = VecDeque::from([first]);
1567- while let Some(event) = events.pop_front() {
1568- let durability = match &event {
1569- Event::DurabilityChecked { op, .. } => Some(*op),
1570- // A deadline resolves the same operation the proof would
1571- // have, so it has to release the same waiters. Without this
1572- // the core abandons the eviction and the caller that asked
1573- // for it stays blocked on a proof that is no longer coming.
1574- Event::TimerFired {
1575- timer: Timer::OperationDeadline { op },
1576- ..
1577- } => Some(*op),
1578- _ => None,
1579- };
1580- let stopped = match &event {
1581- Event::RuntimeStopped { op } => Some(*op),
1582- _ => None,
1583- };
1584- let effects = on_event(&mut self.state, event);
1585- if let Some(op) = durability {
1586- if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
1587- let stop = effects.iter().find_map(|effect| match effect {
1588- Effect::StopRuntime {
1589- op,
1590- cause: StopCause::Evict { .. },
1591- ..
1592- } => Some(*op),
1593- _ => None,
1594- });
1595- if let Some(stop) = stop {
1596- self.eviction_stops.entry(stop).or_default().extend(waiters);
1597- } else {
1598- for waiter in waiters {
1599- let _ = waiter.send(());
1600- }
1601- }
1602- }
1603- }
1604- for effect in effects {
1605- self.execute(effect, &mut events, in_flight);
1606- }
1607- if let Some(op) = stopped {
1608- if let Some(waiters) = self.eviction_stops.remove(&op) {
1609- for waiter in waiters {
1610- let _ = waiter.send(());
1611- }
1612- }
1613- }
1614- if self.validate_invariants {
1615- self.state.validate().expect("celld core invariant");
1616- }
1617- }
1618- }
1619-
1620- fn execute(
1621- &mut self,
1622- effect: Effect,
1623- immediate: &mut VecDeque<Event>,
1624- in_flight: &mut FuturesUnordered<EffectFuture>,
1625- ) {
1626- match effect {
1627- Effect::ScheduleTimer { timer, at_mono_ms } => {
1628- self.schedule_timer(timer, at_mono_ms);
1629- }
1630- Effect::ReadSelfNodeLease { op } => {
1631- let ownership = self.ownership.clone();
1632- let node = self.state.node().to_string();
1633- let started_at = self.started_at;
1634- in_flight.push(Box::pin(async move {
1635- let result = ownership.read_self_node_lease(&node).await;
1636- CompletedEffect::plain(Event::SelfNodeLeaseRead {
1637- op,
1638- now_ms: now_ms(),
1639- now_mono_ms: started_at.elapsed().as_millis() as u64,
1640- result,
1641- })
1642- }));
1643- }
1644- Effect::CasNodeLease {
1645- op,
1646- guard,
1647- record,
1648- authority_expires_ms,
1649- } => {
1650- let ownership = self.ownership.clone();
1651- let started_at = self.started_at;
1652- in_flight.push(Box::pin(async move {
1653- let attempt_started = Instant::now();
1654- let node = record.node.clone();
1655- let candidate_expires_ms = record.expires_ms;
1656- // Logged before the CAS: with only the completion line, a
1657- // renewal hung on a storage tail is indistinguishable from
1658- // a timer that never fired (the n6 fence, 2026-08-11).
1659- tracing::info!(
1660- event = "node_lease_attempt_started",
1661- %node,
1662- attempt = if authority_expires_ms.is_some() {
1663- "renew"
1664- } else {
1665- "acquire"
1666- },
1667- prior_authority_headroom_ms = authority_expires_ms
1668- .map(|expires_ms| expires_ms.saturating_sub(now_ms()))
1669- .unwrap_or(0),
1670- "node lease attempt started"
1671- );
1672- // A renewal must return while proven authority remains,
1673- // because only a returned attempt lets the ambiguity
1674- // read-back run before the watchdog. The 10:15Z R2
1675- // brownout fenced 9 nodes whose sole hung attempt was
1676- // still inside the transport's 15 s timeout when the
1677- // 10 s TTL expired. Bound the attempt to half the
1678- // remaining authority (capped, floored) and map timeout
1679- // to Ambiguous — the same conservative outcome a lost
1680- // response already produces, so safety is unchanged.
1681- let result = match authority_expires_ms {
1682- Some(expires_ms) => {
1683- let remaining = expires_ms.saturating_sub(now_ms());
1684- let bound =
1685- std::time::Duration::from_millis((remaining / 2).clamp(250, 2_500));
1686- match tokio::time::timeout(
1687- bound,
1688- ownership.cas_node_lease(guard, record),
1689- )
1690- .await
1691- {
1692- Ok(result) => result,
1693- Err(_) => Err(Failure::Ambiguous),
1694- }
1695- }
1696- None => ownership.cas_node_lease(guard, record).await,
1697- };
1698- let completed_ms = now_ms();
1699- let elapsed_ms = attempt_started.elapsed().as_millis() as u64;
1700- let prior_authority_headroom_ms = authority_expires_ms
1701- .map(|expires_ms| expires_ms.saturating_sub(completed_ms))
1702- .unwrap_or(0);
1703- let candidate_headroom_ms = candidate_expires_ms.saturating_sub(completed_ms);
1704- let attempt = if authority_expires_ms.is_some() {
1705- "renew"
1706- } else {
1707- "acquire"
1708- };
1709- let outcome = match &result {
1710- Ok(LeaseCasOutcome::Applied { .. }) => "applied",
1711- Ok(LeaseCasOutcome::Rejected) => "rejected",
1712- Err(Failure::Ambiguous) => "ambiguous",
1713- Err(Failure::Definite) => "definite_failure",
1714- };
1715- if matches!(&result, Ok(LeaseCasOutcome::Applied { .. })) {
1716- tracing::info!(
1717- event = "node_lease_attempt",
1718- %node,
1719- attempt,
1720- outcome,
1721- elapsed_ms,
1722- prior_authority_headroom_ms,
1723- candidate_headroom_ms,
1724- "node lease attempt completed"
1725- );
1726- } else {
1727- tracing::warn!(
1728- event = "node_lease_attempt",
1729- %node,
1730- attempt,
1731- outcome,
1732- elapsed_ms,
1733- prior_authority_headroom_ms,
1734- candidate_headroom_ms,
1735- "node lease attempt did not apply"
1736- );
1737- }
1738- CompletedEffect::plain(Event::NodeLeaseCasCompleted {
1739- op,
1740- now_mono_ms: started_at.elapsed().as_millis() as u64,
1741- result,
1742- })
1743- }));
1744- }
1745- Effect::ReadLocalCells => {
1746- let runtime = self.runtime.clone();
1747- in_flight.push(Box::pin(async move {
1748- let result = match runtime {
1749- // The host runtime's blocking pool, not a second
1750- // pool on the core's current-thread runtime.
1751- Some(runtime) => celld::asyncrt::op_handle()
1752- .spawn_blocking(move || {
1753- runtime.local_reload_cells().map_err(|error| {
1754- eprintln!("celld local reload scan failed: {error:#}");
1755- Failure::Definite
1756- })
1757- })
1758- .await
1759- .unwrap_or(Err(Failure::Definite)),
1760- None => Err(Failure::Definite),
1761- };
1762- CompletedEffect::plain(Event::LocalCellsRead { result })
1763- }));
1764- }
1765- Effect::ObserveNodeLeaseShadowRelease { sequence } => {
1766- tracing::info!(
1767- event = "node_lease_shadow_release",
1768- node = %self.state.node(),
1769- sequence,
1770- "lazy lease shadow mode would stop renewal"
1771- );
1772- }
1773- Effect::ObserveNodeLeaseReleased => {
1774- tracing::info!(
1775- event = "node_lease_released",
1776- node = %self.state.node(),
1777- "no locally dependent cells; stopping node lease renewal"
1778- );
1779- }
1780- Effect::ReadOwner { op, cell } => {
1781- self.route_effect_started(&cell);
1782- let ownership = self.ownership.clone();
1783- let timing_cell = cell.clone();
1784- in_flight.push(Box::pin(async move {
1785- let started = Instant::now();
1786- let result = ownership.read_owner(&cell).await;
1787- CompletedEffect::timed(
1788- Event::OwnerRead {
1789- op,
1790- now_ms: now_ms(),
1791- result,
1792- },
1793- timing_cell,
1794- RouteStage::OwnershipRead,
1795- started,
1796- )
1797- }));
1798- }
1799- Effect::ReadNodeLease { op, cell, owner } => {
1800- self.route_effect_started(&cell);
1801- let ownership = self.ownership.clone();
1802- let timing_cell = cell;
1803- in_flight.push(Box::pin(async move {
1804- let started = Instant::now();
1805- let result = ownership.read_node_lease(&owner).await;
1806- CompletedEffect::timed(
1807- Event::NodeLeaseRead {
1808- op,
1809- now_ms: now_ms(),
1810- result,
1811- },
1812- timing_cell,
1813- RouteStage::NodeLeaseLookup,
1814- started,
1815- )
1816- }));
1817- }
1818- Effect::ReadCapacityPeers { op, cell } => {
1819- self.route_effect_started(&cell);
1820- let ownership = self.ownership.clone();
1821- let timing_cell = cell;
1822- in_flight.push(Box::pin(async move {
1823- let started = Instant::now();
1824- let result = ownership.read_capacity_peers().await;
1825- CompletedEffect::timed(
1826- Event::CapacityPeersRead {
1827- op,
1828- now_ms: now_ms(),
1829- result,
1830- },
1831- timing_cell,
1832- RouteStage::CapacityLookup,
1833- started,
1834- )
1835- }));
1836- }
1837- Effect::CasOwner {
1838- op,
1839- cell,
1840- guard,
1841- epoch,
1842- takeover,
1843- } => {
1844- self.route_effect_started(&cell);
1845- if let Some(timing) = self.route_timings.get_mut(&cell) {
1846- timing
1847- .fresh
1848- .get_or_insert(!takeover && matches!(guard, CasGuard::Absent));
1849- }
1850- let ownership = self.ownership.clone();
1851- let timing_cell = cell.clone();
1852- in_flight.push(Box::pin(async move {
1853- let started = Instant::now();
1854- let result = ownership.cas_owner(&cell, guard, epoch).await;
1855- CompletedEffect::timed(
1856- Event::OwnerCasCompleted { op, result },
1857- timing_cell,
1858- RouteStage::OwnershipAcquire,
1859- started,
1860- )
1861- }));
1862- }
1863- Effect::ReconcileWakeEntry {
1864- cell,
1865- next_alarm_ms,
1866- } => {
1867- if self.runtime.is_some() {
1868- // An ARMED alarm must always be reconcilable, tracked or
1869- // not: belief can be lost while the alarm stands (a
1870- // failed arm-time PUT, an entry retired under a racing
1871- // arm), and skipping here would mean it is never
1872- // re-asserted — entryless until the alarm fires or the
1873- // cell moves. Gating the CONSUME side on tracking is
1874- // what keeps alarm-less cells op-quiescent: untracked
1875- // with no alarm, there is nothing to delete.
1876- if next_alarm_ms >= 0 || celld::js::wake_entry_tracked(&cell) {
1877- // On the host runtime: this arm runs on the core
1878- // thread, and a bare spawn would schedule the S3
1879- // round trip there too.
1880- celld::asyncrt::op_handle().spawn(async move {
1881- // A consume-delete only ever follows a firing, and
1882- // the FireAlarm path now proves the consuming
1883- // commit durable (and this node still the owner)
1884- // before the core settles the alarm — so by the
1885- // time the core orders this delete, the proof
1886- // already happened. The old sync_refused probe
1887- // asked the same question a second way and was
1888- // wrong more often: it refused for any database
1889- // the replicator never registered, leaving the
1890- // entry to outlive its alarm forever.
1891- celld::js::reconcile_wake_entry(&cell, next_alarm_ms, true).await;
1892- });
1893- }
1894- }
1895- }
1896- Effect::ReleaseOwner { op, cell, epoch } => {
1897- let ownership = self.ownership.clone();
1898- in_flight.push(Box::pin(async move {
1899- let result = ownership.release_owner(&cell, epoch).await;
1900- CompletedEffect::plain(Event::OwnerReleased { op, result })
1901- }));
1902- }
1903- Effect::Restore { op, cell, spec } => {
1904- self.route_effect_started(&cell);
1905- if let Some(runtime) = self.runtime.clone() {
1906- let timing_cell = cell.clone();
1907- // A restore downloads, merges, and fsyncs a whole
1908- // database. Poll it on the host runtime: this future
1909- // lives in `in_flight`, which the core thread drives,
1910- // and the core owns the node lease timer.
1911- let task = celld::asyncrt::op_handle().spawn(async move {
1912- let started = Instant::now();
1913- let result = runtime.restore_cell(&cell, &spec).await.map_err(|error| {
1914- eprintln!("celld restore failed for {cell}: {error:#}");
1915- Failure::Definite
1916- });
1917- CompletedEffect::timed(
1918- Event::RestoreCompleted { op, result },
1919- timing_cell,
1920- RouteStage::Restore,
1921- started,
1922- )
1923- });
1924- in_flight.push(Box::pin(async move {
1925- task.await.expect("restore task panicked")
1926- }));
1927- } else {
1928- self.record_effect_timing(EffectTiming {
1929- cell,
1930- stage: RouteStage::Restore,
1931- elapsed_us: 0,
1932- });
1933- immediate.push_back(Event::RestoreCompleted {
1934- op,
1935- result: Ok(celld_logic::RestoreOutcome {
1936- restored: false,
1937- alarm: None,
1938- }),
1939- });
1940- }
1941- }
1942- Effect::StartRuntime { op, cell, epoch } => {
1943- self.route_effect_started(&cell);
1944- if let Some(runtime) = self.runtime.clone() {
1945- let fresh = self
1946- .route_timings
1947- .get(&cell)
1948- .and_then(|timing| timing.fresh)
1949- .unwrap_or(false);
1950- let timing_cell = cell.clone();
1951- in_flight.push(Box::pin(async move {
1952- let started = Instant::now();
1953- let result = runtime
1954- .start_cell(cell.clone(), epoch, fresh)
1955- .await
1956- .map_err(|error| {
1957- eprintln!("celld runtime start failed for {cell}: {error:#}");
1958- Failure::Definite
1959- });
1960- CompletedEffect::timed(
1961- Event::RuntimeStarted { op, result },
1962- timing_cell,
1963- RouteStage::IsolateStartup,
1964- started,
1965- )
1966- }));
1967- } else {
1968- self.record_effect_timing(EffectTiming {
1969- cell,
1970- stage: RouteStage::IsolateStartup,
1971- elapsed_us: 0,
1972- });
1973- immediate.push_back(Event::RuntimeStarted { op, result: Ok(()) });
1974- }
1975- }
1976- Effect::Publish { op, cell, epoch } => {
1977- self.route_effect_started(&cell);
1978- let publish_started = Instant::now();
1979- self.publishes += 1;
1980- let result = if self.fail_publish_once {
1981- self.fail_publish_once = false;
1982- Err(Failure::Ambiguous)
1983- } else {
1984- self.runtime
1985- .as_ref()
1986- .map_or(Ok(()), |runtime| runtime.publish_cell(&cell, epoch))
1987- .map_err(|error| {
1988- eprintln!("celld runtime publication failed for {cell}: {error:#}");
1989- Failure::Definite
1990- })
1991- };
1992- if result.is_ok() {
1993- self.published.insert(cell.clone());
1994- }
1995- self.record_effect_timing(EffectTiming {
1996- cell: cell.clone(),
1997- stage: RouteStage::RegistryInsert,
1998- elapsed_us: publish_started.elapsed().as_micros() as u64,
1999- });
2000- if result.is_ok() {
2001- let node = self.state.node().to_string();
2002- self.finish_route(&cell, "activated", "", Some((&node, epoch)));
2003- }
2004- immediate.push_back(Event::Published { op, result });
2005- }
2006- Effect::EnsureDurable { op, cell, epoch } => {
2007- let waiters = self.eviction_waiters.remove(&cell).unwrap_or_default();
2008- self.durability_waiters.insert(op, (cell.clone(), waiters));
2009- if let Some(runtime) = self.runtime.clone() {
2010- in_flight.push(Box::pin(async move {
2011- let result = runtime.ensure_durable(&cell, epoch).await.map_err(|error| {
2012- eprintln!(
2013- "celld durability proof failed for {cell} epoch {epoch}: {error:#}"
2014- );
2015- Failure::Ambiguous
2016- });
2017- CompletedEffect::plain(Event::DurabilityChecked { op, result })
2018- }));
2019- } else {
2020- immediate.push_back(Event::DurabilityChecked { op, result: Ok(()) });
2021- }
2022- }
2023- // The output gate: prove the cell durable, then let the core release
2024- // the held write response. Reuses the same recency-proving primitive
2025- // as EnsureDurable — a proof issued after the write covers it.
2026- Effect::AwaitDurable {
2027- op,
2028- cell,
2029- epoch,
2030- position,
2031- } => {
2032- if let Some(runtime) = self.runtime.clone() {
2033- let ownership = self.ownership.clone();
2034- let node = self.state.node().to_string();
2035- in_flight.push(Box::pin(async move {
2036- // The replicator reports the position it actually proved
2037- // durable; the core acks only if it covers this write.
2038- let result = match runtime.await_durable(&cell, epoch, position).await {
2039- // Durable in `e<epoch>/` is not the same as durable.
2040- // If the cell has been taken over, that prefix is
2041- // orphaned: the next owner restores a higher epoch
2042- // and this write is gone. Re-read the ownership
2043- // record before letting anything out.
2044- //
2045- // A read is enough, and is why this is one GET
2046- // rather than a compare-and-swap. If the record
2047- // still names us, no takeover linearised before
2048- // this read; the LTX went up before it; so any
2049- // later takeover restores from a lineage that
2050- // already contains this position.
2051- Ok(durable) => match ownership.read_owner(&cell).await {
2052- Ok(Some(record))
2053- if record.node.as_deref() == Some(node.as_str())
2054- && record.epoch == epoch =>
2055- {
2056- Ok(durable)
2057- }
2058- Ok(record) => {
2059- eprintln!(
2060- "celld output gate: {cell} epoch {epoch} is no longer \
2061- ours (record: {record:?}); refusing to acknowledge a \
2062- write in an orphaned epoch"
2063- );
2064- Err(Failure::Definite)
2065- }
2066- Err(failure) => Err(failure),
2067- },
2068- Err(error) => {
2069- eprintln!(
2070- "celld output-gate durability proof failed for {cell} \
2071- epoch {epoch}: {error:#}"
2072- );
2073- Err(Failure::Ambiguous)
2074- }
2075- };
2076- CompletedEffect::plain(Event::DurableReached { op, result })
2077- }));
2078- } else {
2079- immediate.push_back(Event::DurableReached {
2080- op,
2081- result: Ok(position),
2082- });
2083- }
2084- }
2085- Effect::ReleaseResponse { request, result } => {
2086- if self.ws_gated.contains_key(&request) {
2087- self.ws_release(request, result.is_ok());
2088- } else if let Some(reply) = self.gated_responses.remove(&request) {
2089- let _ = reply.send(result);
2090- }
2091- }
2092- Effect::StopRuntime {
2093- op,
2094- cell,
2095- epoch,
2096- cause,
2097- } => {
2098- self.stops += 1;
2099- let evicting = matches!(cause, StopCause::Evict { .. });
2100- if matches!(cause, StopCause::Fence) {
2101- // A fenced cell's wake entry belongs to whoever takes the
2102- // cell over; a retained local belief would collide with
2103- // the new owner's arm/consume traffic on the same key.
2104- celld::js::forget_wake_entry(&cell);
2105- }
2106- // Handing the cell away makes the local snapshot dead weight;
2107- // keeping it is the whole point of an idle eviction. A
2108- // reset must keep nothing: the local database is precisely
2109- // what could not be proved durable, so the next activation has
2110- // to come from the bucket.
2111- let preserve_local = !matches!(
2112- cause,
2113- StopCause::Evict { rebalance: true } | StopCause::Reset
2114- );
2115- if evicting {
2116- if let Some(live) = &self.live_load {
2117- live.shed_cells.fetch_add(1, Ordering::Relaxed);
2118- }
2119- }
2120- self.published.remove(&cell);
2121- if let Some(runtime) = self.runtime.clone() {
2122- in_flight.push(Box::pin(async move {
2123- runtime
2124- .stop_cell(&cell, epoch, evicting, preserve_local)
2125- .await;
2126- CompletedEffect::plain(Event::RuntimeStopped { op })
2127- }));
2128- } else {
2129- immediate.push_back(Event::RuntimeStopped { op });
2130- }
2131- }
2132- Effect::FireAlarm {
2133- op,
2134- cell,
2135- epoch,
2136- scheduled_ms,
2137- } => {
2138- let started_at = self.started_at;
2139- if let Some(runtime) = self.runtime.clone() {
2140- let ownership = self.ownership.clone();
2141- let node = self.state.node().to_string();
2142- in_flight.push(Box::pin(async move {
2143- let mut result = runtime
2144- .fire_alarm(cell.clone(), scheduled_ms)
2145- .await
2146- .map_err(|error| {
2147- eprintln!("celld alarm dispatch failed: {error:#}");
2148- Failure::Definite
2149- });
2150- // An alarm handler's write is gated like a request's:
2151- // prove the consuming commit durable — and this node
2152- // still the owner — before the core learns the alarm
2153- // settled. The consume-side wake-entry delete the core
2154- // then orders always follows a proven commit, which is
2155- // what lets the shell drop the old sync_refused probe.
2156- // On failure the core re-arms the alarm: at-least-once
2157- // holds and the entry stays discoverable.
2158- if let Ok((_, _, Some(position))) = result {
2159- let proven = match runtime.await_durable(&cell, epoch, position).await {
2160- Ok(_) => match ownership.read_owner(&cell).await {
2161- Ok(Some(record)) => {
2162- record.node.as_deref() == Some(node.as_str())
2163- && record.epoch == epoch
2164- }
2165- _ => false,
2166- },
2167- Err(error) => {
2168- eprintln!(
2169- "celld alarm durability proof failed for \
2170- {cell} epoch {epoch}: {error:#}"
2171- );
2172- false
2173- }
2174- };
2175- if !proven {
2176- result = Err(Failure::Ambiguous);
2177- }
2178- }
2179- CompletedEffect::plain(Event::AlarmFinished {
2180- op,
2181- now_ms: now_ms(),
2182- now_mono_ms: started_at.elapsed().as_millis() as u64,
2183- result: result.map(|(at_ms, covered, _)| (at_ms, covered)),
2184- })
2185- }));
2186- } else {
2187- immediate.push_back(Event::AlarmFinished {
2188- op,
2189- now_ms: now_ms(),
2190- now_mono_ms: started_at.elapsed().as_millis() as u64,
2191- result: Ok((None, true)),
2192- });
2193- }
2194- }
2195- Effect::Complete { request, result } => {
2196- if let Some(cell) = self.request_cells.remove(&request) {
2197- match &result {
2198- Ok(Route::Remote { node, epoch, .. }) => {
2199- self.finish_route(&cell, "remote_owner", "", Some((node, *epoch)));
2200- // The cell lives elsewhere: its wake entry is no
2201- // longer this node's to track, and a stale local
2202- // belief would collide with the owner's own
2203- // arm/consume traffic on the same key.
2204- celld::js::forget_wake_entry(&cell);
2205- }
2206- Ok(Route::Local) => {
2207- self.finish_route(&cell, "resident_after_wait", "", None);
2208- }
2209- Err(error) => {
2210- self.finish_route(
2211- &cell,
2212- "route_error",
2213- request_error_phase(*error),
2214- None,
2215- );
2216- }
2217- }
2218- }
2219- if let Some(reply) = self.pending.remove(&request) {
2220- let local = result == Ok(Route::Local);
2221- if reply
2222- .send(result.map(|route| Routed { request, route }))
2223- .is_err()
2224- && local
2225- {
2226- immediate.push_back(Event::ActivityFinished { request });
2227- }
2228- }
2229- }
2230- Effect::CompleteWorker { request, route } => {
2231- if let Some(op) = route.as_ref().and_then(|route| route.retired_durability) {
2232- if let Some((_, waiters)) = self.durability_waiters.remove(&op) {
2233- for waiter in waiters {
2234- let _ = waiter.send(());
2235- }
2236- }
2237- }
2238- if let Some(reply) = self.pending_workers.remove(&request) {
2239- let reserved = route.is_some();
2240- if reply.send(WorkerRouted { request, route }).is_err() && reserved {
2241- immediate.push_back(Event::ActivityFinished { request });
2242- }
2243- }
2244- }
2245- Effect::CloseWebSocket { cell, websocket } => {
2246- // The core declined to hold this transport. Drop it and tell
2247- // the core it is gone, so the cell is not left believing it
2248- // has a socket the node already closed.
2249- eprintln!(
2250- "celld refused an outbound WebSocket for {cell}: the node's \
2251- outbound pin budget is spent"
2252- );
2253- celld::js::ws_unregister(websocket);
2254- immediate.push_back(Event::WebSocketClosed { cell, websocket });
2255- }
2256- Effect::Halt { code, reason } => {
2257- // Say why before going. Self-fencing is the most drastic thing
2258- // this process does, and an exit code on its own leaves an
2259- // operator to guess between a lease it could not renew, a
2260- // replicator that died, and a crash.
2261- match reason {
2262- celld_logic::HaltReason::NodeLeaseExpired => tracing::warn!(
2263- event = "node_lease_watchdog_fence",
2264- code,
2265- "SELF-FENCE: node lease not renewed within TTL — halting"
2266- ),
2267- }
2268- let _ = self.fence.send(code);
2269- }
2270- }
2271- }
2272-
2273- fn state_json(&self) -> String {
2274- let residents = self
2275- .state
2276- .residents()
2277- .into_iter()
2278- .map(|cell| format!("{cell:?}"))
2279- .collect::<Vec<_>>()
2280- .join(",");
2281- let published = self
2282- .published
2283- .iter()
2284- .map(|cell| format!("{cell:?}"))
2285- .collect::<Vec<_>>()
2286- .join(",");
2287- // Both numbers: a gap between them is memory the allocator kept, which
2288- // no eviction returns. One sample, so they cannot disagree.
2289- let memory = celld::memory::sample();
2290- // `restoring` is a sum, and a node that refuses cells for a quarter of
2291- // an hour needs its parts. `activating` holds a permit and is doing
2292- // work; `activation_waiting` is queued behind the activation ceiling;
2293- // `capacity_waiting` is queued behind residency. The census says where
2294- // every cell is, which `occupied` cannot: it counts residency, so a
2295- // node part-way through thousands of cold starts reports almost none.
2296- // Issue #50 is open because none of this was recorded at the time.
2297- let phases = self
2298- .state
2299- .phase_census()
2300- .into_iter()
2301- .map(|(phase, count)| format!("{phase:?}:{count}"))
2302- .collect::<Vec<_>>()
2303- .join(",");
2304- format!(
2305- "{{\"ownership\":{:?},\"occupied\":{},\"evicting\":{},\"restoring\":{},\"activating\":{},\"activation_waiting\":{},\"capacity_waiting\":{},\"phases\":{{{}}},\"shedding\":{},\"rss_bytes\":{},\"in_use_bytes\":{},\"residents\":[{}],\"published\":[{}],\"publishes\":{},\"stops\":{}}}",
2306- self.ownership.name(),
2307- self.state.occupied(),
2308- self.state.evicting(),
2309- self.state.activation_backlog(),
2310- self.state.activating(),
2311- self.state.activation_waiting().len(),
2312- self.state.waiting().len(),
2313- phases,
2314- self.state
2315- .shed_reason()
2316- .map_or_else(|| "null".to_string(), |reason| format!("{reason:?}")),
2317- memory.rss_bytes,
2318- memory.in_use_bytes,
2319- residents,
2320- published,
2321- self.publishes,
2322- self.stops
2323- )
2324- }
2325-
2326- fn begin_route_if_cold(&mut self, cell: &str) {
2327- if !matches!(
2328- self.state.phase(cell),
2329- Some(Phase::Resident { .. } | Phase::EnsuringDurability { .. } | Phase::Remote { .. })
2330- ) {
2331- self.route_timings
2332- .entry(cell.to_string())
2333- .or_insert_with(CellRouteTiming::new);
2334- }
2335- }
2336-
2337- fn route_effect_started(&mut self, cell: &str) {
2338- if let Some(timing) = self.route_timings.get_mut(cell) {
2339- timing.effect_started();
2340- }
2341- }
2342-
2343- fn observe_capacity_wait(&mut self, cell: &str) {
2344- if matches!(self.state.phase(cell), Some(Phase::WaitingCapacity)) {
2345- if let Some(timing) = self.route_timings.get_mut(cell) {
2346- timing
2347- .capacity_wait_started
2348- .get_or_insert_with(Instant::now);
2349- }
2350- }
2351- }
2352-
2353- fn record_effect_timing(&mut self, completed: EffectTiming) {
2354- if let Some(timing) = self.route_timings.get_mut(&completed.cell) {
2355- timing.record(completed.stage, completed.elapsed_us);
2356- }
2357- }
2358-
2359- fn finish_route(
2360- &mut self,
2361- cell: &str,
2362- outcome: &str,
2363- failure_phase: &str,
2364- owner: Option<(&str, u64)>,
2365- ) {
2366- let Some(mut timing) = self.route_timings.remove(cell) else {
2367- return;
2368- };
2369- if let Some(started) = timing.capacity_wait_started.take() {
2370- timing.capacity_wait_us = timing
2371- .capacity_wait_us
2372- .saturating_add(started.elapsed().as_micros() as u64);
2373- }
2374- let (owner_node, epoch) = owner.unwrap_or(("", 0));
2375- tracing::debug!(
2376- target: "timing",
2377- event = "cell_route_timing",
2378- outcome,
2379- failure_phase,
2380- scope = %cell,
2381- node = %self.state.node(),
2382- region = %self.region,
2383- runtime_version = env!("CARGO_PKG_VERSION"),
2384- owner_node,
2385- epoch,
2386- fresh = timing.fresh.unwrap_or(false),
2387- total_us = timing.started.elapsed().as_micros() as u64,
2388- latch_wait_us = timing.latch_wait_us,
2389- ownership_read_us = timing.ownership_read_us,
2390- node_lease_lookup_us = timing.node_lease_lookup_us,
2391- capacity_lookup_us = timing.capacity_lookup_us,
2392- capacity_wait_us = timing.capacity_wait_us,
2393- activation_slot_wait_us = timing.activation_slot_wait_us,
2394- lease_permit_us = timing.lease_permit_us,
2395- ownership_acquire_us = timing.ownership_acquire_us,
2396- replica_discovery_us = timing.replica_discovery_us,
2397- restore_us = timing.restore_us,
2398- isolate_startup_us = timing.isolate_startup_us,
2399- registry_insert_us = timing.registry_insert_us,
2400- "cell route resolved"
2401- );
2402- }
2403-}
2404-
2405-fn request_error_phase(error: RequestError) -> &'static str {
2406- match error {
2407- RequestError::NodeUnavailable | RequestError::NodeFenced => "node_authority",
2408- RequestError::ResolveFailed | RequestError::PeerIncompatible => "ownership_lookup",
2409- RequestError::CapacityExhausted => "capacity_wait",
2410- RequestError::AcquireFailed => "ownership_acquire",
2411- RequestError::RestoreFailed => "restore",
2412- RequestError::RuntimeFailed => "isolate_startup",
2413- RequestError::PublishFailed => "registry_insert",
2414- RequestError::DurabilityUnproven => "output_gate",
2415- }
2416-}
2417-
2418-type HttpReply = Response<UnsyncBoxBody<Bytes, std::io::Error>>;
2419-
2420-const STALE_ROUTE_HEADER: &str = "x-cells-route-error";
2421-const STALE_ROUTE_VALUE: &str = "stale-owner";
2422-const DURABLE_OBJECT_ROUTING_ERROR_MARKER: &str = "__CELLD_DO_ROUTING_ERROR__:";
2423-
2424-fn owner_unreachable(scope: &str, owner: &str, source: anyhow::Error) -> anyhow::Error {
2425- // Record how the attempt failed, not just that it did. `connect` is the
2426- // one that decides whether a retry is safe -- a request that never left
2427- // this node may be re-sent, a truncated read may not, because the owner
2428- // already ran it. Without these an operator cannot tell an unreachable
2429- // peer from one that answered badly, and neither can a bug report.
2430- let transport = source.downcast_ref::<reqwest::Error>();
2431- let cause = source
2432- .source()
2433- .map(ToString::to_string)
2434- .unwrap_or_else(|| source.to_string());
2435- tracing::warn!(
2436- %scope,
2437- %owner,
2438- error = %source,
2439- %cause,
2440- connect = transport.is_some_and(reqwest::Error::is_connect),
2441- timeout = transport.is_some_and(reqwest::Error::is_timeout),
2442- request = transport.is_some_and(reqwest::Error::is_request),
2443- body = transport.is_some_and(reqwest::Error::is_body),
2444- decode = transport.is_some_and(reqwest::Error::is_decode),
2445- "peer owner unreachable"
2446- );
2447- let detail = serde_json::json!({
2448- "scope": scope,
2449- "owner": owner,
2450- });
2451- source.context(format!("{DURABLE_OBJECT_ROUTING_ERROR_MARKER}{detail}"))
2452-}
2453-
2454-fn response(status: StatusCode, body: impl Into<Bytes>) -> HttpReply {
2455- Response::builder()
2456- .status(status)
2457- .header("content-type", "application/json")
2458- .body(
2459- Full::new(body.into())
2460- .map_err(|never| match never {})
2461- .boxed_unsync(),
2462- )
2463- .expect("static HTTP response")
2464-}
2465-
2466-fn asset_response(response: axum::response::Response) -> HttpReply {
2467- response.map(|body| body.map_err(std::io::Error::other).boxed_unsync())
2468-}
2469-
2470-fn peer_response(mut response: HttpReply) -> HttpReply {
2471- response.headers_mut().insert(
2472- hyper::header::HeaderName::from_static(peer_auth::RESPONSE_VERSION_HEADER),
2473- hyper::header::HeaderValue::from_static(peer_auth::PROTOCOL_VERSION_TEXT),
2474- );
2475- response
2476-}
2477-
2478-fn runtime_response(worker_response: celld::js::HttpResponse) -> HttpReply {
2479- let Ok(status) = StatusCode::from_u16(worker_response.status) else {
2480- return response(StatusCode::INTERNAL_SERVER_ERROR, "invalid Worker status");
2481- };
2482- let mut builder = Response::builder().status(status);
2483- for (name, value) in worker_response.headers {
2484- if matches!(
2485- name.to_ascii_lowercase().as_str(),
2486- "connection" | "content-length" | "transfer-encoding"
2487- ) {
2488- continue;
2489- }
2490- builder = builder.header(name, value);
2491- }
2492- let body = match worker_response.stream {
2493- Some(stream) => {
2494- let chunks = stream.map(|chunk| {
2495- chunk
2496- .map(|bytes| Frame::data(Bytes::from(bytes)))
2497- .map_err(std::io::Error::other)
2498- });
2499- StreamBody::new(chunks).boxed_unsync()
2500- }
2501- None => Full::new(Bytes::from(worker_response.body))
2502- .map_err(|never| match never {})
2503- .boxed_unsync(),
2504- };
2505- builder
2506- .body(body)
2507- .unwrap_or_else(|_| response(StatusCode::INTERNAL_SERVER_ERROR, "invalid Worker headers"))
2508-}
2509-
2510-fn peer_runtime_response(worker_response: celld::js::HttpResponse) -> HttpReply {
2511- let wire_status = if worker_response.status == 101 && worker_response.ws.is_some() {
2512- StatusCode::OK
2513- } else {
2514- let Ok(status) = StatusCode::from_u16(worker_response.status) else {
2515- return peer_response(response(
2516- StatusCode::INTERNAL_SERVER_ERROR,
2517- "invalid Worker status",
2518- ));
2519- };
2520- status
2521- };
2522- let mut builder = Response::builder().status(wire_status);
2523- for (name, value) in worker_response.headers {
2524- if matches!(
2525- name.to_ascii_lowercase().as_str(),
2526- "connection" | "content-length" | "transfer-encoding"
2527- ) {
2528- continue;
2529- }
2530- builder = builder.header(name, value);
2531- }
2532- if let Some(target) = worker_response.ws {
2533- if let Ok(value) = serde_json::to_string(&target) {
2534- builder = builder.header("x-celld-ws-target", value);
2535- }
2536- }
2537- // Say whether this body is streamed. The peer reads an unmarked body
2538- // rather than handing it on, so without this every response looked
2539- // buffered and streaming was off across the hop.
2540- if worker_response.stream.is_some() {
2541- builder = builder.header("x-celld-body-stream", "1");
2542- }
2543- let body = match worker_response.stream {
2544- Some(stream) => {
2545- let stream = stream.map(|chunk| {
2546- chunk
2547- .map(|bytes| Frame::data(Bytes::from(bytes)))
2548- .map_err(std::io::Error::other)
2549- });
2550- StreamBody::new(stream).boxed_unsync()
2551- }
2552- None => Full::new(Bytes::from(worker_response.body))
2553- .map_err(|never| match never {})
2554- .boxed_unsync(),
2555- };
2556- peer_response(builder.body(body).expect("Worker peer response"))
2557-}
2558-
2559-#[derive(Debug)]
2560-struct StalePeerRoute {
2561- scope: String,
2562-}
2563-
2564-impl std::fmt::Display for StalePeerRoute {
2565- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2566- write!(formatter, "peer no longer owns {}", self.scope)
2567- }
2568-}
2569-
2570-impl std::error::Error for StalePeerRoute {}
2571-
2572-#[derive(Debug)]
2573-struct RoutedRequestError(RequestError);
2574-
2575-impl std::fmt::Display for RoutedRequestError {
2576- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2577- write!(formatter, "route failed: {:?}", self.0)
2578- }
2579-}
2580-
2581-impl std::error::Error for RoutedRequestError {}
2582-
2583-fn classify_remote_attempt(error: &anyhow::Error) -> celld_logic::routing::Attempt {
2584- if error.downcast_ref::<StalePeerRoute>().is_some() {
2585- celld_logic::routing::Attempt::NotOwner
2586- } else if error
2587- .downcast_ref::<reqwest::Error>()
2588- .is_some_and(reqwest::Error::is_connect)
2589- {
2590- celld_logic::routing::Attempt::NeverConnected
2591- } else {
2592- celld_logic::routing::Attempt::Ambiguous
2593- }
2594-}
2595-
2596-struct WebSocketRouteTiming {
2597- started: Instant,
2598- route_resolution_us: u64,
2599- dispatch_us: u64,
2600- attempts: u8,
2601-}
2602-
2603-impl WebSocketRouteTiming {
2604- fn emit(
2605- &self,
2606- app: &AppHandle,
2607- scope: &str,
2608- request_id: Option<celld::js::RequestId>,
2609- outcome: &str,
2610- route: &str,
2611- peer_node: &str,
2612- ) {
2613- let request_id = request_id
2614- .map(celld::js::request_id_string)
2615- .unwrap_or_default();
2616- let (node, region) = app
2617- .runtime
2618- .as_ref()
2619- .map_or(("", ""), |runtime| (runtime.node(), runtime.region()));
2620- tracing::debug!(
2621- target: "timing",
2622- event = "websocket_route_timing",
2623- outcome,
2624- route,
2625- peer_node,
2626- scope,
2627- request_id,
2628- node,
2629- region,
2630- runtime_version = env!("CARGO_PKG_VERSION"),
2631- attempts = self.attempts,
2632- total_us = self.started.elapsed().as_micros() as u64,
2633- route_resolution_us = self.route_resolution_us,
2634- dispatch_us = self.dispatch_us,
2635- "WebSocket cell request resolved"
2636- );
2637- }
2638-}
2639-
2640-/// The output gate for the co-hosted (same-isolate) Durable Object fast path.
2641-/// That path runs a resident DO's `fetch` inline, bypassing `dispatch_do_call`;
2642-/// when it writes, the inline handler calls here to hold its response until the
2643-/// cell is durable. Reuses the routed machinery: `request` pins the cell (no
2644-/// eviction mid-wait) and `gate_write` drives the core gate. `Ok` releases the
2645-/// inline response; `Err` breaks the call, as a routed gate failure would.
2646-async fn dispatch_gate(app: AppHandle, req: celld::js::GateReq) {
2647- if !app.output_gate {
2648- let _ = req.reply.send(Ok(()));
2649- return;
2650- }
2651- let routed = match app.request(req.scope.clone()).await {
2652- Ok(routed) => routed,
2653- Err(error) => {
2654- let _ = req.reply.send(Err(error));
2655- return;
2656- }
2657- };
2658- // The guard pins the cell and releases the request on drop, so the else
2659- // branch does not leak the just-acquired request.
2660- let _activity = app.activity(routed.request, req.scope.clone());
2661- let result = if routed.route == Route::Local {
2662- app.gate_write(routed.request, req.position).await
2663- } else {
2664- // The owning isolate should route the cell locally; if it moved off the
2665- // node mid-call, fail closed rather than acknowledge an unproven write.
2666- Err(RequestError::NodeFenced)
2667- };
2668- let _ = req.reply.send(result);
2669-}
2670-
2671-async fn dispatch_do_call(app: AppHandle, call: DoCallReq) {
2672- let DoCallReq {
2673- request_id,
2674- cancel,
2675- deliver_abort_to_handler,
2676- scope,
2677- name,
2678- url,
2679- method,
2680- body,
2681- headers,
2682- reply,
2683- order,
2684- parent,
2685- } = call;
2686- let mut cancel = cancel;
2687- let mut order = order;
2688- let mut websocket_timing = headers
2689- .iter()
2690- .any(|(name, value)| {
2691- name.eq_ignore_ascii_case("upgrade") && value.eq_ignore_ascii_case("websocket")
2692- })
2693- .then(|| WebSocketRouteTiming {
2694- started: Instant::now(),
2695- route_resolution_us: 0,
2696- dispatch_us: 0,
2697- attempts: 0,
2698- });
2699- let operation = async {
2700- let mut dispatcher = celld_logic::routing::Dispatcher::default();
2701- loop {
2702- if let Some(timing) = websocket_timing.as_mut() {
2703- timing.attempts = timing.attempts.saturating_add(1);
2704- }
2705- let route_started = Instant::now();
2706- // A disconnect before routing completes has executed no handler,
2707- // so cancel the core request and release its activation admission.
2708- // Once routing completes, the same signal moves into the local or
2709- // remote dispatch below and aborts work that did start.
2710- let route = app.request(scope.clone());
2711- let routed = if deliver_abort_to_handler {
2712- // Workerd delivers an explicit JavaScript AbortSignal to the
2713- // target request. Resolve the route first, then give the
2714- // already-fired receiver to fetch_cell so the handler sees
2715- // request.signal and its waitUntil work can continue.
2716- route.await
2717- } else {
2718- match cancel.as_mut() {
2719- Some(cancel) => tokio::select! {
2720- routed = route => routed,
2721- _ = cancel => break Err(anyhow::anyhow!("Durable Object call cancelled")),
2722- },
2723- None => route.await,
2724- }
2725- };
2726- let routed = match routed {
2727- Ok(routed) => routed,
2728- Err(error) => {
2729- if let Some(timing) = websocket_timing.as_mut() {
2730- timing.route_resolution_us = timing
2731- .route_resolution_us
2732- .saturating_add(route_started.elapsed().as_micros() as u64);
2733- timing.emit(&app, &scope, request_id, "route_error", "", "");
2734- }
2735- break Err(anyhow::Error::new(RoutedRequestError(error)));
2736- }
2737- };
2738- if let Some(timing) = websocket_timing.as_mut() {
2739- timing.route_resolution_us = timing
2740- .route_resolution_us
2741- .saturating_add(route_started.elapsed().as_micros() as u64);
2742- }
2743- let Routed { request, route } = routed;
2744- let (node, addr, epoch, peer_protocol) = match route {
2745- Route::Local => {
2746- let dispatch_started = Instant::now();
2747- let _activity = app.activity(request, scope.clone());
2748- let result = async {
2749- let runtime = app.runtime.as_ref().context("no cell runtime")?;
2750- let response = runtime
2751- .fetch_cell(
2752- scope.clone(),
2753- name,
2754- RuntimeFetch {
2755- url,
2756- method,
2757- body,
2758- headers,
2759- request_id,
2760- // Moved on the first attempt and gone on
2761- // a retry, which is right: a retry is a
2762- // second delivery of a call whose place
2763- // in the order was already taken.
2764- order: order.take(),
2765- parent,
2766- },
2767- cancel.take(),
2768- )
2769- .await?;
2770- if let Some(target) = &response.ws {
2771- let kind = if celld::js::ws_hibernatable(target.id).unwrap_or(false) {
2772- WebSocketKind::Hibernatable
2773- } else {
2774- WebSocketKind::Regular
2775- };
2776- app.websocket_opened(target.scope.clone(), target.id, kind)
2777- .await?;
2778- }
2779- Ok(response)
2780- }
2781- .await;
2782- // Output gate (RPO=0): a handler that advanced the cell's
2783- // write position has its response held until the core proves
2784- // the cell durable. The request is still pinned (the
2785- // activity guard has not dropped), so it fails rather than
2786- // acknowledges a write the node cannot prove durable.
2787- let result = match result {
2788- Ok(response) => match response.write_position.filter(|_| app.output_gate) {
2789- Some(position) => match app.gate_write(request, position).await {
2790- Ok(()) => Ok(response),
2791- Err(error) => Err(anyhow::Error::new(RoutedRequestError(error))),
2792- },
2793- None => Ok(response),
2794- },
2795- Err(error) => Err(error),
2796- };
2797- if let Some(timing) = websocket_timing.as_mut() {
2798- timing.dispatch_us = timing
2799- .dispatch_us
2800- .saturating_add(dispatch_started.elapsed().as_micros() as u64);
2801- timing.emit(
2802- &app,
2803- &scope,
2804- request_id,
2805- if result.is_ok() { "ok" } else { "error" },
2806- "local",
2807- app.runtime.as_ref().map_or("", RuntimeManager::node),
2808- );
2809- }
2810- break result;
2811- }
2812- Route::Remote {
2813- node,
2814- addr,
2815- epoch,
2816- peer_protocol,
2817- } => (node, addr, epoch, peer_protocol),
2818- };
2819- let dispatch_started = Instant::now();
2820- let remote_call = async {
2821- anyhow::ensure!(
2822- peer_protocol == peer_auth::PROTOCOL_VERSION,
2823- "peer {node} speaks incompatible protocol {peer_protocol}"
2824- );
2825- let encoded = serde_json::json!({
2826- "name": &name,
2827- "url": &url,
2828- "method": &method,
2829- "bodyBase64": base64::engine::general_purpose::STANDARD.encode(&body),
2830- "headers": &headers,
2831- "requestId": request_id.map(celld::js::request_id_string),
2832- "capacityHandoff": epoch == 0,
2833- });
2834- let encoded = serde_json::to_vec(&encoded)?;
2835- let path = format!("/__do/{scope}");
2836- let request = app.peer_auth.sign(
2837- app.peer_http.post(format!("http://{addr}{path}")),
2838- "POST",
2839- &path,
2840- &encoded,
2841- &node,
2842- )?;
2843- let response =
2844- request.body(encoded).send().await.map_err(|error| {
2845- owner_unreachable(&scope, &addr, anyhow::Error::new(error))
2846- })?;
2847- peer_auth::validate_response(response.headers())?;
2848- if response
2849- .headers()
2850- .get(STALE_ROUTE_HEADER)
2851- .is_some_and(|value| value == STALE_ROUTE_VALUE)
2852- {
2853- return Err(owner_unreachable(
2854- &scope,
2855- &addr,
2856- anyhow::Error::new(StalePeerRoute {
2857- scope: scope.clone(),
2858- }),
2859- ));
2860- }
2861- let mut websocket: Option<celld::js::WsTarget> = response
2862- .headers()
2863- .get("x-celld-ws-target")
2864- .and_then(|value| value.to_str().ok())
2865- .and_then(|value| serde_json::from_str(value).ok());
2866- if let Some(target) = websocket.as_mut() {
2867- target.peer_node = Some(node.clone());
2868- target.peer_addr = Some(addr.clone());
2869- target.peer_epoch = Some(epoch);
2870- }
2871- let status = if websocket.is_some() && response.status() == StatusCode::OK {
2872- 101
2873- } else {
2874- response.status().as_u16()
2875- };
2876- let headers = response
2877- .headers()
2878- .iter()
2879- .filter(|(name, _)| {
2880- name.as_str() != "x-celld-ws-target"
2881- && name.as_str() != "x-celld-body-stream"
2882- })
2883- .filter_map(|(name, value)| {
2884- value
2885- .to_str()
2886- .ok()
2887- .map(|value| (name.to_string(), value.to_string()))
2888- })
2889- .collect();
2890- let (body, stream) = if websocket.is_some() {
2891- (Vec::new(), None)
2892- } else {
2893- // Every proxied body streams through, marked or not. The
2894- // owner already ran the request, so a failure mid-body is
2895- // ambiguous and must surface without a redispatch -- and
2896- // streaming makes that structural: the 200 head has gone
2897- // out before the failure is known, a chunk error aborts
2898- // the client's read instead of ending it cleanly, and
2899- // nothing upstream of a sent head can re-send. Buffering
2900- // here was the old shape; it turned a truncated body into
2901- // a whole-response failure after the owner had committed.
2902- (
2903- Vec::new(),
2904- Some(celld::js::reqwest_response_stream(response)),
2905- )
2906- };
2907- Ok(HttpResponse {
2908- status,
2909- headers,
2910- body,
2911- ws: websocket,
2912- stream,
2913- // A proxied remote response wrote on the owner, not here.
2914- write_position: None,
2915- })
2916- };
2917- let remote = match cancel.as_mut() {
2918- Some(cancel) => tokio::select! {
2919- remote = remote_call => remote,
2920- _ = cancel => break Err(anyhow::anyhow!("Durable Object call cancelled")),
2921- },
2922- None => remote_call.await,
2923- };
2924- if let Some(timing) = websocket_timing.as_mut() {
2925- timing.dispatch_us = timing
2926- .dispatch_us
2927- .saturating_add(dispatch_started.elapsed().as_micros() as u64);
2928- }
2929- match remote {
2930- Ok(response) => {
2931- if let Some(timing) = websocket_timing.as_ref() {
2932- timing.emit(&app, &scope, request_id, "ok", "remote", &node);
2933- }
2934- break Ok(response);
2935- }
2936- Err(error) => {
2937- // Epoch zero is a candidate, not an owner. A signed peer
2938- // refusal proves this attempt did not execute and should
2939- // not consume the ordinary one-owner stale-route budget;
2940- // the core excludes that exact load sample before the
2941- // next deterministic placement decision.
2942- let capacity_refused = epoch == 0
2943- && error
2944- .chain()
2945- .any(|cause| cause.downcast_ref::<StalePeerRoute>().is_some());
2946- if capacity_refused {
2947- app.invalidate_remote(scope.clone(), node, epoch).await;
2948- continue;
2949- }
2950- let attempt = classify_remote_attempt(&error);
2951- if dispatcher.redispatch(attempt) {
2952- app.invalidate_remote(scope.clone(), node, epoch).await;
2953- continue;
2954- }
2955- if let Some(timing) = websocket_timing.as_ref() {
2956- timing.emit(&app, &scope, request_id, "error", "remote", &node);
2957- }
2958- break Err(error);
2959- }
2960- }
2961- }
2962- };
2963- let result = operation.await;
2964- let _ = reply.send(result);
2965-}
2966-
2967-async fn dispatch_rpc_call(app: AppHandle, call: RpcCallReq) {
2968- let RpcCallReq {
2969- scope,
2970- name,
2971- method,
2972- args,
2973- reply,
2974- } = call;
2975- let result = async {
2976- let mut dispatcher = celld_logic::routing::Dispatcher::default();
2977- loop {
2978- let Routed { request, route } = app
2979- .request(scope.clone())
2980- .await
2981- .map_err(|error| anyhow::anyhow!("route RPC {scope}: {error:?}"))?;
2982- let (node, addr, epoch, peer_protocol) = match route {
2983- Route::Local => {
2984- let _activity = app.activity(request, scope.clone());
2985- let outcome = app
2986- .runtime
2987- .as_ref()
2988- .context("no cell runtime")?
2989- .rpc(scope, name, method, args)
2990- .await?;
2991- // Output gate (RPO=0): an RPC method that advanced the
2992- // cell's write position has its reply held until the core
2993- // proves the cell durable, exactly as fetch does. The
2994- // activity guard is still alive, so the cell stays pinned
2995- // across the wait.
2996- if let Some(position) = outcome.write_position.filter(|_| app.output_gate) {
2997- app.gate_write(request, position)
2998- .await
2999- .map_err(|error| anyhow::Error::new(RoutedRequestError(error)))?;
3000- }
3001- return Ok(outcome.data);
3002- }
3003- Route::Remote {
3004- node,
3005- addr,
3006- epoch,
3007- peer_protocol,
3008- } => (node, addr, epoch, peer_protocol),
3009- };
3010- anyhow::ensure!(
3011- peer_protocol == peer_auth::PROTOCOL_VERSION,
3012- "peer {node} speaks incompatible protocol {peer_protocol}"
3013- );
3014- let structured = matches!(args, celld::js::RpcData::V8(_));
3015- let envelope = match &args {
3016- celld::js::RpcData::Json(json) => serde_json::json!({
3017- "name": &name,
3018- "method": &method,
3019- "args": serde_json::from_str::<serde_json::Value>(json)
3020- .unwrap_or_else(|_| serde_json::json!([])),
3021- }),
3022- celld::js::RpcData::V8(bytes) => serde_json::json!({
3023- "name": &name,
3024- "method": &method,
3025- "sc": base64::engine::general_purpose::STANDARD.encode(bytes),
3026- }),
3027- };
3028- let encoded = serde_json::to_vec(&envelope)?;
3029- let path = format!("/__rpc/{scope}");
3030- let request = app.peer_auth.sign(
3031- app.peer_http.post(format!("http://{addr}{path}")),
3032- "POST",
3033- &path,
3034- &encoded,
3035- &node,
3036- )?;
3037- let response = request.body(encoded).send().await;
3038- let response = match response {
3039- Ok(response) => response,
3040- Err(error) => {
3041- let attempt = classify_remote_attempt(&anyhow::Error::new(error));
3042- if dispatcher.redispatch(attempt) {
3043- app.invalidate_remote(scope.clone(), node, epoch).await;
3044- continue;
3045- }
3046- return Err(anyhow::anyhow!("remote RPC transport failed"));
3047- }
3048- };
3049- peer_auth::validate_response(response.headers())?;
3050- if response
3051- .headers()
3052- .get(STALE_ROUTE_HEADER)
3053- .is_some_and(|value| value == STALE_ROUTE_VALUE)
3054- {
3055- if dispatcher.redispatch(celld_logic::routing::Attempt::NotOwner) {
3056- app.invalidate_remote(scope.clone(), node, epoch).await;
3057- continue;
3058- }
3059- anyhow::bail!("remote RPC owner was stale");
3060- }
3061- anyhow::ensure!(
3062- response.status().is_success(),
3063- "remote RPC failed with {}",
3064- response.status()
3065- );
3066- return Ok(if structured {
3067- celld::js::RpcData::V8(response.bytes().await?.to_vec())
3068- } else {
3069- celld::js::RpcData::Json(response.text().await?)
3070- });
3071- }
3072- }
3073- .await;
3074- let _ = reply.send(result);
3075-}
3076-
3077-async fn request_payload(
3078- request: Request<Incoming>,
3079- trust_forwarded_headers: bool,
3080-) -> Result<(String, String, Vec<u8>, Vec<(String, String)>), HttpReply> {
3081- let (parts, body) = request.into_parts();
3082- let body = body.collect().await.map_err(|error| {
3083- response(
3084- StatusCode::BAD_REQUEST,
3085- format!("request body failed: {error}"),
3086- )
3087- })?;
3088- let headers = parts
3089- .headers
3090- .iter()
3091- .filter_map(|(name, value)| {
3092- value
3093- .to_str()
3094- .ok()
3095- .map(|value| (name.to_string(), value.to_string()))
3096- })
3097- .collect();
3098- Ok((
3099- request_url(&parts, trust_forwarded_headers),
3100- parts.method.to_string(),
3101- body.to_bytes().to_vec(),
3102- headers,
3103- ))
3104-}
3105-
3106-/// The refusal every path arm gives a cell scope that fails the charset gate.
3107-///
3108-/// A scope taken from a URL segment reaches `db_path`, which joins it under the
3109-/// data directory, and the replication client, which builds a bucket key from
3110-/// it, so a scope carrying its own path segments walks out of both. The gate
3111-/// itself is reified in `celld_logic::cell`, next to the peer-identity gate it
3112-/// mirrors.
3113-fn malformed_scope() -> HttpReply {
3114- response(
3115- StatusCode::BAD_REQUEST,
3116- "{\"error\":\"malformed_cell_scope\"}",
3117- )
3118-}
3119-
3120-/// `request.url` controls application routing and absolute links, so celld
3121-/// does not let an untrusted forwarding header or request-target authority set
3122-/// its scheme or host. The path and query always come from the request target.
3123-/// The host comes from `Host`, and the scheme is `http` because celld does not
3124-/// terminate TLS.
3125-///
3126-/// An operator can set `--trust-forwarded-headers` when a trusted proxy
3127-/// replaces both forwarded headers. The trusted read takes the last value
3128-/// because a proxy can append its value after a client-supplied value.
3129-fn request_url(parts: &hyper::http::request::Parts, trust_forwarded_headers: bool) -> String {
3130- let header = |name: &str, take_last: bool| {
3131- parts
3132- .headers
3133- .get(name)
3134- .and_then(|value| value.to_str().ok())
3135- .and_then(|value| {
3136- if take_last {
3137- value.split(',').next_back()
3138- } else {
3139- value.split(',').next()
3140- }
3141- })
3142- .map(str::trim)
3143- .filter(|value| !value.is_empty())
3144- };
3145- let forwarded = |name: &str| {
3146- trust_forwarded_headers
3147- .then(|| header(name, true))
3148- .flatten()
3149- };
3150- let host = forwarded("x-forwarded-host")
3151- .or_else(|| header("host", false))
3152- .unwrap_or("celld.local");
3153- let scheme = forwarded("x-forwarded-proto").unwrap_or("http");
3154- let path_and_query = parts
3155- .uri
3156- .path_and_query()
3157- .map_or("/", hyper::http::uri::PathAndQuery::as_str);
3158- format!("{scheme}://{host}{path_and_query}")
3159-}
3160-
3161-async fn internal_do(request: Request<Incoming>, app: AppHandle, scope: String) -> HttpReply {
3162- let method = request.method().clone();
3163- let path_and_query = request
3164- .uri()
3165- .path_and_query()
3166- .map_or_else(|| request.uri().path().to_string(), ToString::to_string);
3167- let request_headers = request.headers().clone();
3168- let body = match request.into_body().collect().await {
3169- Ok(body) => body.to_bytes(),
3170- Err(error) => {
3171- return peer_response(response(
3172- StatusCode::BAD_REQUEST,
3173- format!("invalid body: {error}"),
3174- ));
3175- }
3176- };
3177- if let Err(error) = app.peer_auth.verify(
3178- &method,
3179- &path_and_query,
3180- &request_headers,
3181- &body,
3182- app.peer_auth.source(),
3183- ) {
3184- let mut denied = response(error.status(), error.message());
3185- if matches!(error, peer_auth::VerifyError::WrongTarget) {
3186- denied.headers_mut().insert(
3187- hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
3188- hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
3189- );
3190- }
3191- return peer_response(denied);
3192- }
3193- let value: serde_json::Value = match serde_json::from_slice(&body) {
3194- Ok(value) => value,
3195- Err(error) => {
3196- return peer_response(response(
3197- StatusCode::BAD_REQUEST,
3198- format!("invalid JSON: {error}"),
3199- ));
3200- }
3201- };
3202- let url = value
3203- .get("url")
3204- .and_then(serde_json::Value::as_str)
3205- .unwrap_or("http://cell/")
3206- .to_string();
3207- let method = value
3208- .get("method")
3209- .and_then(serde_json::Value::as_str)
3210- .unwrap_or("GET")
3211- .to_string();
3212- let name = value
3213- .get("name")
3214- .and_then(serde_json::Value::as_str)
3215- .map(str::to_string);
3216- let request_body = value
3217- .get("bodyBase64")
3218- .and_then(serde_json::Value::as_str)
3219- .and_then(|body| base64::engine::general_purpose::STANDARD.decode(body).ok())
3220- .unwrap_or_default();
3221- let headers = serde_json::from_value(
3222- value
3223- .get("headers")
3224- .cloned()
3225- .unwrap_or_else(|| serde_json::json!([])),
3226- )
3227- .unwrap_or_default();
3228- let request_id = value
3229- .get("requestId")
3230- .and_then(serde_json::Value::as_str)
3231- .and_then(celld::js::parse_request_id);
3232- let capacity_handoff = value
3233- .get("capacityHandoff")
3234- .and_then(serde_json::Value::as_bool)
3235- .unwrap_or(false);
3236- let routed = if capacity_handoff {
3237- app.capacity_request(scope.clone()).await
3238- } else {
3239- app.request(scope.clone()).await
3240- };
3241- let result = match routed {
3242- Ok(Routed {
3243- request,
3244- route: Route::Local,
3245- }) => {
3246- let _activity = app.activity(request, scope.clone());
3247- let Some(runtime) = &app.runtime else {
3248- return response(StatusCode::SERVICE_UNAVAILABLE, "no cell runtime");
3249- };
3250- let abort_scope = scope.clone();
3251- // The forwarding node hangs up when its own client does, so this
3252- // connection going away is the cancellation signal reaching the
3253- // owner -- and it arrives as a drop, which is why it is a guard
3254- // rather than the channel `fetch_cell` takes. Without it a handler
3255- // keeps running on the owner for a client that left the node it
3256- // dialled.
3257- let mut abort = AbortPeerFetchOnHangUp {
3258- runtime: runtime.clone(),
3259- scope: abort_scope,
3260- request_id,
3261- };
3262- match runtime
3263- .fetch_cell(
3264- scope,
3265- name,
3266- RuntimeFetch {
3267- url,
3268- method,
3269- body: request_body,
3270- headers,
3271- request_id,
3272- // A peer's call has no caller in this process; its
3273- // trace context crossing nodes is phase 2.
3274- order: None,
3275- parent: None,
3276- },
3277- None,
3278- )
3279- .await
3280- {
3281- Ok(worker_response) => {
3282- abort.request_id = None;
3283- // Output gate (RPO=0): a peer-served handler that advanced
3284- // the cell's committed position holds its reply until the
3285- // cell is proven durable, exactly as the local dispatch
3286- // path does. This path used to acknowledge unproven writes
3287- // — the loss the takeover tests catch. The activity guard
3288- // is still alive, so the request stays pinned across the
3289- // wait.
3290- if let Some(position) =
3291- worker_response.write_position.filter(|_| app.output_gate)
3292- {
3293- if let Err(error) = app.gate_write(request, position).await {
3294- return peer_response(response(
3295- StatusCode::INTERNAL_SERVER_ERROR,
3296- format!("durability unproven: {error:?}"),
3297- ));
3298- }
3299- }
3300- if let Some(target) = &worker_response.ws {
3301- let kind = if celld::js::ws_hibernatable(target.id).unwrap_or(false) {
3302- WebSocketKind::Hibernatable
3303- } else {
3304- WebSocketKind::Regular
3305- };
3306- if let Err(error) = app
3307- .websocket_opened(target.scope.clone(), target.id, kind)
3308- .await
3309- {
3310- return peer_response(response(
3311- StatusCode::SERVICE_UNAVAILABLE,
3312- format!("WebSocket core registration failed: {error:#}"),
3313- ));
3314- }
3315- }
3316- peer_runtime_response(worker_response)
3317- }
3318- Err(error) => response(
3319- StatusCode::INTERNAL_SERVER_ERROR,
3320- format!("cell Worker failed: {error:#}"),
3321- ),
3322- }
3323- }
3324- Ok(Routed {
3325- route: Route::Remote { .. },
3326- ..
3327- }) => {
3328- let mut stale = response(StatusCode::CONFLICT, "stale route");
3329- stale.headers_mut().insert(
3330- hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
3331- hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
3332- );
3333- stale
3334- }
3335- Err(RequestError::CapacityExhausted) => {
3336- let mut stale = response(StatusCode::CONFLICT, "capacity exhausted");
3337- stale.headers_mut().insert(
3338- hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
3339- hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
3340- );
3341- stale
3342- }
3343- Err(error) => response(
3344- StatusCode::SERVICE_UNAVAILABLE,
3345- format!("route failed: {error:?}"),
3346- ),
3347- };
3348- peer_response(result)
3349-}
3350-
3351-async fn internal_abort(request: Request<Incoming>, app: AppHandle, path: String) -> HttpReply {
3352- let (parts, body) = request.into_parts();
3353- let body = match body.collect().await {
3354- Ok(body) => body.to_bytes(),
3355- Err(error) => {
3356- return peer_response(response(
3357- StatusCode::BAD_REQUEST,
3358- format!("invalid abort body: {error}"),
3359- ));
3360- }
3361- };
3362- let path_and_query = parts
3363- .uri
3364- .path_and_query()
3365- .map_or_else(|| parts.uri.path().to_string(), ToString::to_string);
3366- if let Err(error) = app.peer_auth.verify(
3367- &parts.method,
3368- &path_and_query,
3369- &parts.headers,
3370- &body,
3371- app.peer_auth.source(),
3372- ) {
3373- let mut denied = response(error.status(), error.message());
3374- if matches!(error, peer_auth::VerifyError::WrongTarget) {
3375- denied.headers_mut().insert(
3376- hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
3377- hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
3378- );
3379- }
3380- return peer_response(denied);
3381- }
3382- if parts.method != hyper::Method::POST {
3383- return peer_response(response(
3384- StatusCode::METHOD_NOT_ALLOWED,
3385- "method not allowed",
3386- ));
3387- }
3388- let Some((encoded_scope, encoded_request)) = path
3389- .strip_prefix("/__abort/")
3390- .and_then(|rest| rest.rsplit_once('/'))
3391- else {
3392- return peer_response(response(StatusCode::BAD_REQUEST, "invalid abort target"));
3393- };
3394- let scope = match percent_encoding::percent_decode_str(encoded_scope).decode_utf8() {
3395- Ok(scope) => scope.into_owned(),
3396- Err(_) => return peer_response(response(StatusCode::BAD_REQUEST, "invalid abort scope")),
3397- };
3398- if !celld_logic::cell::valid_cell_scope(&scope) {
3399- return peer_response(malformed_scope());
3400- }
3401- let Some(request_id) = celld::js::parse_request_id(encoded_request) else {
3402- return peer_response(response(StatusCode::BAD_REQUEST, "invalid request id"));
3403- };
3404- let result = match app.request(scope.clone()).await {
3405- Ok(Routed {
3406- request,
3407- route: Route::Local,
3408- }) => {
3409- let _activity = app.activity(request, scope.clone());
3410- match &app.runtime {
3411- Some(runtime) => {
3412- runtime.abort_fetch(&scope, request_id);
3413- response(StatusCode::NO_CONTENT, Bytes::new())
3414- }
3415- None => response(StatusCode::SERVICE_UNAVAILABLE, "no cell runtime"),
3416- }
3417- }
3418- Ok(Routed {
3419- route: Route::Remote { .. },
3420- ..
3421- }) => {
3422- let mut stale = response(StatusCode::CONFLICT, "stale route");
3423- stale.headers_mut().insert(
3424- hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
3425- hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
3426- );
3427- stale
3428- }
3429- Err(error) => response(
3430- StatusCode::SERVICE_UNAVAILABLE,
3431- format!("abort route failed: {error:?}"),
3432- ),
3433- };
3434- peer_response(result)
3435-}
3436-
3437-async fn internal_rpc(request: Request<Incoming>, app: AppHandle, scope: String) -> HttpReply {
3438- let method = request.method().clone();
3439- let path_and_query = request
3440- .uri()
3441- .path_and_query()
3442- .map_or_else(|| request.uri().path().to_string(), ToString::to_string);
3443- let request_headers = request.headers().clone();
3444- let body = match request.into_body().collect().await {
3445- Ok(body) => body.to_bytes(),
3446- Err(error) => {
3447- return peer_response(response(
3448- StatusCode::BAD_REQUEST,
3449- format!("invalid body: {error}"),
3450- ));
3451- }
3452- };
3453- if let Err(error) = app.peer_auth.verify(
3454- &method,
3455- &path_and_query,
3456- &request_headers,
3457- &body,
3458- app.peer_auth.source(),
3459- ) {
3460- let mut denied = response(error.status(), error.message());
3461- if matches!(error, peer_auth::VerifyError::WrongTarget) {
3462- denied.headers_mut().insert(
3463- hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
3464- hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
3465- );
3466- }
3467- return peer_response(denied);
3468- }
3469- let value: serde_json::Value = match serde_json::from_slice(&body) {
3470- Ok(value) => value,
3471- Err(error) => {
3472- return peer_response(response(
3473- StatusCode::BAD_REQUEST,
3474- format!("invalid JSON: {error}"),
3475- ));
3476- }
3477- };
3478- let name = value
3479- .get("name")
3480- .and_then(serde_json::Value::as_str)
3481- .map(str::to_string);
3482- let rpc_method = value
3483- .get("method")
3484- .and_then(serde_json::Value::as_str)
3485- .unwrap_or_default()
3486- .to_string();
3487- let args = match value.get("sc").and_then(serde_json::Value::as_str) {
3488- Some(bytes) => celld::js::RpcData::V8(
3489- base64::engine::general_purpose::STANDARD
3490- .decode(bytes)
3491- .unwrap_or_default(),
3492- ),
3493- None => celld::js::RpcData::Json(
3494- value
3495- .get("args")
3496- .cloned()
3497- .unwrap_or_else(|| serde_json::json!([]))
3498- .to_string(),
3499- ),
3500- };
3501- let result = match app.request(scope.clone()).await {
3502- Ok(Routed {
3503- request,
3504- route: Route::Local,
3505- }) => {
3506- let _activity = app.activity(request, scope.clone());
3507- let Some(runtime) = &app.runtime else {
3508- return peer_response(response(StatusCode::SERVICE_UNAVAILABLE, "no cell runtime"));
3509- };
3510- // Output gate on the owner side, so a proxied RPC write is durable
3511- // before the calling node sees the reply -- the same rule the peer
3512- // fetch path follows.
3513- match runtime.rpc(scope, name, rpc_method, args).await {
3514- Ok(outcome) => {
3515- if let Some(position) = outcome.write_position.filter(|_| app.output_gate) {
3516- if let Err(error) = app.gate_write(request, position).await {
3517- return peer_response(response(
3518- StatusCode::INTERNAL_SERVER_ERROR,
3519- format!("durability unproven: {error:?}"),
3520- ));
3521- }
3522- }
3523- Ok(outcome.data)
3524- }
3525- Err(error) => Err(error),
3526- }
3527- }
3528- Ok(Routed {
3529- route: Route::Remote { .. },
3530- ..
3531- }) => {
3532- let mut stale = response(StatusCode::CONFLICT, "stale route");
3533- stale.headers_mut().insert(
3534- hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
3535- hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
3536- );
3537- return peer_response(stale);
3538- }
3539- Err(error) => Err(anyhow::anyhow!("route failed: {error:?}")),
3540- };
3541- match result {
3542- Ok(celld::js::RpcData::Json(json)) => peer_response(
3543- Response::builder()
3544- .status(StatusCode::OK)
3545- .header("content-type", "application/json")
3546- .body(
3547- Full::new(Bytes::from(json))
3548- .map_err(|never| match never {})
3549- .boxed_unsync(),
3550- )
3551- .expect("RPC JSON response"),
3552- ),
3553- Ok(celld::js::RpcData::V8(bytes)) => peer_response(
3554- Response::builder()
3555- .status(StatusCode::OK)
3556- .header("content-type", "application/octet-stream")
3557- .body(
3558- Full::new(Bytes::from(bytes))
3559- .map_err(|never| match never {})
3560- .boxed_unsync(),
3561- )
3562- .expect("RPC clone response"),
3563- ),
3564- Err(error) => peer_response(response(
3565- StatusCode::INTERNAL_SERVER_ERROR,
3566- format!("RPC failed: {error:#}"),
3567- )),
3568- }
3569-}
3570-
3571-#[path = "main/websocket.rs"]
3572-mod websocket;
3573-use websocket::{handle_peer_websocket, handle_websocket, outbound_websocket_task};
3574-
3575-async fn handle_ingress(
3576- request: Request<Incoming>,
3577- app: AppHandle,
3578- connection: ConnectionWorkerRequests,
3579-) -> HttpReply {
3580- if matches!(*request.method(), hyper::Method::GET | hyper::Method::HEAD) {
3581- if let Some(resolver) = app
3582- .asset_script
3583- .as_deref()
3584- .and_then(|script| app.assets.get(script))
3585- {
3586- let path = request.uri().path();
3587- if !resolver.should_run_worker_first(path) {
3588- let head = request.method() == hyper::Method::HEAD;
3589- match resolver
3590- .ingress_response(path, request.uri().query(), head, request.headers())
3591- .await
3592- {
3593- Ok(Some(response)) => return asset_response(response),
3594- Ok(None) if resolver.asset_only() => {
3595- return response(StatusCode::NOT_FOUND, "Not found");
3596- }
3597- Ok(None) => {}
3598- Err(error) => {
3599- eprintln!("celld asset response failed for {path}: {error:#}");
3600- return response(
3601- StatusCode::BAD_GATEWAY,
3602- "Active deployment asset is unavailable",
3603- );
3604- }
3605- }
3606- }
3607- }
3608- }
3609-
3610- let (url, method, body, headers) =
3611- match request_payload(request, app.trust_forwarded_headers).await {
3612- Ok(payload) => payload,
3613- Err(response) => return response,
3614- };
3615- match app
3616- .fetch_worker(url, method, body, headers, connection)
3617- .await
3618- {
3619- Ok(worker_response) => runtime_response(worker_response),
3620- Err(error) => match error.downcast_ref::<celld::pool::AdmitError>() {
3621- // Saturation is not a failure of the request. Answering it now
3622- // lets the caller retry or shed; holding the connection until its
3623- // own deadline is what a node with no capacity used to do.
3624- Some(refused @ celld::pool::AdmitError::Refused(_)) => response(
3625- StatusCode::SERVICE_UNAVAILABLE,
3626- format!("Worker refused: {refused}"),
3627- ),
3628- // A build failure is a fault, not saturation.
3629- Some(celld::pool::AdmitError::Build(_)) | None => response(
3630- StatusCode::INTERNAL_SERVER_ERROR,
3631- format!("Worker failed: {error:#}"),
3632- ),
3633- },
3634- }
3635-}
3636-
3637-async fn dispatch_asset_call(app: AppHandle, call: AssetCallReq) {
3638- let response = match app.assets.get(&call.script) {
3639- Some(resolver) => {
3640- resolver
3641- .binding_response(&call.url, &call.method, &call.headers)
3642- .await
3643- }
3644- None => Err(anyhow::anyhow!(
3645- "no asset resolver for script {}",
3646- call.script
3647- )),
3648- };
3649- let _ = call.reply.send(response);
3650-}
3651-
3652-async fn dispatch_service_call(app: AppHandle, call: SvcCallReq) {
3653- let response = match &app.runtime {
3654- Some(runtime) => {
3655- runtime
3656- .fetch_service(
3657- &call.script,
3658- call.url,
3659- call.method,
3660- call.body,
3661- call.headers,
3662- call.cancel,
3663- )
3664- .await
3665- }
3666- None => Err(anyhow::anyhow!("no Worker runtime")),
3667- };
3668- let _ = call.reply.send(response);
3669-}
3670-
3671-async fn dispatch_service_rpc(app: AppHandle, call: SvcRpcReq) {
3672- let response = match &app.runtime {
3673- Some(runtime) => {
3674- runtime
3675- .rpc_service(&call.script, call.entrypoint, call.method, call.args)
3676- .await
3677- }
3678- None => Err(anyhow::anyhow!("no Worker runtime")),
3679- };
3680- let _ = call.reply.send(response);
3681-}
3682-
3683-async fn internal_probe(request: Request<Incoming>, app: AppHandle) -> HttpReply {
3684- let (parts, body) = request.into_parts();
3685- let body = match body.collect().await {
3686- Ok(body) => body.to_bytes(),
3687- Err(error) => {
3688- return peer_response(response(
3689- StatusCode::BAD_REQUEST,
3690- format!("invalid probe body: {error}"),
3691- ));
3692- }
3693- };
3694- let path_and_query = parts
3695- .uri
3696- .path_and_query()
3697- .map_or_else(|| parts.uri.path().to_string(), ToString::to_string);
3698- if let Err(error) = app.peer_auth.verify(
3699- &parts.method,
3700- &path_and_query,
3701- &parts.headers,
3702- &body,
3703- app.peer_auth.source(),
3704- ) {
3705- return peer_response(response(error.status(), error.message()));
3706- }
3707- if parts.method != hyper::Method::GET {
3708- return peer_response(response(
3709- StatusCode::METHOD_NOT_ALLOWED,
3710- "method not allowed",
3711- ));
3712- }
3713- let Some(challenge) = parts
3714- .headers
3715- .get("x-cells-probe-challenge")
3716- .and_then(|value| value.to_str().ok())
3717- else {
3718- return peer_response(response(StatusCode::BAD_REQUEST, "missing probe challenge"));
3719- };
3720- match celld::peer_probe::respond(app.peer_auth.source(), &app.advertise, challenge) {
3721- Ok(probe) => match serde_json::to_vec(&probe) {
3722- Ok(body) => peer_response(response(StatusCode::OK, body)),
3723- Err(_) => peer_response(response(
3724- StatusCode::INTERNAL_SERVER_ERROR,
3725- "encode probe response",
3726- )),
3727- },
3728- Err(_) => peer_response(response(StatusCode::BAD_REQUEST, "invalid probe challenge")),
3729- }
3730-}
3731-
3732-async fn handle_public(
3733- request: Request<Incoming>,
3734- app: AppHandle,
3735- connection: ConnectionWorkerRequests,
3736-) -> Result<HttpReply, Infallible> {
3737- let path = request.uri().path().to_string();
3738- let draining = app.is_draining();
3739- if draining && path != "/__celld/health" {
3740- let mut refused = response(
3741- StatusCode::SERVICE_UNAVAILABLE,
3742- "{\"ok\":false,\"draining\":true}",
3743- );
3744- refused.headers_mut().insert(
3745- hyper::header::RETRY_AFTER,
3746- hyper::header::HeaderValue::from_static("1"),
3747- );
3748- refused.headers_mut().insert(
3749- hyper::header::CONNECTION,
3750- hyper::header::HeaderValue::from_static("close"),
3751- );
3752- return Ok(refused);
3753- }
3754- if path != "/__celld/health"
3755- && app.runtime.is_some()
3756- && fastwebsockets::upgrade::is_upgrade_request(&request)
3757- {
3758- return Ok(handle_websocket(request, app).await);
3759- }
3760- let mut result = match path.as_str() {
3761- "/__celld/health" if !app.is_draining() && app.healthy().await => {
3762- response(StatusCode::OK, "{\"ok\":true}")
3763- }
3764- "/__celld/health" => response(StatusCode::SERVICE_UNAVAILABLE, "{\"ok\":false}"),
3765- _ if app.runtime.is_some() => handle_ingress(request, app, connection).await,
3766- _ => response(StatusCode::NOT_FOUND, "{\"error\":\"not_found\"}"),
3767- };
3768- if draining {
3769- result.headers_mut().insert(
3770- hyper::header::CONNECTION,
3771- hyper::header::HeaderValue::from_static("close"),
3772- );
3773- }
3774- Ok(result)
3775-}
3776-
3777-async fn handle_internal(
3778- request: Request<Incoming>,
3779- app: AppHandle,
3780- shutdown: mpsc::UnboundedSender<ShutdownMode>,
3781-) -> Result<HttpReply, Infallible> {
3782- let path = request.uri().path().to_string();
3783- let draining = app.is_draining();
3784- // A draining node accepts no new work: a request for a cell it just
3785- // released would re-claim the cell and undo the handoff, so everything
3786- // but diagnostics is refused, and `Connection: close` tears the
3787- // keep-alive down so the drain loop can finish instead of holding every
3788- // idle connection open until the deadline.
3789- if draining && !matches!(path.as_str(), "/__celld/probe" | "/state") {
3790- let mut refused = response(
3791- StatusCode::SERVICE_UNAVAILABLE,
3792- "{\"ok\":false,\"draining\":true}",
3793- );
3794- refused.headers_mut().insert(
3795- hyper::header::RETRY_AFTER,
3796- hyper::header::HeaderValue::from_static("1"),
3797- );
3798- refused.headers_mut().insert(
3799- hyper::header::CONNECTION,
3800- hyper::header::HeaderValue::from_static("close"),
3801- );
3802- return Ok(refused);
3803- }
3804- if path.starts_with("/__ws/") && fastwebsockets::upgrade::is_upgrade_request(&request) {
3805- return Ok(handle_peer_websocket(request, app, &path).await);
3806- }
3807- let result = match path.as_str() {
3808- "/__celld/probe" => internal_probe(request, app).await,
3809- "/state" => response(StatusCode::OK, app.snapshot().await),
3810- "/shutdown" if request.method() != hyper::Method::POST => {
3811- response(StatusCode::METHOD_NOT_ALLOWED, "method not allowed")
3812- }
3813- "/shutdown" => {
3814- let preserve_ownership = request
3815- .uri()
3816- .query()
3817- .is_some_and(|query| query.split('&').any(|part| part == "handoff=preserve"));
3818- let mode = if preserve_ownership {
3819- ShutdownMode::Preserve
3820- } else {
3821- ShutdownMode::Handoff
3822- };
3823- let _ = shutdown.send(mode);
3824- response(StatusCode::OK, "{\"ok\":true}")
3825- }
3826- _ if path.starts_with("/__abort/") && app.runtime.is_some() => {
3827- internal_abort(request, app, path).await
3828- }
3829- _ if path.starts_with("/__do/") && app.runtime.is_some() => {
3830- if celld_logic::cell::valid_cell_scope(&path[6..]) {
3831- internal_do(request, app, path[6..].to_string()).await
3832- } else {
3833- peer_response(malformed_scope())
3834- }
3835- }
3836- _ if path.starts_with("/__rpc/") && app.runtime.is_some() => {
3837- if celld_logic::cell::valid_cell_scope(&path[7..]) {
3838- internal_rpc(request, app, path[7..].to_string()).await
3839- } else {
3840- peer_response(malformed_scope())
3841- }
3842- }
3843- _ if path.starts_with("/do/") && app.runtime.is_some() => {
3844- let runtime = app.runtime.as_ref().expect("checked runtime");
3845- let cell = match runtime.cell_scope(&path[4..]) {
3846- Ok(cell) => cell,
3847- Err(error) => {
3848- return Ok(response(StatusCode::BAD_REQUEST, format!("{error:#}")));
3849- }
3850- };
3851- let (url, method, body, headers) =
3852- match request_payload(request, app.trust_forwarded_headers).await {
3853- Ok(payload) => payload,
3854- Err(response) => return Ok(response),
3855- };
3856- // The same dispatcher a Durable Object call from inside a Worker
3857- // goes through. Public ingress used to resolve the route itself
3858- // and, on finding another owner, answer with a 307 and a JSON
3859- // description of where the cell lived -- with no Location header,
3860- // so nothing could follow it. A fleet behind a load balancer
3861- // serves a cell only from the node that happens to own it, which
3862- // is to say it does not serve a fleet at all.
3863- //
3864- // Going through `dispatch_do_call` also inherits the redispatch
3865- // policy and the cancellation channel, so a client that hangs up
3866- // reaches the owner rather than only the node it connected to.
3867- let (reply, receive) = oneshot::channel();
3868- let (cancel_tx, cancel) = oneshot::channel();
3869- let accepted = celld::js::submit_do_call(celld::js::DoCallReq {
3870- // Named, and named here: the abort fires only for a call that
3871- // carries both an id and a cancel signal, so leaving this None
3872- // silently costs the cancellation rather than failing.
3873- request_id: Some(celld::js::next_request_id()),
3874- cancel: Some(cancel),
3875- deliver_abort_to_handler: false,
3876- scope: cell,
3877- name: None,
3878- url,
3879- method,
3880- body,
3881- headers,
3882- reply,
3883- // An ingress call has no caller in this process to be
3884- // ordered against.
3885- order: None,
3886- // A direct-DO ingress caller's traceparent joins with the
3887- // cross-node propagation work (otel.md phase 2), which is
3888- // where remote parents of cell spans get their sampling
3889- // decision.
3890- parent: None,
3891- });
3892- if !accepted {
3893- return Ok(response(
3894- StatusCode::SERVICE_UNAVAILABLE,
3895- "{\"error\":\"dispatcher unavailable\"}",
3896- ));
3897- }
3898- let _hangup = HangUp(Some(cancel_tx));
3899- match receive.await {
3900- Ok(Ok(worker_response)) => runtime_response(worker_response),
3901- Ok(Err(error)) => match error.downcast_ref::<RoutedRequestError>() {
3902- Some(error) => response(
3903- StatusCode::SERVICE_UNAVAILABLE,
3904- format!("{{\"error\":\"{:?}\"}}", error.0),
3905- ),
3906- None => response(
3907- StatusCode::SERVICE_UNAVAILABLE,
3908- format!("cell Worker failed: {error:#}"),
3909- ),
3910- },
3911- Err(_) => response(
3912- StatusCode::SERVICE_UNAVAILABLE,
3913- "{\"error\":\"dispatcher dropped the call\"}",
3914- ),
3915- }
3916- }
3917- _ if path.starts_with("/cell/") && !celld_logic::cell::valid_cell_scope(&path[6..]) => {
3918- malformed_scope()
3919- }
3920- _ if path.starts_with("/cell/") => {
3921- let cell = path[6..].to_string();
3922- match app.request(cell.clone()).await {
3923- Ok(Routed {
3924- request,
3925- route: Route::Local,
3926- }) => {
3927- let _activity = app.activity(request, cell.clone());
3928- response(
3929- StatusCode::OK,
3930- format!("{{\"route\":\"local\",\"cell\":{cell:?}}}"),
3931- )
3932- }
3933- Ok(Routed {
3934- route:
3935- Route::Remote {
3936- node,
3937- addr,
3938- epoch,
3939- peer_protocol,
3940- },
3941- ..
3942- }) => response(
3943- StatusCode::TEMPORARY_REDIRECT,
3944- format!(
3945- "{{\"route\":\"remote\",\"node\":{node:?},\"addr\":{addr:?},\"epoch\":{epoch},\"peer_protocol\":{peer_protocol}}}"
3946- ),
3947- ),
3948- Err(error) => response(
3949- StatusCode::SERVICE_UNAVAILABLE,
3950- format!("{{\"error\":\"{error:?}\"}}"),
3951- ),
3952- }
3953- }
3954- _ if path.starts_with("/evict/") && !celld_logic::cell::valid_cell_scope(&path[7..]) => {
3955- malformed_scope()
3956- }
3957- _ if path.starts_with("/evict/") => {
3958- app.evict(path[7..].to_string()).await;
3959- response(StatusCode::OK, "{\"ok\":true}")
3960- }
3961- _ => response(StatusCode::NOT_FOUND, "{\"error\":\"not_found\"}"),
3962- };
3963- // Close the connection behind any response sent while draining, so
3964- // keep-alive clients reconnect to a healthy node and the drain loop
3965- // can finish. A request that raced the drain flag converges on its
3966- // next request, which hits the gate above.
3967- let mut result = result;
3968- if draining {
3969- result.headers_mut().insert(
3970- hyper::header::CONNECTION,
3971- hyper::header::HeaderValue::from_static("close"),
3972- );
3973- }
3974- Ok(result)
3975-}
3976-
3977-#[derive(Clone, Copy)]
3978-enum HttpSurface {
3979- Public,
3980- Internal,
3981-}
3982-
3983-fn serve_http_connection(
3984- stream: tokio::net::TcpStream,
3985- surface: HttpSurface,
3986- app: AppHandle,
3987- shutdown: mpsc::UnboundedSender<ShutdownMode>,
3988- mut connection_drain: watch::Receiver<bool>,
3989- connection_grace: std::time::Duration,
3990-) -> ConnectionFuture {
3991- Box::pin(async move {
3992- // Serve on the runtime, not on this task. `main` drives its loop with
3993- // `block_on`, so serving there put every connection on one core.
3994- // Awaiting the spawned task keeps shutdown tracking unchanged.
3995- let served = tokio::spawn(async move {
3996- let connection_requests = ConnectionWorkerRequests::default();
3997- let service_requests = connection_requests.clone();
3998- let service = service_fn(move |request| {
3999- let app = app.clone();
4000- let shutdown = shutdown.clone();
4001- let service_requests = service_requests.clone();
4002- async move {
4003- match surface {
4004- HttpSurface::Public => handle_public(request, app, service_requests).await,
4005- HttpSurface::Internal => handle_internal(request, app, shutdown).await,
4006- }
4007- }
4008- });
4009- let connection = http1::Builder::new()
4010- // Reclaim a connection that never sends a complete request
4011- // head. The timeout also bounds an idle keep-alive waiting
4012- // for its next request.
4013- .timer(hyper_util::rt::TokioTimer::new())
4014- .header_read_timeout(std::time::Duration::from_secs(30))
4015- .serve_connection(TokioIo::new(stream), service)
4016- .with_upgrades();
4017- tokio::pin!(connection);
4018- let result = tokio::select! {
4019- result = &mut connection => Some(result),
4020- _ = connection_drain.changed() => {
4021- connection.as_mut().graceful_shutdown();
4022- tokio::time::timeout(connection_grace, &mut connection)
4023- .await
4024- .ok()
4025- }
4026- };
4027- connection_requests.abort_all();
4028- match result {
4029- Some(Err(error)) => eprintln!("celld connection failed: {error}"),
4030- None => tracing::warn!(
4031- event = "connection_drain_forced",
4032- grace_ms = connection_grace.as_millis(),
4033- "forced an HTTP connection closed after its graceful drain"
4034- ),
4035- Some(Ok(())) => {}
4036- }
4037- });
4038- let _ = served.await;
4039- })
4040-}
4041-
4042-#[path = "main/cli.rs"]
4043-mod cli;
4044-use cli::{action_from_process, print_help, worker_loader_binding, Action};
4045-
4046-/// An activation effect that has not answered by now is not going to help the
4047-/// request that is waiting on it. celld had no such bound and parked requests
4048-/// past ninety seconds.
4049-const DEFAULT_OPERATION_DEADLINE_MS: u64 = 15_000;
4050-/// Cold routes are I/O concurrency, but must stay below the point where they
4051-/// can starve the node lease heartbeat or object store.
4052-const DEFAULT_MAX_CONCURRENT_ACTIVATIONS: usize = 128;
4053-/// celld's own default. Evictions are bounded far tighter than activations
4054-/// because each one carries a durability proof, and a node that lets its whole
4055-/// working set prove durability at once turns a walk down into a thundering
4056-/// herd against the bucket.
4057-const DEFAULT_MAX_CONCURRENT_EVICTIONS: usize = 4;
4058-/// The shutdown handoff bound. Wider than the eviction bound because a
4059-/// draining node has no live traffic left to protect and a stop grace to
4060-/// beat, but still bounded so a node-wide handoff cannot thundering-herd
4061-/// the bucket.
4062-const DEFAULT_MAX_CONCURRENT_RELEASES: usize = 128;
4063-/// Preserved SQLite snapshots make a same-node wake a rename instead of a
4064-/// remote restore, but must not grow with the lifetime population of a node.
4065-const DEFAULT_LOCAL_CACHE_MAX_BYTES: u64 = 2 * 1024 * 1024 * 1024;
4066-/// The walk is O(cached cells), so keep it off the hot maintenance cadence.
4067-const LOCAL_CACHE_PRUNE_PERIOD: std::time::Duration = std::time::Duration::from_secs(60);
4068-
4069-fn main() -> anyhow::Result<()> {
4070- celld::env_vars::validate()?;
4071- // Parse the telemetry group once, before any command or runtime work.
4072- // Its specialized values share the strict scalar parsers in env_vars.
4073- let telemetry_config = celld::telemetry::Config::from_env()?;
4074- rustls::crypto::ring::default_provider()
4075- .install_default()
4076- .ok();
4077- // Before the runtime exists, so every worker thread inherits a PKRU that
4078- // grants access to V8's pointer-table protection key.
4079- celld::runtime::init_v8();
4080- let mut builder = tokio::runtime::Builder::new_multi_thread();
4081- builder.enable_all();
4082- if let Some(workers) = celld::env_vars::positive::<usize>("CELLD_TOKIO_THREADS")? {
4083- builder.worker_threads(workers);
4084- }
4085- builder.build()?.block_on(async_main(telemetry_config))
4086-}
4087-
4088-async fn async_main(telemetry_config: Option<celld::telemetry::Config>) -> anyhow::Result<()> {
4089- celld::asyncrt::set_host_handle(tokio::runtime::Handle::current());
4090- // Docker and journald can stop consuming the process pipe during a log
4091- // burst. Logging must lose diagnostics under that backpressure rather
4092- // than block the Tokio workers that route requests and renew authority.
4093- let (log_writer, log_guard) = tracing_appender::non_blocking::NonBlockingBuilder::default()
4094- .buffered_lines_limit(8_192)
4095- .lossy(true)
4096- .finish(std::io::stdout());
4097- *LOG_GUARD.lock().unwrap() = Some(log_guard);
4098- tracing_subscriber::fmt()
4099- .with_writer(log_writer)
4100- // The custom writer defeats fmt's own TTY detection, and journald
4101- // must not receive ANSI escapes.
4102- .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stdout()))
4103- .with_env_filter(
4104- tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
4105- )
4106- .init();
4107- // After the subscriber, because this reports whether the allocator agreed
4108- // to return freed pages on a timer. A node without that thread holds
4109- // retention until a thread allocates again, which is the condition behind
4110- // issue #36, so the operator has to be able to read the answer.
4111- celld::memory::tune_allocator();
4112- let mut settings = match action_from_process()? {
4113- Action::Deploy(arguments) => return fleet::run_deploy(arguments).await,
4114- Action::Connect(arguments) => {
4115- return celld::control_plane::handle_connect_command(arguments).await
4116- }
4117- Action::Credentials(arguments) => {
4118- return celld::control_plane::handle_credentials_command(arguments).await
4119- }
4120- Action::Token(arguments) => {
4121- return celld::control_plane::handle_token_command(arguments).await
4122- }
4123- Action::Disconnect(arguments) => {
4124- return celld::control_plane::handle_disconnect_command(arguments).await
4125- }
4126- Action::Help => {
4127- print_help();
4128- return Ok(());
4129- }
4130- Action::Version => {
4131- let profile = if cfg!(debug_assertions) {
4132- " (debug)"
4133- } else {
4134- ""
4135- };
4136- println!("celld {}{profile}", env!("CARGO_PKG_VERSION"));
4137- return Ok(());
4138- }
4139- Action::Diagnose {
4140- mut settings,
4141- peers,
4142- read_only,
4143- } => {
4144- let ingress = celld::startup::bind_ingress_listener(&settings.listen).await?;
4145- let internal =
4146- celld::startup::bind_internal_listener(&celld::startup::InternalListenerSettings {
4147- listen: settings.internal_listen.clone(),
4148- advertise: settings.advertise.clone(),
4149- unsafe_public_advertise: settings.unsafe_public_advertise,
4150- })
4151- .await?;
4152- // The bind proves the address is free; diagnose never serves on it,
4153- // and an operator should not read this line as a running listener.
4154- println!(
4155- "ok listen {} (bind check; diagnose does not serve)",
4156- ingress.listen
4157- );
4158- println!(
4159- "ok internal listen {} (bind check; diagnose does not serve)",
4160- internal.listen
4161- );
4162- println!(
4163- "ok advertise {} ({}; direct reachability is not inferred)",
4164- internal.advertise,
4165- internal.advertise.scope()
4166- );
4167- let managed_storage = if settings.control_plane {
4168- match celld::control_plane::installation_storage().context(
4169- "managed diagnostics require an existing enrollment; run `celld --control-plane` first",
4170- )? {
4171- celld::control_plane::InstallationStorageConfig::Managed(storage) => {
4172- settings.bucket = Some(storage.bucket.clone());
4173- settings.endpoint = Some(storage.endpoint.clone());
4174- settings.region = storage.region.clone();
4175- Some(storage)
4176- }
4177- celld::control_plane::InstallationStorageConfig::Byo(storage) => {
4178- settings.bucket = Some(storage.bucket);
4179- settings.endpoint = storage.endpoint;
4180- settings.region = storage.region;
4181- None
4182- }
4183- }
4184- } else {
4185- None
4186- };
4187- let bucket = settings
4188- .bucket
4189- .ok_or_else(|| anyhow::anyhow!("celld diagnose requires --bucket"))?;
4190- let client = fleet::bucket_client_with_credentials(
4191- &bucket,
4192- settings.endpoint.as_deref(),
4193- &settings.region,
4194- managed_storage.as_ref(),
4195- )?;
4196- return fleet::diagnose(&client, peers, settings.unsafe_public_advertise, read_only)
4197- .await;
4198- }
4199- Action::Run(settings) => settings,
4200- };
4201- celld::startup::raise_file_limit();
4202- let max_resident = celld::env_vars::optional("CELLD_MAX_RESIDENT_CELLS")?
4203- // celld has no resident ceiling unless the operator configures one.
4204- // The clean-sheet prototype originally defaulted to eight, which
4205- // introduced eviction churn in otherwise unconstrained workloads and
4206- // made cancellation semantics depend on cold-reactivation latency.
4207- .unwrap_or(usize::MAX);
4208- let local_cache_max_bytes = local_cache_max_bytes_from_environment()?;
4209- let fail_publish_once = std::env::var_os("CELLD_TEST_FAIL_PUBLISH_ONCE").is_some();
4210- let ingress = celld::startup::bind_ingress_listener(&settings.listen).await?;
4211- let internal =
4212- celld::startup::bind_internal_listener(&celld::startup::InternalListenerSettings {
4213- listen: settings.internal_listen.clone(),
4214- advertise: settings.advertise.clone(),
4215- unsafe_public_advertise: settings.unsafe_public_advertise,
4216- })
4217- .await?;
4218- let advertise = internal.advertise.to_string();
4219- let listen = ingress.listen.to_string();
4220- let listener = ingress.listener;
4221- let internal_listener = internal.listener;
4222- let mut adapter_credential_version = None;
4223- let managed_storage = if settings.control_plane {
4224- // The control plane issues and validates S3-compatible storage
4225- // only; celld's GCS client authenticates with OAuth, which the
4226- // control plane's S3-shaped credentials cannot provide.
4227- if settings
4228- .bucket
4229- .as_deref()
4230- .is_some_and(|b| b.starts_with("gs://"))
4231- {
4232- anyhow::bail!(
4233- "--control-plane storage is S3-compatible; a gs:// bucket runs without it"
4234- );
4235- }
4236- // The control plane issues one bucket per fleet and its enrollment
4237- // API rejects a bucket name holding a slash, so a prefix has neither
4238- // a purpose nor a path through. Say so instead of failing enrollment.
4239- if settings.bucket.as_deref().is_some_and(|b| b.contains('/')) {
4240- anyhow::bail!("--control-plane does not accept a --bucket prefix");
4241- }
4242- let requested_byo =
4243- settings
4244- .bucket
4245- .as_ref()
4246- .map(|bucket| celld::control_plane::ByoStorageConfig {
4247- bucket: bucket.clone(),
4248- endpoint: settings.endpoint.clone(),
4249- region: settings.region.clone(),
4250- });
4251- celld::control_plane::connect_on_startup_with_storage(requested_byo).await?;
4252- settings.load_deployment = true;
4253- let (storage, credential_version) =
4254- celld::control_plane::installation_storage_with_version()?;
4255- adapter_credential_version = Some(credential_version);
4256- match storage {
4257- celld::control_plane::InstallationStorageConfig::Managed(storage) => {
4258- settings.bucket = Some(storage.bucket.clone());
4259- settings.endpoint = Some(storage.endpoint.clone());
4260- settings.region = storage.region.clone();
4261- Some(storage)
4262- }
4263- celld::control_plane::InstallationStorageConfig::Byo(storage) => {
4264- settings.bucket = Some(storage.bucket);
4265- settings.endpoint = storage.endpoint;
4266- settings.region = storage.region;
4267- None
4268- }
4269- }
4270- } else {
4271- None
4272- };
4273- let storage_credentials =
4274- managed_storage
4275- .as_ref()
4276- .map(|storage| celld::replication::StorageCredentials {
4277- access_key_id: storage.access_key_id.clone(),
4278- secret_access_key: storage.secret_access_key.clone(),
4279- session_token: storage.session_token.clone(),
4280- });
4281- let (tx, rx) = mpsc::unbounded_channel();
4282- let sample_tx = tx.clone();
4283- let alarm_tx = tx.clone();
4284- let alarm_observer: celld::runtime::AlarmObserver = Arc::new(move |cell, at_ms| {
4285- let _ = alarm_tx.send(Message::AlarmObserved {
4286- cell,
4287- at_ms,
4288- covered: false,
4289- });
4290- });
4291- let (fence_tx, mut fence_rx) = mpsc::unbounded_channel();
4292- let node = std::env::var("CELLD_NODE").unwrap_or_else(|_| random_node_session_id());
4293- let clean_reload_node = node.clone();
4294- celld::control_plane::install_reexec_node_session_id(&node)?;
4295- let probe_public_key = celld::peer_probe::install_signer()?;
4296- let max_activations =
4297- celld::env_vars::positive::<usize>("CELLD_ACTIVATIONS")?.unwrap_or_else(|| {
4298- std::thread::available_parallelism()
4299- .map(usize::from)
4300- .unwrap_or(1)
4301- .min(DEFAULT_MAX_CONCURRENT_ACTIVATIONS)
4302- });
4303- let max_evictions = celld::env_vars::positive::<usize>("CELLD_EVICTIONS")?
4304- .unwrap_or(DEFAULT_MAX_CONCURRENT_EVICTIONS);
4305- let max_releases = celld::env_vars::positive::<usize>("CELLD_RELEASES")?
4306- .unwrap_or(DEFAULT_MAX_CONCURRENT_RELEASES);
4307- let data_dir = std::env::var_os("CELLD_TEST_DATA_DIR")
4308- .or_else(|| std::env::var_os("CELLD_WATCH"))
4309- .map(std::path::PathBuf::from)
4310- .unwrap_or_else(|| std::env::temp_dir().join(format!("celld-{}", std::process::id())));
4311- let mut deploy_agent = None;
4312- let (runtime, ownership, peer_key, wake_scan, assets, asset_script) =
4313- if let Some(bucket) = settings.bucket.clone().filter(|_| settings.load_deployment) {
4314- let client = fleet::bucket_client_with_credentials(
4315- &bucket,
4316- settings.endpoint.as_deref(),
4317- &settings.region,
4318- managed_storage.as_ref(),
4319- )?;
4320- if settings.control_plane {
4321- fleet::validate_managed_bucket(&client).await?;
4322- } else {
4323- fleet::validate_bucket(&client).await?;
4324- }
4325- // The list above proves the bucket answers; it does not prove
4326- // the store enforces the conditional write this node fences
4327- // with. A store that ignores it makes the node self-fence in
4328- // a restart loop, so test it once, here, before serving.
4329- if settings.storage_probe {
4330- fleet::probe_storage_before_serving(&client, settings.control_plane).await?;
4331- }
4332- let lease_client = fleet::lease_bucket_client_with_credentials(
4333- &bucket,
4334- settings.endpoint.as_deref(),
4335- &settings.region,
4336- managed_storage.as_ref(),
4337- )?;
4338- if settings.control_plane {
4339- celld::control_plane::wait_for_initial_deployment(&client).await?;
4340- deploy_agent = Some(client.clone());
4341- }
4342- let peer_key = peer_auth::load_or_create(&client).await?;
4343- let mut deployment = fleet::load_current_worker(&client, node.clone()).await?;
4344- let primary_script = deployment.script_name.clone();
4345- let mut asset_resolvers = HashMap::new();
4346- if let Some(resolver) = deployment.assets.take() {
4347- asset_resolvers.insert(primary_script.clone(), resolver);
4348- }
4349- let mut visited = BTreeSet::from([primary_script.clone()]);
4350- let mut queue = deployment
4351- .services
4352- .iter()
4353- .map(|(_, script, _)| script.clone())
4354- .collect::<VecDeque<_>>();
4355- let mut cohosted = Vec::new();
4356- while let Some(target) = queue.pop_front() {
4357- if target == primary_script || !visited.insert(target.clone()) {
4358- continue;
4359- }
4360- let mut loaded = fleet::load_named_worker(&client, &target, node.clone())
4361- .await
4362- .with_context(|| format!("load service binding target {target}"))?;
4363- if loaded.script_name != target {
4364- anyhow::bail!(
4365- "service pointer {target} resolved script {}",
4366- loaded.script_name
4367- );
4368- }
4369- queue.extend(loaded.services.iter().map(|(_, script, _)| script.clone()));
4370- if let Some(resolver) = loaded.assets.take() {
4371- asset_resolvers.insert(target, resolver);
4372- }
4373- cohosted.push(CohostedWorker {
4374- options: loaded.options,
4375- services: loaded.services,
4376- asset_binding: loaded.asset_binding,
4377- });
4378- }
4379- let wake = Arc::new(celld::wake::WakeFlusher::new());
4380- celld::js::set_arm_gate(ArmGate {
4381- bucket: client.clone(),
4382- flusher: wake.clone(),
4383- });
4384- // celld treats replication as a node service, not as a property
4385- // of today's manifest. Start it even for a stateless deployment
4386- // so a later deployment can introduce cells without changing the
4387- // durability contract underneath the node.
4388- let replication = Some(Replication::start(
4389- client.clone(),
4390- &data_dir,
4391- settings.endpoint.clone(),
4392- settings.region.clone(),
4393- storage_credentials.clone(),
4394- )?);
4395- let asset_script = Some(Arc::<str>::from(primary_script));
4396- let assets = Arc::new(asset_resolvers);
4397- let runtime = RuntimeManager::start(RuntimeOptions {
4398- worker: deployment.options,
4399- services: deployment.services,
4400- asset_binding: deployment.asset_binding,
4401- loader_binding: worker_loader_binding(),
4402- cohosted,
4403- data_dir: data_dir.clone(),
4404- replication,
4405- wake: Some(wake.clone()),
4406- alarm_observer: alarm_observer.clone(),
4407- node: node.clone(),
4408- region: settings.region.clone(),
4409- })?;
4410- let wake_scan = Some((client.clone(), wake.clone()));
4411- let ownership = Ownership::Bucket(Arc::new(
4412- BucketOwnership::new(client, lease_client, node.clone(), probe_public_key.clone())
4413- .with_lease_ttl_ms(lease_ttl_ms_from_environment()),
4414- ));
4415- (
4416- Some(runtime),
4417- Some(ownership),
4418- peer_key,
4419- wake_scan,
4420- assets,
4421- asset_script,
4422- )
4423- } else if let Ok(script_path) = std::env::var("CELLD_TEST_SCRIPT_PATH") {
4424- let source = std::fs::read_to_string(&script_path)?;
4425- let do_classes = std::env::var("CELLD_TEST_DO_CLASSES")
4426- .unwrap_or_default()
4427- .split(',')
4428- .map(str::trim)
4429- .filter(|value| !value.is_empty())
4430- .map(str::to_string)
4431- .collect();
4432- let bindings = std::env::var("CELLD_TEST_DO_BINDINGS")
4433- .unwrap_or_default()
4434- .split(',')
4435- .filter_map(|value| value.split_once('='))
4436- .map(|(name, class)| (name.trim().to_string(), class.trim().to_string()))
4437- .filter(|(name, class)| !name.is_empty() && !class.is_empty())
4438- .collect();
4439- let options = WorkerConfigOptions {
4440- src: source,
4441- script_name: "celld-local".to_string(),
4442- do_classes,
4443- bindings,
4444- r2_bindings: Vec::new(),
4445- ai_binding: fleet::configured_ai_binding(None),
4446- vars: Vec::new(),
4447- node: node.clone(),
4448- modules: Vec::new(),
4449- compat: Compat::default(),
4450- };
4451- let (ownership, peer_key, wake, wake_scan) = match settings.bucket.clone() {
4452- Some(bucket) => {
4453- let client = fleet::bucket_client_with_credentials(
4454- &bucket,
4455- settings.endpoint.as_deref(),
4456- &settings.region,
4457- managed_storage.as_ref(),
4458- )?;
4459- let lease_client = fleet::lease_bucket_client_with_credentials(
4460- &bucket,
4461- settings.endpoint.as_deref(),
4462- &settings.region,
4463- managed_storage.as_ref(),
4464- )?;
4465- let peer_key = peer_auth::load_or_create(&client).await?;
4466- let wake = Arc::new(celld::wake::WakeFlusher::new());
4467- celld::js::set_arm_gate(ArmGate {
4468- bucket: client.clone(),
4469- flusher: wake.clone(),
4470- });
4471- let wake_scan = Some((client.clone(), wake.clone()));
4472- (
4473- Some(Ownership::Bucket(Arc::new(
4474- BucketOwnership::new(
4475- client,
4476- lease_client,
4477- node.clone(),
4478- probe_public_key.clone(),
4479- )
4480- .with_lease_ttl_ms(lease_ttl_ms_from_environment()),
4481- ))),
4482- peer_key,
4483- Some(wake),
4484- wake_scan,
4485- )
4486- }
4487- None => (None, random_peer_key(), None, None),
4488- };
4489- (
4490- Some(RuntimeManager::start(RuntimeOptions {
4491- worker: options,
4492- services: Vec::new(),
4493- asset_binding: None,
4494- loader_binding: worker_loader_binding(),
4495- cohosted: Vec::new(),
4496- data_dir: data_dir.clone(),
4497- replication: None,
4498- wake: wake.clone(),
4499- alarm_observer: alarm_observer.clone(),
4500- node: node.clone(),
4501- region: settings.region.clone(),
4502- })?),
4503- ownership,
4504- peer_key,
4505- wake_scan,
4506- Arc::new(HashMap::new()),
4507- None,
4508- )
4509- } else {
4510- let (ownership, peer_key) = match settings.bucket.clone() {
4511- Some(bucket) => {
4512- let client = fleet::bucket_client_with_credentials(
4513- &bucket,
4514- settings.endpoint.as_deref(),
4515- &settings.region,
4516- managed_storage.as_ref(),
4517- )?;
4518- let lease_client = fleet::lease_bucket_client_with_credentials(
4519- &bucket,
4520- settings.endpoint.as_deref(),
4521- &settings.region,
4522- managed_storage.as_ref(),
4523- )?;
4524- let peer_key = peer_auth::load_or_create(&client).await?;
4525- (
4526- Some(Ownership::Bucket(Arc::new(
4527- BucketOwnership::new(
4528- client,
4529- lease_client,
4530- node.clone(),
4531- probe_public_key.clone(),
4532- )
4533- .with_lease_ttl_ms(lease_ttl_ms_from_environment()),
4534- ))),
4535- peer_key,
4536- )
4537- }
4538- None => (None, random_peer_key()),
4539- };
4540- (
4541- None,
4542- ownership,
4543- peer_key,
4544- None,
4545- Arc::new(HashMap::new()),
4546- None,
4547- )
4548- };
4549- if let Some(config) = &telemetry_config {
4550- let sink_bucket = match config.sink {
4551- celld::telemetry::SinkChoice::Bucket => {
4552- let Some(bucket) = settings.bucket.clone() else {
4553- anyhow::bail!(
4554- "CELLD_OTEL=1 but this node has no bucket; the \
4555- bucket sink needs one (CELLD_BUCKET), or choose \
4556- CELLD_OTEL_SINK=otlp"
4557- );
4558- };
4559- // Its own client even for the fleet bucket: each open is its
4560- // own transport (bucket.rs), so telemetry PUT bursts never
4561- // share a connection pool with ownership traffic.
4562- Some(fleet::bucket_client_with_credentials(
4563- config.bucket_override.as_deref().unwrap_or(&bucket),
4564- settings.endpoint.as_deref(),
4565- &settings.region,
4566- managed_storage.as_ref(),
4567- )?)
4568- }
4569- // The collector path needs no bucket at all.
4570- celld::telemetry::SinkChoice::Otlp => None,
4571- };
4572- celld::telemetry::init(config, sink_bucket, node.clone(), settings.region.clone())?;
4573- }
4574- let peer_auth = Arc::new(PeerAuth::new(peer_key, node.clone())?);
4575- let resume_generation = celld::runtime::take_clean_reload_generation(&data_dir, &node);
4576- let clean_reload_candidate = resume_generation.is_some();
4577- let actor = Actor::from_environment(
4578- AdmissionLimits {
4579- resident: max_resident,
4580- activations: max_activations,
4581- evictions: max_evictions,
4582- releases: max_releases,
4583- },
4584- fail_publish_once,
4585- fence_tx,
4586- runtime.clone(),
4587- ownership,
4588- ActorIdentity {
4589- node: node.clone(),
4590- advertise: advertise.clone(),
4591- region: settings.region.clone(),
4592- managed: settings.control_plane,
4593- },
4594- resume_generation,
4595- )
4596- .await?;
4597- let process_generation = actor.lease_spec.generation.clone();
4598- let ownership_name = actor.ownership.name();
4599- let explorer_replication = runtime.as_ref().and_then(RuntimeManager::replication);
4600- let local_cache_replication = explorer_replication.clone();
4601- let (websocket_tx, mut websocket_rx) = mpsc::unbounded_channel();
4602- let app = AppHandle {
4603- tx,
4604- runtime,
4605- assets,
4606- asset_script,
4607- // Connect-only timeout: a peer request may legitimately run long, but
4608- // a handshake that never completes provably ran nothing, so failing it
4609- // fast lets the caller re-resolve the owner and redispatch.
4610- peer_http: reqwest::Client::builder()
4611- .connect_timeout(PEER_CONNECT_TIMEOUT)
4612- .build()
4613- .unwrap(),
4614- peer_auth,
4615- advertise: advertise.clone(),
4616- websockets: websocket_tx,
4617- draining: Arc::new(std::sync::atomic::AtomicBool::new(false)),
4618- trust_forwarded_headers: settings.trust_forwarded_headers,
4619- // RPO=0 is the default. An operator can disable the output gate to
4620- // remove object-store replication latency from the write response,
4621- // explicitly accepting that an acknowledged write can be lost.
4622- output_gate: celld::env_vars::flag("CELLD_OUTPUT_GATE", true)?,
4623- max_outbound_websockets: celld::env_vars::positive_or(
4624- "CELLD_MAX_OUTBOUND_WEBSOCKETS",
4625- DEFAULT_MAX_OUTBOUND_WEBSOCKETS,
4626- )?,
4627- };
4628- let (do_call_tx, mut do_call_rx) = mpsc::unbounded_channel();
4629- celld::js::set_do_call_tx(do_call_tx);
4630- let (gate_tx, mut gate_rx) = mpsc::unbounded_channel();
4631- celld::js::set_gate_tx(gate_tx);
4632- let (rpc_call_tx, mut rpc_call_rx) = mpsc::unbounded_channel();
4633- celld::js::set_rpc_call_tx(rpc_call_tx);
4634- let (service_call_tx, mut service_call_rx) = mpsc::unbounded_channel();
4635- celld::js::set_svc_call_tx(service_call_tx);
4636- let (service_rpc_tx, mut service_rpc_rx) = mpsc::unbounded_channel();
4637- celld::js::set_svc_rpc_tx(service_rpc_tx);
4638- let (asset_call_tx, mut asset_call_rx) = mpsc::unbounded_channel();
4639- celld::js::set_asset_call_tx(asset_call_tx);
4640- let (outbound_ws_tx, mut outbound_ws_rx) = mpsc::unbounded_channel();
4641- celld::js::set_outbound_ws_tx(outbound_ws_tx);
4642- // The core is a serial ownership actor, not a Worker executor. It owns the
4643- // node lease timer, so ingress, proxy retries, and restore completions must
4644- // not consume every scheduler turn it needs. Its isolated single-thread
4645- // runtime also keeps state transitions ordered exactly as the deterministic
4646- // executor models them. Request work, restores, and blocking scans stay on
4647- // the shared runtime and report their results back as messages.
4648- let (actor_exit_tx, mut actor_exit_rx) = mpsc::unbounded_channel();
4649- std::thread::Builder::new()
4650- .name("celld-core".into())
4651- .spawn(move || {
4652- let result = tokio::runtime::Builder::new_current_thread()
4653- .enable_all()
4654- .build()
4655- .map_err(|error| error.to_string())
4656- .map(|runtime| runtime.block_on(actor.run(rx)));
4657- let _ = actor_exit_tx.send(result);
4658- })?;
4659-
4660- // The sampler is a plain ticker: it measures and posts, and decides
4661- // nothing. Everything downstream of the numbers -- the latch, the target,
4662- // which cell goes -- is in the core, so a sample sequence replays.
4663- {
4664- const LOAD_SAMPLE_PERIOD: std::time::Duration = std::time::Duration::from_secs(1);
4665- tokio::spawn(async move {
4666- let mut tick = tokio::time::interval(LOAD_SAMPLE_PERIOD);
4667- tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
4668- loop {
4669- tick.tick().await;
4670- if sample_tx.send(Message::SampleLoad).is_err() {
4671- return;
4672- }
4673- }
4674- });
4675- }
4676-
4677- if let Some((client, wake)) = wake_scan {
4678- let authority_wait_seconds = if clean_reload_candidate { 60 } else { 10 };
4679- let deadline = Instant::now() + std::time::Duration::from_secs(authority_wait_seconds);
4680- while !app.healthy().await {
4681- if Instant::now() >= deadline {
4682- anyhow::bail!("node authority was not established before wake scan");
4683- }
4684- tokio::time::sleep(std::time::Duration::from_millis(10)).await;
4685- }
4686- for (cell, due_ms) in celld::wake::due_scan(&client, now_ms() as i64).await {
4687- wake.adopt(&cell, due_ms);
4688- let _ = app.tx.send(Message::WakeHint { cell });
4689- }
4690-
4691- // And again, on a timer, for the rest of the process's life.
4692- //
4693- // The boot scan alone only covers alarms that came due while nothing
4694- // was watching *before this node started*. A node that dies while
4695- // this one is already running leaves its cells with armed alarms and
4696- // no owner, and nothing would look at them again until this process
4697- // restarted -- an alarm silently not firing, which is the one thing a
4698- // Durable Object is not allowed to do.
4699- //
4700- // Every decision about a due entry stays in the core: a hint for a
4701- // cell this node already serves is ignored, and one for a cell with a
4702- // live owner elsewhere resolves to that owner rather than stealing
4703- // it. The scan only reports what the bucket says is due.
4704- let scan_app = app.clone();
4705- let waker_node = node.clone();
4706- let tick_ms = celld::env_vars::positive::<u64>("CELLD_WAKER_TICK_MS")?.unwrap_or(60_000);
4707- let period = std::time::Duration::from_millis(tick_ms);
4708- tokio::spawn(async move {
4709- let mut tick = tokio::time::interval(period);
4710- tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
4711- tick.tick().await;
4712- let mut dead_node_gc = celld::dead_node_gc::DeadNodeGc::default();
4713- loop {
4714- tick.tick().await;
4715- dead_node_gc
4716- .run_elected_pass(&client, &waker_node, tick_ms)
4717- .await;
4718- for (cell, due_ms) in celld::wake::due_scan(&client, now_ms() as i64).await {
4719- wake.adopt(&cell, due_ms);
4720- if scan_app.tx.send(Message::WakeHint { cell }).is_err() {
4721- return;
4722- }
4723- }
4724- }
4725- });
4726- }
4727-
4728- if let Some(client) = deploy_agent {
4729- celld::control_plane::start_deploy_agent(client.clone(), Arc::new(AtomicBool::new(true)));
4730- let presence_app = app.clone();
4731- celld::control_plane::start_presence_agent(celld::control_plane::PresenceRuntime {
4732- s3: client,
4733- replication: explorer_replication,
4734- node_session_id: node,
4735- advertise,
4736- listen,
4737- credential_version: adapter_credential_version
4738- .expect("managed adapters have a credential version"),
4739- snapshot: Arc::new(move || {
4740- let app = presence_app.clone();
4741- Box::pin(async move { app.presence().await })
4742- }),
4743- });
4744- }
4745-
4746- println!(
4747- "celld listening on {} (ownership={ownership_name})",
4748- listener.local_addr()?
4749- );
4750- println!(
4751- "celld internal listening on {} (advertise={})",
4752- internal_listener.local_addr()?,
4753- app.advertise
4754- );
4755- let (shutdown_tx, mut shutdown_rx) = mpsc::unbounded_channel();
4756- // A SIGTERM (systemd stop, `docker stop`, a Kubernetes pod delete) or a
4757- // SIGINT begins the same graceful shutdown as `POST /shutdown`, so the
4758- // orchestrator's ordinary stop drains and hands off instead of killing.
4759- let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
4760- let mut sigint = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())?;
4761- let (connection_drain_tx, connection_drain) = watch::channel(false);
4762- let drain_ms: u64 = celld::env_vars::positive("CELLD_SHUTDOWN_DRAIN_MS")?.unwrap_or(25_000);
4763- // A hung connection must not consume the whole preserve budget: the
4764- // semantic drain and the clean-reload certificate come out of the same
4765- // deadline.
4766- let connection_grace =
4767- CONNECTION_DRAIN_GRACE.min(std::time::Duration::from_millis(drain_ms / 4));
4768- let mut connections: FuturesUnordered<ConnectionFuture> = FuturesUnordered::new();
4769- let mut do_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new();
4770- let mut gate_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new();
4771- let mut service_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new();
4772- let mut asset_calls: FuturesUnordered<AssetCallFuture> = FuturesUnordered::new();
4773- let mut websockets: FuturesUnordered<WebSocketFuture> = FuturesUnordered::new();
4774- let mut cache_prunes: FuturesUnordered<CachePruneFuture> = FuturesUnordered::new();
4775- let mut replication_health = tokio::time::interval(std::time::Duration::from_millis(250));
4776- let mut local_cache_prune = tokio::time::interval_at(
4777- tokio::time::Instant::now() + LOCAL_CACHE_PRUNE_PERIOD,
4778- LOCAL_CACHE_PRUNE_PERIOD,
4779- );
4780- local_cache_prune.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
4781- let shutdown_mode = loop {
4782- tokio::select! {
4783- connection = listener.accept() => {
4784- let (stream, _) = connection?;
4785- connections.push(serve_http_connection(
4786- stream,
4787- HttpSurface::Public,
4788- app.clone(),
4789- shutdown_tx.clone(),
4790- connection_drain.clone(),
4791- connection_grace,
4792- ));
4793- }
4794- connection = internal_listener.accept() => {
4795- let (stream, _) = connection?;
4796- connections.push(serve_http_connection(
4797- stream,
4798- HttpSurface::Internal,
4799- app.clone(),
4800- shutdown_tx.clone(),
4801- connection_drain.clone(),
4802- connection_grace,
4803- ));
4804- }
4805- Some(()) = connections.next(), if !connections.is_empty() => {}
4806- call = do_call_rx.recv() => {
4807- let Some(call) = call else {
4808- anyhow::bail!("Durable Object call channel closed");
4809- };
4810- do_calls.push(Box::pin(dispatch_do_call(app.clone(), call)));
4811- }
4812- Some(()) = do_calls.next(), if !do_calls.is_empty() => {}
4813- req = gate_rx.recv() => {
4814- let Some(req) = req else {
4815- anyhow::bail!("output-gate channel closed");
4816- };
4817- gate_calls.push(Box::pin(dispatch_gate(app.clone(), req)));
4818- }
4819- Some(()) = gate_calls.next(), if !gate_calls.is_empty() => {}
4820- call = service_call_rx.recv() => {
4821- let Some(call) = call else {
4822- anyhow::bail!("service call channel closed");
4823- };
4824- service_calls.push(Box::pin(dispatch_service_call(app.clone(), call)));
4825- }
4826- call = service_rpc_rx.recv() => {
4827- let Some(call) = call else {
4828- anyhow::bail!("service RPC channel closed");
4829- };
4830- service_calls.push(Box::pin(dispatch_service_rpc(app.clone(), call)));
4831- }
4832- Some(()) = service_calls.next(), if !service_calls.is_empty() => {}
4833- call = rpc_call_rx.recv() => {
4834- let Some(call) = call else {
4835- anyhow::bail!("Durable Object RPC channel closed");
4836- };
4837- do_calls.push(Box::pin(dispatch_rpc_call(app.clone(), call)));
4838- }
4839- call = asset_call_rx.recv() => {
4840- let Some(call) = call else {
4841- anyhow::bail!("asset call channel closed");
4842- };
4843- asset_calls.push(Box::pin(dispatch_asset_call(app.clone(), call)));
4844- }
4845- Some(()) = asset_calls.next(), if !asset_calls.is_empty() => {}
4846- socket = websocket_rx.recv() => {
4847- let Some(socket) = socket else {
4848- anyhow::bail!("WebSocket channel closed");
4849- };
4850- websockets.push(socket);
4851- }
4852- Some(()) = websockets.next(), if !websockets.is_empty() => {}
4853- _ = local_cache_prune.tick(), if local_cache_replication.is_some()
4854- && local_cache_max_bytes.is_some() && cache_prunes.is_empty() => {
4855- let replication = local_cache_replication.clone().unwrap();
4856- let max_bytes = local_cache_max_bytes.unwrap();
4857- cache_prunes.push(Box::pin(async move {
4858- let result = tokio::task::spawn_blocking(move || {
4859- replication.prune_local_cache(max_bytes)
4860- }).await;
4861- (max_bytes, result)
4862- }));
4863- }
4864- Some((max_bytes, result)) = cache_prunes.next(), if !cache_prunes.is_empty() => {
4865- match result {
4866- Ok((kept, evicted, bytes)) if evicted > 0 => {
4867- tracing::info!(
4868- event = "local_cache_pruned",
4869- kept,
4870- evicted,
4871- bytes,
4872- max_bytes,
4873- "pruned least-recently-used eviction snapshots"
4874- );
4875- }
4876- Ok(_) => {}
4877- Err(error) => {
4878- tracing::warn!(%error, "local cache pruning task failed");
4879- }
4880- }
4881- }
4882- outbound = outbound_ws_rx.recv() => {
4883- let Some(outbound) = outbound else {
4884- anyhow::bail!("outbound WebSocket channel closed");
4885- };
4886- let app = app.clone();
4887- websockets.push(Box::pin(async move {
4888- if let Err(error) = outbound_websocket_task(app, outbound).await {
4889- eprintln!("celld outbound WebSocket failed: {error:#}");
4890- }
4891- }));
4892- }
4893- mode = shutdown_rx.recv() => break mode.unwrap_or(ShutdownMode::Handoff),
4894- _ = sigterm.recv() => break ShutdownMode::Handoff,
4895- _ = sigint.recv() => break ShutdownMode::Handoff,
4896- code = fence_rx.recv() => {
4897- exit_flushed(code.unwrap_or(3));
4898- }
4899- actor_exit = actor_exit_rx.recv() => {
4900- let error = match actor_exit {
4901- Some(Err(error)) => error,
4902- Some(Ok(())) => "the core actor stopped unexpectedly".to_string(),
4903- None => "the core actor thread panicked".to_string(),
4904- };
4905- tracing::error!(
4906- event = "core_actor_exit",
4907- %error,
4908- "SELF-FENCE: the core actor exited unexpectedly"
4909- );
4910- exit_flushed(3);
4911- }
4912- _ = replication_health.tick() => {
4913- if let Some(runtime) = &app.runtime {
4914- match runtime.replication_status() {
4915- Ok(None) => {}
4916- Ok(Some(status)) => {
4917- eprintln!("SELF-FENCE: replication process exited unexpectedly: {status}");
4918- exit_flushed(3);
4919- }
4920- Err(error) => {
4921- eprintln!("SELF-FENCE: replication process health check failed: {error}");
4922- exit_flushed(3);
4923- }
4924- }
4925- }
4926- }
4927- }
4928- };
4929- // Graceful shutdown. Report unhealthy so a load balancer sheds this node,
4930- // and refuse new work. Keep accepting bounded health and diagnostic
4931- // requests while the semantic drain runs. A node removal hands every
4932- // resident cell to a peer. A planned same-node replacement preserves
4933- // ownership and its local replica cache, so the replacement does not
4934- // create a fleet-wide cold handoff or lasting skew.
4935- app.draining
4936- .store(true, std::sync::atomic::Ordering::Relaxed);
4937- let _ = connection_drain_tx.send(true);
4938- // Receivers cloned from `connection_drain` have already observed an old
4939- // version, so `changed()` would close each newly accepted connection
4940- // before it could send a diagnostic response. Give drain-time connections
4941- // their own signal. They are deliberately absent from `shell_drained`: an
4942- // incomplete health request must not prevent a clean reload certificate.
4943- let (drain_connection_tx, drain_connection) = watch::channel(false);
4944- let mut drain_connections: FuturesUnordered<ConnectionFuture> = FuturesUnordered::new();
4945- if shutdown_mode == ShutdownMode::Handoff {
4946- let _ = app.tx.send(Message::ReleaseAll);
4947- } else {
4948- let _ = app.tx.send(Message::BeginPreserve);
4949- }
4950- let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(drain_ms);
4951- let mut handoff = tokio::time::interval(std::time::Duration::from_millis(50));
4952- let drained = loop {
4953- let shell_drained = connections.is_empty()
4954- && do_calls.is_empty()
4955- && gate_calls.is_empty()
4956- && service_calls.is_empty()
4957- && asset_calls.is_empty()
4958- && websockets.is_empty();
4959- // The actor can be busy driving an immediate-effect failure loop, so
4960- // a status request is not itself allowed to bypass the drain deadline.
4961- let core_drained = if shell_drained {
4962- tokio::time::timeout(std::time::Duration::from_millis(50), app.drain_status())
4963- .await
4964- .is_ok_and(|status| match shutdown_mode {
4965- ShutdownMode::Handoff => status.occupied == 0 && status.releasing == 0,
4966- ShutdownMode::Preserve => status.activating == 0 && status.evicting == 0,
4967- })
4968- } else {
4969- false
4970- };
4971- if shell_drained && core_drained {
4972- break true;
4973- }
4974- tokio::select! {
4975- _ = tokio::time::sleep_until(deadline) => break false,
4976- _ = handoff.tick() => {}
4977- connection = listener.accept() => {
4978- let (stream, _) = connection?;
4979- drain_connections.push(serve_http_connection(
4980- stream,
4981- HttpSurface::Public,
4982- app.clone(),
4983- shutdown_tx.clone(),
4984- drain_connection.clone(),
4985- connection_grace,
4986- ));
4987- }
4988- connection = internal_listener.accept() => {
4989- let (stream, _) = connection?;
4990- drain_connections.push(serve_http_connection(
4991- stream,
4992- HttpSurface::Internal,
4993- app.clone(),
4994- shutdown_tx.clone(),
4995- drain_connection.clone(),
4996- connection_grace,
4997- ));
4998- }
4999- Some(_) = drain_connections.next(), if !drain_connections.is_empty() => {}
5000- Some(_) = connections.next(), if !connections.is_empty() => {}
5001- Some(_) = do_calls.next(), if !do_calls.is_empty() => {}
5002- Some(_) = gate_calls.next(), if !gate_calls.is_empty() => {}
5003- Some(_) = service_calls.next(), if !service_calls.is_empty() => {}
5004- Some(_) = asset_calls.next(), if !asset_calls.is_empty() => {}
5005- Some(_) = websockets.next(), if !websockets.is_empty() => {}
5006- }
5007- };
5008- let _ = drain_connection_tx.send(true);
5009- if !drained && shutdown_mode == ShutdownMode::Handoff {
5010- match tokio::time::timeout(
5011- std::time::Duration::from_millis(50),
5012- app.drain_status(),
5013- )
5014- .await
5015- {
5016- Ok(status) => eprintln!(
5017- "celld shutdown drain reached its {drain_ms}ms deadline: occupied={} activating={} evicting={} releasing={}",
5018- status.occupied, status.activating, status.evicting, status.releasing
5019- ),
5020- Err(_) => eprintln!(
5021- "celld shutdown drain reached its {drain_ms}ms deadline: core status unavailable"
5022- ),
5023- }
5024- } else if !drained {
5025- eprintln!(
5026- "celld preserve drain reached its {drain_ms}ms deadline: connections={} do_calls={} gate_calls={} service_calls={} asset_calls={} websockets={}",
5027- connections.len(),
5028- do_calls.len(),
5029- gate_calls.len(),
5030- service_calls.len(),
5031- asset_calls.len(),
5032- websockets.len(),
5033- );
5034- }
5035- if drained && shutdown_mode == ShutdownMode::Preserve {
5036- let prepared = match (&app.runtime, app.presence().await) {
5037- (Some(runtime), Some(presence)) => {
5038- let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
5039- tokio::time::timeout(remaining, runtime.prepare_clean_reload(&presence.cells)).await
5040- }
5041- _ => Ok(Err(anyhow::anyhow!(
5042- "clean reload requires a runtime and a resident snapshot"
5043- ))),
5044- };
5045- match prepared {
5046- Ok(Ok(pruned)) if app.healthy().await => {
5047- match celld::runtime::write_clean_reload_marker(
5048- &data_dir,
5049- &clean_reload_node,
5050- &process_generation,
5051- ) {
5052- Ok(()) => tracing::info!(
5053- event = "clean_reload_prepared",
5054- stale_live_databases_pruned = pruned,
5055- "prepared local cells for an exact-generation reload"
5056- ),
5057- Err(error) => tracing::warn!(
5058- event = "clean_reload_abandoned",
5059- %error,
5060- "could not publish the clean local reload certificate"
5061- ),
5062- }
5063- }
5064- Ok(Ok(_)) => tracing::warn!(
5065- event = "clean_reload_abandoned",
5066- "node authority was lost while local cells were closing"
5067- ),
5068- Ok(Err(error)) => tracing::warn!(
5069- event = "clean_reload_abandoned",
5070- %error,
5071- "local reload preparation failed; replacement will use normal recovery"
5072- ),
5073- Err(_) => tracing::warn!(
5074- event = "clean_reload_abandoned",
5075- "local reload preparation exceeded the shutdown deadline"
5076- ),
5077- }
5078- }
5079- // Exit without unwinding. Returning from here drops the tokio runtime
5080- // and the V8 platform underneath tasks and isolates that are still
5081- // alive -- on a deadline-cut drain that teardown segfaults (status 139
5082- // observed fleet-wide, 2026-08-10). Nothing below needs a destructor:
5083- // every release the drain completed proved durability first, and a
5084- // cell the deadline cut off keeps its owner record exactly as a kill
5085- // would have left it.
5086- exit_flushed(0);
5087-}
5088-
5089-#[path = "main/machine.rs"]
5090-mod machine;
5091-use machine::{
5092- lease_ttl_ms_from_environment, local_cache_max_bytes_from_environment,
5093- ownership_on_evict_from_environment, pressure_config_from_environment, random_node_session_id,
5094- random_peer_key, random_process_generation, ProcessLoadSampler,
5095- DEFAULT_MAX_OUTBOUND_WEBSOCKETS, PEER_CONNECT_TIMEOUT,
3+// The binary is now connection, startup, shutdown, and V8 shell code. The
4+// World boundary lives in the library Actor and its domain-routed adapters.
5+#![allow(clippy::disallowed_macros, clippy::disallowed_methods)]
6+
7+//! Runnable celld vertical slice.
8+//!
9+//! One actor serializes every event through `celld-logic`; the actor polls its
10+//! mailbox, timers, and in-flight effect futures together. This is the
11+//! execution shape required for monotonic lease ticks to fence the node even
12+//! when a storage operation remains hung, without spawning a task per effect.
13+
14+use anyhow::Context as _;
15+use base64::Engine as _;
16+use celld::actor::*;
17+use celld::fleet;
18+use celld::js::{
19+ ArmGate, AssetCallReq, Compat, DoCallReq, HttpResponse, RpcCallReq, SvcCallReq, SvcRpcReq,
20+ WorkerConfigOptions,
21+};
22+use celld::ownership_store::{now_ms, BucketOwnership};
23+use celld::peer_auth::{self, PeerAuth};
24+use celld::runtime::{CohostedWorker, Replication, RuntimeFetch, RuntimeManager, RuntimeOptions};
25+use celld_logic::{RequestError, Route, WebSocketKind};
26+use futures_util::stream::{FuturesUnordered, StreamExt};
27+use http_body_util::combinators::UnsyncBoxBody;
28+use http_body_util::{BodyExt, Full, StreamBody};
29+use hyper::body::{Bytes, Frame, Incoming};
30+use hyper::server::conn::http1;
31+use hyper::service::service_fn;
32+use hyper::{Request, Response, StatusCode};
33+use hyper_util::rt::TokioIo;
34+use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
35+use std::convert::Infallible;
36+use std::sync::atomic::AtomicBool;
37+use std::sync::Arc;
38+use std::time::Instant;
39+use tokio::sync::{mpsc, oneshot, watch};
40+
41+// glibc's malloc serializes its arenas behind futexes, and under load the
42+// sixteen worker threads spent up to half a millisecond blocked per
43+// acquisition. On a 16-core host jemalloc measured 20% more hello-world
44+// throughput than glibc (mimalloc 11%), and returned the ~7% of the machine
45+// that arena-lock sleeps reported as idle.
46+#[global_allocator]
47+static ALLOC: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
48+
49+/// Let an admitted HTTP request finish, then close the transport even when a
50+/// response stream or a client keep-alive does not settle. The semantic drain
51+/// continues after this bound, so durability and resident activity still use
52+/// the complete shutdown grace.
53+const CONNECTION_DRAIN_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
54+
55+/// The lossy stdout writer's flush handle. Every exit path uses
56+/// `std::process::exit`, which skips destructors — but the last lines before
57+/// an exit are the fence forensics, exactly the lines that must survive.
58+static LOG_GUARD: std::sync::Mutex<Option<tracing_appender::non_blocking::WorkerGuard>> =
59+ std::sync::Mutex::new(None);
60+
61+fn exit_flushed(code: i32) -> ! {
62+ drop(LOG_GUARD.lock().unwrap().take());
63+ std::process::exit(code);
64+}
65+
66+type HttpReply = Response<UnsyncBoxBody<Bytes, std::io::Error>>;
67+
68+const STALE_ROUTE_HEADER: &str = "x-cells-route-error";
69+const STALE_ROUTE_VALUE: &str = "stale-owner";
70+const DURABLE_OBJECT_ROUTING_ERROR_MARKER: &str = "__CELLD_DO_ROUTING_ERROR__:";
71+
72+fn owner_unreachable(scope: &str, owner: &str, source: anyhow::Error) -> anyhow::Error {
73+ // Record how the attempt failed, not just that it did. `connect` is the
74+ // one that decides whether a retry is safe -- a request that never left
75+ // this node may be re-sent, a truncated read may not, because the owner
76+ // already ran it. Without these an operator cannot tell an unreachable
77+ // peer from one that answered badly, and neither can a bug report.
78+ let transport = source.downcast_ref::<reqwest::Error>();
79+ let cause = source
80+ .source()
81+ .map(ToString::to_string)
82+ .unwrap_or_else(|| source.to_string());
83+ tracing::warn!(
84+ %scope,
85+ %owner,
86+ error = %source,
87+ %cause,
88+ connect = transport.is_some_and(reqwest::Error::is_connect),
89+ timeout = transport.is_some_and(reqwest::Error::is_timeout),
90+ request = transport.is_some_and(reqwest::Error::is_request),
91+ body = transport.is_some_and(reqwest::Error::is_body),
92+ decode = transport.is_some_and(reqwest::Error::is_decode),
93+ "peer owner unreachable"
94+ );
95+ let detail = serde_json::json!({
96+ "scope": scope,
97+ "owner": owner,
98+ });
99+ source.context(format!("{DURABLE_OBJECT_ROUTING_ERROR_MARKER}{detail}"))
100+}
101+
102+fn response(status: StatusCode, body: impl Into<Bytes>) -> HttpReply {
103+ Response::builder()
104+ .status(status)
105+ .header("content-type", "application/json")
106+ .body(
107+ Full::new(body.into())
108+ .map_err(|never| match never {})
109+ .boxed_unsync(),
110+ )
111+ .expect("static HTTP response")
112+}
113+
114+fn asset_response(response: axum::response::Response) -> HttpReply {
115+ response.map(|body| body.map_err(std::io::Error::other).boxed_unsync())
116+}
117+
118+fn peer_response(mut response: HttpReply) -> HttpReply {
119+ response.headers_mut().insert(
120+ hyper::header::HeaderName::from_static(peer_auth::RESPONSE_VERSION_HEADER),
121+ hyper::header::HeaderValue::from_static(peer_auth::PROTOCOL_VERSION_TEXT),
122+ );
123+ response
124+}
125+
126+fn runtime_response(worker_response: celld::js::HttpResponse) -> HttpReply {
127+ let Ok(status) = StatusCode::from_u16(worker_response.status) else {
128+ return response(StatusCode::INTERNAL_SERVER_ERROR, "invalid Worker status");
129+ };
130+ let mut builder = Response::builder().status(status);
131+ for (name, value) in worker_response.headers {
132+ if matches!(
133+ name.to_ascii_lowercase().as_str(),
134+ "connection" | "content-length" | "transfer-encoding"
135+ ) {
136+ continue;
137+ }
138+ builder = builder.header(name, value);
139+ }
140+ let body = match worker_response.stream {
141+ Some(stream) => {
142+ let chunks = stream.map(|chunk| {
143+ chunk
144+ .map(|bytes| Frame::data(Bytes::from(bytes)))
145+ .map_err(std::io::Error::other)
146+ });
147+ StreamBody::new(chunks).boxed_unsync()
148+ }
149+ None => Full::new(Bytes::from(worker_response.body))
150+ .map_err(|never| match never {})
151+ .boxed_unsync(),
152+ };
153+ builder
154+ .body(body)
155+ .unwrap_or_else(|_| response(StatusCode::INTERNAL_SERVER_ERROR, "invalid Worker headers"))
156+}
157+
158+fn peer_runtime_response(worker_response: celld::js::HttpResponse) -> HttpReply {
159+ let wire_status = if worker_response.status == 101 && worker_response.ws.is_some() {
160+ StatusCode::OK
161+ } else {
162+ let Ok(status) = StatusCode::from_u16(worker_response.status) else {
163+ return peer_response(response(
164+ StatusCode::INTERNAL_SERVER_ERROR,
165+ "invalid Worker status",
166+ ));
167+ };
168+ status
169+ };
170+ let mut builder = Response::builder().status(wire_status);
171+ for (name, value) in worker_response.headers {
172+ if matches!(
173+ name.to_ascii_lowercase().as_str(),
174+ "connection" | "content-length" | "transfer-encoding"
175+ ) {
176+ continue;
177+ }
178+ builder = builder.header(name, value);
179+ }
180+ if let Some(target) = worker_response.ws {
181+ if let Ok(value) = serde_json::to_string(&target) {
182+ builder = builder.header("x-celld-ws-target", value);
183+ }
184+ }
185+ // Say whether this body is streamed. The peer reads an unmarked body
186+ // rather than handing it on, so without this every response looked
187+ // buffered and streaming was off across the hop.
188+ if worker_response.stream.is_some() {
189+ builder = builder.header("x-celld-body-stream", "1");
190+ }
191+ let body = match worker_response.stream {
192+ Some(stream) => {
193+ let stream = stream.map(|chunk| {
194+ chunk
195+ .map(|bytes| Frame::data(Bytes::from(bytes)))
196+ .map_err(std::io::Error::other)
197+ });
198+ StreamBody::new(stream).boxed_unsync()
199+ }
200+ None => Full::new(Bytes::from(worker_response.body))
201+ .map_err(|never| match never {})
202+ .boxed_unsync(),
203+ };
204+ peer_response(builder.body(body).expect("Worker peer response"))
205+}
206+
207+#[derive(Debug)]
208+struct StalePeerRoute {
209+ scope: String,
210+}
211+
212+impl std::fmt::Display for StalePeerRoute {
213+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
214+ write!(formatter, "peer no longer owns {}", self.scope)
215+ }
216+}
217+
218+impl std::error::Error for StalePeerRoute {}
219+
220+#[derive(Debug)]
221+struct RoutedRequestError(RequestError);
222+
223+impl std::fmt::Display for RoutedRequestError {
224+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
225+ write!(formatter, "route failed: {:?}", self.0)
226+ }
227+}
228+
229+impl std::error::Error for RoutedRequestError {}
230+
231+fn classify_remote_attempt(error: &anyhow::Error) -> celld_logic::routing::Attempt {
232+ if error.downcast_ref::<StalePeerRoute>().is_some() {
233+ celld_logic::routing::Attempt::NotOwner
234+ } else if error
235+ .downcast_ref::<reqwest::Error>()
236+ .is_some_and(reqwest::Error::is_connect)
237+ {
238+ celld_logic::routing::Attempt::NeverConnected
239+ } else {
240+ celld_logic::routing::Attempt::Ambiguous
241+ }
242+}
243+
244+struct WebSocketRouteTiming {
245+ started: Instant,
246+ route_resolution_us: u64,
247+ dispatch_us: u64,
248+ attempts: u8,
249+}
250+
251+impl WebSocketRouteTiming {
252+ fn emit(
253+ &self,
254+ app: &AppHandle,
255+ scope: &str,
256+ request_id: Option<celld::js::RequestId>,
257+ outcome: &str,
258+ route: &str,
259+ peer_node: &str,
260+ ) {
261+ let request_id = request_id
262+ .map(celld::js::request_id_string)
263+ .unwrap_or_default();
264+ let (node, region) = app
265+ .runtime
266+ .as_ref()
267+ .map_or(("", ""), |runtime| (runtime.node(), runtime.region()));
268+ tracing::debug!(
269+ target: "timing",
270+ event = "websocket_route_timing",
271+ outcome,
272+ route,
273+ peer_node,
274+ scope,
275+ request_id,
276+ node,
277+ region,
278+ runtime_version = env!("CARGO_PKG_VERSION"),
279+ attempts = self.attempts,
280+ total_us = self.started.elapsed().as_micros() as u64,
281+ route_resolution_us = self.route_resolution_us,
282+ dispatch_us = self.dispatch_us,
283+ "WebSocket cell request resolved"
284+ );
285+ }
286+}
287+
288+/// The output gate for the co-hosted (same-isolate) Durable Object fast path.
289+/// That path runs a resident DO's `fetch` inline, bypassing `dispatch_do_call`;
290+/// when it writes, the inline handler calls here to hold its response until the
291+/// cell is durable. Reuses the routed machinery: `request` pins the cell (no
292+/// eviction mid-wait) and `gate_write` drives the core gate. `Ok` releases the
293+/// inline response; `Err` breaks the call, as a routed gate failure would.
294+async fn dispatch_gate(app: AppHandle, req: celld::js::GateReq) {
295+ if !app.output_gate {
296+ let _ = req.reply.send(Ok(()));
297+ return;
298+ }
299+ let routed = match app.request(req.scope.clone()).await {
300+ Ok(routed) => routed,
301+ Err(error) => {
302+ let _ = req.reply.send(Err(error));
303+ return;
304+ }
305+ };
306+ // The guard pins the cell and releases the request on drop, so the else
307+ // branch does not leak the just-acquired request.
308+ let _activity = app.activity(routed.request, req.scope.clone());
309+ let result = if routed.route == Route::Local {
310+ app.gate_output(routed.request, req.position).await
311+ } else {
312+ // The owning isolate should route the cell locally; if it moved off the
313+ // node mid-call, fail closed rather than acknowledge an unproven write.
314+ Err(RequestError::NodeFenced)
315+ };
316+ let _ = req.reply.send(result);
317+}
318+
319+/// Call the reserved cron cell's arm endpoint, through the ordinary Durable
320+/// Object routing path so ownership resolution and remote forwarding are the
321+/// ones every other call gets.
322+async fn arm_cron_schedule(app: AppHandle, cell: String) -> anyhow::Result<()> {
323+ let (reply, receive) = tokio::sync::oneshot::channel();
324+ dispatch_do_call(
325+ app,
326+ DoCallReq {
327+ request_id: None,
328+ cancel: None,
329+ deliver_abort_to_handler: false,
330+ scope: cell,
331+ name: None,
332+ url: "https://cron.celld.internal/arm".to_string(),
333+ method: "POST".to_string(),
334+ body: Vec::new(),
335+ headers: Vec::new(),
336+ reply,
337+ order: None,
338+ parent: None,
339+ },
340+ )
341+ .await;
342+ let response = receive.await.context("cron arm dispatch dropped")??;
343+ if !(200..300).contains(&response.status) {
344+ anyhow::bail!("cron arm returned status {}", response.status);
345+ }
346+ Ok(())
347+}
348+
349+async fn dispatch_do_call(app: AppHandle, call: DoCallReq) {
350+ let DoCallReq {
351+ request_id,
352+ cancel,
353+ deliver_abort_to_handler,
354+ scope,
355+ name,
356+ url,
357+ method,
358+ body,
359+ headers,
360+ reply,
361+ order,
362+ parent,
363+ } = call;
364+ let mut cancel = cancel;
365+ let mut order = order;
366+ let mut websocket_timing = headers
367+ .iter()
368+ .any(|(name, value)| {
369+ name.eq_ignore_ascii_case("upgrade") && value.eq_ignore_ascii_case("websocket")
370+ })
371+ .then(|| WebSocketRouteTiming {
372+ started: Instant::now(),
373+ route_resolution_us: 0,
374+ dispatch_us: 0,
375+ attempts: 0,
376+ });
377+ let operation = async {
378+ anyhow::ensure!(
379+ celld_logic::cell::valid_cell_scope(&scope),
380+ "cell scope is malformed or exceeds the fleet storage limit"
381+ );
382+ let mut dispatcher = celld_logic::routing::Dispatcher::default();
383+ loop {
384+ if let Some(timing) = websocket_timing.as_mut() {
385+ timing.attempts = timing.attempts.saturating_add(1);
386+ }
387+ let route_started = Instant::now();
388+ // A disconnect before routing completes has executed no handler,
389+ // so cancel the core request and release its activation admission.
390+ // Once routing completes, the same signal moves into the local or
391+ // remote dispatch below and aborts work that did start.
392+ let route = app.request(scope.clone());
393+ let routed = if deliver_abort_to_handler {
394+ // Workerd delivers an explicit JavaScript AbortSignal to the
395+ // target request. Resolve the route first, then give the
396+ // already-fired receiver to fetch_cell so the handler sees
397+ // request.signal and its waitUntil work can continue.
398+ route.await
399+ } else {
400+ match cancel.as_mut() {
401+ Some(cancel) => celld::asyncrt::select! {
402+ _ = cancel => break Err(anyhow::anyhow!("Durable Object call cancelled")),
403+ routed = route => routed,
404+ },
405+ None => route.await,
406+ }
407+ };
408+ let routed = match routed {
409+ Ok(routed) => routed,
410+ Err(error) => {
411+ if let Some(timing) = websocket_timing.as_mut() {
412+ timing.route_resolution_us = timing
413+ .route_resolution_us
414+ .saturating_add(route_started.elapsed().as_micros() as u64);
415+ timing.emit(&app, &scope, request_id, "route_error", "", "");
416+ }
417+ break Err(anyhow::Error::new(RoutedRequestError(error)));
418+ }
419+ };
420+ if let Some(timing) = websocket_timing.as_mut() {
421+ timing.route_resolution_us = timing
422+ .route_resolution_us
423+ .saturating_add(route_started.elapsed().as_micros() as u64);
424+ }
425+ let Routed { request, route } = routed;
426+ let (node, addr, epoch, peer_protocol) = match route {
427+ Route::Local => {
428+ let dispatch_started = Instant::now();
429+ let _activity = app.activity(request, scope.clone());
430+ let result = async {
431+ let runtime = app.runtime.as_ref().context("no cell runtime")?;
432+ let response = runtime
433+ .fetch_cell(
434+ scope.clone(),
435+ name,
436+ RuntimeFetch {
437+ url,
438+ method,
439+ body,
440+ headers,
441+ request_id,
442+ // Moved on the first attempt and gone on
443+ // a retry, which is right: a retry is a
444+ // second delivery of a call whose place
445+ // in the order was already taken.
446+ order: order.take(),
447+ parent,
448+ },
449+ cancel.take(),
450+ )
451+ .await?;
452+ if let Some(target) = &response.ws {
453+ let kind = if celld::js::ws_hibernatable(target.id).unwrap_or(false) {
454+ WebSocketKind::Hibernatable
455+ } else {
456+ WebSocketKind::Regular
457+ };
458+ app.websocket_opened(target.scope.clone(), target.id, kind)
459+ .await?;
460+ }
461+ Ok(response)
462+ }
463+ .await;
464+ // Output gate (RPO=0): a handler that advanced the cell's
465+ // write position has its response held until the core proves
466+ // the cell durable. The request is still pinned (the
467+ // activity guard has not dropped), so it fails rather than
468+ // acknowledges a write the node cannot prove durable.
469+ let result = match result {
470+ Ok(response) if app.output_gate => {
471+ match app.gate_output(request, response.write_position).await {
472+ Ok(()) => Ok(response),
473+ Err(error) => Err(anyhow::Error::new(RoutedRequestError(error))),
474+ }
475+ }
476+ Ok(response) => Ok(response),
477+ Err(error) => Err(error),
478+ };
479+ if let Some(timing) = websocket_timing.as_mut() {
480+ timing.dispatch_us = timing
481+ .dispatch_us
482+ .saturating_add(dispatch_started.elapsed().as_micros() as u64);
483+ timing.emit(
484+ &app,
485+ &scope,
486+ request_id,
487+ if result.is_ok() { "ok" } else { "error" },
488+ "local",
489+ app.runtime.as_ref().map_or("", RuntimeManager::node),
490+ );
491+ }
492+ break result;
493+ }
494+ Route::Remote {
495+ node,
496+ addr,
497+ epoch,
498+ peer_protocol,
499+ } => (node, addr, epoch, peer_protocol),
500+ };
501+ let dispatch_started = Instant::now();
502+ let remote_call = async {
503+ anyhow::ensure!(
504+ peer_protocol == peer_auth::PROTOCOL_VERSION,
505+ "peer {node} speaks incompatible protocol {peer_protocol}"
506+ );
507+ let encoded = serde_json::json!({
508+ "name": &name,
509+ "url": &url,
510+ "method": &method,
511+ "bodyBase64": base64::engine::general_purpose::STANDARD.encode(&body),
512+ "headers": &headers,
513+ "requestId": request_id.map(celld::js::request_id_string),
514+ "capacityHandoff": epoch == 0,
515+ });
516+ let encoded = serde_json::to_vec(&encoded)?;
517+ let path = format!("/__do/{scope}");
518+ let request = app.peer_auth.sign(
519+ app.peer_http.post(format!("http://{addr}{path}")),
520+ "POST",
521+ &path,
522+ &encoded,
523+ &node,
524+ )?;
525+ let response =
526+ request.body(encoded).send().await.map_err(|error| {
527+ owner_unreachable(&scope, &addr, anyhow::Error::new(error))
528+ })?;
529+ peer_auth::validate_response(response.headers())?;
530+ if response
531+ .headers()
532+ .get(STALE_ROUTE_HEADER)
533+ .is_some_and(|value| value == STALE_ROUTE_VALUE)
534+ {
535+ return Err(owner_unreachable(
536+ &scope,
537+ &addr,
538+ anyhow::Error::new(StalePeerRoute {
539+ scope: scope.clone(),
540+ }),
541+ ));
542+ }
543+ let mut websocket: Option<celld::js::WsTarget> = response
544+ .headers()
545+ .get("x-celld-ws-target")
546+ .and_then(|value| value.to_str().ok())
547+ .and_then(|value| serde_json::from_str(value).ok());
548+ if let Some(target) = websocket.as_mut() {
549+ target.peer_node = Some(node.clone());
550+ target.peer_addr = Some(addr.clone());
551+ target.peer_epoch = Some(epoch);
552+ }
553+ let status = if websocket.is_some() && response.status() == StatusCode::OK {
554+ 101
555+ } else {
556+ response.status().as_u16()
557+ };
558+ let headers = response
559+ .headers()
560+ .iter()
561+ .filter(|(name, _)| {
562+ name.as_str() != "x-celld-ws-target"
563+ && name.as_str() != "x-celld-body-stream"
564+ })
565+ .filter_map(|(name, value)| {
566+ value
567+ .to_str()
568+ .ok()
569+ .map(|value| (name.to_string(), value.to_string()))
570+ })
571+ .collect();
572+ let (body, stream) = if websocket.is_some() {
573+ (Vec::new(), None)
574+ } else {
575+ // Every proxied body streams through, marked or not. The
576+ // owner already ran the request, so a failure mid-body is
577+ // ambiguous and must surface without a redispatch -- and
578+ // streaming makes that structural: the 200 head has gone
579+ // out before the failure is known, a chunk error aborts
580+ // the client's read instead of ending it cleanly, and
581+ // nothing upstream of a sent head can re-send. Buffering
582+ // here was the old shape; it turned a truncated body into
583+ // a whole-response failure after the owner had committed.
584+ (
585+ Vec::new(),
586+ Some(celld::js::reqwest_response_stream(response)),
587+ )
588+ };
589+ Ok(HttpResponse {
590+ status,
591+ headers,
592+ body,
593+ ws: websocket,
594+ stream,
595+ // A proxied remote response wrote on the owner, not here.
596+ write_position: None,
597+ })
598+ };
599+ let remote = match cancel.as_mut() {
600+ Some(cancel) => celld::asyncrt::select! {
601+ _ = cancel => break Err(anyhow::anyhow!("Durable Object call cancelled")),
602+ remote = remote_call => remote,
603+ },
604+ None => remote_call.await,
605+ };
606+ if let Some(timing) = websocket_timing.as_mut() {
607+ timing.dispatch_us = timing
608+ .dispatch_us
609+ .saturating_add(dispatch_started.elapsed().as_micros() as u64);
610+ }
611+ match remote {
612+ Ok(response) => {
613+ if let Some(timing) = websocket_timing.as_ref() {
614+ timing.emit(&app, &scope, request_id, "ok", "remote", &node);
615+ }
616+ break Ok(response);
617+ }
618+ Err(error) => {
619+ // Epoch zero is a candidate, not an owner. A signed peer
620+ // refusal proves this attempt did not execute and should
621+ // not consume the ordinary one-owner stale-route budget;
622+ // the core excludes that exact load sample before the
623+ // next deterministic placement decision.
624+ let capacity_refused = epoch == 0
625+ && error
626+ .chain()
627+ .any(|cause| cause.downcast_ref::<StalePeerRoute>().is_some());
628+ if capacity_refused {
629+ app.invalidate_remote(scope.clone(), node, epoch).await;
630+ continue;
631+ }
632+ let attempt = classify_remote_attempt(&error);
633+ if dispatcher.redispatch(attempt) {
634+ app.invalidate_remote(scope.clone(), node, epoch).await;
635+ continue;
636+ }
637+ if let Some(timing) = websocket_timing.as_ref() {
638+ timing.emit(&app, &scope, request_id, "error", "remote", &node);
639+ }
640+ break Err(error);
641+ }
642+ }
643+ }
644+ };
645+ let result = operation.await;
646+ let _ = reply.send(result);
647+}
648+
649+async fn dispatch_rpc_call(app: AppHandle, call: RpcCallReq) {
650+ let RpcCallReq {
651+ scope,
652+ name,
653+ method,
654+ args,
655+ reply,
656+ } = call;
657+ let result = async {
658+ anyhow::ensure!(
659+ celld_logic::cell::valid_cell_scope(&scope),
660+ "cell scope is malformed or exceeds the fleet storage limit"
661+ );
662+ let mut dispatcher = celld_logic::routing::Dispatcher::default();
663+ loop {
664+ let Routed { request, route } = app
665+ .request(scope.clone())
666+ .await
667+ .map_err(|error| anyhow::anyhow!("route RPC {scope}: {error:?}"))?;
668+ let (node, addr, epoch, peer_protocol) = match route {
669+ Route::Local => {
670+ let _activity = app.activity(request, scope.clone());
671+ let outcome = app
672+ .runtime
673+ .as_ref()
674+ .context("no cell runtime")?
675+ .rpc(scope, name, method, args)
676+ .await?;
677+ // Output gate (RPO=0): an RPC method that advanced the
678+ // cell's write position has its reply held until the core
679+ // proves the cell durable, exactly as fetch does. The
680+ // activity guard is still alive, so the cell stays pinned
681+ // across the wait.
682+ if app.output_gate {
683+ app.gate_output(request, outcome.write_position)
684+ .await
685+ .map_err(|error| anyhow::Error::new(RoutedRequestError(error)))?;
686+ }
687+ return Ok(outcome.data);
688+ }
689+ Route::Remote {
690+ node,
691+ addr,
692+ epoch,
693+ peer_protocol,
694+ } => (node, addr, epoch, peer_protocol),
695+ };
696+ anyhow::ensure!(
697+ peer_protocol == peer_auth::PROTOCOL_VERSION,
698+ "peer {node} speaks incompatible protocol {peer_protocol}"
699+ );
700+ let structured = matches!(args, celld::js::RpcData::V8(_));
701+ let envelope = match &args {
702+ celld::js::RpcData::Json(json) => serde_json::json!({
703+ "name": &name,
704+ "method": &method,
705+ "args": serde_json::from_str::<serde_json::Value>(json)
706+ .unwrap_or_else(|_| serde_json::json!([])),
707+ }),
708+ celld::js::RpcData::V8(bytes) => serde_json::json!({
709+ "name": &name,
710+ "method": &method,
711+ "sc": base64::engine::general_purpose::STANDARD.encode(bytes),
712+ }),
713+ };
714+ let encoded = serde_json::to_vec(&envelope)?;
715+ let path = format!("/__rpc/{scope}");
716+ let request = app.peer_auth.sign(
717+ app.peer_http.post(format!("http://{addr}{path}")),
718+ "POST",
719+ &path,
720+ &encoded,
721+ &node,
722+ )?;
723+ let response = request.body(encoded).send().await;
724+ let response = match response {
725+ Ok(response) => response,
726+ Err(error) => {
727+ let attempt = classify_remote_attempt(&anyhow::Error::new(error));
728+ if dispatcher.redispatch(attempt) {
729+ app.invalidate_remote(scope.clone(), node, epoch).await;
730+ continue;
731+ }
732+ return Err(anyhow::anyhow!("remote RPC transport failed"));
733+ }
734+ };
735+ peer_auth::validate_response(response.headers())?;
736+ if response
737+ .headers()
738+ .get(STALE_ROUTE_HEADER)
739+ .is_some_and(|value| value == STALE_ROUTE_VALUE)
740+ {
741+ if dispatcher.redispatch(celld_logic::routing::Attempt::NotOwner) {
742+ app.invalidate_remote(scope.clone(), node, epoch).await;
743+ continue;
744+ }
745+ anyhow::bail!("remote RPC owner was stale");
746+ }
747+ anyhow::ensure!(
748+ response.status().is_success(),
749+ "remote RPC failed with {}",
750+ response.status()
751+ );
752+ return Ok(if structured {
753+ celld::js::RpcData::V8(response.bytes().await?.to_vec())
754+ } else {
755+ celld::js::RpcData::Json(response.text().await?)
756+ });
757+ }
758+ }
759+ .await;
760+ let _ = reply.send(result);
761+}
762+
763+async fn request_payload(
764+ request: Request<Incoming>,
765+ trust_forwarded_headers: bool,
766+) -> Result<(String, String, Vec<u8>, Vec<(String, String)>), HttpReply> {
767+ let (parts, body) = request.into_parts();
768+ let body = body.collect().await.map_err(|error| {
769+ response(
770+ StatusCode::BAD_REQUEST,
771+ format!("request body failed: {error}"),
772+ )
773+ })?;
774+ let headers = parts
775+ .headers
776+ .iter()
777+ .filter_map(|(name, value)| {
778+ value
779+ .to_str()
780+ .ok()
781+ .map(|value| (name.to_string(), value.to_string()))
782+ })
783+ .collect();
784+ Ok((
785+ request_url(&parts, trust_forwarded_headers),
786+ parts.method.to_string(),
787+ body.to_bytes().to_vec(),
788+ headers,
789+ ))
790+}
791+
792+/// A body at or above this many bytes reaches the Worker as a stream.
793+///
794+/// A small body crosses as bytes. The host makes one copy, and the handler
795+/// reads that copy with no asynchronous operation. A large body crosses as
796+/// a stream, because one copy of a large body costs more than the
797+/// operations that read it in parts. The host also streams a body that
798+/// declares no length, because the host cannot know the size of that body.
799+const INGRESS_STREAM_THRESHOLD: u64 = 1 << 20;
800+
801+/// Divide an ingress request into its metadata and a body that the Worker
802+/// can read. The function streams the body if one copy of the body costs
803+/// more than the operations that read it in parts.
804+fn ingress_payload(
805+ request: Request<Incoming>,
806+ trust_forwarded_headers: bool,
807+) -> (
808+ String,
809+ String,
810+ celld::js::RequestBody,
811+ Vec<(String, String)>,
812+ Option<Incoming>,
813+) {
814+ let (parts, body) = request.into_parts();
815+ let headers: Vec<(String, String)> = parts
816+ .headers
817+ .iter()
818+ .filter_map(|(name, value)| {
819+ value
820+ .to_str()
821+ .ok()
822+ .map(|value| (name.to_string(), value.to_string()))
823+ })
824+ .collect();
825+ let url = request_url(&parts, trust_forwarded_headers);
826+ let method = parts.method.to_string();
827+ let declared = parts
828+ .headers
829+ .get(hyper::header::CONTENT_LENGTH)
830+ .and_then(|value| value.to_str().ok())
831+ .and_then(|value| value.parse::<u64>().ok());
832+ // A method that carries no body does not stream. There is nothing to
833+ // pull, and a stream costs the handler one operation to learn this.
834+ let bodyless =
835+ matches!(parts.method, hyper::Method::GET | hyper::Method::HEAD) || declared == Some(0);
836+ if bodyless || declared.is_some_and(|length| length < INGRESS_STREAM_THRESHOLD) {
837+ return (
838+ url,
839+ method,
840+ celld::js::RequestBody::Bytes(Vec::new()),
841+ headers,
842+ Some(body),
843+ );
844+ }
845+ let chunks = body.into_data_stream().map(|chunk| {
846+ chunk
847+ .map(|bytes| bytes.to_vec())
848+ .map_err(|error| error.to_string())
849+ });
850+ let stream_id = celld::js::register_body_stream(Box::pin(chunks));
851+ (
852+ url,
853+ method,
854+ celld::js::RequestBody::Stream(stream_id),
855+ headers,
856+ None,
857+ )
858+}
859+
860+/// The refusal every path arm gives a cell scope that fails the charset gate.
861+///
862+/// A scope taken from a URL segment reaches `db_path`, which joins it under the
863+/// data directory, and the replication client, which builds a bucket key from
864+/// it, so a scope carrying its own path segments walks out of both. The gate
865+/// itself is reified in `celld_logic::cell`, next to the peer-identity gate it
866+/// mirrors.
867+fn malformed_scope() -> HttpReply {
868+ response(
869+ StatusCode::BAD_REQUEST,
870+ "{\"error\":\"malformed_cell_scope\"}",
871+ )
872+}
873+
874+/// `request.url` controls application routing and absolute links, so celld
875+/// does not let an untrusted forwarding header or request-target authority set
876+/// its scheme or host. The path and query always come from the request target.
877+/// The host comes from `Host`, and the scheme is `http` because celld does not
878+/// terminate TLS.
879+///
880+/// An operator can set `--trust-forwarded-headers` when a trusted proxy
881+/// replaces both forwarded headers. The trusted read takes the last value
882+/// because a proxy can append its value after a client-supplied value.
883+fn request_url(parts: &hyper::http::request::Parts, trust_forwarded_headers: bool) -> String {
884+ let header = |name: &str, take_last: bool| {
885+ parts
886+ .headers
887+ .get(name)
888+ .and_then(|value| value.to_str().ok())
889+ .and_then(|value| {
890+ if take_last {
891+ value.split(',').next_back()
892+ } else {
893+ value.split(',').next()
894+ }
895+ })
896+ .map(str::trim)
897+ .filter(|value| !value.is_empty())
898+ };
899+ let forwarded = |name: &str| {
900+ trust_forwarded_headers
901+ .then(|| header(name, true))
902+ .flatten()
903+ };
904+ let host = forwarded("x-forwarded-host")
905+ .or_else(|| header("host", false))
906+ .unwrap_or("celld.local");
907+ let scheme = forwarded("x-forwarded-proto").unwrap_or("http");
908+ let path_and_query = parts
909+ .uri
910+ .path_and_query()
911+ .map_or("/", hyper::http::uri::PathAndQuery::as_str);
912+ format!("{scheme}://{host}{path_and_query}")
913+}
914+
915+/// Send a fetch to a cell through the dispatcher a Durable Object call from
916+/// inside a Worker goes through.
917+///
918+/// Public ingress used to resolve the route itself and, on finding another
919+/// owner, answer with a 307 and a JSON description of where the cell lived --
920+/// with no Location header, so nothing could follow it. A fleet behind a load
921+/// balancer serves a cell only from the node that happens to own it, which is
922+/// to say it does not serve a fleet at all.
923+///
924+/// Going through `dispatch_do_call` also inherits the redispatch policy and
925+/// the cancellation channel, so a client that hangs up reaches the owner
926+/// rather than only the node it connected to. `/do/` and `/__d1/` share this:
927+/// they differ in what they authenticate, not in how they reach a cell.
928+async fn dispatch_cell_fetch(
929+ cell: String,
930+ url: String,
931+ method: String,
932+ body: Vec<u8>,
933+ headers: Vec<(String, String)>,
934+) -> HttpReply {
935+ let (reply, receive) = oneshot::channel();
936+ let (cancel_tx, cancel) = oneshot::channel();
937+ let accepted = celld::js::submit_do_call(celld::js::DoCallReq {
938+ // Named, and named here: the abort fires only for a call that carries
939+ // both an id and a cancel signal, so leaving this None silently costs
940+ // the cancellation rather than failing.
941+ request_id: Some(celld::js::next_request_id()),
942+ cancel: Some(cancel),
943+ deliver_abort_to_handler: false,
944+ scope: cell,
945+ name: None,
946+ url,
947+ method,
948+ body,
949+ headers,
950+ reply,
951+ // An ingress call has no caller in this process to be ordered against.
952+ order: None,
953+ // A direct-DO ingress caller's traceparent joins with the cross-node
954+ // propagation work (otel.md phase 2), which is where remote parents of
955+ // cell spans get their sampling decision.
956+ parent: None,
957+ });
958+ if !accepted {
959+ return response(
960+ StatusCode::SERVICE_UNAVAILABLE,
961+ "{\"error\":\"dispatcher unavailable\"}",
962+ );
963+ }
964+ let _hangup = HangUp(Some(cancel_tx));
965+ match receive.await {
966+ Ok(Ok(worker_response)) => runtime_response(worker_response),
967+ Ok(Err(error)) => match error.downcast_ref::<RoutedRequestError>() {
968+ Some(error) => response(
969+ StatusCode::SERVICE_UNAVAILABLE,
970+ format!("{{\"error\":\"{:?}\"}}", error.0),
971+ ),
972+ None => response(
973+ StatusCode::SERVICE_UNAVAILABLE,
974+ format!("cell Worker failed: {error:#}"),
975+ ),
976+ },
977+ Err(_) => response(
978+ StatusCode::SERVICE_UNAVAILABLE,
979+ "{\"error\":\"dispatcher dropped the call\"}",
980+ ),
981+ }
982+}
983+
984+async fn internal_do(request: Request<Incoming>, app: AppHandle, scope: String) -> HttpReply {
985+ let method = request.method().clone();
986+ let path_and_query = request
987+ .uri()
988+ .path_and_query()
989+ .map_or_else(|| request.uri().path().to_string(), ToString::to_string);
990+ let request_headers = request.headers().clone();
991+ let body = match request.into_body().collect().await {
992+ Ok(body) => body.to_bytes(),
993+ Err(error) => {
994+ return peer_response(response(
995+ StatusCode::BAD_REQUEST,
996+ format!("invalid body: {error}"),
997+ ));
998+ }
999+ };
1000+ if let Err(error) = app.peer_auth.verify(
1001+ &method,
1002+ &path_and_query,
1003+ &request_headers,
1004+ &body,
1005+ app.peer_auth.source(),
1006+ ) {
1007+ let mut denied = response(error.status(), error.message());
1008+ if matches!(error, peer_auth::VerifyError::WrongTarget) {
1009+ denied.headers_mut().insert(
1010+ hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
1011+ hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
1012+ );
1013+ }
1014+ return peer_response(denied);
1015+ }
1016+ let value: serde_json::Value = match serde_json::from_slice(&body) {
1017+ Ok(value) => value,
1018+ Err(error) => {
1019+ return peer_response(response(
1020+ StatusCode::BAD_REQUEST,
1021+ format!("invalid JSON: {error}"),
1022+ ));
1023+ }
1024+ };
1025+ let url = value
1026+ .get("url")
1027+ .and_then(serde_json::Value::as_str)
1028+ .unwrap_or("http://cell/")
1029+ .to_string();
1030+ let method = value
1031+ .get("method")
1032+ .and_then(serde_json::Value::as_str)
1033+ .unwrap_or("GET")
1034+ .to_string();
1035+ let name = value
1036+ .get("name")
1037+ .and_then(serde_json::Value::as_str)
1038+ .map(str::to_string);
1039+ let request_body = value
1040+ .get("bodyBase64")
1041+ .and_then(serde_json::Value::as_str)
1042+ .and_then(|body| base64::engine::general_purpose::STANDARD.decode(body).ok())
1043+ .unwrap_or_default();
1044+ let headers = serde_json::from_value(
1045+ value
1046+ .get("headers")
1047+ .cloned()
1048+ .unwrap_or_else(|| serde_json::json!([])),
1049+ )
1050+ .unwrap_or_default();
1051+ let request_id = value
1052+ .get("requestId")
1053+ .and_then(serde_json::Value::as_str)
1054+ .and_then(celld::js::parse_request_id);
1055+ let capacity_handoff = value
1056+ .get("capacityHandoff")
1057+ .and_then(serde_json::Value::as_bool)
1058+ .unwrap_or(false);
1059+ let routed = if capacity_handoff {
1060+ app.capacity_request(scope.clone()).await
1061+ } else {
1062+ app.request(scope.clone()).await
1063+ };
1064+ let result = match routed {
1065+ Ok(Routed {
1066+ request,
1067+ route: Route::Local,
1068+ }) => {
1069+ let _activity = app.activity(request, scope.clone());
1070+ let Some(runtime) = &app.runtime else {
1071+ return response(StatusCode::SERVICE_UNAVAILABLE, "no cell runtime");
1072+ };
1073+ let abort_scope = scope.clone();
1074+ // The forwarding node hangs up when its own client does, so this
1075+ // connection going away is the cancellation signal reaching the
1076+ // owner -- and it arrives as a drop, which is why it is a guard
1077+ // rather than the channel `fetch_cell` takes. Without it a handler
1078+ // keeps running on the owner for a client that left the node it
1079+ // dialled.
1080+ let mut abort = AbortPeerFetchOnHangUp {
1081+ runtime: runtime.clone(),
1082+ scope: abort_scope,
1083+ request_id,
1084+ };
1085+ match runtime
1086+ .fetch_cell(
1087+ scope,
1088+ name,
1089+ RuntimeFetch {
1090+ url,
1091+ method,
1092+ body: request_body,
1093+ headers,
1094+ request_id,
1095+ // A peer's call has no caller in this process; its
1096+ // trace context crossing nodes is phase 2.
1097+ order: None,
1098+ parent: None,
1099+ },
1100+ None,
1101+ )
1102+ .await
1103+ {
1104+ Ok(worker_response) => {
1105+ abort.request_id = None;
1106+ // Output gate (RPO=0): a peer-served handler that advanced
1107+ // the cell's committed position holds its reply until the
1108+ // cell is proven durable, exactly as the local dispatch
1109+ // path does. This path used to acknowledge unproven writes
1110+ // — the loss the takeover tests catch. The activity guard
1111+ // is still alive, so the request stays pinned across the
1112+ // wait.
1113+ if app.output_gate {
1114+ if let Err(error) = app
1115+ .gate_output(request, worker_response.write_position)
1116+ .await
1117+ {
1118+ return peer_response(response(
1119+ StatusCode::INTERNAL_SERVER_ERROR,
1120+ format!("durability unproven: {error:?}"),
1121+ ));
1122+ }
1123+ }
1124+ if let Some(target) = &worker_response.ws {
1125+ let kind = if celld::js::ws_hibernatable(target.id).unwrap_or(false) {
1126+ WebSocketKind::Hibernatable
1127+ } else {
1128+ WebSocketKind::Regular
1129+ };
1130+ if let Err(error) = app
1131+ .websocket_opened(target.scope.clone(), target.id, kind)
1132+ .await
1133+ {
1134+ return peer_response(response(
1135+ StatusCode::SERVICE_UNAVAILABLE,
1136+ format!("WebSocket core registration failed: {error:#}"),
1137+ ));
1138+ }
1139+ }
1140+ peer_runtime_response(worker_response)
1141+ }
1142+ Err(error) => response(
1143+ StatusCode::INTERNAL_SERVER_ERROR,
1144+ format!("cell Worker failed: {error:#}"),
1145+ ),
1146+ }
1147+ }
1148+ Ok(Routed {
1149+ route: Route::Remote { .. },
1150+ ..
1151+ }) => {
1152+ let mut stale = response(StatusCode::CONFLICT, "stale route");
1153+ stale.headers_mut().insert(
1154+ hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
1155+ hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
1156+ );
1157+ stale
1158+ }
1159+ Err(RequestError::CapacityExhausted) => {
1160+ let mut stale = response(StatusCode::CONFLICT, "capacity exhausted");
1161+ stale.headers_mut().insert(
1162+ hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
1163+ hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
1164+ );
1165+ stale
1166+ }
1167+ Err(error) => response(
1168+ StatusCode::SERVICE_UNAVAILABLE,
1169+ format!("route failed: {error:?}"),
1170+ ),
1171+ };
1172+ peer_response(result)
1173+}
1174+
1175+async fn internal_abort(request: Request<Incoming>, app: AppHandle, path: String) -> HttpReply {
1176+ let (parts, body) = request.into_parts();
1177+ let body = match body.collect().await {
1178+ Ok(body) => body.to_bytes(),
1179+ Err(error) => {
1180+ return peer_response(response(
1181+ StatusCode::BAD_REQUEST,
1182+ format!("invalid abort body: {error}"),
1183+ ));
1184+ }
1185+ };
1186+ let path_and_query = parts
1187+ .uri
1188+ .path_and_query()
1189+ .map_or_else(|| parts.uri.path().to_string(), ToString::to_string);
1190+ if let Err(error) = app.peer_auth.verify(
1191+ &parts.method,
1192+ &path_and_query,
1193+ &parts.headers,
1194+ &body,
1195+ app.peer_auth.source(),
1196+ ) {
1197+ let mut denied = response(error.status(), error.message());
1198+ if matches!(error, peer_auth::VerifyError::WrongTarget) {
1199+ denied.headers_mut().insert(
1200+ hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
1201+ hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
1202+ );
1203+ }
1204+ return peer_response(denied);
1205+ }
1206+ if parts.method != hyper::Method::POST {
1207+ return peer_response(response(
1208+ StatusCode::METHOD_NOT_ALLOWED,
1209+ "method not allowed",
1210+ ));
1211+ }
1212+ let Some((encoded_scope, encoded_request)) = path
1213+ .strip_prefix("/__abort/")
1214+ .and_then(|rest| rest.rsplit_once('/'))
1215+ else {
1216+ return peer_response(response(StatusCode::BAD_REQUEST, "invalid abort target"));
1217+ };
1218+ let scope = match percent_encoding::percent_decode_str(encoded_scope).decode_utf8() {
1219+ Ok(scope) => scope.into_owned(),
1220+ Err(_) => return peer_response(response(StatusCode::BAD_REQUEST, "invalid abort scope")),
1221+ };
1222+ if !celld_logic::cell::valid_cell_scope(&scope) {
1223+ return peer_response(malformed_scope());
1224+ }
1225+ let Some(request_id) = celld::js::parse_request_id(encoded_request) else {
1226+ return peer_response(response(StatusCode::BAD_REQUEST, "invalid request id"));
1227+ };
1228+ let result = match app.request(scope.clone()).await {
1229+ Ok(Routed {
1230+ request,
1231+ route: Route::Local,
1232+ }) => {
1233+ let _activity = app.activity(request, scope.clone());
1234+ match &app.runtime {
1235+ Some(runtime) => {
1236+ runtime.abort_fetch(&scope, request_id);
1237+ response(StatusCode::NO_CONTENT, Bytes::new())
1238+ }
1239+ None => response(StatusCode::SERVICE_UNAVAILABLE, "no cell runtime"),
1240+ }
1241+ }
1242+ Ok(Routed {
1243+ route: Route::Remote { .. },
1244+ ..
1245+ }) => {
1246+ let mut stale = response(StatusCode::CONFLICT, "stale route");
1247+ stale.headers_mut().insert(
1248+ hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
1249+ hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
1250+ );
1251+ stale
1252+ }
1253+ Err(error) => response(
1254+ StatusCode::SERVICE_UNAVAILABLE,
1255+ format!("abort route failed: {error:?}"),
1256+ ),
1257+ };
1258+ peer_response(result)
1259+}
1260+
1261+async fn internal_rpc(request: Request<Incoming>, app: AppHandle, scope: String) -> HttpReply {
1262+ let method = request.method().clone();
1263+ let path_and_query = request
1264+ .uri()
1265+ .path_and_query()
1266+ .map_or_else(|| request.uri().path().to_string(), ToString::to_string);
1267+ let request_headers = request.headers().clone();
1268+ let body = match request.into_body().collect().await {
1269+ Ok(body) => body.to_bytes(),
1270+ Err(error) => {
1271+ return peer_response(response(
1272+ StatusCode::BAD_REQUEST,
1273+ format!("invalid body: {error}"),
1274+ ));
1275+ }
1276+ };
1277+ if let Err(error) = app.peer_auth.verify(
1278+ &method,
1279+ &path_and_query,
1280+ &request_headers,
1281+ &body,
1282+ app.peer_auth.source(),
1283+ ) {
1284+ let mut denied = response(error.status(), error.message());
1285+ if matches!(error, peer_auth::VerifyError::WrongTarget) {
1286+ denied.headers_mut().insert(
1287+ hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
1288+ hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
1289+ );
1290+ }
1291+ return peer_response(denied);
1292+ }
1293+ let value: serde_json::Value = match serde_json::from_slice(&body) {
1294+ Ok(value) => value,
1295+ Err(error) => {
1296+ return peer_response(response(
1297+ StatusCode::BAD_REQUEST,
1298+ format!("invalid JSON: {error}"),
1299+ ));
1300+ }
1301+ };
1302+ let name = value
1303+ .get("name")
1304+ .and_then(serde_json::Value::as_str)
1305+ .map(str::to_string);
1306+ let rpc_method = value
1307+ .get("method")
1308+ .and_then(serde_json::Value::as_str)
1309+ .unwrap_or_default()
1310+ .to_string();
1311+ let args = match value.get("sc").and_then(serde_json::Value::as_str) {
1312+ Some(bytes) => celld::js::RpcData::V8(
1313+ base64::engine::general_purpose::STANDARD
1314+ .decode(bytes)
1315+ .unwrap_or_default(),
1316+ ),
1317+ None => celld::js::RpcData::Json(
1318+ value
1319+ .get("args")
1320+ .cloned()
1321+ .unwrap_or_else(|| serde_json::json!([]))
1322+ .to_string(),
1323+ ),
1324+ };
1325+ let result = match app.request(scope.clone()).await {
1326+ Ok(Routed {
1327+ request,
1328+ route: Route::Local,
1329+ }) => {
1330+ let _activity = app.activity(request, scope.clone());
1331+ let Some(runtime) = &app.runtime else {
1332+ return peer_response(response(StatusCode::SERVICE_UNAVAILABLE, "no cell runtime"));
1333+ };
1334+ // Output gate on the owner side, so a proxied RPC write is durable
1335+ // before the calling node sees the reply -- the same rule the peer
1336+ // fetch path follows.
1337+ match runtime.rpc(scope, name, rpc_method, args).await {
1338+ Ok(outcome) => {
1339+ if app.output_gate {
1340+ if let Err(error) = app.gate_output(request, outcome.write_position).await {
1341+ return peer_response(response(
1342+ StatusCode::INTERNAL_SERVER_ERROR,
1343+ format!("durability unproven: {error:?}"),
1344+ ));
1345+ }
1346+ }
1347+ Ok(outcome.data)
1348+ }
1349+ Err(error) => Err(error),
1350+ }
1351+ }
1352+ Ok(Routed {
1353+ route: Route::Remote { .. },
1354+ ..
1355+ }) => {
1356+ let mut stale = response(StatusCode::CONFLICT, "stale route");
1357+ stale.headers_mut().insert(
1358+ hyper::header::HeaderName::from_static(STALE_ROUTE_HEADER),
1359+ hyper::header::HeaderValue::from_static(STALE_ROUTE_VALUE),
1360+ );
1361+ return peer_response(stale);
1362+ }
1363+ Err(error) => Err(anyhow::anyhow!("route failed: {error:?}")),
1364+ };
1365+ match result {
1366+ Ok(celld::js::RpcData::Json(json)) => peer_response(
1367+ Response::builder()
1368+ .status(StatusCode::OK)
1369+ .header("content-type", "application/json")
1370+ .body(
1371+ Full::new(Bytes::from(json))
1372+ .map_err(|never| match never {})
1373+ .boxed_unsync(),
1374+ )
1375+ .expect("RPC JSON response"),
1376+ ),
1377+ Ok(celld::js::RpcData::V8(bytes)) => peer_response(
1378+ Response::builder()
1379+ .status(StatusCode::OK)
1380+ .header("content-type", "application/octet-stream")
1381+ .body(
1382+ Full::new(Bytes::from(bytes))
1383+ .map_err(|never| match never {})
1384+ .boxed_unsync(),
1385+ )
1386+ .expect("RPC clone response"),
1387+ ),
1388+ Err(error) => peer_response(response(
1389+ StatusCode::INTERNAL_SERVER_ERROR,
1390+ format!("RPC failed: {error:#}"),
1391+ )),
1392+ }
1393+}
1394+
1395+#[path = "main/websocket.rs"]
1396+mod websocket;
1397+use websocket::{handle_peer_websocket, handle_websocket, outbound_websocket_task};
1398+
1399+async fn handle_ingress(
1400+ request: Request<Incoming>,
1401+ app: AppHandle,
1402+ connection: ConnectionWorkerRequests,
1403+) -> HttpReply {
1404+ if matches!(*request.method(), hyper::Method::GET | hyper::Method::HEAD) {
1405+ if let Some(resolver) = app
1406+ .asset_script
1407+ .as_deref()
1408+ .and_then(|script| app.assets.get(script))
1409+ {
1410+ let path = request.uri().path();
1411+ if !resolver.should_run_worker_first(path) {
1412+ let head = request.method() == hyper::Method::HEAD;
1413+ match resolver
1414+ .ingress_response(path, request.uri().query(), head, request.headers())
1415+ .await
1416+ {
1417+ Ok(Some(response)) => return asset_response(response),
1418+ Ok(None) if resolver.asset_only() => {
1419+ return response(StatusCode::NOT_FOUND, "Not found");
1420+ }
1421+ Ok(None) => {}
1422+ Err(error) => {
1423+ eprintln!("celld asset response failed for {path}: {error:#}");
1424+ return response(
1425+ StatusCode::BAD_GATEWAY,
1426+ "Active deployment asset is unavailable",
1427+ );
1428+ }
1429+ }
1430+ }
1431+ }
1432+ }
1433+
1434+ let (url, method, body, headers, held) = ingress_payload(request, app.trust_forwarded_headers);
1435+ // The host collects a small body here. A read failure at this point
1436+ // can still return status 400. A streamed body has no such point,
1437+ // because that body fails while the handler reads it. The failure
1438+ // surfaces there instead.
1439+ let body = match held {
1440+ None => body,
1441+ Some(held) => match held.collect().await {
1442+ Ok(collected) => celld::js::RequestBody::Bytes(collected.to_bytes().to_vec()),
1443+ Err(error) => {
1444+ return response(
1445+ StatusCode::BAD_REQUEST,
1446+ format!("request body failed: {error}"),
1447+ );
1448+ }
1449+ },
1450+ };
1451+ match app
1452+ .fetch_worker(url, method, body, headers, connection)
1453+ .await
1454+ {
1455+ Ok(worker_response) => runtime_response(worker_response),
1456+ Err(error) => match error.downcast_ref::<celld::pool::AdmitError>() {
1457+ // Saturation is not a failure of the request. Answering it now
1458+ // lets the caller retry or shed; holding the connection until its
1459+ // own deadline is what a node with no capacity used to do.
1460+ Some(refused @ celld::pool::AdmitError::Refused(_)) => response(
1461+ StatusCode::SERVICE_UNAVAILABLE,
1462+ format!("Worker refused: {refused}"),
1463+ ),
1464+ // A build failure is a fault, not saturation.
1465+ Some(celld::pool::AdmitError::Build(_)) | None => response(
1466+ StatusCode::INTERNAL_SERVER_ERROR,
1467+ format!("Worker failed: {error:#}"),
1468+ ),
1469+ },
1470+ }
1471+}
1472+
1473+async fn dispatch_asset_call(app: AppHandle, call: AssetCallReq) {
1474+ let response = match app.assets.get(&call.script) {
1475+ Some(resolver) => {
1476+ resolver
1477+ .binding_response(&call.url, &call.method, &call.headers)
1478+ .await
1479+ }
1480+ None => Err(anyhow::anyhow!(
1481+ "no asset resolver for script {}",
1482+ call.script
1483+ )),
1484+ };
1485+ let _ = call.reply.send(response);
1486+}
1487+
1488+async fn dispatch_service_call(app: AppHandle, call: SvcCallReq) {
1489+ let response = match &app.runtime {
1490+ Some(runtime) => {
1491+ runtime
1492+ .fetch_service(
1493+ &call.script,
1494+ call.url,
1495+ call.method,
1496+ call.body,
1497+ call.headers,
1498+ call.cancel,
1499+ )
1500+ .await
1501+ }
1502+ None => Err(anyhow::anyhow!("no Worker runtime")),
1503+ };
1504+ let _ = call.reply.send(response);
1505+}
1506+
1507+async fn dispatch_service_rpc(app: AppHandle, call: SvcRpcReq) {
1508+ let response = match &app.runtime {
1509+ Some(runtime) => {
1510+ runtime
1511+ .rpc_service(&call.script, call.entrypoint, call.method, call.args)
1512+ .await
1513+ }
1514+ None => Err(anyhow::anyhow!("no Worker runtime")),
1515+ };
1516+ let _ = call.reply.send(response);
1517+}
1518+
1519+async fn internal_probe(request: Request<Incoming>, app: AppHandle) -> HttpReply {
1520+ let (parts, body) = request.into_parts();
1521+ let body = match body.collect().await {
1522+ Ok(body) => body.to_bytes(),
1523+ Err(error) => {
1524+ return peer_response(response(
1525+ StatusCode::BAD_REQUEST,
1526+ format!("invalid probe body: {error}"),
1527+ ));
1528+ }
1529+ };
1530+ let path_and_query = parts
1531+ .uri
1532+ .path_and_query()
1533+ .map_or_else(|| parts.uri.path().to_string(), ToString::to_string);
1534+ if let Err(error) = app.peer_auth.verify(
1535+ &parts.method,
1536+ &path_and_query,
1537+ &parts.headers,
1538+ &body,
1539+ app.peer_auth.source(),
1540+ ) {
1541+ return peer_response(response(error.status(), error.message()));
1542+ }
1543+ if parts.method != hyper::Method::GET {
1544+ return peer_response(response(
1545+ StatusCode::METHOD_NOT_ALLOWED,
1546+ "method not allowed",
1547+ ));
1548+ }
1549+ let Some(challenge) = parts
1550+ .headers
1551+ .get("x-cells-probe-challenge")
1552+ .and_then(|value| value.to_str().ok())
1553+ else {
1554+ return peer_response(response(StatusCode::BAD_REQUEST, "missing probe challenge"));
1555+ };
1556+ match celld::peer_probe::respond(app.peer_auth.source(), &app.advertise, challenge) {
1557+ Ok(probe) => match serde_json::to_vec(&probe) {
1558+ Ok(body) => peer_response(response(StatusCode::OK, body)),
1559+ Err(_) => peer_response(response(
1560+ StatusCode::INTERNAL_SERVER_ERROR,
1561+ "encode probe response",
1562+ )),
1563+ },
1564+ Err(_) => peer_response(response(StatusCode::BAD_REQUEST, "invalid probe challenge")),
1565+ }
1566+}
1567+
1568+/// The log tier's follower endpoints (crate::node_log): append fsyncs
1569+/// entries and answers the ack-all vote, seal persists the fence mark
1570+/// before replying, tail hands recovery the held fragment. Fleet-HMAC
1571+/// verified like every internal peer surface.
1572+async fn internal_log(request: Request<Incoming>, app: AppHandle, path: String) -> HttpReply {
1573+ let Some(follower) = app.follower.clone() else {
1574+ return peer_response(response(StatusCode::NOT_FOUND, "no follower store"));
1575+ };
1576+ let (parts, body) = request.into_parts();
1577+ let body = match body.collect().await {
1578+ Ok(body) => body.to_bytes(),
1579+ Err(error) => {
1580+ return peer_response(response(
1581+ StatusCode::BAD_REQUEST,
1582+ format!("invalid log body: {error}"),
1583+ ));
1584+ }
1585+ };
1586+ let path_and_query = parts
1587+ .uri
1588+ .path_and_query()
1589+ .map_or_else(|| parts.uri.path().to_string(), ToString::to_string);
1590+ if let Err(error) = app.peer_auth.verify(
1591+ &parts.method,
1592+ &path_and_query,
1593+ &parts.headers,
1594+ &body,
1595+ app.peer_auth.source(),
1596+ ) {
1597+ return peer_response(response(error.status(), error.message()));
1598+ }
1599+ if parts.method != hyper::Method::POST {
1600+ return peer_response(response(
1601+ StatusCode::METHOD_NOT_ALLOWED,
1602+ "method not allowed",
1603+ ));
1604+ }
1605+ let result: anyhow::Result<Vec<u8>> = match path.as_str() {
1606+ // The append body and the tail response are binary — the entries
1607+ // dominate both — while every control message stays JSON.
1608+ "/__log/append" => match celld::node_log::decode_append(&body) {
1609+ Ok(req) => serde_json::to_vec(&follower.append(req).await).map_err(Into::into),
1610+ Err(error) => Err(error),
1611+ },
1612+ "/__log/seal" => match serde_json::from_slice::<celld::node_log::SealReq>(&body) {
1613+ Ok(req) => match follower.seal(&req).await {
1614+ Ok(resp) => serde_json::to_vec(&resp).map_err(Into::into),
1615+ Err(error) => Err(error),
1616+ },
1617+ Err(error) => Err(error.into()),
1618+ },
1619+ "/__log/tail" => serde_json::from_slice::<celld::node_log::TailReq>(&body)
1620+ .map_err(anyhow::Error::from)
1621+ .map(|req| celld::node_log::encode_tail_resp(&follower.tail(&req))),
1622+ _ => Err(anyhow::anyhow!("unknown log endpoint")),
1623+ };
1624+ match result {
1625+ Ok(body) => peer_response(response(StatusCode::OK, body)),
1626+ Err(error) => peer_response(response(StatusCode::BAD_REQUEST, format!("{error:#}"))),
1627+ }
1628+}
1629+
1630+async fn handle_public(
1631+ request: Request<Incoming>,
1632+ app: AppHandle,
1633+ connection: ConnectionWorkerRequests,
1634+) -> Result<HttpReply, Infallible> {
1635+ let path = request.uri().path().to_string();
1636+ let draining = app.is_draining();
1637+ if draining && path != "/__celld/health" {
1638+ let mut refused = response(
1639+ StatusCode::SERVICE_UNAVAILABLE,
1640+ "{\"ok\":false,\"draining\":true}",
1641+ );
1642+ refused.headers_mut().insert(
1643+ hyper::header::RETRY_AFTER,
1644+ hyper::header::HeaderValue::from_static("1"),
1645+ );
1646+ refused.headers_mut().insert(
1647+ hyper::header::CONNECTION,
1648+ hyper::header::HeaderValue::from_static("close"),
1649+ );
1650+ return Ok(refused);
1651+ }
1652+ if path != "/__celld/health"
1653+ && app.runtime.is_some()
1654+ && fastwebsockets::upgrade::is_upgrade_request(&request)
1655+ {
1656+ return Ok(handle_websocket(request, app).await);
1657+ }
1658+ let mut result = match path.as_str() {
1659+ "/__celld/health" if !app.is_draining() && app.healthy().await => {
1660+ response(StatusCode::OK, "{\"ok\":true}")
1661+ }
1662+ "/__celld/health" => response(StatusCode::SERVICE_UNAVAILABLE, "{\"ok\":false}"),
1663+ _ if app.runtime.is_some() => handle_ingress(request, app, connection).await,
1664+ _ => response(StatusCode::NOT_FOUND, "{\"error\":\"not_found\"}"),
1665+ };
1666+ if draining {
1667+ result.headers_mut().insert(
1668+ hyper::header::CONNECTION,
1669+ hyper::header::HeaderValue::from_static("close"),
1670+ );
1671+ }
1672+ Ok(result)
1673+}
1674+
1675+async fn handle_internal(
1676+ request: Request<Incoming>,
1677+ app: AppHandle,
1678+ shutdown: mpsc::UnboundedSender<ShutdownMode>,
1679+) -> Result<HttpReply, Infallible> {
1680+ let path = request.uri().path().to_string();
1681+ let draining = app.is_draining();
1682+ // A draining node accepts no new work: a request for a cell it just
1683+ // released would re-claim the cell and undo the handoff, so everything
1684+ // but diagnostics is refused, and `Connection: close` tears the
1685+ // keep-alive down so the drain loop can finish instead of holding every
1686+ // idle connection open until the deadline.
1687+ if draining && !matches!(path.as_str(), "/__celld/probe" | "/state") {
1688+ let mut refused = response(
1689+ StatusCode::SERVICE_UNAVAILABLE,
1690+ "{\"ok\":false,\"draining\":true}",
1691+ );
1692+ refused.headers_mut().insert(
1693+ hyper::header::RETRY_AFTER,
1694+ hyper::header::HeaderValue::from_static("1"),
1695+ );
1696+ refused.headers_mut().insert(
1697+ hyper::header::CONNECTION,
1698+ hyper::header::HeaderValue::from_static("close"),
1699+ );
1700+ return Ok(refused);
1701+ }
1702+ if path.starts_with("/__ws/") && fastwebsockets::upgrade::is_upgrade_request(&request) {
1703+ return Ok(handle_peer_websocket(request, app, &path).await);
1704+ }
1705+ let result = match path.as_str() {
1706+ "/__celld/probe" => internal_probe(request, app).await,
1707+ _ if path.starts_with("/__log/") => internal_log(request, app, path.clone()).await,
1708+ "/state" => response(StatusCode::OK, app.snapshot().await),
1709+ "/shutdown" if request.method() != hyper::Method::POST => {
1710+ response(StatusCode::METHOD_NOT_ALLOWED, "method not allowed")
1711+ }
1712+ "/shutdown" => {
1713+ let preserve_ownership = request
1714+ .uri()
1715+ .query()
1716+ .is_some_and(|query| query.split('&').any(|part| part == "handoff=preserve"));
1717+ let mode = if preserve_ownership {
1718+ ShutdownMode::Preserve
1719+ } else {
1720+ ShutdownMode::Handoff
1721+ };
1722+ let _ = shutdown.send(mode);
1723+ response(StatusCode::OK, "{\"ok\":true}")
1724+ }
1725+ _ if path.starts_with("/__abort/") && app.runtime.is_some() => {
1726+ internal_abort(request, app, path).await
1727+ }
1728+ _ if path.starts_with("/__do/") && app.runtime.is_some() => {
1729+ if celld_logic::cell::valid_cell_scope(&path[6..]) {
1730+ internal_do(request, app, path[6..].to_string()).await
1731+ } else {
1732+ peer_response(malformed_scope())
1733+ }
1734+ }
1735+ _ if path.starts_with("/__rpc/") && app.runtime.is_some() => {
1736+ if celld_logic::cell::valid_cell_scope(&path[7..]) {
1737+ internal_rpc(request, app, path[7..].to_string()).await
1738+ } else {
1739+ peer_response(malformed_scope())
1740+ }
1741+ }
1742+ // `celld d1`'s way in: the same forwarding dispatch `/do/` uses, with
1743+ // the peer authentication `/do/` does not have. A D1 database holds
1744+ // application data and answers arbitrary SQL, so it must not be
1745+ // reachable from an unauthenticated operator route; `/do/` refuses a
1746+ // D1 scope below and sends the caller here.
1747+ _ if path.starts_with("/__d1/") && app.runtime.is_some() => {
1748+ let scope = path[6..].to_string();
1749+ if !celld_logic::cell::valid_cell_scope(&scope) {
1750+ return Ok(peer_response(malformed_scope()));
1751+ }
1752+ // The mirror of `/do/`'s refusal: that route serves everything
1753+ // but D1, this one serves nothing but D1. Without the check, a
1754+ // signed request could drive an ordinary Durable Object through
1755+ // a route whose only documented contract is SQL to a database.
1756+ if !celld::deploy::is_d1_scope(&scope) {
1757+ return Ok(peer_response(response(
1758+ StatusCode::FORBIDDEN,
1759+ "{\"error\":\"only a D1 database is served on /__d1/; use /do/ for a Durable Object\"}",
1760+ )));
1761+ }
1762+ let method = request.method().clone();
1763+ let path_and_query = request
1764+ .uri()
1765+ .path_and_query()
1766+ .map_or_else(|| request.uri().path().to_string(), ToString::to_string);
1767+ let request_headers = request.headers().clone();
1768+ let body = match request.into_body().collect().await {
1769+ Ok(body) => body.to_bytes(),
1770+ Err(error) => {
1771+ return Ok(peer_response(response(
1772+ StatusCode::BAD_REQUEST,
1773+ format!("invalid body: {error}"),
1774+ )));
1775+ }
1776+ };
1777+ if let Err(error) = app.peer_auth.verify(
1778+ &method,
1779+ &path_and_query,
1780+ &request_headers,
1781+ &body,
1782+ app.peer_auth.source(),
1783+ ) {
1784+ return Ok(peer_response(response(error.status(), error.message())));
1785+ }
1786+ dispatch_cell_fetch(
1787+ scope,
1788+ "http://cell/".to_string(),
1789+ "POST".to_string(),
1790+ body.to_vec(),
1791+ vec![("content-type".to_string(), "application/json".to_string())],
1792+ )
1793+ .await
1794+ }
1795+ _ if path.starts_with("/do/") && app.runtime.is_some() => {
1796+ let runtime = app.runtime.as_ref().expect("checked runtime");
1797+ let cell = match runtime.cell_scope(&path[4..]) {
1798+ Ok(cell) => cell,
1799+ Err(error) => {
1800+ return Ok(response(StatusCode::BAD_REQUEST, format!("{error:#}")));
1801+ }
1802+ };
1803+ // This route has no authentication, so it must not reach a D1
1804+ // database: the cell answers arbitrary SQL, and its scope is an
1805+ // HMAC over the script and database names, both of which sit in
1806+ // the project's config. `/__d1/` serves D1 and is authenticated.
1807+ if celld::deploy::is_d1_scope(&cell) {
1808+ return Ok(response(
1809+ StatusCode::FORBIDDEN,
1810+ "{\"error\":\"a D1 database is not reachable over /do/; use `celld d1`\"}",
1811+ ));
1812+ }
1813+ let (url, method, body, headers) =
1814+ match request_payload(request, app.trust_forwarded_headers).await {
1815+ Ok(payload) => payload,
1816+ Err(response) => return Ok(response),
1817+ };
1818+ dispatch_cell_fetch(cell, url, method, body, headers).await
1819+ }
1820+ _ if path.starts_with("/cell/") && !celld_logic::cell::valid_cell_scope(&path[6..]) => {
1821+ malformed_scope()
1822+ }
1823+ _ if path.starts_with("/cell/") => {
1824+ let cell = path[6..].to_string();
1825+ match app.request(cell.clone()).await {
1826+ Ok(Routed {
1827+ request,
1828+ route: Route::Local,
1829+ }) => {
1830+ let _activity = app.activity(request, cell.clone());
1831+ response(
1832+ StatusCode::OK,
1833+ format!("{{\"route\":\"local\",\"cell\":{cell:?}}}"),
1834+ )
1835+ }
1836+ Ok(Routed {
1837+ route:
1838+ Route::Remote {
1839+ node,
1840+ addr,
1841+ epoch,
1842+ peer_protocol,
1843+ },
1844+ ..
1845+ }) => response(
1846+ StatusCode::TEMPORARY_REDIRECT,
1847+ format!(
1848+ "{{\"route\":\"remote\",\"node\":{node:?},\"addr\":{addr:?},\"epoch\":{epoch},\"peer_protocol\":{peer_protocol}}}"
1849+ ),
1850+ ),
1851+ Err(error) => response(
1852+ StatusCode::SERVICE_UNAVAILABLE,
1853+ format!("{{\"error\":\"{error:?}\"}}"),
1854+ ),
1855+ }
1856+ }
1857+ _ if path.starts_with("/evict/") && !celld_logic::cell::valid_cell_scope(&path[7..]) => {
1858+ malformed_scope()
1859+ }
1860+ _ if path.starts_with("/evict/") => {
1861+ app.evict(path[7..].to_string()).await;
1862+ response(StatusCode::OK, "{\"ok\":true}")
1863+ }
1864+ _ => response(StatusCode::NOT_FOUND, "{\"error\":\"not_found\"}"),
1865+ };
1866+ // Close the connection behind any response sent while draining, so
1867+ // keep-alive clients reconnect to a healthy node and the drain loop
1868+ // can finish. A request that raced the drain flag converges on its
1869+ // next request, which hits the gate above.
1870+ let mut result = result;
1871+ if draining {
1872+ result.headers_mut().insert(
1873+ hyper::header::CONNECTION,
1874+ hyper::header::HeaderValue::from_static("close"),
1875+ );
1876+ }
1877+ Ok(result)
1878+}
1879+
1880+#[derive(Clone, Copy)]
1881+enum HttpSurface {
1882+ Public,
1883+ Internal,
1884+}
1885+
1886+fn serve_http_connection(
1887+ stream: tokio::net::TcpStream,
1888+ surface: HttpSurface,
1889+ app: AppHandle,
1890+ shutdown: mpsc::UnboundedSender<ShutdownMode>,
1891+ mut connection_drain: watch::Receiver<bool>,
1892+ connection_grace: std::time::Duration,
1893+) -> ConnectionFuture {
1894+ // Nagle + delayed-ACK stalls small request/response exchanges by tens
1895+ // of milliseconds; the log tier's append acks measured it directly (a
1896+ // ~70 ms floor on a sub-millisecond VPC path). Responses must leave
1897+ // when written, on every surface.
1898+ let _ = stream.set_nodelay(true);
1899+ Box::pin(async move {
1900+ // Serve on the runtime, not on this task. `main` drives its loop with
1901+ // `block_on`, so serving there put every connection on one core.
1902+ // Awaiting the spawned task keeps shutdown tracking unchanged.
1903+ let served = tokio::spawn(async move {
1904+ let connection_requests = ConnectionWorkerRequests::default();
1905+ let service_requests = connection_requests.clone();
1906+ let service = service_fn(move |request| {
1907+ let app = app.clone();
1908+ let shutdown = shutdown.clone();
1909+ let service_requests = service_requests.clone();
1910+ async move {
1911+ match surface {
1912+ HttpSurface::Public => handle_public(request, app, service_requests).await,
1913+ HttpSurface::Internal => handle_internal(request, app, shutdown).await,
1914+ }
1915+ }
1916+ });
1917+ let connection = http1::Builder::new()
1918+ // Reclaim a connection that never sends a complete request
1919+ // head. The timeout also bounds an idle keep-alive waiting
1920+ // for its next request.
1921+ .timer(hyper_util::rt::TokioTimer::new())
1922+ .header_read_timeout(std::time::Duration::from_secs(30))
1923+ .serve_connection(TokioIo::new(stream), service)
1924+ .with_upgrades();
1925+ tokio::pin!(connection);
1926+ let result = tokio::select! {
1927+ result = &mut connection => Some(result),
1928+ _ = connection_drain.changed() => {
1929+ connection.as_mut().graceful_shutdown();
1930+ tokio::time::timeout(connection_grace, &mut connection)
1931+ .await
1932+ .ok()
1933+ }
1934+ };
1935+ connection_requests.abort_all();
1936+ match result {
1937+ Some(Err(error)) => eprintln!("celld connection failed: {error}"),
1938+ None => tracing::warn!(
1939+ event = "connection_drain_forced",
1940+ grace_ms = connection_grace.as_millis(),
1941+ "forced an HTTP connection closed after its graceful drain"
1942+ ),
1943+ Some(Ok(())) => {}
1944+ }
1945+ });
1946+ let _ = served.await;
1947+ })
1948+}
1949+
1950+#[path = "main/cli.rs"]
1951+mod cli;
1952+use cli::{action_from_process, print_help, worker_loader_binding, Action};
1953+
1954+/// Cold routes are I/O concurrency, but must stay below the point where they
1955+/// can starve the node lease heartbeat or object store.
1956+const DEFAULT_MAX_CONCURRENT_ACTIVATIONS: usize = 128;
1957+/// celld's own default. Evictions are bounded far tighter than activations
1958+/// because each one carries a durability proof, and a node that lets its whole
1959+/// working set prove durability at once turns a walk down into a thundering
1960+/// herd against the bucket.
1961+const DEFAULT_MAX_CONCURRENT_EVICTIONS: usize = 4;
1962+/// The shutdown handoff bound. Wider than the eviction bound because a
1963+/// draining node has no live traffic left to protect and a stop grace to
1964+/// beat, but still bounded so a node-wide handoff cannot thundering-herd
1965+/// the bucket.
1966+const DEFAULT_MAX_CONCURRENT_RELEASES: usize = 128;
1967+/// Preserved SQLite snapshots make a same-node wake a rename instead of a
1968+/// remote restore, but must not grow with the lifetime population of a node.
1969+/// The walk is O(cached cells), so keep it off the hot maintenance cadence.
1970+const LOCAL_CACHE_PRUNE_PERIOD: std::time::Duration = std::time::Duration::from_secs(60);
1971+
1972+fn main() -> anyhow::Result<()> {
1973+ celld::env_vars::validate()?;
1974+ // Parse the telemetry group once, before any command or runtime work.
1975+ // Its specialized values share the strict scalar parsers in env_vars.
1976+ let telemetry_config = celld::telemetry::Config::from_env()?;
1977+ rustls::crypto::ring::default_provider()
1978+ .install_default()
1979+ .ok();
1980+ // Before the runtime exists, so every worker thread inherits a PKRU that
1981+ // grants access to V8's pointer-table protection key.
1982+ celld::runtime::init_v8();
1983+ let mut builder = tokio::runtime::Builder::new_multi_thread();
1984+ builder.enable_all();
1985+ if let Some(workers) = celld::env_vars::positive::<usize>("CELLD_TOKIO_THREADS")? {
1986+ builder.worker_threads(workers);
1987+ }
1988+ builder.build()?.block_on(async_main(telemetry_config))
1989+}
1990+
1991+async fn async_main(telemetry_config: Option<celld::telemetry::Config>) -> anyhow::Result<()> {
1992+ celld::asyncrt::set_host_handle(tokio::runtime::Handle::current());
1993+ // Docker and journald can stop consuming the process pipe during a log
1994+ // burst. Logging must lose diagnostics under that backpressure rather
1995+ // than block the Tokio workers that route requests and renew authority.
1996+ let (log_writer, log_guard) = tracing_appender::non_blocking::NonBlockingBuilder::default()
1997+ .buffered_lines_limit(8_192)
1998+ .lossy(true)
1999+ .finish(std::io::stdout());
2000+ *LOG_GUARD.lock().unwrap() = Some(log_guard);
2001+ tracing_subscriber::fmt()
2002+ .with_writer(log_writer)
2003+ // The custom writer defeats fmt's own TTY detection, and journald
2004+ // must not receive ANSI escapes.
2005+ .with_ansi(std::io::IsTerminal::is_terminal(&std::io::stdout()))
2006+ .with_env_filter(
2007+ tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
2008+ )
2009+ .init();
2010+ // After the subscriber, because this reports whether the allocator agreed
2011+ // to return freed pages on a timer. A node without that thread holds
2012+ // retention until a thread allocates again, which is the condition behind
2013+ // issue #36, so the operator has to be able to read the answer.
2014+ celld::memory::tune_allocator();
2015+ let mut settings = match action_from_process()? {
2016+ Action::Deploy(arguments) => return fleet::run_deploy(arguments).await,
2017+ Action::D1(arguments) => return celld::d1_cli::run(arguments).await,
2018+ Action::Connect(arguments) => {
2019+ return celld::control_plane::handle_connect_command(arguments).await
2020+ }
2021+ Action::Credentials(arguments) => {
2022+ return celld::control_plane::handle_credentials_command(arguments).await
2023+ }
2024+ Action::Token(arguments) => {
2025+ return celld::control_plane::handle_token_command(arguments).await
2026+ }
2027+ Action::Disconnect(arguments) => {
2028+ return celld::control_plane::handle_disconnect_command(arguments).await
2029+ }
2030+ Action::Help => {
2031+ print_help();
2032+ return Ok(());
2033+ }
2034+ Action::Version => {
2035+ let profile = if cfg!(debug_assertions) {
2036+ " (debug)"
2037+ } else {
2038+ ""
2039+ };
2040+ println!("celld {}{profile}", env!("CARGO_PKG_VERSION"));
2041+ return Ok(());
2042+ }
2043+ Action::Diagnose {
2044+ mut settings,
2045+ peers,
2046+ read_only,
2047+ } => {
2048+ let ingress = celld::startup::bind_ingress_listener(&settings.listen).await?;
2049+ let internal =
2050+ celld::startup::bind_internal_listener(&celld::startup::InternalListenerSettings {
2051+ listen: settings.internal_listen.clone(),
2052+ advertise: settings.advertise.clone(),
2053+ unsafe_public_advertise: settings.unsafe_public_advertise,
2054+ })
2055+ .await?;
2056+ // The bind proves the address is free; diagnose never serves on it,
2057+ // and an operator should not read this line as a running listener.
2058+ println!(
2059+ "ok listen {} (bind check; diagnose does not serve)",
2060+ ingress.listen
2061+ );
2062+ println!(
2063+ "ok internal listen {} (bind check; diagnose does not serve)",
2064+ internal.listen
2065+ );
2066+ println!(
2067+ "ok advertise {} ({}; direct reachability is not inferred)",
2068+ internal.advertise,
2069+ internal.advertise.scope()
2070+ );
2071+ let managed_storage = if settings.control_plane {
2072+ match celld::control_plane::installation_storage().context(
2073+ "managed diagnostics require an existing enrollment; run `celld --control-plane` first",
2074+ )? {
2075+ celld::control_plane::InstallationStorageConfig::Managed(storage) => {
2076+ settings.bucket = Some(storage.bucket.clone());
2077+ settings.endpoint = Some(storage.endpoint.clone());
2078+ settings.region = storage.region.clone();
2079+ Some(storage)
2080+ }
2081+ celld::control_plane::InstallationStorageConfig::Byo(storage) => {
2082+ settings.bucket = Some(storage.bucket);
2083+ settings.endpoint = storage.endpoint;
2084+ settings.region = storage.region;
2085+ None
2086+ }
2087+ }
2088+ } else {
2089+ None
2090+ };
2091+ let bucket = settings
2092+ .bucket
2093+ .ok_or_else(|| anyhow::anyhow!("celld diagnose requires --bucket"))?;
2094+ let client = fleet::bucket_client_with_credentials(
2095+ &bucket,
2096+ settings.endpoint.as_deref(),
2097+ &settings.region,
2098+ managed_storage.as_ref(),
2099+ )?;
2100+ return fleet::diagnose(&client, peers, settings.unsafe_public_advertise, read_only)
2101+ .await;
2102+ }
2103+ Action::Run(settings) => settings,
2104+ };
2105+ celld::startup::raise_file_limit();
2106+ let max_resident = celld::env_vars::optional("CELLD_MAX_RESIDENT_CELLS")?
2107+ // celld has no resident ceiling unless the operator configures one.
2108+ // The clean-sheet prototype originally defaulted to eight, which
2109+ // introduced eviction churn in otherwise unconstrained workloads and
2110+ // made cancellation semantics depend on cold-reactivation latency.
2111+ .unwrap_or(usize::MAX);
2112+ let local_cache_max_bytes = local_cache_max_bytes_from_environment()?;
2113+ let fail_publish_once = std::env::var_os("CELLD_TEST_FAIL_PUBLISH_ONCE").is_some();
2114+ let ingress = celld::startup::bind_ingress_listener(&settings.listen).await?;
2115+ let internal =
2116+ celld::startup::bind_internal_listener(&celld::startup::InternalListenerSettings {
2117+ listen: settings.internal_listen.clone(),
2118+ advertise: settings.advertise.clone(),
2119+ unsafe_public_advertise: settings.unsafe_public_advertise,
2120+ })
2121+ .await?;
2122+ let advertise = internal.advertise.to_string();
2123+ let listen = ingress.listen.to_string();
2124+ let listener = ingress.listener;
2125+ let internal_listener = internal.listener;
2126+ let mut adapter_credential_version = None;
2127+ let managed_storage = if settings.control_plane {
2128+ // The control plane issues and validates S3-compatible storage
2129+ // only. celld's GCS client authenticates with OAuth and its Azure
2130+ // client with an Azure identity or account key, and the control
2131+ // plane's S3-shaped credentials provide neither.
2132+ for scheme in ["gs://", "az://"] {
2133+ if settings
2134+ .bucket
2135+ .as_deref()
2136+ .is_some_and(|bucket| bucket.starts_with(scheme))
2137+ {
2138+ anyhow::bail!(
2139+ "--control-plane storage is S3-compatible; a {scheme} bucket runs without it"
2140+ );
2141+ }
2142+ }
2143+ // The control plane issues one bucket per fleet and its enrollment
2144+ // API rejects a bucket name holding a slash, so a prefix has neither
2145+ // a purpose nor a path through. Say so instead of failing enrollment.
2146+ if settings.bucket.as_deref().is_some_and(|b| b.contains('/')) {
2147+ anyhow::bail!("--control-plane does not accept a --bucket prefix");
2148+ }
2149+ let requested_byo =
2150+ settings
2151+ .bucket
2152+ .as_ref()
2153+ .map(|bucket| celld::control_plane::ByoStorageConfig {
2154+ bucket: bucket.clone(),
2155+ endpoint: settings.endpoint.clone(),
2156+ region: settings.region.clone(),
2157+ });
2158+ celld::control_plane::connect_on_startup_with_storage(requested_byo).await?;
2159+ settings.load_deployment = true;
2160+ let (storage, credential_version) =
2161+ celld::control_plane::installation_storage_with_version()?;
2162+ adapter_credential_version = Some(credential_version);
2163+ match storage {
2164+ celld::control_plane::InstallationStorageConfig::Managed(storage) => {
2165+ settings.bucket = Some(storage.bucket.clone());
2166+ settings.endpoint = Some(storage.endpoint.clone());
2167+ settings.region = storage.region.clone();
2168+ Some(storage)
2169+ }
2170+ celld::control_plane::InstallationStorageConfig::Byo(storage) => {
2171+ settings.bucket = Some(storage.bucket);
2172+ settings.endpoint = storage.endpoint;
2173+ settings.region = storage.region;
2174+ None
2175+ }
2176+ }
2177+ } else {
2178+ None
2179+ };
2180+ let storage_credentials =
2181+ managed_storage
2182+ .as_ref()
2183+ .map(|storage| celld::replication::StorageCredentials {
2184+ access_key_id: storage.access_key_id.clone(),
2185+ secret_access_key: storage.secret_access_key.clone(),
2186+ session_token: storage.session_token.clone(),
2187+ });
2188+ let (tx, rx) = mpsc::unbounded_channel();
2189+ let sample_tx = tx.clone();
2190+ let alarm_tx = tx.clone();
2191+ let alarm_observer: celld::runtime::AlarmObserver = Arc::new(move |cell, at_ms| {
2192+ let _ = alarm_tx.send(Message::AlarmObserved {
2193+ cell,
2194+ at_ms,
2195+ covered: false,
2196+ });
2197+ });
2198+ let (fence_tx, mut fence_rx) = mpsc::unbounded_channel();
2199+ let node = std::env::var("CELLD_NODE").unwrap_or_else(|_| random_node_session_id());
2200+ let clean_reload_node = node.clone();
2201+ celld::control_plane::install_reexec_node_session_id(&node)?;
2202+ let probe_public_key = celld::peer_probe::install_signer()?;
2203+ let max_activations =
2204+ celld::env_vars::positive::<usize>("CELLD_ACTIVATIONS")?.unwrap_or_else(|| {
2205+ std::thread::available_parallelism()
2206+ .map(usize::from)
2207+ .unwrap_or(1)
2208+ .min(DEFAULT_MAX_CONCURRENT_ACTIVATIONS)
2209+ });
2210+ let max_evictions = celld::env_vars::positive::<usize>("CELLD_EVICTIONS")?
2211+ .unwrap_or(DEFAULT_MAX_CONCURRENT_EVICTIONS);
2212+ let max_releases = celld::env_vars::positive::<usize>("CELLD_RELEASES")?
2213+ .unwrap_or(DEFAULT_MAX_CONCURRENT_RELEASES);
2214+ let data_dir = std::env::var_os("CELLD_TEST_DATA_DIR")
2215+ .or_else(|| std::env::var_os("CELLD_WATCH"))
2216+ .map(std::path::PathBuf::from)
2217+ .unwrap_or_else(|| std::env::temp_dir().join(format!("celld-{}", std::process::id())));
2218+ let mut deploy_agent = None;
2219+ let (runtime, ownership, peer_key, wake_scan, assets, asset_script) = if let Some(bucket) =
2220+ settings.bucket.clone().filter(|_| settings.load_deployment)
2221+ {
2222+ let client = fleet::bucket_client_with_credentials(
2223+ &bucket,
2224+ settings.endpoint.as_deref(),
2225+ &settings.region,
2226+ managed_storage.as_ref(),
2227+ )?;
2228+ if settings.control_plane {
2229+ fleet::validate_managed_bucket(&client).await?;
2230+ } else {
2231+ fleet::validate_bucket(&client).await?;
2232+ }
2233+ // The list above proves the bucket answers; it does not prove
2234+ // the store enforces the conditional write this node fences
2235+ // with. A store that ignores it makes the node self-fence in
2236+ // a restart loop, so test it once, here, before serving.
2237+ if settings.storage_probe {
2238+ fleet::probe_storage_before_serving(&client, settings.control_plane).await?;
2239+ }
2240+ let lease_client = fleet::lease_bucket_client_with_credentials(
2241+ &bucket,
2242+ settings.endpoint.as_deref(),
2243+ &settings.region,
2244+ managed_storage.as_ref(),
2245+ )?;
2246+ if settings.control_plane {
2247+ celld::control_plane::wait_for_initial_deployment(&client).await?;
2248+ deploy_agent = Some(client.clone());
2249+ }
2250+ let peer_key = peer_auth::load_or_create(&client).await?;
2251+ let mut deployment = fleet::load_current_worker(&client, node.clone()).await?;
2252+ let primary_script = deployment.script_name.clone();
2253+ let mut asset_resolvers = HashMap::new();
2254+ if let Some(resolver) = deployment.assets.take() {
2255+ asset_resolvers.insert(primary_script.clone(), resolver);
2256+ }
2257+ let mut visited = BTreeSet::from([primary_script.clone()]);
2258+ let mut queue = deployment
2259+ .services
2260+ .iter()
2261+ .map(|(_, script, _)| script.clone())
2262+ .collect::<VecDeque<_>>();
2263+ let mut cohosted = Vec::new();
2264+ while let Some(target) = queue.pop_front() {
2265+ if target == primary_script || !visited.insert(target.clone()) {
2266+ continue;
2267+ }
2268+ let mut loaded = fleet::load_named_worker(&client, &target, node.clone())
2269+ .await
2270+ .with_context(|| format!("load service binding target {target}"))?;
2271+ if loaded.script_name != target {
2272+ anyhow::bail!(
2273+ "service pointer {target} resolved script {}",
2274+ loaded.script_name
2275+ );
2276+ }
2277+ queue.extend(loaded.services.iter().map(|(_, script, _)| script.clone()));
2278+ // A node runs the schedule of the deployment it was given and
2279+ // of no other. The reserved class is one key, so a second
2280+ // script's cron cell would resolve to the first script's
2281+ // config and run the wrong `scheduled` handler. Dropping the
2282+ // schedule is the safe half of that trade and this says so out
2283+ // loud, because a trigger that never fires and says nothing is
2284+ // the failure the whole feature is built to avoid. Deploy the
2285+ // script as a node's own deployment to run its crons.
2286+ if !loaded.crons.is_empty() {
2287+ tracing::warn!(
2288+ script = %target,
2289+ crons = %loaded.crons.join(", "),
2290+ "a service binding target declares cron triggers; a node fires only its own deployment's schedule, so these never run here"
2291+ );
2292+ }
2293+ if let Some(resolver) = loaded.assets.take() {
2294+ asset_resolvers.insert(target, resolver);
2295+ }
2296+ cohosted.push(CohostedWorker {
2297+ options: loaded.options,
2298+ services: loaded.services,
2299+ asset_binding: loaded.asset_binding,
2300+ });
2301+ }
2302+ let wake = Arc::new(celld::wake::WakeFlusher::new());
2303+ celld::js::set_arm_gate(ArmGate {
2304+ bucket: client.clone(),
2305+ flusher: wake.clone(),
2306+ });
2307+ // celld treats replication as a node service, not as a property
2308+ // of today's manifest. Start it even for a stateless deployment
2309+ // so a later deployment can introduce cells without changing the
2310+ // durability contract underneath the node.
2311+ let replication = Some(Replication::start(
2312+ client.clone(),
2313+ &data_dir,
2314+ settings.endpoint.clone(),
2315+ settings.region.clone(),
2316+ storage_credentials.clone(),
2317+ )?);
2318+ let asset_script = Some(Arc::<str>::from(primary_script));
2319+ let assets = Arc::new(asset_resolvers);
2320+ let runtime = RuntimeManager::start(RuntimeOptions {
2321+ worker: deployment.options,
2322+ crons: deployment.crons,
2323+ services: deployment.services,
2324+ asset_binding: deployment.asset_binding,
2325+ loader_binding: worker_loader_binding(),
2326+ cohosted,
2327+ data_dir: data_dir.clone(),
2328+ replication,
2329+ wake: Some(wake.clone()),
2330+ alarm_observer: alarm_observer.clone(),
2331+ node: node.clone(),
2332+ region: settings.region.clone(),
2333+ })?;
2334+ let wake_scan = Some((client.clone(), wake.clone()));
2335+ let ownership = Ownership::Bucket(Arc::new(
2336+ BucketOwnership::new(client, lease_client, node.clone(), probe_public_key.clone())
2337+ .with_lease_ttl_ms(lease_ttl_ms_from_environment()),
2338+ ));
2339+ (
2340+ Some(runtime),
2341+ Some(ownership),
2342+ peer_key,
2343+ wake_scan,
2344+ assets,
2345+ asset_script,
2346+ )
2347+ } else if let Ok(script_path) = std::env::var("CELLD_TEST_SCRIPT_PATH") {
2348+ let source = std::fs::read_to_string(&script_path)?;
2349+ let do_classes = std::env::var("CELLD_TEST_DO_CLASSES")
2350+ .unwrap_or_default()
2351+ .split(',')
2352+ .map(str::trim)
2353+ .filter(|value| !value.is_empty())
2354+ .map(str::to_string)
2355+ .collect();
2356+ let bindings = std::env::var("CELLD_TEST_DO_BINDINGS")
2357+ .unwrap_or_default()
2358+ .split(',')
2359+ .filter_map(|value| value.split_once('='))
2360+ .map(|(name, class)| (name.trim().to_string(), class.trim().to_string()))
2361+ .filter(|(name, class)| !name.is_empty() && !class.is_empty())
2362+ .collect();
2363+ // `BINDING=database` pairs, the local-script equivalent of
2364+ // `d1_databases` in a deployed project.
2365+ let d1_bindings: Vec<(String, String)> = std::env::var("CELLD_TEST_D1_BINDINGS")
2366+ .unwrap_or_default()
2367+ .split(',')
2368+ .filter_map(|value| value.split_once('='))
2369+ .map(|(name, database)| (name.trim().to_string(), database.trim().to_string()))
2370+ .filter(|(name, database)| !name.is_empty() && !database.is_empty())
2371+ .collect();
2372+ let mut do_classes: Vec<String> = do_classes;
2373+ if !d1_bindings.is_empty() {
2374+ do_classes.push(celld::deploy::D1_CLASS.to_string());
2375+ }
2376+ let crons: Vec<String> = std::env::var("CELLD_TEST_CRONS")
2377+ .unwrap_or_default()
2378+ .split(';')
2379+ .map(str::trim)
2380+ .filter(|value| !value.is_empty())
2381+ .map(str::to_string)
2382+ .collect();
2383+ let options = WorkerConfigOptions {
2384+ src: source,
2385+ script_name: std::env::var("CELLD_TEST_SCRIPT_NAME")
2386+ .unwrap_or_else(|_| "celld-local".to_string()),
2387+ do_classes,
2388+ bindings,
2389+ r2_bindings: Vec::new(),
2390+ d1_bindings,
2391+ ai_binding: fleet::configured_ai_binding(None),
2392+ vars: Vec::new(),
2393+ node: node.clone(),
2394+ modules: Vec::new(),
2395+ compat: Compat::default(),
2396+ };
2397+ let (ownership, peer_key, wake, wake_scan) = match settings.bucket.clone() {
2398+ Some(bucket) => {
2399+ let client = fleet::bucket_client_with_credentials(
2400+ &bucket,
2401+ settings.endpoint.as_deref(),
2402+ &settings.region,
2403+ managed_storage.as_ref(),
2404+ )?;
2405+ let lease_client = fleet::lease_bucket_client_with_credentials(
2406+ &bucket,
2407+ settings.endpoint.as_deref(),
2408+ &settings.region,
2409+ managed_storage.as_ref(),
2410+ )?;
2411+ let peer_key = peer_auth::load_or_create(&client).await?;
2412+ let wake = Arc::new(celld::wake::WakeFlusher::new());
2413+ celld::js::set_arm_gate(ArmGate {
2414+ bucket: client.clone(),
2415+ flusher: wake.clone(),
2416+ });
2417+ let wake_scan = Some((client.clone(), wake.clone()));
2418+ (
2419+ Some(Ownership::Bucket(Arc::new(
2420+ BucketOwnership::new(
2421+ client,
2422+ lease_client,
2423+ node.clone(),
2424+ probe_public_key.clone(),
2425+ )
2426+ .with_lease_ttl_ms(lease_ttl_ms_from_environment()),
2427+ ))),
2428+ peer_key,
2429+ Some(wake),
2430+ wake_scan,
2431+ )
2432+ }
2433+ None => (None, random_peer_key(), None, None),
2434+ };
2435+ (
2436+ Some(RuntimeManager::start(RuntimeOptions {
2437+ worker: options,
2438+ crons,
2439+ services: Vec::new(),
2440+ asset_binding: None,
2441+ loader_binding: worker_loader_binding(),
2442+ cohosted: Vec::new(),
2443+ data_dir: data_dir.clone(),
2444+ replication: None,
2445+ wake: wake.clone(),
2446+ alarm_observer: alarm_observer.clone(),
2447+ node: node.clone(),
2448+ region: settings.region.clone(),
2449+ })?),
2450+ ownership,
2451+ peer_key,
2452+ wake_scan,
2453+ Arc::new(HashMap::new()),
2454+ None,
2455+ )
2456+ } else {
2457+ let (ownership, peer_key) = match settings.bucket.clone() {
2458+ Some(bucket) => {
2459+ let client = fleet::bucket_client_with_credentials(
2460+ &bucket,
2461+ settings.endpoint.as_deref(),
2462+ &settings.region,
2463+ managed_storage.as_ref(),
2464+ )?;
2465+ let lease_client = fleet::lease_bucket_client_with_credentials(
2466+ &bucket,
2467+ settings.endpoint.as_deref(),
2468+ &settings.region,
2469+ managed_storage.as_ref(),
2470+ )?;
2471+ let peer_key = peer_auth::load_or_create(&client).await?;
2472+ (
2473+ Some(Ownership::Bucket(Arc::new(
2474+ BucketOwnership::new(
2475+ client,
2476+ lease_client,
2477+ node.clone(),
2478+ probe_public_key.clone(),
2479+ )
2480+ .with_lease_ttl_ms(lease_ttl_ms_from_environment()),
2481+ ))),
2482+ peer_key,
2483+ )
2484+ }
2485+ None => (None, random_peer_key()),
2486+ };
2487+ (
2488+ None,
2489+ ownership,
2490+ peer_key,
2491+ None,
2492+ Arc::new(HashMap::new()),
2493+ None,
2494+ )
2495+ };
2496+ if let Some(config) = &telemetry_config {
2497+ let sink_bucket = match config.sink {
2498+ celld::telemetry::SinkChoice::Bucket => {
2499+ let Some(bucket) = settings.bucket.clone() else {
2500+ anyhow::bail!(
2501+ "CELLD_OTEL=1 but this node has no bucket; the \
2502+ bucket sink needs one (CELLD_BUCKET), or choose \
2503+ CELLD_OTEL_SINK=otlp"
2504+ );
2505+ };
2506+ // Its own client even for the fleet bucket: each open is its
2507+ // own transport (bucket.rs), so telemetry PUT bursts never
2508+ // share a connection pool with ownership traffic.
2509+ Some(fleet::bucket_client_with_credentials(
2510+ config.bucket_override.as_deref().unwrap_or(&bucket),
2511+ settings.endpoint.as_deref(),
2512+ &settings.region,
2513+ managed_storage.as_ref(),
2514+ )?)
2515+ }
2516+ // The collector path needs no bucket at all.
2517+ celld::telemetry::SinkChoice::Otlp => None,
2518+ };
2519+ celld::telemetry::init(config, sink_bucket, node.clone(), settings.region.clone())?;
2520+ }
2521+ let peer_auth = Arc::new(PeerAuth::new(peer_key, node.clone())?);
2522+ let resume_generation = celld::runtime::take_clean_reload_generation(&data_dir, &node);
2523+ let clean_reload_candidate = resume_generation.is_some();
2524+ let actor = Actor::from_environment(
2525+ AdmissionLimits {
2526+ resident: max_resident,
2527+ activations: max_activations,
2528+ evictions: max_evictions,
2529+ releases: max_releases,
2530+ },
2531+ fail_publish_once,
2532+ fence_tx,
2533+ runtime.clone(),
2534+ ownership,
2535+ ActorIdentity {
2536+ node: node.clone(),
2537+ advertise: advertise.clone(),
2538+ region: settings.region.clone(),
2539+ },
2540+ resume_generation,
2541+ )
2542+ .await?;
2543+ let process_generation = actor.lease_spec.generation.clone();
2544+ let ownership_name = actor.ownership.name();
2545+ let explorer_replication = runtime.as_ref().and_then(RuntimeManager::replication);
2546+ let local_cache_replication = explorer_replication.clone();
2547+ let (websocket_tx, mut websocket_rx) = mpsc::unbounded_channel();
2548+ // The log tier's follower store (crate::node_log): fragments other
2549+ // leaders replicate here live under the node's data dir beside the cell
2550+ // databases.
2551+ let follower = match &actor.ownership {
2552+ Ownership::Bucket(bucket_ownership) if settings.bucket.is_some() => {
2553+ Some(Arc::new(celld::node_log::FollowerStore::new(
2554+ &data_dir,
2555+ Some(Arc::new(bucket_ownership.bucket_client())),
2556+ &node,
2557+ )))
2558+ }
2559+ _ => None,
2560+ };
2561+ if let Some(store) = &follower {
2562+ celld::node_log::spawn_fragment_gc(store.clone());
2563+ }
2564+ let app = AppHandle {
2565+ tx,
2566+ runtime,
2567+ assets,
2568+ asset_script,
2569+ // Connect-only timeout: a peer request may legitimately run long, but
2570+ // a handshake that never completes provably ran nothing, so failing it
2571+ // fast lets the caller re-resolve the owner and redispatch.
2572+ peer_http: reqwest::Client::builder()
2573+ .connect_timeout(PEER_CONNECT_TIMEOUT)
2574+ .build()
2575+ .unwrap(),
2576+ peer_auth,
2577+ advertise: advertise.clone(),
2578+ websockets: websocket_tx,
2579+ draining: Arc::new(std::sync::atomic::AtomicBool::new(false)),
2580+ trust_forwarded_headers: settings.trust_forwarded_headers,
2581+ // RPO=0 is the default. An operator can disable the output gate to
2582+ // remove object-store replication latency from the write response,
2583+ // explicitly accepting that an acknowledged write can be lost.
2584+ output_gate: celld::env_vars::flag("CELLD_OUTPUT_GATE", true)?,
2585+ max_outbound_websockets: celld::env_vars::positive_or(
2586+ "CELLD_MAX_OUTBOUND_WEBSOCKETS",
2587+ DEFAULT_MAX_OUTBOUND_WEBSOCKETS,
2588+ )?,
2589+ follower,
2590+ };
2591+
2592+ // The in-fleet log tier, v0. The takeover interlock is installed in
2593+ // every posture — a bucket-posture node can take over from a
2594+ // fleet-posture one and must find a complete bucket — while shipping
2595+ // requires the explicit fleet posture.
2596+ // Fleet is the DEFAULT (decided 2026-08-14): a single node behaves
2597+ // exactly like sync-to-bucket — no peers means no record, no shipper,
2598+ // and bucket-proven acks — and the moment peers appear the
2599+ // maintenance tick recruits them and fleet replication turns on. One
2600+ // value serves the hobbyist's first node and the fleet it grows into;
2601+ // CELLD_DURABILITY=bucket remains the explicit opt-out.
2602+ let durability = std::env::var("CELLD_DURABILITY").unwrap_or_else(|_| "fleet".into());
2603+ anyhow::ensure!(
2604+ matches!(durability.as_str(), "bucket" | "fleet"),
2605+ "CELLD_DURABILITY must be `bucket` or `fleet`"
2606+ );
2607+ let mut node_log_close: Option<Arc<celld::node_log::NodeLogManager>> = None;
2608+ if let Ownership::Bucket(bucket_ownership) = &actor.ownership {
2609+ if let (Some(replication), Some(spec)) = (
2610+ app.runtime.as_ref().and_then(RuntimeManager::replication),
2611+ settings.bucket.clone(),
2612+ ) {
2613+ let _ = spec;
2614+ let log_bucket = Arc::new(bucket_ownership.bucket_client());
2615+ let ltx = replication.ltx();
2616+ // Bundle the paced tiering: one PUT per node-flush instead of
2617+ // one per cell-transaction — the Class A collapse, measured at
2618+ // 208x against per-transaction PUTs. On by default; 0 is the
2619+ // opt-out.
2620+ let bundle_mode = celld::env_vars::flag("CELLD_LOG_BUNDLE", true)?;
2621+ let nudge_tx = app.tx.clone();
2622+ let own_log = Arc::new(celld::node_log::OwnLog {
2623+ ownership: bucket_ownership.clone(),
2624+ nudge: Box::new(move || {
2625+ let _ = nudge_tx.send(Message::NudgeNodeLease);
2626+ }),
2627+ write_lock: tokio::sync::Mutex::new(()),
2628+ });
2629+ let manager = Arc::new(celld::node_log::NodeLogManager::new(
2630+ &format!("{node}/{process_generation}"),
2631+ log_bucket,
2632+ own_log,
2633+ ltx.clone(),
2634+ app.peer_auth.clone(),
2635+ bundle_mode,
2636+ celld::node_log::eviction_policy_from_env()?,
2637+ ));
2638+ *actor.node_log.lock().unwrap() = Some(manager.clone());
2639+ node_log_close = Some(manager.clone());
2640+ // Recovery-before-install, EVERY posture, FATAL on failure
2641+ // (cold reviews, B2/B3 and the second pass's finding 2): the
2642+ // predecessor's folded state lives in the lease record this
2643+ // session is about to replace, and the install writes a fresh
2644+ // log — so an unrecovered predecessor must stop the boot, or
2645+ // the install erases the only evidence recovery was needed.
2646+ // The ladder waits out the predecessor's own lease (the S1
2647+ // fence recheck refuses a live lease), retries with backoff,
2648+ // and exits on exhaustion; systemd restarts while peers'
2649+ // follower stores come back. No hostage problem — this node
2650+ // has no lease yet, and peers may race the same
2651+ // CAS-idempotent recovery.
2652+ {
2653+ let ttl_backoff =
2654+ std::time::Duration::from_millis(actor.lease_spec.ttl_ms.max(1_000));
2655+ let mut recovered = Ok(());
2656+ for attempt in 1..=4u32 {
2657+ recovered = match tokio::time::timeout(
2658+ std::time::Duration::from_secs(180),
2659+ manager.recover_self(),
2660+ )
2661+ .await
2662+ {
2663+ Ok(result) => result,
2664+ Err(_) => Err(anyhow::anyhow!("predecessor recovery timed out")),
2665+ };
2666+ if recovered.is_ok() || attempt == 4 {
2667+ break;
2668+ }
2669+ if let Err(error) = recovered.as_ref() {
2670+ eprintln!("celld predecessor recovery attempt {attempt} failed: {error:#}");
2671+ }
2672+ // At least one full TTL between attempts, so a
2673+ // refused-because-live predecessor lease has expired
2674+ // by the retry.
2675+ tokio::time::sleep(ttl_backoff.saturating_mul(attempt)).await;
2676+ }
2677+ recovered.map_err(|error| {
2678+ anyhow::anyhow!(
2679+ "refusing to install a lease over an unrecovered \
2680+ predecessor log: {error:#}"
2681+ )
2682+ })?;
2683+ }
2684+ if durability == "fleet" {
2685+ ltx.set_shipper(manager.clone());
2686+ if bundle_mode {
2687+ ltx.set_bundle_sink(manager.clone());
2688+ }
2689+ celld::node_log::spawn_maintenance(manager);
2690+ }
2691+ }
2692+ }
2693+ let (do_call_tx, mut do_call_rx) = mpsc::unbounded_channel();
2694+ celld::js::set_do_call_tx(do_call_tx);
2695+ let (gate_tx, mut gate_rx) = mpsc::unbounded_channel();
2696+ celld::js::set_gate_tx(gate_tx);
2697+ let (rpc_call_tx, mut rpc_call_rx) = mpsc::unbounded_channel();
2698+ celld::js::set_rpc_call_tx(rpc_call_tx);
2699+ let (service_call_tx, mut service_call_rx) = mpsc::unbounded_channel();
2700+ celld::js::set_svc_call_tx(service_call_tx);
2701+ let (service_rpc_tx, mut service_rpc_rx) = mpsc::unbounded_channel();
2702+ celld::js::set_svc_rpc_tx(service_rpc_tx);
2703+ let (asset_call_tx, mut asset_call_rx) = mpsc::unbounded_channel();
2704+ celld::js::set_asset_call_tx(asset_call_tx);
2705+ let (outbound_ws_tx, mut outbound_ws_rx) = mpsc::unbounded_channel();
2706+ celld::js::set_outbound_ws_tx(outbound_ws_tx);
2707+ // The core is a serial ownership actor, not a Worker executor. It owns the
2708+ // node lease timer, so ingress, proxy retries, and restore completions must
2709+ // not consume every scheduler turn it needs. Its isolated single-thread
2710+ // runtime also keeps state transitions ordered exactly as the deterministic
2711+ // executor models them. Request work, restores, and blocking scans stay on
2712+ // the shared runtime and report their results back as messages.
2713+ let (actor_exit_tx, mut actor_exit_rx) = mpsc::unbounded_channel();
2714+ std::thread::Builder::new()
2715+ .name("celld-core".into())
2716+ .spawn(move || {
2717+ let result = tokio::runtime::Builder::new_current_thread()
2718+ .enable_all()
2719+ .build()
2720+ .map_err(|error| error.to_string())
2721+ .map(|runtime| runtime.block_on(actor.run(rx)));
2722+ let _ = actor_exit_tx.send(result);
2723+ })?;
2724+
2725+ // The sampler is a plain ticker: it measures and posts, and decides
2726+ // nothing. Everything downstream of the numbers -- the latch, the target,
2727+ // which cell goes -- is in the core, so a sample sequence replays.
2728+ {
2729+ const LOAD_SAMPLE_PERIOD: std::time::Duration = std::time::Duration::from_secs(1);
2730+ celld::asyncrt::spawn(async move {
2731+ let mut tick = celld::asyncrt::interval(LOAD_SAMPLE_PERIOD);
2732+ tick.set_missed_tick_behavior(celld::asyncrt::MissedTickBehavior::Delay);
2733+ loop {
2734+ tick.tick().await;
2735+ if sample_tx.send(Message::SampleLoad).is_err() {
2736+ return;
2737+ }
2738+ }
2739+ })
2740+ .detach();
2741+ }
2742+
2743+ if let Some((client, wake)) = wake_scan {
2744+ let authority_wait_seconds = if clean_reload_candidate { 60 } else { 10 };
2745+ let deadline = Instant::now() + std::time::Duration::from_secs(authority_wait_seconds);
2746+ while !app.healthy().await {
2747+ if Instant::now() >= deadline {
2748+ anyhow::bail!("node authority was not established before wake scan");
2749+ }
2750+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
2751+ }
2752+ for (cell, due_ms) in celld::wake::due_scan(&client, now_ms() as i64).await {
2753+ wake.adopt(&cell, due_ms);
2754+ let _ = app.tx.send(Message::WakeHint { cell });
2755+ }
2756+
2757+ // And again, on a timer, for the rest of the process's life.
2758+ //
2759+ // The boot scan alone only covers alarms that came due while nothing
2760+ // was watching *before this node started*. A node that dies while
2761+ // this one is already running leaves its cells with armed alarms and
2762+ // no owner, and nothing would look at them again until this process
2763+ // restarted -- an alarm silently not firing, which is the one thing a
2764+ // Durable Object is not allowed to do.
2765+ //
2766+ // Every decision about a due entry stays in the core: a hint for a
2767+ // cell this node already serves is ignored, and one for a cell with a
2768+ // live owner elsewhere resolves to that owner rather than stealing
2769+ // it. The scan only reports what the bucket says is due.
2770+ let scan_app = app.clone();
2771+ let waker_node = node.clone();
2772+ let tick_ms = celld::env_vars::positive::<u64>("CELLD_WAKER_TICK_MS")?.unwrap_or(60_000);
2773+ let period = std::time::Duration::from_millis(tick_ms);
2774+ celld::asyncrt::spawn(async move {
2775+ let mut tick = celld::asyncrt::interval(period);
2776+ tick.set_missed_tick_behavior(celld::asyncrt::MissedTickBehavior::Delay);
2777+ tick.tick().await;
2778+ let mut dead_node_gc = celld::dead_node_gc::DeadNodeGc::default();
2779+ loop {
2780+ tick.tick().await;
2781+ dead_node_gc
2782+ .run_elected_pass(&client, &waker_node, tick_ms)
2783+ .await;
2784+ for (cell, due_ms) in celld::wake::due_scan(&client, now_ms() as i64).await {
2785+ wake.adopt(&cell, due_ms);
2786+ if scan_app.tx.send(Message::WakeHint { cell }).is_err() {
2787+ return;
2788+ }
2789+ }
2790+ }
2791+ })
2792+ .detach();
2793+ }
2794+
2795+ // Arm this deployment's cron schedule. A cron cell has no client to wake
2796+ // it, so somebody has to make the first call; every node makes it, and
2797+ // ownership CAS decides which one keeps the cell while the others route to
2798+ // that owner. No new election, no reserved node -- the same arbiter that
2799+ // makes an alarm fire once per fleet makes a cron trigger fire once too.
2800+ //
2801+ // Nothing re-arms after this. Once the schedule is in the cell's alarm row
2802+ // it is durable, its wake entry is in the bucket, and losing the owner is
2803+ // the ordinary alarm-recovery path: the fleet waker finds the due entry
2804+ // and another node takes the cell over.
2805+ if let Some(cell) = app.runtime.as_ref().and_then(|runtime| runtime.cron_cell()) {
2806+ let arm_app = app.clone();
2807+ tokio::spawn(async move {
2808+ // Routing needs node authority, exactly as the wake scan does.
2809+ let deadline = Instant::now() + std::time::Duration::from_secs(30);
2810+ while !arm_app.healthy().await {
2811+ if Instant::now() >= deadline {
2812+ tracing::warn!(cell, "cron schedule not armed: no node authority");
2813+ return;
2814+ }
2815+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
2816+ }
2817+ // A failed arm leaves the schedule silent until the next restart,
2818+ // so retry rather than log once. The backoff is bounded because a
2819+ // fleet that cannot route for a minute has a larger problem.
2820+ for attempt in 0..5 {
2821+ match arm_cron_schedule(arm_app.clone(), cell.clone()).await {
2822+ Ok(()) => return,
2823+ Err(error) if attempt == 4 => {
2824+ tracing::error!(cell, %error, "cron schedule not armed");
2825+ }
2826+ Err(error) => {
2827+ tracing::warn!(cell, %error, attempt, "cron arm failed, retrying");
2828+ tokio::time::sleep(std::time::Duration::from_millis(500 << attempt.min(5)))
2829+ .await;
2830+ }
2831+ }
2832+ }
2833+ });
2834+ }
2835+
2836+ if let Some(client) = deploy_agent {
2837+ celld::control_plane::start_deploy_agent(client.clone(), Arc::new(AtomicBool::new(true)));
2838+ let presence_app = app.clone();
2839+ celld::control_plane::start_presence_agent(celld::control_plane::PresenceRuntime {
2840+ s3: client,
2841+ replication: explorer_replication,
2842+ node_session_id: node,
2843+ advertise,
2844+ listen,
2845+ credential_version: adapter_credential_version
2846+ .expect("managed adapters have a credential version"),
2847+ snapshot: Arc::new(move || {
2848+ let app = presence_app.clone();
2849+ Box::pin(async move { app.presence().await })
2850+ }),
2851+ });
2852+ }
2853+
2854+ println!(
2855+ "celld listening on {} (ownership={ownership_name})",
2856+ listener.local_addr()?
2857+ );
2858+ println!(
2859+ "celld internal listening on {} (advertise={})",
2860+ internal_listener.local_addr()?,
2861+ app.advertise
2862+ );
2863+ let (shutdown_tx, mut shutdown_rx) = mpsc::unbounded_channel();
2864+ // A SIGTERM (systemd stop, `docker stop`, a Kubernetes pod delete) or a
2865+ // SIGINT begins the same graceful shutdown as `POST /shutdown`, so the
2866+ // orchestrator's ordinary stop drains and hands off instead of killing.
2867+ let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
2868+ let mut sigint = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())?;
2869+ let (connection_drain_tx, connection_drain) = watch::channel(false);
2870+ let drain_ms: u64 = celld::env_vars::positive("CELLD_SHUTDOWN_DRAIN_MS")?.unwrap_or(25_000);
2871+ // A hung connection must not consume the whole preserve budget: the
2872+ // semantic drain and the clean-reload certificate come out of the same
2873+ // deadline.
2874+ let connection_grace =
2875+ CONNECTION_DRAIN_GRACE.min(std::time::Duration::from_millis(drain_ms / 4));
2876+ let mut connections: FuturesUnordered<ConnectionFuture> = FuturesUnordered::new();
2877+ let mut do_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new();
2878+ let mut gate_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new();
2879+ let mut service_calls: FuturesUnordered<DoCallFuture> = FuturesUnordered::new();
2880+ let mut asset_calls: FuturesUnordered<AssetCallFuture> = FuturesUnordered::new();
2881+ let mut websockets: FuturesUnordered<WebSocketFuture> = FuturesUnordered::new();
2882+ let mut cache_prunes: FuturesUnordered<CachePruneFuture> = FuturesUnordered::new();
2883+ let mut replication_health = tokio::time::interval(std::time::Duration::from_millis(250));
2884+ let mut local_cache_prune = tokio::time::interval_at(
2885+ tokio::time::Instant::now() + LOCAL_CACHE_PRUNE_PERIOD,
2886+ LOCAL_CACHE_PRUNE_PERIOD,
2887+ );
2888+ local_cache_prune.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
2889+ let shutdown_mode = loop {
2890+ tokio::select! {
2891+ connection = listener.accept() => {
2892+ let (stream, _) = connection?;
2893+ connections.push(serve_http_connection(
2894+ stream,
2895+ HttpSurface::Public,
2896+ app.clone(),
2897+ shutdown_tx.clone(),
2898+ connection_drain.clone(),
2899+ connection_grace,
2900+ ));
2901+ }
2902+ connection = internal_listener.accept() => {
2903+ let (stream, _) = connection?;
2904+ connections.push(serve_http_connection(
2905+ stream,
2906+ HttpSurface::Internal,
2907+ app.clone(),
2908+ shutdown_tx.clone(),
2909+ connection_drain.clone(),
2910+ connection_grace,
2911+ ));
2912+ }
2913+ Some(()) = connections.next(), if !connections.is_empty() => {}
2914+ call = do_call_rx.recv() => {
2915+ let Some(call) = call else {
2916+ anyhow::bail!("Durable Object call channel closed");
2917+ };
2918+ do_calls.push(Box::pin(dispatch_do_call(app.clone(), call)));
2919+ }
2920+ Some(()) = do_calls.next(), if !do_calls.is_empty() => {}
2921+ req = gate_rx.recv() => {
2922+ let Some(req) = req else {
2923+ anyhow::bail!("output-gate channel closed");
2924+ };
2925+ gate_calls.push(Box::pin(dispatch_gate(app.clone(), req)));
2926+ }
2927+ Some(()) = gate_calls.next(), if !gate_calls.is_empty() => {}
2928+ call = service_call_rx.recv() => {
2929+ let Some(call) = call else {
2930+ anyhow::bail!("service call channel closed");
2931+ };
2932+ service_calls.push(Box::pin(dispatch_service_call(app.clone(), call)));
2933+ }
2934+ call = service_rpc_rx.recv() => {
2935+ let Some(call) = call else {
2936+ anyhow::bail!("service RPC channel closed");
2937+ };
2938+ service_calls.push(Box::pin(dispatch_service_rpc(app.clone(), call)));
2939+ }
2940+ Some(()) = service_calls.next(), if !service_calls.is_empty() => {}
2941+ call = rpc_call_rx.recv() => {
2942+ let Some(call) = call else {
2943+ anyhow::bail!("Durable Object RPC channel closed");
2944+ };
2945+ do_calls.push(Box::pin(dispatch_rpc_call(app.clone(), call)));
2946+ }
2947+ call = asset_call_rx.recv() => {
2948+ let Some(call) = call else {
2949+ anyhow::bail!("asset call channel closed");
2950+ };
2951+ asset_calls.push(Box::pin(dispatch_asset_call(app.clone(), call)));
2952+ }
2953+ Some(()) = asset_calls.next(), if !asset_calls.is_empty() => {}
2954+ socket = websocket_rx.recv() => {
2955+ let Some(socket) = socket else {
2956+ anyhow::bail!("WebSocket channel closed");
2957+ };
2958+ websockets.push(socket);
2959+ }
2960+ Some(()) = websockets.next(), if !websockets.is_empty() => {}
2961+ _ = local_cache_prune.tick(), if local_cache_replication.is_some()
2962+ && local_cache_max_bytes.is_some() && cache_prunes.is_empty() => {
2963+ let replication = local_cache_replication.clone().unwrap();
2964+ let max_bytes = local_cache_max_bytes.unwrap();
2965+ cache_prunes.push(Box::pin(async move {
2966+ let result = celld::asyncrt::blocking(move || {
2967+ replication.prune_local_cache(max_bytes)
2968+ }).await;
2969+ (max_bytes, result)
2970+ }));
2971+ }
2972+ Some((max_bytes, result)) = cache_prunes.next(), if !cache_prunes.is_empty() => {
2973+ match result {
2974+ Ok(Ok((kept, evicted, bytes))) if evicted > 0 => {
2975+ tracing::info!(
2976+ event = "local_cache_pruned",
2977+ kept,
2978+ evicted,
2979+ bytes,
2980+ max_bytes,
2981+ "pruned least-recently-used eviction snapshots"
2982+ );
2983+ }
2984+ Ok(Ok(_)) => {}
2985+ Ok(Err(error)) => {
2986+ tracing::warn!(%error, "local cache inventory failed");
2987+ }
2988+ Err(error) => {
2989+ tracing::warn!(%error, "local cache pruning task failed");
2990+ }
2991+ }
2992+ }
2993+ outbound = outbound_ws_rx.recv() => {
2994+ let Some(outbound) = outbound else {
2995+ anyhow::bail!("outbound WebSocket channel closed");
2996+ };
2997+ let app = app.clone();
2998+ websockets.push(Box::pin(async move {
2999+ if let Err(error) = outbound_websocket_task(app, outbound).await {
3000+ eprintln!("celld outbound WebSocket failed: {error:#}");
3001+ }
3002+ }));
3003+ }
3004+ mode = shutdown_rx.recv() => break mode.unwrap_or(ShutdownMode::Handoff),
3005+ _ = sigterm.recv() => break ShutdownMode::Handoff,
3006+ _ = sigint.recv() => break ShutdownMode::Handoff,
3007+ code = fence_rx.recv() => {
3008+ exit_flushed(code.unwrap_or(3));
3009+ }
3010+ actor_exit = actor_exit_rx.recv() => {
3011+ let error = match actor_exit {
3012+ Some(Err(error)) => error,
3013+ Some(Ok(())) => "the core actor stopped unexpectedly".to_string(),
3014+ None => "the core actor thread panicked".to_string(),
3015+ };
3016+ tracing::error!(
3017+ event = "core_actor_exit",
3018+ %error,
3019+ "SELF-FENCE: the core actor exited unexpectedly"
3020+ );
3021+ exit_flushed(3);
3022+ }
3023+ _ = replication_health.tick() => {
3024+ if let Some(runtime) = &app.runtime {
3025+ match runtime.replication_status() {
3026+ Ok(None) => {}
3027+ Ok(Some(status)) => {
3028+ eprintln!("SELF-FENCE: replication process exited unexpectedly: {status}");
3029+ exit_flushed(3);
3030+ }
3031+ Err(error) => {
3032+ eprintln!("SELF-FENCE: replication process health check failed: {error}");
3033+ exit_flushed(3);
3034+ }
3035+ }
3036+ }
3037+ }
3038+ }
3039+ };
3040+ // Graceful shutdown. Report unhealthy so a load balancer sheds this node,
3041+ // and refuse new work. Keep accepting bounded health and diagnostic
3042+ // requests while the semantic drain runs. A node removal hands every
3043+ // resident cell to a peer. A planned same-node replacement preserves
3044+ // ownership and its local replica cache, so the replacement does not
3045+ // create a fleet-wide cold handoff or lasting skew.
3046+ app.draining
3047+ .store(true, std::sync::atomic::Ordering::Relaxed);
3048+ let _ = connection_drain_tx.send(true);
3049+ // Receivers cloned from `connection_drain` have already observed an old
3050+ // version, so `changed()` would close each newly accepted connection
3051+ // before it could send a diagnostic response. Give drain-time connections
3052+ // their own signal. They are deliberately absent from `shell_drained`: an
3053+ // incomplete health request must not prevent a clean reload certificate.
3054+ let (drain_connection_tx, drain_connection) = watch::channel(false);
3055+ let mut drain_connections: FuturesUnordered<ConnectionFuture> = FuturesUnordered::new();
3056+ if shutdown_mode == ShutdownMode::Handoff {
3057+ let _ = app.tx.send(Message::ReleaseAll);
3058+ } else {
3059+ let _ = app.tx.send(Message::BeginPreserve);
3060+ }
3061+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_millis(drain_ms);
3062+ let mut handoff = tokio::time::interval(std::time::Duration::from_millis(50));
3063+ let drained = loop {
3064+ let shell_drained = connections.is_empty()
3065+ && do_calls.is_empty()
3066+ && gate_calls.is_empty()
3067+ && service_calls.is_empty()
3068+ && asset_calls.is_empty()
3069+ && websockets.is_empty();
3070+ // The actor can be busy driving an immediate-effect failure loop, so
3071+ // a status request is not itself allowed to bypass the drain deadline.
3072+ let core_drained = if shell_drained {
3073+ tokio::time::timeout(std::time::Duration::from_millis(50), app.drain_status())
3074+ .await
3075+ .is_ok_and(|status| match shutdown_mode {
3076+ ShutdownMode::Handoff => status.occupied == 0 && status.releasing == 0,
3077+ ShutdownMode::Preserve => status.activating == 0 && status.evicting == 0,
3078+ })
3079+ } else {
3080+ false
3081+ };
3082+ if shell_drained && core_drained {
3083+ break true;
3084+ }
3085+ tokio::select! {
3086+ _ = tokio::time::sleep_until(deadline) => break false,
3087+ _ = handoff.tick() => {}
3088+ connection = listener.accept() => {
3089+ let (stream, _) = connection?;
3090+ drain_connections.push(serve_http_connection(
3091+ stream,
3092+ HttpSurface::Public,
3093+ app.clone(),
3094+ shutdown_tx.clone(),
3095+ drain_connection.clone(),
3096+ connection_grace,
3097+ ));
3098+ }
3099+ connection = internal_listener.accept() => {
3100+ let (stream, _) = connection?;
3101+ drain_connections.push(serve_http_connection(
3102+ stream,
3103+ HttpSurface::Internal,
3104+ app.clone(),
3105+ shutdown_tx.clone(),
3106+ drain_connection.clone(),
3107+ connection_grace,
3108+ ));
3109+ }
3110+ Some(_) = drain_connections.next(), if !drain_connections.is_empty() => {}
3111+ Some(_) = connections.next(), if !connections.is_empty() => {}
3112+ Some(_) = do_calls.next(), if !do_calls.is_empty() => {}
3113+ Some(_) = gate_calls.next(), if !gate_calls.is_empty() => {}
3114+ Some(_) = service_calls.next(), if !service_calls.is_empty() => {}
3115+ Some(_) = asset_calls.next(), if !asset_calls.is_empty() => {}
3116+ Some(_) = websockets.next(), if !websockets.is_empty() => {}
3117+ }
3118+ };
3119+ let _ = drain_connection_tx.send(true);
3120+ if !drained && shutdown_mode == ShutdownMode::Handoff {
3121+ match tokio::time::timeout(
3122+ std::time::Duration::from_millis(50),
3123+ app.drain_status(),
3124+ )
3125+ .await
3126+ {
3127+ Ok(status) => eprintln!(
3128+ "celld shutdown drain reached its {drain_ms}ms deadline: occupied={} activating={} evicting={} releasing={}",
3129+ status.occupied, status.activating, status.evicting, status.releasing
3130+ ),
3131+ Err(_) => eprintln!(
3132+ "celld shutdown drain reached its {drain_ms}ms deadline: core status unavailable"
3133+ ),
3134+ }
3135+ } else if !drained {
3136+ eprintln!(
3137+ "celld preserve drain reached its {drain_ms}ms deadline: connections={} do_calls={} gate_calls={} service_calls={} asset_calls={} websockets={}",
3138+ connections.len(),
3139+ do_calls.len(),
3140+ gate_calls.len(),
3141+ service_calls.len(),
3142+ asset_calls.len(),
3143+ websockets.len(),
3144+ );
3145+ }
3146+ // The graceful-shutdown drain point: seal our node-log record so the
3147+ // next incarnation starts with no gather. Guarded inside — it seals
3148+ // only when every shipped frame is bucket-covered.
3149+ if let Some(manager) = &node_log_close {
3150+ manager.close_gracefully().await;
3151+ }
3152+ if drained && shutdown_mode == ShutdownMode::Preserve {
3153+ let prepared = match (&app.runtime, app.presence().await) {
3154+ (Some(runtime), Some(presence)) => {
3155+ let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
3156+ tokio::time::timeout(remaining, runtime.prepare_clean_reload(&presence.cells)).await
3157+ }
3158+ _ => Ok(Err(anyhow::anyhow!(
3159+ "clean reload requires a runtime and a resident snapshot"
3160+ ))),
3161+ };
3162+ match prepared {
3163+ Ok(Ok(pruned)) if app.healthy().await => {
3164+ match celld::runtime::write_clean_reload_marker(
3165+ &data_dir,
3166+ &clean_reload_node,
3167+ &process_generation,
3168+ ) {
3169+ Ok(()) => tracing::info!(
3170+ event = "clean_reload_prepared",
3171+ stale_live_databases_pruned = pruned,
3172+ "prepared local cells for an exact-generation reload"
3173+ ),
3174+ Err(error) => tracing::warn!(
3175+ event = "clean_reload_abandoned",
3176+ %error,
3177+ "could not publish the clean local reload certificate"
3178+ ),
3179+ }
3180+ }
3181+ Ok(Ok(_)) => tracing::warn!(
3182+ event = "clean_reload_abandoned",
3183+ "node authority was lost while local cells were closing"
3184+ ),
3185+ Ok(Err(error)) => tracing::warn!(
3186+ event = "clean_reload_abandoned",
3187+ %error,
3188+ "local reload preparation failed; replacement will use normal recovery"
3189+ ),
3190+ Err(_) => tracing::warn!(
3191+ event = "clean_reload_abandoned",
3192+ "local reload preparation exceeded the shutdown deadline"
3193+ ),
3194+ }
3195+ }
3196+ // Exit without unwinding. Returning from here drops the tokio runtime
3197+ // and the V8 platform underneath tasks and isolates that are still
3198+ // alive -- on a deadline-cut drain that teardown segfaults (status 139
3199+ // observed fleet-wide, 2026-08-10). Nothing below needs a destructor:
3200+ // every release the drain completed proved durability first, and a
3201+ // cell the deadline cut off keeps its owner record exactly as a kill
3202+ // would have left it.
3203+ exit_flushed(0);
3204+}
3205+
3206+use celld::machine::{
3207+ lease_ttl_ms_from_environment, local_cache_max_bytes_from_environment, random_node_session_id,
3208+ random_peer_key, DEFAULT_MAX_OUTBOUND_WEBSOCKETS, PEER_CONNECT_TIMEOUT,
50963209 };
50973210
50983211 /// Signals cancellation when the connection handling this request goes away.
modifiedcrates/celld/main/cli.rs+281−272View file
Diff not rendered to keep this page fast. View the file
deletedcrates/celld/main/machine.rs+0−209
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/main/websocket.rs+826−699View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/memory.rs+22−21View file
Diff not rendered to keep this page fast. View the file
addedcrates/celld/node_log.rs+2940−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ownership_store.rs+460−373View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/peer_auth.rs+4−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/peer_probe.rs+3−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/pool.rs+407−405View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/protocol.rs+180−155View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/replication.rs+396−139View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/runtime.rs+2052−1777View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/startup.rs+1−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/storage.rs+3704−2696View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/telemetry.rs+3−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/wake.rs+349−261View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/celld/ws_client.rs+3−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/cell.rs+33−20View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/cron.rs+603−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/isolate.rs+74−50View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/lib.rs+4651−4329View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/log_evict.rs+266−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/logic/log_tier.rs+365−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/pressure.rs+37−14View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/types.rs+698−661View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/logic/wake.rs+271−250View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/Cargo.toml+4−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/README.md+15−3View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/scripts/capture-golden.sh+14−14View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/scripts/db_equal.sh+1−1View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/bundle.rs+190−0View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/client/bundle.rs+133−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/file.rs+8−4View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/mod.rs+1−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/client/object_store.rs+865−776View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/compactor.rs+2−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/db.rs+2016−1754View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/error.rs+1−1View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/src/host.rs+383−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/lib.rs+294−276View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/ltx.rs+13−11View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica.rs+863−825View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica_compactor.rs+188−166View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/replica_url.rs+2−2View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/src/wal.rs+295−293View file
Diff not rendered to keep this page fast. View the file
deletedcrates/ltx/tests/conformance.rs+0−1
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/differential_xtool.rs+583−452View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/faults_inject.rs+6−3View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/fixtures/golden/MANIFEST.md+31−32View file
Diff not rendered to keep this page fast. View the file
addedcrates/ltx/tests/fuzz_bundle.rs+218−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/fuzz_parsers.rs+3−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/integration_file.rs+281−247View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/integration_resilience.rs+448−348View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/integration_s3.rs+2−0View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/litestream_helpers.rs+51−52View file
Diff not rendered to keep this page fast. View the file
modifiedcrates/ltx/tests/property_roundtrip.rs+1−1View file
Diff not rendered to keep this page fast. View the file
modifieddocs/README.md+240−167View file
Diff not rendered to keep this page fast. View the file
modifieddocs/cloudflare-compat.md+348−149View file
Diff not rendered to keep this page fast. View the file
modifieddocs/fencing.md+181−92View file
Diff not rendered to keep this page fast. View the file
modifieddocs/limitations.md+27−16View file
Diff not rendered to keep this page fast. View the file
modifieddocs/security.md+39−24View file
Diff not rendered to keep this page fast. View the file
modifieddocs/testing.md+68−20View file
Diff not rendered to keep this page fast. View the file
modifiedexamples/README.md+8−6View file
Diff not rendered to keep this page fast. View the file
addedexamples/cron/index.js+46−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/cron/wrangler.jsonc+11−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/d1/index.js+60−0View file
Diff not rendered to keep this page fast. View the file
addedexamples/d1/wrangler.jsonc+16−0View file
Diff not rendered to keep this page fast. View the file