Diffinery

homeflare/celldpublic

6262 lines · 242.4 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
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
11//! The JS engine: rusty_v8 directly. One isolate per cell.
12//!
13//! This slice runs actual Durable Objects: the worker's default-export `fetch`
14//! receives an `env` whose bindings are DO namespaces; `env.NS.get(id).fetch()`
15//! instantiates the exported DO class (once per id) with a `state` whose
16//! `storage` is backed by the cell's SQLite (crate::storage). DO storage is
17//! async in JS, synchronous underneath — the ops are sync Rust, wrapped in
18//! `async` by the JS harness.
19use crate::asyncrt;
20use crate::storage;
21use anyhow::{anyhow, Context as _, Result};
22use futures_util::StreamExt as _;
23use std::cell::RefCell;
24use std::collections::{HashMap, HashSet};
25use std::pin::Pin;
26use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
27use std::sync::{Arc, Mutex, OnceLock};
28use std::time::{Duration, Instant};
29use v8::{ValueDeserializerHelper, ValueSerializerHelper};
30
31/// Bare Node builtin specifiers that the bundler leaves for the runtime.
32/// Root entries also match subpaths in esbuild and in module resolution.
33pub(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
75/// The pending exception text from a TryCatch scope (a macro so it needs no
76/// bound on the crate-private scope traits).
77macro_rules! exc {
78 ($tc:expr) => {
79 $tc.exception()
80 .map(|e| e.to_rust_string_lossy(&*$tc))
81 .unwrap_or_else(|| "<none>".into())
82 };
83}
84
85/// A cross-node dispatch: the isolate hit `env.NS.get(id)` for a cell this node
86/// does not own. The op hands this to the tokio runtime, which resolves the
87/// owner and HTTP-proxies the fetch, replying on `reply` (an async oneshot the
88/// async-op future awaits — the JS thread is never blocked).
89pub struct DoCallReq {
90 pub request_id: Option<RequestId>,
91 pub cancel: Option<tokio::sync::oneshot::Receiver<()>>,
92 /// An explicit JavaScript AbortSignal must reach the target handler, even
93 /// when it fires before cold routing completes. Transport cancellation has
94 /// no handler contract and can stop the cold route immediately.
95 pub deliver_abort_to_handler: bool,
96 pub scope: String,
97 pub name: Option<String>,
98 pub url: String,
99 pub method: String,
100 pub body: Vec<u8>,
101 pub headers: Vec<(String, String)>,
102 pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
103 /// Where this call sits in its caller's order for this cell.
104 pub order: Option<CallOrder>,
105 /// The dispatching handler's trace context, read from CPED at the
106 /// call site, so the cell's span joins the caller's trace.
107 pub parent: Option<crate::telemetry::TraceIds>,
108}
109static DO_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<DoCallReq>> = OnceLock::new();
110
111/// Delivery order, per caller and per cell.
112///
113/// Two calls a script makes back-to-back on one Durable Object stub reach
114/// the cell in that order. Workerd guarantees it — one pipe per stub — and
115/// celld did too, while a cell's events came off one channel. Nothing
116/// between the call and the cell keeps it now: the caller's two ops race to
117/// the proxy channel, the proxy polls them in a `FuturesUnordered`, and two
118/// drives race for the isolate. So the order is taken where it is still
119/// true, synchronously in `op_do_call_impl`, and carried to the one place
120/// that decides when an event is delivered.
121///
122/// It is a chain, not a counter: each call leaves behind the receiver its
123/// successor waits on, and takes its predecessor's.
124///
125/// **The chain lives on the caller.** It was a process-wide map keyed by
126/// `(context, cell)`, which made every Durable Object call in the node take
127/// one global lock to record something only its own caller could ever read.
128/// A shared mutex on a per-request path is a scalability cliff that a small
129/// machine cannot show you, and the state was never shared to begin with.
130///
131/// **Local delivery only.** A call routed to another node crosses HTTP,
132/// where this order has nowhere to ride, so it is dropped there. Workerd
133/// has the same seam in a different place, and a cell that moves mid-flight
134/// reorders under both.
135pub struct CallOrder {
136 /// The call before this one, or `None` if this is the first.
137 ahead: Option<tokio::sync::oneshot::Receiver<Place>>,
138 /// What the call behind this one waits on.
139 release: Option<tokio::sync::oneshot::Sender<Place>>,
140 /// The caller that owns the chain, and this call's place in it.
141 caller: Arc<IoContext>,
142 cell: String,
143 seq: u64,
144 delivered: bool,
145}
146
147/// What a call hands to the one behind it.
148///
149/// `None` once this call has been delivered: the queue has moved on. `Some`
150/// when it died on the way to a cell and never took its turn, and then it
151/// is this call's own unfinished place — so the call behind waits for what
152/// this one was waiting for instead of jumping the queue.
153///
154/// Without the handoff a failed call releases its successor immediately,
155/// and a third call can be delivered ahead of a first that is still in
156/// flight. Rare, since it needs a call to fail between two that do not, and
157/// silent, since every call involved still gets an answer.
158struct Place(Option<Box<tokio::sync::oneshot::Receiver<Place>>>);
159
160impl CallOrder {
161 /// Wait for every call before this one to be delivered.
162 ///
163 /// A loop rather than one await because a call that died hands back
164 /// what *it* was waiting for. `Err` is the chain ahead going away
165 /// entirely, which is nothing left to wait for.
166 pub async fn wait(&mut self) {
167 let mut ahead = self.ahead.take();
168 while let Some(place) = ahead {
169 ahead = match place.await {
170 Ok(Place(forward)) => forward.map(|boxed| *boxed),
171 Err(_) => None,
172 };
173 }
174 }
175
176 /// This call has been delivered; the one behind it may go.
177 pub fn delivered(&mut self) {
178 self.delivered = true;
179 }
180}
181
182impl Drop for CallOrder {
183 fn drop(&mut self) {
184 // Nothing followed this call, so the chain is empty and its tail is
185 // only a leak. A caller's chains outlive its calls otherwise, and a
186 // cell isolate's default caller outlives everything.
187 let mut chains = self.caller.call_chains.lock().unwrap();
188 if chains
189 .tails
190 .get(&self.cell)
191 .is_some_and(|(seq, _)| *seq == self.seq)
192 {
193 chains.tails.remove(&self.cell);
194 }
195 drop(chains);
196 if let Some(release) = self.release.take() {
197 let forward = (!self.delivered).then(|| self.ahead.take()).flatten();
198 let _ = release.send(Place(forward.map(Box::new)));
199 }
200 }
201}
202
203/// One caller's chains, one per cell it has called.
204#[derive(Default)]
205struct CallChains {
206 next_seq: u64,
207 tails: HashMap<String, (u64, tokio::sync::oneshot::Receiver<Place>)>,
208}
209
210/// Take this call's place in its caller's chain for `cell`. Synchronous, so
211/// the places are taken in the order the script made the calls.
212fn enter_call_order(caller: Arc<IoContext>, cell: &str) -> CallOrder {
213 let (release, next) = tokio::sync::oneshot::channel();
214 let (seq, ahead) = {
215 let mut chains = caller.call_chains.lock().unwrap();
216 chains.next_seq += 1;
217 let seq = chains.next_seq;
218 let ahead = chains
219 .tails
220 .insert(cell.to_string(), (seq, next))
221 .map(|(_, ahead)| ahead);
222 (seq, ahead)
223 };
224 CallOrder {
225 ahead,
226 release: Some(release),
227 caller,
228 cell: cell.to_string(),
229 seq,
230 delivered: false,
231 }
232}
233
234/// An output-gate request for the co-hosted (same-isolate) Durable Object fast
235/// path. That path runs a resident DO's `fetch` inline, bypassing
236/// `dispatch_do_call` where the gate lives; the inline handler samples the
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.
239pub struct GateReq {
240 pub scope: String,
241 pub position: Option<u64>,
242 pub reply: tokio::sync::oneshot::Sender<Result<(), celld_logic::RequestError>>,
243}
244static GATE_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<GateReq>> = OnceLock::new();
245pub fn set_gate_tx(tx: tokio::sync::mpsc::UnboundedSender<GateReq>) {
246 let _ = GATE_TX.set(tx);
247}
248
249/// A service-binding call: `env.NAME.fetch()`. Unlike a Durable Object call
250/// there is no identity to resolve — any isolate running `script` will do — so
251/// the runtime hands this straight to that script's stateless isolate pool.
252pub struct SvcCallReq {
253 /// Fires when the caller's request signal aborts, so the router stops
254 /// waiting on the target instead of leaving the call outstanding.
255 pub cancel: Option<tokio::sync::oneshot::Receiver<()>>,
256 pub script: String,
257 pub url: String,
258 pub method: String,
259 pub body: Vec<u8>,
260 pub headers: Vec<(String, String)>,
261 pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
262}
263static SVC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcCallReq>> = OnceLock::new();
264
265/// A Worker assets-binding call. The script name selects the immutable asset
266/// index loaded for that Worker; unlike ingress this never falls back into the
267/// Worker and therefore cannot recurse.
268pub struct AssetCallReq {
269 pub script: String,
270 pub url: String,
271 pub method: String,
272 pub headers: Vec<(String, String)>,
273 pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
274}
275static ASSET_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<AssetCallReq>> = OnceLock::new();
276
277/// An RPC call on a named `WorkerEntrypoint` of another script. Arguments and
278/// the result cross as V8 structured-clone bytes.
279pub struct SvcRpcReq {
280 pub script: String,
281 pub entrypoint: String,
282 pub method: String,
283 pub args: Vec<u8>,
284 pub reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
285}
286static SVC_RPC_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<SvcRpcReq>> = OnceLock::new();
287pub fn set_svc_rpc_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcRpcReq>) {
288 let _ = SVC_RPC_TX.set(tx);
289}
290pub fn set_svc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<SvcCallReq>) {
291 let _ = SVC_CALL_TX.set(tx);
292}
293pub fn set_asset_call_tx(tx: tokio::sync::mpsc::UnboundedSender<AssetCallReq>) {
294 let _ = ASSET_CALL_TX.set(tx);
295}
296pub fn set_do_call_tx(tx: tokio::sync::mpsc::UnboundedSender<DoCallReq>) {
297 let _ = DO_CALL_TX.set(tx);
298}
299
300/// Hand a Durable Object call to the dispatcher. Public HTTP ingress uses the
301/// same queue a Worker's `env.NAME.get(id).fetch()` does, so both resolve
302/// ownership, forward, and redispatch by one policy rather than two.
303#[must_use]
304pub fn submit_do_call(call: DoCallReq) -> bool {
305 DO_CALL_TX.get().is_some_and(|tx| tx.send(call).is_ok())
306}
307
308/// The arm-time wake-entry gate, output-gate style (matching Durable
309/// Objects): `setAlarm()` resolves optimistically on the committed local
310/// write — it never yields the cell's event scheduling to remote I/O — and
311/// the cell's response edge is withheld until every pending wake-entry PUT
312/// has landed. Invariant: an arm the caller has OBSERVED acknowledged
313/// (received the response) is covered by a durable entry.
314pub struct ArmGate {
315 pub bucket: crate::bucket::Bucket,
316 pub flusher: Arc<crate::wake::WakeFlusher>,
317}
318
319type ArmGateRx = tokio::sync::oneshot::Receiver<Result<(), String>>;
320
321#[derive(Default)]
322pub(crate) struct WakeEntryService {
323 gate: OnceLock<ArmGate>,
324 pending: Mutex<HashMap<String, Vec<ArmGateRx>>>,
325}
326
327pub fn set_arm_gate(gate: ArmGate) {
328 let _ = asyncrt::services().wake_entry().gate.set(gate);
329}
330
331/// Whether this node still holds a wake entry for `cell`.
332pub fn wake_entry_tracked(cell: &str) -> bool {
333 asyncrt::services()
334 .wake_entry()
335 .gate
336 .get()
337 .is_some_and(|gate| gate.flusher.tracks(cell))
338}
339
340/// Drop this node's belief about `cell`'s wake entry — the cell fenced or
341/// resolved to a remote owner, so the entry is no longer ours to manage.
342/// Defined since the wake audit and now actually called (it was dead code,
343/// which meant a node that lost a cell kept believing in its entry).
344pub fn forget_wake_entry(cell: &str) {
345 let services = asyncrt::services();
346 if let Some(gate) = services.wake_entry().gate.get() {
347 gate.flusher.forget(cell);
348 }
349}
350
351/// Adopt the wake entry a restored alarm implies, so consuming that alarm
352/// deletes it rather than orphaning it.
353pub fn adopt_wake_entry(cell: &str, at_ms: i64) {
354 let services = asyncrt::services();
355 if let Some(gate) = services.wake_entry().gate.get() {
356 gate.flusher.adopt(cell, at_ms);
357 }
358}
359
360/// Bring the bucket's wake entry for `cell` into line with its alarm.
361///
362/// Arming writes an entry; something has to take it away again once the alarm
363/// has been consumed, or the entry outlives its alarm and every later due scan
364/// finds it and wakes a cell with nothing to do. `consume_durable` gates that
365/// final delete on the consuming commit being replicated -- removing the hint
366/// while the commit that consumed the alarm is still only local would lose
367/// both the alarm and the record that could have revived it.
368pub async fn reconcile_wake_entry(cell: &str, next_alarm_ms: i64, consume_durable: bool) {
369 let services = asyncrt::services();
370 let Some(gate) = services.wake_entry().gate.get() else {
371 return;
372 };
373 gate.flusher
374 .reconcile(&gate.bucket, cell, next_alarm_ms, consume_durable)
375 .await;
376}
377
378/// A committed alarm tightened the durable wake bound: launch the entry PUT
379/// and register it against the cell's output gate. No-op when the bound
380/// already covers it or no gate is configured (unit tests).
381fn spawn_arm_gate(cell: &str, at_ms: i64) {
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 };
390 let Some(celld_logic::wake::Op::Put { key, due_ms }) = gate.flusher.arm_op(cell, at_ms) else {
391 return;
392 };
393 let cell_ = cell.to_string();
394 let (tx, rx) = tokio::sync::oneshot::channel();
395 {
396 let mut pending = services.wake_entry().pending.lock().unwrap();
397 let gates = pending.entry(cell_.clone()).or_default();
398 // Arms with no response edge to drain them (alarm handlers,
399 // WebSocket events) must not accumulate: drop already-settled gates.
400 gates.retain_mut(|gate| {
401 matches!(
402 gate.try_recv(),
403 Err(tokio::sync::oneshot::error::TryRecvError::Empty)
404 )
405 });
406 gates.push(rx);
407 }
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;
417 let body = format!("{{\"cell\":{cell_:?},\"due_ms\":{due_ms}}}");
418 let result = gate
419 .bucket
420 .put(&key, body.into_bytes())
421 .await
422 .map(|_| gate.flusher.confirm_arm(&cell_, due_ms, key))
423 .map_err(|e| format!("setAlarm wake entry: {e}"));
424 let _ = tx.send(result);
425 })
426 .detach();
427}
428
429#[cfg(all(test, celld_internal_tests))]
430pub(crate) fn spawn_arm_gate_for_test(cell: &str, at_ms: i64) {
431 spawn_arm_gate(cell, at_ms);
432}
433
434/// Await the cell's pending wake-entry PUTs — the output-gate drain a
435/// response edge performs before releasing its reply. An error means an arm
436/// the response would acknowledge is not durably covered; the caller must
437/// fail the response rather than lie (the flusher retries the entry).
438pub async fn drain_arm_gates(cell: &str) -> Result<(), String> {
439 let services = asyncrt::services();
440 let gates = services.wake_entry().pending.lock().unwrap().remove(cell);
441 let Some(gates) = gates else { return Ok(()) };
442 for gate in gates {
443 match gate.await {
444 Ok(Ok(())) => {}
445 Ok(Err(error)) => return Err(error),
446 Err(_) => return Err("wake-entry gate task dropped".into()),
447 }
448 }
449 Ok(())
450}
451
452pub type RequestId = u128;
453
454#[derive(Clone, Copy)]
455pub struct FetchRequest<'a> {
456 pub url: &'a str,
457 pub method: &'a str,
458 pub body: &'a [u8],
459 pub headers: &'a [(String, String)],
460 pub request_id: Option<RequestId>,
461}
462
463/// Allocate an id for an ingress or service-binding request so it can be
464/// aborted mid-flight.
465pub fn next_request_id() -> RequestId {
466 next_do_request_id()
467}
468
469static NEXT_DO_REQUEST_ID: AtomicU64 = AtomicU64::new(1);
470static DO_REQUEST_PROCESS_PREFIX: OnceLock<u64> = OnceLock::new();
471static DO_CALL_CANCELS: OnceLock<
472 std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>>,
473> = OnceLock::new();
474fn do_call_cancels(
475) -> &'static std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>> {
476 DO_CALL_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
477}
478
479fn next_do_request_id() -> RequestId {
480 let prefix = *DO_REQUEST_PROCESS_PREFIX.get_or_init(|| {
481 let mut bytes = [0; 8];
482 getrandom::fill(&mut bytes).expect("OS random source unavailable");
483 u64::from_ne_bytes(bytes)
484 });
485 let sequence = NEXT_DO_REQUEST_ID.fetch_add(1, Ordering::Relaxed);
486 (u128::from(prefix) << 64) | u128::from(sequence)
487}
488
489pub fn request_id_string(request_id: RequestId) -> String {
490 format!("{request_id:032x}")
491}
492
493pub fn parse_request_id(value: &str) -> Option<RequestId> {
494 u128::from_str_radix(value, 16).ok()
495}
496
497struct DoCallCancelGuard(Option<RequestId>);
498
499impl DoCallCancelGuard {
500 fn new(request: RequestId) -> Self {
501 Self(Some(request))
502 }
503
504 fn disarm(&mut self) {
505 if let Some(request) = self.0.take() {
506 do_call_cancels().lock().unwrap().remove(&request);
507 }
508 }
509}
510
511impl Drop for DoCallCancelGuard {
512 fn drop(&mut self) {
513 let Some(request) = self.0.take() else {
514 return;
515 };
516 if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request) {
517 let _ = cancel.send(());
518 }
519 }
520}
521
522/// An RPC payload crossing the host boundary. JS stubs marshal by V8
523/// structured clone (`V8`); the legacy cross-node JSON envelope and the test
524/// harness use `Json`. `__dispatchRpc` answers in the flavor it was asked in.
525pub enum RpcData {
526 Json(String),
527 V8(Vec<u8>),
528}
529
530/// A native Durable Object RPC call (`stub.someMethod(...args)`).
531/// Routing/activation is identical to fetch calls.
532pub struct RpcCallReq {
533 pub scope: String,
534 pub name: Option<String>,
535 pub method: String,
536 pub args: RpcData,
537 pub reply: tokio::sync::oneshot::Sender<Result<RpcData>>,
538}
539static RPC_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<RpcCallReq>> = OnceLock::new();
540pub fn set_rpc_call_tx(tx: tokio::sync::mpsc::UnboundedSender<RpcCallReq>) {
541 let _ = RPC_CALL_TX.set(tx);
542}
543
544pub struct OutboundWsReq {
545 pub scope: String,
546 pub id: u64,
547 pub url: String,
548 pub protocols: Vec<String>,
549 /// Present for an isolate-polled (Worker) socket. Created and registered
550 /// on the JS thread before the request is sent, so `__ws_next` can never
551 /// run ahead of its own queue.
552 pub pull: Option<WsPullSender>,
553 /// Extra request headers, for the `fetch()` upgrade form.
554 pub headers: Vec<(String, String)>,
555 /// A `fetch()` upgrade wants the whole handshake outcome, including the
556 /// ordinary response a server that declines to upgrade sent instead.
557 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>,
564 pub reply: tokio::sync::oneshot::Sender<Result<OutboundWsOpen>>,
565}
566
567/// The ordinary HTTP response a server sent instead of upgrading. `fetch()`
568/// returns it verbatim rather than turning it into a connection error.
569pub struct DeclinedUpgrade {
570 pub status: u16,
571 pub headers: Vec<(String, String)>,
572 pub body: Vec<u8>,
573}
574
575/// What an outbound handshake produced.
576pub struct OutboundWsOpen {
577 pub protocol: Option<String>,
578 pub declined: Option<DeclinedUpgrade>,
579}
580static OUTBOUND_WS_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<OutboundWsReq>> =
581 OnceLock::new();
582pub fn set_outbound_ws_tx(tx: tokio::sync::mpsc::UnboundedSender<OutboundWsReq>) {
583 let _ = OUTBOUND_WS_TX.set(tx);
584}
585
586static NEXT_TIMER_ID: AtomicU64 = AtomicU64::new(1);
587static TIMER_CANCELS: OnceLock<std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>>> =
588 OnceLock::new();
589fn timer_cancels() -> &'static std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>> {
590 TIMER_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
591}
592static 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.
599const HTTP_STREAM_DONE: &str = "__celld_http_stream_end__";
600enum HttpStreamSource {
601 Response(reqwest::Response),
602 Receiver(tokio::sync::mpsc::Receiver<Result<Vec<u8>, String>>),
603 Stream(HttpChunkStream),
604}
605struct HttpStreamEntry {
606 created: Instant,
607 source: Option<HttpStreamSource>,
608 cancelled: tokio::sync::watch::Sender<bool>,
609}
610static HTTP_STREAMS: OnceLock<std::sync::Mutex<HashMap<u64, HttpStreamEntry>>> = OnceLock::new();
611fn http_streams() -> &'static std::sync::Mutex<HashMap<u64, HttpStreamEntry>> {
612 HTTP_STREAMS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
613}
614fn register_http_stream(stream_id: u64, source: HttpStreamSource) {
615 let (cancelled, _) = tokio::sync::watch::channel(false);
616 let mut streams = http_streams().lock().unwrap();
617 streams.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60));
618 streams.insert(
619 stream_id,
620 HttpStreamEntry {
621 created: Instant::now(),
622 source: Some(source),
623 cancelled,
624 },
625 );
626}
627struct ResponseStreamWriter {
628 created: Instant,
629 writer: tokio::sync::mpsc::Sender<Result<Vec<u8>, String>>,
630 finished: tokio::sync::watch::Sender<bool>,
631}
632static RESPONSE_STREAM_WRITERS: OnceLock<std::sync::Mutex<HashMap<u64, ResponseStreamWriter>>> =
633 OnceLock::new();
634fn response_stream_writers() -> &'static std::sync::Mutex<HashMap<u64, ResponseStreamWriter>> {
635 RESPONSE_STREAM_WRITERS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
636}
637
638pub type HttpChunkStream =
639 Pin<Box<dyn futures_util::Stream<Item = Result<Vec<u8>, String>> + Send>>;
640
641#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
642pub struct WsTarget {
643 pub id: u64,
644 pub scope: String,
645 #[serde(default, skip_serializing_if = "Option::is_none")]
646 pub peer_node: Option<String>,
647 #[serde(default, skip_serializing_if = "Option::is_none")]
648 pub peer_addr: Option<String>,
649 #[serde(default, skip_serializing_if = "Option::is_none")]
650 pub peer_epoch: Option<u64>,
651}
652
653/// Encode a host response for the JS side. A text body crosses as a
654/// JS string (cheap, lossless), binary as a byte array, and a streaming body
655/// by id — serializing a Vec<u8> as a JSON number array is the dominant cost
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.
658fn encode_http_response(mut response: HttpResponse, ws_target: bool) -> String {
659 let mut obj = serde_json::json!({
660 "status": response.status,
661 "headers": response.headers,
662 });
663 if ws_target {
664 obj["wsTarget"] = serde_json::json!(response.ws);
665 }
666 if let Some(stream) = response.stream.take() {
667 let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
668 register_http_stream(stream_id, HttpStreamSource::Stream(stream));
669 obj["streamId"] = serde_json::json!(stream_id);
670 } else {
671 match std::str::from_utf8(&response.body) {
672 Ok(text) => obj["body"] = serde_json::Value::String(text.into()),
673 Err(_) => obj["bodyBytes"] = serde_json::json!(response.body),
674 }
675 }
676 obj.to_string()
677}
678
679pub struct HttpResponse {
680 pub status: u16,
681 pub body: Vec<u8>,
682 /// A response body forwarded without materializing it in memory.
683 pub stream: Option<HttpChunkStream>,
684 pub headers: Vec<(String, String)>,
685 pub ws: Option<WsTarget>,
686 /// The cell's committed-write position after the handler ran, for a local
687 /// Durable Object request. The shell gates the response on durability when
688 /// this advanced past the cell's last seen position. `None` for responses
689 /// with no cell storage (Worker, asset, or proxied remote).
690 pub write_position: Option<u64>,
691}
692
693/// Which alarm a dispatch runs, and who owns its bookkeeping.
694pub enum AlarmDispatch {
695 /// Claim whatever is due now, and record the outcome. Production only
696 /// ever asks for this.
697 Due,
698 /// Claim whatever is armed, however far ahead its deadline. Test-only:
699 /// the corpus asserts on retry accounting without waiting out real
700 /// deadlines.
701 Armed,
702 /// The caller has already claimed it. Dispatch with this retry count and
703 /// leave the bookkeeping to them. Test-only, so the corpus can assert on
704 /// the claim and the handler separately.
705 Claimed(i64),
706}
707
708/// One event a cell receives.
709///
710/// Every variant is something the outside world did to the cell, and each
711/// becomes an `InFlight` entry driven by its own tokio task. Lifecycle —
712/// taking a cell in, giving it back, cancelling a request — is not here: it
713/// is a direct call on the isolate, because it is not an event and has no
714/// handler to run.
715pub enum CellJob {
716 Fetch {
717 request_id: Option<RequestId>,
718 scope: String,
719 name: Option<String>,
720 url: String,
721 method: String,
722 body: Vec<u8>,
723 headers: Vec<(String, String)>,
724 reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
725 /// Where this call sits in its caller's order for this cell, if it
726 /// came from a script rather than from a peer or the ingress.
727 order: Option<CallOrder>,
728 },
729 Rpc {
730 scope: String,
731 name: Option<String>,
732 method: String,
733 args: RpcData,
734 reply: tokio::sync::oneshot::Sender<Result<RpcOutcome>>,
735 },
736 WsOpen {
737 scope: String,
738 ws_id: u64,
739 protocol: String,
740 reply: tokio::sync::oneshot::Sender<Result<()>>,
741 },
742 WsMessage {
743 scope: String,
744 ws_id: u64,
745 data: WsIn,
746 reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>,
747 },
748 WsClosed {
749 scope: String,
750 ws_id: u64,
751 code: u16,
752 reason: String,
753 was_clean: bool,
754 reply: tokio::sync::oneshot::Sender<Result<()>>,
755 },
756 Alarm {
757 scope: String,
758 scheduled_ms: i64,
759 /// Which alarm to run, and who owns the bookkeeping.
760 claim: AlarmDispatch,
761 /// Replies with (next alarm, the handler's write delta). The delta is
762 /// sampled inside the turn — cell storage must never be reached from
763 /// the shell — and the shell uses it to prove the consuming commit
764 /// durable before the core settles. Every answer shape samples it the
765 /// same way now, in `InFlight::answer_settled`.
766 reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>,
767 },
768}
769
770impl CellJob {
771 /// The cell this event addresses, which is also the realm it runs in.
772 pub fn scope(&self) -> &str {
773 match self {
774 CellJob::Fetch { scope, .. }
775 | CellJob::Rpc { scope, .. }
776 | CellJob::WsOpen { scope, .. }
777 | CellJob::WsMessage { scope, .. }
778 | CellJob::WsClosed { scope, .. }
779 | CellJob::Alarm { scope, .. } => scope,
780 }
781 }
782
783 /// This event's place in its caller's order, taken out so the drive can
784 /// wait on it and then release the call behind it.
785 pub fn take_order(&mut self) -> Option<CallOrder> {
786 match self {
787 CellJob::Fetch { order, .. } => order.take(),
788 _ => None,
789 }
790 }
791
792 /// Fail this event without running it.
793 pub fn fail(self, error: anyhow::Error) {
794 match self {
795 CellJob::Fetch { reply, .. } => drop(reply.send(Err(error))),
796 CellJob::Rpc { reply, .. } => drop(reply.send(Err(error))),
797 CellJob::WsOpen { reply, .. } => drop(reply.send(Err(error))),
798 CellJob::WsMessage { reply, .. } => drop(reply.send(Err(error))),
799 CellJob::WsClosed { reply, .. } => drop(reply.send(Err(error))),
800 CellJob::Alarm { reply, .. } => drop(reply.send(Err(error))),
801 }
802 }
803}
804
805thread_local! {
806 // One outbound HTTP client per JS thread — building it per fetch rebuilds
807 // the TLS stack every call (async-op-hazards.md).
808 static HTTP: reqwest::Client = reqwest::Client::new();
809 static HTTP_MANUAL: reqwest::Client = reqwest::Client::builder()
810 .redirect(reqwest::redirect::Policy::none()).build().unwrap();
811 static DO_ID_KEYS: RefCell<HashMap<String, [u8; 32]>> = RefCell::new(HashMap::new());
812}
813
814mod websocket;
815pub(crate) use websocket::WebSocketService;
816pub use websocket::*;
817use websocket::{ws_capture_begin, ws_capture_take};
818
819/// Held for the duration of one cell event; pops on every exit path.
820pub struct EgressGateScope;
821
822impl Drop for EgressGateScope {
823 fn drop(&mut self) {
824 current_context().egress.lock().unwrap().pop();
825 }
826}
827
828pub fn egress_gate_enter(cell: &str, position: Option<u64>) -> EgressGateScope {
829 current_context()
830 .egress
831 .lock()
832 .unwrap()
833 .push((cell.to_string(), position.unwrap_or(0)));
834 EgressGateScope
835}
836
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.
845enum 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
857impl 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.
869fn egress_gate_request() -> EgressGate {
870 let context = current_context();
871 let stack = context.egress.lock().unwrap();
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 }
888}
889
890/// Wait for the writes an outbound effect can reveal to be proven durable
891/// before it leaves the process.
892///
893/// This is the output gate applied to egress rather than to the response.
894/// It cannot deadlock the handler that is awaiting it: the ticket is served by
895/// `dispatch_gate` on the host's own loop and resolved by the replicator's
896/// independent task, neither of which needs the isolate's event loop to run.
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.
900async 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),
905 };
906 let (tx, receive) = tokio::sync::oneshot::channel();
907 let sent = GATE_TX
908 .get()
909 .map(|gate| {
910 gate.send(GateReq {
911 scope: cell,
912 position,
913 reply: tx,
914 })
915 .is_ok()
916 })
917 .unwrap_or(false);
918 if !sent {
919 return Err("no output-gate channel".into());
920 }
921 match receive.await {
922 Ok(Ok(())) => Ok(()),
923 Ok(Err(error)) => Err(format!(
924 "refusing to send: the write this request follows is not durable ({error:?})"
925 )),
926 Err(_) => Err("output gate dropped".into()),
927 }
928}
929
930/// Hold an outbound request until the write it follows is durable, then hand
931/// it to the host.
932///
933/// The send moves inside the future deliberately. These channels dispatch as
934/// soon as `send` is called, so gating anywhere after it would let the effect
935/// leave first -- the request would already be on its way while the caller
936/// waited for a durability answer that no longer decides anything.
937async fn gated_channel_send<T>(
938 gate: EgressGate,
939 channel: &'static OnceLock<tokio::sync::mpsc::UnboundedSender<T>>,
940 request: T,
941 missing: &'static str,
942) -> std::result::Result<(), String> {
943 await_egress_gate(gate).await?;
944 match channel.get() {
945 Some(tx) if tx.send(request).is_ok() => Ok(()),
946 _ => Err(missing.to_string()),
947 }
948}
949
950/// One `celld_logic::gate::InputGate` per cell.
951///
952/// The logic decides; this is only the map and the ids. It replaces the
953/// promise chain that used to live in `harness.js`, which serialised blocks
954/// against each other but did nothing about *delivery* — so a second event
955/// could arrive mid-block, and under real concurrency that wedged the cell.
956///
957/// Keyed by cell scope rather than held on the isolate, because a gate
958/// belongs to a cell and cells share isolates.
959static CELL_GATES: OnceLock<Mutex<HashMap<String, celld_logic::gate::InputGate>>> = OnceLock::new();
960static NEXT_GATE_EVENT: AtomicU64 = AtomicU64::new(1);
961
962fn cell_gates() -> &'static Mutex<HashMap<String, celld_logic::gate::InputGate>> {
963 CELL_GATES.get_or_init(|| Mutex::new(HashMap::new()))
964}
965
966/// What a waiting event is told when the gate finally opens: nothing, or
967/// the reason the holder failed.
968type GateWake = tokio::sync::oneshot::Sender<Result<(), String>>;
969
970static GATE_WAITERS: OnceLock<Mutex<HashMap<String, Vec<GateWake>>>> = OnceLock::new();
971
972/// Events waiting for a cell's input gate to open, in arrival order.
973///
974/// Step 6 deleted this queue, correctly at the time: an event the gate
975/// refused stayed on the cell's job channel until a later delivery point
976/// took it, so the channel *was* the queue and a second one could disagree
977/// with it. Drives have no channel, so a refused event needs somewhere to
978/// wait, and workerd keeps the same structure for the same reason
979/// (`io-gate.h`, `kj::List<Waiter, &Waiter::link> waiters`).
980///
981/// In the shell rather than in `celld_logic::gate`, because what waits is a
982/// tokio task and the core is sans-IO. The core still owns the decision —
983/// `is_open` — and this owns only the waking.
984fn gate_waiters() -> &'static Mutex<HashMap<String, Vec<GateWake>>> {
985 GATE_WAITERS.get_or_init(|| Mutex::new(HashMap::new()))
986}
987
988/// Take a ticket to be woken when `cell`'s gate opens, or `None` if it is
989/// open now.
990///
991/// The gate's lock is held across the check and the enqueue, so a release
992/// that lands between the two cannot leave an event waiting on a gate that
993/// is already open.
994pub fn cell_gate_wait(cell: &str) -> Option<tokio::sync::oneshot::Receiver<Result<(), String>>> {
995 let gates = cell_gates().lock().unwrap();
996 if gates.get(cell).is_none_or(|gate| gate.is_open()) {
997 return None;
998 }
999 let (wake, waiter) = tokio::sync::oneshot::channel();
1000 gate_waiters()
1001 .lock()
1002 .unwrap()
1003 .entry(cell.to_string())
1004 .or_default()
1005 .push(wake);
1006 drop(gates);
1007 Some(waiter)
1008}
1009
1010/// Wake everything waiting on `cell`'s gate. Each re-checks and re-queues if
1011/// another block took the gate first, so waking all of them is correct and
1012/// the order they resume in is theirs to lose, not this function's to keep.
1013fn wake_gate_waiters(cell: &str, outcome: Result<(), String>) {
1014 let waiters = gate_waiters().lock().unwrap().remove(cell);
1015 for wake in waiters.into_iter().flatten() {
1016 let _ = wake.send(outcome.clone());
1017 }
1018}
1019
1020/// The event holding this cell's gate died without releasing it.
1021///
1022/// Only execution termination reaches here: every other exit from a block
1023/// runs the `finally` in `harness.js`. Without it a cell whose blocking
1024/// request was killed would refuse every later event forever.
1025fn cell_gate_abandon(scope: &str) {
1026 if let Some(gate) = cell_gates().lock().unwrap().get_mut(scope) {
1027 gate.abandon();
1028 }
1029 // The holder died without running its `finally`, so nobody can say why.
1030 // Refuse the waiters anyway: the cell it queued behind is gone.
1031 wake_gate_waiters(
1032 scope,
1033 Err("the cell's critical section ended without releasing".to_string()),
1034 );
1035}
1036
1037/// JS promise resolvers awaiting an async op, keyed by the op's id.
1038///
1039/// **Per isolate, and shared across threads.** Under D1 a request's turns run
1040/// on whichever tokio worker picks them up, so a resolver registered on one
1041/// thread is resolved from another; a thread-local map loses it, and
1042/// `resolve_res` fails to find the resolver and returns silently, leaving the
1043/// handler awaiting a promise nothing will ever settle. The `Mutex` is what
1044/// makes that safe, not the map's location.
1045///
1046/// It lives on `ActorRuntimeState` — one per isolate, reached from a scope —
1047/// so a resolver is only ever looked up in the heap that owns it. One map for
1048/// the whole process would also work, because op ids come from a single
1049/// counter (`asyncrt::NEXT_ID`) and an id names exactly one resolver. But that
1050/// makes an id-allocation bug into cross-isolate handle confusion, where this
1051/// makes it a miss.
1052type PromiseMap = HashMap<u64, v8::Global<v8::PromiseResolver>>;
1053
1054/// Requests cancelled by a reentrant `AbortFetch`. Global for the same reason
1055/// as [`promises`]: the turn that observes a cancellation need not be on the
1056/// thread that recorded it.
1057static CANCELLED_REQUESTS: OnceLock<Mutex<HashSet<RequestId>>> = OnceLock::new();
1058
1059fn cancelled_requests() -> &'static Mutex<HashSet<RequestId>> {
1060 CANCELLED_REQUESTS.get_or_init(|| Mutex::new(HashSet::new()))
1061}
1062
1063fn promise_store(scope: &mut v8::PinScope, id: u64, r: v8::Global<v8::PromiseResolver>) {
1064 actor_runtime_state(scope)
1065 .promises
1066 .lock()
1067 .unwrap()
1068 .insert(id, r);
1069}
1070
1071/// Resolve or reject op `id`'s promise with its outcome.
1072fn resolve_res(tc: &mut v8::PinScope, id: u64, res: Result<asyncrt::OpOut, String>) {
1073 let g = match actor_runtime_state(tc).promises.lock().unwrap().remove(&id) {
1074 Some(g) => g,
1075 None => return,
1076 };
1077 let r = v8::Local::new(tc, g);
1078 match res {
1079 Ok(asyncrt::OpOut::Str(v)) => {
1080 let s = v8::String::new(tc, &v).unwrap();
1081 r.resolve(tc, s.into());
1082 }
1083 Ok(asyncrt::OpOut::Bytes(b)) => {
1084 let v = bytes_value(tc, b);
1085 r.resolve(tc, v);
1086 }
1087 Err(e) => {
1088 let s = v8::String::new(tc, &e).unwrap();
1089 let ex = v8::Exception::error(tc, s);
1090 r.reject(tc, ex);
1091 }
1092 }
1093}
1094
1095/// Move `bytes` into a `Uint8Array` without copying.
1096fn bytes_value<'s>(scope: &mut v8::PinScope<'s, '_>, bytes: Vec<u8>) -> v8::Local<'s, v8::Value> {
1097 let len = bytes.len();
1098 let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();
1099 let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);
1100 v8::Uint8Array::new(scope, buffer, 0, len).unwrap().into()
1101}
1102
1103pub fn handler_budget() -> Duration {
1104 static BUDGET: OnceLock<Duration> = OnceLock::new();
1105 *BUDGET.get_or_init(|| {
1106 Duration::from_secs(
1107 crate::env_vars::positive_or("CELLD_HANDLER_BUDGET_S", 300)
1108 .expect("validated CELLD_HANDLER_BUDGET_S"),
1109 )
1110 })
1111}
1112
1113/// Aborts raised by an HTTP or service-binding caller disconnecting while the
1114/// target runs in the stateless isolate pool. Durable Object aborts can also
1115/// arrive as a reentrant `CellJob::AbortFetch`, so the abort has to be visible
1116/// from whichever turn observes it.
1117///
1118/// The counter keeps the common path to one relaxed atomic load per loop turn:
1119/// with nothing pending, the mutex is never taken.
1120static PENDING_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> =
1121 OnceLock::new();
1122static PENDING_ABORT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1123
1124fn pending_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> {
1125 PENDING_ABORTS.get_or_init(Default::default)
1126}
1127
1128/// Mark an in-flight request cancelled from any thread.
1129pub fn abort_request(request_id: RequestId) {
1130 if pending_aborts().lock().unwrap().insert(request_id) {
1131 PENDING_ABORT_COUNT.fetch_add(1, Ordering::Relaxed);
1132 }
1133}
1134
1135fn clear_request_cancellation(request_id: RequestId) {
1136 let _ = take_pending_abort(request_id);
1137}
1138
1139fn take_pending_abort(request_id: RequestId) -> bool {
1140 if PENDING_ABORT_COUNT.load(Ordering::Relaxed) == 0 {
1141 return false;
1142 }
1143 if pending_aborts().lock().unwrap().remove(&request_id) {
1144 PENDING_ABORT_COUNT.fetch_sub(1, Ordering::Relaxed);
1145 return true;
1146 }
1147 false
1148}
1149
1150pub fn take_request_cancellation(request_id: Option<RequestId>) -> bool {
1151 request_id.is_some_and(|request_id| {
1152 cancelled_requests().lock().unwrap().remove(&request_id) || take_pending_abort(request_id)
1153 })
1154}
1155
1156fn resolved_promise<'s>(
1157 tc: &mut v8::PinScope<'s, '_>,
1158 value: v8::Local<'s, v8::Value>,
1159) -> Result<v8::Local<'s, v8::Promise>> {
1160 let resolver =
1161 v8::PromiseResolver::new(tc).ok_or_else(|| anyhow!("could not create event promise"))?;
1162 resolver.resolve(tc, value);
1163 Ok(resolver.get_promise(tc))
1164}
1165
1166fn abort_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) -> Result<bool> {
1167 let global = tc.get_current_context().global(tc);
1168 let key = v8::String::new(tc, "__abortIncomingRequest").unwrap();
1169 let function: v8::Local<v8::Function> = global
1170 .get(tc, key.into())
1171 .ok_or_else(|| anyhow!("no __abortIncomingRequest"))?
1172 .try_into()
1173 .map_err(|_| anyhow!("__abortIncomingRequest is not a function"))?;
1174 let request_id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
1175 let recv = v8::undefined(tc).into();
1176 let result = function
1177 .call(tc, recv, &[request_id.into()])
1178 .ok_or_else(|| anyhow!("__abortIncomingRequest threw"))?;
1179 Ok(result.boolean_value(tc))
1180}
1181
1182/// The rejection reason of a settled-rejected promise, with a little stack.
1183fn reject_reason(tc: &mut v8::PinScope, p: v8::Local<v8::Promise>) -> String {
1184 let r = p.result(tc);
1185 let msg = r.to_rust_string_lossy(tc);
1186 let stk = r
1187 .to_object(tc)
1188 .and_then(|o| {
1189 let k = v8::String::new(tc, "stack")?;
1190 o.get(tc, k.into())
1191 })
1192 .map(|s| s.to_rust_string_lossy(tc))
1193 .unwrap_or_default();
1194 let tail = stk
1195 .lines()
1196 .skip(1)
1197 .take(3)
1198 .map(|l| l.trim())
1199 .collect::<Vec<_>>()
1200 .join(" <- ");
1201 if tail.is_empty() {
1202 msg
1203 } else {
1204 format!("{msg} [{tail}]")
1205 }
1206}
1207
1208pub struct Engine;
1209impl Engine {
1210 pub fn init() {
1211 // No `v8::icu::set_common_data_78` call: the rusty_v8 152 prebuilt
1212 // statically links the complete ICU data (full locale tables and
1213 // regex property-of-strings, e.g. /\p{RGI_Emoji}/v — verified
1214 // empirically), so overriding it with an embedded icudtl.dat only
1215 // duplicated 10.8 MB in the binary. A test pins that coverage, so a
1216 // future v8 bump that reduces the builtin data fails rather than
1217 // silently narrowing it; the fix would be to re-embed rusty_v8's
1218 // `third_party/icu/common/icudtl.dat`, 16-byte-aligned.
1219 let platform = v8::new_default_platform(0, false).make_shared();
1220 v8::V8::initialize_platform(platform);
1221 v8::V8::initialize();
1222 }
1223}
1224
1225/// Per-worker compatibility switches, derived from the manifest's
1226/// compatibility date and flags (Workerd compatibility-date.capnp). `Default`
1227/// is every switch off; production derives real values in `main`.
1228#[derive(Clone, Copy, Default)]
1229pub struct Compat {
1230 pub delete_all_deletes_alarm: bool,
1231 /// `js_rpc`: RPC on a Durable Object class that does not extend
1232 /// `DurableObject` (Workerd worker-rpc.c++ getTargetInfo()).
1233 pub js_rpc: bool,
1234 /// `fetcher_has_get_put_delete` (off = `fetcher_no_get_put_delete`,
1235 /// default on for dates >= 2024-03-26): the deprecated `get()`/`put()`/
1236 /// `delete()` HTTP helpers on stubs (Workerd http.c++ Fetcher).
1237 pub fetcher_get_put_delete: bool,
1238 /// `sqlite_vec`: expose the pre-v1 sqlite-vec extension to SQLite-backed
1239 /// Durable Objects. This switch is explicit and has no date default.
1240 pub sqlite_vec: bool,
1241 /// `websocket_standard_binary_type`: `binaryType` defaults to `"blob"` and
1242 /// a binary message arrives as a `Blob`, per the WHATWG default. Without
1243 /// it celld keeps the historical `"arraybuffer"`.
1244 pub websocket_standard_binary_type: bool,
1245}
1246
1247/// A non-main module the worker's main module may import, tagged by how the
1248/// runtime materializes it.
1249pub enum ModuleSource {
1250 /// UTF-8 content served as `export default "<content>"` (wrangler's Text
1251 /// rule), registered under the given specifier verbatim.
1252 Text(String),
1253 /// JS source compiled as a sibling ES module (Worker Loader multi-module
1254 /// bundles), registered under both `name` and `./name`.
1255 EsModule(String),
1256 /// Wasm bytes served as a module whose default export is the compiled
1257 /// `WebAssembly.Module` (Wrangler's `CompiledWasm` rule), registered
1258 /// under both `name` and `./name`.
1259 Wasm(bytes::Bytes),
1260}
1261
1262pub struct WorkerConfig {
1263 src: String,
1264 pub script_name: String,
1265 do_classes: Vec<String>,
1266 bindings: Vec<(String, String)>,
1267 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)>,
1271 ai_binding: Option<String>,
1272 vars: Vec<(String, String)>,
1273 node: String,
1274 /// The worker's non-main modules, so the main module can import siblings.
1275 modules: Vec<(String, ModuleSource)>,
1276 compat: Compat,
1277 /// `[[services]]`: (binding name, target script, optional entrypoint).
1278 /// The target runs in this process; see [[service-bindings]].
1279 services: Vec<(String, String, Option<String>)>,
1280 asset_binding: Option<String>,
1281 /// `env` name of the Worker Loader binding, if this Worker may spawn
1282 /// dynamic isolates.
1283 loader_binding: Option<String>,
1284 /// Ambient outbound authority. Loaded workers may be denied.
1285 egress: EgressPolicy,
1286 /// Extra `env` values a loaded worker was handed, as a JSON object string
1287 /// merged onto its `env`. Loader-only; empty for normal workers.
1288 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>,
1292}
1293
1294pub struct WorkerConfigOptions {
1295 pub src: String,
1296 pub script_name: String,
1297 pub do_classes: Vec<String>,
1298 pub bindings: Vec<(String, String)>,
1299 pub r2_bindings: Vec<String>,
1300 pub d1_bindings: Vec<(String, String)>,
1301 pub ai_binding: Option<String>,
1302 pub vars: Vec<(String, String)>,
1303 pub node: String,
1304 pub modules: Vec<(String, ModuleSource)>,
1305 pub compat: Compat,
1306}
1307
1308impl WorkerConfig {
1309 pub fn new(options: WorkerConfigOptions) -> Self {
1310 let WorkerConfigOptions {
1311 src,
1312 script_name,
1313 do_classes,
1314 bindings,
1315 r2_bindings,
1316 d1_bindings,
1317 ai_binding,
1318 vars,
1319 node,
1320 modules,
1321 compat,
1322 } = options;
1323 Self {
1324 src,
1325 script_name,
1326 do_classes,
1327 bindings,
1328 r2_bindings,
1329 d1_bindings,
1330 ai_binding,
1331 vars,
1332 node,
1333 modules,
1334 compat,
1335 services: Vec::new(),
1336 asset_binding: None,
1337 loader_binding: None,
1338 egress: EgressPolicy::Allow,
1339 loader_env: None,
1340 crons: Vec::new(),
1341 }
1342 }
1343
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
1350 /// Grant this Worker a Worker Loader binding at `env` name `binding`.
1351 pub fn with_loader(mut self, binding: Option<String>) -> Self {
1352 self.loader_binding = binding;
1353 self
1354 }
1355
1356 /// Set this Worker's ambient outbound authority (loaded workers only).
1357 fn with_egress(mut self, egress: EgressPolicy) -> Self {
1358 self.egress = egress;
1359 self
1360 }
1361
1362 /// Merge `env` (a JSON object string) onto a loaded worker's `env`.
1363 fn with_loader_env(mut self, env: Option<String>) -> Self {
1364 self.loader_env = env;
1365 self
1366 }
1367
1368 /// Declare the service bindings this Worker may call.
1369 pub fn with_services(mut self, services: Vec<(String, String, Option<String>)>) -> Self {
1370 self.services = services;
1371 self
1372 }
1373
1374 pub fn with_asset_binding(mut self, binding: Option<String>) -> Self {
1375 self.asset_binding = binding;
1376 self
1377 }
1378}
1379
1380pub struct Worker {
1381 inner: Option<WorkerIsolate>,
1382}
1383
1384pub struct WorkerIsolate {
1385 /// Shared rather than owned: under D1 an isolate belongs to no thread,
1386 /// and a worker enters it by taking its `v8::Locker`.
1387 ///
1388 /// Every `lock()` below blocks until the current holder releases. That is
1389 /// only safe because the pool takes an async permit for this isolate
1390 /// first, so the lock is uncontended by construction; a `lock()` reached
1391 /// without that permit would be a blocking call on a tokio worker.
1392 isolate: v8::SharedIsolate,
1393 /// The one realm this isolate has: its context, and the entry `fetch`
1394 /// that lives in it.
1395 ///
1396 /// It was a `HashMap` keyed by cell, on the premise that a cell needs a
1397 /// realm of its own. It does not, and nothing ever put a second one in.
1398 /// The harness already keys instances by scope (`__cell.instances`), and
1399 /// Durable Objects **share** a context per script rather than getting one
1400 /// each — a context per cell would also duplicate the compiled module per
1401 /// cell, which is most of what sharing an isolate saves.
1402 realm: Realm,
1403 original_heap_limit: usize,
1404 compat: Compat,
1405 /// The storage of the cells this isolate hosts.
1406 ///
1407 /// It lives here, and not in a thread-local, because a driven cell's
1408 /// turns run on whatever tokio worker holds the isolate. See
1409 /// `storage::Cells`.
1410 cells: storage::Cells,
1411}
1412
1413/// An isolate's context and the entry `fetch` that lives in it.
1414///
1415/// `fetch` is here rather than beside the isolate because a function is a
1416/// value in the realm that created it.
1417struct Realm {
1418 context: v8::Global<v8::Context>,
1419 fetch: v8::Global<v8::Function>,
1420}
1421
1422impl WorkerIsolate {
1423 /// Take the isolate for one turn, and make the cells it hosts reachable
1424 /// while it is held.
1425 ///
1426 /// The two belong together. The lock is what makes this thread the only
1427 /// one that can touch the isolate, and a cell's SQLite handles are part
1428 /// of what it may touch — so a locker taken without installing them
1429 /// would let a turn reach no storage at all, or another isolate's.
1430 /// Pairing them here is why no call site has to remember.
1431 fn lock(&self) -> (v8::Locker<'_>, storage::Installed) {
1432 (self.isolate.lock(), self.cells.install())
1433 }
1434
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
1478 /// Localise the realm for one turn.
1479 ///
1480 /// **Taking the scope is the point.** Reaching a realm means touching
1481 /// `Global` handles, which on a shared isolate is only legal while its
1482 /// `Locker` is held — and there is no scope to pass until the isolate is
1483 /// locked. So the requirement is structural rather than a comment asking
1484 /// callers to remember it. It was a comment, and the one call site that
1485 /// forgot cloned two `Global`s a line too early; the panic happened
1486 /// inside a spawned request task, where tokio swallowed it and it
1487 /// surfaced only as a poisoned mutex on every later request.
1488 fn realm<'s>(&self, hs: &mut v8::PinScope<'s, '_, ()>) -> Entered<'s> {
1489 Entered {
1490 context: v8::Local::new(hs, &self.realm.context),
1491 fetch: v8::Local::new(hs, &self.realm.fetch),
1492 }
1493 }
1494}
1495
1496/// One realm, entered. Valid only for the scope that produced it, which is
1497/// what ties it to the isolate being locked.
1498struct Entered<'s> {
1499 context: v8::Local<'s, v8::Context>,
1500 fetch: v8::Local<'s, v8::Function>,
1501}
1502
1503impl std::ops::Deref for Worker {
1504 type Target = WorkerIsolate;
1505
1506 fn deref(&self) -> &Self::Target {
1507 self.inner.as_ref().expect("Worker isolate unavailable")
1508 }
1509}
1510
1511impl std::ops::DerefMut for Worker {
1512 fn deref_mut(&mut self) -> &mut Self::Target {
1513 self.inner.as_mut().expect("Worker isolate unavailable")
1514 }
1515}
1516
1517const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024;
1518const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024;
1519
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.
1524const 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.
1529const 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.
1535const HEAP_GC_NUDGE_INTERVAL: Duration = Duration::from_secs(1);
1536
1537struct HeapLimitState {
1538 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,
1549}
1550
1551impl 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))]
1571fn admission_refusal_forced(state: &HeapLimitState) -> bool {
1572 state.forced_admission_refusal.load(Ordering::Relaxed)
1573}
1574
1575#[cfg(not(all(test, celld_internal_tests)))]
1576fn admission_refusal_forced(_state: &HeapLimitState) -> bool {
1577 false
1578}
1579
1580type SerializedPut = (String, Vec<u8>);
1581type PendingPuts = HashMap<String, Vec<SerializedPut>>;
1582
1583/// Ambient outbound authority for an isolate. Normal workers keep `Allow`; a
1584/// Worker Loader can hand a loaded worker `Deny` (globalOutbound: null) so its
1585/// global `fetch()` throws and it must reach the world through `env`
1586/// capabilities.
1587#[derive(Clone, Copy, Default, PartialEq)]
1588enum EgressPolicy {
1589 #[default]
1590 Allow,
1591 Deny,
1592}
1593
1594#[derive(Default)]
1595struct ActorRuntimeState {
1596 promises: std::sync::Mutex<PromiseMap>,
1597 termination: std::sync::Mutex<Option<ExecutionTermination>>,
1598 pending_puts: std::sync::Mutex<PendingPuts>,
1599 egress: EgressPolicy,
1600}
1601
1602struct ExecutionTermination {
1603 error: String,
1604 actor_scope: Option<String>,
1605}
1606
1607fn finish_terminated_actor_event(scope: &mut v8::PinScope, actor_scope: &str) {
1608 // The one exit from a block that runs no JS, so the `finally` in
1609 // harness.js never releases. Leave it and the cell refuses everything
1610 // from here on.
1611 cell_gate_abandon(actor_scope);
1612 let global = scope.get_current_context().global(scope);
1613 let key = v8::String::new(scope, "__endTerminatedActorEvent").unwrap();
1614 let Some(value) = global.get(scope, key.into()) else {
1615 return;
1616 };
1617 let Ok(function) = v8::Local::<v8::Function>::try_from(value) else {
1618 return;
1619 };
1620 let actor_scope = v8::String::new(scope, actor_scope).unwrap();
1621 let recv = v8::undefined(scope).into();
1622 let _ = function.call(scope, recv, &[actor_scope.into()]);
1623}
1624
1625/// Compile and run a JS expression that evaluates to a function.
1626fn compile_fn<'s>(
1627 scope: &mut v8::PinScope<'s, '_>,
1628 src: &str,
1629) -> Result<v8::Local<'s, v8::Function>> {
1630 let code = v8::String::new(scope, src).unwrap();
1631 let script =
1632 v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compile shim: {src}"))?;
1633 let value = script
1634 .run(scope)
1635 .ok_or_else(|| anyhow!("run shim: {src}"))?;
1636 value
1637 .try_into()
1638 .map_err(|_| anyhow!("shim is not a function: {src}"))
1639}
1640
1641/// Whether `register_entrypoints` put `name` in the `__cell.<registry>`
1642/// object (e.g. `entrypoints`, `doExports`).
1643fn cell_registry_has(scope: &mut v8::PinScope, registry: &str, name: &str) -> Result<bool> {
1644 let context = scope.get_current_context();
1645 let global = context.global(scope);
1646 let cell_key = v8::String::new(scope, "__cell").unwrap();
1647 let registry_key = v8::String::new(scope, registry).unwrap();
1648 let registry_obj = global
1649 .get(scope, cell_key.into())
1650 .and_then(|value| value.to_object(scope))
1651 .and_then(|cell| cell.get(scope, registry_key.into()))
1652 .and_then(|value| value.to_object(scope))
1653 .ok_or_else(|| anyhow!("missing __cell.{registry} registry"))?;
1654 let name_key = v8::String::new(scope, name).unwrap();
1655 Ok(registry_obj
1656 .has_own_property(scope, name_key.into())
1657 .unwrap_or(false))
1658}
1659
1660fn take_execution_termination(scope: &mut v8::PinScope) -> Option<anyhow::Error> {
1661 let state = scope.get_slot::<Arc<ActorRuntimeState>>().cloned();
1662 let termination = state.and_then(|state| state.termination.lock().ok()?.take());
1663 let is_terminating = scope.is_execution_terminating();
1664 if termination.is_some() || is_terminating {
1665 scope.cancel_terminate_execution();
1666 }
1667 if let Some(termination) = termination {
1668 if let Some(actor_scope) = termination.actor_scope {
1669 finish_terminated_actor_event(scope, &actor_scope);
1670 }
1671 return Some(anyhow!(termination.error));
1672 }
1673 is_terminating.then(|| anyhow!("JavaScript execution was terminated"))
1674}
1675
1676extern "C" fn near_heap_limit(
1677 data: *mut std::ffi::c_void,
1678 current_heap_limit: usize,
1679 _initial_heap_limit: usize,
1680) -> usize {
1681 // SAFETY: `data` points into the Arc stored in the isolate slot. Worker::drop
1682 // removes this callback before the isolate (and its slots) are destroyed.
1683 let state = unsafe { &*(data as *const HeapLimitState) };
1684 state.excessively_exceeded.store(true, Ordering::Relaxed);
1685 // V8 fatally aborts the process if a near-limit callback does not extend
1686 // the limit. This reserve lets JS observe condemnation and unwind.
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))
1698}
1699
1700/// Live heap use, as a share of `limit`.
1701fn 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
1708fn v8_heap_limit_bytes() -> usize {
1709 crate::env_vars::positive::<usize>("CELLD_V8_HEAP_LIMIT_MB")
1710 .expect("validated CELLD_V8_HEAP_LIMIT_MB")
1711 .map(|megabytes| {
1712 megabytes
1713 .checked_mul(1024 * 1024)
1714 .expect("validated CELLD_V8_HEAP_LIMIT_MB range")
1715 })
1716 .unwrap_or(DEFAULT_V8_HEAP_LIMIT_BYTES)
1717}
1718
1719impl Drop for WorkerIsolate {
1720 fn drop(&mut self) {
1721 let limit = self.original_heap_limit;
1722 let (mut locker, _cells) = self.lock();
1723 locker.remove_near_heap_limit_callback(near_heap_limit, limit);
1724 }
1725}
1726
1727/// One in-flight request inside a shared isolate.
1728///
1729/// Owned by the request's own tokio task, which is why every field is
1730/// `Send`: the task suspends between turns and can resume on any worker,
1731/// then re-enters the isolate it is affiliated with.
1732/// Where a finished handler's result goes, and in what shape.
1733///
1734/// A fetch answers an `HttpResponse` and an entrypoint RPC answers bytes.
1735/// Everything between — the turn loop, the op region, cancellation, the
1736/// budget — is identical, so the difference lives here rather than in two
1737/// copies of `drive`.
1738pub enum Answer {
1739 Fetch(tokio::sync::oneshot::Sender<Result<HttpResponse>>),
1740 Rpc(tokio::sync::oneshot::Sender<Result<Vec<u8>>>),
1741 /// A DO method call, which answers a value rather than a response.
1742 CellRpc(tokio::sync::oneshot::Sender<Result<RpcOutcome>>),
1743 /// A `webSocketMessage`, which answers the frames the output gate held
1744 /// and the write they are gated on.
1745 WsMessage(tokio::sync::oneshot::Sender<Result<WsDispatch>>),
1746 /// An event whose result is that it finished: `webSocketOpen`,
1747 /// `webSocketClose`.
1748 Ack(tokio::sync::oneshot::Sender<Result<()>>),
1749 /// An alarm, which answers whatever alarm the handler left armed.
1750 Alarm(tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>),
1751}
1752
1753impl Answer {
1754 /// Send an error, whichever shape the caller is waiting for.
1755 fn fail(self, error: anyhow::Error) {
1756 match self {
1757 Answer::Fetch(reply) => drop(reply.send(Err(error))),
1758 Answer::Rpc(reply) => drop(reply.send(Err(error))),
1759 Answer::CellRpc(reply) => drop(reply.send(Err(error))),
1760 Answer::WsMessage(reply) => drop(reply.send(Err(error))),
1761 Answer::Ack(reply) => drop(reply.send(Err(error))),
1762 Answer::Alarm(reply) => drop(reply.send(Err(error))),
1763 }
1764 }
1765}
1766
1767pub struct InFlight {
1768 /// The handler's promise. A `Global` because it outlives the turn that
1769 /// created it: Locals never cross a turn, exactly as workerd's
1770 /// `Worker::Lock` never does.
1771 promise: v8::Global<v8::Promise>,
1772 context: Arc<IoContext>,
1773 /// The cell this event belongs to, and `None` for stateless work.
1774 ///
1775 /// It is what the storage-shaped parts of settling — the durability
1776 /// position, a fatal SQL error — are read against.
1777 scope: Option<String>,
1778 /// The cell's committed-write position before the handler ran.
1779 ///
1780 /// The answer carries a write position only if the handler advanced it,
1781 /// so the output gate sees a write this event made and ignores celld's
1782 /// own activation writes (the actor name, alarm bookkeeping).
1783 writes_before: Option<u64>,
1784 request_id: Option<RequestId>,
1785 active_request_id: Option<RequestId>,
1786 reply: Option<Answer>,
1787 /// `waitUntil` work still running after the response was sent. The
1788 /// request stays in flight until it settles, as the single-request loop
1789 /// keeps driving it.
1790 background: Option<v8::Global<v8::Promise>>,
1791 /// Ops this request is waiting on, so a completion can be attributed to
1792 /// the request whose context must be current while its continuation runs.
1793 ops: std::collections::HashSet<u64>,
1794 /// The alarm bookkeeping this entry still owes, if it is one.
1795 alarm: Option<AlarmClaim>,
1796 started: Instant,
1797 /// The sampled trace this entry records into, `None` when telemetry
1798 /// is off or the trace was not sampled. Installed into the isolate's
1799 /// CPED slot for every turn, so promise continuations carry it.
1800 trace: Option<crate::telemetry::TraceIds>,
1801 /// Why a handler that did not finish failed, captured for the span's
1802 /// `error` so a query sees the reason, not only that it failed. Set
1803 /// only when a trace is sampled.
1804 failure: Option<String>,
1805 /// The isolate this entry's ops belong to, so `abandon` can drop their
1806 /// resolvers without a scope to reach the isolate through.
1807 runtime_state: Arc<ActorRuntimeState>,
1808}
1809
1810impl InFlight {
1811 /// Read the handler's settled value in the shape this entry answers, end
1812 /// the event, and reply.
1813 ///
1814 /// Every shape ends the event exactly once, whether it produced a value
1815 /// or an error — ending it is what yields the `waitUntil` work the entry
1816 /// keeps driving afterwards, and a shape that skipped it on the error
1817 /// path would leave the context open.
1818 fn answer_settled<'s>(
1819 &mut self,
1820 tc: &mut v8::PinScope<'s, '_>,
1821 value: v8::Local<'s, v8::Value>,
1822 ) {
1823 let Some(reply) = self.reply.take() else {
1824 return;
1825 };
1826 // A cell whose SQL failed fatally cannot answer whatever the handler
1827 // returned: the storage the handler read may not be what the cell
1828 // has.
1829 if let Some(error) = self.scope.as_deref().and_then(storage::sql_critical_error) {
1830 let _ = end_event_context(tc);
1831 if self.trace.is_some() {
1832 self.failure = Some(crate::telemetry::cap_error(error.to_string()));
1833 }
1834 reply.fail(anyhow!(error));
1835 return;
1836 }
1837 self.background = match reply {
1838 Answer::Fetch(reply) => {
1839 let read = read_response(tc, value).map(|mut response| {
1840 response.write_position = self.write_delta();
1841 response
1842 });
1843 send_and_end(tc, reply, read)
1844 }
1845 Answer::Rpc(reply) => {
1846 let read =
1847 view_bytes(value).ok_or_else(|| anyhow!("entrypoint RPC answered non-bytes"));
1848 send_and_end(tc, reply, read)
1849 }
1850 Answer::CellRpc(reply) => {
1851 let outcome = RpcOutcome {
1852 data: rpc_data_ret(tc, value),
1853 write_position: self.write_delta(),
1854 };
1855 send_and_end(tc, reply, Ok(outcome))
1856 }
1857 Answer::WsMessage(reply) => {
1858 let dispatch = WsDispatch {
1859 frames: ws_capture_take(),
1860 write_position: self.write_delta(),
1861 };
1862 send_and_end(tc, reply, Ok(dispatch))
1863 }
1864 Answer::Ack(reply) => send_and_end(tc, reply, Ok(())),
1865 Answer::Alarm(reply) => {
1866 // The handler ran and returned, so close the claim as a
1867 // success. This is the only path that does: every other
1868 // `settle_alarm` call site records a failure, and without
1869 // this one a *successful* alarm was recorded as one to
1870 // retry — which re-armed it forever, kept the cell busy,
1871 // and meant an eviction waiting for the cell to go quiet
1872 // never got its turn.
1873 self.settle_alarm(true, false);
1874 // Read what stands *after* that cleanup, and take the delta
1875 // last so it covers the cleanup's own commit — which is the
1876 // write the core must prove durable before it settles the
1877 // alarm.
1878 let alarm = self
1879 .scope
1880 .as_deref()
1881 .map(storage::get_alarm)
1882 .unwrap_or(None);
1883 send_and_end(tc, reply, Ok((alarm, self.write_delta())))
1884 }
1885 };
1886 }
1887
1888 /// The write position to gate this answer on: `None` unless the handler
1889 /// advanced the cell's committed writes past where they were.
1890 fn write_delta(&self) -> Option<u64> {
1891 write_delta(
1892 self.writes_before,
1893 self.scope.as_deref().and_then(storage::write_position),
1894 )
1895 }
1896
1897 /// Fail whichever shape is waiting, without knowing which.
1898 ///
1899 /// An alarm that fails here failed for a reason that is not the
1900 /// handler's — a budget overrun, a disconnect — so it does not count
1901 /// against the retry limit. A handler that threw is recorded by
1902 /// `settle`, which knows that it did, before it reaches this.
1903 fn fail(&mut self, error: anyhow::Error) {
1904 if let Some(reply) = self.reply.take() {
1905 self.settle_alarm(false, false);
1906 if self.trace.is_some() {
1907 self.failure = Some(crate::telemetry::cap_error(error.to_string()));
1908 }
1909 reply.fail(error);
1910 }
1911 }
1912
1913 /// Record how a claimed alarm ended. Runs once; later calls do nothing.
1914 fn settle_alarm(&mut self, ok: bool, counts_against_limit: bool) {
1915 let (Some(scope), Some(claim)) = (self.scope.as_deref(), self.alarm.take()) else {
1916 return;
1917 };
1918 if ok {
1919 storage::finish_alarm_handler(scope, true, claim.now_ms);
1920 } else {
1921 storage::finish_alarm_handler_with_retry_policy(
1922 scope,
1923 false,
1924 claim.now_ms,
1925 counts_against_limit,
1926 );
1927 }
1928 }
1929
1930 /// Whether a claimed alarm's outcome is still unrecorded. True only
1931 /// where the event ended without ever entering the isolate again.
1932 pub fn owes_alarm(&self) -> bool {
1933 self.alarm.is_some()
1934 }
1935
1936 /// Done when the response has been sent and nothing is left running.
1937 pub fn finished(&self) -> bool {
1938 self.reply.is_none() && self.background.is_none() && self.ops.is_empty()
1939 }
1940
1941 /// Why the handler failed, when a sampled trace captured it.
1942 pub fn failure(&self) -> Option<&str> {
1943 self.failure.as_deref()
1944 }
1945
1946 /// How long this handler may still run, or `None` once it has answered.
1947 ///
1948 /// The budget bounds the *response*, not the request: `waitUntil` work
1949 /// continues after the client has been served and is not charged for the
1950 /// time the handler already spent.
1951 pub fn remaining(&self, budget: Duration) -> Option<Duration> {
1952 self.reply
1953 .is_some()
1954 .then(|| budget.saturating_sub(self.started.elapsed()))
1955 }
1956
1957 /// Give up on a handler that will not settle.
1958 pub fn time_out(&mut self, budget: Duration) {
1959 self.fail(anyhow!("handler exceeded {}s budget", budget.as_secs()));
1960 }
1961
1962 /// Nothing this request awaits can move it, so it will never settle on
1963 /// its own. Reachable when a handler awaits a promise only some *other*
1964 /// request could resolve — which the pump concealed, because it settled
1965 /// every entry on every turn whoever the turn belonged to.
1966 pub fn stuck(&mut self) {
1967 self.fail(anyhow!("handler is waiting on nothing"));
1968 self.background = None;
1969 }
1970
1971 /// Has the client been answered? `waitUntil` work can still be running.
1972 pub fn answered(&self) -> bool {
1973 self.reply.is_none()
1974 }
1975
1976 /// Whether a client can still disconnect from this request. A request
1977 /// with no id is internal and has no client to hang up.
1978 pub fn cancellable(&self) -> bool {
1979 self.reply.is_some() && self.request_id.is_some()
1980 }
1981
1982 pub fn request_id(&self) -> Option<RequestId> {
1983 self.request_id
1984 }
1985
1986 /// The request is over and its remaining ops are being dropped. Purge
1987 /// their resolvers.
1988 ///
1989 /// An op that never completes would otherwise leave its
1990 /// `Global<PromiseResolver>` in the isolate's map for as long as the
1991 /// isolate lives. A request that drives itself has to purge them on its
1992 /// own way out.
1993 pub fn abandon(&mut self) {
1994 if self.ops.is_empty() {
1995 return;
1996 }
1997 let mut promises = self.runtime_state.promises.lock().unwrap();
1998 for id in self.ops.drain() {
1999 promises.remove(&id);
2000 }
2001 }
2002}
2003
2004/// The CPED slot carries two riders in one immutable record: the
2005/// harness's async-context frame (`__als_get`/`__als_set` — ALS and
2006/// request-context confinement) and telemetry's trace context. Each
2007/// write builds a fresh two-element array preserving the other rider,
2008/// so V8's per-reaction snapshots restore both atomically and neither
2009/// feature can stomp the other — the collision the trace-join test
2010/// caught when telemetry first took the whole slot.
2011///
2012/// The empty state stays *empty*: when both riders are absent the slot
2013/// is undefined, which V8 fast-paths, and "off is structural" holds.
2014fn cped_parts<'s>(
2015 scope: &mut v8::PinScope<'s, '_>,
2016) -> (v8::Local<'s, v8::Value>, v8::Local<'s, v8::Value>) {
2017 let data = scope.get_continuation_preserved_embedder_data();
2018 if let Ok(record) = v8::Local::<v8::Array>::try_from(data) {
2019 if record.length() == 2 {
2020 let undefined = v8::undefined(scope).into();
2021 return (
2022 record.get_index(scope, 0).unwrap_or(undefined),
2023 record.get_index(scope, 1).unwrap_or(undefined),
2024 );
2025 }
2026 }
2027 // Any non-record value is a bare frame from before this scheme, or
2028 // the empty slot.
2029 (data, v8::undefined(scope).into())
2030}
2031
2032fn cped_frame<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
2033 cped_parts(scope).0
2034}
2035
2036fn cped_trace<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
2037 cped_parts(scope).1
2038}
2039
2040fn set_cped(scope: &mut v8::PinScope, frame: v8::Local<v8::Value>, trace: v8::Local<v8::Value>) {
2041 if frame.is_undefined() && trace.is_undefined() {
2042 let undefined = v8::undefined(scope).into();
2043 scope.set_continuation_preserved_embedder_data(undefined);
2044 return;
2045 }
2046 let record = v8::Array::new(scope, 2);
2047 record.set_index(scope, 0, frame);
2048 record.set_index(scope, 1, trace);
2049 scope.set_continuation_preserved_embedder_data(record.into());
2050}
2051
2052/// Install a trace context into the isolate's CPED slot for one turn.
2053///
2054/// V8 snapshots continuation-preserved embedder data when a promise
2055/// reaction is registered and restores it while the reaction runs. That
2056/// is the exactness `console.log` correlation needs: a continuation
2057/// belonging to a *different* entry that runs during this turn's
2058/// microtask checkpoint carries its own context, not this turn's. The
2059/// layout is 16 trace-id bytes then 8 span-id bytes in one 24-byte
2060/// ArrayBuffer, fresh per turn — cheap at sampled rates, and nothing
2061/// outlives V8's own snapshots.
2062///
2063/// Returns the previous slot value *only when something was installed*;
2064/// the caller restores it before releasing the isolate. An untraced
2065/// turn touches CPED not at all — every traced turn restores what it
2066/// found, so the ambient slot between turns is always empty, and "off
2067/// is structural" stays true at the V8 boundary too (the -13% the
2068/// always-read version cost at 1% sampling was measured, not guessed).
2069fn install_trace<'s>(
2070 scope: &mut v8::PinScope<'s, '_>,
2071 trace: Option<&crate::telemetry::TraceIds>,
2072) -> Option<v8::Local<'s, v8::Value>> {
2073 let ids = trace?;
2074 let previous = scope.get_continuation_preserved_embedder_data();
2075 let buffer = v8::ArrayBuffer::new(scope, 24);
2076 let data = buffer.get_backing_store().data()?;
2077 let bytes = data.as_ptr() as *mut u8;
2078 // SAFETY: a freshly created 24-byte buffer, written before any JS
2079 // can see it.
2080 unsafe {
2081 std::ptr::copy_nonoverlapping(ids.trace_id.as_ptr(), bytes, 16);
2082 std::ptr::copy_nonoverlapping(ids.span_id.as_ptr(), bytes.add(16), 8);
2083 }
2084 let frame = cped_frame(scope);
2085 set_cped(scope, frame, buffer.into());
2086 Some(previous)
2087}
2088
2089fn restore_trace(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) {
2090 if let Some(previous) = previous {
2091 scope.set_continuation_preserved_embedder_data(previous);
2092 }
2093}
2094
2095/// The trace context current at this exact point of JS execution, read
2096/// from CPED — the running turn's, or the running continuation's if V8
2097/// restored one. `None` when telemetry is off, the trace was unsampled,
2098/// or execution is outside any entry.
2099pub(crate) fn current_trace_ids(scope: &mut v8::PinScope) -> Option<crate::telemetry::TraceIds> {
2100 if !crate::telemetry::active() {
2101 return None;
2102 }
2103 let data = cped_trace(scope);
2104 let buffer = v8::Local::<v8::ArrayBuffer>::try_from(data).ok()?;
2105 if buffer.byte_length() != 24 {
2106 return None;
2107 }
2108 let data = buffer.get_backing_store().data()?;
2109 let bytes = data.as_ptr() as *const u8;
2110 let mut trace_id = [0u8; 16];
2111 let mut span_id = [0u8; 8];
2112 // SAFETY: length checked; the buffer is alive for this scope.
2113 unsafe {
2114 std::ptr::copy_nonoverlapping(bytes, trace_id.as_mut_ptr(), 16);
2115 std::ptr::copy_nonoverlapping(bytes.add(16), span_id.as_mut_ptr(), 8);
2116 }
2117 Some(crate::telemetry::TraceIds { trace_id, span_id })
2118}
2119
2120/// The isolate, entered for one turn. Everything a request does to a shared
2121/// isolate goes through one of these, and none of them may be held across an
2122/// await: the caller takes the pool's async permit first, runs a turn, and
2123/// leaves.
2124impl Worker {
2125 /// Run a request's first turn.
2126 ///
2127 /// Returns what is now in flight — `None` when nothing is, the reply
2128 /// already carrying the error — and the ops the handler enqueued, which
2129 /// the caller awaits with no isolate held.
2130 pub fn turn_begin(
2131 &mut self,
2132 job: crate::WorkerJob,
2133 trace: Option<crate::telemetry::TraceIds>,
2134 ) -> (Option<InFlight>, Vec<Op>) {
2135 let Some(inner) = self.inner.as_mut() else {
2136 return (None, Vec::new());
2137 };
2138 let (mut locker, _cells) = inner.lock();
2139 inner.recover_heap(&mut locker);
2140 v8::scope!(let hs, &mut *locker);
2141 let realm = inner.realm(hs);
2142 let context = realm.context;
2143 let cs = &mut v8::ContextScope::new(hs, context);
2144 let tc = std::pin::pin!(v8::TryCatch::new(cs));
2145 let tc = &mut tc.init();
2146
2147 let previous = install_trace(tc, trace.as_ref());
2148 let out = match begin(tc, realm.fetch, job) {
2149 Begun::Running(mut entry) => {
2150 entry.trace = trace;
2151 // A handler that returned an already-resolved promise is
2152 // finished before it ever suspends, and must not wait for an
2153 // op it will never start.
2154 let ops = finish_turn(tc, &mut entry);
2155 (Some(*entry), ops)
2156 }
2157 Begun::Threw(answer) => {
2158 answer.fail(anyhow!("fetch threw: {}", exc!(tc)));
2159 (None, Vec::new())
2160 }
2161 Begun::Nothing => (None, Vec::new()),
2162 };
2163 restore_trace(tc, previous);
2164 out
2165 }
2166
2167 /// Enter the isolate solely to end a request whose client has hung up.
2168 ///
2169 /// A suspended request notices the disconnect without any isolate — the
2170 /// flag is host state — so this is reached only when it has actually
2171 /// fired, rather than on a timer as the blocking run loop did.
2172 pub fn turn_cancel(&mut self, entry: &mut InFlight) -> Vec<Op> {
2173 let Some(inner) = self.inner.as_mut() else {
2174 return Vec::new();
2175 };
2176 let (mut locker, _cells) = inner.lock();
2177 v8::scope!(let hs, &mut *locker);
2178 let realm = inner.realm(hs);
2179 let context = realm.context;
2180 let cs = &mut v8::ContextScope::new(hs, context);
2181 let tc = std::pin::pin!(v8::TryCatch::new(cs));
2182 let tc = &mut tc.init();
2183
2184 let previous = install_trace(tc, entry.trace.as_ref());
2185 cancel(tc, entry);
2186 let ops = finish_turn(tc, entry);
2187 restore_trace(tc, previous);
2188 ops
2189 }
2190
2191 /// Run a later turn: resolve one of this request's ops, drain the
2192 /// microtasks that follow, and answer if the handler settled.
2193 pub fn turn_deliver(
2194 &mut self,
2195 entry: &mut InFlight,
2196 op: u64,
2197 res: Result<asyncrt::OpOut, String>,
2198 ) -> Vec<Op> {
2199 let Some(inner) = self.inner.as_mut() else {
2200 return Vec::new();
2201 };
2202 let (mut locker, _cells) = inner.lock();
2203 v8::scope!(let hs, &mut *locker);
2204 let realm = inner.realm(hs);
2205 let context = realm.context;
2206 let cs = &mut v8::ContextScope::new(hs, context);
2207 let tc = std::pin::pin!(v8::TryCatch::new(cs));
2208 let tc = &mut tc.init();
2209
2210 let previous = install_trace(tc, entry.trace.as_ref());
2211 deliver(tc, entry, op, res);
2212 cancelled(tc, entry);
2213 let ops = finish_turn(tc, entry);
2214 restore_trace(tc, previous);
2215 ops
2216 }
2217}
2218
2219/// Close a turn, whatever the turn did.
2220///
2221/// Every step earns its place and the order is the whole point:
2222///
2223/// 1. **settle** — the handler's promise may have resolved, so marshal the
2224/// response and answer. Marshalling can start a JS-to-host body pump and
2225/// register it with `waitUntil`.
2226/// 2. **checkpoint** — that pump's native ops exist only once the microtasks
2227/// which create them run.
2228/// 3. **settle again** — the checkpoint may itself have settled the promise,
2229/// or the `waitUntil` aggregate.
2230/// 4. **adopt** — only now is the set of ops this request waits on complete.
2231///
2232/// Draining before step 2 is the bug that made a streaming handler answer
2233/// with nothing outstanding and conclude it was waiting on nothing.
2234/// The checkpoint before adoption is what makes response-body pumps visible.
2235fn finish_turn(tc: &mut v8::PinScope, entry: &mut InFlight) -> Vec<Op> {
2236 settle(tc, entry);
2237 tc.perform_microtask_checkpoint();
2238 // `abort()` and `process.exit()` terminate execution without settling
2239 // the handler's promise, so an entry that only watched the promise would
2240 // wait on it forever and then report that it was waiting on nothing.
2241 // The blocking loop broke out of its loop here; an entry fails here.
2242 if let Some(error) = take_execution_termination(tc) {
2243 entry.fail(error);
2244 entry.background = None;
2245 entry.abandon();
2246 return Vec::new();
2247 }
2248 settle(tc, entry);
2249 adopt(entry)
2250}
2251
2252/// An op the JS enqueued, and the id whose promise it resolves.
2253pub type Op = (u64, asyncrt::OpFuture);
2254
2255/// Take the ops this turn enqueued, recording them as the request's own.
2256///
2257/// Drained after `settle`, not before: ending an event runs JS, and anything
2258/// that starts there belongs to this request too. The pump drained first and
2259/// so could attribute those to whichever entry it settled next.
2260fn adopt(entry: &mut InFlight) -> Vec<Op> {
2261 let spawns = asyncrt::drain_spawns();
2262 for (id, _) in &spawns {
2263 entry.ops.insert(*id);
2264 }
2265 spawns
2266}
2267
2268/// What starting a request produced.
2269enum Begun {
2270 /// In flight. Its ops must be adopted and its promise driven.
2271 Running(Box<InFlight>),
2272 /// The handler threw before it could suspend, so nothing is in flight.
2273 /// The exception belongs to the caller's `TryCatch` — an unnameable type
2274 /// no signature here can take — so the caller reads it and answers.
2275 Threw(Answer),
2276 /// Nothing started: the job was not a fetch, or the reply already
2277 /// carries the error.
2278 Nothing,
2279}
2280
2281/// Start a request: build it, call the Worker's `fetch`, and hand back what
2282/// is now in flight.
2283///
2284/// The half of a turn that runs *before* anything can suspend.
2285fn begin<'s>(
2286 tc: &mut v8::PinScope<'s, '_>,
2287 fetch: v8::Local<'s, v8::Function>,
2288 job: crate::WorkerJob,
2289) -> Begun {
2290 let job = match job {
2291 crate::WorkerJob::Rpc {
2292 entrypoint,
2293 method,
2294 args,
2295 reply,
2296 } => return begin_entrypoint_rpc(tc, &entrypoint, &method, args, reply),
2297 job => job,
2298 };
2299 let crate::WorkerJob::Fetch {
2300 url,
2301 method,
2302 body,
2303 headers,
2304 request_id,
2305 reply,
2306 ..
2307 } = job
2308 else {
2309 return Begun::Nothing;
2310 };
2311
2312 let context = IoContext::new();
2313 let guard = CurrentGuard::enter(context.clone());
2314 let started = start_fetch(tc, fetch, &url, &method, &body, &headers, request_id);
2315 let promise = match started {
2316 Ok(Started::Running(ret, active)) => match ret.try_cast::<v8::Promise>() {
2317 Ok(promise) => Ok((promise, active)),
2318 Err(_) => resolved_promise(tc, ret).map(|promise| (promise, active)),
2319 },
2320 Ok(Started::Threw) => {
2321 drop(guard);
2322 return Begun::Threw(Answer::Fetch(reply));
2323 }
2324 Err(error) => Err(error),
2325 };
2326 match promise {
2327 Ok((promise, active_request_id)) => {
2328 tc.perform_microtask_checkpoint();
2329 let entry = InFlight {
2330 runtime_state: actor_runtime_state(tc),
2331 promise: v8::Global::new(tc, promise),
2332 context,
2333 scope: None,
2334 writes_before: None,
2335 request_id,
2336 active_request_id,
2337 reply: Some(Answer::Fetch(reply)),
2338 background: None,
2339 ops: std::collections::HashSet::new(),
2340 alarm: None,
2341 started: Instant::now(),
2342 trace: None,
2343 failure: None,
2344 };
2345 drop(guard);
2346 Begun::Running(Box::new(entry))
2347 }
2348 Err(error) => {
2349 drop(guard);
2350 let _ = reply.send(Err(error));
2351 Begun::Nothing
2352 }
2353 }
2354}
2355
2356/// Start an entrypoint RPC's first turn.
2357///
2358/// The same shape as a fetch and deliberately so: call the handler, keep the
2359/// promise, and let `drive` pump it with no isolate held across the awaits.
2360/// The old dispatcher blocked until the promise settled, which is why RPC
2361/// needed a thread of its own and why `WorkerPool` outlived the fetch path.
2362fn begin_entrypoint_rpc(
2363 tc: &mut v8::PinScope,
2364 entrypoint: &str,
2365 method: &str,
2366 args: Vec<u8>,
2367 reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
2368) -> Begun {
2369 let context = IoContext::new();
2370 let guard = CurrentGuard::enter(context.clone());
2371 let global = tc.get_current_context().global(tc);
2372 let started = (|| {
2373 let key = v8::String::new(tc, "__dispatchEntrypointRpc").unwrap();
2374 let f: v8::Local<v8::Function> = global
2375 .get(tc, key.into())
2376 .ok_or_else(|| anyhow!("no __dispatchEntrypointRpc"))?
2377 .try_into()
2378 .map_err(|_| anyhow!("__dispatchEntrypointRpc is not a function"))?;
2379 let entrypoint = v8::String::new(tc, entrypoint).unwrap();
2380 let method = v8::String::new(tc, method).unwrap();
2381 let args = bytes_value(tc, args);
2382 let recv = v8::undefined(tc).into();
2383 begin_event_context(tc)?;
2384 let ret = f
2385 .call(tc, recv, &[entrypoint.into(), method.into(), args])
2386 .ok_or_else(|| anyhow!("entrypoint RPC threw"))?;
2387 match ret.try_cast::<v8::Promise>() {
2388 Ok(promise) => Ok(promise),
2389 Err(_) => resolved_promise(tc, ret),
2390 }
2391 })();
2392 match started {
2393 Ok(promise) => {
2394 tc.perform_microtask_checkpoint();
2395 let entry = InFlight {
2396 runtime_state: actor_runtime_state(tc),
2397 promise: v8::Global::new(tc, promise),
2398 context,
2399 scope: None,
2400 writes_before: None,
2401 request_id: None,
2402 active_request_id: None,
2403 reply: Some(Answer::Rpc(reply)),
2404 background: None,
2405 ops: std::collections::HashSet::new(),
2406 alarm: None,
2407 started: Instant::now(),
2408 trace: None,
2409 failure: None,
2410 };
2411 drop(guard);
2412 Begun::Running(Box::new(entry))
2413 }
2414 Err(error) => {
2415 let _ = end_event_context(tc);
2416 drop(guard);
2417 let _ = reply.send(Err(error));
2418 Begun::Nothing
2419 }
2420 }
2421}
2422
2423/// for the JSON flavor, a `Uint8Array` for structured clone.
2424fn rpc_data_value<'s>(scope: &mut v8::PinScope<'s, '_>, data: RpcData) -> v8::Local<'s, v8::Value> {
2425 match data {
2426 RpcData::Json(json) => v8::String::new(scope, &json).unwrap().into(),
2427 RpcData::V8(bytes) => bytes_value(scope, bytes),
2428 }
2429}
2430
2431/// The inverse: `__dispatchRpc` answers in the flavor it was asked in.
2432fn rpc_data_ret(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> RpcData {
2433 match view_bytes(ret) {
2434 Some(bytes) => RpcData::V8(bytes),
2435 None => RpcData::Json(ret.to_rust_string_lossy(scope)),
2436 }
2437}
2438
2439fn unix_now_ms() -> i64 {
2440 std::time::SystemTime::now()
2441 .duration_since(std::time::UNIX_EPOCH)
2442 .unwrap_or_default()
2443 .as_millis()
2444 .min(i64::MAX as u128) as i64
2445}
2446
2447/// End the event, then answer with what the handler produced.
2448///
2449/// Ending it is what yields the `waitUntil` aggregate the entry keeps
2450/// driving after the caller has been served, so it happens for every answer
2451/// shape and on the error path too.
2452fn send_and_end<T>(
2453 tc: &mut v8::PinScope,
2454 reply: tokio::sync::oneshot::Sender<Result<T>>,
2455 value: Result<T>,
2456) -> Option<v8::Global<v8::Promise>> {
2457 let background = end_event_context(tc).ok().flatten();
2458 let _ = reply.send(value);
2459 background.map(|promise| v8::Global::new(tc, promise))
2460}
2461
2462/// A committed-write position only counts when the handler advanced it; celld's
2463/// own activation writes are already below `before`.
2464pub(crate) fn write_delta(before: Option<u64>, after: Option<u64>) -> Option<u64> {
2465 match (before, after) {
2466 (Some(before), Some(after)) if after > before => Some(after),
2467 _ => None,
2468 }
2469}
2470
2471/// What a Durable Object RPC method returned, plus the position its writes
2472/// reached, so the caller can hold the reply behind durability.
2473pub struct RpcOutcome {
2474 pub data: RpcData,
2475 pub write_position: Option<u64>,
2476}
2477
2478/// What a claimed alarm still owes its bookkeeping.
2479///
2480/// `finish_alarm_handler` must run exactly once however the event ends, and
2481/// an event can now end without running JS at all — a budget overrun, a
2482/// handler waiting on nothing — so the entry carries the claim rather than
2483/// the caller that made it.
2484struct AlarmClaim {
2485 /// The instant the dispatch was judged due against, so the outcome is
2486 /// recorded against the same one.
2487 now_ms: i64,
2488}
2489
2490/// Start one cell event: the half that runs before the handler can suspend.
2491///
2492/// Every cell event does the same four things — name the cell it belongs to,
2493/// sample the writes its answer will be gated on, open an event context, and
2494/// keep the promise the dispatcher returned. Only the call and the shape of
2495/// the answer differ, which is what the arguments say.
2496fn start_cell_event<'s>(
2497 tc: &mut v8::PinScope<'s, '_>,
2498 scope: &str,
2499 answer: Answer,
2500 request_id: Option<RequestId>,
2501 capture_frames: bool,
2502 call: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>>,
2503) -> Begun {
2504 let context = IoContext::new();
2505 let guard = CurrentGuard::enter(context.clone());
2506 // Sampled before the handler runs so the output gate can tell a write
2507 // this event made from celld's own activation writes.
2508 let writes_before = storage::write_position(scope);
2509 // No guard: this frame is the context's outermost one and the context
2510 // ends with the event, so there is nothing to pop it before.
2511 context
2512 .egress
2513 .lock()
2514 .unwrap()
2515 .push((scope.to_string(), writes_before.unwrap_or(0)));
2516 if capture_frames {
2517 ws_capture_begin();
2518 }
2519 let started = (|| {
2520 begin_event_context(tc)?;
2521 let ret = call(tc)?;
2522 match ret.try_cast::<v8::Promise>() {
2523 Ok(promise) => Ok(promise),
2524 Err(_) => resolved_promise(tc, ret),
2525 }
2526 })();
2527 match started {
2528 Ok(promise) => {
2529 tc.perform_microtask_checkpoint();
2530 let entry = InFlight {
2531 runtime_state: actor_runtime_state(tc),
2532 promise: v8::Global::new(tc, promise),
2533 context,
2534 scope: Some(scope.to_string()),
2535 writes_before,
2536 request_id,
2537 // A cell's dispatcher registers the incoming request itself,
2538 // so there is nothing for the shell to finish; `cancel`
2539 // aborts by the job's own id.
2540 active_request_id: None,
2541 reply: Some(answer),
2542 background: None,
2543 ops: std::collections::HashSet::new(),
2544 alarm: None,
2545 started: Instant::now(),
2546 trace: None,
2547 failure: None,
2548 };
2549 drop(guard);
2550 Begun::Running(Box::new(entry))
2551 }
2552 Err(error) => {
2553 let _ = end_event_context(tc);
2554 drop(guard);
2555 answer.fail(error);
2556 Begun::Nothing
2557 }
2558 }
2559}
2560
2561/// Look one of the harness dispatchers up on the current realm's global.
2562fn dispatcher<'s>(
2563 tc: &mut v8::PinScope<'s, '_>,
2564 name: &str,
2565) -> Result<v8::Local<'s, v8::Function>> {
2566 let global = tc.get_current_context().global(tc);
2567 let key = v8::String::new(tc, name).unwrap();
2568 global
2569 .get(tc, key.into())
2570 .ok_or_else(|| anyhow!("no {name}"))?
2571 .try_into()
2572 .map_err(|_| anyhow!("{name} is not a function"))
2573}
2574
2575/// Start a cell event's first turn.
2576///
2577/// The counterpart of `begin` for the events a cell receives. Where the
2578/// blocking loop ran each of these to completion inside one call — and
2579/// serviced other cells' events inside *that* — each is now an entry a tokio
2580/// task drives, so two events of one cell interleave by suspending rather
2581/// than by nesting.
2582fn begin_cell(tc: &mut v8::PinScope, job: CellJob) -> Begun {
2583 match job {
2584 CellJob::Fetch {
2585 request_id,
2586 scope,
2587 name,
2588 url,
2589 method,
2590 body,
2591 headers,
2592 reply,
2593 order: _,
2594 } => {
2595 if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) {
2596 let _ = reply.send(Err(error));
2597 return Begun::Nothing;
2598 }
2599 start_cell_event(tc, &scope, Answer::Fetch(reply), request_id, false, |tc| {
2600 let f = dispatcher(tc, "__dispatchTo")?;
2601 let arguments = [
2602 v8::String::new(tc, &scope).unwrap().into(),
2603 v8::String::new(tc, &url).unwrap().into(),
2604 v8::String::new(tc, &method).unwrap().into(),
2605 bytes_value(tc, body),
2606 v8::String::new(tc, &serde_json::to_string(&headers)?)
2607 .unwrap()
2608 .into(),
2609 match request_id {
2610 Some(id) => v8::String::new(tc, &request_id_string(id)).unwrap().into(),
2611 None => v8::null(tc).into(),
2612 },
2613 ];
2614 let recv = v8::undefined(tc).into();
2615 f.call(tc, recv, &arguments)
2616 .ok_or_else(|| anyhow!("dispatchTo threw"))
2617 })
2618 }
2619 CellJob::Rpc {
2620 scope,
2621 name,
2622 method,
2623 args,
2624 reply,
2625 } => {
2626 if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) {
2627 let _ = reply.send(Err(error));
2628 return Begun::Nothing;
2629 }
2630 start_cell_event(tc, &scope, Answer::CellRpc(reply), None, false, |tc| {
2631 let f = dispatcher(tc, "__dispatchRpc")?;
2632 let arguments = [
2633 v8::String::new(tc, &scope).unwrap().into(),
2634 v8::String::new(tc, &method).unwrap().into(),
2635 rpc_data_value(tc, args),
2636 ];
2637 let recv = v8::undefined(tc).into();
2638 f.call(tc, recv, &arguments)
2639 .ok_or_else(|| anyhow!("dispatchRpc threw"))
2640 })
2641 }
2642 CellJob::WsOpen {
2643 scope,
2644 ws_id,
2645 protocol,
2646 reply,
2647 } => start_cell_event(tc, &scope, Answer::Ack(reply), None, false, |tc| {
2648 let f = dispatcher(tc, "__wsOpen")?;
2649 let arguments = [
2650 v8::String::new(tc, &scope).unwrap().into(),
2651 v8::Number::new(tc, ws_id as f64).into(),
2652 v8::String::new(tc, &protocol).unwrap().into(),
2653 ];
2654 let recv = v8::undefined(tc).into();
2655 f.call(tc, recv, &arguments)
2656 .ok_or_else(|| anyhow!("wsOpen threw"))
2657 }),
2658 CellJob::WsMessage {
2659 scope,
2660 ws_id,
2661 data,
2662 reply,
2663 } => start_cell_event(tc, &scope, Answer::WsMessage(reply), None, true, |tc| {
2664 let (name, data) = match data {
2665 WsIn::Text(text) => ("__wsMessage", v8::String::new(tc, &text).unwrap().into()),
2666 WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)),
2667 };
2668 let f = dispatcher(tc, name)?;
2669 let arguments = [
2670 v8::String::new(tc, &scope).unwrap().into(),
2671 v8::Number::new(tc, ws_id as f64).into(),
2672 data,
2673 ];
2674 let recv = v8::undefined(tc).into();
2675 f.call(tc, recv, &arguments)
2676 .ok_or_else(|| anyhow!("WebSocket message dispatch threw"))
2677 }),
2678 CellJob::WsClosed {
2679 scope,
2680 ws_id,
2681 code,
2682 reason,
2683 was_clean,
2684 reply,
2685 } => start_cell_event(tc, &scope, Answer::Ack(reply), None, false, |tc| {
2686 let f = dispatcher(tc, "__wsClosed")?;
2687 let arguments = [
2688 v8::String::new(tc, &scope).unwrap().into(),
2689 v8::Number::new(tc, ws_id as f64).into(),
2690 v8::Number::new(tc, f64::from(code)).into(),
2691 v8::String::new(tc, &reason).unwrap().into(),
2692 v8::Boolean::new(tc, was_clean).into(),
2693 ];
2694 let recv = v8::undefined(tc).into();
2695 f.call(tc, recv, &arguments)
2696 .ok_or_else(|| anyhow!("wsClosed threw"))
2697 }),
2698 CellJob::Alarm {
2699 scope,
2700 scheduled_ms,
2701 claim,
2702 reply,
2703 } => begin_alarm(tc, &scope, scheduled_ms, claim, reply),
2704 }
2705}
2706
2707/// Start an alarm, claiming the due entry so nothing else fires it.
2708///
2709/// The claim is recorded on the entry rather than closed here, because the
2710/// handler has not run yet: the outcome is known only when the event ends,
2711/// which is now many turns away.
2712fn begin_alarm(
2713 tc: &mut v8::PinScope,
2714 scope: &str,
2715 scheduled_ms: i64,
2716 claim: AlarmDispatch,
2717 reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>,
2718) -> Begun {
2719 let now = unix_now_ms();
2720 if now < scheduled_ms {
2721 let _ = reply.send(Err(anyhow!("alarm dispatched before its deadline")));
2722 return Begun::Nothing;
2723 }
2724 if let AlarmDispatch::Claimed(retry) = claim {
2725 let Some(scheduled_at) = storage::active_alarm_scheduled_time(scope) else {
2726 let _ = reply.send(Err(anyhow!("alarm dispatched without a claim")));
2727 return Begun::Nothing;
2728 };
2729 return fire_alarm_handler(tc, scope, scheduled_at, retry, None, reply);
2730 }
2731 let due_by = match claim {
2732 AlarmDispatch::Armed => i64::MAX,
2733 _ => now,
2734 };
2735 let Some((scheduled_at, retry)) = storage::due_alarm_entry(scope, due_by) else {
2736 // Nothing is due: another dispatch already ran it, or the handler
2737 // that armed it cleared it. Answer what stands now, with no delta —
2738 // no handler ran, so there is nothing written to prove.
2739 let _ = reply.send(Ok((storage::get_alarm(scope), None)));
2740 return Begun::Nothing;
2741 };
2742 storage::begin_alarm_handler(scope, scheduled_at);
2743 fire_alarm_handler(
2744 tc,
2745 scope,
2746 scheduled_at,
2747 retry,
2748 Some(AlarmClaim { now_ms: now }),
2749 reply,
2750 )
2751}
2752
2753/// Call `alarm()`, carrying whatever claim its outcome must close.
2754fn fire_alarm_handler(
2755 tc: &mut v8::PinScope,
2756 scope: &str,
2757 scheduled_at: i64,
2758 retry: i64,
2759 claim: Option<AlarmClaim>,
2760 reply: tokio::sync::oneshot::Sender<Result<(Option<i64>, Option<u64>)>>,
2761) -> Begun {
2762 let begun = start_cell_event(tc, scope, Answer::Alarm(reply), None, false, |tc| {
2763 let f = dispatcher(tc, "__fireAlarm")?;
2764 let arguments = [
2765 v8::String::new(tc, scope).unwrap().into(),
2766 v8::Number::new(tc, scheduled_at as f64).into(),
2767 v8::Number::new(tc, retry as f64).into(),
2768 ];
2769 let recv = v8::undefined(tc).into();
2770 f.call(tc, recv, &arguments)
2771 .ok_or_else(|| anyhow!("alarm threw"))
2772 });
2773 match begun {
2774 Begun::Running(mut entry) => {
2775 entry.alarm = claim;
2776 Begun::Running(entry)
2777 }
2778 // The dispatcher never ran, so nothing can have changed the alarm.
2779 // Give the claim back as a failure that does not count against the
2780 // retry limit: the handler is not what failed.
2781 begun => {
2782 if let Some(claim) = claim {
2783 storage::finish_alarm_handler_with_retry_policy(scope, false, claim.now_ms, false);
2784 }
2785 begun
2786 }
2787 }
2788}
2789
2790/// Resolve one completed op and run the microtasks that follow, with the
2791/// owning request's context current.
2792///
2793/// The half of a turn that resumes a suspended request. It knows nothing
2794/// about any other request: the caller has already established that this op
2795/// is `entry`'s.
2796fn deliver(
2797 tc: &mut v8::PinScope,
2798 entry: &mut InFlight,
2799 op: u64,
2800 res: Result<asyncrt::OpOut, String>,
2801) {
2802 entry.ops.remove(&op);
2803 let guard = CurrentGuard::enter(entry.context.clone());
2804 resolve_res(tc, op, res);
2805 tc.perform_microtask_checkpoint();
2806 drop(guard);
2807}
2808
2809/// End a request whose client has hung up, so its handler stops running.
2810fn cancelled(tc: &mut v8::PinScope, entry: &mut InFlight) {
2811 if entry.reply.is_none() || !take_request_cancellation(entry.request_id) {
2812 return;
2813 }
2814 cancel(tc, entry);
2815}
2816
2817/// End a request whose cancellation has already been taken.
2818///
2819/// Split from [`cancelled`] because a suspended request observes the
2820/// cancellation *outside* the isolate — the flag is host state and costs no
2821/// V8 — and only then enters to act on it.
2822fn cancel(tc: &mut v8::PinScope, entry: &mut InFlight) {
2823 let guard = CurrentGuard::enter(entry.context.clone());
2824 // The id that names this request to the JS side. A stateless handler is
2825 // registered by the shell, and only once it suspends, so the shell holds
2826 // the id; a cell's dispatcher registers the request itself, so the job's
2827 // own id is the one to abort. Aborting the wrong one — or neither —
2828 // leaves the target's `request.signal` unfired while the caller is told
2829 // the client has gone.
2830 if let Some(id) = entry.active_request_id.or(entry.request_id) {
2831 let _ = abort_incoming_request(tc, id);
2832 }
2833 // Finishing is the shell's to undo only where the shell registered.
2834 if let Some(id) = entry.active_request_id {
2835 finish_incoming_request(tc, id);
2836 }
2837 let background = end_event_context(tc).ok().flatten();
2838 entry.background = background.map(|promise| v8::Global::new(tc, promise));
2839 drop(guard);
2840 entry.fail(anyhow!("The client has disconnected"));
2841 // A cancelled handler with no waitUntil work has nothing left to drive.
2842 // Drop its host ops now, so their guards cancel routed work. Explicit
2843 // waitUntil work keeps its ops and continues after the client disconnects.
2844 if entry.background.is_none() {
2845 entry.abandon();
2846 }
2847}
2848
2849/// Answer a request whose handler promise has settled, and retire its
2850/// `waitUntil` work once that settles too.
2851fn settle(tc: &mut v8::PinScope, entry: &mut InFlight) {
2852 if entry.reply.is_some() {
2853 let promise = v8::Local::new(tc, &entry.promise);
2854 match promise.state() {
2855 v8::PromiseState::Pending => {}
2856 v8::PromiseState::Fulfilled => {
2857 let guard = CurrentGuard::enter(entry.context.clone());
2858 let value = promise.result(tc);
2859 entry.answer_settled(tc, value);
2860 if let Some(request_id) = entry.active_request_id {
2861 finish_incoming_request(tc, request_id);
2862 }
2863 drop(guard);
2864 }
2865 v8::PromiseState::Rejected => {
2866 let guard = CurrentGuard::enter(entry.context.clone());
2867 let reason = reject_reason(tc, promise);
2868 // The handler is what failed, so an alarm's failure here
2869 // counts against its retry limit — unlike a budget overrun
2870 // or a disconnect, which `fail` records as not counting.
2871 entry.settle_alarm(false, true);
2872 let _ = end_event_context(tc);
2873 if let Some(request_id) = entry.active_request_id {
2874 finish_incoming_request(tc, request_id);
2875 }
2876 drop(guard);
2877 entry.fail(anyhow!("rejected: {reason}"));
2878 }
2879 }
2880 }
2881 if let Some(background) = &entry.background {
2882 let promise = v8::Local::new(tc, background);
2883 if !matches!(promise.state(), v8::PromiseState::Pending) {
2884 entry.background = None;
2885 }
2886 }
2887}
2888
2889/// Begin a stateless request: build it, call the Worker's `fetch`, and hand
2890/// back the promise it returned.
2891///
2892/// The half of a request that runs *before* it can suspend. Split out from
2893/// driving it to completion so a caller can start several and drive them
2894/// together; the single-request path starts one and drives it immediately,
2895/// which is what it always did.
2896///
2897/// The caller owns the `IoContext` and must have it current: `__beginEvent`
2898/// runs here, and the frame it pushes belongs to this request.
2899fn start_fetch<'s>(
2900 tc: &mut v8::PinScope<'s, '_>,
2901 fetch: v8::Local<'s, v8::Function>,
2902 url: &str,
2903 method: &str,
2904 body: &RequestBody,
2905 headers: &[(String, String)],
2906 request_id: Option<RequestId>,
2907) -> Result<Started<'s>> {
2908 let req = match request_id {
2909 Some(_) => make_incoming_request(tc, url, method, body, headers),
2910 None => make_request(tc, url, method, body.bytes(), headers),
2911 }?;
2912 let env = harness_env(tc)?;
2913 let recv = v8::undefined(tc).into();
2914 let f = fetch;
2915 let execution_ctx = begin_event_context(tc)?;
2916 let Some(ret) = f.call(tc, recv, &[req, env, execution_ctx]) else {
2917 // The handler threw synchronously. Termination carries its own error;
2918 // otherwise the pending exception is on the caller's TryCatch, which
2919 // is the only scope that can read it, so it formats the message.
2920 let error = take_execution_termination(tc);
2921 let _ = end_event_context(tc);
2922 return match error {
2923 Some(error) => Err(error),
2924 None => Ok(Started::Threw),
2925 };
2926 };
2927 // A handler that suspends must be reachable by an abort: register it as an
2928 // incoming request so a client disconnect can cancel it. One that already
2929 // settled cannot be cancelled, so its registration is cleared instead.
2930 let active_request_id = match request_id {
2931 Some(request_id)
2932 if ret
2933 .try_cast::<v8::Promise>()
2934 .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) =>
2935 {
2936 if let Err(error) = register_incoming_request(tc, request_id, req) {
2937 clear_request_cancellation(request_id);
2938 let _ = end_event_context(tc);
2939 return Err(error);
2940 }
2941 Some(request_id)
2942 }
2943 Some(request_id) => {
2944 clear_request_cancellation(request_id);
2945 None
2946 }
2947 None => None,
2948 };
2949 Ok(Started::Running(ret, active_request_id))
2950}
2951
2952/// What `start_fetch` produced: a running handler, or a synchronous throw
2953/// whose exception only the caller's `TryCatch` can read.
2954enum Started<'s> {
2955 Running(v8::Local<'s, v8::Value>, Option<RequestId>),
2956 Threw,
2957}
2958
2959impl Worker {
2960 /// Compile the worker module, wire the DO harness, and extract the entry
2961 /// `fetch`. `do_classes` come from the manifest; `bindings` maps a binding
2962 /// name to a DO class name (from wrangler metadata).
2963 ///
2964 /// The runtime builds a `WorkerConfig` directly; this helper is
2965 /// test-only.
2966 #[cfg(test)]
2967 pub fn load(options: WorkerConfigOptions, owned: &[String]) -> Result<Worker> {
2968 let config = Arc::new(WorkerConfig::new(options));
2969 Self::load_config(config, owned)
2970 }
2971
2972 pub fn load_config(config: Arc<WorkerConfig>, owned: &[String]) -> Result<Worker> {
2973 Self::load_config_owned(config, Arc::from(owned.to_vec()))
2974 }
2975
2976 fn load_config_owned(config: Arc<WorkerConfig>, owned: Arc<[String]>) -> Result<Worker> {
2977 let src = config.src.as_str();
2978 let script_name = config.script_name.as_str();
2979 let do_classes = config.do_classes.as_slice();
2980 let node = config.node.as_str();
2981 let compat = config.compat;
2982 let params = v8::CreateParams::default().heap_limits(0, v8_heap_limit_bytes());
2983 let mut isolate = v8::Isolate::new(params);
2984 // Dynamic `import()` of builtin specifiers; per-import()-call only.
2985 isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically);
2986 let original_heap_limit = isolate.get_heap_statistics().heap_size_limit();
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 });
2994 let runtime_state = Arc::new(ActorRuntimeState {
2995 promises: std::sync::Mutex::new(PromiseMap::new()),
2996 egress: config.egress,
2997 ..Default::default()
2998 });
2999 let heap_limit_state_ptr =
3000 Arc::as_ptr(&heap_limit_state) as *mut HeapLimitState as *mut std::ffi::c_void;
3001 isolate.set_slot(heap_limit_state);
3002 isolate.set_slot(runtime_state.clone());
3003 isolate.set_slot(Arc::new(ModuleRegistry::default()));
3004 isolate.add_near_heap_limit_callback(near_heap_limit, heap_limit_state_ptr);
3005 let (context, fetch) = {
3006 v8::scope!(let hs, &mut isolate);
3007 let context = v8::Context::new(hs, Default::default());
3008 let cs = &mut v8::ContextScope::new(hs, context);
3009 let tc = std::pin::pin!(v8::TryCatch::new(cs));
3010 let scope = &mut tc.init();
3011
3012 install_ops(scope, context);
3013 install_prelude(scope)?; // Web Platform APIs
3014 install_harness(scope)?; // DO object model + minimal Response
3015 install_lazy_globals(scope)?;
3016 // A global, so it must exist before the module evaluates: bundles
3017 // read Cloudflare.compatibilityFlags at module scope.
3018 inject_compatibility_flags(scope, compat)?;
3019 inject_storage_compatibility(scope, compat)?;
3020
3021 let module = match compile_module(scope, "worker.js", src) {
3022 Some(m) => m,
3023 None => return Err(anyhow!("compile: {}", exc!(scope))),
3024 };
3025 register_stubs(scope, src, &config.modules); // cloudflare:*/node:* + text modules
3026 register_wasm_modules(scope, &config.modules);
3027 register_loader_modules(scope, &config.modules);
3028 module
3029 .instantiate_module(scope, resolve_external)
3030 .ok_or_else(|| anyhow!("instantiate: {}", exc!(scope)))?;
3031 let ev = match module.evaluate(scope) {
3032 Some(value) => value,
3033 None => {
3034 if let Some(error) = take_execution_termination(scope) {
3035 return Err(error);
3036 }
3037 return Err(anyhow!("evaluate: {}", exc!(scope)));
3038 }
3039 };
3040 if let Some(error) = take_execution_termination(scope) {
3041 return Err(error);
3042 }
3043 if let Ok(p) = ev.try_cast::<v8::Promise>() {
3044 if p.state() == v8::PromiseState::Rejected {
3045 let r = p.result(scope);
3046 let stk = r
3047 .to_object(scope)
3048 .and_then(|o| {
3049 let k = v8::String::new(scope, "stack")?;
3050 o.get(scope, k.into())
3051 })
3052 .map(|s| s.to_rust_string_lossy(scope))
3053 .unwrap_or_default();
3054 return Err(anyhow!(
3055 "top-level rejected: {} | {}",
3056 r.to_rust_string_lossy(scope),
3057 stk.lines().take(4).collect::<Vec<_>>().join(" <- ")
3058 ));
3059 }
3060 }
3061
3062 let ns = module
3063 .get_module_namespace()
3064 .to_object(scope)
3065 .ok_or_else(|| anyhow!("ns"))?;
3066
3067 // register each exported DO class into the harness registry
3068 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 }
3076 let key = v8::String::new(scope, cn).unwrap();
3077 let cls = ns
3078 .get(scope, key.into())
3079 .ok_or_else(|| anyhow!("DO class {cn} not exported"))?;
3080 register_class(scope, cn, cls)?;
3081 }
3082 inject_namespace_keys(scope, script_name, do_classes)?;
3083 inject_crons(scope, &config.crons)?;
3084 populate_cf_exports(scope, ns, do_classes)?;
3085 register_entrypoints(scope, ns)?;
3086 // build env from bindings and stash it in the harness
3087 build_env(scope, &config)?;
3088 // tell the harness which cells are local (route the rest cross-node)
3089 inject_routing(scope, owned.as_ref(), node)?;
3090
3091 // entry fetch
3092 let dk = v8::String::new(scope, "default").unwrap();
3093 let default = ns
3094 .get(scope, dk.into())
3095 .ok_or_else(|| anyhow!("no default export"))?
3096 .to_object(scope)
3097 .ok_or_else(|| anyhow!("default not object"))?;
3098 let fk = v8::String::new(scope, "fetch").unwrap();
3099 let fetch_value = default
3100 .get(scope, fk.into())
3101 .ok_or_else(|| anyhow!("no fetch"))?;
3102 let default_is_entrypoint =
3103 default.is_function() && cell_registry_has(scope, "entrypoints", "default")?;
3104 let f: v8::Local<v8::Function> = if fetch_value.is_function() {
3105 fetch_value.try_into().expect("function casts to Function")
3106 } else if default_is_entrypoint {
3107 // A class-based default entrypoint (extends WorkerEntrypoint)
3108 // keeps fetch on the prototype, so route through the
3109 // harness's cached instance like a named entrypoint. Only a
3110 // registered entrypoint dispatches that way — any other
3111 // callable would load fine and then 500 on every request.
3112 compile_fn(
3113 scope,
3114 "(req) => globalThis.__dispatchEntrypointFetch('default', req)",
3115 )?
3116 } else if default.is_function() && cell_registry_has(scope, "doExports", "default")? {
3117 return Err(anyhow!(
3118 "the default export is a Durable Object class; export a fetch \
3119 handler or a WorkerEntrypoint class as the default"
3120 ));
3121 } else {
3122 return Err(anyhow!("fetch not fn"));
3123 };
3124
3125 // Lets a self-targeted service binding invoke the handler in
3126 // this isolate instead of crossing to a pool thread.
3127 {
3128 let cell_key = v8::String::new(scope, "__cell").unwrap();
3129 if let Some(cell) = context
3130 .global(scope)
3131 .get(scope, cell_key.into())
3132 .and_then(|value| value.to_object(scope))
3133 {
3134 let key = v8::String::new(scope, "selfFetch").unwrap();
3135 cell.set(scope, key.into(), f.into());
3136 // Optional scheduled handler, reached by a self-targeted
3137 // service binding's scheduled().
3138 let sk = v8::String::new(scope, "scheduled").unwrap();
3139 let key_ = v8::String::new(scope, "selfScheduled").unwrap();
3140 let own = default
3141 .get(scope, sk.into())
3142 .filter(|handler| handler.is_function());
3143 if let Some(handler) = own {
3144 cell.set(scope, key_.into(), handler);
3145 } else if default_is_entrypoint {
3146 // A class-based default entrypoint keeps scheduled on
3147 // the prototype; dispatch through the cached instance
3148 // like fetch above.
3149 let pk = v8::String::new(scope, "prototype").unwrap();
3150 let proto_scheduled = default
3151 .get(scope, pk.into())
3152 .and_then(|proto| proto.to_object(scope))
3153 .and_then(|proto| proto.get(scope, sk.into()));
3154 if proto_scheduled.is_some_and(|handler| handler.is_function()) {
3155 let shim = compile_fn(
3156 scope,
3157 "(ctrl) => globalThis.__dispatchEntrypointScheduled('default', ctrl)",
3158 )?;
3159 cell.set(scope, key_.into(), shim.into());
3160 }
3161 }
3162 }
3163 }
3164 (v8::Global::new(scope, context), v8::Global::new(scope, f))
3165 };
3166 Ok(Worker {
3167 inner: Some(WorkerIsolate {
3168 // Every setup scope above has closed, so nothing is entered
3169 // on top of this isolate and it can be handed over.
3170 // SAFETY: `into_shared` requires every piece of embedder
3171 // state hanging off this isolate to be `Send`, because it
3172 // migrates between threads and is dropped on whichever one
3173 // holds the lock last. This isolate carries exactly:
3174 //
3175 // - three slots, whose types the assertion below pins as
3176 // `Send + Sync`;
3177 // - `near_heap_limit`, a bare fn pointer whose only captured
3178 // state is a raw pointer into the `HeapLimitState` above;
3179 // - `host_import_module_dynamically`, a bare fn pointer that
3180 // captures nothing;
3181 // - a default `CreateParams` allocator, owned by V8.
3182 //
3183 // Nothing else is attached, and the assertion fails the build
3184 // if a slot type ever stops being thread-safe.
3185 //
3186 // 152.1.0 made this fallible. None of the four refusals can
3187 // hold here — this isolate is entered, is not a snapshot
3188 // creator, has no C++ heap, and has taken no weak handles —
3189 // so a refusal is a bug in the setup above, not a condition
3190 // to recover from. It panics with the reason named.
3191 isolate: unsafe { isolate.try_into_shared() }
3192 .unwrap_or_else(|error| panic!("cell isolate cannot be shared: {error}")),
3193 realm: Realm { context, fetch },
3194 original_heap_limit,
3195 compat,
3196 cells: storage::Cells::default(),
3197 }),
3198 })
3199 }
3200
3201 /// Restore an idFromName() actor's human-readable identity before its
3202 /// constructor runs. The host calls this on activation and before a named
3203 /// request is dispatched.
3204 /// Record whether this isolate hosts `cell`, so the harness can dispatch
3205 /// to it in-isolate instead of going back out through the host.
3206 ///
3207 /// Baked in at load time until cells shared isolates, when an isolate
3208 /// served exactly one cell for its whole life and the list could not
3209 /// change. Now a cell arrives at an isolate that already exists, so the
3210 /// list has to move with placement.
3211 ///
3212 /// Getting this wrong is not symmetric. A cell missing from the list
3213 /// still works: the dispatch goes out to the host, which routes it
3214 /// straight back here, costing a round trip. A cell wrongly *in* the
3215 /// list is a cell this isolate would try to serve without hosting it, so
3216 /// the shell sets it when it takes a residency and clears it when the
3217 /// residency ends.
3218 pub fn own_cell(
3219 &mut self,
3220 cell: &str,
3221 db_path: Option<&str>,
3222 owned: bool,
3223 ) -> Result<Option<i64>> {
3224 let compat = self.inner.as_ref().expect("live worker isolate").compat;
3225 let (mut locker, _cells) = self.lock();
3226 v8::scope!(let hs, &mut *locker);
3227 let realm = self.realm(hs);
3228 let context = realm.context;
3229 let cs = &mut v8::ContextScope::new(hs, context);
3230 let tc = std::pin::pin!(v8::TryCatch::new(cs));
3231 adopt_cell(&mut tc.init(), cell, db_path, owned, compat)
3232 }
3233
3234 /// Drain the alarm moves the last turn committed in this isolate.
3235 ///
3236 /// An alarm move is a turn output, exactly like the ops a turn starts:
3237 /// the drive that ran the turn reports it to the host, so a handler
3238 /// that arms an alarm and then awaits it is schedulable immediately,
3239 /// not when the request ends. A separate call rather than part of the
3240 /// turn methods' return because stateless turns cannot move an alarm
3241 /// and never pay for it.
3242 pub fn take_alarm_moves(&mut self) -> Vec<(String, i64)> {
3243 let Some(inner) = self.inner.as_mut() else {
3244 return Vec::new();
3245 };
3246 let (_locker, _cells) = inner.lock();
3247 storage::take_alarm_moves()
3248 }
3249
3250 pub fn set_id_name(&mut self, scope: &str, name: &str) -> Result<()> {
3251 let (mut locker, _cells) = self.lock();
3252 v8::scope!(let hs, &mut *locker);
3253 let realm = self.realm(hs);
3254 let context = realm.context;
3255 let cs = &mut v8::ContextScope::new(hs, context);
3256 let tc = std::pin::pin!(v8::TryCatch::new(cs));
3257 register_actor_name(&mut tc.init(), scope, Some(name))
3258 }
3259
3260 /// Start a cell event's first turn.
3261 ///
3262 /// The cell counterpart of `turn_begin`: it hands back what is now in
3263 /// flight for `runtime::drive_cell` to pump.
3264 pub fn turn_begin_cell(
3265 &mut self,
3266 job: CellJob,
3267 trace: Option<crate::telemetry::TraceIds>,
3268 ) -> (Option<InFlight>, Vec<Op>) {
3269 let Some(inner) = self.inner.as_mut() else {
3270 return (None, Vec::new());
3271 };
3272 let (mut locker, _cells) = inner.lock();
3273 inner.recover_heap(&mut locker);
3274 v8::scope!(let hs, &mut *locker);
3275 let realm = inner.realm(hs);
3276 let context = realm.context;
3277 let cs = &mut v8::ContextScope::new(hs, context);
3278 let tc = std::pin::pin!(v8::TryCatch::new(cs));
3279 let tc = &mut tc.init();
3280
3281 let previous = install_trace(tc, trace.as_ref());
3282 let out = match begin_cell(tc, job) {
3283 Begun::Running(mut entry) => {
3284 entry.trace = trace;
3285 let ops = finish_turn(tc, &mut entry);
3286 (Some(*entry), ops)
3287 }
3288 Begun::Threw(answer) => {
3289 answer.fail(anyhow!("cell event threw: {}", exc!(tc)));
3290 (None, Vec::new())
3291 }
3292 Begun::Nothing => (None, Vec::new()),
3293 };
3294 restore_trace(tc, previous);
3295 out
3296 }
3297
3298 /// Enter the isolate solely to see whether another event settled this
3299 /// one's promise.
3300 ///
3301 /// A promise resolved by a different entry has no waker pointing here,
3302 /// so the driving task cannot be told and has to look. That is why this
3303 /// is a poll and not an event, and it is the same reason the blocking
3304 /// loop woke every 10 ms.
3305 pub fn turn_poll(&mut self, entry: &mut InFlight) -> Vec<Op> {
3306 let Some(inner) = self.inner.as_mut() else {
3307 return Vec::new();
3308 };
3309 let (mut locker, _cells) = inner.lock();
3310 v8::scope!(let hs, &mut *locker);
3311 let realm = inner.realm(hs);
3312 let context = realm.context;
3313 let cs = &mut v8::ContextScope::new(hs, context);
3314 let tc = std::pin::pin!(v8::TryCatch::new(cs));
3315 let tc = &mut tc.init();
3316
3317 let previous = install_trace(tc, entry.trace.as_ref());
3318 let ops = finish_turn(tc, entry);
3319 restore_trace(tc, previous);
3320 ops
3321 }
3322
3323 /// Enter the isolate solely to record how a claimed alarm ended.
3324 ///
3325 /// Reached only when the event ended without running JS again — a budget
3326 /// overrun, or a handler waiting on nothing. The bookkeeping is storage
3327 /// the isolate owns, so it cannot be done from the driving task.
3328 pub fn turn_finish_alarm(&mut self, entry: &mut InFlight) {
3329 let Some(inner) = self.inner.as_mut() else {
3330 return;
3331 };
3332 let (_locker, _cells) = inner.lock();
3333 entry.settle_alarm(false, false);
3334 }
3335}
3336
3337// ---- native ops exposed to JS ----
3338
3339/// Host ops, defined non-enumerable. They are runtime internals: a bundle
3340/// walking `globalThis` must not find them, let alone `new` one — `for (const
3341/// k in globalThis) new globalThis[k]()` used to reach `__actor_abort` and
3342/// kill the actor.
3343macro_rules! ops {
3344 ($scope:expr, $global:expr, $($name:literal => $op:path),* $(,)?) => {
3345 $({
3346 let f = v8::Function::new($scope, $op).unwrap();
3347 let k = v8::String::new($scope, $name).unwrap();
3348 $global.define_own_property(
3349 $scope, k.into(), f.into(), v8::PropertyAttribute::DONT_ENUM);
3350 })*
3351 };
3352}
3353
3354fn install_ops(scope: &mut v8::PinScope, context: v8::Local<v8::Context>) {
3355 let global = context.global(scope);
3356 ops! { scope, global,
3357 "__heap_limit_excessively_exceeded" =>
3358 op_heap_limit_excessively_exceeded,
3359 "__heap_over_admission_share" => op_heap_over_admission_share,
3360 "__ws_send" => websocket::op_ws_send,
3361 "__ws_send_binary" => websocket::op_ws_send_binary,
3362 "__ws_close" => websocket::op_ws_close,
3363 "__ws_alloc" => websocket::op_ws_alloc,
3364 "__ws_accept" => websocket::op_ws_accept,
3365 "__ws_accept_regular" => websocket::op_ws_accept_regular,
3366 "__ws_list" => websocket::op_ws_list,
3367 "__ws_attachment_set" => websocket::op_ws_attachment_set,
3368 "__ws_auto_response_set" => websocket::op_ws_auto_response_set,
3369 "__ws_auto_response_get" => websocket::op_ws_auto_response_get,
3370 "__ws_auto_response_ts" => websocket::op_ws_auto_response_ts,
3371 "__ws_connect" => websocket::op_ws_connect,
3372 "__ws_bind_target" => websocket::op_ws_bind_target,
3373 "__ws_next" => websocket::op_ws_next,
3374 "__ws_upgrade" => websocket::op_ws_upgrade,
3375 "__storage_get" => storage_ops::op_storage_get,
3376 "__storage_get_many" => storage_ops::op_storage_get_many,
3377 "__sql_exec" => storage_ops::op_sql_exec,
3378 "__sql_ingest" => storage_ops::op_sql_ingest,
3379 "__sql_cursor_start" => storage_ops::op_sql_cursor_start,
3380 "__sql_cursor_next" => storage_ops::op_sql_cursor_next,
3381 "__sql_cursor_close" => storage_ops::op_sql_cursor_close,
3382 "__sql_database_size" => storage_ops::op_sql_database_size,
3383 "__d1_run" => storage_ops::op_d1_run,
3384 "__storage_transaction_control" => storage_ops::op_storage_transaction_control,
3385 "__log" => op_log,
3386 "__storage_put" => storage_ops::op_storage_put,
3387 "__storage_put_many" => storage_ops::op_storage_put_many,
3388 "__storage_queue_put" => storage_ops::op_storage_queue_put,
3389 "__storage_queue_put_many" => storage_ops::op_storage_queue_put_many,
3390 "__storage_put_serialized" => storage_ops::op_storage_put_serialized,
3391 "__storage_queue_put_serialized" => storage_ops::op_storage_queue_put_serialized,
3392 "__storage_flush_pending_puts" => storage_ops::op_storage_flush_pending_puts,
3393 "__storage_cancel_pending_puts" => storage_ops::op_storage_cancel_pending_puts,
3394 "__actor_abort" => op_actor_abort,
3395 "__cron_plan" => op_cron_plan,
3396 "__process_exit" => op_process_exit,
3397 "__storage_delete" => storage_ops::op_storage_delete,
3398 "__storage_delete_many" => storage_ops::op_storage_delete_many,
3399 "__storage_list" => storage_ops::op_storage_list,
3400 "__storage_sync_list_start" => storage_ops::op_storage_sync_list_start,
3401 "__storage_sync_list_next" => storage_ops::op_storage_sync_list_next,
3402 "__storage_delete_all" => storage_ops::op_storage_delete_all,
3403 "$$urlParse" => op_url_parse,
3404 "$$urlPatternParse" => op_urlpattern_parse,
3405 "$$urlPatternMatchInput" => op_urlpattern_match_input,
3406 "$$atob" => op_atob,
3407 "$$btoa" => op_btoa,
3408 "$$textDecoderLabel" => op_text_decoder_label,
3409 "$$textDecoderNew" => op_text_decoder_new,
3410 "$$textDecoderDecode" => op_text_decoder_decode,
3411 "$$textDecoderDecodeOnce" => op_text_decoder_decode_once,
3412 "$$textDecoderFree" => op_text_decoder_free,
3413 "__alarm_set" => op_alarm_set,
3414 "__alarm_get" => op_alarm_get,
3415 "__alarm_delete" => op_alarm_delete,
3416 "__loader_load" => op_loader_load,
3417 "__loader_fetch" => op_loader_fetch,
3418 "__loader_rpc" => op_loader_rpc,
3419 "__loader_drop" => op_loader_drop,
3420 "__do_call" => op_do_call,
3421 "__writePosition" => op_write_position,
3422 "__gateWrite" => op_gate_write,
3423 "__svc_call" => op_svc_call,
3424 "__svc_call_cancellable" => op_svc_call_cancellable,
3425 "__svc_rpc" => op_svc_rpc,
3426 "__do_call_cancellable" => op_do_call_cancellable,
3427 "__do_call_cancel" => op_do_call_cancel,
3428 "__do_id" => op_do_id,
3429 "__rpc_call" => op_rpc_call,
3430 "__sc_encode" => storage_ops::op_sc_encode,
3431 "__sc_decode" => storage_ops::op_sc_decode,
3432 "__op_fetch" => op_fetch,
3433 "__asset_fetch" => op_asset_fetch,
3434 "__http_stream_read" => op_http_stream_read,
3435 "__http_stream_cancel" => op_http_stream_cancel,
3436 "__http_stream_tee" => op_http_stream_tee,
3437 "__response_stream_create" => op_response_stream_create,
3438 "__response_stream_write" => op_response_stream_write,
3439 "__response_stream_closed" => op_response_stream_closed,
3440 "__response_stream_close" => op_response_stream_close,
3441 "__op_timer" => op_timer,
3442 "__timer_alloc" => op_timer_alloc,
3443 "__gate_acquire" => op_gate_acquire,
3444 "__gate_wait" => op_gate_wait,
3445 "__gate_release" => op_gate_release,
3446 "__timer_cancel" => op_timer_cancel,
3447 "__crypto_operation" => crypto::op_crypto_operation,
3448 "$$randomValues" => crypto::op_webcrypto_random,
3449 "$$digest" => crypto::op_webcrypto_digest,
3450 "$$hmacSign" => crypto::op_webcrypto_hmac_sign,
3451 "$$hmacVerify" => crypto::op_webcrypto_hmac_verify,
3452 "$$aesEncrypt" => crypto::op_webcrypto_aes_encrypt,
3453 "$$aesDecrypt" => crypto::op_webcrypto_aes_decrypt,
3454 "$$pbkdf2" => crypto::op_node_pbkdf2,
3455 "$$hkdf" => crypto::op_node_hkdf,
3456 "$$timingSafeEqual" => crypto::op_timing_safe_equal,
3457 "__event_begin" => op_event_begin,
3458 "__event_end" => op_event_end,
3459 "__wait_until" => op_wait_until,
3460 "__event_depth" => op_event_depth,
3461 "__als_get" => op_als_get,
3462 "__als_set" => op_als_set,
3463 "__util_type_flags" => op_util_type_flags,
3464 "__util_constructor_name" => op_util_constructor_name,
3465 "__util_proxy_details" => op_util_proxy_details,
3466 "__util_promise_details" => op_util_promise_details,
3467 "__util_preview_entries" => op_util_preview_entries,
3468 "__builtin_module" => op_builtin_module,
3469 "__zlib" => zlib::op_zlib,
3470 "__zlib_stream_new" => zlib::op_zlib_stream_new,
3471 "__zlib_stream_push" => zlib::op_zlib_stream_push,
3472 "__zlib_stream_end" => zlib::op_zlib_stream_end,
3473 "__zlib_stream_drop" => zlib::op_zlib_stream_drop,
3474 }
3475 #[cfg(all(test, celld_internal_tests))]
3476 ops! { scope, global,
3477 "__test_gc" => op_test_gc,
3478 "__loader_count" => op_loader_count,
3479 "__test_set_heap_limit_excessively_exceeded" =>
3480 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,
3484 "__sql_set_max_page_count_for_test" =>
3485 storage_ops::op_sql_set_max_page_count_for_test,
3486 "__sql_set_write_fault_for_test" => storage_ops::op_sql_set_write_fault_for_test,
3487 "__sql_set_cache_size_for_test" => storage_ops::op_sql_set_cache_size_for_test,
3488 "__sql_set_interrupt_fault_for_test" =>
3489 storage_ops::op_sql_set_interrupt_fault_for_test,
3490 "__sql_register_nomem_function_for_test" =>
3491 storage_ops::op_sql_register_nomem_function_for_test,
3492 }
3493}
3494
3495/// Create a JS promise for an async op `id` and return it to JS.
3496fn promise_for<'s>(scope: &mut v8::PinScope<'s, '_>, id: u64) -> v8::Local<'s, v8::Value> {
3497 let resolver = v8::PromiseResolver::new(scope).unwrap();
3498 let promise = resolver.get_promise(scope);
3499 promise_store(scope, id, v8::Global::new(scope, resolver));
3500 promise.into()
3501}
3502
3503/// Async cross-node dispatch: hand the fetch to the tokio proxy task and await
3504/// its reply off-thread — the JS thread is never blocked. Resolves to a JSON
3505/// `{status, body, headers}` string the harness turns back into a Response.
3506/// `__svc_rpc(script, entrypoint, method, argsSc)` -> Promise<Uint8Array>;
3507/// arguments and result are V8 structured-clone bytes.
3508fn op_svc_rpc(
3509 scope: &mut v8::PinScope,
3510 args: v8::FunctionCallbackArguments,
3511 mut rv: v8::ReturnValue<v8::Value>,
3512) {
3513 let script = args.get(0).to_rust_string_lossy(scope);
3514 let entrypoint = args.get(1).to_rust_string_lossy(scope);
3515 let method = args.get(2).to_rust_string_lossy(scope);
3516 let call_args = view_bytes(args.get(3)).unwrap_or_default();
3517 let (tx, rx) = tokio::sync::oneshot::channel();
3518 let gate = egress_gate_request();
3519 let request = SvcRpcReq {
3520 script,
3521 entrypoint,
3522 method,
3523 args: call_args,
3524 reply: tx,
3525 };
3526 let id = asyncrt::enqueue(async move {
3527 gated_channel_send(gate, &SVC_RPC_TX, request, "no service binding channel").await?;
3528 match rx.await {
3529 Ok(Ok(result)) => Ok(result),
3530 Ok(Err(error)) => Err(format!("{error}")),
3531 Err(error) => Err(format!("service dropped: {error}")),
3532 }
3533 });
3534 rv.set(promise_for(scope, id));
3535}
3536
3537/// `__svc_call(script, url, method, body, headersJson)` -> Promise<json>.
3538/// The service-binding equivalent of `__do_call`: no scope to resolve and no
3539/// cancellation token, just a handoff to the target script's pool.
3540fn op_svc_call(
3541 scope: &mut v8::PinScope,
3542 args: v8::FunctionCallbackArguments,
3543 mut rv: v8::ReturnValue<v8::Value>,
3544) {
3545 op_svc_call_impl(scope, args, &mut rv, false);
3546}
3547
3548fn op_svc_call_cancellable(
3549 scope: &mut v8::PinScope,
3550 args: v8::FunctionCallbackArguments,
3551 mut rv: v8::ReturnValue<v8::Value>,
3552) {
3553 op_svc_call_impl(scope, args, &mut rv, true);
3554}
3555
3556fn op_svc_call_impl(
3557 scope: &mut v8::PinScope,
3558 args: v8::FunctionCallbackArguments,
3559 rv: &mut v8::ReturnValue<v8::Value>,
3560 cancellable: bool,
3561) {
3562 let script = args.get(0).to_rust_string_lossy(scope);
3563 let url = args.get(1).to_rust_string_lossy(scope);
3564 let method = args.get(2).to_rust_string_lossy(scope);
3565 let body = view_bytes(args.get(3)).unwrap_or_default();
3566 let headers =
3567 serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default();
3568 let (tx, rx) = tokio::sync::oneshot::channel();
3569 // Shares the Durable Object cancel registry, so `__do_call_cancel` works
3570 // unchanged for a service call.
3571 let (request_id, cancel, cancel_guard) = if cancellable {
3572 let request_id = next_do_request_id();
3573 let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
3574 do_call_cancels()
3575 .lock()
3576 .unwrap()
3577 .insert(request_id, cancel_sender);
3578 (
3579 Some(request_id),
3580 Some(cancel_receiver),
3581 Some(DoCallCancelGuard::new(request_id)),
3582 )
3583 } else {
3584 (None, None, None)
3585 };
3586 let gate = egress_gate_request();
3587 let request = SvcCallReq {
3588 cancel,
3589 script,
3590 url,
3591 method,
3592 body,
3593 headers,
3594 reply: tx,
3595 };
3596 let id = asyncrt::enqueue(async move {
3597 let mut cancel_guard = cancel_guard;
3598 gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?;
3599 let result = match rx.await {
3600 Ok(Ok(response)) => Ok(encode_http_response(response, true)),
3601 Ok(Err(error)) => Err(format!("{error}")),
3602 Err(error) => Err(format!("service dropped: {error}")),
3603 };
3604 if let Some(cancel_guard) = cancel_guard.as_mut() {
3605 cancel_guard.disarm();
3606 }
3607 result
3608 });
3609 let promise = promise_for(scope, id);
3610 if let Some(request_id) = request_id {
3611 if let Some(object) = promise.to_object(scope) {
3612 let key = v8::String::new(scope, "__celldCancelId").unwrap();
3613 let value = v8::String::new(scope, &request_id.to_string()).unwrap();
3614 object.set(scope, key.into(), value.into());
3615 }
3616 }
3617 rv.set(promise);
3618}
3619
3620// --- Worker Loader: dynamic isolates for Code Mode ---
3621// A running Worker creates a fresh isolate from code it supplies at runtime
3622// and invokes it. The loaded isolate uses the same turn driver as every
3623// stateless Worker, so an awaited operation holds no thread or isolate.
3624
3625// Mirror the workerd dynamic-worker limits (worker-loader.c++): 64 MiB total
3626// module bytes, 1 MiB env. Messages match so the conformance cases pass.
3627const MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024;
3628const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024;
3629
3630#[derive(Clone)]
3631enum LoaderState {
3632 Loading,
3633 Ready(Arc<crate::pool::Slot>),
3634 Failed(Arc<str>),
3635}
3636
3637type LoaderRegistry = HashMap<u64, tokio::sync::watch::Receiver<LoaderState>>;
3638static LOADER_REGISTRY: OnceLock<std::sync::Mutex<LoaderRegistry>> = OnceLock::new();
3639static LOADER_NEXT_ID: AtomicU64 = AtomicU64::new(1);
3640
3641fn loader_registry() -> &'static std::sync::Mutex<LoaderRegistry> {
3642 LOADER_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
3643}
3644
3645fn loader_throw(scope: &mut v8::PinScope, message: &str) {
3646 let message = v8::String::new(scope, message).unwrap();
3647 let exception = v8::Exception::error(scope, message);
3648 scope.throw_exception(exception);
3649}
3650
3651async fn loaded_worker_slot(
3652 mut state: tokio::sync::watch::Receiver<LoaderState>,
3653) -> Result<Arc<crate::pool::Slot>, String> {
3654 loop {
3655 match state.borrow().clone() {
3656 LoaderState::Ready(slot) => return Ok(slot),
3657 LoaderState::Failed(error) => return Err(error.to_string()),
3658 LoaderState::Loading => {}
3659 }
3660 state
3661 .changed()
3662 .await
3663 .map_err(|_| "worker loader: load task dropped".to_string())?;
3664 }
3665}
3666
3667/// `__loader_load(codeJson)` -> stub id. Builds a WorkerConfig from the
3668/// supplied modules and registers its asynchronous load state. Compilation
3669/// runs on Tokio's blocking pool. Calls wait for that result and then use the
3670/// normal stateless turn driver.
3671fn op_loader_load(
3672 scope: &mut v8::PinScope,
3673 args: v8::FunctionCallbackArguments,
3674 mut rv: v8::ReturnValue<v8::Value>,
3675) {
3676 let code_json = args.get(0).to_rust_string_lossy(scope);
3677 let code: serde_json::Value = match serde_json::from_str(&code_json) {
3678 Ok(code) => code,
3679 Err(e) => return loader_throw(scope, &format!("worker loader: {e}")),
3680 };
3681 let Some(main) = code.get("mainModule").and_then(|v| v.as_str()) else {
3682 return loader_throw(scope, "worker loader: missing mainModule");
3683 };
3684 let Some(src) = code
3685 .get("modules")
3686 .and_then(|m| m.get(main))
3687 .and_then(|v| v.as_str())
3688 .map(str::to_string)
3689 else {
3690 return loader_throw(
3691 scope,
3692 &format!("worker loader: module {main:?} missing or not a string"),
3693 );
3694 };
3695 // Every module other than the main one is a sibling the main module may
3696 // import. JS modules arrive in the JSON as strings; anything else there is
3697 // rejected — JSON.stringify would already have mangled it, and dropping it
3698 // silently leaves the loaded worker failing instantiation with an
3699 // unresolved specifier that never names the cause. Wasm modules arrive
3700 // out of band as the second argument, an array of `[name, Uint8Array]`
3701 // pairs, which keeps the blobs out of the JSON payload entirely.
3702 let mut modules: Vec<(String, ModuleSource)> = Vec::new();
3703 if let Some(map) = code.get("modules").and_then(|m| m.as_object()) {
3704 for (name, value) in map.iter().filter(|(name, _)| name.as_str() != main) {
3705 let Some(source) = value.as_str() else {
3706 return loader_throw(
3707 scope,
3708 &format!("worker loader: module {name:?} must be a string or wasm bytes"),
3709 );
3710 };
3711 modules.push((name.clone(), ModuleSource::EsModule(source.to_string())));
3712 }
3713 }
3714 let sideband = args.get(1);
3715 if !sideband.is_undefined() {
3716 let Ok(entries) = v8::Local::<v8::Array>::try_from(sideband) else {
3717 return loader_throw(scope, "worker loader: wasm modules must be an array");
3718 };
3719 for index in 0..entries.length() {
3720 let entry = entries
3721 .get_index(scope, index)
3722 .and_then(|entry| v8::Local::<v8::Array>::try_from(entry).ok())
3723 .and_then(|pair| Some((pair.get_index(scope, 0)?, pair.get_index(scope, 1)?)))
3724 .filter(|(name, _)| name.is_string())
3725 .and_then(|(name, value)| {
3726 let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
3727 Some((name.to_rust_string_lossy(scope), view))
3728 });
3729 let Some((name, view)) = entry else {
3730 return loader_throw(scope, "worker loader: malformed wasm module entry");
3731 };
3732 // A name carried by both the JSON map and the side-band would
3733 // silently shadow one module with the other in the registry;
3734 // refuse it the way a non-string JSON module is refused.
3735 if name == main || modules.iter().any(|(existing, _)| *existing == name) {
3736 return loader_throw(
3737 scope,
3738 &format!("worker loader: duplicate module name {name:?}"),
3739 );
3740 }
3741 let mut bytes = vec![0u8; view.byte_length()];
3742 view.copy_contents(&mut bytes);
3743 modules.push((name, ModuleSource::Wasm(bytes.into())));
3744 }
3745 }
3746 // Total module bytes, checked before compiling anything (the oversized
3747 // module is never parsed) — the extra modules are not yet loaded but do
3748 // count against the ceiling, as upstream.
3749 let code_size: usize = src.len()
3750 + modules
3751 .iter()
3752 .map(|(_, source)| match source {
3753 ModuleSource::Text(source) | ModuleSource::EsModule(source) => source.len(),
3754 ModuleSource::Wasm(bytes) => bytes.len(),
3755 })
3756 .sum::<usize>();
3757 if code_size > MAX_DYNAMIC_WORKER_CODE_SIZE {
3758 return loader_throw(
3759 scope,
3760 &format!(
3761 "Dynamic Worker code size ({code_size} bytes) exceeds the \
3762 maximum allowed size of {MAX_DYNAMIC_WORKER_CODE_SIZE} bytes."
3763 ),
3764 );
3765 }
3766 // Plain JSON `env` values merge onto the loaded worker's env; capability
3767 // stubs are not yet supported and would fail to serialize upstream in JS.
3768 let loader_env = code
3769 .get("env")
3770 .filter(|v| !v.is_null())
3771 .map(|v| v.to_string());
3772 if let Some(env) = &loader_env {
3773 if env.len() > MAX_DYNAMIC_WORKER_ENV_SIZE {
3774 return loader_throw(
3775 scope,
3776 &format!(
3777 "Dynamic Worker env size ({} bytes) exceeds the maximum \
3778 allowed size of {MAX_DYNAMIC_WORKER_ENV_SIZE} bytes.",
3779 env.len()
3780 ),
3781 );
3782 }
3783 }
3784 // globalOutbound: absent inherits the caller's authority, null denies
3785 // ambient egress, a Fetcher (broker) is not implemented yet.
3786 let egress = match code.get("globalOutbound") {
3787 None => actor_runtime_state(scope).egress,
3788 Some(v) if v.is_null() => EgressPolicy::Deny,
3789 Some(_) => {
3790 return loader_throw(
3791 scope,
3792 "worker loader: globalOutbound broker is not implemented yet",
3793 );
3794 }
3795 };
3796 // Bound live loaded workers so a runaway agent loop cannot exhaust
3797 // isolates. Evicted workers (dropped stubs) free their slot.
3798 let max = crate::env_vars::positive_or("CELLD_MAX_LOADED_WORKERS", 256)
3799 .expect("validated CELLD_MAX_LOADED_WORKERS");
3800 if loader_registry().lock().unwrap().len() >= max {
3801 return loader_throw(
3802 scope,
3803 &format!("worker loader: too many loaded workers (limit {max})"),
3804 );
3805 }
3806 // Honor the WorkerCode's declared compatibility (workerd worker_compat
3807 // reads snake_case keys); Code Mode workers keep RPC on regardless.
3808 let mut compat = crate::worker_compat(&serde_json::json!({
3809 "compatibility_date": code.get("compatibilityDate"),
3810 "compatibility_flags": code.get("compatibilityFlags"),
3811 }));
3812 compat.js_rpc = true;
3813 let id = LOADER_NEXT_ID.fetch_add(1, Ordering::Relaxed);
3814 let config = Arc::new(
3815 WorkerConfig::new(WorkerConfigOptions {
3816 src,
3817 script_name: format!("__loader:{id}"),
3818 do_classes: Vec::new(),
3819 bindings: Vec::new(),
3820 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(),
3824 ai_binding: None,
3825 vars: Vec::new(),
3826 node: String::new(),
3827 modules,
3828 compat,
3829 })
3830 .with_egress(egress)
3831 .with_loader_env(loader_env),
3832 );
3833 let handle = match tokio::runtime::Handle::try_current() {
3834 Ok(handle) => handle,
3835 Err(error) => return loader_throw(scope, &format!("worker loader: {error}")),
3836 };
3837 let (loaded, state) = tokio::sync::watch::channel(LoaderState::Loading);
3838 loader_registry().lock().unwrap().insert(id, state);
3839 handle.spawn(async move {
3840 let state =
3841 match tokio::task::spawn_blocking(move || Worker::load_config(config, &[])).await {
3842 Ok(Ok(worker)) => LoaderState::Ready(crate::pool::Slot::standalone(worker)),
3843 Ok(Err(error)) => LoaderState::Failed(Arc::from(format!("{error}"))),
3844 Err(error) => LoaderState::Failed(Arc::from(format!(
3845 "worker loader: load task failed: {error}"
3846 ))),
3847 };
3848 loaded.send_replace(state);
3849 });
3850 rv.set(v8::Number::new(scope, id as f64).into());
3851}
3852
3853/// `__loader_fetch(id, url, method, body, headersJson)` -> Promise<json>. The
3854/// loaded-worker analog of `__svc_call`: encodes the response the same way.
3855fn op_loader_fetch(
3856 scope: &mut v8::PinScope,
3857 args: v8::FunctionCallbackArguments,
3858 mut rv: v8::ReturnValue<v8::Value>,
3859) {
3860 let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3861 let url = args.get(1).to_rust_string_lossy(scope);
3862 let method = args.get(2).to_rust_string_lossy(scope);
3863 let body = view_bytes(args.get(3)).unwrap_or_default();
3864 let headers =
3865 serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)).unwrap_or_default();
3866 let loaded = loader_registry().lock().unwrap().get(&id).cloned();
3867 let async_id = asyncrt::enqueue(async move {
3868 let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?;
3869 let slot = loaded_worker_slot(state).await?;
3870 let (reply, receive) = tokio::sync::oneshot::channel();
3871 let job = crate::WorkerJob::Fetch {
3872 queued_at: Instant::now(),
3873 url,
3874 method,
3875 body: body.into(),
3876 headers,
3877 request_id: None,
3878 reply,
3879 };
3880 let driving = tokio::spawn(crate::runtime::drive(slot, job, None));
3881 match receive.await {
3882 Ok(Ok(response)) => Ok(encode_http_response(response, false)),
3883 Ok(Err(error)) => Err(format!("{error}")),
3884 Err(_) => match driving.await {
3885 Err(error) => Err(format!("loaded worker task died: {error}")),
3886 Ok(()) => Err("loaded worker dropped response".to_string()),
3887 },
3888 }
3889 });
3890 rv.set(promise_for(scope, async_id));
3891}
3892
3893/// `__loader_rpc(id, entrypoint, method, argsSc)` -> Promise<Uint8Array>. The
3894/// loaded-worker analog of `__svc_rpc`: a named-entrypoint method call whose
3895/// args and result are V8 structured-clone bytes.
3896fn op_loader_rpc(
3897 scope: &mut v8::PinScope,
3898 args: v8::FunctionCallbackArguments,
3899 mut rv: v8::ReturnValue<v8::Value>,
3900) {
3901 let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3902 let entrypoint = args.get(1).to_rust_string_lossy(scope);
3903 let method = args.get(2).to_rust_string_lossy(scope);
3904 let call_args = view_bytes(args.get(3)).unwrap_or_default();
3905 let loaded = loader_registry().lock().unwrap().get(&id).cloned();
3906 let async_id = asyncrt::enqueue(async move {
3907 let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?;
3908 let slot = loaded_worker_slot(state).await?;
3909 let (reply, receive) = tokio::sync::oneshot::channel();
3910 let job = crate::WorkerJob::Rpc {
3911 entrypoint,
3912 method,
3913 args: call_args,
3914 reply,
3915 };
3916 let driving = tokio::spawn(crate::runtime::drive(slot, job, None));
3917 match receive.await {
3918 Ok(Ok(result)) => Ok(result),
3919 Ok(Err(error)) => Err(format!("{error}")),
3920 Err(_) => match driving.await {
3921 Err(error) => Err(format!("loaded worker task died: {error}")),
3922 Ok(()) => Err("loaded worker dropped RPC result".to_string()),
3923 },
3924 }
3925 });
3926 rv.set(promise_for(scope, async_id));
3927}
3928
3929/// `__loader_drop(id)` — evict a loaded worker. Called from a
3930/// FinalizationRegistry when its stub is GC'd. Removing the registry entry
3931/// drops the isolate after any calls that already cloned its load state end.
3932fn op_loader_drop(
3933 scope: &mut v8::PinScope,
3934 args: v8::FunctionCallbackArguments,
3935 _rv: v8::ReturnValue<v8::Value>,
3936) {
3937 let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
3938 if let Some(state) = loader_registry().lock().unwrap().remove(&id) {
3939 // This op runs while the parent isolate is entered. The load state can
3940 // own the loaded isolate, and V8 forbids dropping one isolate while a
3941 // different isolate is entered on the same thread. Hand the final
3942 // reference to the host scheduler so destruction happens after this
3943 // turn has left V8.
3944 asyncrt::op_handle().spawn(async move { drop(state) });
3945 }
3946}
3947
3948/// `__writePosition(scope)` -> the cell's committed-write position (a number),
3949/// or `null` when the scope has no open connection. The co-hosted DO fast path
3950/// samples this around an inline `fetch` to tell a write from a read.
3951fn op_write_position(
3952 scope: &mut v8::PinScope,
3953 args: v8::FunctionCallbackArguments,
3954 mut rv: v8::ReturnValue<v8::Value>,
3955) {
3956 let cell = args.get(0).to_rust_string_lossy(scope);
3957 match storage::write_position(&cell) {
3958 Some(position) => rv.set(v8::Number::new(scope, position as f64).into()),
3959 None => rv.set(v8::null(scope).into()),
3960 }
3961}
3962
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.
3966fn op_gate_write(
3967 scope: &mut v8::PinScope,
3968 args: v8::FunctionCallbackArguments,
3969 mut rv: v8::ReturnValue<v8::Value>,
3970) {
3971 let cell = args.get(0).to_rust_string_lossy(scope);
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();
3977 let (tx, receive) = tokio::sync::oneshot::channel();
3978 let sent = GATE_TX
3979 .get()
3980 .map(|gate| {
3981 gate.send(GateReq {
3982 scope: cell,
3983 position,
3984 reply: tx,
3985 })
3986 .is_ok()
3987 })
3988 .unwrap_or(false);
3989 let id = asyncrt::enqueue(async move {
3990 if !sent {
3991 if read_only {
3992 return Ok(String::new());
3993 }
3994 return Err("no output-gate channel".into());
3995 }
3996 match receive.await {
3997 Ok(Ok(())) => Ok(String::new()),
3998 Ok(Err(error)) => Err(format!("{error:?}")),
3999 Err(_) => Err("output gate dropped".into()),
4000 }
4001 });
4002 rv.set(promise_for(scope, id));
4003}
4004
4005fn op_do_call(
4006 scope: &mut v8::PinScope,
4007 args: v8::FunctionCallbackArguments,
4008 mut rv: v8::ReturnValue<v8::Value>,
4009) {
4010 op_do_call_impl(scope, args, &mut rv, false);
4011}
4012
4013fn op_do_call_cancellable(
4014 scope: &mut v8::PinScope,
4015 args: v8::FunctionCallbackArguments,
4016 mut rv: v8::ReturnValue<v8::Value>,
4017) {
4018 op_do_call_impl(scope, args, &mut rv, true);
4019}
4020
4021fn op_do_call_impl(
4022 scope: &mut v8::PinScope,
4023 args: v8::FunctionCallbackArguments,
4024 rv: &mut v8::ReturnValue<v8::Value>,
4025 cancellable: bool,
4026) {
4027 let cell = args.get(0).to_rust_string_lossy(scope);
4028 let name_value = args.get(1);
4029 let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
4030 let url = args.get(2).to_rust_string_lossy(scope);
4031 let method = args.get(3).to_rust_string_lossy(scope);
4032 let body = view_bytes(args.get(4)).unwrap_or_default();
4033 let headers =
4034 serde_json::from_str(&args.get(5).to_rust_string_lossy(scope)).unwrap_or_default();
4035 let (tx, rx) = tokio::sync::oneshot::channel();
4036 // Taken here and nowhere later: this is the last point that still runs
4037 // in the order the script made the calls.
4038 let order = Some(enter_call_order(current_context(), &cell));
4039 // Every host op needs an internal cancellation channel. A caller without
4040 // an AbortSignal cannot cancel from JavaScript, but its enclosing Worker
4041 // can still disappear and drop this op before routing completes.
4042 let request_id = next_do_request_id();
4043 let (cancel_sender, cancel) = tokio::sync::oneshot::channel();
4044 do_call_cancels()
4045 .lock()
4046 .unwrap()
4047 .insert(request_id, cancel_sender);
4048 let mut cancel_guard = DoCallCancelGuard::new(request_id);
4049 let gate = egress_gate_request();
4050 let request = DoCallReq {
4051 request_id: Some(request_id),
4052 cancel: Some(cancel),
4053 deliver_abort_to_handler: cancellable,
4054 scope: cell,
4055 name,
4056 url,
4057 method,
4058 body,
4059 headers,
4060 reply: tx,
4061 order,
4062 parent: current_trace_ids(scope),
4063 };
4064 let id = asyncrt::enqueue(async move {
4065 gated_channel_send(gate, &DO_CALL_TX, request, "no proxy channel").await?;
4066 let result = match rx.await {
4067 Ok(Ok(response)) => Ok(encode_http_response(response, true)),
4068 Ok(Err(e)) => Err(format!("{e}")),
4069 Err(e) => Err(format!("proxy dropped: {e}")),
4070 };
4071 cancel_guard.disarm();
4072 result
4073 });
4074 let p = promise_for(scope, id);
4075 if cancellable {
4076 if let Some(promise) = p.to_object(scope) {
4077 let key = v8::String::new(scope, "__celldCancelId").unwrap();
4078 let request_id = v8::String::new(scope, &request_id_string(request_id)).unwrap();
4079 promise.set(scope, key.into(), request_id.into());
4080 }
4081 }
4082 rv.set(p);
4083}
4084
4085fn op_do_call_cancel(
4086 scope: &mut v8::PinScope,
4087 args: v8::FunctionCallbackArguments,
4088 _rv: v8::ReturnValue<v8::Value>,
4089) {
4090 let request_id = args.get(0).to_rust_string_lossy(scope);
4091 let Some(request_id) = parse_request_id(&request_id) else {
4092 return;
4093 };
4094 if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request_id) {
4095 let _ = cancel.send(());
4096 }
4097}
4098
4099/// `__rpc_call(scope, name, method, argsSc)` -> Promise<Uint8Array>;
4100/// arguments and result are V8 structured-clone bytes.
4101fn op_rpc_call(
4102 scope: &mut v8::PinScope,
4103 args: v8::FunctionCallbackArguments,
4104 mut rv: v8::ReturnValue<v8::Value>,
4105) {
4106 let cell = args.get(0).to_rust_string_lossy(scope);
4107 let name_value = args.get(1);
4108 let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
4109 let method = args.get(2).to_rust_string_lossy(scope);
4110 let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default());
4111 let (tx, rx) = tokio::sync::oneshot::channel();
4112 let gate = egress_gate_request();
4113 let request = RpcCallReq {
4114 scope: cell,
4115 name,
4116 method,
4117 args,
4118 reply: tx,
4119 };
4120 let id = asyncrt::enqueue(async move {
4121 gated_channel_send(gate, &RPC_CALL_TX, request, "no RPC channel").await?;
4122 match rx.await {
4123 Ok(Ok(RpcData::V8(bytes))) => Ok(bytes),
4124 Ok(Ok(RpcData::Json(_))) => Err("RPC answered JSON to a structured-clone call".into()),
4125 Ok(Err(e)) => Err(format!("{e}")),
4126 Err(e) => Err(format!("RPC proxy dropped: {e}")),
4127 }
4128 });
4129 let p = promise_for(scope, id);
4130 rv.set(p);
4131}
4132
4133/// Outbound `fetch` — the op behind the harness's `fetch()`. Resolves to a JSON
4134/// `{status, body, headers}` string. Streaming is a later layer.
4135fn op_fetch(
4136 scope: &mut v8::PinScope,
4137 args: v8::FunctionCallbackArguments,
4138 mut rv: v8::ReturnValue<v8::Value>,
4139) {
4140 // A loaded worker with globalOutbound: null has no ambient egress: it must
4141 // reach the world through `env` capabilities. Message matches workerd.
4142 if actor_runtime_state(scope).egress == EgressPolicy::Deny {
4143 return loader_throw(
4144 scope,
4145 "This worker is not permitted to access the internet via global \
4146 functions like fetch(). It must use capabilities (such as \
4147 bindings in 'env') to talk to the outside world.",
4148 );
4149 }
4150 let method = args.get(0).to_rust_string_lossy(scope);
4151 let url = args.get(1).to_rust_string_lossy(scope);
4152 let b = args.get(2);
4153 let body: Option<Vec<u8>> = if b.is_undefined() || b.is_null() {
4154 None
4155 } else {
4156 serde_json::from_str(&b.to_rust_string_lossy(scope)).ok()
4157 };
4158 let mut headers: Vec<(String, String)> =
4159 serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
4160 let redirect = args.get(4).to_rust_string_lossy(scope);
4161 let client = if redirect == "manual" {
4162 HTTP_MANUAL.with(|client| client.clone())
4163 } else {
4164 HTTP.with(|client| client.clone())
4165 };
4166 // The creating context, read here while JS is still running: the op
4167 // future resolves on whatever worker polls it, far from any CPED.
4168 let trace = current_trace_ids(scope);
4169 // The child's ids are minted before the request leaves so the
4170 // traceparent header carries them: whatever this fetch reaches can
4171 // join the trace celld is part of.
4172 let child = trace.as_ref().map(crate::telemetry::child_ids);
4173 if let Some(child) = child.as_ref() {
4174 if !headers
4175 .iter()
4176 .any(|(name, _)| name.eq_ignore_ascii_case("traceparent"))
4177 {
4178 headers.push(("traceparent".into(), crate::telemetry::traceparent(child)));
4179 }
4180 }
4181 let span_url = trace.as_ref().map(|_| url.clone());
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();
4187 let id = asyncrt::enqueue(async move {
4188 let span_started = trace.as_ref().map(|_| crate::telemetry::now_unix_us());
4189 let mut span = trace.as_ref().zip(child).map(|(parent, child)| {
4190 let mut span =
4191 crate::telemetry::Span::new(child, "fetch", crate::telemetry::KIND_CLIENT);
4192 span.parent_span_id = Some(parent.span_id);
4193 span.parent_remote = Some(false);
4194 span.url = span_url;
4195 span
4196 });
4197 let mut finish = |ok: bool, status: Option<u16>, error: Option<String>| {
4198 if let Some(mut span) = span.take() {
4199 span.start_unix_us = span_started.unwrap_or_default();
4200 span.duration_us = crate::telemetry::now_unix_us() - span.start_unix_us;
4201 span.ok = ok;
4202 span.http_status = status;
4203 span.error = error;
4204 crate::telemetry::record(span);
4205 }
4206 };
4207 await_egress_gate(gate).await.inspect_err(|error| {
4208 finish(false, None, Some(error.clone()));
4209 })?;
4210 let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET);
4211 // a timeout bounds a black-hole host: the future settles (Err) instead
4212 // of parking run_loop forever — the hang the Drop guard can't catch.
4213 let fetch_timeout = crate::env_vars::positive_or("CELLD_FETCH_TIMEOUT_S", 120)
4214 .expect("validated CELLD_FETCH_TIMEOUT_S");
4215 let mut rb = client
4216 .request(m, &url)
4217 .timeout(std::time::Duration::from_secs(fetch_timeout));
4218 for (name, value) in headers {
4219 rb = rb.header(name, value);
4220 }
4221 if let Some(b) = body {
4222 rb = rb.body(b);
4223 }
4224 match rb.send().await {
4225 Ok(resp) => {
4226 let status = resp.status().as_u16();
4227 finish(true, Some(status), None);
4228 let headers = resp
4229 .headers()
4230 .iter()
4231 .map(|(name, value)| {
4232 (
4233 name.as_str().to_string(),
4234 value.to_str().unwrap_or_default().to_string(),
4235 )
4236 })
4237 .collect::<Vec<_>>();
4238 let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
4239 register_http_stream(stream_id, HttpStreamSource::Response(resp));
4240 Ok(serde_json::json!({
4241 "status": status, "streamId": stream_id, "headers": headers,
4242 })
4243 .to_string())
4244 }
4245 Err(e) => {
4246 finish(false, None, Some(format!("fetch: {e}")));
4247 Err(format!("fetch: {e}"))
4248 }
4249 }
4250 });
4251 let p = promise_for(scope, id);
4252 rv.set(p);
4253}
4254
4255fn op_asset_fetch(
4256 scope: &mut v8::PinScope,
4257 args: v8::FunctionCallbackArguments,
4258 mut rv: v8::ReturnValue<v8::Value>,
4259) {
4260 let script = args.get(0).to_rust_string_lossy(scope);
4261 let method = args.get(1).to_rust_string_lossy(scope);
4262 let url = args.get(2).to_rust_string_lossy(scope);
4263 let headers: Vec<(String, String)> =
4264 serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)).unwrap_or_default();
4265 let (tx, rx) = tokio::sync::oneshot::channel();
4266 let sent = ASSET_CALL_TX.get().is_some_and(|sender| {
4267 sender
4268 .send(AssetCallReq {
4269 script,
4270 url,
4271 method,
4272 headers,
4273 reply: tx,
4274 })
4275 .is_ok()
4276 });
4277 let id = asyncrt::enqueue(async move {
4278 if !sent {
4279 return Err("no asset resolver channel".to_string());
4280 }
4281 match rx.await {
4282 Ok(Ok(response)) => Ok(encode_http_response(response, false)),
4283 Ok(Err(error)) => Err(format!("asset fetch: {error}")),
4284 Err(error) => Err(format!("asset resolver dropped: {error}")),
4285 }
4286 });
4287 rv.set(promise_for(scope, id));
4288}
4289
4290async fn next_http_stream_chunk(source: &mut HttpStreamSource) -> Result<Option<Vec<u8>>, String> {
4291 match source {
4292 HttpStreamSource::Response(response) => response
4293 .chunk()
4294 .await
4295 .map(|chunk| chunk.map(|bytes| bytes.to_vec()))
4296 .map_err(|error| format!("response stream: {error}")),
4297 HttpStreamSource::Receiver(receiver) => match receiver.recv().await {
4298 Some(Ok(bytes)) => Ok(Some(bytes)),
4299 Some(Err(error)) => Err(error),
4300 None => Ok(None),
4301 },
4302 HttpStreamSource::Stream(stream) => stream.next().await.transpose(),
4303 }
4304}
4305
4306/// Move a host response source into a directly-polled stream. No pump task is
4307/// needed: the eventual HTTP or JS consumer supplies the backpressure.
4308fn http_chunk_stream(source: HttpStreamSource) -> HttpChunkStream {
4309 match source {
4310 HttpStreamSource::Response(response) => Box::pin(response.bytes_stream().map(|chunk| {
4311 chunk
4312 .map(|bytes| bytes.to_vec())
4313 .map_err(|error| format!("response stream: {error}"))
4314 })),
4315 HttpStreamSource::Receiver(receiver) => {
4316 Box::pin(tokio_stream::wrappers::ReceiverStream::new(receiver))
4317 }
4318 HttpStreamSource::Stream(stream) => stream,
4319 }
4320}
4321
4322/// Host-native tee for an outbound response. Both branches are represented by
4323/// stream IDs, so one can be returned through Axum while JS independently
4324/// scans the other for observability or usage accounting.
4325fn tee_http_stream(mut source: HttpStreamSource) -> (u64, u64) {
4326 let (tx1, rx1) = tokio::sync::mpsc::channel(16);
4327 let (tx2, rx2) = tokio::sync::mpsc::channel(16);
4328 let id1 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
4329 let id2 = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
4330 register_http_stream(id1, HttpStreamSource::Receiver(rx1));
4331 register_http_stream(id2, HttpStreamSource::Receiver(rx2));
4332 asyncrt::op_handle().spawn(async move {
4333 loop {
4334 match next_http_stream_chunk(&mut source).await {
4335 Ok(Some(bytes)) => {
4336 let first = tx1.send(Ok(bytes.clone())).await.is_ok();
4337 let second = tx2.send(Ok(bytes)).await.is_ok();
4338 if !first && !second {
4339 break;
4340 }
4341 }
4342 Ok(None) => break,
4343 Err(error) => {
4344 let _ = tx1.send(Err(error.clone())).await;
4345 let _ = tx2.send(Err(error)).await;
4346 break;
4347 }
4348 }
4349 }
4350 });
4351 (id1, id2)
4352}
4353
4354fn op_http_stream_read(
4355 scope: &mut v8::PinScope,
4356 args: v8::FunctionCallbackArguments,
4357 mut rv: v8::ReturnValue<v8::Value>,
4358) {
4359 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4360 let source = http_streams()
4361 .lock()
4362 .unwrap()
4363 .get_mut(&stream_id)
4364 .and_then(|stream| {
4365 stream
4366 .source
4367 .take()
4368 .map(|source| (source, stream.cancelled.subscribe()))
4369 });
4370 let id = asyncrt::enqueue(async move {
4371 let Some((mut source, mut cancelled)) = source else {
4372 return Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into()));
4373 };
4374 let next = tokio::select! {
4375 result = next_http_stream_chunk(&mut source) => Some(result),
4376 _ = cancelled.changed() => None,
4377 };
4378 match next {
4379 None => Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())),
4380 Some(Ok(Some(bytes))) => {
4381 if let Some(stream) = http_streams().lock().unwrap().get_mut(&stream_id) {
4382 stream.created = Instant::now();
4383 stream.source = Some(source);
4384 }
4385 Ok(asyncrt::OpOut::Bytes(bytes))
4386 }
4387 Some(Ok(None)) => {
4388 http_streams().lock().unwrap().remove(&stream_id);
4389 Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into()))
4390 }
4391 Some(Err(error)) => {
4392 http_streams().lock().unwrap().remove(&stream_id);
4393 Err(error)
4394 }
4395 }
4396 });
4397 rv.set(promise_for(scope, id));
4398}
4399
4400fn op_http_stream_tee(
4401 scope: &mut v8::PinScope,
4402 args: v8::FunctionCallbackArguments,
4403 mut rv: v8::ReturnValue<v8::Value>,
4404) {
4405 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4406 let source = http_streams()
4407 .lock()
4408 .unwrap()
4409 .remove(&stream_id)
4410 .and_then(|stream| stream.source);
4411 let Some(source) = source else {
4412 let message = v8::String::new(scope, "response stream is no longer available").unwrap();
4413 let exception = v8::Exception::type_error(scope, message);
4414 scope.throw_exception(exception);
4415 return;
4416 };
4417 let ids = tee_http_stream(source);
4418 let json = serde_json::to_string(&ids).unwrap();
4419 rv.set(v8::String::new(scope, &json).unwrap().into());
4420}
4421
4422fn op_http_stream_cancel(
4423 scope: &mut v8::PinScope,
4424 args: v8::FunctionCallbackArguments,
4425 _rv: v8::ReturnValue<v8::Value>,
4426) {
4427 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4428 if let Some(stream) = http_streams().lock().unwrap().remove(&stream_id) {
4429 let _ = stream.cancelled.send(true);
4430 }
4431}
4432
4433fn op_response_stream_create(
4434 scope: &mut v8::PinScope,
4435 _args: v8::FunctionCallbackArguments,
4436 mut rv: v8::ReturnValue<v8::Value>,
4437) {
4438 let stream_id = NEXT_HTTP_STREAM_ID.fetch_add(1, Ordering::Relaxed);
4439 let (writer, receiver) = tokio::sync::mpsc::channel(1);
4440 let (finished, _) = tokio::sync::watch::channel(false);
4441 let now = Instant::now();
4442 register_http_stream(stream_id, HttpStreamSource::Receiver(receiver));
4443 let mut writers = response_stream_writers().lock().unwrap();
4444 writers.retain(|_, stream| stream.created.elapsed() < Duration::from_secs(60));
4445 writers.insert(
4446 stream_id,
4447 ResponseStreamWriter {
4448 created: now,
4449 writer,
4450 finished,
4451 },
4452 );
4453 rv.set(v8::Number::new(scope, stream_id as f64).into());
4454}
4455
4456fn op_response_stream_write(
4457 scope: &mut v8::PinScope,
4458 args: v8::FunctionCallbackArguments,
4459 mut rv: v8::ReturnValue<v8::Value>,
4460) {
4461 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4462 let bytes = args
4463 .get(1)
4464 .try_cast::<v8::ArrayBufferView>()
4465 .ok()
4466 .map(|view| {
4467 let mut bytes = vec![0; view.byte_length()];
4468 view.copy_contents(&mut bytes);
4469 bytes
4470 });
4471 let writer = response_stream_writers()
4472 .lock()
4473 .unwrap()
4474 .get_mut(&stream_id)
4475 .map(|stream| {
4476 stream.created = Instant::now();
4477 stream.writer.clone()
4478 });
4479 let id = asyncrt::enqueue(async move {
4480 let Some(bytes) = bytes else {
4481 return Err("response stream chunks must be ArrayBuffer views".into());
4482 };
4483 let Some(writer) = writer else {
4484 return Err("response stream consumer canceled".into());
4485 };
4486 if writer.send(Ok(bytes)).await.is_err() {
4487 response_stream_writers().lock().unwrap().remove(&stream_id);
4488 return Err("response stream consumer canceled".into());
4489 }
4490 Ok(String::new())
4491 });
4492 rv.set(promise_for(scope, id));
4493}
4494
4495fn op_response_stream_closed(
4496 scope: &mut v8::PinScope,
4497 args: v8::FunctionCallbackArguments,
4498 mut rv: v8::ReturnValue<v8::Value>,
4499) {
4500 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4501 let (writer, mut finished) = response_stream_writers()
4502 .lock()
4503 .unwrap()
4504 .get(&stream_id)
4505 .map(|stream| (stream.writer.clone(), stream.finished.subscribe()))
4506 .unzip();
4507 let id = asyncrt::enqueue(async move {
4508 let cancelled = match (writer, finished.as_mut()) {
4509 (Some(writer), Some(finished)) => tokio::select! {
4510 biased;
4511 result = finished.changed() => result.is_err(),
4512 _ = writer.closed() => true,
4513 },
4514 _ => false,
4515 };
4516 Ok(String::from(if cancelled {
4517 "cancelled"
4518 } else {
4519 "finished"
4520 }))
4521 });
4522 rv.set(promise_for(scope, id));
4523}
4524
4525fn op_response_stream_close(
4526 scope: &mut v8::PinScope,
4527 args: v8::FunctionCallbackArguments,
4528 mut rv: v8::ReturnValue<v8::Value>,
4529) {
4530 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4531 let error = args.get(1).to_rust_string_lossy(scope);
4532 let stream = response_stream_writers().lock().unwrap().remove(&stream_id);
4533 let id = asyncrt::enqueue(async move {
4534 if let Some(stream) = stream {
4535 let _ = stream.finished.send(true);
4536 if !error.is_empty() {
4537 let _ = stream.writer.send(Err(error)).await;
4538 }
4539 }
4540 Ok(String::new())
4541 });
4542 rv.set(promise_for(scope, id));
4543}
4544
4545pub fn reqwest_response_stream(response: reqwest::Response) -> HttpChunkStream {
4546 http_chunk_stream(HttpStreamSource::Response(response))
4547}
4548
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.
4553pub 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.
4565pub enum RequestBody {
4566 Bytes(Vec<u8>),
4567 Stream(u64),
4568}
4569
4570impl 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
4580impl From<Vec<u8>> for RequestBody {
4581 fn from(bytes: Vec<u8>) -> Self {
4582 Self::Bytes(bytes)
4583 }
4584}
4585
4586/// Timer op behind `setTimeout`: a promise resolving after `ms`.
4587fn op_timer(
4588 scope: &mut v8::PinScope,
4589 args: v8::FunctionCallbackArguments,
4590 mut rv: v8::ReturnValue<v8::Value>,
4591) {
4592 let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4593 let ms = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64;
4594 let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
4595 timer_cancels().lock().unwrap().insert(timer_id, cancel_tx);
4596 let id = asyncrt::enqueue(async move {
4597 tokio::select! {
4598 _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => {}
4599 _ = &mut cancel_rx => {}
4600 }
4601 timer_cancels().lock().unwrap().remove(&timer_id);
4602 Ok(String::new())
4603 });
4604 let p = promise_for(scope, id);
4605 rv.set(p);
4606}
4607
4608/// `__gate_acquire(scope)` — take the cell's input gate for a
4609/// `blockConcurrencyWhile`, waiting if another block holds it.
4610///
4611/// Answers a promise of the event id, not the id itself. It was synchronous,
4612/// and that was right while a cell's events came off one channel: only one
4613/// ran at a time, a delivery point had already found the gate open, and
4614/// yielding even one microtask reopened a window in which a nested delivery
4615/// could wait on a gate nothing would release. Neither half holds now —
4616/// events are independent tasks, several run at once, and nothing nests —
4617/// so two blocks can meet and the second must queue.
4618fn op_gate_acquire(
4619 scope: &mut v8::PinScope,
4620 args: v8::FunctionCallbackArguments,
4621 mut rv: v8::ReturnValue<v8::Value>,
4622) {
4623 let cell = args.get(0).to_rust_string_lossy(scope);
4624 let event = NEXT_GATE_EVENT.fetch_add(1, Ordering::Relaxed);
4625 // Taken under the gates lock so the test and the take are one step: a
4626 // release landing between them would leave this block queued behind a
4627 // gate that is already open.
4628 let taken = cell_gates()
4629 .lock()
4630 .unwrap()
4631 .entry(cell.clone())
4632 .or_default()
4633 .acquire(event);
4634 if taken {
4635 let id = asyncrt::enqueue(async move { Ok(event.to_string()) });
4636 rv.set(promise_for(scope, id));
4637 return;
4638 }
4639 let id = asyncrt::enqueue(async move {
4640 loop {
4641 // Ask for a ticket first: `cell_gate_wait` tests and enqueues
4642 // under the gates lock, so a release landing between the two
4643 // cannot leave this waiter behind an open gate.
4644 let waiting = cell_gate_wait(&cell);
4645 let taken = cell_gates()
4646 .lock()
4647 .unwrap()
4648 .entry(cell.clone())
4649 .or_default()
4650 .acquire(event);
4651 if taken {
4652 return Ok(event.to_string());
4653 }
4654 match waiting {
4655 Some(open) => match open.await {
4656 Ok(Ok(())) => {}
4657 // The block ahead of this one failed and reset the cell,
4658 // so this block has nothing left to guard.
4659 Ok(Err(failure)) => return Err(failure),
4660 Err(_) => {
4661 return Err("cell stopped while waiting for its input gate".to_string())
4662 }
4663 },
4664 // The gate was open when we asked and shut before we took
4665 // it: another block won the race. Yield rather than spin —
4666 // this runs on a tokio worker, and a bare `continue` here
4667 // starved the runtime.
4668 None => tokio::task::yield_now().await,
4669 }
4670 }
4671 });
4672 rv.set(promise_for(scope, id));
4673}
4674
4675/// `__gate_wait(scope)` — settle when the cell's input gate is open.
4676///
4677/// The gate's other side. `op_gate_acquire` is for something that wants to
4678/// *hold* the gate; this is for something that only has to arrive after it,
4679/// which is every event the gate exists to hold back. A drive does this in
4680/// Rust before it begins a turn; an RPC stub op does it here, because it is
4681/// dispatched inside the isolate and never becomes a drive.
4682///
4683/// Rejecting matters as much as resolving: a critical section that failed
4684/// reset the cell, so what waited behind it is refused with the reason
4685/// rather than run against state that no longer exists.
4686fn op_gate_wait(
4687 scope: &mut v8::PinScope,
4688 args: v8::FunctionCallbackArguments,
4689 mut rv: v8::ReturnValue<v8::Value>,
4690) {
4691 let cell = args.get(0).to_rust_string_lossy(scope);
4692 let id = asyncrt::enqueue(async move {
4693 loop {
4694 match cell_gate_wait(&cell) {
4695 None => return Ok(String::new()),
4696 Some(open) => match open.await {
4697 Ok(Ok(())) => {}
4698 Ok(Err(failure)) => return Err(failure),
4699 Err(_) => {
4700 return Err("cell stopped while waiting for its input gate".to_string())
4701 }
4702 },
4703 }
4704 }
4705 });
4706 rv.set(promise_for(scope, id));
4707}
4708
4709/// `__gate_release(scope, event)` — the block is over. The next delivery
4710/// point to run takes whatever queued behind it.
4711fn op_gate_release(
4712 scope: &mut v8::PinScope,
4713 args: v8::FunctionCallbackArguments,
4714 _rv: v8::ReturnValue<v8::Value>,
4715) {
4716 let cell = args.get(0).to_rust_string_lossy(scope);
4717 let event = args.get(1).number_value(scope).unwrap_or_default() as celld_logic::gate::EventId;
4718 // A third argument means the block failed and the actor was reset, so
4719 // what queued behind it is refused with that reason rather than
4720 // delivered to a cell whose state is gone.
4721 let failure = args.get(2);
4722 let outcome = if failure.is_null_or_undefined() {
4723 Ok(())
4724 } else {
4725 Err(failure.to_rust_string_lossy(scope))
4726 };
4727 if let Some(gate) = cell_gates().lock().unwrap().get_mut(&cell) {
4728 gate.release(event);
4729 }
4730 wake_gate_waiters(&cell, outcome);
4731}
4732
4733fn op_timer_alloc(
4734 scope: &mut v8::PinScope,
4735 _args: v8::FunctionCallbackArguments,
4736 mut rv: v8::ReturnValue<v8::Value>,
4737) {
4738 let id = v8::Number::new(scope, NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64);
4739 rv.set(id.into());
4740}
4741
4742fn op_timer_cancel(
4743 scope: &mut v8::PinScope,
4744 args: v8::FunctionCallbackArguments,
4745 _rv: v8::ReturnValue<v8::Value>,
4746) {
4747 let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
4748 if let Some(cancel) = timer_cancels().lock().unwrap().remove(&timer_id) {
4749 let _ = cancel.send(());
4750 }
4751}
4752
4753fn durable_object_id_key(namespace_key: &str) -> [u8; 32] {
4754 DO_ID_KEYS.with(|keys| {
4755 if let Some(key) = keys.borrow().get(namespace_key) {
4756 return *key;
4757 }
4758 use sha2::Digest;
4759 let key: [u8; 32] = sha2::Sha256::digest(namespace_key.as_bytes()).into();
4760 keys.borrow_mut().insert(namespace_key.to_string(), key);
4761 key
4762 })
4763}
4764
4765fn durable_object_id_hmac(key: &[u8; 32], input: &[u8]) -> hmac::Hmac<sha2::Sha256> {
4766 use hmac::Mac;
4767 let mut mac = <hmac::Hmac<sha2::Sha256> as hmac::Mac>::new_from_slice(key)
4768 .expect("SHA-256 accepts any HMAC key");
4769 mac.update(input);
4770 mac
4771}
4772
4773/// Ids already derived on this thread, keyed by namespace and name.
4774///
4775/// `getByName` costs two HMAC-SHA256 rounds, and a profile of `/c/hello`
4776/// found them among the largest terms the stateless path does not have —
4777/// the same name resolving to the same id, recomputed on every request.
4778///
4779/// Per thread and unsynchronised, which is sound because the derivation is
4780/// a pure function of its inputs: a worker that has not seen a name pays
4781/// for it once, and no answer can differ between threads. Bounded because
4782/// names come from the application, and cleared wholesale at the cap rather
4783/// than evicted one at a time — a cache this cheap to refill does not earn
4784/// an LRU.
4785const DO_ID_CACHE_MAX: usize = 4096;
4786
4787fn durable_object_id_for_name(namespace_key: &str, name: &str) -> [u8; 32] {
4788 use hmac::Mac;
4789
4790 thread_local! {
4791 static IDS: RefCell<HashMap<(String, String), [u8; 32]>> =
4792 RefCell::new(HashMap::new());
4793 }
4794 let cached = IDS.with(|ids| {
4795 ids.borrow()
4796 .get(&(namespace_key.to_string(), name.to_string()))
4797 .copied()
4798 });
4799 if let Some(id) = cached {
4800 return id;
4801 }
4802
4803 let key = durable_object_id_key(namespace_key);
4804 let mut id = [0_u8; 32];
4805 let digest = durable_object_id_hmac(&key, name.as_bytes())
4806 .finalize()
4807 .into_bytes();
4808 id[..16].copy_from_slice(&digest[..16]);
4809 let digest = durable_object_id_hmac(&key, &id[..16])
4810 .finalize()
4811 .into_bytes();
4812 id[16..].copy_from_slice(&digest[..16]);
4813
4814 IDS.with(|ids| {
4815 let mut ids = ids.borrow_mut();
4816 if ids.len() >= DO_ID_CACHE_MAX {
4817 ids.clear();
4818 }
4819 ids.insert((namespace_key.to_string(), name.to_string()), id);
4820 });
4821 id
4822}
4823
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.
4827const D1_NAMESPACE_KEY: &str = "cells:v1:d1:__D1Database";
4828
4829pub(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.
4841pub 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
4846fn durable_object_id_hex(bytes: &[u8; 32]) -> String {
4847 const HEX: &[u8; 16] = b"0123456789abcdef";
4848 let mut output = String::with_capacity(64);
4849 for byte in bytes {
4850 output.push(HEX[(byte >> 4) as usize] as char);
4851 output.push(HEX[(byte & 0x0f) as usize] as char);
4852 }
4853 output
4854}
4855
4856fn decode_durable_object_id(value: &str) -> Option<[u8; 32]> {
4857 if value.len() != 64 {
4858 return None;
4859 }
4860 let mut output = [0_u8; 32];
4861 for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
4862 let nibble = |byte| match byte {
4863 b'0'..=b'9' => Some(byte - b'0'),
4864 b'a'..=b'f' => Some(byte - b'a' + 10),
4865 b'A'..=b'F' => Some(byte - b'A' + 10),
4866 _ => None,
4867 };
4868 output[index] = (nibble(pair[0])? << 4) | nibble(pair[1])?;
4869 }
4870 Some(output)
4871}
4872
4873fn throw_durable_object_id_error(scope: &mut v8::PinScope, message: &str) {
4874 let message = v8::String::new(scope, message).unwrap();
4875 let exception = v8::Exception::type_error(scope, message);
4876 scope.throw_exception(exception);
4877}
4878
4879fn register_actor_name(
4880 scope: &mut v8::PinScope,
4881 actor_scope: &str,
4882 name: Option<&str>,
4883) -> Result<()> {
4884 let Some(name) = name else {
4885 return Ok(());
4886 };
4887 let context = scope.get_current_context();
4888 let global = context.global(scope);
4889 let cell_key = v8::String::new(scope, "__cell").unwrap();
4890 let cell = global
4891 .get(scope, cell_key.into())
4892 .and_then(|value| value.to_object(scope))
4893 .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
4894 let names_key = v8::String::new(scope, "idNames").unwrap();
4895 let names = cell
4896 .get(scope, names_key.into())
4897 .and_then(|value| value.to_object(scope))
4898 .ok_or_else(|| anyhow!("missing Durable Object name registry"))?;
4899 let actor_scope_key = v8::String::new(scope, actor_scope).unwrap();
4900 if let Some(existing) = names.get(scope, actor_scope_key.into()) {
4901 if !existing.is_undefined() {
4902 if existing.to_rust_string_lossy(scope) == name {
4903 return Ok(());
4904 }
4905 anyhow::bail!("actor name conflicts with active identity for {actor_scope}");
4906 }
4907 }
4908
4909 let (class_name, id) = actor_scope
4910 .split_once(':')
4911 .ok_or_else(|| anyhow!("named Durable Object scope has no class separator"))?;
4912 let namespace_keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
4913 let namespace_keys = cell
4914 .get(scope, namespace_keys_key.into())
4915 .and_then(|value| value.to_object(scope))
4916 .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
4917 let class_name_key = v8::String::new(scope, class_name).unwrap();
4918 let namespace_key = namespace_keys
4919 .get(scope, class_name_key.into())
4920 .filter(|value| value.is_string())
4921 .ok_or_else(|| anyhow!("missing namespace key for Durable Object class {class_name}"))?
4922 .to_rust_string_lossy(scope);
4923 let expected = durable_object_id_hex(&durable_object_id_for_name(&namespace_key, name));
4924 if id != expected {
4925 anyhow::bail!("actor name does not match Durable Object ID for {actor_scope}");
4926 }
4927 storage::set_actor_name(actor_scope, name)?;
4928
4929 let name_value = v8::String::new(scope, name).unwrap();
4930 if !names
4931 .set(scope, actor_scope_key.into(), name_value.into())
4932 .unwrap_or(false)
4933 {
4934 anyhow::bail!("could not register Durable Object name");
4935 }
4936 Ok(())
4937}
4938
4939fn op_do_id(
4940 scope: &mut v8::PinScope,
4941 args: v8::FunctionCallbackArguments,
4942 mut rv: v8::ReturnValue<v8::Value>,
4943) {
4944 use hmac::Mac;
4945
4946 let namespace_key = args.get(0).to_rust_string_lossy(scope);
4947 let operation = args.get(1).to_rust_string_lossy(scope);
4948 let input = args.get(2).to_rust_string_lossy(scope);
4949 let key = durable_object_id_key(&namespace_key);
4950 let mut id = [0_u8; 32];
4951
4952 match operation.as_str() {
4953 "name" => {
4954 id = durable_object_id_for_name(&namespace_key, &input);
4955 rv.set(
4956 v8::String::new(scope, &durable_object_id_hex(&id))
4957 .unwrap()
4958 .into(),
4959 );
4960 return;
4961 }
4962 "unique" => {
4963 if getrandom::fill(&mut id[..16]).is_err() {
4964 throw_durable_object_id_error(scope, "secure random generation failed");
4965 return;
4966 }
4967 }
4968 "validate" => {
4969 let Some(decoded) = decode_durable_object_id(&input) else {
4970 throw_durable_object_id_error(
4971 scope,
4972 "Invalid Durable Object ID: must be 64 hex digits",
4973 );
4974 return;
4975 };
4976 if durable_object_id_hmac(&key, &decoded[..16])
4977 .verify_truncated_left(&decoded[16..])
4978 .is_err()
4979 {
4980 throw_durable_object_id_error(
4981 scope,
4982 "Durable Object ID is not valid for this namespace",
4983 );
4984 return;
4985 }
4986 rv.set(
4987 v8::String::new(scope, &input.to_ascii_lowercase())
4988 .unwrap()
4989 .into(),
4990 );
4991 return;
4992 }
4993 _ => {
4994 throw_durable_object_id_error(scope, "unknown Durable Object ID operation");
4995 return;
4996 }
4997 }
4998
4999 let digest = durable_object_id_hmac(&key, &id[..16])
5000 .finalize()
5001 .into_bytes();
5002 id[16..].copy_from_slice(&digest[..16]);
5003 rv.set(
5004 v8::String::new(scope, &durable_object_id_hex(&id))
5005 .unwrap()
5006 .into(),
5007 );
5008}
5009
5010fn view_bytes(value: v8::Local<v8::Value>) -> Option<Vec<u8>> {
5011 let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
5012 let mut bytes = vec![0_u8; view.byte_length()];
5013 view.copy_contents(&mut bytes);
5014 Some(bytes)
5015}
5016
5017fn webcrypto_return_bytes(
5018 scope: &mut v8::PinScope,
5019 mut rv: v8::ReturnValue<v8::Value>,
5020 bytes: &[u8],
5021) {
5022 let buffer = v8::ArrayBuffer::new(scope, bytes.len());
5023 if !bytes.is_empty() {
5024 let store = buffer.get_backing_store();
5025 let destination = unsafe {
5026 std::slice::from_raw_parts_mut(store.data().unwrap().as_ptr() as *mut u8, bytes.len())
5027 };
5028 destination.copy_from_slice(bytes);
5029 }
5030 let view = v8::Uint8Array::new(scope, buffer, 0, bytes.len()).unwrap();
5031 rv.set(view.into());
5032}
5033
5034mod crypto;
5035mod zlib;
5036
5037fn op_actor_abort(
5038 scope: &mut v8::PinScope,
5039 args: v8::FunctionCallbackArguments,
5040 _rv: v8::ReturnValue<v8::Value>,
5041) {
5042 let cell = args.get(0).to_rust_string_lossy(scope);
5043 let reason = args.get(1).to_rust_string_lossy(scope);
5044 let state = actor_runtime_state(scope);
5045 state
5046 .pending_puts
5047 .lock()
5048 .expect("pending puts lock poisoned")
5049 .remove(&cell);
5050 *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
5051 error: format!("__CELLD_ACTOR_ABORT__:{reason}"),
5052 actor_scope: Some(cell),
5053 });
5054 scope.terminate_execution();
5055}
5056
5057fn op_process_exit(
5058 scope: &mut v8::PinScope,
5059 args: v8::FunctionCallbackArguments,
5060 _rv: v8::ReturnValue<v8::Value>,
5061) {
5062 let code = args.get(0).integer_value(scope).unwrap_or(0);
5063 if current_context().depth() == 0 {
5064 tracing::warn!(
5065 code,
5066 "process.exit called without an active request; ignoring"
5067 );
5068 return;
5069 }
5070 let actor_scope = args.get(1).to_rust_string_lossy(scope);
5071 let actor_scope = (!actor_scope.is_empty()).then_some(actor_scope);
5072 let state = actor_runtime_state(scope);
5073 if let Some(actor_scope) = actor_scope.as_deref() {
5074 state
5075 .pending_puts
5076 .lock()
5077 .expect("pending puts lock poisoned")
5078 .remove(actor_scope);
5079 }
5080 *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
5081 error: format!("__CELLD_PROCESS_EXIT__:The Node.js process.exit({code}) API was called."),
5082 actor_scope,
5083 });
5084 scope.terminate_execution();
5085}
5086
5087fn op_log(
5088 scope: &mut v8::PinScope,
5089 args: v8::FunctionCallbackArguments,
5090 _rv: v8::ReturnValue<v8::Value>,
5091) {
5092 let msg: Vec<String> = (0..args.length())
5093 .map(|i| args.get(i).to_rust_string_lossy(scope))
5094 .collect();
5095 let body = msg.join(" ");
5096 // Correlated by CPED, so a continuation logging after an await — or
5097 // another entry's continuation running in this turn's checkpoint —
5098 // lands on the trace that owns it, not on whoever holds the isolate.
5099 if crate::telemetry::active() {
5100 let ids = current_trace_ids(scope);
5101 crate::telemetry::record_log(crate::telemetry::Log {
5102 trace_id: ids.as_ref().map(|ids| ids.trace_id),
5103 span_id: ids.as_ref().map(|ids| ids.span_id),
5104 time_unix_us: crate::telemetry::now_unix_us(),
5105 body: body.clone(),
5106 });
5107 }
5108 tracing::info!(target: "cell_console", "{}", body);
5109}
5110fn op_heap_limit_excessively_exceeded(
5111 scope: &mut v8::PinScope,
5112 _args: v8::FunctionCallbackArguments,
5113 mut rv: v8::ReturnValue<v8::Value>,
5114) {
5115 let exceeded = scope
5116 .get_slot::<Arc<HeapLimitState>>()
5117 .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed));
5118 rv.set(v8::Boolean::new(scope, exceeded).into());
5119}
5120/// Whether this isolate is too close to its heap limit to retain more state.
5121fn 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}
5140#[cfg(all(test, celld_internal_tests))]
5141fn op_test_set_heap_limit_excessively_exceeded(
5142 scope: &mut v8::PinScope,
5143 args: v8::FunctionCallbackArguments,
5144 _rv: v8::ReturnValue<v8::Value>,
5145) {
5146 if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() {
5147 state
5148 .excessively_exceeded
5149 .store(args.get(0).boolean_value(scope), Ordering::Relaxed);
5150 }
5151}
5152#[cfg(all(test, celld_internal_tests))]
5153fn 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))]
5165fn op_test_gc(
5166 scope: &mut v8::PinScope,
5167 _args: v8::FunctionCallbackArguments,
5168 _rv: v8::ReturnValue<v8::Value>,
5169) {
5170 scope.request_garbage_collection_for_testing(v8::GarbageCollectionType::Full);
5171}
5172mod storage_ops;
5173use storage_ops::{actor_runtime_state, throw_storage_error};
5174
5175/// $$urlParse(input, base?) -> {protocol,username,password,host,port,pathname,search,hash,href}
5176/// Backed by the WHATWG-conformant `url` crate.
5177fn op_url_parse(
5178 scope: &mut v8::PinScope,
5179 args: v8::FunctionCallbackArguments,
5180 mut rv: v8::ReturnValue<v8::Value>,
5181) {
5182 let input = args.get(0).to_rust_string_lossy(scope);
5183 let base = args.get(1);
5184 let parsed = if base.is_undefined() {
5185 url::Url::parse(&input)
5186 } else {
5187 url::Url::options()
5188 .base_url(
5189 url::Url::parse(&base.to_rust_string_lossy(scope))
5190 .ok()
5191 .as_ref(),
5192 )
5193 .parse(&input)
5194 };
5195 let u = match parsed {
5196 Ok(u) => u,
5197 Err(e) => {
5198 let msg = v8::String::new(scope, &format!("Invalid URL: {e}")).unwrap();
5199 let exc = v8::Exception::type_error(scope, msg);
5200 scope.throw_exception(exc);
5201 return;
5202 }
5203 };
5204 let o = v8::Object::new(scope);
5205 let set = |k: &str, v: &str| {
5206 let key = v8::String::new(scope, k).unwrap();
5207 let val = v8::String::new(scope, v).unwrap();
5208 o.set(scope, key.into(), val.into());
5209 };
5210 set("protocol", u.scheme());
5211 set("username", u.username());
5212 set("password", u.password().unwrap_or(""));
5213 set("host", u.host_str().unwrap_or(""));
5214 set("port", &u.port().map(|p| p.to_string()).unwrap_or_default());
5215 set("pathname", u.path());
5216 set("search", u.query().unwrap_or(""));
5217 set("hash", u.fragment().unwrap_or(""));
5218 set("href", u.as_str());
5219 rv.set(o.into());
5220}
5221
5222// URLPattern host seam, split like Deno's: pattern parsing and match-input
5223// canonicalization run in Rust via the `urlpattern` crate; per-match regex
5224// execution stays in JS `RegExp` (src/js/url_pattern.js). JSON is the
5225// boundary — both ops run at construct/match-canonicalize time only.
5226
5227/// `$$urlPatternParse(inputJson, baseURL?, ignoreCase)` -> json. Input is a
5228/// pattern string or an init object of string components. Returns
5229/// per-component `{ patternString, regexpString, groupNameList }` plus
5230/// `hasRegexpGroups`. Throws TypeError on an invalid pattern.
5231fn op_urlpattern_parse(
5232 scope: &mut v8::PinScope,
5233 args: v8::FunctionCallbackArguments,
5234 mut rv: v8::ReturnValue<v8::Value>,
5235) {
5236 use urlpattern::quirks;
5237 let input = args.get(0).to_rust_string_lossy(scope);
5238 let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
5239 let base = args.get(1);
5240 let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
5241 let options = urlpattern::UrlPatternOptions {
5242 ignore_case: args.get(2).boolean_value(scope),
5243 };
5244 let pattern = quirks::process_construct_pattern_input(input, base.as_deref())
5245 .and_then(|init| quirks::parse_pattern(init, options));
5246 let p = match pattern {
5247 Ok(p) => p,
5248 Err(e) => {
5249 let msg = v8::String::new(scope, &e.to_string()).unwrap();
5250 let exc = v8::Exception::type_error(scope, msg);
5251 scope.throw_exception(exc);
5252 return;
5253 }
5254 };
5255 let component = |c: &quirks::UrlPatternComponent| {
5256 serde_json::json!({
5257 "patternString": c.pattern_string,
5258 "regexpString": c.regexp_string,
5259 "groupNameList": c.group_name_list,
5260 })
5261 };
5262 let out = serde_json::json!({
5263 "protocol": component(&p.protocol),
5264 "username": component(&p.username),
5265 "password": component(&p.password),
5266 "hostname": component(&p.hostname),
5267 "port": component(&p.port),
5268 "pathname": component(&p.pathname),
5269 "search": component(&p.search),
5270 "hash": component(&p.hash),
5271 "hasRegexpGroups": p.has_regexp_groups,
5272 });
5273 rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5274}
5275
5276/// `$$urlPatternMatchInput(inputJson, baseURL?)` -> json `[8 strings]` in
5277/// component order (protocol..hash), or `null` when the input does not parse
5278/// as a URL. Throws TypeError for an init combined with a baseURL argument.
5279fn op_urlpattern_match_input(
5280 scope: &mut v8::PinScope,
5281 args: v8::FunctionCallbackArguments,
5282 mut rv: v8::ReturnValue<v8::Value>,
5283) {
5284 use urlpattern::quirks;
5285 let input = args.get(0).to_rust_string_lossy(scope);
5286 let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
5287 let base = args.get(1);
5288 let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
5289 let null = v8::null(scope).into();
5290 let m = match quirks::process_match_input(input, base.as_deref()) {
5291 Ok(Some((input_, _inputs))) => match quirks::parse_match_input(input_) {
5292 Some(m) => m,
5293 None => return rv.set(null),
5294 },
5295 Ok(None) => return rv.set(null),
5296 Err(e) => {
5297 let msg = v8::String::new(scope, &e.to_string()).unwrap();
5298 let exc = v8::Exception::type_error(scope, msg);
5299 scope.throw_exception(exc);
5300 return;
5301 }
5302 };
5303 let out = serde_json::json!([
5304 m.protocol, m.username, m.password, m.hostname, m.port, m.pathname, m.search, m.hash,
5305 ]);
5306 rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
5307}
5308
5309fn op_atob(
5310 scope: &mut v8::PinScope,
5311 args: v8::FunctionCallbackArguments,
5312 mut rv: v8::ReturnValue<v8::Value>,
5313) {
5314 use base64::Engine;
5315 let input = args.get(0).to_rust_string_lossy(scope);
5316 let cleaned: String = input.chars().filter(|c| !c.is_whitespace()).collect();
5317 match base64::engine::general_purpose::STANDARD.decode(cleaned) {
5318 Ok(bytes) => {
5319 // atob returns a binary string (latin1)
5320 let s: String = bytes.iter().map(|&b| b as char).collect();
5321 rv.set(v8::String::new(scope, &s).unwrap().into());
5322 }
5323 Err(_) => {
5324 let msg = v8::String::new(scope, "Invalid base64").unwrap();
5325 let exc = v8::Exception::error(scope, msg);
5326 scope.throw_exception(exc);
5327 }
5328 }
5329}
5330
5331// node:util introspection seam: V8-level queries that JS cannot perform,
5332// mirroring Workerd's C++ `node-internal:util` builtin. Only the lazy
5333// node:async_hooks prelude calls these. The value is V8's
5334// continuation-preserved embedder data — the primitive Workerd's
5335// AsyncContextFrame rides — which V8 itself captures and restores
5336// around every promise reaction. No promise hooks are installed, and an
5337// isolate that never touches AsyncLocalStorage never sets the value, so
5338// a bundle that does not import async_hooks pays nothing per promise.
5339
5340/// The per-request context: everything a request owns while it is in flight.
5341///
5342/// Modelled on workerd's `IoContext`. The host owns it, not JS: a request's
5343/// event frames and the `waitUntil` promises inside them live here, and JS
5344/// reaches them only through ops that ask for the *current* context. That
5345/// inversion is the point. While an isolate serves one request at a time,
5346/// JS-side per-request state is indistinguishable from isolate-side state,
5347/// and the two silently diverge the moment requests interleave — one
5348/// request's `__endEvent` popping another's event, its `waitUntil` work
5349/// attributed to a request that never asked for it.
5350///
5351/// `current()` is a thread-local the host installs for the duration of a
5352/// turn and restores on the way out, exactly as `threadLocalRequest` is set
5353/// in `IoContext::runInContextScope` and restored by `SuppressIoContextScope`.
5354/// An op that needs a context and finds none is a bug in the host, not in
5355/// the script, so it says so rather than inventing one.
5356///
5357/// **It is `Send + Sync`, and that is load-bearing.** Under D1 a request is
5358/// a tokio task that suspends between turns and can resume on any worker, so
5359/// the context it carries has to cross threads with it. `Rc` and `RefCell`
5360/// would forbid that, and the alternative — parking every live context in a
5361/// map inside the isolate, keyed by request id — rebuilds the very
5362/// demultiplexing table (`idmap`) that deleting the pump exists to remove.
5363/// So the interiors are `Mutex` instead. The locks are uncontended by
5364/// construction, because only the isolate's holder can reach a context, and
5365/// they are taken about twice per request.
5366pub struct IoContext {
5367 /// This caller's delivery order for each cell it has called. See
5368 /// `CallOrder` — it is here rather than in a process-wide map because
5369 /// nothing outside this caller ever reads it.
5370 call_chains: Mutex<CallChains>,
5371 /// Event frames, innermost last. A frame collects the `waitUntil`
5372 /// promises registered while it is the innermost one.
5373 ///
5374 /// Nesting is per-request and strictly LIFO — a service-binding
5375 /// dispatch, an RPC entry, or a DO construction pushes its own frame so
5376 /// its `waitUntil` binds to that dispatch, matching workerd.
5377 events: Mutex<Vec<Vec<v8::Global<v8::Promise>>>>,
5378 /// Isolate-polled sockets opened by each nested run loop of this
5379 /// request, innermost last. `asyncrt` aborts a region's pending ops when
5380 /// it exits; these are host-side resources abort cannot reach, so the
5381 /// region closes them itself.
5382 sockets: Mutex<Vec<Vec<u64>>>,
5383 /// Sockets opened before any run loop exists. A handler runs
5384 /// synchronously to its first await before its loop is entered, so a
5385 /// socket built at the top of a handler has no frame yet; the loop
5386 /// adopts these when it starts.
5387 pending_sockets: Mutex<Vec<u64>>,
5388 /// Output-gate capture. While a `webSocketMessage` runs, the frames it
5389 /// sends are collected here instead of reaching the wire, so the shell
5390 /// can hold them until the message's write is durable. A stack, so a
5391 /// nested dispatch keeps its frames apart from the outer one's.
5392 ///
5393 /// On the event and not on the thread, because an event outlives the
5394 /// turn that began it: capture starts in one turn and is taken in a
5395 /// later one, which tokio may run on a different worker.
5396 ws_capture: Mutex<Vec<Vec<(u64, WsOut)>>>,
5397 /// Which cell an event belongs to, and the committed-write position it
5398 /// started at, innermost last. An outbound effect raised during the
5399 /// event consults this: if the handler has advanced the position, the
5400 /// effect waits for the output gate before it leaves the process.
5401 ///
5402 /// Empty for stateless Worker code, which owns no cell and gates
5403 /// nothing.
5404 egress: Mutex<Vec<(String, u64)>>,
5405}
5406
5407impl IoContext {
5408 fn new() -> Arc<Self> {
5409 Arc::new(Self {
5410 call_chains: Mutex::new(CallChains::default()),
5411 events: Mutex::new(Vec::new()),
5412 sockets: Mutex::new(Vec::new()),
5413 pending_sockets: Mutex::new(Vec::new()),
5414 ws_capture: Mutex::new(Vec::new()),
5415 egress: Mutex::new(Vec::new()),
5416 })
5417 }
5418
5419 fn begin_event(&self) {
5420 self.events.lock().unwrap().push(Vec::new());
5421 }
5422
5423 /// Pop the innermost frame and hand back what it collected. `None` when
5424 /// there is no frame, which is a script calling `waitUntil` outside any
5425 /// event; the harness turns that into workerd's global-scope error.
5426 fn end_event(&self) -> Option<Vec<v8::Global<v8::Promise>>> {
5427 self.events.lock().unwrap().pop()
5428 }
5429
5430 fn register_wait_until(&self, promise: v8::Global<v8::Promise>) {
5431 if let Some(frame) = self.events.lock().unwrap().last_mut() {
5432 frame.push(promise);
5433 }
5434 }
5435
5436 fn depth(&self) -> usize {
5437 self.events.lock().unwrap().len()
5438 }
5439}
5440
5441/// What `OwnedIsolate::into_shared` demands of us: every slot value on a
5442/// shared isolate is reachable, and droppable, from whichever thread holds
5443/// the lock. The type system cannot check it at the call site, so it is
5444/// checked here instead.
5445const _: fn() = || {
5446 fn assert_send_sync<T: Send + Sync>() {}
5447 assert_send_sync::<HeapLimitState>();
5448 assert_send_sync::<ActorRuntimeState>();
5449 assert_send_sync::<ModuleRegistry>();
5450};
5451
5452/// A request must be able to carry its own context across a suspension. A
5453/// compile-time check, because losing it would surface as an unrelated
5454/// `Send` error wherever the request task is spawned.
5455const _: fn() = || {
5456 fn assert_send_sync<T: Send + Sync>() {}
5457 assert_send_sync::<Arc<IoContext>>();
5458};
5459
5460thread_local! {
5461 /// The request whose turn is running on this thread, or none between
5462 /// turns. Never set by JS.
5463 static CURRENT: RefCell<Option<Arc<IoContext>>> =
5464 const { RefCell::new(None) };
5465}
5466
5467/// Install `context` for the duration of a turn, restoring whatever was
5468/// current when the guard drops.
5469///
5470/// Restoring rather than clearing is what makes nested host dispatch safe: a
5471/// service binding runs a second handler inside the first one's turn, and the
5472/// outer request must still be current when it returns.
5473pub struct CurrentGuard(Option<Arc<IoContext>>);
5474
5475impl CurrentGuard {
5476 pub fn enter(context: Arc<IoContext>) -> Self {
5477 CurrentGuard(CURRENT.with(|current| current.borrow_mut().replace(context)))
5478 }
5479}
5480
5481impl Drop for CurrentGuard {
5482 fn drop(&mut self) {
5483 CURRENT.with(|current| *current.borrow_mut() = self.0.take());
5484 }
5485}
5486
5487/// The context this turn belongs to.
5488///
5489/// A thread that has not had one installed gets a default: every path that
5490/// runs JS without an explicit request context — a cell isolate, which the
5491/// DO contract already serializes, an RPC entry, a DO constructor — keeps
5492/// exactly the semantics it had when the stack lived in JS, one per isolate.
5493/// Isolation is a property of *installing* a context, so it arrives with the
5494/// paths that need it rather than being retrofitted to every caller at once.
5495fn current_context() -> Arc<IoContext> {
5496 CURRENT.with(|current| {
5497 let mut current = current.borrow_mut();
5498 current.get_or_insert_with(IoContext::new).clone()
5499 })
5500}
5501
5502fn op_event_begin(
5503 scope: &mut v8::PinScope,
5504 _args: v8::FunctionCallbackArguments,
5505 _rv: v8::ReturnValue<v8::Value>,
5506) {
5507 let _ = scope;
5508 current_context().begin_event();
5509}
5510
5511/// Pop the innermost event and return the aggregate of its `waitUntil`
5512/// promises, or null when it collected none. The aggregate is built here
5513/// rather than in JS because the promises live here: the host holds them for
5514/// the request, and the request is what the frame belongs to.
5515fn op_event_end<'s>(
5516 scope: &mut v8::PinScope<'s, '_>,
5517 _args: v8::FunctionCallbackArguments,
5518 mut rv: v8::ReturnValue<v8::Value>,
5519) {
5520 let Some(frame) = current_context().end_event() else {
5521 rv.set_null();
5522 return;
5523 };
5524 if frame.is_empty() {
5525 rv.set_null();
5526 return;
5527 }
5528 let promises: Vec<v8::Local<v8::Value>> = frame
5529 .iter()
5530 .map(|promise| v8::Local::new(scope, promise).into())
5531 .collect();
5532 let array = v8::Array::new_with_elements(scope, &promises);
5533 match all_settled(scope, array.into()) {
5534 Some(aggregate) => rv.set(aggregate),
5535 None => rv.set_null(),
5536 }
5537}
5538
5539fn op_wait_until<'s>(
5540 scope: &mut v8::PinScope<'s, '_>,
5541 args: v8::FunctionCallbackArguments<'s>,
5542 _rv: v8::ReturnValue<v8::Value>,
5543) {
5544 let value = args.get(0);
5545 let promise = match value.try_cast::<v8::Promise>() {
5546 Ok(promise) => promise,
5547 Err(_) => match resolved_promise(scope, value) {
5548 Ok(promise) => promise,
5549 Err(_) => return,
5550 },
5551 };
5552 current_context().register_wait_until(v8::Global::new(scope, promise));
5553}
5554
5555/// How many events are open on the current request. The harness uses it for
5556/// workerd's global-scope error, which fires when `waitUntil` is imported and
5557/// called with no event in progress.
5558fn op_event_depth(
5559 scope: &mut v8::PinScope,
5560 _args: v8::FunctionCallbackArguments,
5561 mut rv: v8::ReturnValue<v8::Value>,
5562) {
5563 let depth = current_context().depth();
5564 rv.set(v8::Integer::new(scope, depth as i32).into());
5565}
5566
5567/// `Promise.allSettled(values)`, from the context's own realm.
5568fn all_settled<'s>(
5569 scope: &mut v8::PinScope<'s, '_>,
5570 values: v8::Local<'s, v8::Value>,
5571) -> Option<v8::Local<'s, v8::Value>> {
5572 let global = scope.get_current_context().global(scope);
5573 let key = v8::String::new(scope, "Promise").unwrap();
5574 let promise_ctor: v8::Local<v8::Object> = global.get(scope, key.into())?.try_into().ok()?;
5575 let key = v8::String::new(scope, "allSettled").unwrap();
5576 let all_settled: v8::Local<v8::Function> =
5577 promise_ctor.get(scope, key.into())?.try_into().ok()?;
5578 all_settled.call(scope, promise_ctor.into(), &[values])
5579}
5580
5581fn op_als_get(
5582 scope: &mut v8::PinScope,
5583 _args: v8::FunctionCallbackArguments,
5584 mut rv: v8::ReturnValue<v8::Value>,
5585) {
5586 rv.set(cped_frame(scope));
5587}
5588
5589fn op_als_set(
5590 scope: &mut v8::PinScope,
5591 args: v8::FunctionCallbackArguments,
5592 _rv: v8::ReturnValue<v8::Value>,
5593) {
5594 let trace = cped_trace(scope);
5595 set_cped(scope, args.get(0), trace);
5596}
5597
5598// node:util prelude calls these; registration is the sole per-isolate cost.
5599
5600/// Type-check bitmask. Bit order must match `T` in src/js/node_util.js.
5601fn op_util_type_flags(
5602 _scope: &mut v8::PinScope,
5603 args: v8::FunctionCallbackArguments,
5604 mut rv: v8::ReturnValue<v8::Value>,
5605) {
5606 let v = args.get(0);
5607 let checks: [bool; 27] = [
5608 v.is_external(),
5609 v.is_date(),
5610 v.is_arguments_object(),
5611 v.is_big_int_object(),
5612 v.is_boolean_object(),
5613 v.is_number_object(),
5614 v.is_string_object(),
5615 v.is_symbol_object(),
5616 v.is_native_error(),
5617 v.is_reg_exp(),
5618 v.is_async_function(),
5619 v.is_generator_function(),
5620 v.is_generator_object(),
5621 v.is_promise(),
5622 v.is_map(),
5623 v.is_set(),
5624 v.is_map_iterator(),
5625 v.is_set_iterator(),
5626 v.is_weak_map(),
5627 v.is_weak_set(),
5628 v.is_array_buffer(),
5629 v.is_data_view(),
5630 v.is_shared_array_buffer(),
5631 v.is_proxy(),
5632 v.is_module_namespace_object(),
5633 v.is_typed_array(),
5634 v.is_array_buffer_view(),
5635 ];
5636 let mut flags: u32 = 0;
5637 for (i, hit) in checks.iter().enumerate() {
5638 if *hit {
5639 flags |= 1 << i;
5640 }
5641 }
5642 rv.set_uint32(flags);
5643}
5644
5645fn op_util_constructor_name(
5646 _scope: &mut v8::PinScope,
5647 args: v8::FunctionCallbackArguments,
5648 mut rv: v8::ReturnValue<v8::Value>,
5649) {
5650 let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
5651 return; // undefined
5652 };
5653 rv.set(obj.get_constructor_name().into());
5654}
5655
5656/// `[target, handler]` for a proxy, undefined otherwise.
5657fn op_util_proxy_details(
5658 scope: &mut v8::PinScope,
5659 args: v8::FunctionCallbackArguments,
5660 mut rv: v8::ReturnValue<v8::Value>,
5661) {
5662 let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(args.get(0)) else {
5663 return;
5664 };
5665 let target = proxy.get_target(scope);
5666 let handler = proxy.get_handler(scope);
5667 rv.set(v8::Array::new_with_elements(scope, &[target, handler]).into());
5668}
5669
5670/// `[state]` for a pending promise, `[state, result]` otherwise,
5671/// undefined for a non-promise. States: 0 pending, 1 fulfilled, 2 rejected.
5672fn op_util_promise_details(
5673 scope: &mut v8::PinScope,
5674 args: v8::FunctionCallbackArguments,
5675 mut rv: v8::ReturnValue<v8::Value>,
5676) {
5677 let Ok(promise) = v8::Local::<v8::Promise>::try_from(args.get(0)) else {
5678 return;
5679 };
5680 let state = match promise.state() {
5681 v8::PromiseState::Pending => 0,
5682 v8::PromiseState::Fulfilled => 1,
5683 v8::PromiseState::Rejected => 2,
5684 };
5685 let pending = state == 0;
5686 let state: v8::Local<v8::Value> = v8::Integer::new(scope, state).into();
5687 let elements = if pending {
5688 vec![state]
5689 } else {
5690 vec![state, promise.result(scope)]
5691 };
5692 rv.set(v8::Array::new_with_elements(scope, &elements).into());
5693}
5694
5695/// `[entries, isKeyValue]` for collections and their iterators (V8's
5696/// PreviewEntries), undefined when V8 has no preview.
5697fn op_util_preview_entries(
5698 scope: &mut v8::PinScope,
5699 args: v8::FunctionCallbackArguments,
5700 mut rv: v8::ReturnValue<v8::Value>,
5701) {
5702 let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
5703 return;
5704 };
5705 let (entries, is_key_value) = obj.preview_entries(scope);
5706 let Some(entries) = entries else { return };
5707 let flag: v8::Local<v8::Value> = v8::Boolean::new(scope, is_key_value).into();
5708 rv.set(v8::Array::new_with_elements(scope, &[entries.into(), flag]).into());
5709}
5710
5711fn op_alarm_set(
5712 scope: &mut v8::PinScope,
5713 args: v8::FunctionCallbackArguments,
5714 _rv: v8::ReturnValue<v8::Value>,
5715) {
5716 let s = args.get(0).to_rust_string_lossy(scope);
5717 let at = args.get(1).number_value(scope).unwrap_or(0.0) as i64;
5718 match storage::set_alarm(&s, at) {
5719 Err(error) => throw_storage_error(scope, "setAlarm", error),
5720 // Committed immediately: register the wake-entry PUT against the
5721 // cell's output gate. Inside an explicit transaction (`Ok(None)`)
5722 // the gate registers at that transaction's commit instead.
5723 Ok(Some(committed)) if committed >= 0 => spawn_arm_gate(&s, committed),
5724 Ok(_) => {}
5725 }
5726}
5727fn op_alarm_get(
5728 scope: &mut v8::PinScope,
5729 args: v8::FunctionCallbackArguments,
5730 mut rv: v8::ReturnValue<v8::Value>,
5731) {
5732 let s = args.get(0).to_rust_string_lossy(scope);
5733 match storage::get_alarm(&s) {
5734 Some(at) => rv.set(v8::Number::new(scope, at as f64).into()),
5735 None => rv.set(v8::null(scope).into()),
5736 }
5737}
5738fn op_alarm_delete(
5739 scope: &mut v8::PinScope,
5740 args: v8::FunctionCallbackArguments,
5741 _rv: v8::ReturnValue<v8::Value>,
5742) {
5743 let s = args.get(0).to_rust_string_lossy(scope);
5744 if let Err(error) = storage::delete_alarm(&s) {
5745 throw_storage_error(scope, "deleteAlarm", error);
5746 }
5747}
5748
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.
5759fn 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
5834fn op_btoa(
5835 scope: &mut v8::PinScope,
5836 args: v8::FunctionCallbackArguments,
5837 mut rv: v8::ReturnValue<v8::Value>,
5838) {
5839 use base64::Engine;
5840 let input = args.get(0).to_rust_string_lossy(scope);
5841 let bytes: Vec<u8> = input.chars().map(|c| c as u8).collect();
5842 let s = base64::engine::general_purpose::STANDARD.encode(bytes);
5843 rv.set(v8::String::new(scope, &s).unwrap().into());
5844}
5845
5846// ---- WHATWG text decoders (encoding_rs) ----
5847//
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
5855// one on the final decode (last=true), on a fatal error (encoding_rs
5856// poisons an errored decoder), or via FinalizationRegistry when a
5857// mid-stream decoder is abandoned. Ids are never reused, so a late
5858// finalizer free of an already-closed id is a no-op.
5859
5860/// Live streaming decoders for one isolate, keyed by an id JS holds across
5861/// awaits.
5862///
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)]
5889struct TextDecoders(HashMap<u64, encoding_rs::Decoder>);
5890
5891static TEXT_DECODER_NEXT: AtomicU64 = AtomicU64::new(1);
5892
5893/// The calling isolate's decoder table, created on first use.
5894fn 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
5899}
5900
5901/// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined
5902/// for unknown labels and the replacement encoding (RangeError in JS).
5903fn op_text_decoder_label(
5904 scope: &mut v8::PinScope,
5905 args: v8::FunctionCallbackArguments,
5906 mut rv: v8::ReturnValue<v8::Value>,
5907) {
5908 let label = args.get(0).to_rust_string_lossy(scope);
5909 if let Some(enc) = encoding_rs::Encoding::for_label_no_replacement(label.as_bytes()) {
5910 let name = enc.name().to_ascii_lowercase();
5911 rv.set(v8::String::new(scope, &name).unwrap().into());
5912 }
5913}
5914
5915/// `$$textDecoderNew(name, ignoreBOM)` -> id.
5916fn op_text_decoder_new(
5917 scope: &mut v8::PinScope,
5918 args: v8::FunctionCallbackArguments,
5919 mut rv: v8::ReturnValue<v8::Value>,
5920) {
5921 let name = args.get(0).to_rust_string_lossy(scope);
5922 let ignore_bom = args.get(1).boolean_value(scope);
5923 let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label");
5924 let dec = if ignore_bom {
5925 enc.new_decoder_without_bom_handling()
5926 } else {
5927 enc.new_decoder_with_bom_removal()
5928 };
5929 let id = TEXT_DECODER_NEXT.fetch_add(1, Ordering::Relaxed);
5930 text_decoders(scope).insert(id, dec);
5931 rv.set(v8::Number::new(scope, id as f64).into());
5932}
5933
5934/// `$$textDecoderDecode(id, view, fatal, last)` -> string. Frees the
5935/// decoder when `last` is true or on a fatal malformed sequence
5936/// (TypeError).
5937fn op_text_decoder_decode(
5938 scope: &mut v8::PinScope,
5939 args: v8::FunctionCallbackArguments,
5940 mut rv: v8::ReturnValue<v8::Value>,
5941) {
5942 let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
5943 let bytes = view_bytes(args.get(1)).unwrap_or_default();
5944 let fatal = args.get(2).boolean_value(scope);
5945 let last = args.get(3).boolean_value(scope);
5946 // Per spec an empty streaming chunk is a no-op, but encoding_rs
5947 // 0.8 flushes a pending multibyte lead when fed an empty non-last
5948 // slice (e.g. Shift_JIS 0x82, "", 0xA0 would yield U+FFFD instead
5949 // of あ). Skip the decoder entirely.
5950 if bytes.is_empty() && !last {
5951 rv.set(v8::String::empty(scope).into());
5952 return;
5953 }
5954 let mut dec = text_decoders(scope)
5955 .remove(&id)
5956 .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.
5978fn 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.
6001fn run_decoder(
6002 dec: &mut encoding_rs::Decoder,
6003 bytes: &[u8],
6004 fatal: bool,
6005 last: bool,
6006) -> Result<String, ()> {
6007 let mut out = String::new();
6008 if fatal {
6009 let cap = dec
6010 .max_utf8_buffer_length_without_replacement(bytes.len())
6011 .unwrap();
6012 out.reserve(cap);
6013 if !matches!(
6014 dec.decode_to_string_without_replacement(bytes, &mut out, last),
6015 (encoding_rs::DecoderResult::InputEmpty, _),
6016 ) {
6017 return Err(());
6018 }
6019 } else {
6020 let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap();
6021 out.reserve(cap);
6022 let _ = dec.decode_to_string(bytes, &mut out, last);
6023 }
6024 Ok(out)
6025}
6026
6027fn 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
6033/// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder
6034/// abandoned mid-stream.
6035fn op_text_decoder_free(
6036 scope: &mut v8::PinScope,
6037 args: v8::FunctionCallbackArguments,
6038 _rv: v8::ReturnValue<v8::Value>,
6039) {
6040 let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
6041 text_decoders(scope).remove(&id);
6042}
6043
6044// ---- the JS harness: Web API + the DO object model ----
6045
6046mod bootstrap;
6047mod modules;
6048use bootstrap::{
6049 adopt_cell, begin_event_context, build_env, end_event_context, harness_env,
6050 inject_compatibility_flags, inject_crons, inject_namespace_keys, inject_routing,
6051 inject_storage_compatibility, install_harness, install_prelude, populate_cf_exports,
6052 register_class, register_entrypoints,
6053};
6054use modules::{
6055 compile_module, host_import_module_dynamically, install_lazy_globals, op_builtin_module,
6056 register_loader_modules, register_stubs, register_wasm_modules, resolve_external,
6057 ModuleRegistry,
6058};
6059/// Like `make_request`, but marks the request as incoming. Its signal is
6060/// registered only if the handler actually suspends, preserving the
6061/// synchronous request path.
6062fn make_incoming_request<'s>(
6063 tc: &mut v8::PinScope<'s, '_>,
6064 url: &str,
6065 method: &str,
6066 body: &RequestBody,
6067 headers: &[(String, String)],
6068) -> Result<v8::Local<'s, v8::Value>> {
6069 let global = tc.get_current_context().global(tc);
6070 let key = v8::String::new(tc, "__makeIncomingRequest").unwrap();
6071 let f: v8::Local<v8::Function> = global
6072 .get(tc, key.into())
6073 .ok_or_else(|| anyhow!("no __makeIncomingRequest"))?
6074 .try_into()
6075 .map_err(|_| anyhow!("not fn"))?;
6076 let url = v8::String::new(tc, url).unwrap();
6077 let method = v8::String::new(tc, method).unwrap();
6078 let headers = v8::String::new(
6079 tc,
6080 &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()),
6081 )
6082 .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 };
6092 let recv = v8::undefined(tc).into();
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"))
6099}
6100
6101fn register_incoming_request(
6102 tc: &mut v8::PinScope,
6103 request_id: RequestId,
6104 request: v8::Local<v8::Value>,
6105) -> Result<()> {
6106 let global = tc.get_current_context().global(tc);
6107 let key = v8::String::new(tc, "__registerIncomingRequest").unwrap();
6108 let function: v8::Local<v8::Function> = global
6109 .get(tc, key.into())
6110 .ok_or_else(|| anyhow!("no __registerIncomingRequest"))?
6111 .try_into()
6112 .map_err(|_| anyhow!("__registerIncomingRequest is not a function"))?;
6113 let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
6114 let recv = v8::undefined(tc).into();
6115 function
6116 .call(tc, recv, &[id.into(), request])
6117 .ok_or_else(|| anyhow!("__registerIncomingRequest threw"))?;
6118 Ok(())
6119}
6120
6121fn finish_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) {
6122 let global = tc.get_current_context().global(tc);
6123 let key = v8::String::new(tc, "__finishIncomingRequest").unwrap();
6124 let Some(value) = global.get(tc, key.into()) else {
6125 return;
6126 };
6127 let Ok(function) = value.try_cast::<v8::Function>() else {
6128 return;
6129 };
6130 let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
6131 let recv = v8::undefined(tc).into();
6132 let _ = function.call(tc, recv, &[id.into()]);
6133}
6134
6135fn make_request<'s>(
6136 tc: &mut v8::PinScope<'s, '_>,
6137 url: &str,
6138 method: &str,
6139 body: &[u8],
6140 headers: &[(String, String)],
6141) -> Result<v8::Local<'s, v8::Value>> {
6142 let g = tc.get_current_context().global(tc);
6143 let k = v8::String::new(tc, "__makeRequest").unwrap();
6144 let f: v8::Local<v8::Function> = g.get(tc, k.into()).unwrap().try_into().unwrap();
6145 let u = v8::String::new(tc, url).unwrap();
6146 let m = v8::String::new(tc, method).unwrap();
6147 let b = bytes_value(tc, body.to_vec());
6148 let h = v8::String::new(tc, &serde_json::to_string(headers)?).unwrap();
6149 let recv = v8::undefined(tc).into();
6150 f.call(tc, recv, &[u.into(), m.into(), b, h.into()])
6151 .ok_or_else(|| anyhow!("makeRequest threw"))
6152}
6153
6154fn read_response(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> Result<HttpResponse> {
6155 let ctx = scope.get_current_context();
6156 let global = ctx.global(scope);
6157 let key = v8::String::new(scope, "__readResponse").unwrap();
6158 let f: v8::Local<v8::Function> = global
6159 .get(scope, key.into())
6160 .ok_or_else(|| anyhow!("no __readResponse"))?
6161 .try_into()
6162 .map_err(|_| anyhow!("not fn"))?;
6163 let recv = v8::undefined(scope).into();
6164 let out = f
6165 .call(scope, recv, &[ret])
6166 .ok_or_else(|| anyhow!("readResponse threw"))?;
6167 // The harness response reader is synchronous. Keeping this assertion at
6168 // the native boundary prevents a future harness change from quietly
6169 // reintroducing a nested async runtime while an isolate is entered.
6170 if out.is_promise() {
6171 return Err(anyhow!("__readResponse returned a promise"));
6172 }
6173 let out = out.to_object(scope).ok_or_else(|| anyhow!("not object"))?;
6174 let sk = v8::String::new(scope, "status").unwrap();
6175 let bk = v8::String::new(scope, "bodyBytes").unwrap();
6176 let tk = v8::String::new(scope, "bodyStreamId").unwrap();
6177 let hk = v8::String::new(scope, "headersJson").unwrap();
6178 let wk = v8::String::new(scope, "wsTargetJson").unwrap();
6179 let status = out
6180 .get(scope, sk.into())
6181 .and_then(|v| v.uint32_value(scope))
6182 .unwrap_or(200) as u16;
6183 // Body bytes cross as a Uint8Array copied directly out of V8 — no JSON
6184 // number array (which was ~4x the bytes to serialize + parse per response).
6185 let body = out
6186 .get(scope, bk.into())
6187 .and_then(|v| v8::Local::<v8::ArrayBufferView>::try_from(v).ok())
6188 .map(|view| {
6189 let mut buf = vec![0u8; view.byte_length()];
6190 view.copy_contents(&mut buf);
6191 buf
6192 })
6193 .unwrap_or_default();
6194 let stream_id = out
6195 .get(scope, tk.into())
6196 .and_then(|value| value.integer_value(scope))
6197 .unwrap_or(0)
6198 .max(0) as u64;
6199 let stream = if stream_id == 0 {
6200 None
6201 } else {
6202 http_streams()
6203 .lock()
6204 .unwrap()
6205 .remove(&stream_id)
6206 .and_then(|stream| stream.source)
6207 .map(http_chunk_stream)
6208 };
6209 if stream_id != 0 && stream.is_none() {
6210 return Err(anyhow!(
6211 "response stream {stream_id} is no longer available"
6212 ));
6213 }
6214 let headers = out
6215 .get(scope, hk.into())
6216 .and_then(|v| serde_json::from_str(&v.to_rust_string_lossy(scope)).ok())
6217 .unwrap_or_default();
6218 let ws_json = out
6219 .get(scope, wk.into())
6220 .map(|v| v.to_rust_string_lossy(scope))
6221 .unwrap_or_else(|| "null".into());
6222 let ws = serde_json::from_str(&ws_json).ok();
6223 if status == 101 {
6224 tracing::info!(%ws_json, has_target = ws.is_some(), "JS WebSocket response");
6225 }
6226 Ok(HttpResponse {
6227 status,
6228 body,
6229 stream,
6230 headers,
6231 ws,
6232 write_position: None,
6233 })
6234}
6235
6236#[cfg(all(test, celld_internal_tests))]
6237fn init_engine_for_tests() {
6238 static INIT: std::sync::Once = std::sync::Once::new();
6239 INIT.call_once(|| {
6240 v8::V8::set_flags_from_string("--expose-gc");
6241 Engine::init();
6242 });
6243}
6244
6245#[cfg(all(test, celld_internal_tests))]
6246include!(env!("CELLD_INTERNAL_JS_OBSERVERS"));
6247
6248/// Externally injected Web-platform tests.
6249#[cfg(all(test, celld_internal_tests))]
6250pub(crate) mod conformance_runtime_tests {
6251 include!(env!("CELLD_CONFORMANCE_JS_RUNTIME_TESTS"));
6252}
6253
6254#[cfg(all(test, celld_internal_tests))]
6255mod conformance_web_platform_tests {
6256 include!(env!("CELLD_CONFORMANCE_WEB_PLATFORM_TESTS"));
6257}
6258
6259#[cfg(all(test, celld_internal_tests))]
6260mod call_order_private {
6261 include!(env!("CELLD_CONFORMANCE_CALL_ORDER_TESTS"));
6262}