| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | //! Engine-neutral types and helpers that the cell runtimes and the host |
| 4 | //! share. Nothing here touches V8; `crate::js`, `crate::runtime` and |
| 5 | //! `crate::pool` re-export every item at its old path. |
| 6 | use crate::ws_registry::WorkerWebSocket; |
| 7 | use anyhow::Result; |
| 8 | use celld_logic::isolate::Refusal; |
| 9 | use std::cell::RefCell; |
| 10 | use std::collections::HashMap; |
| 11 | use std::pin::Pin; |
| 12 | use std::sync::atomic::AtomicU64; |
| 13 | use std::sync::atomic::Ordering; |
| 14 | use std::sync::Arc; |
| 15 | use std::sync::OnceLock; |
| 16 | |
| 17 | /// Bare Node builtin specifiers that the bundler leaves for the runtime. |
| 18 | /// Root entries also match subpaths in esbuild and in module resolution. |
| 19 | pub(crate) const BARE_NODE_BUILTINS: &[&str] = &[ |
| 20 | "assert", |
| 21 | "async_hooks", |
| 22 | "buffer", |
| 23 | "child_process", |
| 24 | "cluster", |
| 25 | "constants", |
| 26 | "crypto", |
| 27 | "dgram", |
| 28 | "diagnostics_channel", |
| 29 | "dns", |
| 30 | "events", |
| 31 | "fs", |
| 32 | "fs/promises", |
| 33 | "http", |
| 34 | "http2", |
| 35 | "https", |
| 36 | "inspector", |
| 37 | "module", |
| 38 | "net", |
| 39 | "os", |
| 40 | "path", |
| 41 | "perf_hooks", |
| 42 | "process", |
| 43 | "punycode", |
| 44 | "querystring", |
| 45 | "readline", |
| 46 | "sqlite", |
| 47 | "stream", |
| 48 | "string_decoder", |
| 49 | "timers", |
| 50 | "tls", |
| 51 | "tty", |
| 52 | "url", |
| 53 | "util", |
| 54 | "util/types", |
| 55 | "v8", |
| 56 | "vm", |
| 57 | "worker_threads", |
| 58 | "zlib", |
| 59 | ]; |
| 60 | |
| 61 | pub type RequestId = u128; |
| 62 | |
| 63 | /// Allocate an id for an ingress or service-binding request so it can be |
| 64 | /// aborted mid-flight. |
| 65 | pub fn next_request_id() -> RequestId { |
| 66 | next_do_request_id() |
| 67 | } |
| 68 | |
| 69 | static NEXT_DO_REQUEST_ID: AtomicU64 = AtomicU64::new(1); |
| 70 | static DO_REQUEST_PROCESS_PREFIX: OnceLock<u64> = OnceLock::new(); |
| 71 | |
| 72 | #[doc(hidden)] |
| 73 | pub fn next_do_request_id() -> RequestId { |
| 74 | let prefix = *DO_REQUEST_PROCESS_PREFIX.get_or_init(|| { |
| 75 | let mut bytes = [0; 8]; |
| 76 | getrandom::fill(&mut bytes).expect("OS random source unavailable"); |
| 77 | u64::from_ne_bytes(bytes) |
| 78 | }); |
| 79 | let sequence = NEXT_DO_REQUEST_ID.fetch_add(1, Ordering::Relaxed); |
| 80 | (u128::from(prefix) << 64) | u128::from(sequence) |
| 81 | } |
| 82 | |
| 83 | pub fn request_id_string(request_id: RequestId) -> String { |
| 84 | format!("{request_id:032x}") |
| 85 | } |
| 86 | |
| 87 | pub fn parse_request_id(value: &str) -> Option<RequestId> { |
| 88 | u128::from_str_radix(value, 16).ok() |
| 89 | } |
| 90 | |
| 91 | /// An RPC payload crossing the host boundary. JS stubs marshal by V8 |
| 92 | /// structured clone (`V8`), and legacy callers use the JSON envelope (`Json`). |
| 93 | /// `__dispatchRpc` answers in the flavor it was asked in. |
| 94 | pub enum RpcData { |
| 95 | Json(String), |
| 96 | V8(bytes::Bytes), |
| 97 | } |
| 98 | |
| 99 | pub type HttpChunkStream = |
| 100 | Pin<Box<dyn futures_util::Stream<Item = Result<Vec<u8>, String>> + Send>>; |
| 101 | |
| 102 | #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] |
| 103 | pub struct WsTarget { |
| 104 | pub id: u64, |
| 105 | pub scope: String, |
| 106 | /// A parked tunneled 101 on the calling node (`peer_tunnel::splice`). |
| 107 | /// The id is meaningful only in the process that parked it, but it must |
| 108 | /// survive the isolate round trip, so it serializes. |
| 109 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 110 | pub tunnel: Option<u64>, |
| 111 | } |
| 112 | |
| 113 | pub enum HttpResponseWebSocket { |
| 114 | Cell(WsTarget), |
| 115 | Worker(WorkerWebSocket), |
| 116 | } |
| 117 | |
| 118 | pub struct HttpResponse { |
| 119 | pub status: u16, |
| 120 | pub body: Vec<u8>, |
| 121 | /// A response body forwarded without materializing it in memory. |
| 122 | pub stream: Option<HttpChunkStream>, |
| 123 | pub headers: Vec<(String, String)>, |
| 124 | /// The one WebSocket target that owns this response, if it is an upgrade. |
| 125 | pub websocket: Option<HttpResponseWebSocket>, |
| 126 | /// The cell's committed-write position after the handler ran, for a local |
| 127 | /// Durable Object request. The shell gates the response on durability when |
| 128 | /// this advanced past the cell's last seen position. `None` for responses |
| 129 | /// with no cell storage (Worker, asset, or proxied remote). |
| 130 | pub write_position: Option<u64>, |
| 131 | /// The position the answer observed above the cell's published baseline |
| 132 | /// when the handler did not write, so the shell can hold a read-only |
| 133 | /// response behind the proof of another handler's commit. `None` when the |
| 134 | /// cell holds no handler write, or the response has no cell storage. |
| 135 | pub observed_position: Option<u64>, |
| 136 | } |
| 137 | |
| 138 | /// The encoding that the queue producer selected for one message body. |
| 139 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 140 | pub enum QueueContentType { |
| 141 | Text, |
| 142 | Bytes, |
| 143 | Json, |
| 144 | V8, |
| 145 | } |
| 146 | |
| 147 | impl QueueContentType { |
| 148 | pub(crate) fn as_str(self) -> &'static str { |
| 149 | match self { |
| 150 | Self::Text => "text", |
| 151 | Self::Bytes => "bytes", |
| 152 | Self::Json => "json", |
| 153 | Self::V8 => "v8", |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | /// One message handed from a queue cell to a consumer isolate. |
| 159 | pub struct QueueMessage { |
| 160 | pub id: String, |
| 161 | pub timestamp_ms: i64, |
| 162 | pub body: Vec<u8>, |
| 163 | pub content_type: QueueContentType, |
| 164 | pub attempts: u16, |
| 165 | } |
| 166 | |
| 167 | /// The queue state observed when a cell leases a batch. |
| 168 | pub struct QueueMetrics { |
| 169 | pub backlog_count: f64, |
| 170 | pub backlog_bytes: f64, |
| 171 | pub oldest_message_timestamp_ms: Option<i64>, |
| 172 | } |
| 173 | |
| 174 | /// One leased batch handed to the stateless isolate pool. |
| 175 | pub struct QueueBatch { |
| 176 | pub queue: String, |
| 177 | pub messages: Vec<QueueMessage>, |
| 178 | pub metrics: QueueMetrics, |
| 179 | } |
| 180 | |
| 181 | /// The batch-wide retry decision made by a queue handler. |
| 182 | #[derive(Debug, Eq, PartialEq)] |
| 183 | pub struct QueueRetryBatch { |
| 184 | pub retry: bool, |
| 185 | pub delay_seconds: Option<i32>, |
| 186 | } |
| 187 | |
| 188 | /// An explicit retry decision made for one message. |
| 189 | #[derive(Debug, Eq, PartialEq)] |
| 190 | pub struct QueueRetryMessage { |
| 191 | pub msg_id: String, |
| 192 | pub delay_seconds: Option<i32>, |
| 193 | } |
| 194 | |
| 195 | /// How the queue handler itself completed. Infrastructure failures still use |
| 196 | /// the outer `Result`, so a handler exception can preserve earlier acks. |
| 197 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 198 | pub enum QueueOutcome { |
| 199 | Ok, |
| 200 | Exception, |
| 201 | } |
| 202 | |
| 203 | /// The handler outcome and the settlement instructions it made before return. |
| 204 | #[derive(Debug, Eq, PartialEq)] |
| 205 | pub struct QueueDispatchResult { |
| 206 | pub outcome: QueueOutcome, |
| 207 | pub error: Option<String>, |
| 208 | pub ack_all: bool, |
| 209 | pub retry_batch: QueueRetryBatch, |
| 210 | pub explicit_acks: Vec<String>, |
| 211 | pub retry_messages: Vec<QueueRetryMessage>, |
| 212 | } |
| 213 | |
| 214 | /// A cell event that the runtime refuses before application code starts. |
| 215 | /// |
| 216 | /// The type survives the Rust RPC path. Its display text also survives the V8 |
| 217 | /// promise boundary, so the public ingress can restore the HTTP overload |
| 218 | /// contract after a Worker forwards the refusal. |
| 219 | #[doc(hidden)] |
| 220 | #[derive(Debug)] |
| 221 | pub struct CellOverloaded; |
| 222 | |
| 223 | /// The V8 promise boundary preserves only an error string. Keep the public |
| 224 | /// overload phrase so a Worker can classify a caught Queue producer refusal. |
| 225 | /// Also include an opaque marker so unrelated application text cannot restore |
| 226 | /// an HTTP overload response, and keep the producer and ingress checks on one |
| 227 | /// value. |
| 228 | #[doc(hidden)] |
| 229 | pub const CELL_OVERLOAD_ERROR_MARKER: &str = |
| 230 | "celld-internal-cell-overload-7ec38c64-12d7-4ddc-9e77-b63f9dc14130"; |
| 231 | |
| 232 | impl std::fmt::Display for CellOverloaded { |
| 233 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 234 | write!( |
| 235 | formatter, |
| 236 | "cell overload: admission refused ({CELL_OVERLOAD_ERROR_MARKER})" |
| 237 | ) |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | impl std::error::Error for CellOverloaded {} |
| 242 | |
| 243 | /// Per-worker compatibility switches, derived from the manifest's |
| 244 | /// compatibility date and flags (Workerd compatibility-date.capnp). `Default` |
| 245 | /// is every switch off; production derives real values in `main`. |
| 246 | #[derive(Clone, Copy, Default)] |
| 247 | pub struct Compat { |
| 248 | pub delete_all_deletes_alarm: bool, |
| 249 | /// `js_rpc`: RPC on a Durable Object class that does not extend |
| 250 | /// `DurableObject` (Workerd worker-rpc.c++ getTargetInfo()). |
| 251 | pub js_rpc: bool, |
| 252 | /// `fetcher_has_get_put_delete` (off = `fetcher_no_get_put_delete`, |
| 253 | /// default on for dates >= 2024-03-26): the deprecated `get()`/`put()`/ |
| 254 | /// `delete()` HTTP helpers on stubs (Workerd http.c++ Fetcher). |
| 255 | pub fetcher_get_put_delete: bool, |
| 256 | /// `sqlite_vec`: expose the pre-v1 sqlite-vec extension to SQLite-backed |
| 257 | /// Durable Objects. This switch is explicit and has no date default. |
| 258 | pub sqlite_vec: bool, |
| 259 | /// `websocket_standard_binary_type`: `binaryType` defaults to `"blob"` and |
| 260 | /// a binary message arrives as a `Blob`, per the WHATWG default. Without |
| 261 | /// it celld keeps the historical `"arraybuffer"`. |
| 262 | pub websocket_standard_binary_type: bool, |
| 263 | /// Queue bodies default to JSON on compatibility dates after 2024-03-18; |
| 264 | /// older deployments retain the V8 structured-clone default. |
| 265 | pub queue_json_messages: bool, |
| 266 | } |
| 267 | |
| 268 | /// A non-main module the worker's main module may import, tagged by how the |
| 269 | /// runtime materializes it. |
| 270 | #[derive(Clone)] |
| 271 | pub enum ModuleSource { |
| 272 | /// UTF-8 content served as `export default "<content>"` (wrangler's Text |
| 273 | /// rule), registered under the given specifier verbatim. |
| 274 | Text(String), |
| 275 | /// JS source compiled as a sibling ES module (Worker Loader multi-module |
| 276 | /// bundles), registered under both `name` and `./name`. |
| 277 | EsModule(String), |
| 278 | /// Wasm bytes served as a module whose default export is the compiled |
| 279 | /// `WebAssembly.Module` (Wrangler's `CompiledWasm` rule), registered |
| 280 | /// under both `name` and `./name`. |
| 281 | Wasm(bytes::Bytes), |
| 282 | } |
| 283 | |
| 284 | /// A Workflow binding keeps the three names distinct across deployment |
| 285 | /// loading, environment construction, and runtime class injection. |
| 286 | pub struct WorkflowBinding { |
| 287 | pub environment: String, |
| 288 | pub workflow: String, |
| 289 | pub class: String, |
| 290 | } |
| 291 | |
| 292 | /// One Queue producer binding in a Worker environment. |
| 293 | #[derive(Clone)] |
| 294 | pub struct QueueBinding { |
| 295 | pub environment: String, |
| 296 | pub queue: String, |
| 297 | pub delivery_delay: u32, |
| 298 | } |
| 299 | |
| 300 | pub struct WorkerConfigOptions { |
| 301 | pub src: String, |
| 302 | pub script_name: String, |
| 303 | pub do_classes: Vec<String>, |
| 304 | pub bindings: Vec<(String, String)>, |
| 305 | pub r2_bindings: Vec<(String, String)>, |
| 306 | pub d1_bindings: Vec<(String, String)>, |
| 307 | pub kv_bindings: Vec<(String, String)>, |
| 308 | pub queue_bindings: Vec<QueueBinding>, |
| 309 | pub queue_consumers: Vec<crate::protocol::QueueConsumerConfig>, |
| 310 | pub workflow_bindings: Vec<WorkflowBinding>, |
| 311 | pub vars: Vec<(String, String)>, |
| 312 | pub node: String, |
| 313 | pub modules: Vec<(String, ModuleSource)>, |
| 314 | pub compat: Compat, |
| 315 | } |
| 316 | |
| 317 | /// A handler that failed inside its turn, with the positions that turn |
| 318 | /// sampled from the cell. |
| 319 | /// |
| 320 | /// A commit the handler made before it failed is as real as one a successful |
| 321 | /// handler made: it stays in the local database, unproven, and a read-only |
| 322 | /// output that followed would trail no barrier and reveal it while a crash can |
| 323 | /// still lose it. The error answer therefore takes the same write ticket a |
| 324 | /// success takes. |
| 325 | /// |
| 326 | /// A handler that committed nothing still reveals what it read, because the |
| 327 | /// message it throws with can quote it — "insufficient funds: balance is 90" |
| 328 | /// is an ordinary shape — and that value can be another event's commit that no |
| 329 | /// proof covers yet. An error answer reveals cell state exactly as a 200 does, |
| 330 | /// so a read-only failure carries the observed position and the gate holds it |
| 331 | /// behind the newest barrier, as it holds a read-only success. |
| 332 | /// |
| 333 | /// The failure the handler reported is the source; this wrapper displays its |
| 334 | /// message and continues its chain, so a client and a log see the handler's |
| 335 | /// own words. |
| 336 | #[derive(Debug)] |
| 337 | pub struct FailedInTurn { |
| 338 | pub(crate) write_position: Option<u64>, |
| 339 | pub(crate) observed_position: Option<u64>, |
| 340 | source: anyhow::Error, |
| 341 | } |
| 342 | |
| 343 | impl std::fmt::Display for FailedInTurn { |
| 344 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 345 | write!(f, "{}", self.source) |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | impl std::error::Error for FailedInTurn { |
| 350 | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 351 | // The wrapped error's own message is this wrapper's display, so the |
| 352 | // chain continues below it rather than repeating it. The wrapped |
| 353 | // error's own type is therefore not in the chain: a `downcast_ref` |
| 354 | // for it, or a `chain()` walk that looks for it, sees this wrapper |
| 355 | // instead. Every error that reaches `fail_in_turn_error` today is a |
| 356 | // plain message, so nothing looks; a typed handler failure would have |
| 357 | // to be matched through `failed_write_position` and its text. |
| 358 | let source: &(dyn std::error::Error + 'static) = self.source.as_ref(); |
| 359 | source.source() |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | /// Attach the positions a failing handler's turn sampled, when it has either. |
| 364 | /// The pair comes from one `gate_positions` call, so an error cannot report a |
| 365 | /// write and an observation that disagree. |
| 366 | pub(crate) fn fail_in_turn_error( |
| 367 | error: anyhow::Error, |
| 368 | positions: (Option<u64>, Option<u64>), |
| 369 | ) -> anyhow::Error { |
| 370 | let (write_position, observed_position) = positions; |
| 371 | if write_position.is_none() && observed_position.is_none() { |
| 372 | return error; |
| 373 | } |
| 374 | anyhow::Error::new(FailedInTurn { |
| 375 | write_position, |
| 376 | observed_position, |
| 377 | source: error, |
| 378 | }) |
| 379 | } |
| 380 | |
| 381 | /// The position a failed handler committed before it failed, when it did. |
| 382 | pub fn failed_write_position(error: &anyhow::Error) -> Option<u64> { |
| 383 | error |
| 384 | .downcast_ref::<FailedInTurn>() |
| 385 | .and_then(|failed| failed.write_position) |
| 386 | } |
| 387 | |
| 388 | /// How an incoming request body reaches the isolate. |
| 389 | /// |
| 390 | /// A small body crosses as bytes. This costs one copy and no asynchronous |
| 391 | /// operations, so a common request pays nothing for a stream that it does |
| 392 | /// not need. A large body, or a body of unknown length, crosses as a |
| 393 | /// stream id. The peak cost of that body is one chunk, not its length. |
| 394 | pub enum RequestBody { |
| 395 | Bytes(bytes::Bytes), |
| 396 | Stream(u64), |
| 397 | } |
| 398 | |
| 399 | impl RequestBody { |
| 400 | /// The bytes already in hand, for the paths that hold a whole body. |
| 401 | pub fn bytes(&self) -> &[u8] { |
| 402 | match self { |
| 403 | Self::Bytes(bytes) => bytes, |
| 404 | Self::Stream(_) => &[], |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | pub fn stream_id(&self) -> Option<u64> { |
| 409 | match self { |
| 410 | Self::Bytes(_) => None, |
| 411 | Self::Stream(id) => Some(*id), |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | pub(crate) fn into_held_bytes(self) -> Option<Vec<u8>> { |
| 416 | match self { |
| 417 | Self::Bytes(bytes) => Some(bytes.into()), |
| 418 | Self::Stream(_) => None, |
| 419 | } |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | impl From<Vec<u8>> for RequestBody { |
| 424 | fn from(bytes: Vec<u8>) -> Self { |
| 425 | Self::Bytes(bytes.into()) |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | thread_local! { |
| 430 | static DO_ID_KEYS: RefCell<HashMap<String, [u8; 32]>> = RefCell::new(HashMap::new()); |
| 431 | } |
| 432 | |
| 433 | pub(crate) fn durable_object_id_key(namespace_key: &str) -> [u8; 32] { |
| 434 | DO_ID_KEYS.with(|keys| { |
| 435 | if let Some(key) = keys.borrow().get(namespace_key) { |
| 436 | return *key; |
| 437 | } |
| 438 | use sha2::Digest; |
| 439 | let key: [u8; 32] = sha2::Sha256::digest(namespace_key.as_bytes()).into(); |
| 440 | keys.borrow_mut().insert(namespace_key.to_string(), key); |
| 441 | key |
| 442 | }) |
| 443 | } |
| 444 | |
| 445 | pub(crate) fn durable_object_id_hmac(key: &[u8; 32], input: &[u8]) -> hmac::Hmac<sha2::Sha256> { |
| 446 | use hmac::Mac; |
| 447 | let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(key) |
| 448 | .expect("SHA-256 accepts any HMAC key"); |
| 449 | mac.update(input); |
| 450 | mac |
| 451 | } |
| 452 | |
| 453 | /// Ids already derived on this thread, keyed by namespace and name. |
| 454 | /// |
| 455 | /// `getByName` costs two HMAC-SHA256 rounds, and a profile of `/c/hello` |
| 456 | /// found them among the largest terms the stateless path does not have — |
| 457 | /// the same name resolving to the same id, recomputed on every request. |
| 458 | /// |
| 459 | /// Per thread and unsynchronised, which is sound because the derivation is |
| 460 | /// a pure function of its inputs: a worker that has not seen a name pays |
| 461 | /// for it once, and no answer can differ between threads. Bounded because |
| 462 | /// names come from the application, and cleared wholesale at the cap rather |
| 463 | /// than evicted one at a time — a cache this cheap to refill does not earn |
| 464 | /// an LRU. |
| 465 | const DO_ID_CACHE_MAX: usize = 4096; |
| 466 | |
| 467 | pub(crate) fn durable_object_id_for_name(namespace_key: &str, name: &str) -> [u8; 32] { |
| 468 | use hmac::Mac; |
| 469 | |
| 470 | thread_local! { |
| 471 | static IDS: RefCell<HashMap<(String, String), [u8; 32]>> = |
| 472 | RefCell::new(HashMap::new()); |
| 473 | } |
| 474 | let cached = IDS.with(|ids| { |
| 475 | ids.borrow() |
| 476 | .get(&(namespace_key.to_string(), name.to_string())) |
| 477 | .copied() |
| 478 | }); |
| 479 | if let Some(id) = cached { |
| 480 | return id; |
| 481 | } |
| 482 | |
| 483 | let key = durable_object_id_key(namespace_key); |
| 484 | let mut id = [0_u8; 32]; |
| 485 | let digest = durable_object_id_hmac(&key, name.as_bytes()) |
| 486 | .finalize() |
| 487 | .into_bytes(); |
| 488 | id[..16].copy_from_slice(&digest[..16]); |
| 489 | let digest = durable_object_id_hmac(&key, &id[..16]) |
| 490 | .finalize() |
| 491 | .into_bytes(); |
| 492 | id[16..].copy_from_slice(&digest[..16]); |
| 493 | |
| 494 | IDS.with(|ids| { |
| 495 | let mut ids = ids.borrow_mut(); |
| 496 | if ids.len() >= DO_ID_CACHE_MAX { |
| 497 | ids.clear(); |
| 498 | } |
| 499 | ids.insert((namespace_key.to_string(), name.to_string()), id); |
| 500 | }); |
| 501 | id |
| 502 | } |
| 503 | |
| 504 | /// The key a Durable Object namespace derives its IDs from. D1 uses one |
| 505 | /// fleet-wide namespace because the database is a resource that several |
| 506 | /// Workers can bind, and a Worker rename must not rename that database. |
| 507 | pub(crate) const D1_NAMESPACE_KEY: &str = "cells:v1:d1:__D1Database"; |
| 508 | |
| 509 | /// The same, for a KV namespace, and for the same reason: several Workers can |
| 510 | /// bind one namespace, and they must reach one set of cells. |
| 511 | /// |
| 512 | /// Written out rather than derived from the class name, because these two |
| 513 | /// strings are addresses. A scheme that computed them would be free to change, |
| 514 | /// and changing one renames every cell it ever addressed. |
| 515 | pub(crate) const KV_NAMESPACE_KEY: &str = "cells:v1:kv:__KvNamespace"; |
| 516 | |
| 517 | /// The fleet-wide namespace for Queue broker cells. The queue name is the |
| 518 | /// durable resource identity, so a producer and a consumer in different |
| 519 | /// scripts must derive the same cell id. |
| 520 | pub(crate) const QUEUE_NAMESPACE_KEY: &str = "cells:v1:queue:__Queue"; |
| 521 | |
| 522 | /// A shared reserved class addresses one set of cells for the whole fleet; every |
| 523 | /// other class, reserved or not, is scoped to the script that exports it. |
| 524 | /// |
| 525 | /// The question is asked once, through `deploy::is_shared_reserved_class`, and |
| 526 | /// not as a chain of `==` against class names. A reserved class declared shared |
| 527 | /// there and script-scoped here would silently give each script its own copy of |
| 528 | /// a resource the configuration says they share -- which is what happened to KV |
| 529 | /// between its manifest landing and this line being written. |
| 530 | fn shared_namespace_key(class_name: &str) -> Option<&'static str> { |
| 531 | match class_name { |
| 532 | crate::deploy::D1_CLASS => Some(D1_NAMESPACE_KEY), |
| 533 | crate::deploy::KV_CLASS => Some(KV_NAMESPACE_KEY), |
| 534 | crate::deploy::QUEUE_CLASS => Some(QUEUE_NAMESPACE_KEY), |
| 535 | _ => { |
| 536 | debug_assert!( |
| 537 | !crate::deploy::is_shared_reserved_class(class_name), |
| 538 | "a shared reserved class needs a fleet-wide namespace key: {class_name}" |
| 539 | ); |
| 540 | None |
| 541 | } |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | pub(crate) fn namespace_key(script_name: &str, class_name: &str) -> String { |
| 546 | match shared_namespace_key(class_name) { |
| 547 | Some(shared) => shared.to_string(), |
| 548 | None => format!("cells:v1:{}:{script_name}:{class_name}", script_name.len()), |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | /// The cell scope a D1 database lives at, for a caller outside any isolate. |
| 553 | /// `celld d1` addresses a database over the operator route, which takes a |
| 554 | /// scope, so this derives what `getByName` derives in the harness, from the |
| 555 | /// same key and the same HMAC. |
| 556 | pub fn d1_cell_scope(database_identity: &str) -> String { |
| 557 | let id = durable_object_id_for_name(D1_NAMESPACE_KEY, database_identity); |
| 558 | format!("{}:{}", crate::deploy::D1_CLASS, durable_object_id_hex(&id)) |
| 559 | } |
| 560 | |
| 561 | /// The cell scope one shard of a KV namespace lives at, for a caller outside |
| 562 | /// any isolate. `celld kv` addresses a namespace over the operator route, and |
| 563 | /// this derives what `getByName` derives in the harness -- from the same key, |
| 564 | /// the same name, and the same HMAC. |
| 565 | /// |
| 566 | /// The name comes from `celld_logic::kv::cell_name`, which is also what the |
| 567 | /// binding is handed at `build_env`. Neither side formats it, because a |
| 568 | /// formatting disagreement here does not fail: it silently addresses a second, |
| 569 | /// empty namespace. |
| 570 | pub fn kv_cell_scope(namespace_id: &str, shard: u32) -> String { |
| 571 | let name = celld_logic::kv::cell_name(namespace_id, shard); |
| 572 | let id = durable_object_id_for_name(KV_NAMESPACE_KEY, &name); |
| 573 | format!("{}:{}", crate::deploy::KV_CLASS, durable_object_id_hex(&id)) |
| 574 | } |
| 575 | |
| 576 | /// The Queue broker scope for callers outside a Worker isolate. |
| 577 | pub fn queue_cell_scope(queue: &str) -> String { |
| 578 | let name = celld_logic::queue::cell_name(queue); |
| 579 | let id = durable_object_id_for_name(QUEUE_NAMESPACE_KEY, name); |
| 580 | format!( |
| 581 | "{}:{}", |
| 582 | crate::deploy::QUEUE_CLASS, |
| 583 | durable_object_id_hex(&id) |
| 584 | ) |
| 585 | } |
| 586 | |
| 587 | #[cfg(celld_internal_tests)] |
| 588 | #[doc(hidden)] |
| 589 | pub fn workflow_cell_scope_for_test( |
| 590 | script_name: &str, |
| 591 | workflow_name: &str, |
| 592 | instance_id: &str, |
| 593 | ) -> String { |
| 594 | let class = crate::deploy::workflow_class(script_name); |
| 595 | let namespace = namespace_key(script_name, &class); |
| 596 | let name = format!("{workflow_name}/{instance_id}"); |
| 597 | let id = durable_object_id_for_name(&namespace, &name); |
| 598 | format!("{class}:{}", durable_object_id_hex(&id)) |
| 599 | } |
| 600 | |
| 601 | pub(crate) fn durable_object_id_hex(bytes: &[u8; 32]) -> String { |
| 602 | const HEX: &[u8; 16] = b"0123456789abcdef"; |
| 603 | let mut output = String::with_capacity(64); |
| 604 | for byte in bytes { |
| 605 | output.push(HEX[(byte >> 4) as usize] as char); |
| 606 | output.push(HEX[(byte & 0x0f) as usize] as char); |
| 607 | } |
| 608 | output |
| 609 | } |
| 610 | |
| 611 | pub(crate) fn decode_durable_object_id(value: &str) -> Option<[u8; 32]> { |
| 612 | if value.len() != 64 { |
| 613 | return None; |
| 614 | } |
| 615 | let mut output = [0_u8; 32]; |
| 616 | for (index, pair) in value.as_bytes().as_chunks::<2>().0.iter().enumerate() { |
| 617 | let nibble = |byte| match byte { |
| 618 | b'0'..=b'9' => Some(byte - b'0'), |
| 619 | b'a'..=b'f' => Some(byte - b'a' + 10), |
| 620 | b'A'..=b'F' => Some(byte - b'A' + 10), |
| 621 | _ => None, |
| 622 | }; |
| 623 | output[index] = (nibble(pair[0])? << 4) | nibble(pair[1])?; |
| 624 | } |
| 625 | Some(output) |
| 626 | } |
| 627 | pub type AlarmObserver = Arc<dyn Fn(String, celld_logic::wake::AlarmSnapshot) + Send + Sync>; |
| 628 | |
| 629 | #[derive(Clone)] |
| 630 | pub(crate) enum StopMode { |
| 631 | /// Prove the final position, then optionally retain a local base. |
| 632 | /// |
| 633 | /// `abandon` travels with `preserve_local` because an eviction that could |
| 634 | /// be abandoned and an eviction that keeps a local base are the same |
| 635 | /// eviction: the one a live node can change its mind about. A drain and a |
| 636 | /// fence carry neither. |
| 637 | Evict { |
| 638 | preserve_local: bool, |
| 639 | abandon: Option<Arc<crate::replication::EvictionAbandon>>, |
| 640 | }, |
| 641 | /// Prove the final position and retain it for the successor epoch. |
| 642 | Rebase, |
| 643 | /// Close without a remote write because the caller lacks authority. |
| 644 | CloseInPlace, |
| 645 | /// Remove an image whose durability proof failed. |
| 646 | Discard, |
| 647 | } |
| 648 | /// One pool's isolates by state, as `/state` reports them. |
| 649 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] |
| 650 | pub struct PoolCensus { |
| 651 | /// Isolates that accept placement and work. |
| 652 | pub live: usize, |
| 653 | /// Live isolates that house no cell. The next maintenance pass retires |
| 654 | /// them, so a count that persists across passes means the pass is not |
| 655 | /// running. |
| 656 | pub live_empty: usize, |
| 657 | /// Retiring isolates whose heap is still installed, because a turn, a |
| 658 | /// request, or a cell holds it. |
| 659 | pub retiring: usize, |
| 660 | /// Slots whose heap has been freed. |
| 661 | pub freed: usize, |
| 662 | /// Cells housed across the pool. |
| 663 | pub cells: usize, |
| 664 | /// Request affiliations across the pool, running or suspended. |
| 665 | pub requests: usize, |
| 666 | /// Turns in flight across the pool. |
| 667 | pub turns: usize, |
| 668 | /// Physical memory V8 has committed to the heaps of the isolates a turn |
| 669 | /// did not hold at the sample. |
| 670 | pub heap_bytes: u64, |
| 671 | /// External memory those isolates track: array buffer stores and the |
| 672 | /// like, which live outside the V8 heap. |
| 673 | pub external_bytes: u64, |
| 674 | } |
| 675 | |
| 676 | /// Refused by policy, or the isolate could not be built. Distinct because the |
| 677 | /// first is a 503 the caller may retry elsewhere and the second is a fault. |
| 678 | #[derive(Debug)] |
| 679 | pub enum AdmitError { |
| 680 | Refused(Refusal), |
| 681 | Build(anyhow::Error), |
| 682 | } |
| 683 | |
| 684 | impl From<Refusal> for AdmitError { |
| 685 | fn from(refusal: Refusal) -> Self { |
| 686 | AdmitError::Refused(refusal) |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | impl std::fmt::Display for AdmitError { |
| 691 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 692 | match self { |
| 693 | AdmitError::Refused(Refusal::NodeFull) => { |
| 694 | write!(f, "node is at its stateless request limit") |
| 695 | } |
| 696 | AdmitError::Refused(Refusal::NodePressured) => write!(f, "node is shedding load"), |
| 697 | AdmitError::Build(error) => write!(f, "isolate could not be started: {error}"), |
| 698 | } |
| 699 | } |
| 700 | } |
| 701 | |
| 702 | impl std::error::Error for AdmitError {} |
| 703 | |
| 704 | /// Node-level inputs to the cell runtime: everything that outlives an |
| 705 | /// application generation. What a deployment implies goes through |
| 706 | /// `Generation::build` instead. |
| 707 | pub struct RuntimeOptions { |
| 708 | pub data_dir: std::path::PathBuf, |
| 709 | pub replication: Option<crate::ltx_replication::Replication>, |
| 710 | pub wake: Option<Arc<crate::wake::WakeFlusher>>, |
| 711 | pub alarm_observer: AlarmObserver, |
| 712 | pub node: String, |
| 713 | pub region: String, |
| 714 | /// The fleet bucket, where container images live. `None` for a local |
| 715 | /// script, which has no bucket and loads images from the engine alone. |
| 716 | pub bucket: Option<crate::bucket::Bucket>, |
| 717 | } |
| 718 | |
| 719 | /// A service-binding fetch crossing from a calling isolate into the router. |
| 720 | pub struct ServiceFetch { |
| 721 | /// The caller's application generation; the target is resolved in its |
| 722 | /// deployment graph. |
| 723 | pub generation: crate::generation::GenerationId, |
| 724 | pub script: String, |
| 725 | pub entrypoint: Option<crate::WorkerFetchEntrypoint>, |
| 726 | pub url: String, |
| 727 | pub method: String, |
| 728 | pub body: RequestBody, |
| 729 | pub headers: Vec<(String, String)>, |
| 730 | pub cancel: Option<tokio::sync::oneshot::Receiver<()>>, |
| 731 | } |
| 732 | |
| 733 | /// Owned HTTP request crossing from the async shell into a cell executor. |
| 734 | pub struct RuntimeFetch { |
| 735 | pub url: String, |
| 736 | pub method: String, |
| 737 | pub body: RequestBody, |
| 738 | pub headers: Vec<(String, String)>, |
| 739 | pub request_id: Option<RequestId>, |
| 740 | /// Where this call sits in its caller's order for this cell. |
| 741 | pub order: Option<crate::js::CallOrder>, |
| 742 | /// The dispatching Worker's trace context, so the cell's span joins |
| 743 | /// the caller's trace instead of rooting a disconnected one. |
| 744 | pub parent: Option<crate::telemetry::TraceContext>, |
| 745 | } |
| 746 | |
| 747 | /// What a Durable Object RPC method returned, plus the position its writes |
| 748 | /// reached, so the caller can hold the reply behind durability. |
| 749 | pub struct RpcOutcome { |
| 750 | pub data: RpcData, |
| 751 | pub write_position: Option<u64>, |
| 752 | /// As on `HttpResponse`: what a read-only reply observed above the cell's |
| 753 | /// published baseline. |
| 754 | pub observed_position: Option<u64>, |
| 755 | } |
| 756 | |
| 757 | /// An answer the shell gates: a success reports the position its writes |
| 758 | /// reached, and the position it observed when it wrote nothing, in its own |
| 759 | /// shape. |
| 760 | pub trait GatedAnswer { |
| 761 | fn write_position(&self) -> Option<u64>; |
| 762 | fn observed_position(&self) -> Option<u64>; |
| 763 | } |
| 764 | |
| 765 | impl GatedAnswer for HttpResponse { |
| 766 | fn write_position(&self) -> Option<u64> { |
| 767 | self.write_position |
| 768 | } |
| 769 | |
| 770 | fn observed_position(&self) -> Option<u64> { |
| 771 | self.observed_position |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | impl GatedAnswer for RpcOutcome { |
| 776 | fn write_position(&self) -> Option<u64> { |
| 777 | self.write_position |
| 778 | } |
| 779 | |
| 780 | fn observed_position(&self) -> Option<u64> { |
| 781 | self.observed_position |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | /// The ticket an answer takes through the output gate, or `None` when it |
| 786 | /// takes none. |
| 787 | /// |
| 788 | /// A success always takes one: a write ticket when the handler advanced the |
| 789 | /// position, and otherwise a read-only ticket that carries what the answer |
| 790 | /// observed and trails the newest barrier on the cell. A failure raised inside |
| 791 | /// the handler's turn takes the same two shapes, which [`FailedInTurn`] |
| 792 | /// reports, because an error message can carry the cell's state as a body can. |
| 793 | /// A failure raised outside a turn — a budget overrun, a handler waiting on |
| 794 | /// nothing — took no sample and reports the host's own words, so it reveals |
| 795 | /// nothing and takes no ticket. The shell reads both arms through this one |
| 796 | /// function so that no answer site can gate one and forget the other. |
| 797 | pub fn answer_ticket<T: GatedAnswer>(result: &Result<T>) -> Option<crate::actor::GateTicket> { |
| 798 | match result { |
| 799 | Ok(answer) => Some(crate::actor::GateTicket::response( |
| 800 | answer.write_position(), |
| 801 | answer.observed_position(), |
| 802 | )), |
| 803 | Err(error) => error.downcast_ref::<FailedInTurn>().map(|failed| { |
| 804 | crate::actor::GateTicket::response(failed.write_position, failed.observed_position) |
| 805 | }), |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | /// Fail the next release of a generation swap, for the black-box matrix. |
| 810 | /// |
| 811 | /// A count rather than a latch, so a test can prove the retry reaches |
| 812 | /// success instead of only proving that it never proceeds. `debug_assertions` |
| 813 | /// is the gate `CELLD_TEST_CELL_STARTUP_FAILURE` beside it already uses: the |
| 814 | /// runtime matrix drives the debug binary, which no internal test cfg |
| 815 | /// reaches, and a release build compiles neither. |
| 816 | #[cfg(debug_assertions)] |
| 817 | pub(crate) fn injected_swap_release_failure() -> Option<anyhow::Error> { |
| 818 | use std::sync::atomic::AtomicI64; |
| 819 | use std::sync::atomic::Ordering; |
| 820 | |
| 821 | static REMAINING: std::sync::OnceLock<AtomicI64> = std::sync::OnceLock::new(); |
| 822 | let remaining = REMAINING.get_or_init(|| { |
| 823 | AtomicI64::new( |
| 824 | std::env::var("CELLD_TEST_SWAP_RELEASE_FAILURES") |
| 825 | .ok() |
| 826 | .and_then(|value| value.parse().ok()) |
| 827 | .unwrap_or(0), |
| 828 | ) |
| 829 | }); |
| 830 | (remaining.fetch_sub(1, Ordering::Relaxed) > 0) |
| 831 | .then(|| anyhow::anyhow!("injected generation swap release failure")) |
| 832 | } |
| 833 | |
| 834 | /// Is `cell` a facet's stream? Only [`facet_cell`] builds a name with this |
| 835 | /// segment; a root cell's scope cannot contain `/`. |
| 836 | pub(crate) fn is_facet_cell(cell: &str) -> bool { |
| 837 | cell.contains("/facets/") |
| 838 | } |
| 839 | |
| 840 | /// The replication stream of a facet: nested under its root's own |
| 841 | /// coordinates, `<root>/facets/<h>` locally and `cells/<root>/facets/<h>/` |
| 842 | /// in the bucket, one level per name of the facet's path, so no scan of |
| 843 | /// cells sees a facet and deleting a facet with everything below it is |
| 844 | /// deleting one prefix. `<h>` is the first 16 bytes of the name's SHA-256 |
| 845 | /// in hex: a name can be any string of up to 256 bytes, and the charset a |
| 846 | /// path segment allows is narrower. Workerd's own server names a facet |
| 847 | /// file by a small id from a per-object index; a hash needs no index to |
| 848 | /// replicate beside the root. |
| 849 | pub(crate) fn facet_cell(root: &str, names: &[String]) -> String { |
| 850 | use sha2::Digest; |
| 851 | let mut cell = root.to_string(); |
| 852 | for name in names { |
| 853 | let digest = sha2::Sha256::digest(name.as_bytes()); |
| 854 | cell.push_str("/facets/"); |
| 855 | for byte in &digest[..16] { |
| 856 | cell.push_str(&format!("{byte:02x}")); |
| 857 | } |
| 858 | } |
| 859 | cell |
| 860 | } |
| 861 | |
| 862 | /// How long a stateless request may wait for a free `max_requests` slot |
| 863 | /// before it is refused. Zero restores the old refuse-at-once behaviour. |
| 864 | /// The default is one second: long enough that a saturated node converts |
| 865 | /// its refusal storm into kernel-buffer queueing, short enough that a |
| 866 | /// caller learns the truth before it matters. |
| 867 | pub fn admission_wait() -> std::time::Duration { |
| 868 | // Not `env_usize`, which filters zero out — zero is meaningful here. |
| 869 | let ms = crate::env_vars::with_default("CELLD_ADMISSION_WAIT_MS", 1000u64) |
| 870 | .expect("validated CELLD_ADMISSION_WAIT_MS"); |
| 871 | std::time::Duration::from_millis(ms) |
| 872 | } |
| 873 | |
| 874 | /// The JavaScript handler budget, `CELLD_HANDLER_BUDGET_S`. |
| 875 | pub fn handler_budget() -> std::time::Duration { |
| 876 | static BUDGET: OnceLock<std::time::Duration> = OnceLock::new(); |
| 877 | *BUDGET.get_or_init(|| { |
| 878 | std::time::Duration::from_secs( |
| 879 | crate::env_vars::positive_or("CELLD_HANDLER_BUDGET_S", 300) |
| 880 | .expect("validated CELLD_HANDLER_BUDGET_S"), |
| 881 | ) |
| 882 | }) |
| 883 | } |