Diffinery

homeflare/celldpublic

12203 lines · 475.3 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 Actor execution
4// domain. The Actor-reachable wake and WebSocket state is injected through
5// HostServices.
6#![allow(clippy::disallowed_methods, clippy::disallowed_types)]
7
8//! The JS engine: rusty_v8 directly. One isolate per cell.
9//!
10//! This slice runs actual Durable Objects: the worker's default-export `fetch`
11//! receives an `env` whose bindings are DO namespaces; `env.NS.get(id).fetch()`
12//! instantiates the exported DO class (once per id) with a `state` whose
13//! `storage` is backed by the cell's SQLite (crate::storage). DO storage is
14//! async in JS, synchronous underneath — the ops are sync Rust, wrapped in
15//! `async` by the JS harness.
16use crate::asyncrt;
17use crate::storage;
18use anyhow::{anyhow, Context as _, Result};
19use std::cell::RefCell;
20use std::collections::{HashMap, HashSet};
21use std::pin::Pin;
22use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
23use std::sync::{Arc, Mutex, OnceLock, Weak};
24use std::time::{Duration, Instant};
25use v8::{ValueDeserializerHelper, ValueSerializerHelper};
26
27pub(crate) mod input_gate_lifecycle;
28use input_gate_lifecycle::{CrossEntryGateClaim, CrossEntryGateClaims};
29
30pub use crate::engine_api::answer_ticket;
31pub use crate::engine_api::d1_cell_scope;
32pub(crate) use crate::engine_api::decode_durable_object_id;
33pub(crate) use crate::engine_api::durable_object_id_for_name;
34pub(crate) use crate::engine_api::durable_object_id_hex;
35pub(crate) use crate::engine_api::durable_object_id_hmac;
36pub(crate) use crate::engine_api::durable_object_id_key;
37pub(crate) use crate::engine_api::fail_in_turn_error;
38pub use crate::engine_api::failed_write_position;
39pub use crate::engine_api::handler_budget;
40pub use crate::engine_api::kv_cell_scope;
41pub(crate) use crate::engine_api::namespace_key;
42pub use crate::engine_api::next_do_request_id;
43pub use crate::engine_api::next_request_id;
44pub use crate::engine_api::parse_request_id;
45pub use crate::engine_api::queue_cell_scope;
46pub use crate::engine_api::request_id_string;
47#[cfg(celld_internal_tests)]
48pub use crate::engine_api::workflow_cell_scope_for_test;
49pub use crate::engine_api::CellOverloaded;
50pub use crate::engine_api::Compat;
51pub use crate::engine_api::FailedInTurn;
52pub use crate::engine_api::GatedAnswer;
53pub use crate::engine_api::HttpChunkStream;
54pub use crate::engine_api::HttpResponse;
55pub use crate::engine_api::HttpResponseWebSocket;
56pub use crate::engine_api::ModuleSource;
57pub use crate::engine_api::QueueBatch;
58pub use crate::engine_api::QueueBinding;
59pub use crate::engine_api::QueueContentType;
60pub use crate::engine_api::QueueDispatchResult;
61pub use crate::engine_api::QueueMessage;
62pub use crate::engine_api::QueueMetrics;
63pub use crate::engine_api::QueueOutcome;
64pub use crate::engine_api::QueueRetryBatch;
65pub use crate::engine_api::QueueRetryMessage;
66pub use crate::engine_api::RequestBody;
67pub use crate::engine_api::RequestId;
68pub use crate::engine_api::RpcData;
69pub use crate::engine_api::RpcOutcome;
70pub use crate::engine_api::WorkerConfigOptions;
71pub use crate::engine_api::WorkflowBinding;
72pub use crate::engine_api::WsTarget;
73pub(crate) use crate::engine_api::BARE_NODE_BUILTINS;
74pub use crate::engine_api::CELL_OVERLOAD_ERROR_MARKER;
75#[cfg(celld_internal_tests)]
76pub use crate::host_channels::install_outbound_ws_connector_for_test;
77pub(crate) use crate::host_channels::outbound_ws_tx;
78pub use crate::host_channels::set_asset_call_tx;
79pub use crate::host_channels::set_facet_tx;
80pub use crate::host_channels::set_gate_tx;
81pub use crate::host_channels::set_kv_blob_store;
82pub use crate::host_channels::set_outbound_ws_tx;
83pub use crate::host_channels::set_queue_dispatch_tx;
84pub use crate::host_channels::set_rpc_call_tx;
85pub use crate::host_channels::set_svc_call_tx;
86pub use crate::host_channels::set_svc_rpc_tx;
87pub use crate::host_channels::AssetCallReq;
88pub use crate::host_channels::FacetReq;
89pub use crate::host_channels::GateReq;
90pub use crate::host_channels::QueueDispatchReq;
91pub use crate::host_channels::QueueLeaseRef;
92pub use crate::host_channels::RpcCallReq;
93pub use crate::host_channels::SvcCallReq;
94pub use crate::host_channels::SvcRpcReq;
95#[cfg(celld_internal_tests)]
96pub use crate::host_channels::TestOutboundWsConnector;
97pub(crate) use crate::host_channels::ASSET_CALL_TX;
98pub(crate) use crate::host_channels::FACET_TX;
99pub(crate) use crate::host_channels::GATE_TX;
100pub(crate) use crate::host_channels::QUEUE_DISPATCH_TX;
101pub(crate) use crate::host_channels::RPC_CALL_TX;
102pub(crate) use crate::host_channels::SVC_CALL_TX;
103pub(crate) use crate::host_channels::SVC_RPC_TX;
104pub(crate) use crate::http_streams::claim_http_stream;
105pub(crate) use crate::http_streams::encode_http_response;
106pub(crate) use crate::http_streams::http_stream_read;
107#[cfg(all(test, celld_internal_tests))]
108pub(crate) use crate::http_streams::http_stream_read_source_first_for_test;
109pub(crate) use crate::http_streams::http_stream_service;
110#[cfg(all(test, celld_internal_tests))]
111pub(crate) use crate::http_streams::next_http_stream_chunk;
112pub(crate) use crate::http_streams::prepare_http_stream_tee;
113pub use crate::http_streams::register_body_stream;
114pub(crate) use crate::http_streams::response_stream_close;
115pub(crate) use crate::http_streams::response_stream_write;
116pub(crate) use crate::http_streams::retain_first_http_cleanup_panic;
117#[cfg(all(test, celld_internal_tests))]
118pub(crate) use crate::http_streams::settle_http_stream_read;
119pub use crate::http_streams::take_body_stream;
120#[cfg(all(test, celld_internal_tests))]
121pub(crate) use crate::http_streams::HttpStreamActivityError;
122#[cfg(all(test, celld_internal_tests))]
123pub(crate) use crate::http_streams::HttpStreamActivityKind;
124pub(crate) use crate::http_streams::HttpStreamClaim;
125#[cfg(all(test, celld_internal_tests))]
126pub(crate) use crate::http_streams::HttpStreamEntry;
127pub(crate) use crate::http_streams::HttpStreamService;
128pub(crate) use crate::http_streams::HttpStreamSource;
129#[cfg(all(test, celld_internal_tests))]
130pub(crate) use crate::http_streams::HttpStreamTermination;
131#[cfg(all(test, celld_internal_tests))]
132pub(crate) use crate::http_streams::HttpStreamTerminationReason;
133#[cfg(all(test, celld_internal_tests))]
134pub(crate) use crate::http_streams::HttpSweeperExitGate;
135#[cfg(all(test, celld_internal_tests))]
136pub(crate) use crate::http_streams::HttpTeePump;
137pub(crate) use crate::http_streams::HttpTransferredStream;
138pub use crate::http_streams::RequestBodyGuard;
139pub(crate) use crate::http_streams::ResponseStreamWriter;
140pub(crate) use crate::http_streams::HTTP_STREAM_DONE;
141#[cfg(all(test, celld_internal_tests))]
142pub(crate) use crate::http_streams::HTTP_STREAM_IDLE_TIMEOUT_MS;
143pub(crate) use crate::http_streams::HTTP_STREAM_REGISTRATION_CLOSED;
144#[cfg(all(test, celld_internal_tests))]
145pub(crate) use crate::http_streams::HTTP_TEE_BRANCH_CAPACITY;
146#[cfg(all(test, celld_internal_tests))]
147pub(crate) use crate::http_streams::NEXT_HTTP_STREAM_ID;
148pub use crate::wake_entry::forget_wake_entry;
149pub(crate) use crate::wake_entry::launch_arm_gate;
150pub(crate) use crate::wake_entry::maintain_wake_entry;
151pub(crate) use crate::wake_entry::publish_observed_wake_entry;
152pub use crate::wake_entry::set_arm_gate;
153pub use crate::wake_entry::ArmGate;
154pub(crate) use crate::wake_entry::ArmGateRx;
155pub(crate) use crate::wake_entry::WakeEntryService;
156
157#[cfg(all(test, celld_internal_tests))]
158fn test_host_services() -> Arc<crate::host_services::HostServices> {
159 asyncrt::services()
160}
161
162/// The pending exception text from a TryCatch scope (a macro so it needs no
163/// bound on the crate-private scope traits).
164macro_rules! exc {
165 ($tc:expr) => {
166 $tc.exception()
167 .map(|e| e.to_rust_string_lossy(&*$tc))
168 .unwrap_or_else(|| "<none>".into())
169 };
170}
171
172/// A cross-node dispatch: the isolate hit `env.NS.get(id)` for a cell this node
173/// does not own. The op hands this to the tokio runtime, which resolves the
174/// owner and HTTP-proxies the fetch, replying on `reply` (an async oneshot the
175/// async-op future awaits — the JS thread is never blocked).
176pub struct DoCallReq {
177 pub request_id: Option<RequestId>,
178 pub cancel: Option<tokio::sync::oneshot::Receiver<()>>,
179 /// An explicit JavaScript AbortSignal must reach the target handler, even
180 /// when it fires before cold routing completes. Transport cancellation has
181 /// no handler contract and can stop the cold route immediately.
182 pub deliver_abort_to_handler: bool,
183 pub scope: String,
184 pub name: Option<String>,
185 pub url: String,
186 pub method: String,
187 pub body: RequestBody,
188 /// Owns a streamed body while the call waits for routing or admission.
189 pub body_guard: RequestBodyGuard,
190 pub headers: Vec<(String, String)>,
191 pub reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
192 /// Where this call sits in its caller's order for this cell.
193 pub order: Option<CallOrder>,
194 /// The dispatching handler's trace context, read from CPED at the
195 /// call site, so the cell's span joins the caller's trace.
196 pub parent: Option<crate::telemetry::TraceContext>,
197}
198static DO_CALL_TX: OnceLock<tokio::sync::mpsc::UnboundedSender<DoCallReq>> = OnceLock::new();
199
200/// Delivery order, per caller and per cell.
201///
202/// Two calls a script makes back-to-back on one Durable Object stub reach
203/// the cell in that order. Workerd guarantees it — one pipe per stub — and
204/// celld did too, while a cell's events came off one channel. Nothing
205/// between the call and the cell keeps it now: the caller's two ops race to
206/// the proxy channel, the proxy polls them in a `FuturesUnordered`, and two
207/// drives race for the isolate. So the order is taken where it is still
208/// true, synchronously in `op_do_call_impl`, and carried to the one place
209/// that decides when an event is delivered.
210///
211/// It is a chain, not a counter: each call leaves behind the receiver its
212/// successor waits on, and takes its predecessor's.
213///
214/// **The chain lives on the caller.** It was a process-wide map keyed by
215/// `(context, cell)`, which made every Durable Object call in the node take
216/// one global lock to record something only its own caller could ever read.
217/// A shared mutex on a per-request path is a scalability cliff that a small
218/// machine cannot show you, and the state was never shared to begin with.
219///
220/// **Local delivery only.** A call routed to another node crosses HTTP,
221/// where this order has nowhere to ride, so it is dropped there. Workerd
222/// has the same seam in a different place, and a cell that moves mid-flight
223/// reorders under both.
224pub struct CallOrder {
225 /// The call before this one, or `None` if this is the first.
226 ahead: Option<tokio::sync::oneshot::Receiver<Place>>,
227 /// What the call behind this one waits on.
228 release: Option<tokio::sync::oneshot::Sender<Place>>,
229 /// The caller that owns the chain, and this call's place in it.
230 caller: Arc<IoContext>,
231 cell: String,
232 seq: u64,
233 delivered: bool,
234}
235
236/// What a call hands to the one behind it.
237///
238/// `None` once this call has been delivered: the queue has moved on. `Some`
239/// when it died on the way to a cell and never took its turn, and then it
240/// is this call's own unfinished place — so the call behind waits for what
241/// this one was waiting for instead of jumping the queue.
242///
243/// Without the handoff a failed call releases its successor immediately,
244/// and a third call can be delivered ahead of a first that is still in
245/// flight. Rare, since it needs a call to fail between two that do not, and
246/// silent, since every call involved still gets an answer.
247#[doc(hidden)]
248pub struct Place(Option<Box<tokio::sync::oneshot::Receiver<Place>>>);
249
250impl CallOrder {
251 /// Wait for every call before this one to be delivered.
252 ///
253 /// A loop rather than one await because a call that died hands back
254 /// what *it* was waiting for. `Err` is the chain ahead going away
255 /// entirely, which is nothing left to wait for.
256 pub async fn wait(&mut self) {
257 let mut ahead = self.ahead.take();
258 while let Some(place) = ahead {
259 ahead = match place.await {
260 Ok(Place(forward)) => forward.map(|boxed| *boxed),
261 Err(_) => None,
262 };
263 }
264 }
265
266 /// This call has been delivered; the one behind it may go.
267 pub fn delivered(&mut self) {
268 self.delivered = true;
269 }
270}
271
272impl Drop for CallOrder {
273 fn drop(&mut self) {
274 // Nothing followed this call, so the chain is empty and its tail is
275 // only a leak. A caller's chains outlive its calls otherwise, and a
276 // cell isolate's default caller outlives everything.
277 let mut chains = self.caller.call_chains.lock().unwrap();
278 if chains
279 .tails
280 .get(&self.cell)
281 .is_some_and(|(seq, _)| *seq == self.seq)
282 {
283 chains.tails.remove(&self.cell);
284 }
285 drop(chains);
286 if let Some(release) = self.release.take() {
287 let forward = (!self.delivered).then(|| self.ahead.take()).flatten();
288 let _ = release.send(Place(forward.map(Box::new)));
289 }
290 }
291}
292
293/// One caller's chains, one per cell it has called.
294#[derive(Default)]
295#[doc(hidden)]
296pub struct CallChains {
297 next_seq: u64,
298 pub tails: HashMap<String, (u64, tokio::sync::oneshot::Receiver<Place>)>,
299}
300
301/// Take this call's place in its caller's chain for `cell`. Synchronous, so
302/// the places are taken in the order the script made the calls.
303#[doc(hidden)]
304pub fn enter_call_order(caller: Arc<IoContext>, cell: &str) -> CallOrder {
305 let (release, next) = tokio::sync::oneshot::channel();
306 let (seq, ahead) = {
307 let mut chains = caller.call_chains.lock().unwrap();
308 chains.next_seq += 1;
309 let seq = chains.next_seq;
310 let ahead = chains
311 .tails
312 .insert(cell.to_string(), (seq, next))
313 .map(|(_, ahead)| ahead);
314 (seq, ahead)
315 };
316 CallOrder {
317 ahead,
318 release: Some(release),
319 caller,
320 cell: cell.to_string(),
321 seq,
322 delivered: false,
323 }
324}
325
326pub fn set_do_call_tx(tx: tokio::sync::mpsc::UnboundedSender<DoCallReq>) {
327 let _ = DO_CALL_TX.set(tx);
328}
329
330/// Hand a Durable Object call to the dispatcher. Public HTTP ingress uses the
331/// same queue a Worker's `env.NAME.get(id).fetch()` does, so both resolve
332/// ownership, forward, and redispatch by one policy rather than two.
333#[must_use]
334pub fn submit_do_call(call: DoCallReq) -> bool {
335 DO_CALL_TX.get().is_some_and(|tx| tx.send(call).is_ok())
336}
337
338pub use r2_ops::set_r2_store;
339
340/// Sample the source under its SQLite lock. A missing source cannot grant
341/// publication or cleanup authority; the output gate fails closed for an arm.
342pub(crate) fn observe_alarm(cell: &str, at_ms: Option<i64>) -> celld_logic::wake::AlarmSnapshot {
343 storage::alarm_snapshot(cell).unwrap_or_else(|error| {
344 tracing::warn!(%cell, %error, "alarm observation has no committed wake source");
345 celld_logic::wake::AlarmSnapshot::without_wake(at_ms)
346 })
347}
348
349/// A committed installation needs discovery coverage: launch the entry PUT
350/// and register it against the current event's output gate. No-op when the
351/// bound already covers it or no gate is configured.
352fn spawn_arm_gate(cell: &str, at_ms: i64, context: Option<Arc<IoContext>>) {
353 if let Some(rx) = launch_arm_gate(cell, observe_alarm(cell, Some(at_ms))) {
354 register_arm_gate_with_current_event(rx, context);
355 }
356}
357
358fn register_arm_gate_with_current_event(gate: ArmGateRx, context: Option<Arc<IoContext>>) {
359 let Some(context) = context else {
360 drop(gate);
361 return;
362 };
363 if let Err(gate) = context.register_arm_gate(gate) {
364 // The response boundary sealed this context. The PUT itself
365 // continues, but its receiver cannot migrate into a later event's
366 // reply batch.
367 drop(gate);
368 }
369}
370
371#[cfg(celld_internal_tests)]
372fn register_test_pending_arm_gate(cell: &str, gate: ArmGateRx) {
373 let services = asyncrt::services();
374 let mut pending = services.wake_entry().test_pending.lock().unwrap();
375 let gates = pending.entry(cell.to_string()).or_default();
376 gates.retain_mut(|gate| {
377 matches!(
378 gate.try_recv(),
379 Err(tokio::sync::oneshot::error::TryRecvError::Empty)
380 )
381 });
382 gates.push(gate);
383}
384
385#[cfg(all(test, celld_internal_tests))]
386pub(crate) fn spawn_observed_arm_gate_for_test(
387 cell: &str,
388 alarm: celld_logic::wake::AlarmSnapshot,
389) {
390 let Some(gate) = launch_arm_gate(cell, alarm) else {
391 return;
392 };
393 match installed_context() {
394 Some(context) => register_arm_gate_with_current_event(gate, Some(context)),
395 None => register_test_pending_arm_gate(cell, gate),
396 }
397}
398
399#[cfg(celld_internal_tests)]
400#[doc(hidden)]
401pub fn pause_next_arm_gate_for_test() -> tokio::sync::oneshot::Sender<Result<(), String>> {
402 let (resume, paused) = tokio::sync::oneshot::channel();
403 asyncrt::services()
404 .wake_entry()
405 .scripted
406 .lock()
407 .unwrap()
408 .push_back(paused);
409 resume
410}
411
412#[cfg(celld_internal_tests)]
413#[doc(hidden)]
414pub fn pause_next_arm_gate_for_cell_for_test(
415 cell: &str,
416) -> tokio::sync::oneshot::Sender<Result<(), String>> {
417 let (resume, paused) = tokio::sync::oneshot::channel();
418 asyncrt::services()
419 .wake_entry()
420 .scripted_by_cell
421 .lock()
422 .unwrap()
423 .entry(cell.to_string())
424 .or_default()
425 .push_back(paused);
426 resume
427}
428
429#[cfg(celld_internal_tests)]
430#[doc(hidden)]
431pub fn next_arm_gate_is_paused_for_test() -> bool {
432 !asyncrt::services()
433 .wake_entry()
434 .scripted
435 .lock()
436 .unwrap()
437 .is_empty()
438}
439
440#[cfg(celld_internal_tests)]
441#[doc(hidden)]
442pub fn next_arm_gate_for_cell_is_paused_for_test(cell: &str) -> bool {
443 asyncrt::services()
444 .wake_entry()
445 .scripted_by_cell
446 .lock()
447 .unwrap()
448 .get(cell)
449 .is_some_and(|gates| !gates.is_empty())
450}
451
452/// Drain the compatibility wake-entry PUT gates for a simulated S1 cell.
453#[cfg(celld_internal_tests)]
454#[doc(hidden)]
455pub async fn drain_arm_gates(cell: &str) -> Result<(), String> {
456 let services = asyncrt::services();
457 let gates = services
458 .wake_entry()
459 .test_pending
460 .lock()
461 .unwrap()
462 .remove(cell);
463 let Some(gates) = gates else {
464 return Ok(());
465 };
466 await_arm_gates(gates).await
467}
468
469#[derive(Clone, Copy)]
470pub struct FetchRequest<'a> {
471 pub url: &'a str,
472 pub method: &'a str,
473 pub body: &'a [u8],
474 pub headers: &'a [(String, String)],
475 pub request_id: Option<RequestId>,
476}
477
478static DO_CALL_CANCELS: OnceLock<
479 std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>>,
480> = OnceLock::new();
481fn do_call_cancels(
482) -> &'static std::sync::Mutex<HashMap<RequestId, tokio::sync::oneshot::Sender<()>>> {
483 DO_CALL_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
484}
485
486enum RpcSignalState {
487 Live(HashMap<RequestId, tokio::sync::oneshot::Sender<Option<Vec<u8>>>>),
488 Aborted(Vec<u8>),
489}
490
491static RPC_SIGNALS: OnceLock<std::sync::Mutex<HashMap<RequestId, RpcSignalState>>> =
492 OnceLock::new();
493
494fn rpc_signals() -> &'static std::sync::Mutex<HashMap<RequestId, RpcSignalState>> {
495 RPC_SIGNALS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
496}
497
498struct RpcSignalSubscriptionGuard {
499 signal: RequestId,
500 subscription: RequestId,
501}
502
503impl Drop for RpcSignalSubscriptionGuard {
504 fn drop(&mut self) {
505 let mut signals = rpc_signals().lock().unwrap();
506 if let Some(RpcSignalState::Live(subscribers)) = signals.get_mut(&self.signal) {
507 subscribers.remove(&self.subscription);
508 }
509 }
510}
511
512/// Publish `request_id` on a pending call's promise as the token the JS
513/// harness hands back to `__do_call_cancel`.
514///
515/// The only writer of `__celldCancelId`, and the counterpart of
516/// [`parse_request_id`]. Each cancellable op used to spell the property name
517/// and the encoding out for itself, and `op_svc_call_impl` wrote decimal while
518/// `op_do_call_cancel` reads hexadecimal. Every decimal digit is also a
519/// hexadecimal digit, so the parse succeeded on a different number, the
520/// registry lookup missed, and the cancel was dropped with no error — a
521/// service-binding abort rejected the caller and left the target running. One
522/// writer paired with one parser removes the chance to disagree.
523fn attach_cancel_id(
524 scope: &mut v8::PinScope,
525 promise: v8::Local<v8::Value>,
526 request_id: RequestId,
527) {
528 let Some(object) = promise.to_object(scope) else {
529 return;
530 };
531 let key = v8::String::new(scope, "__celldCancelId").unwrap();
532 let value = v8::String::new(scope, &request_id_string(request_id)).unwrap();
533 object.set(scope, key.into(), value.into());
534}
535
536struct DoCallCancelGuard(Option<RequestId>);
537
538impl DoCallCancelGuard {
539 fn new(request: RequestId) -> Self {
540 Self(Some(request))
541 }
542
543 fn disarm(&mut self) {
544 if let Some(request) = self.0.take() {
545 do_call_cancels().lock().unwrap().remove(&request);
546 }
547 }
548}
549
550impl Drop for DoCallCancelGuard {
551 fn drop(&mut self) {
552 let Some(request) = self.0.take() else {
553 return;
554 };
555 if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request) {
556 let _ = cancel.send(());
557 }
558 }
559}
560
561static NEXT_TIMER_ID: AtomicU64 = AtomicU64::new(1);
562static TIMER_CANCELS: OnceLock<std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>>> =
563 OnceLock::new();
564fn timer_cancels() -> &'static std::sync::Mutex<HashMap<u64, tokio::sync::oneshot::Sender<()>>> {
565 TIMER_CANCELS.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
566}
567
568/// Which alarm a dispatch runs, and who owns its bookkeeping.
569pub enum AlarmDispatch {
570 /// Claim whatever is due now, and record the outcome.
571 Due,
572 #[cfg(celld_internal_tests)]
573 Armed,
574 #[cfg(celld_internal_tests)]
575 Claimed(i64),
576}
577
578/// One event a cell receives.
579///
580/// Every variant is something the outside world did to the cell, and each
581/// becomes an `InFlight` entry driven by its own tokio task. Lifecycle —
582/// taking a cell in, giving it back, cancelling a request — is not here: it
583/// is a direct call on the isolate, because it is not an event and has no
584/// handler to run.
585pub enum CellJob {
586 Fetch {
587 request_id: Option<RequestId>,
588 scope: String,
589 name: Option<String>,
590 url: String,
591 method: String,
592 body: RequestBody,
593 headers: Vec<(String, String)>,
594 reply: tokio::sync::oneshot::Sender<Result<HttpResponse>>,
595 /// Where this call sits in its caller's order for this cell, if it
596 /// came from a script rather than from a peer or the ingress.
597 order: Option<CallOrder>,
598 },
599 Rpc {
600 request_id: Option<RequestId>,
601 scope: String,
602 name: Option<String>,
603 method: String,
604 args: RpcData,
605 reply: tokio::sync::oneshot::Sender<Result<RpcOutcome>>,
606 },
607 WsOpen {
608 scope: String,
609 ws_id: u64,
610 protocol: String,
611 reply: tokio::sync::oneshot::Sender<Result<Option<u64>>>,
612 },
613 WsMessage {
614 scope: String,
615 ws_id: u64,
616 data: WsIn,
617 reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>,
618 },
619 WsClosed {
620 scope: String,
621 ws_id: u64,
622 code: u16,
623 reason: String,
624 was_clean: bool,
625 reply: tokio::sync::oneshot::Sender<Result<Option<u64>>>,
626 },
627 Alarm {
628 /// The shell task identity used to interrupt a firing during drain.
629 request_id: Option<RequestId>,
630 scope: String,
631 scheduled_ms: i64,
632 /// Which alarm to run, and who owns the bookkeeping.
633 claim: AlarmDispatch,
634 /// Replies with (next alarm, the handler's write delta). The delta is
635 /// sampled inside the turn — cell storage must never be reached from
636 /// the shell — and the shell uses it to prove the consuming commit
637 /// durable before the core settles. Every answer shape samples it the
638 /// same way now, in `InFlight::answer_settled`.
639 reply:
640 tokio::sync::oneshot::Sender<Result<(celld_logic::wake::AlarmSnapshot, Option<u64>)>>,
641 },
642 #[cfg(celld_internal_tests)]
643 SyncErrorForTest {
644 scope: String,
645 gate: ArmGateRx,
646 socket_id: Option<u64>,
647 terminate: bool,
648 reply: tokio::sync::oneshot::Sender<Result<Option<u64>>>,
649 },
650}
651
652impl CellJob {
653 /// The cell this event addresses, which is also the realm it runs in.
654 pub fn scope(&self) -> &str {
655 match self {
656 CellJob::Fetch { scope, .. }
657 | CellJob::Rpc { scope, .. }
658 | CellJob::WsOpen { scope, .. }
659 | CellJob::WsMessage { scope, .. }
660 | CellJob::WsClosed { scope, .. }
661 | CellJob::Alarm { scope, .. } => scope,
662 #[cfg(celld_internal_tests)]
663 CellJob::SyncErrorForTest { scope, .. } => scope,
664 }
665 }
666
667 /// The client request that can cancel this event, when it is a fetch.
668 pub(crate) fn request_id(&self) -> Option<RequestId> {
669 match self {
670 CellJob::Fetch { request_id, .. } => *request_id,
671 _ => None,
672 }
673 }
674
675 /// Queue sends use native RPC, so the method is the narrow seam where the
676 /// owner can bound producer events without limiting an ordinary Durable
677 /// Object RPC or a Queue alarm and settlement.
678 pub(crate) fn is_queue_producer(&self) -> bool {
679 matches!(self, CellJob::Rpc { scope, method, .. }
680 if scope.split_once(':').is_some_and(|(class, _)|
681 class == crate::deploy::QUEUE_CLASS) && method == "__queueSend")
682 }
683
684 /// This event's place in its caller's order, taken out so the drive can
685 /// wait on it and then release the call behind it.
686 pub fn take_order(&mut self) -> Option<CallOrder> {
687 match self {
688 CellJob::Fetch { order, .. } => order.take(),
689 _ => None,
690 }
691 }
692
693 /// Fail this event without running it.
694 pub fn fail(self, error: anyhow::Error) {
695 match self {
696 CellJob::Fetch { reply, .. } => drop(reply.send(Err(error))),
697 CellJob::Rpc { reply, .. } => drop(reply.send(Err(error))),
698 CellJob::WsOpen { reply, .. } => drop(reply.send(Err(error))),
699 CellJob::WsMessage { reply, .. } => drop(reply.send(Err(error))),
700 CellJob::WsClosed { reply, .. } => drop(reply.send(Err(error))),
701 CellJob::Alarm { reply, .. } => drop(reply.send(Err(error))),
702 #[cfg(celld_internal_tests)]
703 CellJob::SyncErrorForTest { reply, .. } => drop(reply.send(Err(error))),
704 }
705 }
706}
707
708thread_local! {
709 // One outbound HTTP client per JS thread — building it per fetch rebuilds
710 // the TLS stack every call (async-op-hazards.md).
711 static HTTP: reqwest::Client = reqwest::Client::new();
712 static HTTP_MANUAL: reqwest::Client = reqwest::Client::builder()
713 .redirect(reqwest::redirect::Policy::none()).build().unwrap();
714 // A separate policy stops an `error` request before reqwest can replay it
715 // at the destination. Inspecting the final response would be too late:
716 // the method, body, and credentials could already have left the process.
717 static HTTP_ERROR: reqwest::Client = reqwest::Client::builder()
718 .redirect(reqwest::redirect::Policy::custom(|attempt| {
719 attempt.error("fetch redirect mode is error")
720 })).build().unwrap();
721}
722
723#[derive(Debug)]
724struct RedirectSubrequestLimit(String);
725
726impl std::fmt::Display for RedirectSubrequestLimit {
727 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
728 formatter.write_str(&self.0)
729 }
730}
731
732impl std::error::Error for RedirectSubrequestLimit {}
733
734fn fetch_request_error(error: &reqwest::Error) -> String {
735 let mut source: &(dyn std::error::Error + 'static) = error;
736 loop {
737 if let Some(limit) = source.downcast_ref::<RedirectSubrequestLimit>() {
738 return limit.0.clone();
739 }
740 let Some(next) = source.source() else {
741 return format!("fetch: {error}");
742 };
743 source = next;
744 }
745}
746
747#[doc(hidden)]
748pub mod websocket;
749pub(crate) use websocket::WebSocketService;
750pub use websocket::*;
751use websocket::{
752 ws_capture_begin, ws_capture_discard, ws_capture_flush_touched, ws_capture_set_promise,
753 ws_capture_take, ws_close_request_sockets,
754};
755
756/// What an outbound effect must trail before it leaves the process.
757///
758/// The three cases are named rather than nested inside one another because
759/// two of them once shared a representation and lost this distinction:
760/// a reader that starts after another request committed samples the new
761/// position as its own baseline and advances nothing, so a two-state gate read
762/// it as code that owns no cell at all and let its side effect out ungated.
763/// A variant per case makes the distinction one the compiler keeps.
764enum EgressGate {
765 /// No cell event is running. Stateless Worker code owns no cell state, so
766 /// its egress reveals nothing that can still be lost and leaves directly.
767 NoCell,
768 /// This event wrote through the position. The effect waits for that
769 /// write. The last field is the activation epoch the position belongs to.
770 Wrote(String, celld_logic::Channel, u64, Option<u64>),
771 /// A read-only output. It reveals whatever the cell holds, so it carries
772 /// the position it observed above the cell's published baseline, for the
773 /// core to hold it behind the proof of a commit whose handler has not
774 /// taken a ticket yet, and it trails the newest write barrier still open
775 /// on the cell otherwise. Only the core knows which writes are
776 /// outstanding, so this asks rather than guesses. The last field is the
777 /// activation epoch the sample was taken at.
778 ReadOnly(String, celld_logic::Channel, Option<u64>, Option<u64>),
779 /// A facet's storage failed. No proof can cover its write, so the effect
780 /// fails closed. The field is the storage failure.
781 Unpersisted(String),
782 /// An effect of a facet that wrote: the facet's own stream proves the
783 /// write before the root cell's gate verdicts the rest, as workerd's
784 /// facet output gate holds the effect. Fields: the root cell's gate, the
785 /// facet's stream, and the activation epoch.
786 Facet(Box<EgressGate>, String, u64),
787}
788
789impl EgressGate {
790 /// Whether the effect must consult the gate before it leaves. True for a
791 /// read as well as a write: a read whose cell has no barrier is released
792 /// at once, but only the core can say so.
793 fn is_gated(&self) -> bool {
794 !matches!(self, EgressGate::NoCell)
795 }
796
797 /// The cell whose event raised the effect. The host derives this from the
798 /// active event, so JavaScript cannot claim another cell's authority.
799 fn cell_scope(&self) -> Option<&str> {
800 match self {
801 EgressGate::NoCell | EgressGate::Unpersisted(_) => None,
802 EgressGate::Wrote(cell, ..) | EgressGate::ReadOnly(cell, ..) => Some(cell),
803 EgressGate::Facet(root, ..) => root.cell_scope(),
804 }
805 }
806}
807
808/// The cell event the executing JavaScript belongs to.
809///
810/// The continuation's own context first, from CPED: V8 runs a promise
811/// reaction of cell A inside another event's microtask checkpoint, and the
812/// thread-local turn owner then names that other event. An effect raised by
813/// A's reaction would otherwise be gated against the wrong cell's position, or
814/// refused as belonging to the wrong cell. The turn owner remains the answer
815/// for a context that installs no continuation token.
816fn event_context(scope: &mut v8::PinScope) -> Arc<IoContext> {
817 current_reaction_io_context(scope).unwrap_or_else(current_context)
818}
819
820/// What one cell event's outbound effects gate against.
821#[derive(Clone)]
822struct EgressFrame {
823 /// The scope whose connection records this event's writes: the cell for an
824 /// ordinary event, and the facet for an event of an embedded facet.
825 storage: String,
826 /// The committed-write position of `storage` when the event started.
827 before: u64,
828 /// The root cell's gate, when `storage` names an embedded facet. Kept
829 /// beside the scope it stores under, so an effect cannot take one without
830 /// the other and charge a facet's egress to the facet.
831 root: Option<storage::RootGate>,
832}
833
834/// The frame of the running event, if a cell event is running at all.
835fn current_cell_event(context: &IoContext) -> Option<EgressFrame> {
836 context.egress.lock().unwrap().last().cloned()
837}
838
839/// Return and clear the number of output-gate samples for one test cell.
840#[cfg(all(test, celld_internal_tests))]
841pub(crate) fn take_egress_gate_samples_for_test(scope: &str, channel: celld_logic::Channel) -> u64 {
842 test_host_services()
843 .wake_entry()
844 .egress_gate_samples
845 .lock()
846 .unwrap()
847 .remove(&(scope.to_string(), channel))
848 .unwrap_or(0)
849}
850
851/// Sample what the running handler's outbound effects must trail. Answers for
852/// every active cell event, including a read whose core lookup can settle
853/// immediately. Every sample here happens in the calling turn; the ticket
854/// carries them to the host loop, which must not reach cell storage itself.
855fn egress_gate_request(context: &IoContext, channel: celld_logic::Channel) -> EgressGate {
856 let Some(frame) = current_cell_event(context) else {
857 return EgressGate::NoCell;
858 };
859 #[cfg(all(test, celld_internal_tests))]
860 {
861 let cell = frame
862 .root
863 .as_ref()
864 .map(|root| root.cell.clone())
865 .unwrap_or_else(|| frame.storage.clone());
866 *test_host_services()
867 .wake_entry()
868 .egress_gate_samples
869 .lock()
870 .unwrap()
871 .entry((cell, channel))
872 .or_default() += 1;
873 }
874 let (cell, before) = (frame.storage, frame.before);
875 let sample = match storage::write_position(&cell) {
876 Ok(sample) => sample,
877 Err(error) => return EgressGate::Unpersisted(error.to_string()),
878 };
879 if let Some(root) = frame.root {
880 return facet_egress_gate(&cell, root, channel);
881 }
882 let epoch = storage::activation_epoch(&cell);
883 match sample.filter(|position| *position > before) {
884 Some(position) => EgressGate::Wrote(cell, channel, position, epoch),
885 // A read-only output in a process that configured no output gate has
886 // nothing to trail. Such a process cannot acknowledge a write either
887 // -- `await_egress_gate` fails a write closed for want of the same
888 // channel -- so no committed-but-unproven write exists for a read to
889 // reveal. Answer as
890 // if no cell event were running, which keeps the effect on the direct,
891 // synchronous path it has always taken; a WebSocket frame in
892 // particular must not join a deferred queue whose flush needs a gate
893 // to release it. A write still takes a ticket and still fails closed.
894 None if GATE_TX.get().is_none() => EgressGate::NoCell,
895 None => {
896 let observed = storage::observed_position(&cell, sample);
897 EgressGate::ReadOnly(cell, channel, observed, epoch)
898 }
899 }
900}
901
902/// Sample an effect raised by an event of an embedded facet.
903///
904/// A facet is not a cell: no Worker exports its class under the id
905/// `facet_scope` builds, so a ticket in the facet's name activates a cell
906/// that cannot start. The effect can reveal what the root cell showed the
907/// facet, so it trails the root cell's reader gate with the sample the parent
908/// took for the call; a write of the facet's own is proved on its stream.
909fn facet_egress_gate(
910 facet: &str,
911 root: storage::RootGate,
912 channel: celld_logic::Channel,
913) -> EgressGate {
914 if let Some(error) = storage::sql_critical_error(facet) {
915 return EgressGate::Unpersisted(error);
916 }
917 // A process with no output gate has nothing to trail, and a WebSocket
918 // frame must keep its direct path (see `egress_gate_request`).
919 if GATE_TX.get().is_none() {
920 return EgressGate::NoCell;
921 }
922 let gate = EgressGate::ReadOnly(root.cell, channel, root.observed, Some(root.epoch));
923 // Any effect can reveal a facet write, this event's or an earlier one's,
924 // so every effect waits for the facet's stream, as workerd's facet
925 // output gate holds it.
926 EgressGate::Facet(Box::new(gate), root.stream, root.epoch)
927}
928
929/// Prove a facet's stream through the host loop, which owns the replicator.
930async fn prove_facet(stream: String, epoch: u64) -> std::result::Result<(), GateRefusal> {
931 // No host loop means no replicator, so nothing can prove the write and
932 // nothing can lose it to a later proof either.
933 let Some(sender) = FACET_TX.get() else {
934 return Ok(());
935 };
936 let (reply, receive) = tokio::sync::oneshot::channel();
937 let request = FacetReq::Prove {
938 stream,
939 epoch,
940 reply,
941 };
942 sender.send(request).map_err(|_| GateRefusal::Dropped)?;
943 match receive.await {
944 Ok(Ok(())) => Ok(()),
945 Ok(Err(error)) => Err(GateRefusal::Unpersisted(format!("{error:#}"))),
946 Err(_) => Err(GateRefusal::Dropped),
947 }
948}
949
950/// Why the output gate did not release a ticket.
951enum GateRefusal {
952 /// The process installed no gate channel. A write must still fail closed
953 /// here: an acknowledgement nobody can prove is the loss this gate exists
954 /// to prevent.
955 NoChannel,
956 /// The core answered, and the answer is that the write is not durable.
957 Unproven(celld_logic::RequestError),
958 /// The shell dropped the ticket before the core answered.
959 Dropped,
960 /// A facet's write never reached a database a proof can cover.
961 Unpersisted(String),
962}
963
964impl std::fmt::Display for GateRefusal {
965 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
966 match self {
967 GateRefusal::NoChannel => f.write_str("no output-gate channel"),
968 GateRefusal::Unproven(error @ celld_logic::RequestError::DurabilityUnproven) => {
969 write!(
970 f,
971 "the write this request follows is not durable ({error:?})"
972 )
973 }
974 GateRefusal::Unproven(error) => {
975 write!(f, "the output gate refused the ticket ({error:?})")
976 }
977 GateRefusal::Dropped => f.write_str("output gate dropped"),
978 GateRefusal::Unpersisted(error) => {
979 write!(f, "the facet's write did not reach its database ({error})")
980 }
981 }
982 }
983}
984
985/// Take one ticket on the output gate and wait for the core's verdict.
986///
987/// This is the output gate applied to an in-handler effect rather than to the
988/// response. It cannot deadlock the handler that is awaiting it: the ticket is
989/// served by `dispatch_gate` on the host's own loop and resolved by the
990/// replicator's independent task, neither of which needs the isolate's event
991/// loop to run. A read-only ticket carries `None` and the core releases it at
992/// once when the cell has no barrier open, so an ordinary read pays one actor
993/// hop and no replica write.
994async fn egress_gate_verdict(gate: EgressGate) -> std::result::Result<(), GateRefusal> {
995 let gate = match gate {
996 EgressGate::Facet(root, stream, epoch) => {
997 prove_facet(stream, epoch).await?;
998 *root
999 }
1000 gate => gate,
1001 };
1002 let (cell, channel, position, observed, epoch) = match gate {
1003 EgressGate::Facet(..) => unreachable!("a facet gate nests no facet gate"),
1004 EgressGate::NoCell => return Ok(()),
1005 EgressGate::Unpersisted(error) => return Err(GateRefusal::Unpersisted(error)),
1006 EgressGate::Wrote(cell, channel, position, epoch) => {
1007 (cell, channel, Some(position), None, epoch)
1008 }
1009 EgressGate::ReadOnly(cell, channel, observed, epoch) => {
1010 (cell, channel, None, observed, epoch)
1011 }
1012 };
1013 let (tx, receive) = tokio::sync::oneshot::channel();
1014 let sent = GATE_TX
1015 .get()
1016 .map(|gate| {
1017 gate.send(GateReq {
1018 scope: cell,
1019 ticket: crate::actor::GateTicket {
1020 channel,
1021 position,
1022 observed,
1023 epoch,
1024 },
1025 reply: tx,
1026 })
1027 .is_ok()
1028 })
1029 .unwrap_or(false);
1030 if !sent {
1031 return Err(GateRefusal::NoChannel);
1032 }
1033 match receive.await {
1034 Ok(Ok(())) => Ok(()),
1035 Ok(Err(error)) => Err(GateRefusal::Unproven(error)),
1036 Err(_) => Err(GateRefusal::Dropped),
1037 }
1038}
1039
1040/// Wait for the writes an outbound effect can reveal to be proven durable
1041/// before it leaves the process. See `egress_gate_verdict`.
1042async fn await_egress_gate(gate: EgressGate) -> std::result::Result<(), String> {
1043 egress_gate_verdict(gate)
1044 .await
1045 .map_err(|refusal| match refusal {
1046 GateRefusal::Unproven(_) | GateRefusal::Unpersisted(_) => {
1047 format!("refusing to send: {refusal}")
1048 }
1049 GateRefusal::NoChannel | GateRefusal::Dropped => refusal.to_string(),
1050 })
1051}
1052
1053/// Hold an outbound request until the write it follows is durable, then hand
1054/// it to the host.
1055///
1056/// The send moves inside the future deliberately. These channels dispatch as
1057/// soon as `send` is called, so gating anywhere after it would let the effect
1058/// leave first -- the request would already be on its way while the caller
1059/// waited for a durability answer that no longer decides anything.
1060async fn gated_channel_send<T>(
1061 gate: EgressGate,
1062 channel: &'static OnceLock<tokio::sync::mpsc::UnboundedSender<T>>,
1063 request: T,
1064 missing: &'static str,
1065) -> std::result::Result<(), String> {
1066 await_egress_gate(gate).await?;
1067 match channel.get() {
1068 Some(tx) if tx.send(request).is_ok() => Ok(()),
1069 _ => Err(missing.to_string()),
1070 }
1071}
1072
1073/// One `celld_logic::gate::InputGate` per cell.
1074///
1075/// The logic decides; this is only the map and the ids. It replaces the
1076/// promise chain that used to live in `harness.js`, which serialised blocks
1077/// against each other but did nothing about *delivery* — so a second event
1078/// could arrive mid-block, and under real concurrency that wedged the cell.
1079///
1080/// Keyed by cell scope rather than held on the isolate, because a gate
1081/// belongs to a cell and cells share isolates.
1082static CELL_GATES: OnceLock<Mutex<HashMap<String, CellGate>>> = OnceLock::new();
1083static NEXT_GATE_EVENT: AtomicU64 = AtomicU64::new(1);
1084// Cell gates are process-wide, so their owner ids must not repeat in another
1085// isolate. A per-isolate sequence can make one event appear to own another
1086// isolate's gate and keep the wrong event alive.
1087static NEXT_IO_CONTEXT_ID: AtomicU64 = AtomicU64::new(0);
1088
1089fn allocate_io_context_id() -> u64 {
1090 NEXT_IO_CONTEXT_ID
1091 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
1092 current.checked_add(1)
1093 })
1094 .unwrap_or_else(|_| panic!("the process exhausted its IoContext ids"))
1095 + 1
1096}
1097
1098/// One cell's input gate, with the event that holds it and the events queued
1099/// to take it, named by the continuation id of their `IoContext`.
1100///
1101/// The critical section binds this owner to its continuation's operation
1102/// driver before acquisition. An ordinary continuation belongs to its origin;
1103/// a critical section retains the driver that started it, even when a foreign
1104/// checkpoint resumes its callback. The origin claim preserves the separate
1105/// resource context. Recording only the ambient turn here lets that event
1106/// retire while another driver polls the acquisition, rejecting a live block.
1107#[derive(Default)]
1108struct CellGate {
1109 gate: celld_logic::gate::InputGate,
1110 holder: Option<u64>,
1111 /// A reaction can belong to an event other than the turn owner. The claim
1112 /// keeps that originating event and its resources active until the block
1113 /// ends. A same-event block needs no claim because its `InFlight` owns the
1114 /// gate itself.
1115 origin: Option<CrossEntryGateClaim>,
1116 /// Counted, because one event can start several blocks at once.
1117 queued: HashMap<u64, u32>,
1118}
1119
1120/// How many holds and queued takes exist across every gate, so the checks
1121/// every turn makes can skip the map while no event blocks at all, which is
1122/// nearly always.
1123static GATE_ENGAGEMENTS: AtomicUsize = AtomicUsize::new(0);
1124
1125fn cell_gates() -> &'static Mutex<HashMap<String, CellGate>> {
1126 CELL_GATES.get_or_init(|| Mutex::new(HashMap::new()))
1127}
1128
1129impl CellGate {
1130 fn take(
1131 &mut self,
1132 event: celld_logic::gate::EventId,
1133 owner: Option<u64>,
1134 origin: &mut Option<CrossEntryGateClaim>,
1135 ) -> bool {
1136 let was_open = self.gate.is_open();
1137 let taken = self.gate.acquire(event);
1138 if taken && was_open {
1139 self.set_holder(owner, origin.take());
1140 }
1141 taken
1142 }
1143
1144 fn set_holder(&mut self, owner: Option<u64>, origin: Option<CrossEntryGateClaim>) {
1145 if self.holder.is_none() && owner.is_some() {
1146 GATE_ENGAGEMENTS.fetch_add(1, Ordering::Relaxed);
1147 }
1148 self.holder = owner;
1149 self.origin = origin;
1150 }
1151
1152 fn clear_holder(&mut self) -> Option<CrossEntryGateClaim> {
1153 if self.holder.take().is_some() {
1154 GATE_ENGAGEMENTS.fetch_sub(1, Ordering::Relaxed);
1155 }
1156 self.origin.take()
1157 }
1158
1159 fn release(
1160 &mut self,
1161 event: celld_logic::gate::EventId,
1162 ) -> (bool, Option<CrossEntryGateClaim>) {
1163 if !self.gate.release(event) {
1164 return (false, None);
1165 }
1166 (true, self.clear_holder())
1167 }
1168
1169 fn abandon(
1170 &mut self,
1171 event: celld_logic::gate::EventId,
1172 ) -> (bool, Option<CrossEntryGateClaim>) {
1173 if !self.gate.abandon(event) {
1174 return (false, None);
1175 }
1176 (true, self.clear_holder())
1177 }
1178
1179 fn is_unused(&self) -> bool {
1180 self.gate.is_open() && self.queued.is_empty()
1181 }
1182}
1183
1184/// How the event running under `context` is engaged with the cells' gates:
1185/// it holds one, it is queued to take one, or neither.
1186///
1187/// Every gate is searched, not only the gate of the event's own cell: a
1188/// reaction of cell A's event can run inside cell B's checkpoint, and the
1189/// block it starts then belongs to A's gate while its ops belong to B's
1190/// entry. B's entry is the one that must keep them, and it finds itself
1191/// through its own id whichever gate names it.
1192#[derive(Clone, Copy, PartialEq, Eq)]
1193enum GateEngagement {
1194 Holds,
1195 Queued,
1196 None,
1197}
1198
1199fn gate_engagement(cell: Option<&str>, context: &Arc<IoContext>) -> GateEngagement {
1200 if GATE_ENGAGEMENTS.load(Ordering::Relaxed) == 0 {
1201 return GateEngagement::None;
1202 }
1203 let Some(id) = context.continuation_id() else {
1204 return GateEngagement::None;
1205 };
1206 fn of(gate: &CellGate, id: u64) -> GateEngagement {
1207 if !gate.gate.is_open() && gate.holder == Some(id) {
1208 GateEngagement::Holds
1209 } else if gate.queued.contains_key(&id) {
1210 GateEngagement::Queued
1211 } else {
1212 GateEngagement::None
1213 }
1214 }
1215 let gates = cell_gates().lock().unwrap();
1216 // The event's own cell first: nearly every block is on it, and the walk
1217 // below is the price of the cross-cell case alone.
1218 if let Some(gate) = cell.and_then(|cell| gates.get(cell)) {
1219 let engagement = of(gate, id);
1220 if engagement != GateEngagement::None {
1221 return engagement;
1222 }
1223 }
1224 let mut engagement = GateEngagement::None;
1225 for gate in gates.values() {
1226 match of(gate, id) {
1227 GateEngagement::Holds => return GateEngagement::Holds,
1228 GateEngagement::Queued => engagement = GateEngagement::Queued,
1229 GateEngagement::None => {}
1230 }
1231 }
1232 engagement
1233}
1234
1235/// What a waiting event is told when the gate finally opens: nothing, or
1236/// the reason the holder failed.
1237type GateWake = tokio::sync::oneshot::Sender<Result<(), String>>;
1238
1239static GATE_WAITERS: OnceLock<Mutex<HashMap<String, Vec<GateWake>>>> = OnceLock::new();
1240
1241/// Events waiting for a cell's input gate to open, in arrival order.
1242///
1243/// An earlier implementation deleted this queue because an event the gate
1244/// refused stayed on the cell's job channel until a later delivery point
1245/// took it, so the channel *was* the queue and a second one could disagree
1246/// with it. Drives have no channel, so a refused event needs somewhere to
1247/// wait, and workerd keeps the same structure for the same reason
1248/// (`io-gate.h`, `kj::List<Waiter, &Waiter::link> waiters`).
1249///
1250/// In the shell rather than in `celld_logic::gate`, because what waits is a
1251/// tokio task and the core is sans-IO. The core still owns the decision —
1252/// `is_open` — and this owns only the waking.
1253fn gate_waiters() -> &'static Mutex<HashMap<String, Vec<GateWake>>> {
1254 GATE_WAITERS.get_or_init(|| Mutex::new(HashMap::new()))
1255}
1256
1257/// Take a ticket to be woken when `cell`'s gate opens, or `None` if it is
1258/// open now.
1259///
1260/// The gate's lock is held across the check and the enqueue, so a release
1261/// that lands between the two cannot leave an event waiting on a gate that
1262/// is already open.
1263pub fn cell_gate_wait(cell: &str) -> Option<tokio::sync::oneshot::Receiver<Result<(), String>>> {
1264 let gates = cell_gates().lock().unwrap();
1265 if gates.get(cell).is_none_or(|gate| gate.gate.is_open()) {
1266 return None;
1267 }
1268 let (wake, waiter) = tokio::sync::oneshot::channel();
1269 gate_waiters()
1270 .lock()
1271 .unwrap()
1272 .entry(cell.to_string())
1273 .or_default()
1274 .push(wake);
1275 drop(gates);
1276 Some(waiter)
1277}
1278
1279enum CellGateAcquisition {
1280 Acquired,
1281 Waiting {
1282 gate: tokio::sync::oneshot::Receiver<Result<(), String>>,
1283 retirement: tokio::sync::watch::Receiver<bool>,
1284 },
1285 Retired,
1286}
1287
1288/// Acquire `cell` for `event`, or enqueue its next attempt before the gate can
1289/// change state.
1290///
1291/// A failed holder wakes its existing waiters with an error. Separating the
1292/// failed acquisition from waiter registration lets that failure land between
1293/// the two, so the event can miss the error and run against the reset actor.
1294/// The context lock also covers the successful host claim, so event retirement
1295/// cannot land between acquiring the process gate and recording its owner.
1296fn acquire_cell_gate(
1297 context: &IoContext,
1298 cell: &str,
1299 event: celld_logic::gate::EventId,
1300 owner: Option<u64>,
1301 origin: &mut Option<CrossEntryGateClaim>,
1302) -> CellGateAcquisition {
1303 let mut claims = context.input_gates.lock().unwrap();
1304 if claims.retired {
1305 return CellGateAcquisition::Retired;
1306 }
1307 let mut gates = cell_gates().lock().unwrap();
1308 if gates
1309 .entry(cell.to_string())
1310 .or_default()
1311 .take(event, owner, origin)
1312 {
1313 let previous = claims.held.insert(event, cell.to_string());
1314 assert!(previous.is_none(), "an input-gate event id was reused");
1315 return CellGateAcquisition::Acquired;
1316 }
1317 let (wake, waiter) = tokio::sync::oneshot::channel();
1318 gate_waiters()
1319 .lock()
1320 .unwrap()
1321 .entry(cell.to_string())
1322 .or_default()
1323 .push(wake);
1324 let retirement = claims.retirement.subscribe();
1325 drop(gates);
1326 CellGateAcquisition::Waiting {
1327 gate: waiter,
1328 retirement,
1329 }
1330}
1331
1332/// Wake everything waiting on `cell`'s gate. Each re-checks and re-queues if
1333/// another block took the gate first, so waking all of them is correct and
1334/// the order they resume in is theirs to lose, not this function's to keep.
1335fn wake_gate_waiters(cell: &str, outcome: Result<(), String>) {
1336 let waiters = gate_waiters().lock().unwrap().remove(cell);
1337 for wake in waiters.into_iter().flatten() {
1338 let _ = wake.send(outcome.clone());
1339 }
1340}
1341
1342const ABANDONED_INPUT_GATE: &str = "the cell's critical section ended without releasing";
1343const RETIRED_INPUT_GATE: &str = "the cell event ended before it could acquire an input gate";
1344
1345/// Release one completed block and remove the open gate from the process map.
1346fn release_cell_gate(cell: &str, event: celld_logic::gate::EventId, outcome: Result<(), String>) {
1347 let origin = {
1348 let mut gates = cell_gates().lock().unwrap();
1349 let Some(gate) = gates.get_mut(cell) else {
1350 return;
1351 };
1352 let (opened, origin) = gate.release(event);
1353 // A stale release or a remaining nested hold cannot wake the waiters.
1354 // In particular, a stale error must not fail a replacement holder's
1355 // queued events.
1356 if !opened {
1357 return;
1358 }
1359 if gate.is_unused() {
1360 gates.remove(cell);
1361 }
1362 origin
1363 };
1364 // Releasing the origin claim can wake its drive and eventually run
1365 // `IoContext::drop`, which also locks the gate map. Keep that work outside
1366 // the map's lock.
1367 drop(origin);
1368 wake_gate_waiters(cell, outcome);
1369}
1370
1371/// Retire `context`'s waiters and abandon every input gate that it still owns.
1372///
1373/// The event id is part of each claim. A concurrent event can already be
1374/// running when this one dies, so a cell name alone cannot safely decide
1375/// which holder to release. Removing the open map entry also prevents an old
1376/// cell incarnation from leaving process-wide state for a later one.
1377fn abandon_context_input_gates(context: &IoContext) -> Vec<(String, celld_logic::gate::EventId)> {
1378 let claims = context.retire_input_gates();
1379 for (cell, event) in &claims {
1380 let (abandoned, origin) = {
1381 let mut gates = cell_gates().lock().unwrap();
1382 let (abandoned, origin) = gates
1383 .get_mut(cell)
1384 .map_or((false, None), |gate| gate.abandon(*event));
1385 if abandoned {
1386 gates.remove(cell);
1387 }
1388 (abandoned, origin)
1389 };
1390 // See `release_cell_gate`: releasing an origin can re-enter this map
1391 // from its eventual context destructor.
1392 drop(origin);
1393 if abandoned {
1394 wake_gate_waiters(cell, Err(ABANDONED_INPUT_GATE.to_string()));
1395 }
1396 }
1397 claims
1398}
1399
1400/// JS promise resolvers awaiting an async op, keyed by the op's id.
1401///
1402/// **Per isolate, and shared across threads.** Under D1 a request's turns run
1403/// on whichever tokio worker picks them up, so a resolver registered on one
1404/// thread is resolved from another; a thread-local map loses it, and
1405/// `resolve_res` fails to find the resolver and returns silently, leaving the
1406/// handler awaiting a promise nothing will ever settle. The `Mutex` is what
1407/// makes that safe, not the map's location.
1408///
1409/// It lives on `ActorRuntimeState` — one per isolate, reached from a scope —
1410/// so a resolver is only ever looked up in the heap that owns it. One map for
1411/// the whole process would also work, because op ids come from a single
1412/// counter (`asyncrt::NEXT_ID`) and an id names exactly one resolver. But that
1413/// makes an id-allocation bug into cross-isolate handle confusion, where this
1414/// makes it a miss.
1415type PromiseMap = HashMap<u64, v8::Global<v8::PromiseResolver>>;
1416
1417/// Requests cancelled by a reentrant `AbortFetch`. Global for the same reason
1418/// as [`promises`]: the turn that observes a cancellation need not be on the
1419/// thread that recorded it.
1420static CANCELLED_REQUESTS: OnceLock<Mutex<HashSet<RequestId>>> = OnceLock::new();
1421
1422fn cancelled_requests() -> &'static Mutex<HashSet<RequestId>> {
1423 CANCELLED_REQUESTS.get_or_init(|| Mutex::new(HashSet::new()))
1424}
1425
1426fn promise_store(scope: &mut v8::PinScope, id: u64, r: v8::Global<v8::PromiseResolver>) {
1427 actor_runtime_state(scope)
1428 .promises
1429 .lock()
1430 .unwrap()
1431 .insert(id, r);
1432}
1433
1434/// Resolve or reject op `id`'s promise with its outcome.
1435fn resolve_res(tc: &mut v8::PinScope, id: u64, res: Result<asyncrt::OpOut, String>) {
1436 let g = match actor_runtime_state(tc).promises.lock().unwrap().remove(&id) {
1437 Some(g) => g,
1438 None => return,
1439 };
1440 let r = v8::Local::new(tc, g);
1441 match res {
1442 Ok(asyncrt::OpOut::Str(v)) => {
1443 let s = v8::String::new(tc, &v).unwrap();
1444 r.resolve(tc, s.into());
1445 }
1446 Ok(asyncrt::OpOut::Bytes(b)) => {
1447 let v = bytes_value(tc, b);
1448 r.resolve(tc, v);
1449 }
1450 Err(e) => {
1451 let s = v8::String::new(tc, &e).unwrap();
1452 let ex = v8::Exception::error(tc, s);
1453 r.reject(tc, ex);
1454 }
1455 }
1456}
1457
1458/// Move `bytes` into a `Uint8Array` without copying.
1459fn bytes_value<'s>(scope: &mut v8::PinScope<'s, '_>, bytes: Vec<u8>) -> v8::Local<'s, v8::Value> {
1460 #[cfg(celld_internal_tests)]
1461 let input = bytes.as_ptr() as usize;
1462 let len = bytes.len();
1463 let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();
1464 let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);
1465 #[cfg(celld_internal_tests)]
1466 record_bytes_value_allocation_for_test(
1467 input,
1468 buffer
1469 .get_backing_store()
1470 .data()
1471 .map(|data| data.as_ptr() as usize),
1472 );
1473 v8::Uint8Array::new(scope, buffer, 0, len).unwrap().into()
1474}
1475
1476#[cfg(celld_internal_tests)]
1477static BYTES_VALUE_ALLOCATION_PROBE: Mutex<Option<(usize, Option<usize>)>> = Mutex::new(None);
1478
1479#[cfg(celld_internal_tests)]
1480#[doc(hidden)]
1481pub fn capture_bytes_value_allocation_for_test(expected: *const u8) {
1482 *BYTES_VALUE_ALLOCATION_PROBE.lock().unwrap() = Some((expected as usize, None));
1483}
1484
1485#[cfg(celld_internal_tests)]
1486fn record_bytes_value_allocation_for_test(input: usize, output: Option<usize>) {
1487 let mut probe = BYTES_VALUE_ALLOCATION_PROBE.lock().unwrap();
1488 if probe
1489 .as_ref()
1490 .is_some_and(|(expected, _)| *expected == input)
1491 {
1492 *probe = Some((input, output));
1493 }
1494}
1495
1496#[cfg(celld_internal_tests)]
1497#[doc(hidden)]
1498pub fn take_bytes_value_allocation_for_test() -> Option<usize> {
1499 BYTES_VALUE_ALLOCATION_PROBE
1500 .lock()
1501 .unwrap()
1502 .take()
1503 .and_then(|(_, output)| output)
1504}
1505
1506#[cfg(unix)]
1507fn clock_nanos(clock: libc::clockid_t) -> Option<u64> {
1508 // SAFETY: `clock_gettime` initializes the complete `timespec` on success,
1509 // and the pointer remains valid for the call.
1510 let mut time = std::mem::MaybeUninit::<libc::timespec>::uninit();
1511 if unsafe { libc::clock_gettime(clock, time.as_mut_ptr()) } != 0 {
1512 return None;
1513 }
1514 // SAFETY: The successful call above initialized `time`.
1515 let time = unsafe { time.assume_init() };
1516 let seconds = u64::try_from(time.tv_sec).ok()?;
1517 let nanos = u64::try_from(time.tv_nsec).ok()?;
1518 seconds.checked_mul(1_000_000_000)?.checked_add(nanos)
1519}
1520
1521#[cfg(unix)]
1522fn platform_thread_cpu_nanos() -> Option<u64> {
1523 clock_nanos(libc::CLOCK_THREAD_CPUTIME_ID)
1524}
1525
1526#[cfg(not(unix))]
1527fn platform_thread_cpu_nanos() -> Option<u64> {
1528 None
1529}
1530
1531fn thread_cpu_nanos() -> Option<u64> {
1532 #[cfg(all(test, celld_internal_tests))]
1533 if let Some(sample) =
1534 THREAD_CPU_NANOS_SAMPLES_FOR_TEST.with(|samples| samples.borrow_mut().pop_front())
1535 {
1536 return sample;
1537 }
1538 platform_thread_cpu_nanos()
1539}
1540
1541#[cfg(target_os = "linux")]
1542#[derive(Clone, Copy)]
1543struct TargetThreadCpuClock(libc::clockid_t);
1544
1545#[cfg(target_os = "linux")]
1546impl TargetThreadCpuClock {
1547 fn current() -> Option<Self> {
1548 unsafe extern "C" {
1549 fn pthread_getcpuclockid(
1550 thread: libc::pthread_t,
1551 clock_id: *mut libc::clockid_t,
1552 ) -> libc::c_int;
1553 }
1554 let mut clock_id = std::mem::MaybeUninit::<libc::clockid_t>::uninit();
1555 // SAFETY: `pthread_self` returns the calling thread, and the output
1556 // pointer remains valid for the call.
1557 if unsafe { pthread_getcpuclockid(libc::pthread_self(), clock_id.as_mut_ptr()) } != 0 {
1558 return None;
1559 }
1560 // SAFETY: The successful call above initialized `clock_id`.
1561 Some(Self(unsafe { clock_id.assume_init() }))
1562 }
1563
1564 fn nanos(self) -> Option<u64> {
1565 clock_nanos(self.0)
1566 }
1567}
1568
1569#[cfg(target_os = "macos")]
1570#[derive(Clone, Copy)]
1571struct TargetThreadCpuClock(libc::mach_port_t);
1572
1573#[cfg(target_os = "macos")]
1574impl TargetThreadCpuClock {
1575 fn current() -> Option<Self> {
1576 // SAFETY: Both calls inspect the calling thread and transfer no
1577 // ownership. The returned Mach thread port remains valid while this
1578 // turn holds the execution thread.
1579 Some(Self(unsafe {
1580 libc::pthread_mach_thread_np(libc::pthread_self())
1581 }))
1582 }
1583
1584 fn nanos(self) -> Option<u64> {
1585 let mut info = std::mem::MaybeUninit::<libc::thread_basic_info>::uninit();
1586 let mut count = libc::THREAD_BASIC_INFO_COUNT;
1587 // SAFETY: `info` has the size described by `count`, and `thread_info`
1588 // initializes it completely when the call succeeds.
1589 let status = unsafe {
1590 libc::thread_info(
1591 self.0,
1592 u32::try_from(libc::THREAD_BASIC_INFO).expect("thread info flavor is positive"),
1593 info.as_mut_ptr().cast::<libc::integer_t>(),
1594 &mut count,
1595 )
1596 };
1597 if status != libc::KERN_SUCCESS {
1598 return None;
1599 }
1600 // SAFETY: The successful call above initialized `info`.
1601 let info = unsafe { info.assume_init() };
1602 let user_seconds = u64::try_from(info.user_time.seconds).ok()?;
1603 let user_micros = u64::try_from(info.user_time.microseconds).ok()?;
1604 let system_seconds = u64::try_from(info.system_time.seconds).ok()?;
1605 let system_micros = u64::try_from(info.system_time.microseconds).ok()?;
1606 user_seconds
1607 .checked_add(system_seconds)?
1608 .checked_mul(1_000_000_000)?
1609 .checked_add(user_micros.checked_add(system_micros)?.checked_mul(1_000)?)
1610 }
1611}
1612
1613#[cfg(not(any(target_os = "linux", target_os = "macos")))]
1614#[derive(Clone, Copy)]
1615struct TargetThreadCpuClock;
1616
1617#[cfg(not(any(target_os = "linux", target_os = "macos")))]
1618impl TargetThreadCpuClock {
1619 fn current() -> Option<Self> {
1620 None
1621 }
1622
1623 fn nanos(self) -> Option<u64> {
1624 None
1625 }
1626}
1627
1628/// Aborts raised by an HTTP or service-binding caller disconnecting while the
1629/// target runs in the stateless isolate pool. Durable Object aborts can also
1630/// arrive as a reentrant `CellJob::AbortFetch`, so the abort has to be visible
1631/// from whichever turn observes it.
1632///
1633/// The counter keeps the common path to one relaxed atomic load per loop turn:
1634/// with nothing pending, the mutex is never taken.
1635static PENDING_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> =
1636 OnceLock::new();
1637static SHUTDOWN_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> =
1638 OnceLock::new();
1639static PENDING_ABORT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1640
1641fn pending_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> {
1642 PENDING_ABORTS.get_or_init(Default::default)
1643}
1644
1645fn shutdown_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> {
1646 SHUTDOWN_ABORTS.get_or_init(Default::default)
1647}
1648
1649#[cfg(all(test, celld_internal_tests))]
1650type AbortRequestPauseForTest = (
1651 RequestId,
1652 std::sync::mpsc::Sender<()>,
1653 std::sync::mpsc::Receiver<()>,
1654);
1655
1656#[cfg(all(test, celld_internal_tests))]
1657static ABORT_REQUEST_PAUSE_FOR_TEST: Mutex<Option<AbortRequestPauseForTest>> = Mutex::new(None);
1658
1659#[cfg(all(test, celld_internal_tests))]
1660pub(crate) struct AbortRequestPauseHandleForTest {
1661 entered: std::sync::mpsc::Receiver<()>,
1662 release: Option<std::sync::mpsc::Sender<()>>,
1663}
1664
1665#[cfg(all(test, celld_internal_tests))]
1666impl AbortRequestPauseHandleForTest {
1667 pub(crate) fn wait_until_entered(&self) {
1668 self.entered
1669 .recv()
1670 .expect("the abort publisher dropped before its publication seam");
1671 }
1672
1673 pub(crate) fn release(mut self) {
1674 self.release
1675 .take()
1676 .expect("the abort publication pause was released twice")
1677 .send(())
1678 .expect("the abort publisher dropped while paused");
1679 }
1680}
1681
1682#[cfg(all(test, celld_internal_tests))]
1683pub(crate) fn pause_abort_request_for_test(
1684 request_id: RequestId,
1685) -> AbortRequestPauseHandleForTest {
1686 let (entered_tx, entered) = std::sync::mpsc::channel();
1687 let (release, release_rx) = std::sync::mpsc::channel();
1688 let previous = ABORT_REQUEST_PAUSE_FOR_TEST
1689 .lock()
1690 .unwrap()
1691 .replace((request_id, entered_tx, release_rx));
1692 assert!(
1693 previous.is_none(),
1694 "an abort publication pause is already armed"
1695 );
1696 AbortRequestPauseHandleForTest {
1697 entered,
1698 release: Some(release),
1699 }
1700}
1701
1702#[cfg(all(test, celld_internal_tests))]
1703pub(crate) fn pause_abort_request_if_armed_for_test(request_id: RequestId) {
1704 let pause = {
1705 let mut pause = ABORT_REQUEST_PAUSE_FOR_TEST.lock().unwrap();
1706 if pause
1707 .as_ref()
1708 .is_some_and(|(expected, _, _)| *expected == request_id)
1709 {
1710 pause.take()
1711 } else {
1712 None
1713 }
1714 };
1715 if let Some((_, entered, release)) = pause {
1716 entered
1717 .send(())
1718 .expect("the abort publication test dropped its observer");
1719 release
1720 .recv()
1721 .expect("the abort publication test dropped its release");
1722 }
1723}
1724
1725#[cfg(all(test, celld_internal_tests))]
1726pub(crate) fn request_cancellation_state_for_test(request_id: RequestId) -> (bool, bool) {
1727 (
1728 pending_aborts().lock().unwrap().contains(&request_id),
1729 cancelled_requests().lock().unwrap().contains(&request_id),
1730 )
1731}
1732
1733/// Mark an in-flight request cancelled from any thread.
1734pub fn abort_request(request_id: RequestId) {
1735 #[cfg(all(test, celld_internal_tests))]
1736 pause_abort_request_if_armed_for_test(request_id);
1737 if pending_aborts().lock().unwrap().insert(request_id) {
1738 PENDING_ABORT_COUNT.fetch_add(1, Ordering::Relaxed);
1739 }
1740}
1741
1742/// Force a cell event to retire for a lifecycle transition. Unlike a client
1743/// disconnect, shutdown cannot preserve `waitUntil` work because the runtime
1744/// and its ownership are about to leave this process.
1745pub fn abort_request_for_shutdown(request_id: RequestId) {
1746 shutdown_aborts().lock().unwrap().insert(request_id);
1747 abort_request(request_id);
1748}
1749
1750pub(crate) fn clear_request_cancellation(request_id: RequestId) {
1751 let _ = take_pending_abort(request_id);
1752 cancelled_requests().lock().unwrap().remove(&request_id);
1753 shutdown_aborts().lock().unwrap().remove(&request_id);
1754}
1755
1756pub fn take_shutdown_cancellation(request_id: Option<RequestId>) -> bool {
1757 request_id.is_some_and(|request_id| shutdown_aborts().lock().unwrap().remove(&request_id))
1758}
1759
1760#[cfg(celld_internal_tests)]
1761#[doc(hidden)]
1762pub fn clear_request_cancellation_for_test(request_id: RequestId) {
1763 clear_request_cancellation(request_id);
1764}
1765
1766fn take_pending_abort(request_id: RequestId) -> bool {
1767 if PENDING_ABORT_COUNT.load(Ordering::Relaxed) == 0 {
1768 return false;
1769 }
1770 if pending_aborts().lock().unwrap().remove(&request_id) {
1771 PENDING_ABORT_COUNT.fetch_sub(1, Ordering::Relaxed);
1772 return true;
1773 }
1774 false
1775}
1776
1777pub fn take_request_cancellation(request_id: Option<RequestId>) -> bool {
1778 request_id.is_some_and(|request_id| {
1779 cancelled_requests().lock().unwrap().remove(&request_id) || take_pending_abort(request_id)
1780 })
1781}
1782
1783fn resolved_promise<'s>(
1784 tc: &mut v8::PinScope<'s, '_>,
1785 value: v8::Local<'s, v8::Value>,
1786) -> Result<v8::Local<'s, v8::Promise>> {
1787 let resolver =
1788 v8::PromiseResolver::new(tc).ok_or_else(|| anyhow!("could not create event promise"))?;
1789 resolver.resolve(tc, value);
1790 Ok(resolver.get_promise(tc))
1791}
1792
1793fn abort_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) -> Result<bool> {
1794 let function = event_hook(tc, |hooks| &hooks.abort_incoming_request)?;
1795 let request_id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
1796 let recv = v8::undefined(tc).into();
1797 let result = function
1798 .call(tc, recv, &[request_id.into()])
1799 .ok_or_else(|| anyhow!("__abortIncomingRequest threw"))?;
1800 Ok(result.boolean_value(tc))
1801}
1802
1803/// The rejection reason of a settled-rejected promise, with a little stack.
1804fn reject_reason(tc: &mut v8::PinScope, p: v8::Local<v8::Promise>) -> String {
1805 let r = p.result(tc);
1806 let msg = r.to_rust_string_lossy(tc);
1807 let stk = r
1808 .to_object(tc)
1809 .and_then(|o| {
1810 let k = v8::String::new(tc, "stack")?;
1811 o.get(tc, k.into())
1812 })
1813 .map(|s| s.to_rust_string_lossy(tc))
1814 .unwrap_or_default();
1815 let tail = stk
1816 .lines()
1817 .skip(1)
1818 .take(3)
1819 .map(|l| l.trim())
1820 .collect::<Vec<_>>()
1821 .join(" <- ");
1822 if tail.is_empty() {
1823 msg
1824 } else {
1825 format!("{msg} [{tail}]")
1826 }
1827}
1828
1829pub struct Engine;
1830impl Engine {
1831 pub fn init() {
1832 // V8 is process-global, so the guard belongs to the initializer. A
1833 // guard at each caller allowed two callers to each initialize V8 once,
1834 // which poisoned the global state when both ran.
1835 static INIT: std::sync::Once = std::sync::Once::new();
1836 INIT.call_once(|| {
1837 #[cfg(celld_internal_tests)]
1838 v8::V8::set_flags_from_string("--expose-gc");
1839 // No `v8::icu::set_common_data_78` call: the rusty_v8 152 prebuilt
1840 // statically links the complete ICU data (full locale tables and
1841 // regex property-of-strings, e.g. /\p{RGI_Emoji}/v — verified
1842 // empirically), so overriding it with an embedded icudtl.dat only
1843 // duplicated 10.8 MB in the binary. The required coverage is
1844 // explicit, so a future v8 bump that reduces the builtin data
1845 // fails rather than silently narrowing it; the fix would be to
1846 // re-embed rusty_v8's `third_party/icu/common/icudtl.dat`,
1847 // 16-byte-aligned.
1848 let platform = v8::new_default_platform(0, false).make_shared();
1849 v8::V8::initialize_platform(platform);
1850 v8::V8::initialize();
1851 });
1852 }
1853}
1854
1855/// The resource name the entry module compiles under. It is also the name the
1856/// entry module is projected under in `/bundle`, so a stack frame and a bundle
1857/// path name the same file.
1858const ENTRY_MODULE_NAME: &str = "worker.js";
1859
1860/// One queue's push consumer after the owning script has been resolved.
1861#[derive(Clone)]
1862pub struct QueueConsumerRegistration {
1863 pub script: String,
1864 pub config: crate::protocol::QueueConsumerConfig,
1865}
1866
1867#[derive(Clone, Copy, PartialEq, Eq)]
1868enum WorkerOrigin {
1869 Deployment,
1870 Dynamic,
1871}
1872
1873type ResourceLimits = crate::WorkerInvocationLimits;
1874
1875fn effective_resource_limits(
1876 configured: Option<ResourceLimits>,
1877 invocation: Option<ResourceLimits>,
1878) -> Option<ResourceLimits> {
1879 let lower = |configured: Option<u32>, invocation: Option<u32>| match (configured, invocation) {
1880 (Some(configured), Some(invocation)) => Some(configured.min(invocation)),
1881 (configured, invocation) => configured.or(invocation),
1882 };
1883 let limits = ResourceLimits {
1884 cpu_ms: lower(
1885 configured.and_then(|limits| limits.cpu_ms),
1886 invocation.and_then(|limits| limits.cpu_ms),
1887 ),
1888 sub_requests: lower(
1889 configured.and_then(|limits| limits.sub_requests),
1890 invocation.and_then(|limits| limits.sub_requests),
1891 ),
1892 };
1893 (limits.cpu_ms.is_some() || limits.sub_requests.is_some()).then_some(limits)
1894}
1895
1896struct CpuTurnStart {
1897 thread_nanos: Option<u64>,
1898 wall: Instant,
1899}
1900
1901#[derive(Clone)]
1902struct LoaderEnvRoute {
1903 script: String,
1904 entrypoint: Option<String>,
1905 props: Vec<u8>,
1906}
1907
1908#[derive(Clone)]
1909struct LoaderEnv {
1910 bytes: Vec<u8>,
1911 routes: Vec<LoaderEnvRoute>,
1912}
1913
1914pub struct WorkerConfig {
1915 src: String,
1916 /// The canonical module name for `src`. Dynamic Workers preserve the
1917 /// caller's `mainModule` path so relative imports use its directory.
1918 main_module_name: String,
1919 pub script_name: String,
1920 /// The construction path that grants Dynamic Worker load semantics.
1921 /// A script name is caller-controlled, so it cannot prove this origin.
1922 origin: WorkerOrigin,
1923 do_classes: Vec<String>,
1924 bindings: Vec<(String, String)>,
1925 /// `r2_buckets`: (environment name, bucket name). The bucket name is
1926 /// the key space the binding owns inside the fleet bucket; see [[r2]].
1927 r2_bindings: Vec<(String, String)>,
1928 /// `d1_databases`: (environment name, stable database identity). The
1929 /// identity addresses the cell that holds the database; see [[d1]].
1930 d1_bindings: Vec<(String, String)>,
1931 /// `kv_namespaces`: (environment name, namespace identity). The identity is
1932 /// the config's `id` verbatim, and it addresses the namespace's cells; see
1933 /// [[kv]].
1934 kv_bindings: Vec<(String, String)>,
1935 queue_bindings: Vec<QueueBinding>,
1936 pub(crate) queue_consumers: Vec<QueueConsumerRegistration>,
1937 /// This script declared a consumer in its own manifest. The deployment-
1938 /// wide catalog later replaces `queue_consumers` in every isolate, so the
1939 /// catalog cannot answer whether this particular default export can omit
1940 /// `fetch` and provide only `queue`.
1941 declares_queue_consumer: bool,
1942 workflow_bindings: Vec<WorkflowBinding>,
1943 vars: Vec<(String, String)>,
1944 node: String,
1945 /// The worker's non-main modules, so the main module can import siblings.
1946 modules: Vec<(String, ModuleSource)>,
1947 compat: Compat,
1948 /// `[[services]]`: (binding name, target script, optional entrypoint).
1949 /// The target runs in this process; see [[service-bindings]].
1950 services: Vec<(String, String, Option<String>)>,
1951 asset_binding: Option<String>,
1952 /// `env` names of the Worker Loader bindings, if this Worker can spawn
1953 /// dynamic isolates. A config can declare more than one loader, and each
1954 /// binding gets a cache of its own, so a name loaded through one loader
1955 /// is a different Worker from the same name loaded through another.
1956 loader_bindings: Vec<String>,
1957 /// Ambient outbound authority. Loaded workers may be denied.
1958 egress: EgressPolicy,
1959 /// Structured-clone values and host-minted service routes that a loaded
1960 /// worker receives. Loader-only; empty for a normal worker.
1961 loader_env: Option<LoaderEnv>,
1962 /// Per-invocation limits supplied with a dynamically loaded Worker.
1963 /// Deployment Workers leave this empty.
1964 resource_limits: Option<ResourceLimits>,
1965 /// Whether a Dynamic Worker can receive a tail report sender on a fetch.
1966 tail_reporting: bool,
1967 /// `triggers.crons` from the deployment. Empty for a loaded worker and for
1968 /// any script without cron triggers.
1969 pub crons: Vec<String>,
1970 /// `containers` from the deployment: the classes whose `ctx.container`
1971 /// exists. Empty for a loaded worker.
1972 pub containers: Vec<crate::container::ContainerSpec>,
1973 /// The application generation this configuration belongs to. Every
1974 /// isolate built from it carries the value as a slot, so its host calls
1975 /// resolve against the deployment graph it was built with.
1976 pub generation: crate::generation::GenerationId,
1977 /// The external (`node:*`/`cloudflare:*`) imports of `src`.
1978 ///
1979 /// The scan walks the whole bundle, which an esbuild artifact makes
1980 /// megabytes, and its answer depends only on `src` — a field nothing
1981 /// mutates after construction. It used to run inside `load_config`,
1982 /// so a deployment paid it again on every cell wake and on every
1983 /// stateless pool thread. One `Arc<WorkerConfig>` backs all of those
1984 /// isolates, so scanning here pays it once instead.
1985 main_imports: modules::ExternalImports,
1986 /// The same scan for each `ModuleSource::EsModule` sibling, in the order
1987 /// `es_module_sources` yields them. Read through
1988 /// [`WorkerConfig::es_modules`], which hands a module and its scan out
1989 /// together so no caller can pair a module with another module's scan.
1990 module_imports: Vec<modules::ExternalImports>,
1991}
1992
1993/// The `ModuleSource::EsModule` siblings of a worker, as (name, source).
1994///
1995/// The single definition of that order: `WorkerConfig::new` scans in it and
1996/// `WorkerConfig::es_modules` zips against it, so the two cannot disagree.
1997fn es_module_sources(modules: &[(String, ModuleSource)]) -> impl Iterator<Item = (&str, &str)> {
1998 modules.iter().filter_map(|(name, source)| match source {
1999 ModuleSource::EsModule(source) => Some((name.as_str(), source.as_str())),
2000 _ => None,
2001 })
2002}
2003
2004#[derive(Clone, serde::Serialize)]
2005#[serde(rename_all = "camelCase")]
2006struct TailLog {
2007 timestamp: i64,
2008 level: String,
2009 message: Vec<String>,
2010}
2011
2012const TAIL_LOG_LIMIT_BYTES: usize = 256 * 1024;
2013
2014#[derive(Default)]
2015struct TailLogCapture {
2016 records: Vec<TailLog>,
2017 /// The serialized record bytes, including separators but excluding the
2018 /// two array delimiters. The records and this measure share one lock, so
2019 /// no caller can retain a record without charging it to the same budget.
2020 serialized_bytes: usize,
2021 /// A record that crosses the limit ends capture for this invocation.
2022 /// Continuing after that record would expose later context that Workerd
2023 /// omits, even when a smaller record could fit in the remaining budget.
2024 full: bool,
2025}
2026
2027#[derive(Default)]
2028struct JsonByteCounter(usize);
2029
2030impl std::io::Write for JsonByteCounter {
2031 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
2032 self.0 = self.0.saturating_add(bytes.len());
2033 Ok(bytes.len())
2034 }
2035
2036 fn flush(&mut self) -> std::io::Result<()> {
2037 Ok(())
2038 }
2039}
2040
2041fn serialized_json_bytes(value: &impl serde::Serialize) -> usize {
2042 let mut counter = JsonByteCounter::default();
2043 serde_json::to_writer(&mut counter, value).expect("TailLog serialization is infallible");
2044 counter.0
2045}
2046
2047#[cfg(all(test, celld_internal_tests))]
2048fn tail_log_limit_bytes_for_test() -> usize {
2049 TAIL_LOG_LIMIT_BYTES
2050}
2051
2052impl WorkerConfig {
2053 pub fn new(options: WorkerConfigOptions) -> Self {
2054 let WorkerConfigOptions {
2055 src,
2056 script_name,
2057 do_classes,
2058 bindings,
2059 r2_bindings,
2060 d1_bindings,
2061 kv_bindings,
2062 queue_bindings,
2063 queue_consumers,
2064 workflow_bindings,
2065 vars,
2066 node,
2067 modules,
2068 compat,
2069 } = options;
2070 let main_imports = modules::scan_external_imports(&src);
2071 let module_imports = es_module_sources(&modules)
2072 .map(|(_name, source)| modules::scan_external_imports(source))
2073 .collect();
2074 let declares_queue_consumer = !queue_consumers.is_empty();
2075 let queue_consumers = queue_consumers
2076 .into_iter()
2077 .map(|config| QueueConsumerRegistration {
2078 script: script_name.clone(),
2079 config,
2080 })
2081 .collect();
2082 Self {
2083 src,
2084 main_module_name: ENTRY_MODULE_NAME.to_string(),
2085 script_name,
2086 origin: WorkerOrigin::Deployment,
2087 do_classes,
2088 bindings,
2089 r2_bindings,
2090 d1_bindings,
2091 kv_bindings,
2092 queue_bindings,
2093 queue_consumers,
2094 declares_queue_consumer,
2095 workflow_bindings,
2096 vars,
2097 node,
2098 modules,
2099 compat,
2100 services: Vec::new(),
2101 asset_binding: None,
2102 loader_bindings: Vec::new(),
2103 egress: EgressPolicy::Allow,
2104 loader_env: None,
2105 resource_limits: None,
2106 tail_reporting: false,
2107 crons: Vec::new(),
2108 containers: Vec::new(),
2109 generation: 0,
2110 main_imports,
2111 module_imports,
2112 }
2113 }
2114
2115 pub fn with_containers(mut self, containers: Vec<crate::container::ContainerSpec>) -> Self {
2116 self.containers = containers;
2117 self
2118 }
2119
2120 /// Whether cells of `class` supervise a container.
2121 pub fn container_class(&self, class: &str) -> bool {
2122 self.containers.iter().any(|spec| spec.class_name == class)
2123 }
2124
2125 /// Stamp this Worker with the application generation it serves.
2126 pub fn with_generation(mut self, generation: crate::generation::GenerationId) -> Self {
2127 self.generation = generation;
2128 self
2129 }
2130
2131 pub fn with_queue_consumers(mut self, consumers: Vec<QueueConsumerRegistration>) -> Self {
2132 self.queue_consumers = consumers;
2133 self
2134 }
2135
2136 /// Grant the relaxed load contract used only by a Worker Loader isolate.
2137 fn into_dynamic_worker(mut self) -> Self {
2138 self.origin = WorkerOrigin::Dynamic;
2139 self
2140 }
2141
2142 fn with_main_module_name(mut self, name: String) -> Self {
2143 self.main_module_name = name;
2144 self
2145 }
2146
2147 fn with_tail_reporting(mut self, enabled: bool) -> Self {
2148 self.tail_reporting = enabled;
2149 self
2150 }
2151 /// Every `ModuleSource::EsModule` sibling with its name, its source and
2152 /// its scanned external imports.
2153 fn es_modules(&self) -> impl Iterator<Item = (&str, &str, &modules::ExternalImports)> {
2154 // `zip` would truncate silently if the two ever disagreed, and a
2155 // truncated scan means a sibling links against a stub missing its
2156 // names. Both are filled from `es_module_sources` in `new`, so a
2157 // disagreement is a bug in a future mutator, not a reachable state.
2158 debug_assert_eq!(
2159 es_module_sources(&self.modules).count(),
2160 self.module_imports.len(),
2161 "an ES sibling lost its scanned imports",
2162 );
2163 es_module_sources(&self.modules)
2164 .zip(&self.module_imports)
2165 .map(|((name, source), imports)| (name, source, imports))
2166 }
2167
2168 /// Give this Worker the deployment's cron trigger expressions.
2169 pub fn with_crons(mut self, crons: Vec<String>) -> Self {
2170 self.crons = crons;
2171 self
2172 }
2173
2174 /// Grant this Worker a Worker Loader binding at each `env` name.
2175 pub fn with_loaders(mut self, bindings: Vec<String>) -> Self {
2176 self.loader_bindings = bindings;
2177 self
2178 }
2179
2180 /// Set this Worker's ambient outbound authority (loaded workers only).
2181 fn with_egress(mut self, egress: EgressPolicy) -> Self {
2182 self.egress = egress;
2183 self
2184 }
2185
2186 /// Install the limits that every invocation of this Dynamic Worker owns.
2187 fn with_resource_limits(mut self, limits: Option<ResourceLimits>) -> Self {
2188 self.resource_limits = limits;
2189 self
2190 }
2191
2192 /// Merge the caller's structured-clone `env` onto a loaded worker's env.
2193 fn with_loader_env(mut self, env: Option<LoaderEnv>) -> Self {
2194 self.loader_env = env;
2195 self
2196 }
2197
2198 /// Declare the service bindings this Worker may call.
2199 pub fn with_services(mut self, services: Vec<(String, String, Option<String>)>) -> Self {
2200 self.services = services;
2201 self
2202 }
2203
2204 pub fn with_asset_binding(mut self, binding: Option<String>) -> Self {
2205 self.asset_binding = binding;
2206 self
2207 }
2208}
2209
2210/// The storage authority installed when a cell enters an isolate.
2211///
2212/// The path and epoch form one value because opening either one without the
2213/// other would let later asynchronous work use the wrong ownership epoch.
2214#[doc(hidden)]
2215pub struct CellStorage<'a> {
2216 pub path: &'a str,
2217 pub epoch: u64,
2218 /// Fleet ownership supplies persistent writer epochs. Standalone ownership
2219 /// resets on restart and never publishes discovery objects.
2220 pub replicated_wake: bool,
2221 /// The activation's paged VFS, when its restore paged. The file at `path`
2222 /// is then sparse; opening it without this VFS reads holes as data.
2223 pub vfs: Option<&'a str>,
2224}
2225
2226pub struct Worker {
2227 inner: Option<WorkerIsolate>,
2228}
2229
2230pub struct WorkerIsolate {
2231 /// Shared rather than owned: under D1 an isolate belongs to no thread,
2232 /// and a worker enters it by taking its `v8::Locker`.
2233 ///
2234 /// Every `lock()` below blocks until the current holder releases. That is
2235 /// only safe because the pool takes an async permit for this isolate
2236 /// first, so the lock is uncontended by construction; a `lock()` reached
2237 /// without that permit would be a blocking call on a tokio worker.
2238 isolate: v8::SharedIsolate,
2239 runtime_state: Arc<ActorRuntimeState>,
2240 /// The one realm this isolate has: its context, and the entry `fetch`
2241 /// that lives in it.
2242 ///
2243 /// It was a `HashMap` keyed by cell, on the premise that a cell needs a
2244 /// realm of its own. It does not, and nothing ever put a second one in.
2245 /// The harness already keys instances by scope (`__cell.instances`), and
2246 /// Durable Objects **share** a context per script rather than getting one
2247 /// each — a context per cell would also duplicate the compiled module per
2248 /// cell, which is most of what sharing an isolate saves.
2249 realm: Realm,
2250 original_heap_limit: usize,
2251 compat: Compat,
2252 /// Identity used to reclaim every dynamic Worker this isolate created.
2253 /// Named Worker Loader identity lives in this isolate's JavaScript heap,
2254 /// so no child can remain charged to the registry after its owner is gone.
2255 loader_owner: LoaderOwner,
2256 /// The storage of the cells this isolate hosts.
2257 ///
2258 /// It lives here, and not in a thread-local, because a driven cell's
2259 /// turns run on whatever tokio worker holds the isolate. See
2260 /// `storage::Cells`.
2261 cells: storage::Cells,
2262}
2263
2264/// An isolate's context and the entry `fetch` that lives in it.
2265///
2266/// `fetch` is here rather than beside the isolate because a function is a
2267/// value in the realm that created it.
2268struct Realm {
2269 context: v8::Global<v8::Context>,
2270 fetch: v8::Global<v8::Function>,
2271}
2272
2273impl WorkerIsolate {
2274 fn cpu_watchdog(
2275 &self,
2276 remaining: Option<Duration>,
2277 declared_ms: Option<u32>,
2278 ) -> Option<CpuWatchdog> {
2279 CpuWatchdog::start(
2280 remaining,
2281 declared_ms,
2282 self.isolate.thread_safe_handle(),
2283 self.runtime_state.clone(),
2284 )
2285 }
2286
2287 fn initial_cpu_budget(&self) -> Option<Duration> {
2288 self.runtime_state
2289 .resource_limits
2290 .and_then(|limits| limits.cpu_ms)
2291 .map(|milliseconds| Duration::from_millis(u64::from(milliseconds)))
2292 }
2293
2294 /// Take the isolate for one turn, and make the cells it hosts reachable
2295 /// while it is held.
2296 ///
2297 /// The two belong together. The lock is what makes this thread the only
2298 /// one that can touch the isolate, and a cell's SQLite handles are part
2299 /// of what it may touch — so a locker taken without installing them
2300 /// would let a turn reach no storage at all, or another isolate's.
2301 /// Pairing them here is why no call site has to remember.
2302 fn lock(&self) -> (v8::Locker<'_>, storage::Installed) {
2303 (self.isolate.lock(), self.cells.install())
2304 }
2305
2306 /// Lift condemnation from an isolate whose heap has drained.
2307 ///
2308 /// `near_heap_limit` latches a flag that nothing used to clear, so a cell
2309 /// that reached its limit once stayed condemned until the process
2310 /// restarted. The flag is re-read here, between turns rather than inside
2311 /// one, because a handler must not see the isolate recover halfway
2312 /// through.
2313 ///
2314 /// A heap still over the line buys one `low_memory_notification` and a
2315 /// second reading. V8 stops collecting once it is past the limit, so a
2316 /// drained isolate holds the dead heap until something allocates again —
2317 /// without the forced collection the reading that decides recovery is a
2318 /// reading of garbage. `HEAP_GC_NUDGE_INTERVAL` bounds the cost.
2319 ///
2320 /// Removing the callback with the original limit puts back the limit
2321 /// `near_heap_limit` raised; re-adding it re-arms the guard.
2322 fn recover_heap(&self, locker: &mut v8::Locker<'_>) {
2323 let Some(state) = locker.get_slot::<Arc<HeapLimitState>>().cloned() else {
2324 return;
2325 };
2326 if !state.excessively_exceeded.load(Ordering::Relaxed) {
2327 return;
2328 }
2329 if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE {
2330 if !state.due_for_gc_nudge() {
2331 return;
2332 }
2333 locker.low_memory_notification();
2334 if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE {
2335 return;
2336 }
2337 }
2338 state.excessively_exceeded.store(false, Ordering::Relaxed);
2339 let data = Arc::as_ptr(&state) as *mut HeapLimitState as *mut std::ffi::c_void;
2340 locker.remove_near_heap_limit_callback(near_heap_limit, state.limit);
2341 locker.add_near_heap_limit_callback(near_heap_limit, data);
2342 tracing::info!(
2343 event = "isolate_heap_recovered",
2344 limit_bytes = state.limit,
2345 "isolate heap fell back under its limit, so it serves again"
2346 );
2347 }
2348
2349 /// Localise the realm for one turn.
2350 ///
2351 /// **Taking the scope is the point.** Reaching a realm means touching
2352 /// `Global` handles, which on a shared isolate is only legal while its
2353 /// `Locker` is held — and there is no scope to pass until the isolate is
2354 /// locked. So the requirement is structural rather than a comment asking
2355 /// callers to remember it. It was a comment, and the one call site that
2356 /// forgot cloned two `Global`s a line too early; the panic happened
2357 /// inside a spawned request task, where tokio swallowed it and it
2358 /// surfaced only as a poisoned mutex on every later request.
2359 fn realm<'s>(&self, hs: &mut v8::PinScope<'s, '_, ()>) -> Entered<'s> {
2360 Entered {
2361 context: v8::Local::new(hs, &self.realm.context),
2362 fetch: v8::Local::new(hs, &self.realm.fetch),
2363 }
2364 }
2365}
2366
2367/// One realm, entered. Valid only for the scope that produced it, which is
2368/// what ties it to the isolate being locked.
2369struct Entered<'s> {
2370 context: v8::Local<'s, v8::Context>,
2371 fetch: v8::Local<'s, v8::Function>,
2372}
2373
2374impl std::ops::Deref for Worker {
2375 type Target = WorkerIsolate;
2376
2377 fn deref(&self) -> &Self::Target {
2378 self.inner.as_ref().expect("Worker isolate unavailable")
2379 }
2380}
2381
2382impl std::ops::DerefMut for Worker {
2383 fn deref_mut(&mut self) -> &mut Self::Target {
2384 self.inner.as_mut().expect("Worker isolate unavailable")
2385 }
2386}
2387
2388const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024;
2389const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024;
2390
2391/// Share of the heap limit past which an isolate takes on no more retained
2392/// state. It sits below the near-limit callback on purpose: this refuses one
2393/// hibernatable socket while the isolate still works, where the callback
2394/// fires once it no longer does.
2395const HEAP_ADMISSION_SHARE: f64 = 0.9;
2396
2397/// Share of the heap limit under which a condemned isolate is condemned no
2398/// more. Under `HEAP_ADMISSION_SHARE` by enough that recovery does not
2399/// immediately re-admit into a heap that is about to fail again.
2400const HEAP_RECOVERY_SHARE: f64 = 0.75;
2401
2402/// The shortest gap between two collections forced by `recover_heap`. A full
2403/// collection of a 128 MB heap costs tens of milliseconds and a loaded cell
2404/// begins many turns each second, so an unbounded nudge would spend more of a
2405/// condemned isolate on collecting than on serving.
2406const HEAP_GC_NUDGE_INTERVAL: Duration = Duration::from_secs(1);
2407
2408struct HeapLimitState {
2409 excessively_exceeded: AtomicBool,
2410 /// The limit V8 gave this isolate, before any emergency extension.
2411 /// Recovery measures against this one because `near_heap_limit` raises
2412 /// the current one.
2413 limit: usize,
2414 last_gc_nudge: Mutex<Option<Instant>>,
2415 /// An explicit admission refusal cannot use the condemnation flag because
2416 /// recovery clears that flag at the next turn.
2417 #[cfg(celld_internal_tests)]
2418 forced_admission_refusal: AtomicBool,
2419}
2420
2421impl HeapLimitState {
2422 /// Whether a condemned isolate can pay for another forced collection.
2423 ///
2424 /// Rate-limited rather than once for each condemnation: the load can
2425 /// still be live at the first reading and gone by the second, so a
2426 /// one-shot nudge would leave the cell condemned exactly as before.
2427 fn due_for_gc_nudge(&self) -> bool {
2428 let Ok(mut last) = self.last_gc_nudge.lock() else {
2429 return false;
2430 };
2431 let now = Instant::now();
2432 if last.is_some_and(|at| now.duration_since(at) < HEAP_GC_NUDGE_INTERVAL) {
2433 return false;
2434 }
2435 *last = Some(now);
2436 true
2437 }
2438}
2439
2440#[cfg(celld_internal_tests)]
2441fn admission_refusal_forced(state: &HeapLimitState) -> bool {
2442 state.forced_admission_refusal.load(Ordering::Relaxed)
2443}
2444
2445#[cfg(not(celld_internal_tests))]
2446fn admission_refusal_forced(_state: &HeapLimitState) -> bool {
2447 false
2448}
2449
2450type SerializedPut = (String, Vec<u8>);
2451type PendingPuts = HashMap<String, Vec<SerializedPut>>;
2452
2453/// One Fetcher route transferred from a Worker Loader parent into its child.
2454/// The generation and the complete target travel together, so a loaded Worker
2455/// cannot accidentally resolve the route against a later deployment.
2456#[derive(Clone, Debug, PartialEq)]
2457struct OutboundBroker {
2458 generation: crate::generation::GenerationId,
2459 script: String,
2460 entrypoint: Option<crate::WorkerFetchEntrypoint>,
2461}
2462
2463/// Ambient outbound authority for an isolate. Normal workers keep `Allow`; a
2464/// Worker Loader can deny egress or route it through a transferred Fetcher.
2465#[derive(Clone, Default, PartialEq)]
2466enum EgressPolicy {
2467 #[default]
2468 Allow,
2469 Deny,
2470 Broker(OutboundBroker),
2471}
2472
2473#[derive(Default)]
2474struct ActorRuntimeState {
2475 promises: std::sync::Mutex<PromiseMap>,
2476 termination: std::sync::Mutex<Option<ExecutionTermination>>,
2477 pending_puts: std::sync::Mutex<PendingPuts>,
2478 io_contexts: std::sync::Mutex<HashMap<u64, Weak<IoContext>>>,
2479 /// WebSocket captures that received a frame in the current isolate turn.
2480 /// Weak references record every continuation context without extending
2481 /// an event's lifetime merely to flush its output.
2482 ws_capture_touched: Mutex<Vec<Weak<IoContext>>>,
2483 egress: EgressPolicy,
2484 resource_limits: Option<ResourceLimits>,
2485 tail_reporting: bool,
2486 script_name: String,
2487 event_hooks: OnceLock<EventHooks>,
2488 /// See [`internals`].
2489 internals: OnceLock<v8::Global<v8::Object>>,
2490 /// Set once a patch is installed, so an unpatched isolate pays one
2491 /// relaxed load per op and not a lock: the patch check runs on every op
2492 /// call of every test, and the lock cost 18% on an op-bound loop.
2493 #[cfg(celld_internal_tests)]
2494 op_patched: AtomicBool,
2495 #[cfg(celld_internal_tests)]
2496 op_patches: Mutex<HashMap<&'static str, v8::Global<v8::Function>>>,
2497 #[cfg(celld_internal_tests)]
2498 op_patches_active: Mutex<HashSet<&'static str>>,
2499}
2500
2501/// The harness functions the host calls on the boundary of every cell event.
2502///
2503/// `harness.js` installs `__beginEvent`, `__endEvent`, `__advanceIoTime`, and
2504/// `__abortIncomingRequest` on the internals object once per isolate and
2505/// never replaces them. Reading each one back by name per event costs a fresh
2506/// `v8::String` plus a lookup for a result that cannot change; holding the
2507/// functions removes the string and the lookup together.
2508///
2509/// The four are resolved together on purpose. A partial resolution would
2510/// leave one hook still reached by name, so `install_harness` builds all four
2511/// or the isolate fails to load, and no caller has to remember which of them
2512/// is cached.
2513///
2514/// A `v8::Global` is only valid in the isolate that created it, which is why
2515/// this hangs off `ActorRuntimeState` — an isolate slot — and not off a
2516/// process-wide `static`. `ModuleRegistry` documents the same constraint.
2517struct EventHooks {
2518 begin_event: v8::Global<v8::Function>,
2519 end_event: v8::Global<v8::Function>,
2520 advance_io_time: v8::Global<v8::Function>,
2521 abort_incoming_request: v8::Global<v8::Function>,
2522}
2523
2524/// One cached hook, opened into `scope`.
2525///
2526/// `pick` names the hook rather than a getter per hook, so the four call
2527/// sites stay one line each.
2528fn event_hook<'s>(
2529 scope: &mut v8::PinScope<'s, '_>,
2530 pick: fn(&EventHooks) -> &v8::Global<v8::Function>,
2531) -> Result<v8::Local<'s, v8::Function>> {
2532 let state = actor_runtime_state(scope);
2533 let hooks = state
2534 .event_hooks
2535 .get()
2536 .ok_or_else(|| anyhow!("event hooks are not installed"))?;
2537 Ok(v8::Local::new(scope, pick(hooks)))
2538}
2539
2540/// Advance the isolate clock at an I/O boundary before JavaScript resumes.
2541///
2542/// The cached hook is installed before user code loads, so a script cannot
2543/// replace the function that owns this invariant. Each caller is a complete
2544/// JavaScript turn caused by external input or by a completed native op.
2545/// The return value is the sample that an alarm turn must use for its due
2546/// comparison, so the host and JavaScript observe one event time.
2547fn advance_io_time(scope: &mut v8::PinScope) -> i64 {
2548 let timestamp_ms = unix_now_ms();
2549 let hook = event_hook(scope, |hooks| &hooks.advance_io_time)
2550 .expect("the isolate clock hook is installed");
2551 let timestamp = v8::Number::new(scope, timestamp_ms as f64);
2552 let recv = v8::undefined(scope).into();
2553 hook.call(scope, recv, &[timestamp.into()])
2554 .expect("the isolate clock hook cannot throw");
2555 timestamp_ms
2556}
2557
2558impl ActorRuntimeState {
2559 fn io_context(&self, id: u64) -> Option<Arc<IoContext>> {
2560 let mut contexts = self.io_contexts.lock().unwrap();
2561 let context = contexts.get(&id)?.upgrade();
2562 if context.is_none() {
2563 contexts.remove(&id);
2564 }
2565 context
2566 }
2567}
2568
2569struct ExecutionTermination {
2570 error: String,
2571 actor_scope: Option<String>,
2572 context_id: Option<u64>,
2573}
2574
2575#[cfg(all(test, celld_internal_tests))]
2576static CPU_FINISH_TERMINATION_FOR_TEST: Mutex<Option<(usize, usize)>> = Mutex::new(None);
2577
2578#[cfg(all(test, celld_internal_tests))]
2579fn terminate_on_cpu_finish_for_test(runtime_state: &Arc<ActorRuntimeState>, finish: usize) {
2580 let previous = CPU_FINISH_TERMINATION_FOR_TEST
2581 .lock()
2582 .unwrap()
2583 .replace((Arc::as_ptr(runtime_state) as usize, finish));
2584 assert!(
2585 previous.is_none(),
2586 "a CPU finish termination is already armed"
2587 );
2588}
2589
2590#[cfg(all(test, celld_internal_tests))]
2591fn inject_cpu_finish_termination_for_test(
2592 tc: &mut v8::PinScope,
2593 entry: &InFlight,
2594) -> Option<String> {
2595 let mut armed = CPU_FINISH_TERMINATION_FOR_TEST.lock().unwrap();
2596 let (runtime_state, remaining) = armed.as_mut()?;
2597 if *runtime_state != Arc::as_ptr(&entry.runtime_state) as usize {
2598 return None;
2599 }
2600 *remaining = remaining.saturating_sub(1);
2601 if *remaining != 0 {
2602 return None;
2603 }
2604 armed.take();
2605 let error = "Worker exceeded CPU limit of 10 ms".to_string();
2606 *entry
2607 .runtime_state
2608 .termination
2609 .lock()
2610 .expect("termination lock poisoned") = Some(ExecutionTermination {
2611 error: error.clone(),
2612 actor_scope: None,
2613 context_id: None,
2614 });
2615 tc.terminate_execution();
2616 Some(error)
2617}
2618
2619fn finish_cpu_turn(_tc: &mut v8::PinScope, entry: &InFlight) -> Result<(), String> {
2620 #[cfg(all(test, celld_internal_tests))]
2621 if let Some(error) = inject_cpu_finish_termination_for_test(_tc, entry) {
2622 return Err(error);
2623 }
2624 entry.context.finish_cpu_turn()
2625}
2626
2627/// A backstop for JavaScript that never returns to the host's exact CPU
2628/// sample. Exact accounting rejects finite turns in `finish_cpu_turn`; this
2629/// scheduler exists because an infinite loop has no later boundary at which
2630/// that sample can run. One process-wide thread watches all isolates. A thread
2631/// per turn consumed a PID under cgroup `pids.max` and paid an OS thread spawn
2632/// and join for every JavaScript continuation.
2633struct CpuWatchdog {
2634 id: u64,
2635}
2636
2637struct CpuWatch {
2638 limit: Duration,
2639 declared_ms: u32,
2640 target_clock: Option<TargetThreadCpuClock>,
2641 target_started: Option<u64>,
2642 next_check: Instant,
2643 isolate: v8::IsolateHandle,
2644 runtime_state: Arc<ActorRuntimeState>,
2645}
2646
2647#[derive(Default)]
2648struct CpuWatchdogState {
2649 next_id: u64,
2650 watches: HashMap<u64, CpuWatch>,
2651}
2652
2653struct CpuWatchdogService {
2654 shared: Arc<(Mutex<CpuWatchdogState>, std::sync::Condvar)>,
2655}
2656
2657static CPU_WATCHDOG_SERVICE: OnceLock<CpuWatchdogService> = OnceLock::new();
2658
2659fn cpu_watchdog_remaining(
2660 limit: Duration,
2661 started_nanos: Option<u64>,
2662 current_nanos: Option<u64>,
2663) -> Option<Duration> {
2664 let elapsed = started_nanos
2665 .zip(current_nanos)
2666 .map(|(started, current)| current.saturating_sub(started))?;
2667 let limit_nanos = u64::try_from(limit.as_nanos()).unwrap_or(u64::MAX);
2668 (elapsed < limit_nanos).then(|| Duration::from_nanos(limit_nanos - elapsed))
2669}
2670
2671impl CpuWatchdog {
2672 fn start(
2673 limit: Option<Duration>,
2674 declared_ms: Option<u32>,
2675 isolate: v8::IsolateHandle,
2676 runtime_state: Arc<ActorRuntimeState>,
2677 ) -> Option<Self> {
2678 let limit = limit?;
2679 let declared_ms = declared_ms?;
2680 let service = cpu_watchdog_service();
2681 let target_clock = TargetThreadCpuClock::current();
2682 let watch = CpuWatch {
2683 limit,
2684 declared_ms,
2685 target_clock,
2686 target_started: target_clock.and_then(TargetThreadCpuClock::nanos),
2687 next_check: Instant::now() + limit,
2688 isolate,
2689 runtime_state,
2690 };
2691 let (state, wake) = &*service.shared;
2692 let mut state = state.lock().unwrap();
2693 let id = state.next_id;
2694 state.next_id = state.next_id.wrapping_add(1);
2695 state.watches.insert(id, watch);
2696 drop(state);
2697 wake.notify_one();
2698 Some(Self { id })
2699 }
2700
2701 #[cfg(all(test, celld_internal_tests))]
2702 fn is_registered_for_test(&self) -> bool {
2703 cpu_watchdog_service()
2704 .shared
2705 .0
2706 .lock()
2707 .unwrap()
2708 .watches
2709 .contains_key(&self.id)
2710 }
2711}
2712
2713impl Drop for CpuWatchdog {
2714 fn drop(&mut self) {
2715 let (state, wake) = &*cpu_watchdog_service().shared;
2716 state.lock().unwrap().watches.remove(&self.id);
2717 wake.notify_one();
2718 }
2719}
2720
2721fn cpu_watchdog_service() -> &'static CpuWatchdogService {
2722 CPU_WATCHDOG_SERVICE.get_or_init(|| {
2723 let shared = Arc::new((
2724 Mutex::new(CpuWatchdogState::default()),
2725 std::sync::Condvar::new(),
2726 ));
2727 let scheduler = shared.clone();
2728 std::thread::Builder::new()
2729 .name("celld-cpu-watchdog".to_string())
2730 .spawn(move || run_cpu_watchdog_service(&scheduler))
2731 .expect("spawn the process CPU watchdog");
2732 CpuWatchdogService { shared }
2733 })
2734}
2735
2736fn run_cpu_watchdog_service(shared: &Arc<(Mutex<CpuWatchdogState>, std::sync::Condvar)>) -> ! {
2737 let (state, wake) = &**shared;
2738 let mut state = state.lock().unwrap();
2739 loop {
2740 let Some(next_check) = state.watches.values().map(|watch| watch.next_check).min() else {
2741 state = wake.wait(state).unwrap();
2742 continue;
2743 };
2744 let now = Instant::now();
2745 if now < next_check {
2746 let (next_state, _) = wake.wait_timeout(state, next_check - now).unwrap();
2747 state = next_state;
2748 continue;
2749 }
2750
2751 let due = state
2752 .watches
2753 .iter()
2754 .filter_map(|(id, watch)| (watch.next_check <= now).then_some(*id))
2755 .collect::<Vec<_>>();
2756 for id in due {
2757 let Some(watch) = state.watches.get_mut(&id) else {
2758 continue;
2759 };
2760 if let Some(remaining) = cpu_watchdog_remaining(
2761 watch.limit,
2762 watch.target_started,
2763 watch.target_clock.and_then(TargetThreadCpuClock::nanos),
2764 ) {
2765 watch.next_check = Instant::now() + remaining;
2766 continue;
2767 }
2768 let watch = state.watches.remove(&id).unwrap();
2769 let mut termination = watch
2770 .runtime_state
2771 .termination
2772 .lock()
2773 .expect("termination lock poisoned");
2774 if termination.is_none() {
2775 *termination = Some(ExecutionTermination {
2776 error: format!("Worker exceeded CPU limit of {} ms", watch.declared_ms),
2777 actor_scope: None,
2778 context_id: None,
2779 });
2780 drop(termination);
2781 watch.isolate.terminate_execution();
2782 }
2783 }
2784 }
2785}
2786
2787fn cpu_watchdog_for_context(scope: &mut v8::PinScope, context: &IoContext) -> Option<CpuWatchdog> {
2788 let runtime_state = actor_runtime_state(scope);
2789 let declared_ms = context
2790 .cpu_limit_nanos
2791 .and_then(|limit| u32::try_from(limit / 1_000_000).ok());
2792 CpuWatchdog::start(
2793 context.remaining_cpu_budget(),
2794 declared_ms,
2795 scope.thread_safe_handle(),
2796 runtime_state,
2797 )
2798}
2799
2800fn finish_terminated_actor_event(scope: &mut v8::PinScope, context: &IoContext) {
2801 finish_retired_input_gate_context(scope, context);
2802}
2803
2804fn finish_retired_input_gate_context(scope: &mut v8::PinScope, context: &IoContext) {
2805 context.force_retire_cross_entry_gates();
2806 let _ = abandon_context_input_gates(context);
2807 let context_id = context.continuation_id().unwrap_or_default();
2808 retire_input_gate_js_context(scope, context_id);
2809}
2810
2811fn retire_input_gate_js_context(scope: &mut v8::PinScope, context_id: u64) {
2812 let Ok(function) = internal_function(scope, "__retireInputGateContext") else {
2813 return;
2814 };
2815 let context_id = v8::String::new(scope, &context_id.to_string()).unwrap();
2816 let recv = v8::undefined(scope).into();
2817 let _ = function.call(scope, recv, &[context_id.into()]);
2818}
2819
2820/// The fetch handler of a loaded Worker that exports none: workerd's text,
2821/// thrown when a request reaches it, as on Cloudflare.
2822const NO_FETCH_HANDLER: &str =
2823 "() => { throw new Error('Handler does not export a fetch() function.'); }";
2824
2825/// Evaluate a host-written JS expression, with `__celld` bound, to a function.
2826fn compile_fn<'s>(
2827 scope: &mut v8::PinScope<'s, '_>,
2828 src: &str,
2829) -> Result<v8::Local<'s, v8::Function>> {
2830 let value = run_internal_snippet(scope, &format!("return {src};"))
2831 .ok_or_else(|| anyhow!("compile shim: {src}"))?;
2832 value
2833 .try_into()
2834 .map_err(|_| anyhow!("shim is not a function: {src}"))
2835}
2836
2837/// Whether `register_entrypoints` put `name` in the `__cell.<registry>`
2838/// object (e.g. `entrypoints`, `doExports`).
2839fn cell_registry_has(scope: &mut v8::PinScope, registry: &str, name: &str) -> Result<bool> {
2840 let cell = cell_state(scope)?;
2841 let registry_key = v8::String::new(scope, registry).unwrap();
2842 let registry_obj = cell
2843 .get(scope, registry_key.into())
2844 .and_then(|value| value.to_object(scope))
2845 .ok_or_else(|| anyhow!("missing __cell.{registry} registry"))?;
2846 let name_key = v8::String::new(scope, name).unwrap();
2847 Ok(registry_obj
2848 .has_own_property(scope, name_key.into())
2849 .unwrap_or(false))
2850}
2851
2852fn take_execution_termination_in_context(
2853 scope: &mut v8::PinScope,
2854 context: Option<&IoContext>,
2855) -> Option<anyhow::Error> {
2856 let state = scope.get_slot::<Arc<ActorRuntimeState>>().cloned();
2857 let termination = state
2858 .as_ref()
2859 .and_then(|state| state.termination.lock().ok()?.take());
2860 let is_terminating = scope.is_execution_terminating();
2861 if termination.is_some() || is_terminating {
2862 scope.cancel_terminate_execution();
2863 }
2864 if let Some(termination) = termination {
2865 if termination.actor_scope.is_some() {
2866 if let Some(context_id) = termination.context_id {
2867 if let Some(context) = state
2868 .as_ref()
2869 .and_then(|state| state.io_context(context_id))
2870 {
2871 finish_terminated_actor_event(scope, &context);
2872 }
2873 } else if let Some(context) = context {
2874 finish_terminated_actor_event(scope, context);
2875 } else {
2876 finish_terminated_actor_event(scope, &current_context());
2877 }
2878 }
2879 return Some(anyhow!(termination.error));
2880 }
2881 is_terminating.then(|| anyhow!("JavaScript execution was terminated"))
2882}
2883
2884fn take_execution_termination(scope: &mut v8::PinScope) -> Option<anyhow::Error> {
2885 take_execution_termination_in_context(scope, None)
2886}
2887
2888extern "C" fn near_heap_limit(
2889 data: *mut std::ffi::c_void,
2890 current_heap_limit: usize,
2891 _initial_heap_limit: usize,
2892) -> usize {
2893 // SAFETY: `data` points into the Arc stored in the isolate slot. Worker::drop
2894 // removes this callback before the isolate (and its slots) are destroyed.
2895 let state = unsafe { &*(data as *const HeapLimitState) };
2896 state.excessively_exceeded.store(true, Ordering::Relaxed);
2897 // V8 fatally aborts the process if a near-limit callback does not extend
2898 // the limit. This reserve lets JS observe condemnation and unwind.
2899 //
2900 // The extension must also cover one allocation as large as the limit
2901 // itself: flattening a 128 MiB cons string asks V8 for a single 128 MiB
2902 // block, and V8 re-invokes this callback across last-resort GC rounds
2903 // only unreliably (under parallel load it often stops after one round
2904 // and aborts the process). Doubling the original limit makes the first
2905 // invocation sufficient on its own; `recover_heap` and `Drop` still
2906 // restore the original limit, so nothing else changes.
2907 current_heap_limit
2908 .saturating_add(V8_HEAP_EMERGENCY_BYTES)
2909 .max(state.limit.saturating_mul(2))
2910}
2911
2912/// Live heap use, as a share of `limit`.
2913fn heap_share(isolate: &mut v8::Isolate, limit: usize) -> f64 {
2914 if limit == 0 {
2915 return 0.0;
2916 }
2917 isolate.get_heap_statistics().used_heap_size() as f64 / limit as f64
2918}
2919
2920fn v8_heap_limit_bytes() -> usize {
2921 crate::env_vars::positive::<usize>("CELLD_V8_HEAP_LIMIT_MB")
2922 .expect("validated CELLD_V8_HEAP_LIMIT_MB")
2923 .map(|megabytes| {
2924 megabytes
2925 .checked_mul(1024 * 1024)
2926 .expect("validated CELLD_V8_HEAP_LIMIT_MB range")
2927 })
2928 .unwrap_or(DEFAULT_V8_HEAP_LIMIT_BYTES)
2929}
2930
2931impl Drop for WorkerIsolate {
2932 fn drop(&mut self) {
2933 // Detach children while their IDs are still attributable to this
2934 // parent, but do not drop their V8 isolates while this one is entered.
2935 // In-flight child calls hold their own receiver clones and finish
2936 // normally; this removes only the registry's ownership reference.
2937 let loaded_children = take_loader_owner(&self.loader_owner);
2938 let limit = self.original_heap_limit;
2939 {
2940 let (mut locker, _cells) = self.lock();
2941 locker.remove_near_heap_limit_callback(near_heap_limit, limit);
2942 }
2943 drop(loaded_children);
2944 }
2945}
2946
2947/// One in-flight request inside a shared isolate.
2948///
2949/// Owned by the request's own tokio task, which is why every field is
2950/// `Send`: the task suspends between turns and can resume on any worker,
2951/// then re-enters the isolate it is affiliated with.
2952/// Where a finished handler's result goes, and in what shape.
2953///
2954/// A fetch answers an `HttpResponse` and an entrypoint RPC answers bytes.
2955/// Everything between — the turn loop, the op region, cancellation, the
2956/// budget — is identical, so the difference lives here rather than in two
2957/// copies of `drive`.
2958pub enum Answer {
2959 Fetch(tokio::sync::oneshot::Sender<Result<HttpResponse>>),
2960 Rpc(tokio::sync::oneshot::Sender<Result<Vec<u8>>>),
2961 Queue(tokio::sync::oneshot::Sender<Result<QueueDispatchResult>>),
2962 /// A DO method call, which answers a value rather than a response.
2963 CellRpc(tokio::sync::oneshot::Sender<Result<RpcOutcome>>),
2964 /// A `webSocketMessage`, which answers the frames the output gate held
2965 /// and the write they are gated on.
2966 WsMessage(tokio::sync::oneshot::Sender<Result<WsDispatch>>),
2967 /// An event whose result is that it finished: `webSocketOpen`,
2968 /// `webSocketClose`. It answers the position its writes reached, so the
2969 /// shell can open the barrier they need.
2970 Ack(tokio::sync::oneshot::Sender<Result<Option<u64>>>),
2971 /// An alarm, which answers whatever alarm the handler left armed.
2972 Alarm(tokio::sync::oneshot::Sender<Result<(celld_logic::wake::AlarmSnapshot, Option<u64>)>>),
2973}
2974
2975/// The invocation data that becomes one Tail Worker event after all referenced
2976/// work finishes. The response sender stays independent, so tail delivery
2977/// cannot delay or replace the Dynamic Worker response.
2978struct TailReportState {
2979 reply: tokio::sync::oneshot::Sender<String>,
2980 script_name: String,
2981 event_timestamp: i64,
2982 url: String,
2983 method: String,
2984 headers: serde_json::Map<String, serde_json::Value>,
2985 response_status: Option<u16>,
2986 failure: Option<TailException>,
2987}
2988
2989/// A failure and the instant it occurred. Tail delivery can wait for
2990/// `waitUntil` work, so sampling the clock when the report finishes would
2991/// move the exception forward by the duration of that work.
2992#[derive(serde::Serialize)]
2993struct TailException {
2994 timestamp: i64,
2995 name: &'static str,
2996 message: String,
2997}
2998
2999impl TailException {
3000 fn new(message: String) -> Self {
3001 Self {
3002 timestamp: crate::telemetry::now_unix_us() / 1_000,
3003 name: "Error",
3004 message,
3005 }
3006 }
3007}
3008
3009fn tail_request_headers(
3010 headers: &[(String, String)],
3011) -> serde_json::Map<String, serde_json::Value> {
3012 let mut normalized = serde_json::Map::new();
3013 for (name, value) in headers {
3014 match normalized.entry(name.to_ascii_lowercase()) {
3015 serde_json::map::Entry::Vacant(entry) => {
3016 entry.insert(serde_json::Value::String(value.clone()));
3017 }
3018 serde_json::map::Entry::Occupied(mut entry) => {
3019 let serde_json::Value::String(joined) = entry.get_mut() else {
3020 unreachable!("tail request headers contain only strings");
3021 };
3022 joined.push_str(", ");
3023 joined.push_str(value);
3024 }
3025 }
3026 }
3027 normalized
3028}
3029
3030impl TailReportState {
3031 fn record_failure(&mut self, message: String) {
3032 self.failure = Some(TailException::new(message));
3033 }
3034
3035 fn finish(self, context: &IoContext) {
3036 let outcome = if self.failure.is_some() {
3037 "exception"
3038 } else {
3039 "ok"
3040 };
3041 let exceptions: Vec<_> = self.failure.into_iter().collect();
3042 let event = serde_json::json!([{
3043 "scriptName": self.script_name,
3044 "event": {
3045 "request": {
3046 "cf": {},
3047 "headers": self.headers,
3048 "method": self.method,
3049 "url": self.url,
3050 },
3051 "response": self.response_status.map(|status| serde_json::json!({
3052 "status": status,
3053 })),
3054 },
3055 "eventTimestamp": self.event_timestamp,
3056 "logs": context.take_tail_logs(),
3057 "exceptions": exceptions,
3058 "outcome": outcome,
3059 }]);
3060 let _ = self.reply.send(event.to_string());
3061 }
3062}
3063
3064impl Answer {
3065 /// Send an error, whichever shape the caller is waiting for.
3066 fn fail(self, error: anyhow::Error) {
3067 let _ = self.fail_with_arm_gates(error, Vec::new());
3068 }
3069
3070 fn fail_with_arm_gates(
3071 self,
3072 error: anyhow::Error,
3073 gates: Vec<ArmGateRx>,
3074 ) -> Option<GatedReplyRx> {
3075 match self {
3076 Answer::Fetch(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3077 Answer::Rpc(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3078 Answer::Queue(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3079 Answer::CellRpc(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3080 Answer::WsMessage(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3081 Answer::Ack(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3082 Answer::Alarm(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3083 }
3084 }
3085}
3086
3087async fn await_arm_gates(gates: Vec<ArmGateRx>) -> Result<(), String> {
3088 let mut first_failure = None;
3089 for gate in gates {
3090 let failure = match gate.await {
3091 Ok(Ok(())) => None,
3092 Ok(Err(error)) => Some(error),
3093 Err(_) => Some("wake-entry gate task dropped".into()),
3094 };
3095 if first_failure.is_none() {
3096 first_failure = failure;
3097 }
3098 }
3099 match first_failure {
3100 Some(failure) => Err(failure),
3101 None => Ok(()),
3102 }
3103}
3104
3105fn send_answer_after_arm_gates<T: Send + 'static>(
3106 mut reply: tokio::sync::oneshot::Sender<Result<T>>,
3107 value: Result<T>,
3108 gates: Vec<ArmGateRx>,
3109) -> Option<GatedReplyRx> {
3110 if gates.is_empty() {
3111 drop(reply.send(value));
3112 return None;
3113 }
3114 let (completed, completion) = tokio::sync::oneshot::channel();
3115 let (cancel, mut cancelled) = tokio::sync::oneshot::channel();
3116 #[cfg(celld_internal_tests)]
3117 let drop_task = asyncrt::services()
3118 .wake_entry()
3119 .drop_next_gated_reply_task
3120 .swap(false, Ordering::AcqRel);
3121 asyncrt::spawn(async move {
3122 #[cfg(celld_internal_tests)]
3123 if drop_task {
3124 return;
3125 }
3126 enum GateWait {
3127 Completed(Result<(), String>),
3128 CallerClosed,
3129 Cancelled,
3130 DriverDropped,
3131 }
3132 let gate_wait = {
3133 let mut waiting = Box::pin(await_arm_gates(gates));
3134 let result = asyncrt::select_biased! {
3135 "a completed gate aggregate wins a tie with caller cancellation";
3136 result = &mut waiting => GateWait::Completed(result),
3137 cancellation = async {
3138 asyncrt::select_biased! {
3139 "a closed caller wins a tie with an explicit cancellation signal";
3140 _ = reply.closed() => GateWait::CallerClosed,
3141 cancelled = &mut cancelled => match cancelled {
3142 Ok(()) => GateWait::Cancelled,
3143 Err(_) => GateWait::DriverDropped,
3144 },
3145 }
3146 } => cancellation,
3147 };
3148 // On either cancellation path this drops every unobserved gate
3149 // receiver before the completion becomes visible to the driver.
3150 drop(waiting);
3151 result
3152 };
3153 let value = match gate_wait {
3154 GateWait::Completed(gate_result) => match (value, gate_result) {
3155 (value, Ok(())) => value,
3156 (Ok(_), Err(error)) => Err(anyhow!("wake-entry gate: {error}")),
3157 (Err(primary), Err(error)) => {
3158 tracing::error!(
3159 event = "wake_entry_gate_failed_after_handler_error",
3160 handler_error = %primary,
3161 gate_error = %error,
3162 );
3163 Err(primary.context(format!("wake-entry gate also failed: {error}")))
3164 }
3165 },
3166 GateWait::CallerClosed => {
3167 let failure = value
3168 .as_ref()
3169 .err()
3170 .map(|error| crate::telemetry::cap_error(format!("{error:#}")));
3171 drop(value);
3172 let _ = completed.send(GatedReplyCompletion::CallerClosed { failure });
3173 return;
3174 }
3175 // The driver observed a request cancellation after the handler
3176 // fixed its reply. Do not enter JavaScript again: the handler is
3177 // already over. A successful answer becomes a disconnect error,
3178 // while an existing handler error remains the primary failure.
3179 GateWait::Cancelled => match value {
3180 Ok(_) => Err(anyhow!("The client has disconnected")),
3181 Err(primary) => Err(primary),
3182 },
3183 // Dropping the driver drops both halves of its completion handle.
3184 // Release every detached resource, but do not let an abandoned
3185 // driver manufacture a reply that nothing owns any longer.
3186 GateWait::DriverDropped => {
3187 drop(value);
3188 return;
3189 }
3190 };
3191 let failure = value
3192 .as_ref()
3193 .err()
3194 .map(|error| crate::telemetry::cap_error(format!("{error:#}")));
3195 let completion = match reply.send(value) {
3196 Ok(()) => GatedReplyCompletion::Sent { failure },
3197 Err(value) => {
3198 drop(value);
3199 GatedReplyCompletion::CallerClosed { failure }
3200 }
3201 };
3202 let _ = completed.send(completion);
3203 })
3204 .detach();
3205 Some(GatedReplyRx {
3206 completion,
3207 cancel: Some(cancel),
3208 })
3209}
3210
3211pub(crate) enum GatedReplyCompletion {
3212 /// The final reply value is now visible to the receiver.
3213 Sent { failure: Option<String> },
3214 /// The receiver disappeared, so no reply remains to deliver.
3215 CallerClosed { failure: Option<String> },
3216}
3217
3218pub(crate) struct GatedReplyRx {
3219 completion: tokio::sync::oneshot::Receiver<GatedReplyCompletion>,
3220 cancel: Option<tokio::sync::oneshot::Sender<()>>,
3221}
3222
3223impl GatedReplyRx {
3224 /// Stop waiting on event gates after a request cancellation. The detached
3225 /// task owns the reply value and gate receivers, so it performs their
3226 /// ordered cleanup and reports completion back to the driver.
3227 pub(crate) fn cancel(&mut self) {
3228 if let Some(cancel) = self.cancel.take() {
3229 let _ = cancel.send(());
3230 }
3231 }
3232}
3233
3234impl std::future::Future for GatedReplyRx {
3235 type Output = Result<GatedReplyCompletion, tokio::sync::oneshot::error::RecvError>;
3236
3237 fn poll(
3238 self: Pin<&mut Self>,
3239 context: &mut std::task::Context<'_>,
3240 ) -> std::task::Poll<Self::Output> {
3241 Pin::new(&mut self.get_mut().completion).poll(context)
3242 }
3243}
3244
3245#[cfg(celld_internal_tests)]
3246#[doc(hidden)]
3247pub async fn await_arm_gates_for_test(
3248 gates: Vec<tokio::sync::oneshot::Receiver<Result<(), String>>>,
3249) -> Result<(), String> {
3250 await_arm_gates(gates).await
3251}
3252
3253#[cfg(celld_internal_tests)]
3254#[doc(hidden)]
3255pub enum GatedReplyCompletionForTest {
3256 Sent { failure: Option<String> },
3257 CallerClosed { failure: Option<String> },
3258}
3259
3260#[cfg(celld_internal_tests)]
3261#[doc(hidden)]
3262pub struct GatedReplyForTest(GatedReplyRx);
3263
3264#[cfg(celld_internal_tests)]
3265impl std::future::Future for GatedReplyForTest {
3266 type Output = Result<GatedReplyCompletionForTest, tokio::sync::oneshot::error::RecvError>;
3267
3268 fn poll(
3269 self: Pin<&mut Self>,
3270 context: &mut std::task::Context<'_>,
3271 ) -> std::task::Poll<Self::Output> {
3272 Pin::new(&mut self.get_mut().0).poll(context).map(|result| {
3273 result.map(|completion| match completion {
3274 GatedReplyCompletion::Sent { failure } => {
3275 GatedReplyCompletionForTest::Sent { failure }
3276 }
3277 GatedReplyCompletion::CallerClosed { failure } => {
3278 GatedReplyCompletionForTest::CallerClosed { failure }
3279 }
3280 })
3281 })
3282 }
3283}
3284
3285#[cfg(celld_internal_tests)]
3286#[doc(hidden)]
3287pub fn send_answer_after_arm_gates_for_test<T: Send + 'static>(
3288 reply: tokio::sync::oneshot::Sender<Result<T>>,
3289 value: Result<T>,
3290 gates: Vec<tokio::sync::oneshot::Receiver<Result<(), String>>>,
3291) -> Option<GatedReplyForTest> {
3292 send_answer_after_arm_gates(reply, value, gates).map(GatedReplyForTest)
3293}
3294
3295#[cfg(celld_internal_tests)]
3296#[doc(hidden)]
3297pub fn drop_next_gated_reply_task_for_test() {
3298 asyncrt::services()
3299 .wake_entry()
3300 .drop_next_gated_reply_task
3301 .store(true, Ordering::Release);
3302}
3303
3304pub struct InFlight {
3305 /// The handler's promise. A `Global` because it outlives the turn that
3306 /// created it: Locals never cross a turn, exactly as workerd's
3307 /// `Worker::Lock` never does.
3308 promise: v8::Global<v8::Promise>,
3309 context: Arc<IoContext>,
3310 /// The cell this event belongs to, and `None` for stateless work.
3311 ///
3312 /// It is what the storage-shaped parts of settling — the durability
3313 /// position, a fatal SQL error — are read against.
3314 scope: Option<String>,
3315 /// The cell's committed-write position before the handler ran.
3316 ///
3317 /// The answer carries a write position only if the handler advanced it,
3318 /// so the output gate sees a write this event made and ignores celld's
3319 /// own activation writes (the actor name, alarm bookkeeping).
3320 writes_before: Option<u64>,
3321 request_id: Option<RequestId>,
3322 active_request_id: Option<RequestId>,
3323 reply: Option<Answer>,
3324 gated_reply: Option<GatedReplyRx>,
3325 /// `waitUntil` work still running after the response was sent. The
3326 /// request stays in flight until it settles, as the single-request loop
3327 /// keeps driving it.
3328 background: Option<v8::Global<v8::Promise>>,
3329 /// A successfully completed Durable Object event keeps every referenced
3330 /// native operation alive. Workerd does not require `waitUntil` for this
3331 /// I/O, so dropping these operations loses detached timers and subrequests.
3332 completed_cell_event: bool,
3333 /// Ops this request is waiting on, so a completion can be attributed to
3334 /// the request whose context must be current while its continuation runs.
3335 ops: std::collections::HashSet<u64>,
3336 /// The subset of `ops` whose resource owns this event's `IoContext`.
3337 /// These operations continue after the handler and `waitUntil` settle.
3338 io_context_ops: std::collections::HashSet<u64>,
3339 /// The subset of `ops` that can run while referenced work is live but
3340 /// cannot keep this event alive by themselves.
3341 unrefed_ops: std::collections::HashSet<u64>,
3342 /// The alarm bookkeeping this entry still owes, if it is one.
3343 alarm: Option<AlarmClaim>,
3344 started: Instant,
3345 /// The propagation context for this entry. A rejected foreign context
3346 /// stays here with `sampled` clear, so continuations can forward it
3347 /// without treating it as permission to record spans or logs.
3348 trace: Option<crate::telemetry::TraceContext>,
3349 /// Why the event failed, captured for the span's `error` so a query sees
3350 /// the reason, not only that it failed. This also records an output-gate
3351 /// failure after a successful handler.
3352 failure: Option<String>,
3353 /// The report owed to the loader isolate after this invocation retires.
3354 tail_report: Option<TailReportState>,
3355 /// The isolate this entry's ops belong to, so `abandon` can drop their
3356 /// resolvers without a scope to reach the isolate through.
3357 runtime_state: Arc<ActorRuntimeState>,
3358}
3359
3360impl InFlight {
3361 /// Read the handler's settled value in the shape this entry answers, end
3362 /// the event, and reply.
3363 ///
3364 /// Every shape ends the event exactly once, whether it produced a value
3365 /// or an error — ending it is what yields the `waitUntil` work the entry
3366 /// keeps driving afterwards, and a shape that skipped it on the error
3367 /// path would leave the context open.
3368 fn answer_settled<'s>(
3369 &mut self,
3370 tc: &mut v8::PinScope<'s, '_>,
3371 value: v8::Local<'s, v8::Value>,
3372 ) {
3373 let Some(reply) = self.reply.take() else {
3374 return;
3375 };
3376 // A cell whose SQL failed fatally cannot answer whatever the handler
3377 // returned: the storage the handler read may not be what the cell
3378 // has.
3379 if let Some(error) = self.scope.as_deref().and_then(storage::sql_critical_error) {
3380 let _ = end_event_context(tc);
3381 self.context.seal_wait_until();
3382 if self.trace.is_some_and(|trace| trace.sampled) {
3383 self.failure = Some(crate::telemetry::cap_error(error.to_string()));
3384 }
3385 self.gated_reply =
3386 reply.fail_with_arm_gates(anyhow!(error), self.context.take_arm_gates());
3387 return;
3388 }
3389 self.completed_cell_event = self.scope.is_some();
3390 let (background, gated_reply) = match reply {
3391 Answer::Fetch(reply) => {
3392 // A value the decoder refuses is a failure in the turn like a
3393 // throw is, so it carries the same positions.
3394 let read = self.gate_positions().and_then(|positions| {
3395 let (write_position, observed_position) = positions;
3396 read_response(tc, value)
3397 .map(|mut response| {
3398 response.write_position = write_position;
3399 response.observed_position = observed_position;
3400 response
3401 })
3402 .map_err(|error| fail_in_turn_error(error, positions))
3403 });
3404 if let Some(report) = &mut self.tail_report {
3405 match &read {
3406 Ok(response) => report.response_status = Some(response.status),
3407 Err(error) => report.record_failure(format!("{error:#}")),
3408 }
3409 }
3410 send_and_end(tc, &self.context, reply, read)
3411 }
3412 Answer::Rpc(reply) => {
3413 let read =
3414 view_bytes(value).ok_or_else(|| anyhow!("entrypoint RPC answered non-bytes"));
3415 send_and_end(tc, &self.context, reply, read)
3416 }
3417 Answer::Queue(reply) => {
3418 let read = read_queue_result(tc, value);
3419 if let Ok(result) = &read {
3420 if result.outcome == QueueOutcome::Exception
3421 && self.trace.is_some_and(|trace| trace.sampled)
3422 {
3423 self.failure = Some(crate::telemetry::cap_error(
3424 result
3425 .error
3426 .clone()
3427 .unwrap_or_else(|| "queue handler rejected".to_string()),
3428 ));
3429 }
3430 }
3431 send_and_end(tc, &self.context, reply, read)
3432 }
3433 Answer::CellRpc(reply) => {
3434 let outcome = self
3435 .gate_positions()
3436 .map(|(write_position, observed_position)| {
3437 #[cfg(celld_internal_tests)]
3438 if self.scope.as_deref().is_some_and(|scope| {
3439 scope
3440 .split_once(':')
3441 .is_some_and(|(class, _)| class == crate::deploy::QUEUE_CLASS)
3442 }) {
3443 QUEUE_PRODUCER_WRITE_POSITIONS
3444 .with(|positions| positions.borrow_mut().push(write_position));
3445 }
3446 RpcOutcome {
3447 data: rpc_data_ret(tc, value),
3448 write_position,
3449 observed_position,
3450 }
3451 });
3452 send_and_end(tc, &self.context, reply, outcome)
3453 }
3454 Answer::WsMessage(reply) => {
3455 let dispatch = self
3456 .gate_positions()
3457 .map(|(write_position, observed_position)| WsDispatch {
3458 frames: ws_capture_take(),
3459 write_position,
3460 observed_position,
3461 });
3462 send_and_end(tc, &self.context, reply, dispatch)
3463 }
3464 Answer::Ack(reply) => send_and_end(tc, &self.context, reply, self.write_delta()),
3465 Answer::Alarm(reply) => {
3466 // The handler ran and returned, so close the claim as a
3467 // success. This is the only path that does: every other
3468 // `settle_alarm` call site records a failure, and without
3469 // this one a *successful* alarm was recorded as one to
3470 // retry — which re-armed it forever, kept the cell busy,
3471 // and meant an eviction waiting for the cell to go quiet
3472 // never got its turn.
3473 self.settle_alarm(true, false);
3474 // Read what stands *after* that cleanup, and take the delta
3475 // last so it covers the cleanup's own commit — which is the
3476 // write the core must prove durable before it settles the
3477 // alarm.
3478 let alarm = self
3479 .scope
3480 .as_deref()
3481 .map(|cell| observe_alarm(cell, storage::get_alarm(cell)))
3482 .unwrap_or_else(|| celld_logic::wake::AlarmSnapshot::without_wake(None));
3483 send_and_end(
3484 tc,
3485 &self.context,
3486 reply,
3487 self.write_delta().map(|write| (alarm, write)),
3488 )
3489 }
3490 };
3491 self.background = background;
3492 self.gated_reply = gated_reply;
3493 }
3494
3495 /// The write position to gate this answer on: `None` unless the handler
3496 /// advanced the cell's committed writes past where they were.
3497 fn write_delta(&self) -> Result<Option<u64>> {
3498 self.gate_positions().map(|(write, _)| write)
3499 }
3500
3501 /// The positions this answer's ticket carries: the write position when
3502 /// the handler advanced the cell's committed writes past where they were,
3503 /// and the position the answer observed above the cell's published
3504 /// baseline. One sample serves both, so they cannot disagree about what
3505 /// the cell holds.
3506 fn gate_positions(&self) -> Result<(Option<u64>, Option<u64>)> {
3507 match self.scope.as_deref() {
3508 Some(scope) => gate_positions(scope, self.writes_before),
3509 None => Ok((None, None)),
3510 }
3511 }
3512
3513 /// Fail whichever shape is waiting, without knowing which.
3514 ///
3515 /// This must not touch cell storage: a budget overrun and a stuck
3516 /// handler are found on the driving task, between turns, where the
3517 /// storage thread-local is null — settling the alarm claim here
3518 /// panicked the node (denoland/celld#170). The claim stays put, and
3519 /// the drive loop's `owes_alarm` turn records it as not counting
3520 /// against the retry limit, because a failure here is not the
3521 /// handler's. A handler that threw is recorded by `settle`, which
3522 /// knows that it did, before it reaches this.
3523 ///
3524 /// For the same reason the error leaves here without the position the
3525 /// handler's commits reached: `fail_in_turn` is the half that can sample
3526 /// it. A write a handler made before it ran out of budget is therefore
3527 /// still an unproven commit with no barrier of its own.
3528 fn fail(&mut self, error: anyhow::Error) {
3529 if let Some(report) = &mut self.tail_report {
3530 report.record_failure(format!("{error:#}"));
3531 }
3532 if let Some(reply) = self.reply.take() {
3533 if matches!(&reply, Answer::WsMessage(_)) {
3534 // A failed message has no successful dispatch whose barrier
3535 // can authorize its output. Discard the still-active capture
3536 // here so rejection, cancellation, and turn failures cannot
3537 // leave frames for the turn-end flush to publish.
3538 ws_capture_discard(&self.context);
3539 }
3540 if self.trace.is_some_and(|trace| trace.sampled) {
3541 self.failure = Some(crate::telemetry::cap_error(error.to_string()));
3542 }
3543 self.gated_reply = reply.fail_with_arm_gates(error, self.context.take_arm_gates());
3544 }
3545 }
3546
3547 /// Fail the event from inside its isolate turn, where the cell's storage
3548 /// is at hand. The error carries the positions the turn sampled, so the
3549 /// shell gates it as it gates a success. A commit a handler made before it
3550 /// threw is as unproven as one it answered with, and without a ticket it
3551 /// opened no barrier, so a read-only request that followed revealed it
3552 /// while a crash could still lose it. A handler that only read carries the
3553 /// observed position for the same reason: the message it throws with can
3554 /// quote what it read, and the error answer reveals that state as a
3555 /// response body does. An alarm that rejected settled its claim before
3556 /// this, so the delta covers its retry record too; one that failed any
3557 /// other way still owes that record, and `turn_finish_alarm` samples again
3558 /// after writing it.
3559 fn fail_in_turn(&mut self, error: anyhow::Error) {
3560 let error = match self.gate_positions() {
3561 Ok(positions) => fail_in_turn_error(error, positions),
3562 Err(sample) => sample,
3563 };
3564 self.fail(error);
3565 }
3566
3567 /// Fail the event of a client that has hung up. The write half of
3568 /// `fail_in_turn` applies — a commit the handler made still needs its
3569 /// barrier — but the read-only half does not: there is no client left to
3570 /// tell, so no message carries what the handler read, and a read-only
3571 /// ticket would only hold the request's pin, and a shutdown, for a
3572 /// durability round trip that proves nothing.
3573 fn fail_cancelled(&mut self, error: anyhow::Error) {
3574 let error = match self.write_delta() {
3575 Ok(write_position) => fail_in_turn_error(error, (write_position, None)),
3576 Err(sample) => sample,
3577 };
3578 self.fail(error);
3579 }
3580
3581 /// Record how a claimed alarm ended. Runs once; later calls do nothing.
3582 fn settle_alarm(&mut self, ok: bool, counts_against_limit: bool) {
3583 let (Some(scope), Some(claim)) = (self.scope.as_deref(), self.alarm.take()) else {
3584 return;
3585 };
3586 if ok {
3587 storage::finish_alarm_handler(scope, true, claim.now_ms);
3588 } else {
3589 storage::finish_alarm_handler_with_retry_policy(
3590 scope,
3591 false,
3592 claim.now_ms,
3593 counts_against_limit,
3594 );
3595 }
3596 }
3597
3598 /// Whether a claimed alarm's outcome is still unrecorded. True only
3599 /// where the event ended without ever entering the isolate again.
3600 pub fn owes_alarm(&self) -> bool {
3601 self.alarm.is_some()
3602 }
3603
3604 /// Done when the response is sent and no referenced work remains.
3605 pub fn finished(&self) -> bool {
3606 self.retired() && !self.has_refed_ops()
3607 }
3608
3609 /// Whether an operation can keep this event alive.
3610 pub(crate) fn has_refed_ops(&self) -> bool {
3611 self.ops != self.unrefed_ops
3612 }
3613
3614 /// Borrow the reply gate and operation mailbox together. The wake loop
3615 /// must listen to both while the detached gate owns the response, and a
3616 /// split borrow avoids cloning the context on every operation pass.
3617 pub(crate) fn gated_reply_and_io_context(
3618 &mut self,
3619 ) -> (Option<&mut GatedReplyRx>, &Arc<IoContext>) {
3620 (self.gated_reply.as_mut(), &self.context)
3621 }
3622
3623 #[cfg(celld_internal_tests)]
3624 #[doc(hidden)]
3625 pub fn has_gated_reply_for_test(&self) -> bool {
3626 self.gated_reply.is_some()
3627 }
3628
3629 #[cfg(celld_internal_tests)]
3630 #[doc(hidden)]
3631 pub async fn finish_gated_reply_for_test(&mut self) -> bool {
3632 let Some(gated_reply) = self.gated_reply.as_mut() else {
3633 return false;
3634 };
3635 let completion = gated_reply.await;
3636 self.finish_gated_reply(completion);
3637 true
3638 }
3639
3640 /// Ask the detached gate owner to release every event gate and finish the
3641 /// reply edge. The driver waits for its completion before it retires the
3642 /// event, so response resources cannot outlive that cleanup.
3643 pub(crate) fn cancel_gated_reply(&mut self) {
3644 if let Some(gated_reply) = &mut self.gated_reply {
3645 gated_reply.cancel();
3646 }
3647 }
3648
3649 /// Retire a gate waiter after it sent the reply or observed caller-close.
3650 ///
3651 /// This method also closes request sockets when the completion makes the
3652 /// entry retire. `finish_turn` cannot do that earlier because the reply
3653 /// value can still own response resources while the gate is pending.
3654 pub(crate) fn finish_gated_reply(
3655 &mut self,
3656 completion: Result<GatedReplyCompletion, tokio::sync::oneshot::error::RecvError>,
3657 ) {
3658 self.gated_reply = None;
3659 if self.trace.is_some_and(|trace| trace.sampled) {
3660 match completion {
3661 Ok(GatedReplyCompletion::Sent {
3662 failure: Some(failure),
3663 })
3664 | Ok(GatedReplyCompletion::CallerClosed {
3665 failure: Some(failure),
3666 }) => self.failure = Some(failure),
3667 Ok(GatedReplyCompletion::Sent { failure: None }) => {}
3668 Ok(GatedReplyCompletion::CallerClosed { failure: None }) => {
3669 if self.failure.is_none() {
3670 self.failure = Some("The client has disconnected".to_string());
3671 }
3672 }
3673 Err(_) => {
3674 if self.failure.is_none() {
3675 self.failure = Some("wake-entry reply gate task dropped".to_string());
3676 }
3677 }
3678 }
3679 }
3680 if self.retired() {
3681 self.context.close_sockets();
3682 }
3683 }
3684
3685 /// The request has answered and its `waitUntil` work has settled.
3686 ///
3687 /// An isolate-polled WebSocket can still own an op after this point, and
3688 /// that op must not defer retirement. Retiring closes the sockets the
3689 /// request opened, and the pump of an outbound socket ends only with a
3690 /// close, so a retirement that waited for the pump waited for itself and
3691 /// the request never left the drive loop. The op keeps the entry's ops
3692 /// alive instead, through `keeps_native_ops`, which is what a socket the
3693 /// response took over needs: that socket left the request's set at the
3694 /// handoff, so retiring does not close it, and its pump runs until the
3695 /// client closes it.
3696 fn retired(&self) -> bool {
3697 self.reply.is_none()
3698 && self.gated_reply.is_none()
3699 && self.background.is_none()
3700 // A block that holds the gate is still this event's work:
3701 // retiring would close the sockets its callback may still read.
3702 && !self.holds_gate()
3703 // A reaction from this event can run its block during another
3704 // event's turn. Retain this event until that block releases its
3705 // claim, or retirement closes resources the callback still uses.
3706 && self.context.retire_without_cross_entry_gate()
3707 }
3708
3709 /// Why the event failed, when a sampled trace captured it.
3710 pub fn failure(&self) -> Option<&str> {
3711 self.failure.as_deref()
3712 }
3713
3714 pub(crate) fn finish_tail_report(&mut self) {
3715 if let Some(report) = self.tail_report.take() {
3716 report.finish(&self.context);
3717 }
3718 }
3719
3720 /// How long this handler may still run, or `None` once it has answered.
3721 ///
3722 /// The budget bounds the *response*, not the request: `waitUntil` work
3723 /// continues after the client has been served and is not charged for the
3724 /// time the handler already spent.
3725 pub fn remaining(&self, budget: Duration) -> Option<Duration> {
3726 self.reply
3727 .is_some()
3728 .then(|| budget.saturating_sub(self.started.elapsed()))
3729 }
3730
3731 /// Give up on a handler that will not settle.
3732 pub fn time_out(&mut self, budget: Duration) {
3733 self.fail(anyhow!("handler exceeded {}s budget", budget.as_secs()));
3734 }
3735
3736 /// Nothing this request awaits can move it, so it will never settle on
3737 /// its own. Reachable when a handler awaits a promise only some *other*
3738 /// request could resolve — which the pump concealed, because it settled
3739 /// every entry on every turn whoever the turn belonged to.
3740 pub fn stuck(&mut self) {
3741 self.fail(anyhow!("handler is waiting on nothing"));
3742 self.background = None;
3743 self.context.seal_wait_until();
3744 }
3745
3746 /// Whether a nested `WorkerEntrypoint` call is still pending. When no
3747 /// native operation can resume JavaScript, the call itself must reject;
3748 /// failing the enclosing event would prevent its caller from catching the
3749 /// Workerd cancellation.
3750 pub(crate) fn has_pending_events(&self) -> bool {
3751 self.context.has_pending_events()
3752 }
3753
3754 /// Has the client been answered? `waitUntil` work can still be running.
3755 pub fn answered(&self) -> bool {
3756 self.reply.is_none() && self.gated_reply.is_none()
3757 }
3758
3759 /// Whether a native operation can still resume JavaScript for this event.
3760 ///
3761 /// A detached reply gate is host work. It cannot keep handler operations
3762 /// alive after the handler ends. A successfully completed Durable Object
3763 /// event keeps its pending I/O without `waitUntil`, as Workerd does. An
3764 /// operation that owns the event's `IoContext` and a block that holds or
3765 /// is queued to take a cell's input gate can also continue. The block
3766 /// belongs to the object, not to the client: it runs to completion as
3767 /// workerd's critical section does, and its `finally` opens the gate.
3768 /// Dropping its ops with the reply dropped the timer or subrequest it
3769 /// awaited, and the gate stayed shut for every later event (#733).
3770 pub(crate) fn keeps_native_ops(&self) -> bool {
3771 self.reply.is_some()
3772 || self.completed_cell_event
3773 || !self.io_context_ops.is_empty()
3774 || self.keeps_native_ops_after_disconnect()
3775 }
3776
3777 /// Whether work that survives a normal client disconnect still needs
3778 /// this event's native operations.
3779 ///
3780 /// An origin claim covers operations started before a cross-entry block.
3781 /// Its callback can already hold their promises even though another
3782 /// event owns the block's turn and therefore owns the gate engagement.
3783 fn keeps_native_ops_after_disconnect(&self) -> bool {
3784 self.background.is_some()
3785 || self.engages_gate()
3786 || self.context.has_cross_entry_gate_claim()
3787 }
3788
3789 /// Complete the resource-retirement edge that a claim release woke.
3790 pub(crate) fn finish_cross_entry_gates(&self) {
3791 if self.retired() {
3792 self.context.close_sockets();
3793 }
3794 }
3795
3796 /// Whether this event holds a cell's input gate now, or is queued to
3797 /// take one.
3798 fn engages_gate(&self) -> bool {
3799 gate_engagement(self.scope.as_deref(), &self.context) != GateEngagement::None
3800 }
3801
3802 /// Whether this event holds a cell's input gate now. A queued block has
3803 /// not started, so only a held one keeps the event's sockets: a stale
3804 /// queue count from a future that was never adopted must not keep the
3805 /// event from retiring.
3806 fn holds_gate(&self) -> bool {
3807 gate_engagement(self.scope.as_deref(), &self.context) == GateEngagement::Holds
3808 }
3809
3810 /// Whether a client can still disconnect from this request. A request
3811 /// with no id is internal and has no client to hang up.
3812 pub fn cancellable(&self) -> bool {
3813 self.reply.is_some() && self.request_id.is_some()
3814 }
3815
3816 pub fn request_id(&self) -> Option<RequestId> {
3817 self.request_id
3818 }
3819
3820 /// The request is over and its remaining ops are being dropped. Purge
3821 /// their resolvers.
3822 ///
3823 /// An op that never completes would otherwise leave its
3824 /// `Global<PromiseResolver>` in the isolate's map for as long as the
3825 /// isolate lives. A request that drives itself has to purge them on its
3826 /// own way out.
3827 pub fn abandon(&mut self) {
3828 self.context.seal_wait_until();
3829 self.io_context_ops.clear();
3830 self.unrefed_ops.clear();
3831 // An op a foreign turn handed this event after its driver's last pass
3832 // never reached `ops`, so the drain below cannot reach its resolver.
3833 // Closing the mailbox both yields those ops and refuses every later
3834 // hand-off, which is what bounds this to one place instead of a race
3835 // the driver would have to keep re-checking on its way out.
3836 let handed = self.context.close_handed_ops();
3837 if self.ops.is_empty() && handed.is_empty() {
3838 return;
3839 }
3840 let mut promises = self.runtime_state.promises.lock().unwrap();
3841 for id in self.ops.drain() {
3842 promises.remove(&id);
3843 }
3844 for (id, _, _) in handed {
3845 promises.remove(&id);
3846 }
3847 }
3848
3849 /// The context whose mailbox carries the ops other turns enqueued for
3850 /// this event.
3851 ///
3852 /// Borrowed, not cloned. The driver reads this once per pass of a loop
3853 /// that turns for every operation the event completes, and it holds the
3854 /// entry alive for longer than it holds this.
3855 pub(crate) fn io_context(&self) -> &Arc<IoContext> {
3856 &self.context
3857 }
3858
3859 /// Give an op to the event whose continuation enqueued it.
3860 ///
3861 /// The owner's driver polls it, so the owner's retirement decides when it
3862 /// is cancelled and this event's retirement cannot take it away. An owner
3863 /// that is already gone can never run the continuation again, so its
3864 /// resolver goes with the op, exactly as `abandon` drops this event's own.
3865 fn hand_op(
3866 &mut self,
3867 owner: u64,
3868 id: u64,
3869 future: asyncrt::OpFuture,
3870 lifetime: asyncrt::OpLifetime,
3871 ) {
3872 // One branch for both refusals — an owner that is already gone, and
3873 // one whose mailbox closed while this turn ran. Splitting them let the
3874 // second forget to drop the resolver, which is the whole defect.
3875 let delivered = self
3876 .runtime_state
3877 .io_context(owner)
3878 .is_some_and(|context| context.hand_op(id, future, lifetime));
3879 if !delivered {
3880 self.runtime_state.promises.lock().unwrap().remove(&id);
3881 }
3882 }
3883
3884 /// Take the ops another turn enqueued for this event, and record them as
3885 /// this event's own so that `deliver` and `abandon` treat them alike.
3886 pub(crate) fn take_handed_ops(&mut self) -> Vec<Op> {
3887 // The common answer is "none", and reaching it without the queue's
3888 // lock is why the count exists.
3889 if !self.context.has_handed_ops() {
3890 return Vec::new();
3891 }
3892 let handed = self.context.take_handed_ops();
3893 let mut ops = Vec::with_capacity(handed.len());
3894 for (id, future, lifetime) in handed {
3895 self.ops.insert(id);
3896 if lifetime == asyncrt::OpLifetime::IoContext {
3897 self.io_context_ops.insert(id);
3898 }
3899 if lifetime == asyncrt::OpLifetime::Unrefed {
3900 self.unrefed_ops.insert(id);
3901 }
3902 ops.push((id, future));
3903 }
3904 ops
3905 }
3906
3907 fn retire_background_for_shutdown(&mut self) {
3908 self.background = None;
3909 self.context.seal_wait_until();
3910 self.context.close_sockets();
3911 }
3912}
3913
3914/// The CPED slot carries three riders in one immutable record: the
3915/// harness's async-context frame (`__als_get`/`__als_set` — ALS and
3916/// request-context confinement), telemetry's trace context, and the native
3917/// `IoContext` token. Each write builds a fresh three-element array preserving
3918/// the other riders, so V8's per-reaction snapshots restore them atomically.
3919/// Telemetry once took the whole slot and exposed this collision.
3920///
3921/// When all three riders are absent, the slot stays undefined and V8 can use
3922/// its empty-state fast path. Stateless code can retain that path. A cell
3923/// event intentionally installs the native token even when telemetry is off.
3924///
3925/// This reads one rider and leaves the other two unmaterialized. Reading a
3926/// single rider is what every caller wants, so the layout rule lives here
3927/// once and each accessor names its own index. Returning all three instead
3928/// made a caller that wanted one rider pay three `get_index` calls, and a
3929/// caller that wanted two pay six across two reads of the slot. Op
3930/// attribution wants only the token and runs for every operation a
3931/// JavaScript call enqueues, so that difference sits on a hot path.
3932fn cped_rider<'s>(scope: &mut v8::PinScope<'s, '_>, index: u32) -> v8::Local<'s, v8::Value> {
3933 let data = scope.get_continuation_preserved_embedder_data();
3934 let record = match v8::Local::<v8::Array>::try_from(data) {
3935 // Length 2 is the former layout. Its snapshots can still be live
3936 // while an isolate upgrades across this code boundary, and they
3937 // carry no token, so the token rider reads undefined from them.
3938 Ok(record) if record.length() == 3 || record.length() == 2 => record,
3939 // Any non-record value is a bare frame from before this scheme, or
3940 // the empty slot. Only the frame rider can read anything from it,
3941 // and that path returns without asking V8 for anything further.
3942 _ => {
3943 return if index == 0 {
3944 data
3945 } else {
3946 v8::undefined(scope).into()
3947 };
3948 }
3949 };
3950 if index >= record.length() {
3951 return v8::undefined(scope).into();
3952 }
3953 let undefined = v8::undefined(scope).into();
3954 record.get_index(scope, index).unwrap_or(undefined)
3955}
3956
3957fn cped_frame<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
3958 cped_rider(scope, 0)
3959}
3960
3961fn cped_trace<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
3962 cped_rider(scope, 1)
3963}
3964
3965fn cped_io_context<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
3966 cped_rider(scope, 2)
3967}
3968
3969fn set_cped(
3970 scope: &mut v8::PinScope,
3971 frame: v8::Local<v8::Value>,
3972 trace: v8::Local<v8::Value>,
3973 io_context: v8::Local<v8::Value>,
3974) {
3975 if frame.is_undefined() && trace.is_undefined() && io_context.is_undefined() {
3976 let undefined = v8::undefined(scope).into();
3977 scope.set_continuation_preserved_embedder_data(undefined);
3978 return;
3979 }
3980 let record = v8::Array::new(scope, 3);
3981 record.set_index(scope, 0, frame);
3982 record.set_index(scope, 1, trace);
3983 record.set_index(scope, 2, io_context);
3984 scope.set_continuation_preserved_embedder_data(record.into());
3985}
3986
3987/// Install a trace context into the isolate's CPED slot for one turn.
3988///
3989/// V8 snapshots continuation-preserved embedder data when a promise
3990/// reaction is registered and restores it while the reaction runs. That
3991/// is the exactness `console.log` correlation needs: a continuation
3992/// belonging to a *different* entry that runs during this turn's
3993/// microtask checkpoint carries its own context, not this turn's. The
3994/// layout is 16 trace-id bytes, 8 span-id bytes, and one sampling byte
3995/// in one ArrayBuffer. Sampled contexts pay the existing cost, and only a
3996/// rejected foreign context adds this cost to an unsampled request.
3997///
3998/// Returns the previous slot value *only when a trace was installed*; the
3999/// caller restores it before releasing the isolate. An untraced turn does not
4000/// install the trace rider. A cell event separately installs its `IoContext`
4001/// token, so V8 can attribute a continuation that runs during another event's
4002/// checkpoint.
4003fn install_trace<'s>(
4004 scope: &mut v8::PinScope<'s, '_>,
4005 trace: Option<&crate::telemetry::TraceContext>,
4006) -> Option<v8::Local<'s, v8::Value>> {
4007 let context = trace?;
4008 let previous = scope.get_continuation_preserved_embedder_data();
4009 let buffer = v8::ArrayBuffer::new(scope, 25);
4010 let data = buffer.get_backing_store().data()?;
4011 let bytes = data.as_ptr() as *mut u8;
4012 // SAFETY: a freshly created 25-byte buffer, written before any JS
4013 // can see it.
4014 unsafe {
4015 std::ptr::copy_nonoverlapping(context.trace_id.as_ptr(), bytes, 16);
4016 std::ptr::copy_nonoverlapping(context.span_id.as_ptr(), bytes.add(16), 8);
4017 bytes.add(24).write(u8::from(context.sampled));
4018 }
4019 let frame = cped_frame(scope);
4020 let io_context = cped_io_context(scope);
4021 set_cped(scope, frame, buffer.into(), io_context);
4022 Some(previous)
4023}
4024
4025fn restore_trace(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) {
4026 if let Some(previous) = previous {
4027 scope.set_continuation_preserved_embedder_data(previous);
4028 }
4029}
4030
4031/// Install the current cell event's native context in CPED. V8 restores this
4032/// token for each reaction, including a reaction that runs during another
4033/// event's microtask checkpoint.
4034fn install_io_context<'s>(
4035 scope: &mut v8::PinScope<'s, '_>,
4036 context: &IoContext,
4037) -> Option<v8::Local<'s, v8::Value>> {
4038 let (id, _) = context.continuation.as_ref()?;
4039 let previous = scope.get_continuation_preserved_embedder_data();
4040 let frame = cped_frame(scope);
4041 let trace = cped_trace(scope);
4042 let token: v8::Local<v8::Value> = v8::BigInt::new_from_u64(scope, *id).into();
4043 set_cped(scope, frame, trace, token);
4044 Some(previous)
4045}
4046
4047fn restore_io_context(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) {
4048 if let Some(previous) = previous {
4049 scope.set_continuation_preserved_embedder_data(previous);
4050 }
4051}
4052
4053fn current_reaction_io_context(scope: &mut v8::PinScope) -> Option<Arc<IoContext>> {
4054 let id = reaction_continuation_id(scope)?;
4055 actor_runtime_state(scope).io_context(id)
4056}
4057
4058/// The `IoContext` id of the code running at this exact point, read from CPED.
4059///
4060/// It is the running turn's id, or the id of a continuation V8 restored — the
4061/// resource identity of the code, even when a critical section has a separate
4062/// driver for its native operations.
4063fn reaction_continuation_id(scope: &mut v8::PinScope) -> Option<u64> {
4064 continuation_context_id(scope, 0)
4065}
4066
4067/// A plain token names both the resource context and the operation driver.
4068/// A critical section carries [origin, driver] instead: its driver owns the
4069/// gate and must also poll its operations, while storage and resource access
4070/// must still resolve to the origin. Keeping both in the same CPED rider
4071/// preserves this relationship across foreign microtask checkpoints and ALS
4072/// frame changes without charging ordinary continuations for another rider.
4073fn continuation_context_id(scope: &mut v8::PinScope, index: u32) -> Option<u64> {
4074 let token = cped_io_context(scope);
4075 let token = if let Ok(pair) = v8::Local::<v8::Array>::try_from(token) {
4076 pair.get_index(scope, index)?
4077 } else {
4078 token
4079 };
4080 let token = v8::Local::<v8::BigInt>::try_from(token).ok()?;
4081 let (id, lossless) = token.u64_value();
4082 lossless.then_some(id)
4083}
4084
4085fn operation_continuation_id(scope: &mut v8::PinScope) -> Option<u64> {
4086 continuation_context_id(scope, 1)
4087}
4088
4089/// Enter a critical section with its gate owner and operation driver bound
4090/// together. Only the callback's continuations inherit the pair; restoring
4091/// the previous slot leaves the caller's subsequent work with its own event.
4092fn op_with_input_gate_context(
4093 scope: &mut v8::PinScope,
4094 args: v8::FunctionCallbackArguments,
4095 mut rv: v8::ReturnValue<v8::Value>,
4096) {
4097 let Ok(callback) = v8::Local::<v8::Function>::try_from(args.get(0)) else {
4098 return;
4099 };
4100 let previous = scope.get_continuation_preserved_embedder_data();
4101 let token = cped_io_context(scope);
4102 // A nested block inherits its driver's identity, even if a third event
4103 // runs the checkpoint. A new block uses the entry driving this turn.
4104 if !token.is_array() {
4105 if let Some(origin) = reaction_continuation_id(scope) {
4106 let driver = current_context().continuation_id().unwrap_or(origin);
4107 let origin = v8::BigInt::new_from_u64(scope, origin);
4108 let driver = v8::BigInt::new_from_u64(scope, driver);
4109 let pair = v8::Array::new_with_elements(scope, &[origin.into(), driver.into()]);
4110 let frame = cped_frame(scope);
4111 let trace = cped_trace(scope);
4112 set_cped(scope, frame, trace, pair.into());
4113 }
4114 }
4115 let receiver = v8::undefined(scope).into();
4116 let result = callback.call(scope, receiver, &[]);
4117 scope.set_continuation_preserved_embedder_data(previous);
4118 if let Some(result) = result {
4119 rv.set(result);
4120 }
4121}
4122
4123/// Resolve the exact tracked reaction, or use the active context when this
4124/// isolate does not track reactions at all.
4125///
4126/// Cell events always install a token. A token that no longer resolves names
4127/// a retired event and must not borrow another event's ambient context.
4128/// Stateless requests install no token, so their current turn remains the
4129/// only context that can own a synchronous operation such as `process.exit`.
4130fn current_reaction_or_untracked_io_context(scope: &mut v8::PinScope) -> Option<Arc<IoContext>> {
4131 if cped_io_context(scope).is_undefined() {
4132 return Some(current_context());
4133 }
4134 current_reaction_io_context(scope)
4135}
4136
4137/// The trace context current at this exact point of JS execution, read
4138/// from CPED — the running turn's, or the running continuation's if V8
4139/// restored one. `None` when telemetry is off or execution is outside an
4140/// entry. An unsampled foreign context remains present with its flag clear.
4141pub(crate) fn current_trace_context(
4142 scope: &mut v8::PinScope,
4143) -> Option<crate::telemetry::TraceContext> {
4144 if !crate::telemetry::active() {
4145 return None;
4146 }
4147 let data = cped_trace(scope);
4148 let buffer = v8::Local::<v8::ArrayBuffer>::try_from(data).ok()?;
4149 if buffer.byte_length() != 25 {
4150 return None;
4151 }
4152 let data = buffer.get_backing_store().data()?;
4153 let bytes = data.as_ptr() as *const u8;
4154 let mut trace_id = [0u8; 16];
4155 let mut span_id = [0u8; 8];
4156 // SAFETY: length checked; the buffer is alive for this scope.
4157 unsafe {
4158 std::ptr::copy_nonoverlapping(bytes, trace_id.as_mut_ptr(), 16);
4159 std::ptr::copy_nonoverlapping(bytes.add(16), span_id.as_mut_ptr(), 8);
4160 }
4161 let sampled = unsafe { bytes.add(24).read() != 0 };
4162 Some(crate::telemetry::TraceContext {
4163 trace_id,
4164 span_id,
4165 sampled,
4166 })
4167}
4168
4169/// The isolate, entered for one turn. Everything a request does to a shared
4170/// isolate goes through one of these, and none of them may be held across an
4171/// await: the caller takes the pool's async permit first, runs a turn, and
4172/// leaves.
4173/// An isolate's heap as V8 accounts for it, for `/state`.
4174#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4175pub struct HeapBytes {
4176 /// Physical memory committed to the heap.
4177 pub physical: u64,
4178 /// External memory the isolate tracks: array buffer stores and the like.
4179 pub external: u64,
4180}
4181
4182impl Worker {
4183 /// The heap V8 reports for this isolate. Takes the isolate lock, so the
4184 /// caller must hold the pool's permit for this worker, exactly as a turn
4185 /// does; `None` once the isolate has been freed.
4186 pub fn heap_bytes(&self) -> Option<HeapBytes> {
4187 let inner = self.inner.as_ref()?;
4188 let (mut locker, _cells) = inner.lock();
4189 let statistics = locker.get_heap_statistics();
4190 Some(HeapBytes {
4191 physical: statistics.total_physical_size() as u64,
4192 external: statistics.external_memory() as u64,
4193 })
4194 }
4195
4196 /// Run a request's first turn.
4197 ///
4198 /// Returns what is now in flight — `None` when nothing is, the reply
4199 /// already carrying the error — and the ops the handler enqueued, which
4200 /// the caller awaits with no isolate held.
4201 pub fn turn_begin(
4202 &mut self,
4203 job: crate::WorkerJob,
4204 trace: Option<crate::telemetry::TraceContext>,
4205 ) -> (Option<InFlight>, Vec<Op>) {
4206 let Some(inner) = self.inner.as_mut() else {
4207 return (None, Vec::new());
4208 };
4209 let (mut locker, _cells) = inner.lock();
4210 inner.recover_heap(&mut locker);
4211 v8::scope!(let hs, &mut *locker);
4212 let realm = inner.realm(hs);
4213 let context = realm.context;
4214 let cs = &mut v8::ContextScope::new(hs, context);
4215 let tc = std::pin::pin!(v8::TryCatch::new(cs));
4216 let tc = &mut tc.init();
4217
4218 advance_io_time(tc);
4219 let previous = install_trace(tc, trace.as_ref());
4220 let invocation_limits = match &job {
4221 crate::WorkerJob::Fetch {
4222 invocation_limits, ..
4223 }
4224 | crate::WorkerJob::Rpc {
4225 invocation_limits, ..
4226 } => *invocation_limits,
4227 crate::WorkerJob::Queue { .. } => None,
4228 };
4229 let initial_limits =
4230 effective_resource_limits(inner.runtime_state.resource_limits, invocation_limits);
4231 let declared_ms = initial_limits.and_then(|limits| limits.cpu_ms);
4232 let cpu_watchdog = inner.cpu_watchdog(
4233 declared_ms.map(|milliseconds| Duration::from_millis(u64::from(milliseconds))),
4234 declared_ms,
4235 );
4236 let begun = begin(tc, realm.fetch, job);
4237 drop(cpu_watchdog);
4238 let out = match begun {
4239 Begun::Running(mut entry) => {
4240 entry.trace = trace;
4241 // A handler that returned an already-resolved promise is
4242 // finished before it ever suspends, and must not wait for an
4243 // op it will never start.
4244 let ops = finish_turn(tc, &mut entry);
4245 (Some(*entry), ops)
4246 }
4247 Begun::Threw(failure) => {
4248 let BegunFailure {
4249 answer,
4250 cpu_error,
4251 tail_report,
4252 } = *failure;
4253 let error = take_execution_termination(tc)
4254 .or_else(|| cpu_error.map(anyhow::Error::msg))
4255 .unwrap_or_else(|| anyhow!("fetch threw: {}", exc!(tc)));
4256 if let Some((mut report, context)) = tail_report {
4257 report.record_failure(format!("{error:#}"));
4258 report.finish(&context);
4259 }
4260 answer.fail(error);
4261 (None, Vec::new())
4262 }
4263 Begun::Nothing => (None, Vec::new()),
4264 };
4265 restore_trace(tc, previous);
4266 out
4267 }
4268
4269 /// Enter the isolate solely to end a request whose client has hung up.
4270 ///
4271 /// A suspended request notices the disconnect without any isolate — the
4272 /// flag is host state — so this is reached only when it has actually
4273 /// fired, rather than on a timer as the blocking run loop did.
4274 pub fn turn_cancel(&mut self, entry: &mut InFlight) -> Vec<Op> {
4275 self.cancel_turn(entry, false)
4276 }
4277
4278 /// The runtime is stopping: end the event as a client hang-up does, but
4279 /// keep nothing running for it, a critical section included. The block
4280 /// would not reach its end before the process exits, so its gate is
4281 /// abandoned and the events queued behind it are refused now rather
4282 /// than left waiting through the shutdown.
4283 pub fn turn_cancel_for_shutdown(&mut self, entry: &mut InFlight) -> Vec<Op> {
4284 self.cancel_turn(entry, true)
4285 }
4286
4287 fn cancel_turn(&mut self, entry: &mut InFlight, shutdown: bool) -> Vec<Op> {
4288 let Some(inner) = self.inner.as_mut() else {
4289 return Vec::new();
4290 };
4291 let (mut locker, _cells) = inner.lock();
4292 v8::scope!(let hs, &mut *locker);
4293 let realm = inner.realm(hs);
4294 let context = realm.context;
4295 let cs = &mut v8::ContextScope::new(hs, context);
4296 let tc = std::pin::pin!(v8::TryCatch::new(cs));
4297 let tc = &mut tc.init();
4298
4299 advance_io_time(tc);
4300 let previous_io_context = install_io_context(tc, &entry.context);
4301 let previous = install_trace(tc, entry.trace.as_ref());
4302 entry.context.begin_cpu_turn();
4303 let cpu_watchdog = inner.cpu_watchdog(
4304 entry.context.remaining_cpu_budget(),
4305 entry.context.cpu_limit_ms(),
4306 );
4307 cancel(tc, entry, shutdown);
4308 drop(cpu_watchdog);
4309 let ops = finish_turn(tc, entry);
4310 restore_trace(tc, previous);
4311 restore_io_context(tc, previous_io_context);
4312 ops
4313 }
4314
4315 /// Retire input-gate work for an event that cannot run JavaScript again.
4316 ///
4317 /// The host claims are taken before the isolate lock because the caller
4318 /// already owns this slot. A newly woken event can queue for the slot, but
4319 /// it cannot enter the isolate until the stale actor state is removed.
4320 pub(crate) fn turn_retire_input_gates(&mut self, entry: &InFlight) {
4321 entry.context.force_retire_cross_entry_gates();
4322 let _ = abandon_context_input_gates(&entry.context);
4323 self.turn_retire_input_gate_context(entry);
4324 }
4325
4326 /// Enforce the host-side invariant when an ordinarily completed event
4327 /// drops its final owner. The JavaScript `finally` normally released every
4328 /// gate, so entering the isolate is necessary only when a hold remains.
4329 pub(crate) fn turn_abandon_input_gates(&mut self, entry: &InFlight) {
4330 let abandoned = abandon_context_input_gates(&entry.context);
4331 if abandoned.is_empty() {
4332 return;
4333 }
4334 self.turn_retire_input_gate_context(entry);
4335 }
4336
4337 fn turn_retire_input_gate_context(&mut self, entry: &InFlight) {
4338 let Some(inner) = self.inner.as_mut() else {
4339 return;
4340 };
4341 let (mut locker, _cells) = inner.lock();
4342 v8::scope!(let hs, &mut *locker);
4343 let realm = inner.realm(hs);
4344 let context = realm.context;
4345 let cs = &mut v8::ContextScope::new(hs, context);
4346 let context_id = entry.context.continuation_id().unwrap_or_default();
4347 retire_input_gate_js_context(cs, context_id);
4348 }
4349
4350 /// Run a later turn: resolve one of this request's ops, drain the
4351 /// microtasks that follow, and answer if the handler settled.
4352 pub fn turn_deliver(
4353 &mut self,
4354 entry: &mut InFlight,
4355 op: u64,
4356 res: Result<asyncrt::OpOut, String>,
4357 ) -> Vec<Op> {
4358 let Some(inner) = self.inner.as_mut() else {
4359 return Vec::new();
4360 };
4361 let (mut locker, _cells) = inner.lock();
4362 v8::scope!(let hs, &mut *locker);
4363 let realm = inner.realm(hs);
4364 let context = realm.context;
4365 let cs = &mut v8::ContextScope::new(hs, context);
4366 let tc = std::pin::pin!(v8::TryCatch::new(cs));
4367 let tc = &mut tc.init();
4368
4369 advance_io_time(tc);
4370 let previous_io_context = install_io_context(tc, &entry.context);
4371 let previous = install_trace(tc, entry.trace.as_ref());
4372 entry.context.begin_cpu_turn();
4373 let cpu_watchdog = inner.cpu_watchdog(
4374 entry.context.remaining_cpu_budget(),
4375 entry.context.cpu_limit_ms(),
4376 );
4377 deliver(tc, entry, op, res);
4378 cancelled(tc, entry);
4379 drop(cpu_watchdog);
4380 let ops = finish_turn(tc, entry);
4381 restore_trace(tc, previous);
4382 restore_io_context(tc, previous_io_context);
4383 ops
4384 }
4385}
4386
4387/// Close a turn, whatever the turn did.
4388///
4389/// Every step earns its place and the order is the whole point:
4390///
4391/// 1. **settle** — the handler's promise may have resolved, so marshal the
4392/// response and answer. Marshalling can start a JS-to-host body pump and
4393/// register it with `waitUntil`.
4394/// 2. **checkpoint** — that pump's native ops exist only once the microtasks
4395/// which create them run.
4396/// 3. **release the facet gate** — the second facet flush can now cover every
4397/// write exposed by the checkpoint, or reject the held response.
4398/// 4. **settle again** — the checkpoint may itself have settled the promise,
4399/// or the `waitUntil` aggregate.
4400/// 5. **flush captured frames** — a `webSocketMessage` handler that has not
4401/// answered is suspended, so the frames it has sent so far leave now
4402/// rather than at the end of the handler.
4403/// 6. **adopt** — only now is the set of ops this request waits on complete.
4404/// 7. **close** — close the sockets the request opened, once it has retired.
4405/// A socket the response took over left that set at the handoff.
4406///
4407/// Draining before step 2 is the bug that made a streaming handler answer
4408/// with nothing outstanding and conclude it was waiting on nothing.
4409/// The checkpoint before adoption is what makes response-body pumps visible.
4410///
4411/// An accepted Worker socket starts its next `__ws_next` before the fetch
4412/// response retires. The driver used to drop that receive future with the
4413/// handler's other ops once the handler answered, so later frames hung. An op
4414/// that owns the `IoContext` therefore keeps the entry's ops alive after the
4415/// answer, through `keeps_native_ops`. The lifetime travels in the spawn
4416/// record rather than in a separate op-id tag: a tag can outlive a failed
4417/// turn, and the spawn and its classification drain together. Such an op
4418/// does not defer retirement: see `retired`.
4419fn finish_turn(tc: &mut v8::PinScope, entry: &mut InFlight) -> Vec<Op> {
4420 if let Err(error) = finish_cpu_turn(tc, entry) {
4421 let error = take_execution_termination_in_context(tc, Some(&entry.context))
4422 .unwrap_or_else(|| anyhow!(error));
4423 entry.fail_in_turn(error);
4424 entry.background = None;
4425 entry.abandon();
4426 ws_capture_flush_touched(tc, &entry.runtime_state);
4427 return Vec::new();
4428 }
4429 entry.context.begin_cpu_turn();
4430 {
4431 let _cpu_watchdog = cpu_watchdog_for_context(tc, &entry.context);
4432 settle(tc, entry);
4433 tc.perform_microtask_checkpoint();
4434 }
4435 if let Err(error) = finish_cpu_turn(tc, entry) {
4436 let error = take_execution_termination_in_context(tc, Some(&entry.context))
4437 .unwrap_or_else(|| anyhow!(error));
4438 entry.fail_in_turn(error);
4439 entry.background = None;
4440 entry.abandon();
4441 ws_capture_flush_touched(tc, &entry.runtime_state);
4442 return Vec::new();
4443 }
4444 // `abort()` and `process.exit()` terminate execution without settling
4445 // the handler's promise, so an entry that only watched the promise would
4446 // wait on it forever and then report that it was waiting on nothing.
4447 // The blocking loop broke out of its loop here; an entry fails here.
4448 if let Some(error) = take_execution_termination_in_context(tc, Some(&entry.context)) {
4449 entry.fail_in_turn(error);
4450 entry.background = None;
4451 entry.abandon();
4452 ws_capture_flush_touched(tc, &entry.runtime_state);
4453 return Vec::new();
4454 }
4455 settle(tc, entry);
4456 // 5. **release what suspended WebSocket handlers have sent** — after the
4457 // settles above, so a handler that answered in this turn keeps the
4458 // whole-batch path its answer carries. The set comes from each capture
4459 // write rather than the turn owner, because the checkpoint can run a
4460 // continuation from another event.
4461 ws_capture_flush_touched(tc, &entry.runtime_state);
4462 let ops = adopt(entry);
4463 // 7. **close the request's sockets** — see above.
4464 if entry.retired() {
4465 entry.context.close_sockets();
4466 }
4467 ops
4468}
4469
4470/// An op the JS enqueued, and the id whose promise it resolves.
4471pub type Op = (u64, asyncrt::OpFuture);
4472
4473/// Take the ops this turn enqueued that belong to this event, and hand every
4474/// other event its own.
4475///
4476/// Drained after `settle`, not before: ending an event runs JS, and anything
4477/// that starts there belongs to this request too. The pump drained first and
4478/// so could attribute those to whichever entry it settled next.
4479///
4480/// A turn is not proof of ownership. V8 runs a *foreign* continuation during
4481/// this turn's microtask checkpoint — a cell event resumed by the promise this
4482/// event just settled — and an op that continuation enqueues arrives here
4483/// exactly like this event's own. Adopting it made the wrong driver poll it,
4484/// and retiring then cancelled it together with the resolver, so the event
4485/// really waiting never settled and every later event queued behind it. The op
4486/// layer names the enqueueing continuation,
4487/// so an op with a foreign name goes to that event's driver instead. Critical
4488/// sections carry an explicit driver alongside their resource context; the
4489/// op wrapper uses that driver so gate retirement and op cancellation agree.
4490fn adopt(entry: &mut InFlight) -> Vec<Op> {
4491 let spawns = asyncrt::drain_spawns();
4492 let mine = entry.context.continuation_id();
4493 let mut ops = Vec::with_capacity(spawns.len());
4494 for (id, future, lifetime, owner) in spawns {
4495 if let Some(owner) = owner.filter(|owner| Some(*owner) != mine) {
4496 entry.hand_op(owner, id, future, lifetime);
4497 continue;
4498 }
4499 entry.ops.insert(id);
4500 if lifetime == asyncrt::OpLifetime::IoContext {
4501 entry.io_context_ops.insert(id);
4502 }
4503 if lifetime == asyncrt::OpLifetime::Unrefed {
4504 entry.unrefed_ops.insert(id);
4505 }
4506 ops.push((id, future));
4507 }
4508 ops
4509}
4510
4511/// What starting a request produced.
4512enum Begun {
4513 /// In flight. Its ops must be adopted and its promise driven.
4514 Running(Box<InFlight>),
4515 /// The handler threw before it could suspend, so nothing is in flight.
4516 /// The exception belongs to the caller's `TryCatch` — an unnameable type
4517 /// no signature here can take — so the caller reads it and answers.
4518 Threw(Box<BegunFailure>),
4519 /// Nothing started: the job was not a fetch, or the reply already
4520 /// carries the error.
4521 Nothing,
4522}
4523
4524struct BegunFailure {
4525 answer: Answer,
4526 cpu_error: Option<String>,
4527 tail_report: Option<(TailReportState, Arc<IoContext>)>,
4528}
4529
4530/// Start a request: build it, call the Worker's `fetch`, and hand back what
4531/// is now in flight.
4532///
4533/// The half of a turn that runs *before* anything can suspend.
4534fn begin<'s>(
4535 tc: &mut v8::PinScope<'s, '_>,
4536 fetch: v8::Local<'s, v8::Function>,
4537 job: crate::WorkerJob,
4538) -> Begun {
4539 let job = match job {
4540 crate::WorkerJob::Rpc {
4541 entrypoint,
4542 operation,
4543 props,
4544 invocation_limits,
4545 reply,
4546 } => {
4547 return begin_entrypoint_rpc(
4548 tc,
4549 &entrypoint,
4550 operation,
4551 props,
4552 invocation_limits,
4553 reply,
4554 );
4555 }
4556 crate::WorkerJob::Queue { batch, reply, .. } => {
4557 return begin_queue(tc, batch, reply);
4558 }
4559 job => job,
4560 };
4561 let crate::WorkerJob::Fetch {
4562 entrypoint,
4563 invocation_limits,
4564 url,
4565 method,
4566 body,
4567 headers,
4568 request_id,
4569 tail_report,
4570 reply,
4571 ..
4572 } = job
4573 else {
4574 return Begun::Nothing;
4575 };
4576 let runtime_state = actor_runtime_state(tc);
4577 let tail_reporting = tail_report.is_some();
4578 debug_assert!(
4579 !tail_reporting || runtime_state.tail_reporting,
4580 "a tail report reached a Worker that was loaded without tails",
4581 );
4582 // The report sender is the invocation-level authority. The isolate-level
4583 // option also applies to RPC and cell events, but those events have no
4584 // report to consume retained logs, so enabling capture for them only
4585 // holds records until their IoContext retires.
4586 let context = IoContext::with_options(
4587 effective_resource_limits(runtime_state.resource_limits, invocation_limits),
4588 tail_reporting,
4589 );
4590 if let Some(stream_id) = body.stream_id() {
4591 context.own_body_stream(stream_id);
4592 }
4593 let guard = CurrentGuard::enter(context.clone());
4594 context.begin_cpu_turn();
4595 let target = match entrypoint {
4596 Some(entrypoint) => FetchTarget::Entrypoint(entrypoint),
4597 None => FetchTarget::Default(fetch),
4598 };
4599 let started = start_fetch(tc, target, &url, &method, body, &headers, request_id);
4600 let tail_headers = tail_request_headers(&headers);
4601 let mut tail_report = tail_report.map(|reply| TailReportState {
4602 reply,
4603 script_name: runtime_state.script_name.clone(),
4604 event_timestamp: unix_now_ms(),
4605 url,
4606 method,
4607 headers: tail_headers,
4608 response_status: None,
4609 failure: None,
4610 });
4611 let promise = match started {
4612 Ok(Started::Running(ret, active)) => match ret.try_cast::<v8::Promise>() {
4613 Ok(promise) => Ok((promise, active)),
4614 Err(_) => resolved_promise(tc, ret).map(|promise| (promise, active)),
4615 },
4616 Ok(Started::Threw) => {
4617 let cpu_error = context.finish_cpu_turn().err();
4618 drop(guard);
4619 return Begun::Threw(Box::new(BegunFailure {
4620 answer: Answer::Fetch(reply),
4621 cpu_error,
4622 tail_report: tail_report.take().map(|report| (report, context)),
4623 }));
4624 }
4625 Err(error) => Err(error),
4626 };
4627 match promise {
4628 Ok((promise, active_request_id)) => {
4629 tc.perform_microtask_checkpoint();
4630 let entry = InFlight {
4631 runtime_state,
4632 promise: v8::Global::new(tc, promise),
4633 context,
4634 scope: None,
4635 writes_before: None,
4636 request_id,
4637 active_request_id,
4638 reply: Some(Answer::Fetch(reply)),
4639 gated_reply: None,
4640 background: None,
4641 completed_cell_event: false,
4642 ops: std::collections::HashSet::new(),
4643 io_context_ops: std::collections::HashSet::new(),
4644 unrefed_ops: std::collections::HashSet::new(),
4645 alarm: None,
4646 started: Instant::now(),
4647 trace: None,
4648 failure: None,
4649 tail_report,
4650 };
4651 drop(guard);
4652 Begun::Running(Box::new(entry))
4653 }
4654 Err(error) => {
4655 let cpu_error = context.finish_cpu_turn().err().map(anyhow::Error::msg);
4656 let error = take_execution_termination(tc)
4657 .or(cpu_error)
4658 .unwrap_or(error);
4659 if let Some(mut report) = tail_report.take() {
4660 report.record_failure(format!("{error:#}"));
4661 report.finish(&context);
4662 }
4663 drop(guard);
4664 let _ = reply.send(Err(error));
4665 Begun::Nothing
4666 }
4667 }
4668}
4669
4670/// Start an entrypoint RPC's first turn.
4671///
4672/// The same shape as a fetch and deliberately so: call the handler, keep the
4673/// promise, and let `drive` pump it with no isolate held across the awaits.
4674/// The old dispatcher blocked until the promise settled, which is why RPC
4675/// needed a thread of its own and why `WorkerPool` outlived the fetch path.
4676fn begin_entrypoint_rpc(
4677 tc: &mut v8::PinScope,
4678 entrypoint: &str,
4679 operation: crate::WorkerRpcOperation,
4680 props: Vec<u8>,
4681 invocation_limits: Option<ResourceLimits>,
4682 reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
4683) -> Begun {
4684 let context = IoContext::with_resource_limits(effective_resource_limits(
4685 actor_runtime_state(tc).resource_limits,
4686 invocation_limits,
4687 ));
4688 let guard = CurrentGuard::enter(context.clone());
4689 context.begin_cpu_turn();
4690 let started = (|| {
4691 let f = internal_function(tc, "__dispatchEntrypointRpc")?;
4692 let entrypoint = v8::String::new(tc, entrypoint).unwrap();
4693 let (path, args) = match operation {
4694 crate::WorkerRpcOperation::Get { path } => (path, v8::null(tc).into()),
4695 crate::WorkerRpcOperation::Call { path, args } => (path, bytes_value(tc, args)),
4696 };
4697 let path = path
4698 .iter()
4699 .map(|part| v8::String::new(tc, part).unwrap().into())
4700 .collect::<Vec<v8::Local<v8::Value>>>();
4701 let path = v8::Array::new_with_elements(tc, &path);
4702 // The caller's props, structured-clone bytes like `args`. `local` stays
4703 // false: the call crossed an isolate boundary.
4704 let local = v8::Boolean::new(tc, false);
4705 let props = bytes_value(tc, props);
4706 let recv = v8::undefined(tc).into();
4707 begin_event_context(tc)?;
4708 let ret = f
4709 .call(
4710 tc,
4711 recv,
4712 &[entrypoint.into(), path.into(), args, local.into(), props],
4713 )
4714 .ok_or_else(|| anyhow!("entrypoint RPC threw"))?;
4715 match ret.try_cast::<v8::Promise>() {
4716 Ok(promise) => Ok(promise),
4717 Err(_) => resolved_promise(tc, ret),
4718 }
4719 })();
4720 let event_started = Instant::now();
4721 match started {
4722 Ok(promise) => {
4723 tc.perform_microtask_checkpoint();
4724 let entry = InFlight {
4725 runtime_state: actor_runtime_state(tc),
4726 promise: v8::Global::new(tc, promise),
4727 context,
4728 scope: None,
4729 writes_before: None,
4730 request_id: None,
4731 active_request_id: None,
4732 reply: Some(Answer::Rpc(reply)),
4733 gated_reply: None,
4734 background: None,
4735 completed_cell_event: false,
4736 ops: std::collections::HashSet::new(),
4737 io_context_ops: std::collections::HashSet::new(),
4738 unrefed_ops: std::collections::HashSet::new(),
4739 alarm: None,
4740 started: event_started,
4741 trace: None,
4742 failure: None,
4743 tail_report: None,
4744 };
4745 drop(guard);
4746 Begun::Running(Box::new(entry))
4747 }
4748 Err(error) => {
4749 let _ = end_event_context(tc);
4750 let cpu_error = context.finish_cpu_turn().err().map(anyhow::Error::msg);
4751 let error = take_execution_termination(tc)
4752 .or(cpu_error)
4753 .unwrap_or(error);
4754 drop(guard);
4755 let _ = reply.send(Err(error));
4756 Begun::Nothing
4757 }
4758 }
4759}
4760
4761fn queue_property<'s>(
4762 scope: &mut v8::PinScope<'s, '_>,
4763 object: v8::Local<'s, v8::Object>,
4764 name: &str,
4765) -> Result<v8::Local<'s, v8::Value>> {
4766 let key = v8::String::new(scope, name).unwrap();
4767 object
4768 .get(scope, key.into())
4769 .ok_or_else(|| anyhow!("queue result has no {name}"))
4770}
4771
4772fn queue_bool<'s>(
4773 scope: &mut v8::PinScope<'s, '_>,
4774 object: v8::Local<'s, v8::Object>,
4775 name: &str,
4776) -> Result<bool> {
4777 let value = queue_property(scope, object, name)?;
4778 anyhow::ensure!(value.is_boolean(), "queue result {name} is not a boolean");
4779 Ok(value.boolean_value(scope))
4780}
4781
4782fn queue_delay<'s>(
4783 scope: &mut v8::PinScope<'s, '_>,
4784 object: v8::Local<'s, v8::Object>,
4785) -> Result<Option<i32>> {
4786 let value = queue_property(scope, object, "delaySeconds")?;
4787 if value.is_undefined() {
4788 return Ok(None);
4789 }
4790 value
4791 .int32_value(scope)
4792 .map(Some)
4793 .ok_or_else(|| anyhow!("queue retry delaySeconds is not a 32-bit integer"))
4794}
4795
4796fn queue_string_array<'s>(
4797 scope: &mut v8::PinScope<'s, '_>,
4798 object: v8::Local<'s, v8::Object>,
4799 name: &str,
4800) -> Result<Vec<String>> {
4801 let value = queue_property(scope, object, name)?;
4802 let array: v8::Local<v8::Array> = value
4803 .try_into()
4804 .map_err(|_| anyhow!("queue result {name} is not an array"))?;
4805 (0..array.length())
4806 .map(|index| {
4807 let value = array
4808 .get_index(scope, index)
4809 .ok_or_else(|| anyhow!("queue result {name}[{index}] is missing"))?;
4810 anyhow::ensure!(
4811 value.is_string(),
4812 "queue result {name}[{index}] is not a string"
4813 );
4814 Ok(value.to_rust_string_lossy(scope))
4815 })
4816 .collect()
4817}
4818
4819fn read_queue_result<'s>(
4820 scope: &mut v8::PinScope<'s, '_>,
4821 value: v8::Local<'s, v8::Value>,
4822) -> Result<QueueDispatchResult> {
4823 let object: v8::Local<v8::Object> = value
4824 .try_into()
4825 .map_err(|_| anyhow!("queue handler answered a non-object"))?;
4826 let outcome = queue_property(scope, object, "outcome")?;
4827 anyhow::ensure!(outcome.is_string(), "queue result outcome is not a string");
4828 let outcome = match outcome.to_rust_string_lossy(scope).as_str() {
4829 "ok" => QueueOutcome::Ok,
4830 "exception" => QueueOutcome::Exception,
4831 outcome => return Err(anyhow!("unknown queue result outcome {outcome}")),
4832 };
4833 let error = queue_property(scope, object, "error")?;
4834 let error = if error.is_undefined() {
4835 None
4836 } else {
4837 anyhow::ensure!(error.is_string(), "queue result error is not a string");
4838 Some(error.to_rust_string_lossy(scope))
4839 };
4840 let retry_batch: v8::Local<v8::Object> = queue_property(scope, object, "retryBatch")?
4841 .try_into()
4842 .map_err(|_| anyhow!("queue result retryBatch is not an object"))?;
4843 let retries = queue_property(scope, object, "retryMessages")?;
4844 let retries: v8::Local<v8::Array> = retries
4845 .try_into()
4846 .map_err(|_| anyhow!("queue result retryMessages is not an array"))?;
4847 let mut retry_messages = Vec::with_capacity(retries.length() as usize);
4848 for index in 0..retries.length() {
4849 let retry: v8::Local<v8::Object> = retries
4850 .get_index(scope, index)
4851 .ok_or_else(|| anyhow!("queue result retryMessages[{index}] is missing"))?
4852 .try_into()
4853 .map_err(|_| anyhow!("queue result retryMessages[{index}] is not an object"))?;
4854 let msg_id = queue_property(scope, retry, "msgId")?;
4855 anyhow::ensure!(
4856 msg_id.is_string(),
4857 "queue result retryMessages[{index}].msgId is not a string"
4858 );
4859 retry_messages.push(QueueRetryMessage {
4860 msg_id: msg_id.to_rust_string_lossy(scope),
4861 delay_seconds: queue_delay(scope, retry)?,
4862 });
4863 }
4864 Ok(QueueDispatchResult {
4865 outcome,
4866 error,
4867 ack_all: queue_bool(scope, object, "ackAll")?,
4868 retry_batch: QueueRetryBatch {
4869 retry: queue_bool(scope, retry_batch, "retry")?,
4870 delay_seconds: queue_delay(scope, retry_batch)?,
4871 },
4872 explicit_acks: queue_string_array(scope, object, "explicitAcks")?,
4873 retry_messages,
4874 })
4875}
4876
4877fn set_queue_property<'s>(
4878 scope: &mut v8::PinScope<'s, '_>,
4879 object: v8::Local<'s, v8::Object>,
4880 name: &str,
4881 value: v8::Local<'s, v8::Value>,
4882) -> Result<()> {
4883 let key = v8::String::new(scope, name).unwrap();
4884 anyhow::ensure!(
4885 object.create_data_property(scope, key.into(), value) == Some(true),
4886 "could not construct queue batch field {name}"
4887 );
4888 Ok(())
4889}
4890
4891fn queue_batch_value<'s>(
4892 scope: &mut v8::PinScope<'s, '_>,
4893 batch: QueueBatch,
4894) -> Result<v8::Local<'s, v8::Value>> {
4895 let QueueBatch {
4896 queue,
4897 messages,
4898 metrics,
4899 } = batch;
4900 let mut message_values = Vec::with_capacity(messages.len());
4901 for message in messages {
4902 let object = v8::Object::new(scope);
4903 let id = v8::String::new(scope, &message.id).unwrap();
4904 set_queue_property(scope, object, "id", id.into())?;
4905 let timestamp = v8::Number::new(scope, message.timestamp_ms as f64);
4906 set_queue_property(scope, object, "timestamp", timestamp.into())?;
4907 let body = bytes_value(scope, message.body);
4908 set_queue_property(scope, object, "body", body)?;
4909 let content_type = v8::String::new(scope, message.content_type.as_str()).unwrap();
4910 set_queue_property(scope, object, "contentType", content_type.into())?;
4911 let attempts = v8::Integer::new_from_unsigned(scope, u32::from(message.attempts));
4912 set_queue_property(scope, object, "attempts", attempts.into())?;
4913 message_values.push(object.into());
4914 }
4915
4916 let metrics_value = v8::Object::new(scope);
4917 let count = v8::Number::new(scope, metrics.backlog_count);
4918 set_queue_property(scope, metrics_value, "backlogCount", count.into())?;
4919 let bytes = v8::Number::new(scope, metrics.backlog_bytes);
4920 set_queue_property(scope, metrics_value, "backlogBytes", bytes.into())?;
4921 let oldest = match metrics.oldest_message_timestamp_ms {
4922 Some(timestamp) => v8::Number::new(scope, timestamp as f64).into(),
4923 None => v8::undefined(scope).into(),
4924 };
4925 set_queue_property(scope, metrics_value, "oldestMessageTimestamp", oldest)?;
4926
4927 let value = v8::Object::new(scope);
4928 let queue = v8::String::new(scope, &queue).unwrap();
4929 set_queue_property(scope, value, "queue", queue.into())?;
4930 let messages = v8::Array::new_with_elements(scope, &message_values);
4931 set_queue_property(scope, value, "messages", messages.into())?;
4932 set_queue_property(scope, value, "metrics", metrics_value.into())?;
4933 Ok(value.into())
4934}
4935
4936/// Start a queue consumer's first turn. The batch body bytes move directly
4937/// into V8, and only the small settlement record crosses back out.
4938fn begin_queue(
4939 tc: &mut v8::PinScope,
4940 batch: QueueBatch,
4941 reply: tokio::sync::oneshot::Sender<Result<QueueDispatchResult>>,
4942) -> Begun {
4943 let context = IoContext::with_resource_limits(actor_runtime_state(tc).resource_limits);
4944 let guard = CurrentGuard::enter(context.clone());
4945 context.begin_cpu_turn();
4946 let started = (|| {
4947 let dispatch = internal_function(tc, "__dispatchEntrypointQueue")?;
4948 let batch = queue_batch_value(tc, batch)?;
4949 let entrypoint = v8::String::new(tc, "default").unwrap();
4950 let recv = v8::undefined(tc).into();
4951 begin_event_context(tc)?;
4952 let ret = dispatch
4953 .call(tc, recv, &[entrypoint.into(), batch])
4954 .ok_or_else(|| anyhow!("queue dispatch threw"))?;
4955 match ret.try_cast::<v8::Promise>() {
4956 Ok(promise) => Ok(promise),
4957 Err(_) => resolved_promise(tc, ret),
4958 }
4959 })();
4960 match started {
4961 Ok(promise) => {
4962 tc.perform_microtask_checkpoint();
4963 let entry = InFlight {
4964 runtime_state: actor_runtime_state(tc),
4965 promise: v8::Global::new(tc, promise),
4966 context,
4967 scope: None,
4968 writes_before: None,
4969 request_id: None,
4970 active_request_id: None,
4971 reply: Some(Answer::Queue(reply)),
4972 gated_reply: None,
4973 background: None,
4974 completed_cell_event: false,
4975 ops: std::collections::HashSet::new(),
4976 io_context_ops: std::collections::HashSet::new(),
4977 unrefed_ops: std::collections::HashSet::new(),
4978 alarm: None,
4979 started: Instant::now(),
4980 trace: None,
4981 failure: None,
4982 tail_report: None,
4983 };
4984 drop(guard);
4985 Begun::Running(Box::new(entry))
4986 }
4987 Err(error) => {
4988 let _ = end_event_context(tc);
4989 let cpu_error = context.finish_cpu_turn().err().map(anyhow::Error::msg);
4990 let error = take_execution_termination(tc)
4991 .or(cpu_error)
4992 .unwrap_or(error);
4993 drop(guard);
4994 let _ = reply.send(Err(error));
4995 Begun::Nothing
4996 }
4997 }
4998}
4999
5000/// for the JSON flavor, a `Uint8Array` for structured clone.
5001fn rpc_data_value<'s>(scope: &mut v8::PinScope<'s, '_>, data: RpcData) -> v8::Local<'s, v8::Value> {
5002 match data {
5003 RpcData::Json(json) => v8::String::new(scope, &json).unwrap().into(),
5004 RpcData::V8(bytes) => bytes_value(scope, bytes.into()),
5005 }
5006}
5007
5008/// The inverse: `__dispatchRpc` answers in the flavor it was asked in.
5009fn rpc_data_ret(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> RpcData {
5010 match view_bytes(ret) {
5011 Some(bytes) => RpcData::V8(bytes.into()),
5012 None => RpcData::Json(ret.to_rust_string_lossy(scope)),
5013 }
5014}
5015
5016fn unix_now_ms() -> i64 {
5017 #[cfg(all(test, celld_internal_tests))]
5018 if let Some(timestamp_ms) = unix_now_ms_for_test() {
5019 return timestamp_ms;
5020 }
5021 std::time::SystemTime::now()
5022 .duration_since(std::time::UNIX_EPOCH)
5023 .unwrap_or_default()
5024 .as_millis()
5025 .min(i64::MAX as u128) as i64
5026}
5027
5028/// End the event, then answer with what the handler produced.
5029///
5030/// Ending it is what yields the `waitUntil` aggregate the entry keeps
5031/// driving after the caller has been served, so it happens for every answer
5032/// shape and on the error path too.
5033fn send_and_end<T>(
5034 tc: &mut v8::PinScope,
5035 context: &IoContext,
5036 reply: tokio::sync::oneshot::Sender<Result<T>>,
5037 value: Result<T>,
5038) -> (Option<v8::Global<v8::Promise>>, Option<GatedReplyRx>)
5039where
5040 T: Send + 'static,
5041{
5042 let background = end_event_context(tc).ok().flatten();
5043 let gated_reply = send_answer_after_arm_gates(reply, value, context.take_arm_gates());
5044 (
5045 background.map(|promise| v8::Global::new(tc, promise)),
5046 gated_reply,
5047 )
5048}
5049
5050/// The positions an answer's ticket carries, sampled from a cell's storage:
5051/// the write position when the handler advanced the cell's committed writes
5052/// past `writes_before`, and otherwise the position the answer observed above
5053/// the cell's published baseline. One sample serves both, so they cannot
5054/// disagree about what the cell holds, and they are returned together because
5055/// a site that gates on one alone releases the output the other covers.
5056fn gate_positions(scope: &str, writes_before: Option<u64>) -> Result<(Option<u64>, Option<u64>)> {
5057 let sample = storage::write_position(scope)?;
5058 let write = write_delta(writes_before, sample);
5059 let observed = if write.is_none() {
5060 storage::observed_position(scope, sample)
5061 } else {
5062 None
5063 };
5064 Ok((write, observed))
5065}
5066
5067/// A committed-write position only counts when the handler advanced it; celld's
5068/// own activation writes are already below `before`.
5069pub(crate) fn write_delta(before: Option<u64>, after: Option<u64>) -> Option<u64> {
5070 match (before, after) {
5071 (Some(before), Some(after)) if after > before => Some(after),
5072 _ => None,
5073 }
5074}
5075
5076/// What a claimed alarm still owes its bookkeeping.
5077///
5078/// `finish_alarm_handler` must run exactly once however the event ends, and
5079/// an event can now end without running JS at all — a budget overrun, a
5080/// handler waiting on nothing — so the entry carries the claim rather than
5081/// the caller that made it.
5082struct AlarmClaim {
5083 /// The instant the dispatch was judged due against, so the outcome is
5084 /// recorded against the same one.
5085 now_ms: i64,
5086}
5087
5088/// Start one cell event: the half that runs before the handler can suspend.
5089///
5090/// Every cell event does the same four things — name the cell it belongs to,
5091/// sample the writes its answer will be gated on, open an event context, and
5092/// keep the promise the dispatcher returned. Only the call and the shape of
5093/// the answer differ, which is what the arguments say.
5094fn start_cell_event<'s>(
5095 tc: &mut v8::PinScope<'s, '_>,
5096 scope: &str,
5097 answer: Answer,
5098 request_id: Option<RequestId>,
5099 body_stream_id: Option<u64>,
5100 capture_frames: bool,
5101 call: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>>,
5102) -> Begun {
5103 let runtime_state = actor_runtime_state(tc);
5104 let context = IoContext::tracked(&runtime_state);
5105 if let Some(stream_id) = body_stream_id {
5106 context.own_body_stream(stream_id);
5107 }
5108 let guard = CurrentGuard::enter(context.clone());
5109 let previous_io_context = install_io_context(tc, &context);
5110 context.begin_cpu_turn();
5111 // Sampled before the handler runs so the output gate can tell a write
5112 // this event made from celld's own activation writes. The first sample of
5113 // an activation is also the baseline a read-only answer observes above.
5114 let writes_before = storage::event_start_position(scope);
5115 // No guard: this frame is the context's outermost one and the context
5116 // ends with the event, so there is nothing to pop it before.
5117 context.egress.lock().unwrap().push(EgressFrame {
5118 storage: scope.to_string(),
5119 before: writes_before.unwrap_or(0),
5120 // A facet event stores here and gates on the cell that owns the root
5121 // database. Read once, with the position, so no later effect can take
5122 // one without the other.
5123 root: storage::embedded_root_gate(scope),
5124 });
5125 if capture_frames {
5126 ws_capture_begin();
5127 }
5128 let event_started = Instant::now();
5129 let started = (|| {
5130 begin_event_context(tc)?;
5131 let ret = call(tc)?;
5132 match ret.try_cast::<v8::Promise>() {
5133 Ok(promise) => Ok(promise),
5134 Err(_) => resolved_promise(tc, ret),
5135 }
5136 })();
5137 match started {
5138 Ok(promise) => {
5139 tc.perform_microtask_checkpoint();
5140 if capture_frames {
5141 ws_capture_set_promise(&context, v8::Global::new(tc, promise));
5142 }
5143 let entry = InFlight {
5144 runtime_state: runtime_state.clone(),
5145 promise: v8::Global::new(tc, promise),
5146 context,
5147 scope: Some(scope.to_string()),
5148 writes_before,
5149 request_id,
5150 // A cell's dispatcher registers the incoming request itself,
5151 // so there is nothing for the shell to finish; `cancel`
5152 // aborts by the job's own id.
5153 active_request_id: None,
5154 reply: Some(answer),
5155 gated_reply: None,
5156 background: None,
5157 completed_cell_event: false,
5158 ops: std::collections::HashSet::new(),
5159 io_context_ops: std::collections::HashSet::new(),
5160 unrefed_ops: std::collections::HashSet::new(),
5161 alarm: None,
5162 started: event_started,
5163 trace: None,
5164 failure: None,
5165 tail_report: None,
5166 };
5167 restore_io_context(tc, previous_io_context);
5168 drop(guard);
5169 Begun::Running(Box::new(entry))
5170 }
5171 Err(error) => {
5172 // A V8 termination has a concrete stored cause. The dispatcher
5173 // wrapper can only report that its call returned no value, so do
5174 // not replace process.exit or actor-abort with that generic seam.
5175 let cpu_error = context.finish_cpu_turn().err().map(anyhow::Error::msg);
5176 let error = take_execution_termination(tc)
5177 .or(cpu_error)
5178 .unwrap_or(error);
5179 // The handler ran synchronously before it threw, and a
5180 // synchronous storage call both commits and reads, so the error
5181 // carries the positions it reached like a rejection does.
5182 let error = match gate_positions(scope, writes_before) {
5183 Ok(positions) => fail_in_turn_error(error, positions),
5184 Err(sample) => sample,
5185 };
5186 let background = end_event_context(tc)
5187 .ok()
5188 .flatten()
5189 .map(|promise| v8::Global::new(tc, promise));
5190 let failure = crate::telemetry::cap_error(format!("{error:#}"));
5191 if matches!(&answer, Answer::WsMessage(_)) {
5192 ws_capture_discard(&context);
5193 }
5194 let gated_reply = answer.fail_with_arm_gates(error, context.take_arm_gates());
5195 let begun = if gated_reply.is_none() && background.is_none() {
5196 Begun::Nothing
5197 } else {
5198 let undefined = v8::undefined(tc).into();
5199 let promise = resolved_promise(tc, undefined)
5200 .expect("a finishing cell event can create a resolved promise");
5201 Begun::Running(Box::new(InFlight {
5202 runtime_state,
5203 promise: v8::Global::new(tc, promise),
5204 context,
5205 scope: Some(scope.to_string()),
5206 writes_before,
5207 request_id,
5208 active_request_id: None,
5209 reply: None,
5210 gated_reply,
5211 background,
5212 completed_cell_event: false,
5213 ops: std::collections::HashSet::new(),
5214 io_context_ops: std::collections::HashSet::new(),
5215 unrefed_ops: std::collections::HashSet::new(),
5216 alarm: None,
5217 started: event_started,
5218 trace: None,
5219 failure: Some(failure),
5220 tail_report: None,
5221 }))
5222 };
5223 restore_io_context(tc, previous_io_context);
5224 drop(guard);
5225 begun
5226 }
5227 }
5228}
5229
5230/// Start a cell event's first turn.
5231///
5232/// The counterpart of `begin` for the events a cell receives. Where the
5233/// blocking loop ran each of these to completion inside one call — and
5234/// serviced other cells' events inside *that* — each is now an entry a tokio
5235/// task drives, so two events of one cell interleave by suspending rather
5236/// than by nesting.
5237fn begin_cell(tc: &mut v8::PinScope, job: CellJob, event_time: i64) -> Begun {
5238 match job {
5239 CellJob::Fetch {
5240 request_id,
5241 scope,
5242 name,
5243 url,
5244 method,
5245 body,
5246 headers,
5247 reply,
5248 order: _,
5249 } => {
5250 if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) {
5251 let _ = reply.send(Err(error));
5252 return Begun::Nothing;
5253 }
5254 let body_stream_id = body.stream_id();
5255 start_cell_event(
5256 tc,
5257 &scope,
5258 Answer::Fetch(reply),
5259 request_id,
5260 body_stream_id,
5261 false,
5262 |tc| {
5263 let f = internal_function(tc, "__dispatchTo")?;
5264 // A held body crosses as its bytes; a streamed body crosses as
5265 // its host stream id, so the handler reads it in parts instead
5266 // of the routing seam collecting it first.
5267 let (body_value, stream_id) = match body {
5268 RequestBody::Bytes(bytes) => {
5269 (bytes_value(tc, bytes.into()), v8::null(tc).into())
5270 }
5271 RequestBody::Stream(id) => (
5272 v8::undefined(tc).into(),
5273 v8::Number::new(tc, id as f64).into(),
5274 ),
5275 };
5276 let arguments = [
5277 v8::String::new(tc, &scope).unwrap().into(),
5278 v8::String::new(tc, &url).unwrap().into(),
5279 v8::String::new(tc, &method).unwrap().into(),
5280 body_value,
5281 v8::String::new(tc, &serde_json::to_string(&headers)?)
5282 .unwrap()
5283 .into(),
5284 match request_id {
5285 Some(id) => v8::String::new(tc, &request_id_string(id)).unwrap().into(),
5286 None => v8::null(tc).into(),
5287 },
5288 stream_id,
5289 ];
5290 let recv = v8::undefined(tc).into();
5291 f.call(tc, recv, &arguments)
5292 .ok_or_else(|| anyhow!("dispatchTo threw"))
5293 },
5294 )
5295 }
5296 CellJob::Rpc {
5297 request_id,
5298 scope,
5299 name,
5300 method,
5301 args,
5302 reply,
5303 } => {
5304 if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) {
5305 let _ = reply.send(Err(error));
5306 return Begun::Nothing;
5307 }
5308 start_cell_event(
5309 tc,
5310 &scope,
5311 Answer::CellRpc(reply),
5312 request_id,
5313 None,
5314 false,
5315 |tc| {
5316 let f = internal_function(tc, "__dispatchRpc")?;
5317 let arguments = [
5318 v8::String::new(tc, &scope).unwrap().into(),
5319 v8::String::new(tc, &method).unwrap().into(),
5320 rpc_data_value(tc, args),
5321 ];
5322 let recv = v8::undefined(tc).into();
5323 f.call(tc, recv, &arguments)
5324 .ok_or_else(|| anyhow!("dispatchRpc threw"))
5325 },
5326 )
5327 }
5328 CellJob::WsOpen {
5329 scope,
5330 ws_id,
5331 protocol,
5332 reply,
5333 } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5334 let f = internal_function(tc, "__wsOpen")?;
5335 let arguments = [
5336 v8::String::new(tc, &scope).unwrap().into(),
5337 v8::Number::new(tc, ws_id as f64).into(),
5338 v8::String::new(tc, &protocol).unwrap().into(),
5339 ];
5340 let recv = v8::undefined(tc).into();
5341 f.call(tc, recv, &arguments)
5342 .ok_or_else(|| anyhow!("wsOpen threw"))
5343 }),
5344 CellJob::WsMessage {
5345 scope,
5346 ws_id,
5347 data,
5348 reply,
5349 } => start_cell_event(
5350 tc,
5351 &scope,
5352 Answer::WsMessage(reply),
5353 None,
5354 None,
5355 true,
5356 |tc| {
5357 let (name, data) = match data {
5358 WsIn::Text(text) => ("__wsMessage", v8::String::new(tc, &text).unwrap().into()),
5359 WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)),
5360 };
5361 let f = internal_function(tc, name)?;
5362 let arguments = [
5363 v8::String::new(tc, &scope).unwrap().into(),
5364 v8::Number::new(tc, ws_id as f64).into(),
5365 data,
5366 ];
5367 let recv = v8::undefined(tc).into();
5368 f.call(tc, recv, &arguments)
5369 .ok_or_else(|| anyhow!("WebSocket message dispatch threw"))
5370 },
5371 ),
5372 CellJob::WsClosed {
5373 scope,
5374 ws_id,
5375 code,
5376 reason,
5377 was_clean,
5378 reply,
5379 } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5380 let f = internal_function(tc, "__wsClosed")?;
5381 let arguments = [
5382 v8::String::new(tc, &scope).unwrap().into(),
5383 v8::Number::new(tc, ws_id as f64).into(),
5384 v8::Number::new(tc, f64::from(code)).into(),
5385 v8::String::new(tc, &reason).unwrap().into(),
5386 v8::Boolean::new(tc, was_clean).into(),
5387 ];
5388 let recv = v8::undefined(tc).into();
5389 f.call(tc, recv, &arguments)
5390 .ok_or_else(|| anyhow!("wsClosed threw"))
5391 }),
5392 CellJob::Alarm {
5393 request_id,
5394 scope,
5395 scheduled_ms,
5396 claim,
5397 reply,
5398 } => begin_alarm(
5399 tc,
5400 &scope,
5401 scheduled_ms,
5402 claim,
5403 request_id,
5404 reply,
5405 event_time,
5406 ),
5407 #[cfg(celld_internal_tests)]
5408 CellJob::SyncErrorForTest {
5409 scope,
5410 gate,
5411 socket_id,
5412 terminate,
5413 reply,
5414 } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5415 register_arm_gate_with_current_event(gate, installed_context());
5416 if let Some(socket_id) = socket_id {
5417 current_context().sockets.lock().unwrap().push(socket_id);
5418 }
5419 if terminate {
5420 let state = actor_runtime_state(tc);
5421 *state.termination.lock().expect("termination lock poisoned") =
5422 Some(ExecutionTermination {
5423 error: "synchronous V8 termination sentinel".to_string(),
5424 actor_scope: None,
5425 context_id: None,
5426 });
5427 tc.terminate_execution();
5428 Err(anyhow!("generic synchronous dispatch failure"))
5429 } else {
5430 Err(anyhow!("synchronous cell dispatch sentinel"))
5431 }
5432 }),
5433 }
5434}
5435
5436/// Start an alarm, claiming the due entry so nothing else fires it.
5437///
5438/// The claim is recorded on the entry rather than closed here, because the
5439/// handler has not run yet: the outcome is known only when the event ends,
5440/// which is now many turns away.
5441fn begin_alarm(
5442 tc: &mut v8::PinScope,
5443 scope: &str,
5444 scheduled_ms: i64,
5445 claim: AlarmDispatch,
5446 request_id: Option<RequestId>,
5447 reply: tokio::sync::oneshot::Sender<Result<(celld_logic::wake::AlarmSnapshot, Option<u64>)>>,
5448 event_time: i64,
5449) -> Begun {
5450 if event_time < scheduled_ms {
5451 let _ = reply.send(Err(anyhow!("alarm dispatched before its deadline")));
5452 return Begun::Nothing;
5453 }
5454 #[cfg(celld_internal_tests)]
5455 if let AlarmDispatch::Claimed(retry) = claim {
5456 let Some(scheduled_at) = storage::active_alarm_scheduled_time(scope) else {
5457 let _ = reply.send(Err(anyhow!("alarm dispatched without a claim")));
5458 return Begun::Nothing;
5459 };
5460 return fire_alarm_handler(tc, scope, scheduled_at, retry, None, request_id, reply);
5461 }
5462 let due_by = match claim {
5463 #[cfg(celld_internal_tests)]
5464 AlarmDispatch::Armed => i64::MAX,
5465 AlarmDispatch::Due => event_time,
5466 #[cfg(celld_internal_tests)]
5467 AlarmDispatch::Claimed(_) => unreachable!("claimed alarms return above"),
5468 };
5469 let Some((scheduled_at, retry)) = storage::due_alarm_entry(scope, due_by) else {
5470 // Nothing is due: another dispatch already ran it, or the handler
5471 // that armed it cleared it. Answer what stands now, with no delta —
5472 // no handler ran, so there is nothing written to prove.
5473 let _ = reply.send(Ok((observe_alarm(scope, storage::get_alarm(scope)), None)));
5474 return Begun::Nothing;
5475 };
5476 storage::begin_alarm_handler(scope, scheduled_at);
5477 fire_alarm_handler(
5478 tc,
5479 scope,
5480 scheduled_at,
5481 retry,
5482 Some(AlarmClaim { now_ms: event_time }),
5483 request_id,
5484 reply,
5485 )
5486}
5487
5488/// Call `alarm()`, carrying whatever claim its outcome must close.
5489fn fire_alarm_handler(
5490 tc: &mut v8::PinScope,
5491 scope: &str,
5492 scheduled_at: i64,
5493 retry: i64,
5494 claim: Option<AlarmClaim>,
5495 request_id: Option<RequestId>,
5496 reply: tokio::sync::oneshot::Sender<Result<(celld_logic::wake::AlarmSnapshot, Option<u64>)>>,
5497) -> Begun {
5498 let begun = start_cell_event(
5499 tc,
5500 scope,
5501 Answer::Alarm(reply),
5502 request_id,
5503 None,
5504 false,
5505 |tc| {
5506 let f = internal_function(tc, "__fireAlarm")?;
5507 let arguments = [
5508 v8::String::new(tc, scope).unwrap().into(),
5509 v8::Number::new(tc, scheduled_at as f64).into(),
5510 v8::Number::new(tc, retry as f64).into(),
5511 ];
5512 let recv = v8::undefined(tc).into();
5513 f.call(tc, recv, &arguments)
5514 .ok_or_else(|| anyhow!("alarm threw"))
5515 },
5516 );
5517 match begun {
5518 Begun::Running(mut entry) => {
5519 entry.alarm = claim;
5520 Begun::Running(entry)
5521 }
5522 // The dispatcher never ran, so nothing can have changed the alarm.
5523 // Give the claim back as a failure that does not count against the
5524 // retry limit: the handler is not what failed.
5525 begun => {
5526 if let Some(claim) = claim {
5527 storage::finish_alarm_handler_with_retry_policy(scope, false, claim.now_ms, false);
5528 }
5529 begun
5530 }
5531 }
5532}
5533
5534/// Resolve one completed op and run the microtasks that follow, with the
5535/// owning request's context current.
5536///
5537/// The half of a turn that resumes a suspended request. It knows nothing
5538/// about any other request: the caller has already established that this op
5539/// is `entry`'s.
5540fn deliver(
5541 tc: &mut v8::PinScope,
5542 entry: &mut InFlight,
5543 op: u64,
5544 res: Result<asyncrt::OpOut, String>,
5545) {
5546 entry.ops.remove(&op);
5547 entry.io_context_ops.remove(&op);
5548 entry.unrefed_ops.remove(&op);
5549 let guard = CurrentGuard::enter(entry.context.clone());
5550 resolve_res(tc, op, res);
5551 tc.perform_microtask_checkpoint();
5552 drop(guard);
5553}
5554
5555/// End a request whose client has hung up, so its handler stops running.
5556fn cancelled(tc: &mut v8::PinScope, entry: &mut InFlight) {
5557 if entry.reply.is_none() || !take_request_cancellation(entry.request_id) {
5558 return;
5559 }
5560 let shutdown = take_shutdown_cancellation(entry.request_id);
5561 cancel(tc, entry, shutdown);
5562}
5563
5564/// End a request whose cancellation has already been taken.
5565///
5566/// Split from [`cancelled`] because a suspended request observes the
5567/// cancellation *outside* the isolate — the flag is host state and costs no
5568/// V8 — and only then enters to act on it.
5569fn cancel(tc: &mut v8::PinScope, entry: &mut InFlight, shutdown: bool) {
5570 let guard = CurrentGuard::enter(entry.context.clone());
5571 // The id that names this request to the JS side. A stateless handler is
5572 // registered by the shell, and only once it suspends, so the shell holds
5573 // the id; a cell's dispatcher registers the request itself, so the job's
5574 // own id is the one to abort. Aborting the wrong one — or neither —
5575 // leaves the target's `request.signal` unfired while the caller is told
5576 // the client has gone.
5577 if let Some(id) = entry.active_request_id.or(entry.request_id) {
5578 let _ = abort_incoming_request(tc, id);
5579 }
5580 // Finishing is the shell's to undo only where the shell registered.
5581 if let Some(id) = entry.active_request_id {
5582 finish_incoming_request(tc, id);
5583 }
5584 let background = end_event_context(tc).ok().flatten();
5585 entry.background = background.map(|promise| v8::Global::new(tc, promise));
5586 if shutdown {
5587 finish_retired_input_gate_context(tc, &entry.context);
5588 }
5589 drop(guard);
5590 entry.fail_cancelled(anyhow!("The client has disconnected"));
5591 if shutdown {
5592 // A lifecycle cancellation can be consumed either between turns or
5593 // during an operation turn. Keep the background cleanup here so both
5594 // paths retire the same work.
5595 entry.retire_background_for_shutdown();
5596 }
5597 // A cancelled handler with no waitUntil work has nothing left to drive.
5598 // Drop its host ops now, so their guards cancel routed work. Explicit
5599 // waitUntil work keeps its ops and continues after the client disconnects.
5600 //
5601 // So does a handler that holds or awaits the cell's input gate, or whose
5602 // cross-entry block can still use an operation started by this event.
5603 // Not at shutdown: nothing will run the block to its end, so its gate is
5604 // given up instead.
5605 if shutdown || !entry.keeps_native_ops_after_disconnect() {
5606 entry.abandon();
5607 }
5608}
5609
5610/// Answer a request whose handler promise has settled, and retire its
5611/// `waitUntil` work once that settles too.
5612fn settle(tc: &mut v8::PinScope, entry: &mut InFlight) {
5613 if entry.reply.is_some() {
5614 let promise = v8::Local::new(tc, &entry.promise);
5615 match promise.state() {
5616 v8::PromiseState::Pending => {}
5617 v8::PromiseState::Fulfilled => {
5618 let guard = CurrentGuard::enter(entry.context.clone());
5619 let value = promise.result(tc);
5620 entry.answer_settled(tc, value);
5621 if let Some(request_id) = entry.active_request_id {
5622 finish_incoming_request(tc, request_id);
5623 }
5624 drop(guard);
5625 }
5626 v8::PromiseState::Rejected => {
5627 let guard = CurrentGuard::enter(entry.context.clone());
5628 let reason = reject_reason(tc, promise);
5629 // The handler is what failed, so an alarm's failure here
5630 // counts against its retry limit — unlike a budget overrun
5631 // or a disconnect, which `fail` records as not counting.
5632 entry.settle_alarm(false, true);
5633 let _ = end_event_context(tc);
5634 entry.context.seal_wait_until();
5635 if let Some(request_id) = entry.active_request_id {
5636 finish_incoming_request(tc, request_id);
5637 }
5638 drop(guard);
5639 entry.fail_in_turn(anyhow!("rejected: {reason}"));
5640 }
5641 }
5642 }
5643 if let Some(background) = &entry.background {
5644 let promise = v8::Local::new(tc, background);
5645 if !matches!(promise.state(), v8::PromiseState::Pending) {
5646 let late = entry.context.take_late_wait_until();
5647 entry.background =
5648 wait_until_aggregate(tc, &late).map(|promise| v8::Global::new(tc, promise));
5649 if !late.is_empty() && entry.background.is_none() {
5650 entry.context.seal_wait_until();
5651 }
5652 }
5653 }
5654}
5655
5656fn wait_until_aggregate<'s>(
5657 scope: &mut v8::PinScope<'s, '_>,
5658 promises: &[v8::Global<v8::Promise>],
5659) -> Option<v8::Local<'s, v8::Promise>> {
5660 if promises.is_empty() {
5661 return None;
5662 }
5663 let values = promises
5664 .iter()
5665 .map(|promise| v8::Local::new(scope, promise).into())
5666 .collect::<Vec<v8::Local<v8::Value>>>();
5667 let array = v8::Array::new_with_elements(scope, &values);
5668 all_settled(scope, array.into())?.try_cast().ok()
5669}
5670
5671enum FetchTarget<'s> {
5672 Default(v8::Local<'s, v8::Function>),
5673 Entrypoint(crate::WorkerFetchEntrypoint),
5674}
5675
5676/// Begin a stateless request: build it, call the Worker's `fetch`, and hand
5677/// back the promise it returned.
5678///
5679/// The half of a request that runs *before* it can suspend. Split out from
5680/// driving it to completion so a caller can start several and drive them
5681/// together; the single-request path starts one and drives it immediately,
5682/// which is what it always did.
5683///
5684/// The caller owns the `IoContext` and must have it current: `__beginEvent`
5685/// runs here, and the frame it pushes belongs to this request.
5686fn start_fetch<'s>(
5687 tc: &mut v8::PinScope<'s, '_>,
5688 target: FetchTarget<'s>,
5689 url: &str,
5690 method: &str,
5691 body: RequestBody,
5692 headers: &[(String, String)],
5693 request_id: Option<RequestId>,
5694) -> Result<Started<'s>> {
5695 let req = match request_id {
5696 Some(_) => make_incoming_request(tc, url, method, body, headers),
5697 None => make_request(tc, url, method, body, headers),
5698 }?;
5699 let recv = v8::undefined(tc).into();
5700 let ret = match target {
5701 FetchTarget::Entrypoint(entrypoint) => {
5702 let dispatch = internal_function(tc, "__dispatchEntrypointFetch")?;
5703 let name = v8::String::new(tc, &entrypoint.name).unwrap();
5704 let props = bytes_value(tc, entrypoint.props);
5705 // Settlement and synchronous-throw cleanup both close this host
5706 // frame. The dispatcher supplies its own handler context, but
5707 // omitting the outer frame would leave those paths unbalanced.
5708 begin_event_context(tc)?;
5709 dispatch.call(tc, recv, &[name.into(), req, props])
5710 }
5711 FetchTarget::Default(fetch) => {
5712 let env = harness_env(tc)?;
5713 let execution_ctx = begin_event_context(tc)?;
5714 fetch.call(tc, recv, &[req, env, execution_ctx])
5715 }
5716 };
5717 let Some(ret) = ret else {
5718 // The handler threw synchronously. Termination carries its own error;
5719 // otherwise the pending exception is on the caller's TryCatch, which
5720 // is the only scope that can read it, so it formats the message.
5721 let error = take_execution_termination(tc);
5722 let _ = end_event_context(tc);
5723 return match error {
5724 Some(error) => Err(error),
5725 None => Ok(Started::Threw),
5726 };
5727 };
5728 // A handler that suspends must be reachable by an abort: register it as an
5729 // incoming request so a client disconnect can cancel it. One that already
5730 // settled cannot be cancelled, so its registration is cleared instead.
5731 let active_request_id = match request_id {
5732 Some(request_id)
5733 if ret
5734 .try_cast::<v8::Promise>()
5735 .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) =>
5736 {
5737 if let Err(error) = register_incoming_request(tc, request_id, req) {
5738 clear_request_cancellation(request_id);
5739 let _ = end_event_context(tc);
5740 return Err(error);
5741 }
5742 Some(request_id)
5743 }
5744 Some(request_id) => {
5745 clear_request_cancellation(request_id);
5746 None
5747 }
5748 None => None,
5749 };
5750 Ok(Started::Running(ret, active_request_id))
5751}
5752
5753/// What `start_fetch` produced: a running handler, or a synchronous throw
5754/// whose exception only the caller's `TryCatch` can read.
5755enum Started<'s> {
5756 Running(v8::Local<'s, v8::Value>, Option<RequestId>),
5757 Threw,
5758}
5759
5760fn settle_isolate_heap(isolate: &mut v8::Isolate) {
5761 #[cfg(all(test, celld_internal_tests))]
5762 let _observation = HeapSettlementObservationForTest::begin();
5763 isolate.low_memory_notification();
5764}
5765
5766impl Worker {
5767 /// Compile the worker module, wire the DO harness, and extract the entry
5768 /// `fetch`. `do_classes` come from the manifest; `bindings` maps a binding
5769 /// name to a DO class name (from wrangler metadata).
5770 ///
5771 /// The runtime builds a `WorkerConfig` directly. This cfg-gated helper
5772 /// constructs the same value from individual options.
5773 #[cfg(celld_internal_tests)]
5774 pub fn load(options: WorkerConfigOptions) -> Result<Worker> {
5775 Self::load_config(Arc::new(WorkerConfig::new(options)))
5776 }
5777
5778 pub fn load_config(config: Arc<WorkerConfig>) -> Result<Worker> {
5779 let src = config.src.as_str();
5780 let script_name = config.script_name.as_str();
5781 let do_classes = config.do_classes.as_slice();
5782 let node = config.node.as_str();
5783 let compat = config.compat;
5784 let params = v8::CreateParams::default().heap_limits(0, v8_heap_limit_bytes());
5785 let mut isolate = v8::Isolate::new(params);
5786 // Dynamic `import()` of builtin specifiers; per-import()-call only.
5787 isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically);
5788 let original_heap_limit = isolate.get_heap_statistics().heap_size_limit();
5789 let heap_limit_state = Arc::new(HeapLimitState {
5790 excessively_exceeded: AtomicBool::new(false),
5791 limit: original_heap_limit,
5792 last_gc_nudge: Mutex::new(None),
5793 #[cfg(celld_internal_tests)]
5794 forced_admission_refusal: AtomicBool::new(false),
5795 });
5796 let runtime_state = Arc::new(ActorRuntimeState {
5797 promises: std::sync::Mutex::new(PromiseMap::new()),
5798 egress: config.egress.clone(),
5799 resource_limits: config.resource_limits,
5800 tail_reporting: config.tail_reporting,
5801 script_name: script_name.to_string(),
5802 ..Default::default()
5803 });
5804 let loader_owner = LoaderOwner::fresh(script_name, config.generation);
5805 let heap_limit_state_ptr =
5806 Arc::as_ptr(&heap_limit_state) as *mut HeapLimitState as *mut std::ffi::c_void;
5807 isolate.set_slot(heap_limit_state);
5808 isolate.set_slot(runtime_state.clone());
5809 isolate.set_slot(Arc::new(ModuleRegistry::default()));
5810 isolate.set_slot(loader_owner.clone());
5811 isolate.set_slot(crate::generation::GenerationTag(config.generation));
5812 // Retains the config so `/bundle` can project it later. Nothing is
5813 // walked or copied here: a worker that never reads its own bundle pays
5814 // only this `Arc` clone.
5815 isolate.set_slot(Arc::new(BundleFs {
5816 config: config.clone(),
5817 tree: OnceLock::new(),
5818 }));
5819 isolate.add_near_heap_limit_callback(near_heap_limit, heap_limit_state_ptr);
5820 let (context, fetch) = {
5821 v8::scope!(let hs, &mut isolate);
5822 let context = v8::Context::new(hs, Default::default());
5823 let cs = &mut v8::ContextScope::new(hs, context);
5824 let tc = std::pin::pin!(v8::TryCatch::new(cs));
5825 let scope = &mut tc.init();
5826
5827 let arguments = install_ops(scope);
5828 install_prelude(scope, &arguments)?; // Web Platform APIs
5829 install_harness(scope, &arguments)?; // DO object model + minimal Response
5830 install_lazy_globals(scope)?;
5831 // A global, so it must exist before the module evaluates: bundles
5832 // read Cloudflare.compatibilityFlags at module scope.
5833 inject_compatibility_flags(scope, compat)?;
5834 inject_storage_compatibility(scope, compat)?;
5835
5836 let module = match compile_module(scope, &config.main_module_name, src) {
5837 Some(m) => m,
5838 None => return Err(anyhow!("compile: {}", exc!(scope))),
5839 };
5840 register_stubs(scope, &config); // cloudflare:*/node:* + text modules
5841 register_wasm_modules(scope, &config.modules);
5842 register_loader_modules(scope, &config, module);
5843 module
5844 .instantiate_module(scope, resolve_external)
5845 .ok_or_else(|| anyhow!("instantiate: {}", exc!(scope)))?;
5846 let ev = match module.evaluate(scope) {
5847 Some(value) => value,
5848 None => {
5849 if let Some(error) = take_execution_termination(scope) {
5850 return Err(error);
5851 }
5852 return Err(anyhow!("evaluate: {}", exc!(scope)));
5853 }
5854 };
5855 if let Some(error) = take_execution_termination(scope) {
5856 return Err(error);
5857 }
5858 if let Ok(p) = ev.try_cast::<v8::Promise>() {
5859 if p.state() == v8::PromiseState::Rejected {
5860 let r = p.result(scope);
5861 let stk = r
5862 .to_object(scope)
5863 .and_then(|o| {
5864 let k = v8::String::new(scope, "stack")?;
5865 o.get(scope, k.into())
5866 })
5867 .map(|s| s.to_rust_string_lossy(scope))
5868 .unwrap_or_default();
5869 return Err(anyhow!(
5870 "top-level rejected: {}\n{}",
5871 r.to_rust_string_lossy(scope),
5872 stk
5873 ));
5874 }
5875 }
5876
5877 let ns = module
5878 .get_module_namespace()
5879 .to_object(scope)
5880 .ok_or_else(|| anyhow!("ns"))?;
5881 // workerd reads every export of the main module as a handler or
5882 // a class, so a primitive export fails the Worker's start.
5883 let names = ns
5884 .get_own_property_names(scope, Default::default())
5885 .ok_or_else(|| anyhow!("ns names"))?;
5886 for index in 0..names.length() {
5887 let name = names.get_index(scope, index).unwrap();
5888 let value = ns.get(scope, name).unwrap();
5889 if !value.is_object() {
5890 return Err(anyhow!(
5891 "Uncaught TypeError: Incorrect type for map entry '{}': the \
5892 provided value is not of type 'function or ExportedHandler'.",
5893 name.to_rust_string_lossy(scope)
5894 ));
5895 }
5896 }
5897
5898 // register each exported DO class into the harness registry
5899 for cn in do_classes {
5900 // The D1 class is the runtime's own and is never a worker
5901 // export. It is in `do_classes` so that it gets a namespace
5902 // key; reading it off the module namespace would find
5903 // `undefined` and overwrite the harness's registration.
5904 if crate::deploy::is_reserved_class(cn) {
5905 continue;
5906 }
5907 let key = v8::String::new(scope, cn).unwrap();
5908 let cls = ns
5909 .get(scope, key.into())
5910 .ok_or_else(|| anyhow!("DO class {cn} not exported"))?;
5911 register_class(scope, cn, cls)?;
5912 }
5913 inject_namespace_keys(scope, script_name, do_classes)?;
5914 inject_crons(scope, &config.crons)?;
5915 inject_workflows(scope, script_name, &config.workflow_bindings)?;
5916 inject_containers(scope, &config.containers)?;
5917 inject_kv_limits(scope)?;
5918 inject_queue_config(scope, &config)?;
5919 populate_cf_exports(scope, ns, do_classes)?;
5920 register_entrypoints(scope, ns)?;
5921 validate_workflow_classes(scope, ns, &config.workflow_bindings)?;
5922 // build env from bindings and stash it in the harness
5923 build_env(scope, &config)?;
5924 // tell the harness which cells are local (route the rest cross-node)
5925 inject_routing(scope, node)?;
5926
5927 // entry fetch. A loaded Worker often exists for its Durable
5928 // Object class alone, and workerd loads such a module without a
5929 // default export, so one reads as an empty object here. A
5930 // deployment's own script keeps the refusal: a bundle that lost
5931 // its handler must fail adoption, so the serving generation stays
5932 // up instead of answering 500 to every request.
5933 let loaded = config.origin == WorkerOrigin::Dynamic;
5934 let dk = v8::String::new(scope, "default").unwrap();
5935 let default_value = ns
5936 .get(scope, dk.into())
5937 .ok_or_else(|| anyhow!("no default export"))?;
5938 let default = if default_value.is_object() {
5939 default_value.to_object(scope).expect("an object")
5940 } else if loaded && default_value.is_undefined() {
5941 v8::Object::new(scope)
5942 } else {
5943 return Err(anyhow!("default not object"));
5944 };
5945 let fk = v8::String::new(scope, "fetch").unwrap();
5946 let fetch_value = default
5947 .get(scope, fk.into())
5948 .ok_or_else(|| anyhow!("no fetch"))?;
5949 let default_is_entrypoint =
5950 default.is_function() && cell_registry_has(scope, "entrypoints", "default")?;
5951 let class_fetch = default_is_entrypoint
5952 && default
5953 .get(scope, v8::String::new(scope, "prototype").unwrap().into())
5954 .and_then(|prototype| prototype.to_object(scope))
5955 .and_then(|prototype| prototype.get(scope, fk.into()))
5956 .is_some_and(|handler| handler.is_function());
5957 let qk = v8::String::new(scope, "queue").unwrap();
5958 let own_queue = default
5959 .get(scope, qk.into())
5960 .is_some_and(|handler| handler.is_function());
5961 let class_queue = default_is_entrypoint
5962 && default
5963 .get(scope, v8::String::new(scope, "prototype").unwrap().into())
5964 .and_then(|prototype| prototype.to_object(scope))
5965 .and_then(|prototype| prototype.get(scope, qk.into()))
5966 .is_some_and(|handler| handler.is_function());
5967 let has_queue_handler = own_queue || class_queue;
5968 anyhow::ensure!(
5969 !config.declares_queue_consumer || has_queue_handler,
5970 "queue consumer has no queue handler"
5971 );
5972 let f: v8::Local<v8::Function> = if fetch_value.is_function() {
5973 fetch_value.try_into().expect("function casts to Function")
5974 } else if default_is_entrypoint && class_fetch {
5975 // A class-based default entrypoint (extends WorkerEntrypoint)
5976 // keeps fetch on the prototype, so route through the
5977 // harness's invocation instance like a named entrypoint. Only a
5978 // registered entrypoint dispatches that way — any other
5979 // callable would load fine and then 500 on every request.
5980 compile_fn(
5981 scope,
5982 "(req) => __celld.__dispatchEntrypointFetch('default', req)",
5983 )?
5984 } else if default.is_function() && cell_registry_has(scope, "doExports", "default")? {
5985 return Err(anyhow!(
5986 "the default export is a Durable Object class; export a fetch \
5987 handler or a WorkerEntrypoint class as the default"
5988 ));
5989 } else if config.declares_queue_consumer {
5990 // A push-consumer Worker needs no HTTP handler. Keep the
5991 // stateless pool's fetch slot total, but fail closed if this
5992 // deployment becomes the fleet's HTTP entry point. Test the
5993 // prototype above before the entrypoint fallback below: a
5994 // queue-only class is still a registered entrypoint, but
5995 // routing fetch through it throws instead of returning 404.
5996 compile_fn(scope, "() => new Response('Not found', { status: 404 })")?
5997 } else if default_is_entrypoint {
5998 // Preserve an RPC-only default entrypoint. Its HTTP path
5999 // reports the harness's specific missing-fetch error, while
6000 // its named methods remain callable through RPC.
6001 compile_fn(
6002 scope,
6003 "(req) => __celld.__dispatchEntrypointFetch('default', req)",
6004 )?
6005 } else if loaded {
6006 compile_fn(scope, NO_FETCH_HANDLER)?
6007 } else {
6008 return Err(anyhow!("fetch not fn"));
6009 };
6010
6011 // Lets a self-targeted service binding invoke the handler in
6012 // this isolate instead of crossing to a pool thread.
6013 {
6014 if let Ok(cell) = cell_state(scope) {
6015 let key = v8::String::new(scope, "selfFetch").unwrap();
6016 cell.set(scope, key.into(), f.into());
6017 // Optional scheduled handler, reached by a self-targeted
6018 // service binding's scheduled().
6019 let sk = v8::String::new(scope, "scheduled").unwrap();
6020 let key_ = v8::String::new(scope, "selfScheduled").unwrap();
6021 let own = default
6022 .get(scope, sk.into())
6023 .filter(|handler| handler.is_function());
6024 if let Some(handler) = own {
6025 cell.set(scope, key_.into(), handler);
6026 } else if default_is_entrypoint {
6027 // A class-based default entrypoint keeps scheduled on
6028 // the prototype; dispatch through an invocation instance
6029 // like fetch above.
6030 let pk = v8::String::new(scope, "prototype").unwrap();
6031 let proto_scheduled = default
6032 .get(scope, pk.into())
6033 .and_then(|proto| proto.to_object(scope))
6034 .and_then(|proto| proto.get(scope, sk.into()));
6035 if proto_scheduled.is_some_and(|handler| handler.is_function()) {
6036 let shim = compile_fn(
6037 scope,
6038 "(ctrl) => __celld.__dispatchEntrypointScheduled('default', ctrl)",
6039 )?;
6040 cell.set(scope, key_.into(), shim.into());
6041 }
6042 }
6043 }
6044 }
6045 (v8::Global::new(scope, context), v8::Global::new(scope, f))
6046 };
6047 // Module evaluation and harness installation allocate temporary V8
6048 // objects. No request can reuse them after these scopes close, and a
6049 // new cell isolate can otherwise retain their pages indefinitely.
6050 // Observe only post-setup collection, so bootstrap GC cannot make
6051 // a missing settlement notification pass the regression.
6052 #[cfg(all(test, celld_internal_tests))]
6053 install_heap_collection_observer_for_test(&mut isolate);
6054 settle_isolate_heap(&mut isolate);
6055 Ok(Worker {
6056 inner: Some(WorkerIsolate {
6057 // Every setup scope above has closed, so nothing is entered
6058 // on top of this isolate and it can be handed over.
6059 // SAFETY: `into_shared` requires every piece of embedder
6060 // state hanging off this isolate to be `Send`, because it
6061 // migrates between threads and is dropped on whichever one
6062 // holds the lock last. This isolate carries exactly:
6063 //
6064 // - four slots, whose types the assertion below pins as
6065 // `Send + Sync`;
6066 // - `near_heap_limit`, a bare fn pointer whose only captured
6067 // state is a raw pointer into the `HeapLimitState` above;
6068 // - `host_import_module_dynamically`, a bare fn pointer that
6069 // captures nothing;
6070 // - a default `CreateParams` allocator, owned by V8.
6071 //
6072 // Nothing else is attached, and the assertion fails the build
6073 // if a slot type ever stops being thread-safe.
6074 //
6075 // 152.1.0 made this fallible. None of the four refusals can
6076 // hold here — this isolate is entered, is not a snapshot
6077 // creator, has no C++ heap, and has taken no weak handles —
6078 // so a refusal is a bug in the setup above, not a condition
6079 // to recover from. It panics with the reason named.
6080 isolate: unsafe { isolate.try_into_shared() }
6081 .unwrap_or_else(|error| panic!("cell isolate cannot be shared: {error}")),
6082 runtime_state,
6083 realm: Realm { context, fetch },
6084 original_heap_limit,
6085 compat,
6086 loader_owner,
6087 cells: storage::Cells::default(),
6088 }),
6089 })
6090 }
6091
6092 /// Restore an idFromName() actor's human-readable identity before its
6093 /// constructor runs. The host calls this on activation and before a named
6094 /// request is dispatched.
6095 /// Take a cell into this isolate or give it back.
6096 ///
6097 /// Taking it opens the cell's SQLite -- which the isolate owns, not the
6098 /// caller -- and restores the persisted id name. Giving it back releases
6099 /// what the isolate holds for the residency and closes the database, so
6100 /// state cannot span two epochs.
6101 ///
6102 /// Dispatch does not depend on this: every cell call goes out through the
6103 /// host whichever isolate hosts the target.
6104 pub fn own_cell(
6105 &mut self,
6106 cell: &str,
6107 storage: Option<CellStorage<'_>>,
6108 ) -> Result<celld_logic::wake::AlarmSnapshot> {
6109 let compat = self.inner.as_ref().expect("live worker isolate").compat;
6110 let (mut locker, _cells) = self.lock();
6111 v8::scope!(let hs, &mut *locker);
6112 let realm = self.realm(hs);
6113 let context = realm.context;
6114 let cs = &mut v8::ContextScope::new(hs, context);
6115 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6116 let alarm = adopt_cell(&mut tc.init(), cell, storage, compat)?;
6117 // The source identity belongs to this installed SQLite turn. Reading
6118 // it from the pool after this guard drops reaches no cell connection.
6119 Ok(observe_alarm(cell, alarm))
6120 }
6121
6122 /// Collect objects left by cell adoption after an isolate becomes full.
6123 /// The pool calls this when completed adoptions reach the resident limit,
6124 /// because collecting after every adoption slows activation.
6125 pub(crate) fn settle_heap(&mut self) {
6126 let (mut locker, _cells) = self.lock();
6127 settle_isolate_heap(&mut locker);
6128 }
6129
6130 fn own_embedded_cell(
6131 &mut self,
6132 cell: &str,
6133 parent: &storage::StorageIdentity,
6134 name: &str,
6135 id: &str,
6136 props_sc: Vec<u8>,
6137 file: (std::path::PathBuf, bool),
6138 ) -> Result<Option<i64>> {
6139 let compat = self.inner.as_ref().expect("live worker isolate").compat;
6140 let (mut locker, _cells) = self.lock();
6141 if storage::activation_epoch(cell).is_some() {
6142 // The facet is already open, but this call carries a newer sample
6143 // of the root cell. Take it: the egress of this call must wait for
6144 // what the root cell had committed when the call left it.
6145 storage::refresh_embedded_root(cell, parent);
6146 return Ok(None);
6147 }
6148 v8::scope!(let hs, &mut *locker);
6149 let realm = self.realm(hs);
6150 let context = realm.context;
6151 let cs = &mut v8::ContextScope::new(hs, context);
6152 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6153 let tc = &mut tc.init();
6154 let (path, restored) = file;
6155 adopt_embedded_cell(
6156 tc,
6157 cell,
6158 parent,
6159 name,
6160 EmbeddedStartup {
6161 id,
6162 props_sc,
6163 path,
6164 restored,
6165 },
6166 compat,
6167 )
6168 }
6169
6170 /// Drain the alarm moves the last turn committed in this isolate.
6171 ///
6172 /// An alarm move is a turn output, exactly like the ops a turn starts:
6173 /// the drive that ran the turn reports it to the host, so a handler
6174 /// that arms an alarm and then awaits it is schedulable immediately,
6175 /// not when the request ends. A separate call rather than part of the
6176 /// turn methods' return because stateless turns cannot move an alarm
6177 /// and never pay for it.
6178 /// Bind the revision under the isolate lock too. A later reporter callback
6179 /// can run after another turn arms the cell; sampling there would combine
6180 /// the old value with the new arm's authority to change its wake entry.
6181 pub fn take_alarm_moves(&mut self) -> Vec<(String, celld_logic::wake::AlarmSnapshot)> {
6182 let Some(inner) = self.inner.as_mut() else {
6183 return Vec::new();
6184 };
6185 let (_locker, _cells) = inner.lock();
6186 storage::take_alarm_moves()
6187 }
6188
6189 pub fn set_id_name(&mut self, scope: &str, name: &str) -> Result<()> {
6190 let (mut locker, _cells) = self.lock();
6191 v8::scope!(let hs, &mut *locker);
6192 let realm = self.realm(hs);
6193 let context = realm.context;
6194 let cs = &mut v8::ContextScope::new(hs, context);
6195 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6196 register_actor_name(&mut tc.init(), scope, Some(name))
6197 }
6198
6199 /// Start a cell event's first turn.
6200 ///
6201 /// The cell counterpart of `turn_begin`: it hands back what is now in
6202 /// flight for `runtime::drive_cell` to pump.
6203 pub fn turn_begin_cell(
6204 &mut self,
6205 job: CellJob,
6206 trace: Option<crate::telemetry::TraceContext>,
6207 ) -> (Option<InFlight>, Vec<Op>) {
6208 let Some(inner) = self.inner.as_mut() else {
6209 return (None, Vec::new());
6210 };
6211 let (mut locker, _cells) = inner.lock();
6212 inner.recover_heap(&mut locker);
6213 v8::scope!(let hs, &mut *locker);
6214 let realm = inner.realm(hs);
6215 let context = realm.context;
6216 let cs = &mut v8::ContextScope::new(hs, context);
6217 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6218 let tc = &mut tc.init();
6219
6220 let event_time = advance_io_time(tc);
6221 let previous = install_trace(tc, trace.as_ref());
6222 let cpu_watchdog = inner.cpu_watchdog(
6223 inner.initial_cpu_budget(),
6224 inner
6225 .runtime_state
6226 .resource_limits
6227 .and_then(|limits| limits.cpu_ms),
6228 );
6229 let begun = begin_cell(tc, job, event_time);
6230 drop(cpu_watchdog);
6231 let out = match begun {
6232 Begun::Running(mut entry) => {
6233 entry.trace = trace;
6234 let previous_io_context = install_io_context(tc, &entry.context);
6235 let ops = finish_turn(tc, &mut entry);
6236 restore_io_context(tc, previous_io_context);
6237 (Some(*entry), ops)
6238 }
6239 Begun::Threw(failure) => {
6240 let BegunFailure {
6241 answer, cpu_error, ..
6242 } = *failure;
6243 answer.fail(
6244 take_execution_termination(tc)
6245 .or_else(|| cpu_error.map(anyhow::Error::msg))
6246 .unwrap_or_else(|| anyhow!("cell event threw: {}", exc!(tc))),
6247 );
6248 (None, Vec::new())
6249 }
6250 Begun::Nothing => (None, Vec::new()),
6251 };
6252 restore_trace(tc, previous);
6253 out
6254 }
6255
6256 /// Enter the isolate solely to see whether another event settled this
6257 /// one's promise.
6258 ///
6259 /// A promise resolved by a different entry has no waker pointing here,
6260 /// so the driving task cannot be told and has to look. That is why this
6261 /// is a poll and not an event, and it is the same reason the blocking
6262 /// loop woke every 10 ms.
6263 pub fn turn_poll(&mut self, entry: &mut InFlight) -> Vec<Op> {
6264 let Some(inner) = self.inner.as_mut() else {
6265 return Vec::new();
6266 };
6267 let (mut locker, _cells) = inner.lock();
6268 v8::scope!(let hs, &mut *locker);
6269 let realm = inner.realm(hs);
6270 let context = realm.context;
6271 let cs = &mut v8::ContextScope::new(hs, context);
6272 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6273 let tc = &mut tc.init();
6274
6275 let previous_io_context = install_io_context(tc, &entry.context);
6276 let previous = install_trace(tc, entry.trace.as_ref());
6277 entry.context.begin_cpu_turn();
6278 let ops = finish_turn(tc, entry);
6279 restore_trace(tc, previous);
6280 restore_io_context(tc, previous_io_context);
6281 ops
6282 }
6283
6284 /// Reject each pending `WorkerEntrypoint` call that has no native work.
6285 /// The rejection runs inside the owning request, so the enclosing handler
6286 /// can catch it and continue exactly as it can in Workerd.
6287 pub(crate) fn turn_cancel_pending_events(&mut self, entry: &mut InFlight) -> Vec<Op> {
6288 let Some(inner) = self.inner.as_mut() else {
6289 return Vec::new();
6290 };
6291 let (mut locker, _cells) = inner.lock();
6292 v8::scope!(let hs, &mut *locker);
6293 let realm = inner.realm(hs);
6294 let context = realm.context;
6295 let cs = &mut v8::ContextScope::new(hs, context);
6296 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6297 let tc = &mut tc.init();
6298
6299 let previous_io_context = install_io_context(tc, &entry.context);
6300 let previous = install_trace(tc, entry.trace.as_ref());
6301 entry.context.begin_cpu_turn();
6302 let cpu_watchdog = inner.cpu_watchdog(
6303 entry.context.remaining_cpu_budget(),
6304 entry.context.cpu_limit_ms(),
6305 );
6306 let ids = entry.context.take_pending_events();
6307 let called = (|| {
6308 let function = internal_function(tc, "__cancelPendingEvents").ok()?;
6309 let values = ids
6310 .iter()
6311 .map(|id| v8::Number::new(tc, *id as f64).into())
6312 .collect::<Vec<v8::Local<v8::Value>>>();
6313 let values = v8::Array::new_with_elements(tc, &values);
6314 let receiver = v8::undefined(tc).into();
6315 function.call(tc, receiver, &[values.into()])
6316 })();
6317 if called.is_none() {
6318 entry.fail_in_turn(anyhow!("pending-event cancellation threw"));
6319 }
6320 drop(cpu_watchdog);
6321 let ops = finish_turn(tc, entry);
6322 restore_trace(tc, previous);
6323 restore_io_context(tc, previous_io_context);
6324 ops
6325 }
6326
6327 /// Enter the isolate solely to record how a claimed alarm ended.
6328 ///
6329 /// Reached only when the event ended without running JS again — a budget
6330 /// overrun, or a handler waiting on nothing — or threw before it could
6331 /// suspend. The bookkeeping is storage the isolate owns, so it cannot be
6332 /// done from the driving task.
6333 ///
6334 /// Answers the position the event's commits reached, sampled after the
6335 /// retry record is written: that record and whatever the handler wrote
6336 /// before it failed are unproven, and the error that already left carried
6337 /// at most the handler's part, so `fire_alarm` gates on this instead.
6338 pub fn turn_finish_alarm(&mut self, entry: &mut InFlight) -> Result<Option<u64>> {
6339 debug_assert!(
6340 self.inner.is_some(),
6341 "the final alarm turn runs on a live worker"
6342 );
6343 let Some(inner) = self.inner.as_mut() else {
6344 return Ok(None);
6345 };
6346 let (_locker, _cells) = inner.lock();
6347 entry.settle_alarm(false, false);
6348 entry.write_delta()
6349 }
6350}
6351
6352// ---- native ops exposed to JS ----
6353
6354/// One host op per entry. The macro names the table and the installer
6355/// together, so the parameter list every internal script is compiled with
6356/// and the functions it is called with come from one source and cannot
6357/// drift apart.
6358///
6359/// The ops are runtime internals and never globals: `for (const k in
6360/// globalThis) new globalThis[k]()` once reached `__actor_abort` and killed
6361/// the actor, and a loaded worker once reached `__do_call` around its
6362/// `globalOutbound: null` (denoland/celld#192).
6363macro_rules! ops {
6364 ($names:ident, $install:ident, $($name:literal => $op:path),* $(,)?) => {
6365 const $names: &[&str] = &[$($name),*];
6366 fn $install<'s>(
6367 scope: &mut v8::PinScope<'s, '_>,
6368 functions: &mut Vec<v8::Local<'s, v8::Function>>,
6369 ) {
6370 $({
6371 // Each expansion defines its own `attributed`, so every op
6372 // keeps a distinct callback. It records which continuation
6373 // enqueued the op, and only when the call enqueued one: the
6374 // count is a thread-local read, while the name costs a CPED
6375 // lookup.
6376 fn attributed<'s>(
6377 scope: &mut v8::PinScope<'s, '_>,
6378 args: v8::FunctionCallbackArguments<'s>,
6379 rv: v8::ReturnValue<'s, v8::Value>,
6380 ) {
6381 #[cfg(celld_internal_tests)]
6382 let mut rv = rv;
6383 #[cfg(celld_internal_tests)]
6384 if call_op_patch(scope, $name, &args, &mut rv) {
6385 return;
6386 }
6387 let before = asyncrt::spawn_count();
6388 $op(scope, args, rv);
6389 if asyncrt::spawn_count() != before {
6390 if let Some(owner) = operation_continuation_id(scope) {
6391 asyncrt::attribute_spawns(before, owner);
6392 }
6393 }
6394 }
6395 functions.push(v8::Function::new(scope, attributed).unwrap());
6396 })*
6397 }
6398 };
6399}
6400
6401/// The parameters every internal script is compiled with: the internals
6402/// object, then one binding per host op in table order. The values are what
6403/// the script is called with, in the same order.
6404///
6405/// Ops reach the harness as parameters and not as globals, so a bundle cannot
6406/// name `__do_call` and address a cell it holds no stub for, and a loaded
6407/// worker with `globalOutbound: null` cannot reach the host at all except
6408/// through the capabilities in its `env`. A parameter is also a binding user
6409/// code cannot replace, which is what the event hooks already required.
6410///
6411/// Parameters rather than `__celld.__op(...)` at every call site: the
6412/// internal scripts name an op in several hundred places, a bare identifier
6413/// keeps each of those lines as it was, and a closure binding costs a
6414/// context-slot load where a property costs a lookup. The same op is also a
6415/// property of `__celld`, read-only, for the host and for the test hatch.
6416pub(super) struct InternalArguments<'s> {
6417 names: Vec<v8::Local<'s, v8::String>>,
6418 values: Vec<v8::Local<'s, v8::Value>>,
6419}
6420
6421fn op_names() -> impl Iterator<Item = &'static str> {
6422 #[cfg(celld_internal_tests)]
6423 let test = TEST_OP_NAMES.iter().copied();
6424 #[cfg(not(celld_internal_tests))]
6425 let test = std::iter::empty();
6426 OP_NAMES.iter().copied().chain(test)
6427}
6428
6429impl<'s> InternalArguments<'s> {
6430 /// `__celld` first, then `ops` in `op_names()` order.
6431 fn new(
6432 scope: &mut v8::PinScope<'s, '_>,
6433 internals: v8::Local<'s, v8::Object>,
6434 ops: impl FnMut(
6435 &mut v8::PinScope<'s, '_>,
6436 v8::Local<'s, v8::String>,
6437 ) -> v8::Local<'s, v8::Value>,
6438 ) -> Self {
6439 let mut ops = ops;
6440 let mut names = vec![v8_strings::key(scope, &v8_strings::INTERNALS)];
6441 let mut values = vec![internals.into()];
6442 for name in op_names() {
6443 let key = v8::String::new(scope, name).unwrap();
6444 values.push(ops(scope, key));
6445 names.push(key);
6446 }
6447 Self { names, values }
6448 }
6449}
6450
6451/// Build the ops, hold them on the internals object, and return them as the
6452/// arguments of the bootstrap scripts. Nothing here touches the global.
6453fn install_ops<'s>(scope: &mut v8::PinScope<'s, '_>) -> InternalArguments<'s> {
6454 let internals = v8::Object::new(scope);
6455 let mut functions = Vec::new();
6456 install_op_functions(scope, &mut functions);
6457 #[cfg(celld_internal_tests)]
6458 install_test_op_functions(scope, &mut functions);
6459 let mut functions = functions.into_iter();
6460 // Read-only: a test that assigns `__celld.__op = fn`, the idiom that
6461 // patching a global once allowed, throws instead of binding a script that
6462 // compiles later to a function the bootstrap harness never saw.
6463 let arguments = InternalArguments::new(scope, internals, |scope, key| {
6464 let function = functions.next().expect("one function per op name");
6465 internals.define_own_property(
6466 scope,
6467 key.into(),
6468 function.into(),
6469 v8::PropertyAttribute::READ_ONLY | v8::PropertyAttribute::DONT_DELETE,
6470 );
6471 function.into()
6472 });
6473 actor_runtime_state(scope)
6474 .internals
6475 .set(v8::Global::new(scope, internals))
6476 .unwrap_or_else(|_| panic!("internals were already installed"));
6477 // A test build exposes the internals object, so an engine test can reach
6478 // ops and harness state by name and patch an op through
6479 // `__test_patch_op`. A shipping isolate has no `__`-prefixed global.
6480 #[cfg(celld_internal_tests)]
6481 {
6482 let global = scope.get_current_context().global(scope);
6483 let key = v8_strings::key(scope, &v8_strings::INTERNALS);
6484 global.define_own_property(
6485 scope,
6486 key.into(),
6487 internals.into(),
6488 v8::PropertyAttribute::DONT_ENUM,
6489 );
6490 }
6491 arguments
6492}
6493
6494/// The same arguments, rebuilt from the internals object for a script that
6495/// compiles after bootstrap: a lazy global or a lazy builtin module.
6496pub(super) fn internal_arguments<'s>(scope: &mut v8::PinScope<'s, '_>) -> InternalArguments<'s> {
6497 let internals = internals(scope);
6498 InternalArguments::new(scope, internals, |scope, key| {
6499 internals.get(scope, key.into()).unwrap()
6500 })
6501}
6502
6503/// The internals object of this isolate: every host op and every harness
6504/// function the host calls, reachable from Rust and from internal scripts
6505/// but from no user code.
6506pub(super) fn internals<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object> {
6507 let state = actor_runtime_state(scope);
6508 let internals = state
6509 .internals
6510 .get()
6511 .expect("internals are installed before any script runs");
6512 v8::Local::new(scope, internals)
6513}
6514
6515pub(super) fn internal_value<'s>(
6516 scope: &mut v8::PinScope<'s, '_>,
6517 name: &str,
6518) -> Option<v8::Local<'s, v8::Value>> {
6519 let internals = internals(scope);
6520 let key = v8::String::new(scope, name).unwrap();
6521 internals
6522 .get(scope, key.into())
6523 .filter(|value| !value.is_undefined())
6524}
6525
6526pub(super) fn internal_function<'s>(
6527 scope: &mut v8::PinScope<'s, '_>,
6528 name: &str,
6529) -> Result<v8::Local<'s, v8::Function>> {
6530 internal_value(scope, name)
6531 .ok_or_else(|| anyhow!("no {name}"))?
6532 .try_into()
6533 .map_err(|_| anyhow!("{name} is not a function"))
6534}
6535
6536pub(super) fn internal_object<'s>(
6537 scope: &mut v8::PinScope<'s, '_>,
6538 name: &str,
6539) -> Result<v8::Local<'s, v8::Object>> {
6540 internal_value(scope, name)
6541 .and_then(|value| value.to_object(scope))
6542 .ok_or_else(|| anyhow!("missing {name} runtime state"))
6543}
6544
6545/// `__cell`, the harness's runtime-state object.
6546pub(super) fn cell_state<'s>(
6547 scope: &mut v8::PinScope<'s, '_>,
6548) -> Result<v8::Local<'s, v8::Object>> {
6549 let internals = internals(scope);
6550 let key = v8_strings::key(scope, &v8_strings::CELL);
6551 internals
6552 .get(scope, key.into())
6553 .and_then(|value| value.to_object(scope))
6554 .ok_or_else(|| anyhow!("missing __cell runtime state"))
6555}
6556
6557/// Run a small host-generated snippet with `__celld` bound. The snippet
6558/// differs per load, so it is compiled without the bootstrap cache.
6559pub(super) fn run_internal_snippet<'s>(
6560 scope: &mut v8::PinScope<'s, '_>,
6561 source: &str,
6562) -> Option<v8::Local<'s, v8::Value>> {
6563 let code = v8::String::new(scope, source)?;
6564 let arguments = InternalArguments {
6565 names: vec![v8_strings::key(scope, &v8_strings::INTERNALS)],
6566 values: vec![internals(scope).into()],
6567 };
6568 bootstrap::run_internal_script(scope, None, code, &arguments).ok()
6569}
6570
6571/// `__test_patch_op(name, fn | null)`: route the named op through `fn` for
6572/// the rest of the isolate's life, or restore it. The patch receives the op's
6573/// arguments and `this`; an op it calls itself runs the real op, so a patch
6574/// can observe or clamp arguments and then forward them.
6575///
6576/// The forward must happen before the patch returns. The re-entrancy guard
6577/// is held for that synchronous extent only, so a forward after an `await`
6578/// meets the patch again and recurses.
6579#[cfg(celld_internal_tests)]
6580fn op_test_patch_op(
6581 scope: &mut v8::PinScope,
6582 args: v8::FunctionCallbackArguments,
6583 _rv: v8::ReturnValue<v8::Value>,
6584) {
6585 let requested = args.get(0).to_rust_string_lossy(scope);
6586 let Some(name) = op_names()
6587 .filter(|name| *name != "__test_patch_op")
6588 .find(|name| *name == requested)
6589 else {
6590 return loader_throw(
6591 scope,
6592 &format!("__test_patch_op: {requested} is not a patchable op"),
6593 );
6594 };
6595 let state = actor_runtime_state(scope);
6596 let mut patches = state.op_patches.lock().unwrap();
6597 match v8::Local::<v8::Function>::try_from(args.get(1)) {
6598 Ok(patch) => {
6599 state.op_patched.store(true, Ordering::Relaxed);
6600 patches.insert(name, v8::Global::new(scope, patch));
6601 }
6602 Err(_) => {
6603 patches.remove(name);
6604 }
6605 }
6606}
6607
6608#[cfg(celld_internal_tests)]
6609fn call_op_patch(
6610 scope: &mut v8::PinScope,
6611 name: &'static str,
6612 args: &v8::FunctionCallbackArguments,
6613 rv: &mut v8::ReturnValue<v8::Value>,
6614) -> bool {
6615 let state = actor_runtime_state(scope);
6616 if !state.op_patched.load(Ordering::Relaxed) {
6617 return false;
6618 }
6619 let patch = state
6620 .op_patches
6621 .lock()
6622 .unwrap()
6623 .get(name)
6624 .map(|patch| v8::Local::new(scope, patch));
6625 let Some(patch) = patch else {
6626 return false;
6627 };
6628 // Re-entered from inside the patch: this call is the forward to the real
6629 // op.
6630 if !state.op_patches_active.lock().unwrap().insert(name) {
6631 return false;
6632 }
6633 let values: Vec<v8::Local<v8::Value>> = (0..args.length()).map(|i| args.get(i)).collect();
6634 let result = patch.call(scope, args.this().into(), &values);
6635 state.op_patches_active.lock().unwrap().remove(name);
6636 if let Some(result) = result {
6637 rv.set(result);
6638 }
6639 true
6640}
6641
6642ops! { OP_NAMES, install_op_functions,
6643 "__heap_limit_excessively_exceeded" =>
6644 op_heap_limit_excessively_exceeded,
6645 "__heap_over_admission_share" => op_heap_over_admission_share,
6646 "__ws_send" => websocket::op_ws_send,
6647 "__ws_send_binary" => websocket::op_ws_send_binary,
6648 "__ws_close" => websocket::op_ws_close,
6649 "__ws_alloc" => websocket::op_ws_alloc,
6650 "__ws_prepare_worker_handoff" => websocket::op_ws_prepare_worker_handoff,
6651 "__ws_accept" => websocket::op_ws_accept,
6652 "__ws_accept_regular" => websocket::op_ws_accept_regular,
6653 "__ws_list" => websocket::op_ws_list,
6654 "__ws_attachment_set" => websocket::op_ws_attachment_set,
6655 "__ws_auto_response_set" => websocket::op_ws_auto_response_set,
6656 "__ws_auto_response_get" => websocket::op_ws_auto_response_get,
6657 "__ws_auto_response_ts" => websocket::op_ws_auto_response_ts,
6658 "__ws_connect" => websocket::op_ws_connect,
6659 "__ws_bind_target" => websocket::op_ws_bind_target,
6660 "__ws_next" => websocket::op_ws_next,
6661 "__ws_upgrade" => websocket::op_ws_upgrade,
6662 "__hr_create" => html_rewriter::op_hr_create,
6663 "__hr_write" => html_rewriter::op_hr_write,
6664 "__hr_end" => html_rewriter::op_hr_end,
6665 "__hr_cmd" => html_rewriter::op_hr_cmd,
6666 "__hr_event" => html_rewriter::op_hr_event,
6667 "__hr_take" => html_rewriter::op_hr_take,
6668 "__hr_free" => html_rewriter::op_hr_free,
6669 "__tcp_connect" => tcp::op_tcp_connect,
6670 "__tcp_read" => tcp::op_tcp_read,
6671 "__tcp_write" => tcp::op_tcp_write,
6672 "__tcp_shutdown" => tcp::op_tcp_shutdown,
6673 "__tcp_close" => tcp::op_tcp_close,
6674 "__tcp_starttls" => tcp::op_tcp_starttls,
6675 "__container_running" => container::op_container_running,
6676 "__container_address" => container::op_container_address,
6677 "__container_start" => container::op_container_start,
6678 "__container_monitor" => container::op_container_monitor,
6679 "__container_destroy" => container::op_container_destroy,
6680 "__container_signal" => container::op_container_signal,
6681 "__container_inactivity" => container::op_container_inactivity,
6682 "__container_exec" => container::op_container_exec,
6683 "__container_exec_read" => container::op_container_exec_read,
6684 "__container_exec_write" => container::op_container_exec_write,
6685 "__container_exec_close" => container::op_container_exec_close,
6686 "__container_exec_wait" => container::op_container_exec_wait,
6687 "__container_exec_kill" => container::op_container_exec_kill,
6688 "__container_exec_drop" => container::op_container_exec_drop,
6689 "__storage_get" => storage_ops::op_storage_get,
6690 "__storage_get_many" => storage_ops::op_storage_get_many,
6691 "__sql_ingest" => storage_ops::op_sql_ingest,
6692 "__sql_cursor_start" => storage_ops::op_sql_cursor_start,
6693 "__sql_cursor_next" => storage_ops::op_sql_cursor_next,
6694 "__sql_cursor_close" => storage_ops::op_sql_cursor_close,
6695 "__sql_database_size" => storage_ops::op_sql_database_size,
6696 "__d1_run" => storage_ops::op_d1_run,
6697 "__storage_transaction_control" => storage_ops::op_storage_transaction_control,
6698 "__log" => op_log,
6699 "__storage_put" => storage_ops::op_storage_put,
6700 "__storage_put_many" => storage_ops::op_storage_put_many,
6701 "__storage_queue_put" => storage_ops::op_storage_queue_put,
6702 "__storage_queue_put_many" => storage_ops::op_storage_queue_put_many,
6703 "__storage_put_serialized" => storage_ops::op_storage_put_serialized,
6704 "__storage_queue_put_serialized" => storage_ops::op_storage_queue_put_serialized,
6705 "__storage_flush_pending_puts" => storage_ops::op_storage_flush_pending_puts,
6706 "__storage_sync" => storage_ops::op_storage_sync,
6707 "__storage_cancel_pending_puts" => storage_ops::op_storage_cancel_pending_puts,
6708 "__actor_abort" => op_actor_abort,
6709 "__cron_plan" => op_cron_plan,
6710 "__kv_blob" => op_kv_blob,
6711 "__process_exit" => op_process_exit,
6712 "__storage_delete" => storage_ops::op_storage_delete,
6713 "__storage_delete_many" => storage_ops::op_storage_delete_many,
6714 "__storage_list" => storage_ops::op_storage_list,
6715 "__storage_sync_list_start" => storage_ops::op_storage_sync_list_start,
6716 "__storage_sync_list_next" => storage_ops::op_storage_sync_list_next,
6717 "__storage_delete_all" => storage_ops::op_storage_delete_all,
6718 "$$urlParse" => op_url_parse,
6719 "$$urlPatternParse" => op_urlpattern_parse,
6720 "$$urlPatternMatchInput" => op_urlpattern_match_input,
6721 "$$atob" => op_atob,
6722 "$$btoa" => op_btoa,
6723 "$$textDecoderLabel" => op_text_decoder_label,
6724 "$$textDecoderNew" => op_text_decoder_new,
6725 "$$textDecoderDecode" => op_text_decoder_decode,
6726 "$$textDecoderDecodeOnce" => op_text_decoder_decode_once,
6727 "$$textDecoderFree" => op_text_decoder_free,
6728 "__alarm_set" => op_alarm_set,
6729 "__queue_alarm_set_wait" => op_queue_alarm_set_wait,
6730 "__alarm_get" => op_alarm_get,
6731 "__alarm_delete" => op_alarm_delete,
6732 "__loader_load" => op_loader_load,
6733 "__loader_fetch" => op_loader_fetch,
6734 "__loader_rpc" => op_loader_rpc,
6735 "__loader_drop" => op_loader_drop,
6736 "__facet_fetch" => op_facet_fetch,
6737 "__facet_rpc" => op_facet_rpc,
6738 "__facet_abort" => op_facet_abort,
6739 "__facet_delete" => op_facet_delete,
6740 "__do_call" => op_do_call,
6741 "__svc_call" => op_svc_call,
6742 "__svc_call_cancellable" => op_svc_call_cancellable,
6743 "__svc_rpc" => op_svc_rpc,
6744 "__queue_dispatch" => op_queue_dispatch,
6745 "__queue_policy" => op_queue_policy,
6746 "__do_call_cancellable" => op_do_call_cancellable,
6747 "__do_call_cancel" => op_do_call_cancel,
6748 "__rpc_signal_new" => op_rpc_signal_new,
6749 "__rpc_signal_abort" => op_rpc_signal_abort,
6750 "__rpc_signal_release" => op_rpc_signal_release,
6751 "__rpc_signal_poll" => op_rpc_signal_poll,
6752 "__rpc_signal_wait" => op_rpc_signal_wait,
6753 "__rpc_signal_unsubscribe" => op_rpc_signal_unsubscribe,
6754 "__do_id" => op_do_id,
6755 "__rpc_call" => op_rpc_call,
6756 "__sc_encode" => storage_ops::op_sc_encode,
6757 "__sc_decode" => storage_ops::op_sc_decode,
6758 "__structured_clone" => storage_ops::op_structured_clone,
6759 "__op_fetch" => op_fetch,
6760 "__r2_head" => r2_ops::op_r2_head,
6761 "__r2_get" => r2_ops::op_r2_get,
6762 "__r2_put" => r2_ops::op_r2_put,
6763 "__r2_put_begin" => r2_ops::op_r2_put_begin,
6764 "__r2_put_chunk" => r2_ops::op_r2_put_chunk,
6765 "__r2_put_end" => r2_ops::op_r2_put_end,
6766 "__r2_delete" => r2_ops::op_r2_delete,
6767 "__r2_list" => r2_ops::op_r2_list,
6768 "__r2_mp_begin" => r2_ops::op_r2_mp_begin,
6769 "__r2_mp_resume" => r2_ops::op_r2_mp_resume,
6770 "__r2_mp_part" => r2_ops::op_r2_mp_part,
6771 "__r2_mp_complete" => r2_ops::op_r2_mp_complete,
6772 "__r2_mp_abort" => r2_ops::op_r2_mp_abort,
6773 "__asset_fetch" => op_asset_fetch,
6774 "__http_stream_read" => op_http_stream_read,
6775 "__http_stream_cancel" => op_http_stream_cancel,
6776 "__http_stream_tee" => op_http_stream_tee,
6777 "__response_stream_create" => op_response_stream_create,
6778 "__response_stream_write" => op_response_stream_write,
6779 "__response_stream_closed" => op_response_stream_closed,
6780 "__response_stream_close" => op_response_stream_close,
6781 "__op_timer" => op_timer,
6782 "__timer_alloc" => op_timer_alloc,
6783 "__io_context_id" => op_io_context_id,
6784 "__with_input_gate_context" => op_with_input_gate_context,
6785 "__gate_acquire" => op_gate_acquire,
6786 "__gate_wait" => op_gate_wait,
6787 "__gate_release" => op_gate_release,
6788 "__timer_cancel" => op_timer_cancel,
6789 "__crypto_operation" => crypto::op_crypto_operation,
6790 "$$randomValues" => crypto::op_webcrypto_random,
6791 "$$digest" => crypto::op_webcrypto_digest,
6792 "$$hmacSign" => crypto::op_webcrypto_hmac_sign,
6793 "$$hmacVerify" => crypto::op_webcrypto_hmac_verify,
6794 "$$aesEncrypt" => crypto::op_webcrypto_aes_encrypt,
6795 "$$aesDecrypt" => crypto::op_webcrypto_aes_decrypt,
6796 "$$pbkdf2" => crypto::op_node_pbkdf2,
6797 "$$hkdf" => crypto::op_node_hkdf,
6798 "$$timingSafeEqual" => crypto::op_timing_safe_equal,
6799 "__event_begin" => op_event_begin,
6800 "__event_end" => op_event_end,
6801 "__pending_event_begin" => op_pending_event_begin,
6802 "__pending_event_end" => op_pending_event_end,
6803 "__vfs_mkdir" => op_vfs_mkdir,
6804 "__vfs_read_file" => op_vfs_read_file,
6805 "__vfs_stat" => op_vfs_stat,
6806 "__wait_until" => op_wait_until,
6807 "__wait_until_active" => op_wait_until_active,
6808 "__event_depth" => op_event_depth,
6809 "__als_get" => op_als_get,
6810 "__als_set" => op_als_set,
6811 "__util_type_flags" => op_util_type_flags,
6812 "__util_constructor_name" => op_util_constructor_name,
6813 "__util_proxy_details" => op_util_proxy_details,
6814 "__util_promise_details" => op_util_promise_details,
6815 "__util_preview_entries" => op_util_preview_entries,
6816 "__builtin_module" => op_builtin_module,
6817 "__zlib" => zlib::op_zlib,
6818 "__zlib_stream_new" => zlib::op_zlib_stream_new,
6819 "__zlib_stream_push" => zlib::op_zlib_stream_push,
6820 "__zlib_stream_end" => zlib::op_zlib_stream_end,
6821 "__zlib_stream_drop" => zlib::op_zlib_stream_drop,
6822}
6823
6824#[cfg(celld_internal_tests)]
6825ops! { TEST_OP_NAMES, install_test_op_functions,
6826 "__test_patch_op" => op_test_patch_op,
6827 "__test_gc" => op_test_gc,
6828 "__loader_count" => op_loader_count,
6829 "__test_set_heap_limit_excessively_exceeded" =>
6830 op_test_set_heap_limit_excessively_exceeded,
6831 "__test_force_heap_admission_refusal" =>
6832 op_test_force_heap_admission_refusal,
6833 "__test_heap_share" => op_test_heap_share,
6834 "__test_external_memory" => op_test_external_memory,
6835 "__test_workflow_event_consumed" => op_test_workflow_event_consumed,
6836 "__test_workflow_meta_created" => op_test_workflow_meta_created,
6837 "__test_workflow_terminal_alarm_set" => op_test_workflow_terminal_alarm_set,
6838 "__test_queue_dlq_accepted" => op_test_queue_dlq_accepted,
6839 "__test_queue_metrics_materialized" => op_test_queue_metrics_materialized,
6840 "__test_queue_producer_group" => op_test_queue_producer_group,
6841 "__test_queue_rearm_bounded" => op_test_queue_rearm_bounded,
6842 "__test_queue_lease_lookup_plan" => op_test_queue_lease_lookup_plan,
6843 "__test_kv_list_plan" => op_test_kv_list_plan,
6844 "__sql_set_max_page_count_for_test" =>
6845 storage_ops::op_sql_set_max_page_count_for_test,
6846 "__sql_set_write_fault_for_test" => storage_ops::op_sql_set_write_fault_for_test,
6847 "__sql_set_cache_size_for_test" => storage_ops::op_sql_set_cache_size_for_test,
6848 "__sql_set_interrupt_fault_for_test" =>
6849 storage_ops::op_sql_set_interrupt_fault_for_test,
6850 "__sql_register_nomem_function_for_test" =>
6851 storage_ops::op_sql_register_nomem_function_for_test,
6852}
6853
6854/// `__kv_blob(requestJson, bytes?)` -> Promise<string | Uint8Array>.
6855///
6856/// One op for the whole large-value path, following `__d1_run` rather than
6857/// exposing get, put and sweep as three. A put copies one typed view into Rust,
6858/// and a successful get resolves directly to a `Uint8Array`. JSON arrays would
6859/// turn a valid 25 MiB value into millions of heap objects and crash the
6860/// isolate before the bucket I/O began.
6861///
6862/// JSON remains the control envelope for an absent get and a swept count. The
6863/// cell scope is host-derived, so JavaScript cannot read or collect another
6864/// namespace's objects by changing the request.
6865fn op_kv_blob(
6866 scope: &mut v8::PinScope,
6867 args: v8::FunctionCallbackArguments,
6868 mut rv: v8::ReturnValue<v8::Value>,
6869) {
6870 let request = args.get(0).to_rust_string_lossy(scope);
6871 let value = view_bytes(args.get(1));
6872 // Bucket I/O is egress, so it waits on the same gate a service call does
6873 // rather than escaping the shed the node applies under pressure.
6874 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
6875 // Blob authority follows the storage installed for this exact cell
6876 // activation. Capturing it before enqueue prevents a later ownership
6877 // lookup from lending a deposed collector the new owner's epoch.
6878 let authority = gate
6879 .cell_scope()
6880 .and_then(|cell| storage::activation_epoch(cell).map(|epoch| (cell.to_string(), epoch)));
6881 let id = asyncrt::enqueue(async move {
6882 let (cell, activation_epoch) =
6883 authority.ok_or_else(|| "KV blob I/O requires active cell storage".to_string())?;
6884 await_egress_gate(gate).await?;
6885 match crate::kv_blob::run(&cell, activation_epoch, &request, value).await? {
6886 crate::kv_blob::BlobReply::Bytes(bytes) => Ok(asyncrt::OpOut::Bytes(bytes)),
6887 crate::kv_blob::BlobReply::Json(reply) => Ok(asyncrt::OpOut::Str(reply.to_string())),
6888 }
6889 });
6890 rv.set(promise_for(scope, id));
6891}
6892
6893/// Create a JS promise for an async op `id` and return it to JS.
6894fn promise_for<'s>(scope: &mut v8::PinScope<'s, '_>, id: u64) -> v8::Local<'s, v8::Value> {
6895 let resolver = v8::PromiseResolver::new(scope).unwrap();
6896 let promise = resolver.get_promise(scope);
6897 promise_store(scope, id, v8::Global::new(scope, resolver));
6898 promise.into()
6899}
6900
6901fn rejected_promise<'s>(
6902 scope: &mut v8::PinScope<'s, '_>,
6903 message: &str,
6904) -> v8::Local<'s, v8::Value> {
6905 let resolver = v8::PromiseResolver::new(scope).unwrap();
6906 let promise = resolver.get_promise(scope);
6907 let message = v8::String::new(scope, message).unwrap();
6908 let exception = v8::Exception::error(scope, message);
6909 resolver.reject(scope, exception);
6910 promise.into()
6911}
6912
6913fn op_queue_dispatch(
6914 scope: &mut v8::PinScope,
6915 args: v8::FunctionCallbackArguments,
6916 mut rv: v8::ReturnValue<v8::Value>,
6917) {
6918 let script = args.get(0).to_rust_string_lossy(scope);
6919 let queue = args.get(1).to_rust_string_lossy(scope);
6920 let envelope = args.get(2).to_rust_string_lossy(scope);
6921 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Queue);
6922 let cell = gate.cell_scope().map(str::to_string).unwrap_or_default();
6923 let request = match crate::queue_policy::dispatch_request(
6924 current_generation(scope),
6925 cell,
6926 script,
6927 queue,
6928 &envelope,
6929 ) {
6930 Ok(request) => request,
6931 Err(error) => return loader_throw(scope, &format!("{error:#}")),
6932 };
6933 let id = asyncrt::enqueue(async move {
6934 if request.scope.is_empty() {
6935 return Err("Queue dispatch requires a cell event".to_string());
6936 }
6937 gated_channel_send(
6938 gate,
6939 &QUEUE_DISPATCH_TX,
6940 request,
6941 "no Queue dispatch channel",
6942 )
6943 .await?;
6944 Ok(asyncrt::OpOut::Str(String::new()))
6945 });
6946 rv.set(promise_for(scope, id));
6947}
6948
6949/// The Queue policy boundary, `crate::queue_policy::run` behind one
6950/// synchronous op.
6951fn op_queue_policy(
6952 scope: &mut v8::PinScope,
6953 args: v8::FunctionCallbackArguments,
6954 mut rv: v8::ReturnValue<v8::Value>,
6955) {
6956 let request: serde_json::Value =
6957 match serde_json::from_str(&args.get(0).to_rust_string_lossy(scope)) {
6958 Ok(request) => request,
6959 Err(error) => {
6960 return loader_throw(scope, &format!("invalid Queue policy input: {error}"))
6961 }
6962 };
6963 #[cfg(celld_internal_tests)]
6964 if request.get("op").and_then(serde_json::Value::as_str) == Some("settlement") {
6965 QUEUE_SETTLEMENT_POLICY_OBSERVED.with(|observed| observed.set(true));
6966 }
6967 match crate::queue_policy::run(&request) {
6968 Ok(value) => {
6969 let value = v8::String::new(scope, &value.to_string()).unwrap();
6970 rv.set(value.into());
6971 }
6972 Err(error) => loader_throw(scope, &error.to_string()),
6973 }
6974}
6975
6976/// Async cross-node dispatch: hand the fetch to the tokio proxy task and await
6977/// its reply off-thread — the JS thread is never blocked. Resolves to a JSON
6978/// `{status, body, headers}` string the harness turns back into a Response.
6979/// `__svc_rpc(script, entrypoint, pathJson, argsSc, propsSc)` ->
6980/// Promise<Uint8Array>; arguments, props, and the result are structured-clone
6981/// bytes.
6982/// The application generation the calling isolate was built for, from the
6983/// slot `load_config` installs. Zero for an isolate built outside any
6984/// generation, which the runtime resolves as the current one.
6985fn current_generation(scope: &mut v8::PinScope) -> crate::generation::GenerationId {
6986 scope
6987 .get_slot::<crate::generation::GenerationTag>()
6988 .map(|tag| tag.0)
6989 .unwrap_or(0)
6990}
6991
6992fn op_svc_rpc(
6993 scope: &mut v8::PinScope,
6994 args: v8::FunctionCallbackArguments,
6995 mut rv: v8::ReturnValue<v8::Value>,
6996) {
6997 let context = event_context(scope);
6998 if let Err(error) = context.charge_subrequest() {
6999 return loader_throw(scope, &error);
7000 }
7001 let script = args.get(0).to_rust_string_lossy(scope);
7002 let entrypoint = args.get(1).to_rust_string_lossy(scope);
7003 let path = match serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)) {
7004 Ok(path) => path,
7005 Err(error) => return loader_throw(scope, &format!("service RPC path is invalid: {error}")),
7006 };
7007 let call_args = args.get(3);
7008 let operation = if call_args.is_null() {
7009 crate::WorkerRpcOperation::Get { path }
7010 } else {
7011 crate::WorkerRpcOperation::Call {
7012 path,
7013 args: view_bytes(call_args).unwrap_or_default(),
7014 }
7015 };
7016 let props = view_bytes(args.get(4)).unwrap_or_default();
7017 let (tx, rx) = tokio::sync::oneshot::channel();
7018 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
7019 let request = SvcRpcReq {
7020 generation: current_generation(scope),
7021 script,
7022 entrypoint,
7023 props,
7024 operation,
7025 reply: tx,
7026 };
7027 let id = asyncrt::enqueue(async move {
7028 gated_channel_send(gate, &SVC_RPC_TX, request, "no service binding channel").await?;
7029 match rx.await {
7030 Ok(Ok(result)) => Ok(result),
7031 Ok(Err(error)) => Err(format!("{error}")),
7032 Err(error) => Err(format!("service dropped: {error}")),
7033 }
7034 });
7035 rv.set(promise_for(scope, id));
7036}
7037
7038/// `__svc_call(script, url, method, body, headersJson, streamId, entrypoint,
7039/// propsSc)` -> Promise<json>.
7040/// The service-binding equivalent of `__do_call`: no scope to resolve and no
7041/// cancellation token, just a handoff to the target script's pool.
7042fn op_svc_call(
7043 scope: &mut v8::PinScope,
7044 args: v8::FunctionCallbackArguments,
7045 mut rv: v8::ReturnValue<v8::Value>,
7046) {
7047 op_svc_call_impl(scope, args, &mut rv, false);
7048}
7049
7050fn op_svc_call_cancellable(
7051 scope: &mut v8::PinScope,
7052 args: v8::FunctionCallbackArguments,
7053 mut rv: v8::ReturnValue<v8::Value>,
7054) {
7055 op_svc_call_impl(scope, args, &mut rv, true);
7056}
7057
7058fn op_svc_call_impl(
7059 scope: &mut v8::PinScope,
7060 args: v8::FunctionCallbackArguments,
7061 rv: &mut v8::ReturnValue<v8::Value>,
7062 cancellable: bool,
7063) {
7064 if let Err(error) = event_context(scope).charge_subrequest() {
7065 return loader_throw(scope, &error);
7066 }
7067 let script = args.get(0).to_rust_string_lossy(scope);
7068 let url = args.get(1).to_rust_string_lossy(scope);
7069 let method = args.get(2).to_rust_string_lossy(scope);
7070 let stream_arg = args.get(5);
7071 let entrypoint_arg = args.get(6);
7072 let props = view_bytes(args.get(7)).unwrap_or_default();
7073 let entrypoint = entrypoint_arg
7074 .is_string()
7075 .then(|| crate::WorkerFetchEntrypoint {
7076 name: entrypoint_arg.to_rust_string_lossy(scope),
7077 props,
7078 });
7079 let body = if stream_arg.is_number() {
7080 RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64)
7081 } else {
7082 let Some(bytes) = view_bytes(args.get(3)) else {
7083 return loader_throw(
7084 scope,
7085 "service binding: the request body is not a typed array",
7086 );
7087 };
7088 RequestBody::Bytes(bytes.into())
7089 };
7090 let headers: Vec<(String, String)> =
7091 match serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)) {
7092 Ok(headers) => headers,
7093 Err(error) => {
7094 return loader_throw(
7095 scope,
7096 &format!(
7097 "service binding: the request headers are not a name/value list: {error}"
7098 ),
7099 )
7100 }
7101 };
7102 let body_guard = match body.stream_id() {
7103 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
7104 Some(guard) => guard,
7105 None => return loader_throw(scope, "service binding: the body stream is not owned"),
7106 },
7107 None => RequestBodyGuard::of(&body),
7108 };
7109 let (tx, rx) = tokio::sync::oneshot::channel();
7110 // Shares the Durable Object cancel registry and the id encoding
7111 // `attach_cancel_id` writes, so `__do_call_cancel` works unchanged for a
7112 // service call. Only a cancellable call registers: a caller with no
7113 // AbortSignal has nothing that can cancel it, and the router already ends
7114 // the call when the reply sender drops.
7115 let (request_id, cancel, cancel_guard) = if cancellable {
7116 let request_id = next_do_request_id();
7117 let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
7118 do_call_cancels()
7119 .lock()
7120 .unwrap()
7121 .insert(request_id, cancel_sender);
7122 (
7123 Some(request_id),
7124 Some(cancel_receiver),
7125 Some(DoCallCancelGuard::new(request_id)),
7126 )
7127 } else {
7128 (None, None, None)
7129 };
7130 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
7131 let request = SvcCallReq {
7132 cancel,
7133 generation: current_generation(scope),
7134 script,
7135 entrypoint,
7136 url,
7137 method,
7138 body,
7139 body_guard,
7140 headers,
7141 reply: tx,
7142 };
7143 let stream_service = http_stream_service();
7144 let id = asyncrt::enqueue(async move {
7145 let mut cancel_guard = cancel_guard;
7146 gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?;
7147 let result = match rx.await {
7148 Ok(Ok(response)) => encode_http_response(response, true, &stream_service),
7149 Ok(Err(error)) => Err(format!("{error}")),
7150 Err(error) => Err(format!("service dropped: {error}")),
7151 };
7152 if let Some(cancel_guard) = cancel_guard.as_mut() {
7153 cancel_guard.disarm();
7154 }
7155 result
7156 });
7157 let promise = promise_for(scope, id);
7158 if let Some(request_id) = request_id {
7159 attach_cancel_id(scope, promise, request_id);
7160 }
7161 rv.set(promise);
7162}
7163
7164// --- Worker Loader: dynamic isolates for Code Mode ---
7165// A running Worker creates a fresh isolate from code it supplies at runtime
7166// and invokes it. The loaded isolate uses the same turn driver as every
7167// stateless Worker, so an awaited operation holds no thread or isolate.
7168
7169// Mirror the workerd dynamic-worker limits (worker-loader.c++): 64 MiB total
7170// module bytes, 1 MiB env. Messages match so the conformance cases pass.
7171const MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024;
7172const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024;
7173/// The largest `props` value one loaded entrypoint or Durable Object class can
7174/// carry, as structured-clone bytes. Workerd does not impose this bound, but
7175/// celld holds the value on a host job for the whole call. The harness shares
7176/// the caller's isolate and cannot prevent that unbounded host allocation, so
7177/// every op that accepts call props must enforce the limit.
7178const MAX_DYNAMIC_WORKER_PROPS_SIZE: usize = 1024 * 1024;
7179
7180fn loader_props_bytes(value: v8::Local<v8::Value>) -> Result<Vec<u8>, String> {
7181 // RPC and facet calls use undefined for absent props. A different
7182 // non-typed value is a malformed transport argument, not empty props.
7183 let props = if value.is_undefined() {
7184 Vec::new()
7185 } else {
7186 view_bytes(value)
7187 .ok_or_else(|| "worker loader: the props are not a typed array".to_string())?
7188 };
7189 if props.len() > MAX_DYNAMIC_WORKER_PROPS_SIZE {
7190 return Err(format!(
7191 "Dynamic Worker props size ({} bytes) exceeds the maximum \
7192 allowed size of {MAX_DYNAMIC_WORKER_PROPS_SIZE} bytes.",
7193 props.len()
7194 ));
7195 }
7196 Ok(props)
7197}
7198
7199#[derive(Clone)]
7200enum LoaderState {
7201 Loading,
7202 Ready(Arc<crate::pool::Slot>),
7203 Failed(Arc<str>),
7204}
7205
7206#[derive(Clone, Eq, PartialEq)]
7207struct LoaderPrincipal {
7208 script: Arc<str>,
7209 generation: crate::generation::GenerationId,
7210}
7211
7212#[derive(Clone, Eq, PartialEq)]
7213struct LoaderOwner {
7214 id: u64,
7215 principal: LoaderPrincipal,
7216}
7217
7218impl LoaderOwner {
7219 fn fresh(script: &str, generation: crate::generation::GenerationId) -> Self {
7220 Self {
7221 id: LOADER_NEXT_OWNER.fetch_add(1, Ordering::Relaxed),
7222 principal: LoaderPrincipal {
7223 script: Arc::from(script),
7224 generation,
7225 },
7226 }
7227 }
7228}
7229
7230#[doc(hidden)]
7231pub struct LoaderEntry {
7232 owner: LoaderOwner,
7233 state: tokio::sync::watch::Receiver<LoaderState>,
7234}
7235
7236type LoaderRegistry = HashMap<u64, LoaderEntry>;
7237static LOADER_REGISTRY: OnceLock<std::sync::Mutex<LoaderRegistry>> = OnceLock::new();
7238static LOADER_NEXT_ID: AtomicU64 = AtomicU64::new(1);
7239static LOADER_NEXT_OWNER: AtomicU64 = AtomicU64::new(1);
7240
7241#[doc(hidden)]
7242pub fn loader_registry() -> &'static std::sync::Mutex<LoaderRegistry> {
7243 LOADER_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
7244}
7245
7246/// Remove the registry references for every child of `owner`. The caller
7247/// chooses when to drop the returned states, because they can own V8 isolates
7248/// and no other isolate can be entered on that thread at destruction time.
7249fn take_loader_owner(owner: &LoaderOwner) -> Vec<tokio::sync::watch::Receiver<LoaderState>> {
7250 let mut registry = loader_registry().lock().unwrap();
7251 let ids: Vec<u64> = registry
7252 .iter()
7253 .filter_map(|(id, entry)| (&entry.owner == owner).then_some(*id))
7254 .collect();
7255 ids.into_iter()
7256 .filter_map(|id| registry.remove(&id).map(|entry| entry.state))
7257 .collect()
7258}
7259
7260// Bound live Dynamic Workers so a runaway loader cannot exhaust isolates.
7261// Keep admission policy inside the registry: a caller-selected bound would let
7262// different entry points disagree about how much process capacity remains.
7263const MAX_LOADED_WORKERS: usize = 256;
7264// Reserve only the final process slot. A fixed fraction needlessly reduces
7265// single-script capacity without giving every competing principal a share.
7266const MAX_LOADED_WORKERS_PER_PRINCIPAL: usize = MAX_LOADED_WORKERS - 1;
7267
7268/// Check both limits and install the live state under one registry lock. A
7269/// separate check and insert lets concurrent isolates exceed either limit.
7270fn admit_loaded_worker(
7271 owner: LoaderOwner,
7272 state: tokio::sync::watch::Receiver<LoaderState>,
7273) -> Result<u64, String> {
7274 let mut registry = loader_registry().lock().unwrap();
7275 let principal_limit = MAX_LOADED_WORKERS_PER_PRINCIPAL;
7276 let principal_count = registry
7277 .values()
7278 .filter(|entry| entry.owner.principal == owner.principal)
7279 .count();
7280 if principal_count >= principal_limit {
7281 return Err(format!(
7282 "worker loader: too many loaded workers for script \"{}\" in generation {} (limit {principal_limit})",
7283 owner.principal.script, owner.principal.generation
7284 ));
7285 }
7286 if registry.len() >= MAX_LOADED_WORKERS {
7287 return Err(format!(
7288 "worker loader: too many loaded workers (limit {MAX_LOADED_WORKERS})"
7289 ));
7290 }
7291
7292 let id = LOADER_NEXT_ID.fetch_add(1, Ordering::Relaxed);
7293 registry.insert(id, LoaderEntry { owner, state });
7294 Ok(id)
7295}
7296
7297fn loader_throw(scope: &mut v8::PinScope, message: &str) {
7298 let message = v8::String::new(scope, message).unwrap();
7299 let exception = v8::Exception::error(scope, message);
7300 scope.throw_exception(exception);
7301}
7302
7303fn loader_invocation_limits(
7304 scope: &mut v8::PinScope,
7305 value: v8::Local<v8::Value>,
7306) -> Result<Option<ResourceLimits>, String> {
7307 let json = value.to_rust_string_lossy(scope);
7308 serde_json::from_str(&json)
7309 .map_err(|error| format!("worker loader: invalid invocation limits: {error}"))
7310}
7311
7312async fn loaded_worker_slot(
7313 mut state: tokio::sync::watch::Receiver<LoaderState>,
7314) -> Result<Arc<crate::pool::Slot>, String> {
7315 loop {
7316 match state.borrow().clone() {
7317 LoaderState::Ready(slot) => return Ok(slot),
7318 LoaderState::Failed(error) => return Err(error.to_string()),
7319 LoaderState::Loading => {}
7320 }
7321 state
7322 .changed()
7323 .await
7324 .map_err(|_| "worker loader: load task dropped".to_string())?;
7325 }
7326}
7327
7328/// `__loader_load(codeJson, wasm, outbound, outboundProps, envSc, envRoutes,
7329/// tailReporting)` -> stub id. Builds a WorkerConfig from the supplied modules
7330/// and registers its asynchronous load state. Compilation runs on Tokio's
7331/// blocking pool. Calls wait for that result and use the normal turn driver.
7332fn op_loader_load(
7333 scope: &mut v8::PinScope,
7334 args: v8::FunctionCallbackArguments,
7335 mut rv: v8::ReturnValue<v8::Value>,
7336) {
7337 let generation = current_generation(scope);
7338 let code_json = args.get(0).to_rust_string_lossy(scope);
7339 let code: serde_json::Value = match serde_json::from_str(&code_json) {
7340 Ok(code) => code,
7341 Err(e) => return loader_throw(scope, &format!("worker loader: {e}")),
7342 };
7343 // These fields change the security or observability contract of the
7344 // loaded Worker. Ignoring one makes a Worker run without the contract its
7345 // caller requested, which is more dangerous than refusing the load. Keep
7346 // this check in the host op so both load() and the lazy get() path cross
7347 // the same enforcement boundary.
7348 if code.get("allowExperimental").is_some() {
7349 return loader_throw(
7350 scope,
7351 "worker loader: WorkerCode field `allowExperimental` is not supported",
7352 );
7353 }
7354 let limits = match code.get("limits") {
7355 Some(value) => match serde_json::from_value::<ResourceLimits>(value.clone()) {
7356 Ok(limits) => Some(limits),
7357 Err(error) => {
7358 return loader_throw(scope, &format!("worker loader: invalid limits: {error}"));
7359 }
7360 },
7361 None => None,
7362 };
7363 let tail_reporting = args.get(6).boolean_value(scope);
7364 let Some(main) = code.get("mainModule").and_then(|v| v.as_str()) else {
7365 return loader_throw(scope, "worker loader: missing mainModule");
7366 };
7367 let Some(src) = code
7368 .get("modules")
7369 .and_then(|m| m.get(main))
7370 .and_then(|v| v.as_str())
7371 .map(str::to_string)
7372 else {
7373 return loader_throw(
7374 scope,
7375 &format!("worker loader: module {main:?} missing or not a string"),
7376 );
7377 };
7378 // Every module other than the main one is a sibling the main module may
7379 // import. JS modules arrive in the JSON as strings; anything else there is
7380 // rejected — JSON.stringify would already have mangled it, and dropping it
7381 // silently leaves the loaded worker failing instantiation with an
7382 // unresolved specifier that never names the cause. Wasm modules arrive
7383 // out of band as the second argument, an array of `[name, Uint8Array]`
7384 // pairs, which keeps the blobs out of the JSON payload entirely.
7385 let mut modules: Vec<(String, ModuleSource)> = Vec::new();
7386 if let Some(map) = code.get("modules").and_then(|m| m.as_object()) {
7387 for (name, value) in map.iter().filter(|(name, _)| name.as_str() != main) {
7388 let Some(source) = value.as_str() else {
7389 return loader_throw(
7390 scope,
7391 &format!("worker loader: module {name:?} must be a string or wasm bytes"),
7392 );
7393 };
7394 modules.push((name.clone(), ModuleSource::EsModule(source.to_string())));
7395 }
7396 }
7397 let sideband = args.get(1);
7398 if !sideband.is_undefined() {
7399 let Ok(entries) = v8::Local::<v8::Array>::try_from(sideband) else {
7400 return loader_throw(scope, "worker loader: wasm modules must be an array");
7401 };
7402 for index in 0..entries.length() {
7403 let entry = entries
7404 .get_index(scope, index)
7405 .and_then(|entry| v8::Local::<v8::Array>::try_from(entry).ok())
7406 .and_then(|pair| Some((pair.get_index(scope, 0)?, pair.get_index(scope, 1)?)))
7407 .filter(|(name, _)| name.is_string())
7408 .and_then(|(name, value)| {
7409 let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
7410 Some((name.to_rust_string_lossy(scope), view))
7411 });
7412 let Some((name, view)) = entry else {
7413 return loader_throw(scope, "worker loader: malformed wasm module entry");
7414 };
7415 // A name carried by both the JSON map and the side-band would
7416 // silently shadow one module with the other in the registry;
7417 // refuse it the way a non-string JSON module is refused.
7418 if name == main || modules.iter().any(|(existing, _)| *existing == name) {
7419 return loader_throw(
7420 scope,
7421 &format!("worker loader: duplicate module name {name:?}"),
7422 );
7423 }
7424 let mut bytes = vec![0u8; view.byte_length()];
7425 view.copy_contents(&mut bytes);
7426 modules.push((name, ModuleSource::Wasm(bytes.into())));
7427 }
7428 }
7429 // Total module bytes, checked before compiling anything (the oversized
7430 // module is never parsed) — the extra modules are not yet loaded but do
7431 // count against the ceiling, as upstream.
7432 let code_size: usize = src.len()
7433 + modules
7434 .iter()
7435 .map(|(_, source)| match source {
7436 ModuleSource::Text(source) | ModuleSource::EsModule(source) => source.len(),
7437 ModuleSource::Wasm(bytes) => bytes.len(),
7438 })
7439 .sum::<usize>();
7440 if code_size > MAX_DYNAMIC_WORKER_CODE_SIZE {
7441 return loader_throw(
7442 scope,
7443 &format!(
7444 "Dynamic Worker code size ({code_size} bytes) exceeds the \
7445 maximum allowed size of {MAX_DYNAMIC_WORKER_CODE_SIZE} bytes."
7446 ),
7447 );
7448 }
7449 // The environment crosses as structured-clone bytes. Service Binding
7450 // capabilities use a separate host-minted route table, so application
7451 // data can select only a route that the parent already supplied.
7452 let env_arg = args.get(4);
7453 let loader_env = if env_arg.is_undefined() {
7454 None
7455 } else {
7456 let Some(bytes) = view_bytes(env_arg) else {
7457 return loader_throw(scope, "worker loader: env is not a typed array");
7458 };
7459 let routes_arg = args.get(5);
7460 let Ok(route_entries) = v8::Local::<v8::Array>::try_from(routes_arg) else {
7461 return loader_throw(scope, "worker loader: env routes are not an array");
7462 };
7463 let mut routes = Vec::with_capacity(route_entries.length() as usize);
7464 let mut total_size = bytes.len();
7465 for index in 0..route_entries.length() {
7466 let Some(entry) = route_entries
7467 .get_index(scope, index)
7468 .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
7469 else {
7470 return loader_throw(scope, "worker loader: malformed env capability route");
7471 };
7472 let Some(script_value) = entry.get_index(scope, 0).filter(|value| value.is_string())
7473 else {
7474 return loader_throw(scope, "worker loader: malformed env capability script");
7475 };
7476 let Some(entrypoint_value) = entry.get_index(scope, 1) else {
7477 return loader_throw(scope, "worker loader: malformed env capability entrypoint");
7478 };
7479 let entrypoint = if entrypoint_value.is_null_or_undefined() {
7480 None
7481 } else if entrypoint_value.is_string() {
7482 Some(entrypoint_value.to_rust_string_lossy(scope))
7483 } else {
7484 return loader_throw(scope, "worker loader: malformed env capability entrypoint");
7485 };
7486 let Some(props_value) = entry.get_index(scope, 2) else {
7487 return loader_throw(scope, "worker loader: malformed env capability props");
7488 };
7489 let Some(props) = view_bytes(props_value) else {
7490 return loader_throw(scope, "worker loader: env capability props are not bytes");
7491 };
7492 total_size = total_size.saturating_add(props.len());
7493 routes.push(LoaderEnvRoute {
7494 script: script_value.to_rust_string_lossy(scope),
7495 entrypoint,
7496 props,
7497 });
7498 }
7499 if total_size > MAX_DYNAMIC_WORKER_ENV_SIZE {
7500 return loader_throw(
7501 scope,
7502 &format!(
7503 "Dynamic Worker env size ({total_size} bytes) exceeds the maximum \
7504 allowed size of {MAX_DYNAMIC_WORKER_ENV_SIZE} bytes.",
7505 ),
7506 );
7507 }
7508 Some(LoaderEnv { bytes, routes })
7509 };
7510 // The harness removes the live Fetcher from the JSON and sends only the
7511 // route that its private WeakMap minted. This op supplies the generation,
7512 // so neither application data nor a stale child can select another graph.
7513 #[derive(serde::Deserialize)]
7514 struct BrokerRoute {
7515 script: String,
7516 entrypoint: Option<String>,
7517 }
7518 let outbound = args.get(2);
7519 let outbound_props = args.get(3);
7520 let egress = if outbound.is_undefined() {
7521 actor_runtime_state(scope).egress.clone()
7522 } else if outbound.is_null() {
7523 EgressPolicy::Deny
7524 } else {
7525 let route: BrokerRoute = match serde_json::from_str(&outbound.to_rust_string_lossy(scope)) {
7526 Ok(route) => route,
7527 Err(error) => {
7528 return loader_throw(
7529 scope,
7530 &format!("worker loader: malformed globalOutbound route: {error}"),
7531 )
7532 }
7533 };
7534 let props = match view_bytes(outbound_props) {
7535 Some(props) => props,
7536 None => {
7537 return loader_throw(
7538 scope,
7539 "worker loader: globalOutbound props are not a typed array",
7540 )
7541 }
7542 };
7543 let entrypoint = match route.entrypoint {
7544 Some(name) => Some(crate::WorkerFetchEntrypoint { name, props }),
7545 None if props.is_empty() => None,
7546 None => {
7547 return loader_throw(
7548 scope,
7549 "worker loader: globalOutbound props require an entrypoint",
7550 )
7551 }
7552 };
7553 EgressPolicy::Broker(OutboundBroker {
7554 generation,
7555 script: route.script,
7556 entrypoint,
7557 })
7558 };
7559 let owner = scope
7560 .get_slot::<LoaderOwner>()
7561 .expect("Worker isolate has a Loader owner")
7562 .clone();
7563 // Honor the WorkerCode's declared compatibility (workerd worker_compat
7564 // reads snake_case keys); Code Mode workers keep RPC on regardless.
7565 let mut compat = crate::worker_compat(&serde_json::json!({
7566 "compatibility_date": code.get("compatibilityDate"),
7567 "compatibility_flags": code.get("compatibilityFlags"),
7568 }));
7569 compat.js_rpc = true;
7570 let handle = match tokio::runtime::Handle::try_current() {
7571 Ok(handle) => handle,
7572 Err(error) => return loader_throw(scope, &format!("worker loader: {error}")),
7573 };
7574 let (loaded, state) = tokio::sync::watch::channel(LoaderState::Loading);
7575 let id = match admit_loaded_worker(owner, state) {
7576 Ok(id) => id,
7577 Err(error) => return loader_throw(scope, &error),
7578 };
7579 let config = Arc::new(
7580 WorkerConfig::new(WorkerConfigOptions {
7581 src,
7582 script_name: format!("__loader:{id}"),
7583 do_classes: Vec::new(),
7584 bindings: Vec::new(),
7585 r2_bindings: Vec::new(),
7586 // A loaded worker reaches D1 only if its parent injects a stub;
7587 // ambient bindings are exactly what Code Mode withholds.
7588 d1_bindings: Vec::new(),
7589 kv_bindings: Vec::new(),
7590 queue_bindings: Vec::new(),
7591 queue_consumers: Vec::new(),
7592 workflow_bindings: Vec::new(),
7593 vars: Vec::new(),
7594 node: String::new(),
7595 modules,
7596 compat,
7597 })
7598 .into_dynamic_worker()
7599 .with_main_module_name(main.to_string())
7600 .with_generation(generation)
7601 .with_egress(egress)
7602 .with_resource_limits(limits)
7603 .with_tail_reporting(tail_reporting)
7604 .with_loader_env(loader_env),
7605 );
7606 handle.spawn(async move {
7607 let state = match tokio::task::spawn_blocking(move || Worker::load_config(config)).await {
7608 Ok(Ok(worker)) => LoaderState::Ready(crate::pool::Slot::standalone(worker)),
7609 Ok(Err(error)) => LoaderState::Failed(Arc::from(format!("{error}"))),
7610 Err(error) => LoaderState::Failed(Arc::from(format!(
7611 "worker loader: load task failed: {error}"
7612 ))),
7613 };
7614 loaded.send_replace(state);
7615 });
7616 rv.set(v8::Number::new(scope, id as f64).into());
7617}
7618
7619/// `__loader_fetch(id, url, method, body, headersJson, streamId, entrypoint,
7620/// propsSc, limitsJson, tailReporting)` -> Promise<json> or
7621/// [Promise<json>, Promise<json>].
7622/// The loaded-worker analog of `__svc_call`: it encodes the response the same
7623/// way and can return a separate report after the invocation finishes.
7624fn op_loader_fetch(
7625 scope: &mut v8::PinScope,
7626 args: v8::FunctionCallbackArguments,
7627 mut rv: v8::ReturnValue<v8::Value>,
7628) {
7629 let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
7630 let url = args.get(1).to_rust_string_lossy(scope);
7631 let method = args.get(2).to_rust_string_lossy(scope);
7632 let entrypoint = args.get(6);
7633 if !entrypoint.is_string() {
7634 return loader_throw(scope, "worker loader: the entrypoint is not a string");
7635 }
7636 let entrypoint = entrypoint.to_rust_string_lossy(scope);
7637 let props = match loader_props_bytes(args.get(7)) {
7638 Ok(props) => props,
7639 Err(error) => return loader_throw(scope, &error),
7640 };
7641 let invocation_limits = match loader_invocation_limits(scope, args.get(8)) {
7642 Ok(limits) => limits,
7643 Err(error) => return loader_throw(scope, &error),
7644 };
7645 // The Worker already stores its default handler, including the synthetic
7646 // missing-handler function for a class-only module. A named entrypoint
7647 // must instead use the harness dispatcher, so an absent name fails rather
7648 // than falling back to the default export. A props-carrying default fetch
7649 // also needs that dispatcher because the direct path cannot install props.
7650 let entrypoint =
7651 (entrypoint != "default" || !props.is_empty()).then_some(crate::WorkerFetchEntrypoint {
7652 name: entrypoint,
7653 props,
7654 });
7655 let stream_arg = args.get(5);
7656 let body = if stream_arg.is_number() {
7657 RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64)
7658 } else {
7659 let Some(bytes) = view_bytes(args.get(3)) else {
7660 return loader_throw(
7661 scope,
7662 "worker loader: the request body is not a typed array",
7663 );
7664 };
7665 RequestBody::Bytes(bytes.into())
7666 };
7667 let headers: Vec<(String, String)> =
7668 match serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)) {
7669 Ok(headers) => headers,
7670 Err(error) => {
7671 return loader_throw(
7672 scope,
7673 &format!(
7674 "worker loader: the request headers are not a name/value list: {error}"
7675 ),
7676 )
7677 }
7678 };
7679 let want_tail_report = args.get(9).boolean_value(scope);
7680 let (tail_report, tail_receive) = if want_tail_report {
7681 let (send, receive) = tokio::sync::oneshot::channel();
7682 (Some(send), Some(receive))
7683 } else {
7684 (None, None)
7685 };
7686 let mut body_guard = match body.stream_id() {
7687 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
7688 Some(guard) => guard,
7689 None => return loader_throw(scope, "worker loader: the body stream is not owned"),
7690 },
7691 None => RequestBodyGuard::of(&body),
7692 };
7693 let loaded = loader_registry()
7694 .lock()
7695 .unwrap()
7696 .get(&id)
7697 .map(|entry| entry.state.clone());
7698 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
7699 let stream_service = http_stream_service();
7700 let async_id = asyncrt::enqueue(async move {
7701 // The child's own `IoContext` has an empty egress stack, so nothing
7702 // inside it gates what it sends onward. Holding the call until the
7703 // caller's writes are proven makes every effect of the loaded worker
7704 // trail that proof, as a service-binding call already does.
7705 await_egress_gate(gate).await?;
7706 let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?;
7707 let slot = loaded_worker_slot(state).await?;
7708 let (reply, receive) = tokio::sync::oneshot::channel();
7709 let job = crate::WorkerJob::Fetch {
7710 queued_at: Instant::now(),
7711 entrypoint,
7712 invocation_limits,
7713 url,
7714 method,
7715 body,
7716 headers,
7717 // A loaded Worker receives an incoming request like a service
7718 // target does. The id selects the stream-aware construction path
7719 // and gives an abandoned request a lifecycle owner.
7720 request_id: Some(next_request_id()),
7721 tail_report,
7722 reply,
7723 };
7724 let driving = tokio::spawn(crate::runtime::drive(slot, job, None));
7725 match receive.await {
7726 Ok(Ok(response)) => {
7727 // The response proves that the loaded Worker installed its
7728 // request context. That context owns an unread body tail
7729 // through its waitUntil work.
7730 body_guard.disarm();
7731 encode_http_response(response, false, &stream_service)
7732 }
7733 Ok(Err(error)) => Err(format!("{error}")),
7734 Err(_) => match driving.await {
7735 Err(error) => Err(format!("loaded worker task died: {error}")),
7736 Ok(()) => Err("loaded worker dropped response".to_string()),
7737 },
7738 }
7739 });
7740 let response = promise_for(scope, async_id);
7741 let Some(tail_receive) = tail_receive else {
7742 rv.set(response);
7743 return;
7744 };
7745 let report_id = asyncrt::enqueue(async move {
7746 tail_receive
7747 .await
7748 .map_err(|error| format!("loaded worker dropped tail report: {error}"))
7749 });
7750 let report = promise_for(scope, report_id);
7751 let pair = v8::Array::new_with_elements(scope, &[response, report]);
7752 rv.set(pair.into());
7753}
7754
7755/// `__loader_rpc(id, entrypoint, method, argsSc, propsSc, limitsJson)` ->
7756/// Promise<Uint8Array>. The loaded-worker analog of `__svc_rpc`: a
7757/// named-entrypoint method call whose args and result are V8 structured-clone
7758/// bytes. `propsSc` carries `getEntrypoint(name, {props})` to the callee's
7759/// `ctx.props` in the same encoding; it is empty for no props.
7760fn op_loader_rpc(
7761 scope: &mut v8::PinScope,
7762 args: v8::FunctionCallbackArguments,
7763 mut rv: v8::ReturnValue<v8::Value>,
7764) {
7765 let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
7766 let entrypoint = args.get(1).to_rust_string_lossy(scope);
7767 let method = args.get(2).to_rust_string_lossy(scope);
7768 let call_args = view_bytes(args.get(3)).unwrap_or_default();
7769 let props = match loader_props_bytes(args.get(4)) {
7770 Ok(props) => props,
7771 Err(error) => return loader_throw(scope, &error),
7772 };
7773 let invocation_limits = match loader_invocation_limits(scope, args.get(5)) {
7774 Ok(limits) => limits,
7775 Err(error) => return loader_throw(scope, &error),
7776 };
7777 // The props ride on `WorkerJob::Rpc` for the whole call, so an unbounded
7778 // value is an unbounded per-call allocation in the host. The harness checks
7779 // nothing here: it runs in the calling worker's isolate beside the
7780 // application's code, so only this op can bound the value.
7781 let loaded = loader_registry()
7782 .lock()
7783 .unwrap()
7784 .get(&id)
7785 .map(|entry| entry.state.clone());
7786 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
7787 let async_id = asyncrt::enqueue(async move {
7788 // The same rule as `op_loader_fetch`: the call carries cell state.
7789 await_egress_gate(gate).await?;
7790 let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?;
7791 let slot = loaded_worker_slot(state).await?;
7792 let (reply, receive) = tokio::sync::oneshot::channel();
7793 let job = crate::WorkerJob::Rpc {
7794 entrypoint,
7795 operation: crate::WorkerRpcOperation::Call {
7796 path: vec![method],
7797 args: call_args,
7798 },
7799 props,
7800 invocation_limits,
7801 reply,
7802 };
7803 let driving = tokio::spawn(crate::runtime::drive(slot, job, None));
7804 match receive.await {
7805 Ok(Ok(result)) => Ok(result),
7806 Ok(Err(error)) => Err(format!("{error}")),
7807 Err(_) => match driving.await {
7808 Err(error) => Err(format!("loaded worker task died: {error}")),
7809 Ok(()) => Err("loaded worker dropped RPC result".to_string()),
7810 },
7811 }
7812 });
7813 rv.set(promise_for(scope, async_id));
7814}
7815
7816fn facet_scope(class_name: &str, parent_scope: &str, owner: &str, name: &str) -> String {
7817 use sha2::Digest as _;
7818 let mut digest = sha2::Sha256::new();
7819 digest.update(parent_scope.as_bytes());
7820 digest.update([0]);
7821 digest.update(owner.as_bytes());
7822 digest.update([0]);
7823 digest.update(name.as_bytes());
7824 let digest: [u8; 32] = digest.finalize().into();
7825 format!("{class_name}:{}", durable_object_id_hex(&digest))
7826}
7827
7828/// Activate a facet's stream through the host loop, which owns the
7829/// replicator, and answer its database file and whether it was restored.
7830async fn open_facet_file(
7831 parent: &storage::StorageIdentity,
7832 name: &str,
7833) -> Result<(std::path::PathBuf, bool), String> {
7834 let mut names = parent.facet_path.clone();
7835 names.push(name.to_string());
7836 let Some(sender) = FACET_TX.get() else {
7837 // No host loop runs the replicator, so the file sits beside the
7838 // root's database and is named after it, as workerd names a facet
7839 // `<id>.<facet>.sqlite`.
7840 let stream = crate::engine_api::facet_cell(&parent.root_scope, &names);
7841 let facet = stream[parent.root_scope.len()..]
7842 .trim_start_matches('/')
7843 .replace('/', "-");
7844 let root = std::path::Path::new(&parent.root_path);
7845 let file = root.file_name().unwrap().to_string_lossy();
7846 return Ok((root.with_file_name(format!("{file}.{facet}.sqlite")), false));
7847 };
7848 let (reply, receive) = tokio::sync::oneshot::channel();
7849 let request = FacetReq::Open {
7850 root: parent.root_scope.clone(),
7851 epoch: parent.epoch,
7852 names,
7853 reply,
7854 };
7855 sender
7856 .send(request)
7857 .map_err(|_| "the facet channel closed".to_string())?;
7858 receive
7859 .await
7860 .map_err(|_| "the facet open was dropped".to_string())?
7861 .map_err(|error| format!("open the facet database: {error:#}"))
7862}
7863
7864struct FacetStart {
7865 class_name: String,
7866 parent_scope: String,
7867 owner: String,
7868 name: String,
7869 id: String,
7870 props_sc: Vec<u8>,
7871 parent: storage::StorageIdentity,
7872}
7873
7874/// A facet ready for one call, with what its reply must wait for.
7875struct LoadedFacet {
7876 slot: Arc<crate::pool::Slot>,
7877 scope: String,
7878 stream: String,
7879 epoch: u64,
7880}
7881
7882impl LoadedFacet {
7883 /// A facet's reply leaves as workerd's facet output gate lets it: after
7884 /// every write the facet committed is durable on its own stream. That
7885 /// covers an earlier call's write this reply can reveal as well as the
7886 /// call's own, and an error reply as well as a result.
7887 async fn gate_reply(&self) -> Result<(), String> {
7888 prove_facet(self.stream.clone(), self.epoch)
7889 .await
7890 .map_err(|refusal| format!("facet reply: {refusal}"))
7891 }
7892}
7893
7894/// The loader id of a class from the script's own `ctx.exports`. Loaded
7895/// Workers' ids start at 1.
7896const OWN_SCRIPT_LOADER: u64 = 0;
7897
7898/// The isolate a facet's class runs in: a loaded Worker's, or, for a class
7899/// of the root's own script, the root's own, as workerd runs it.
7900enum FacetHost {
7901 Loaded(tokio::sync::watch::Receiver<LoaderState>),
7902 Own(Arc<crate::pool::Slot>),
7903}
7904
7905impl FacetHost {
7906 /// Resolved in the op, while the root's turn names its slot.
7907 fn of(loader: u64) -> Result<Self, String> {
7908 if loader == OWN_SCRIPT_LOADER {
7909 return crate::pool::current_slot()
7910 .map(Self::Own)
7911 .ok_or_else(|| "facet: no isolate runs this turn".to_string());
7912 }
7913 loader_registry()
7914 .lock()
7915 .unwrap()
7916 .get(&loader)
7917 .map(|entry| Self::Loaded(entry.state.clone()))
7918 .ok_or_else(|| "worker loader: unknown worker".to_string())
7919 }
7920
7921 async fn slot(self) -> Result<Arc<crate::pool::Slot>, String> {
7922 match self {
7923 Self::Loaded(loaded) => loaded_worker_slot(loaded).await,
7924 Self::Own(slot) => Ok(slot),
7925 }
7926 }
7927}
7928
7929async fn prepare_facet(host: FacetHost, start: FacetStart) -> Result<LoadedFacet, String> {
7930 let slot = host.slot().await?;
7931 let file = open_facet_file(&start.parent, &start.name).await?;
7932 let mut names = start.parent.facet_path.clone();
7933 names.push(start.name.clone());
7934 let stream = crate::engine_api::facet_cell(&start.parent.root_scope, &names);
7935 let epoch = start.parent.epoch;
7936 let scope = facet_scope(
7937 &start.class_name,
7938 &start.parent_scope,
7939 &start.owner,
7940 &start.name,
7941 );
7942 slot.turn(|worker| {
7943 worker.own_embedded_cell(
7944 &scope,
7945 &start.parent,
7946 &start.name,
7947 &start.id,
7948 start.props_sc,
7949 file,
7950 )
7951 })
7952 .await
7953 .map_err(|error| format!("worker loader facet: {error}"))?;
7954 Ok(LoadedFacet {
7955 slot,
7956 scope,
7957 stream,
7958 epoch,
7959 })
7960}
7961
7962fn op_facet_rpc(
7963 scope: &mut v8::PinScope,
7964 args: v8::FunctionCallbackArguments,
7965 mut rv: v8::ReturnValue<v8::Value>,
7966) {
7967 let loader = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
7968 let class_name = args.get(1).to_rust_string_lossy(scope);
7969 let parent_scope = args.get(2).to_rust_string_lossy(scope);
7970 let owner = args.get(3).to_rust_string_lossy(scope);
7971 let name = args.get(4).to_rust_string_lossy(scope);
7972 let facet_id = args.get(5).to_rust_string_lossy(scope);
7973 let props_sc = match loader_props_bytes(args.get(6)) {
7974 Ok(props) => props,
7975 Err(error) => return loader_throw(scope, &error),
7976 };
7977 let method = args.get(7).to_rust_string_lossy(scope);
7978 let call_args = view_bytes(args.get(8)).unwrap_or_default();
7979 let parent = match storage::storage_identity(&parent_scope) {
7980 Ok(Some(parent)) => parent,
7981 Ok(None) => {
7982 return loader_throw(
7983 scope,
7984 "facets are available only inside a Durable Object event",
7985 )
7986 }
7987 Err(error) => return loader_throw(scope, &error.to_string()),
7988 };
7989 let host = FacetHost::of(loader);
7990 let trace = current_trace_context(scope);
7991 let async_id = asyncrt::enqueue(async move {
7992 let facet = prepare_facet(
7993 host?,
7994 FacetStart {
7995 class_name,
7996 parent_scope,
7997 owner,
7998 name,
7999 id: facet_id,
8000 props_sc,
8001 parent,
8002 },
8003 )
8004 .await?;
8005 let (reply, receive) = tokio::sync::oneshot::channel();
8006 let job = CellJob::Rpc {
8007 request_id: None,
8008 scope: facet.scope.clone(),
8009 name: None,
8010 method,
8011 args: RpcData::V8(call_args.into()),
8012 reply,
8013 };
8014 let driving = tokio::spawn(crate::runtime::drive_cell(
8015 facet.slot.affiliate(),
8016 job,
8017 None,
8018 trace,
8019 ));
8020 let replied = receive.await;
8021 if replied.is_ok() {
8022 facet.gate_reply().await?;
8023 }
8024 match replied {
8025 Ok(Ok(outcome)) => match outcome.data {
8026 RpcData::V8(bytes) => {
8027 facet.gate_reply().await?;
8028 Ok(Vec::<u8>::from(bytes))
8029 }
8030 RpcData::Json(_) => Err("facet RPC answered JSON".to_string()),
8031 },
8032 Ok(Err(error)) => Err(format!("{error}")),
8033 Err(_) => match driving.await {
8034 Err(error) => Err(format!("facet RPC task died: {error}")),
8035 Ok(()) => Err("facet dropped RPC result".to_string()),
8036 },
8037 }
8038 });
8039 rv.set(promise_for(scope, async_id));
8040}
8041
8042fn op_facet_fetch(
8043 scope: &mut v8::PinScope,
8044 args: v8::FunctionCallbackArguments,
8045 mut rv: v8::ReturnValue<v8::Value>,
8046) {
8047 let loader = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8048 let class_name = args.get(1).to_rust_string_lossy(scope);
8049 let parent_scope = args.get(2).to_rust_string_lossy(scope);
8050 let owner = args.get(3).to_rust_string_lossy(scope);
8051 let name = args.get(4).to_rust_string_lossy(scope);
8052 let facet_id = args.get(5).to_rust_string_lossy(scope);
8053 let props_sc = match loader_props_bytes(args.get(6)) {
8054 Ok(props) => props,
8055 Err(error) => return loader_throw(scope, &error),
8056 };
8057 let url = args.get(7).to_rust_string_lossy(scope);
8058 let method = args.get(8).to_rust_string_lossy(scope);
8059 let stream_arg = args.get(11);
8060 let body = if stream_arg.is_number() {
8061 RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64)
8062 } else {
8063 let Some(bytes) = view_bytes(args.get(9)) else {
8064 return loader_throw(scope, "facet: the request body is not a typed array");
8065 };
8066 RequestBody::Bytes(bytes.into())
8067 };
8068 let headers: Vec<(String, String)> =
8069 match serde_json::from_str(&args.get(10).to_rust_string_lossy(scope)) {
8070 Ok(headers) => headers,
8071 Err(error) => return loader_throw(scope, &format!("facet headers: {error}")),
8072 };
8073 let mut body_guard = match body.stream_id() {
8074 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
8075 Some(guard) => guard,
8076 None => return loader_throw(scope, "facet: the body stream is not owned"),
8077 },
8078 None => RequestBodyGuard::of(&body),
8079 };
8080 let parent = match storage::storage_identity(&parent_scope) {
8081 Ok(Some(parent)) => parent,
8082 Ok(None) => {
8083 return loader_throw(
8084 scope,
8085 "facets are available only inside a Durable Object event",
8086 )
8087 }
8088 Err(error) => return loader_throw(scope, &error.to_string()),
8089 };
8090 let host = FacetHost::of(loader);
8091 let trace = current_trace_context(scope);
8092 let stream_service = http_stream_service();
8093 let async_id = asyncrt::enqueue(async move {
8094 let facet = prepare_facet(
8095 host?,
8096 FacetStart {
8097 class_name,
8098 parent_scope,
8099 owner,
8100 name,
8101 id: facet_id,
8102 props_sc,
8103 parent,
8104 },
8105 )
8106 .await?;
8107 let (reply, receive) = tokio::sync::oneshot::channel();
8108 let job = CellJob::Fetch {
8109 request_id: None,
8110 scope: facet.scope.clone(),
8111 name: None,
8112 url,
8113 method,
8114 body,
8115 headers,
8116 reply,
8117 order: None,
8118 };
8119 let driving = tokio::spawn(crate::runtime::drive_cell(
8120 facet.slot.affiliate(),
8121 job,
8122 None,
8123 trace,
8124 ));
8125 let replied = receive.await;
8126 if replied.is_ok() {
8127 facet.gate_reply().await?;
8128 }
8129 match replied {
8130 Ok(Ok(response)) => {
8131 body_guard.disarm();
8132 facet.gate_reply().await?;
8133 encode_http_response(response, false, &stream_service)
8134 }
8135 Ok(Err(error)) => Err(format!("{error}")),
8136 Err(_) => match driving.await {
8137 Err(error) => Err(format!("facet fetch task died: {error}")),
8138 Ok(()) => Err("facet dropped fetch response".to_string()),
8139 },
8140 }
8141 });
8142 rv.set(promise_for(scope, async_id));
8143}
8144
8145fn op_facet_abort(
8146 scope: &mut v8::PinScope,
8147 args: v8::FunctionCallbackArguments,
8148 mut rv: v8::ReturnValue<v8::Value>,
8149) {
8150 let loader = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8151 let class_name = args.get(1).to_rust_string_lossy(scope);
8152 let parent_scope = args.get(2).to_rust_string_lossy(scope);
8153 let owner = args.get(3).to_rust_string_lossy(scope);
8154 let name = args.get(4).to_rust_string_lossy(scope);
8155 let host = FacetHost::of(loader);
8156 let facet_scope = facet_scope(&class_name, &parent_scope, &owner, &name);
8157 let async_id = asyncrt::enqueue(async move {
8158 let slot = host?.slot().await?;
8159 slot.turn(|worker| worker.own_cell(&facet_scope, None))
8160 .await
8161 .map_err(|error| format!("abort facet: {error}"))?;
8162 Ok(Vec::new())
8163 });
8164 rv.set(promise_for(scope, async_id));
8165}
8166
8167fn op_facet_delete(
8168 scope: &mut v8::PinScope,
8169 args: v8::FunctionCallbackArguments,
8170 mut rv: v8::ReturnValue<v8::Value>,
8171) {
8172 let parent_scope = args.get(0).to_rust_string_lossy(scope);
8173 let name = args.get(1).to_rust_string_lossy(scope);
8174 let parent = match storage::storage_identity(&parent_scope) {
8175 Ok(Some(parent)) => parent,
8176 Ok(None) => {
8177 return loader_throw(
8178 scope,
8179 "facets are available only inside a Durable Object event",
8180 )
8181 }
8182 Err(error) => return loader_throw(scope, &error.to_string()),
8183 };
8184 if let Err(error) = storage::delete_legacy_facet(&parent, &name) {
8185 return loader_throw(scope, &format!("delete facet storage: {error}"));
8186 }
8187 let mut names = parent.facet_path.clone();
8188 names.push(name);
8189 let async_id = asyncrt::enqueue(async move {
8190 let Some(sender) = FACET_TX.get() else {
8191 let (path, _) = open_facet_file(&parent, names.last().unwrap()).await?;
8192 for suffix in ["", "-wal", "-shm"] {
8193 let mut file = path.clone().into_os_string();
8194 file.push(suffix);
8195 let _ = asyncrt::fs().remove_file(std::path::Path::new(&file));
8196 }
8197 return Ok(Vec::new());
8198 };
8199 let (reply, receive) = tokio::sync::oneshot::channel();
8200 let request = FacetReq::Delete {
8201 root: parent.root_scope,
8202 epoch: parent.epoch,
8203 names,
8204 reply,
8205 };
8206 sender
8207 .send(request)
8208 .map_err(|_| "the facet channel closed".to_string())?;
8209 receive
8210 .await
8211 .map_err(|_| "the facet delete was dropped".to_string())?
8212 .map_err(|error| format!("delete facet storage: {error:#}"))?;
8213 Ok(Vec::new())
8214 });
8215 rv.set(promise_for(scope, async_id));
8216}
8217
8218/// `__loader_drop(id)` — evict a loaded worker. Called from a
8219/// FinalizationRegistry when its stub is GC'd. Removing the registry entry
8220/// drops the isolate after any calls that already cloned its load state end.
8221fn op_loader_drop(
8222 scope: &mut v8::PinScope,
8223 args: v8::FunctionCallbackArguments,
8224 _rv: v8::ReturnValue<v8::Value>,
8225) {
8226 let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8227 if let Some(entry) = loader_registry().lock().unwrap().remove(&id) {
8228 // This op runs while the parent isolate is entered. The load state can
8229 // own the loaded isolate, and V8 forbids dropping one isolate while a
8230 // different isolate is entered on the same thread. Hand the final
8231 // reference to the host scheduler so destruction happens after this
8232 // turn has left V8.
8233 asyncrt::op_handle().spawn(async move { drop(entry.state) });
8234 }
8235}
8236
8237fn op_do_call(
8238 scope: &mut v8::PinScope,
8239 args: v8::FunctionCallbackArguments,
8240 mut rv: v8::ReturnValue<v8::Value>,
8241) {
8242 op_do_call_impl(scope, args, &mut rv, false);
8243}
8244
8245fn op_do_call_cancellable(
8246 scope: &mut v8::PinScope,
8247 args: v8::FunctionCallbackArguments,
8248 mut rv: v8::ReturnValue<v8::Value>,
8249) {
8250 op_do_call_impl(scope, args, &mut rv, true);
8251}
8252
8253fn op_do_call_impl(
8254 scope: &mut v8::PinScope,
8255 args: v8::FunctionCallbackArguments,
8256 rv: &mut v8::ReturnValue<v8::Value>,
8257 cancellable: bool,
8258) {
8259 let cell = args.get(0).to_rust_string_lossy(scope);
8260 let name_value = args.get(1);
8261 let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
8262 let url = args.get(2).to_rust_string_lossy(scope);
8263 let method = args.get(3).to_rust_string_lossy(scope);
8264 // arg 4 is the held bytes; arg 6, when a number, is a host stream id for a
8265 // body that must not be collected here (a large or unbounded upload). The
8266 // owning cell reads that stream directly; only a cross-node hop collects it.
8267 let stream_arg = args.get(6);
8268 let body = if stream_arg.is_number() {
8269 RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64)
8270 } else {
8271 let Some(bytes) = view_bytes(args.get(4)) else {
8272 return loader_throw(
8273 scope,
8274 "durable object: the request body is not a typed array",
8275 );
8276 };
8277 RequestBody::Bytes(bytes.into())
8278 };
8279 let headers: Vec<(String, String)> =
8280 match serde_json::from_str(&args.get(5).to_rust_string_lossy(scope)) {
8281 Ok(headers) => headers,
8282 Err(error) => {
8283 return loader_throw(
8284 scope,
8285 &format!(
8286 "durable object: the request headers are not a name/value list: {error}"
8287 ),
8288 )
8289 }
8290 };
8291 let body_guard = match body.stream_id() {
8292 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
8293 Some(guard) => guard,
8294 None => return loader_throw(scope, "durable object: the body stream is not owned"),
8295 },
8296 None => RequestBodyGuard::of(&body),
8297 };
8298 let (tx, rx) = tokio::sync::oneshot::channel();
8299 // Taken here and nowhere later: this is the last point that still runs
8300 // in the order the script made the calls.
8301 let order = Some(enter_call_order(current_context(), &cell));
8302 // Every host op needs an internal cancellation channel. A caller without
8303 // an AbortSignal cannot cancel from JavaScript, but its enclosing Worker
8304 // can still disappear and drop this op before routing completes.
8305 let request_id = next_do_request_id();
8306 let (cancel_sender, cancel) = tokio::sync::oneshot::channel();
8307 do_call_cancels()
8308 .lock()
8309 .unwrap()
8310 .insert(request_id, cancel_sender);
8311 let mut cancel_guard = DoCallCancelGuard::new(request_id);
8312 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::CellRpc);
8313 let request = DoCallReq {
8314 request_id: Some(request_id),
8315 cancel: Some(cancel),
8316 deliver_abort_to_handler: cancellable,
8317 scope: cell,
8318 name,
8319 url,
8320 method,
8321 body,
8322 body_guard,
8323 headers,
8324 reply: tx,
8325 order,
8326 parent: current_trace_context(scope),
8327 };
8328 let stream_service = http_stream_service();
8329 let id = asyncrt::enqueue(async move {
8330 gated_channel_send(gate, &DO_CALL_TX, request, "no proxy channel").await?;
8331 let result = match rx.await {
8332 Ok(Ok(response)) => encode_http_response(response, true, &stream_service),
8333 Ok(Err(e)) => Err(format!("{e}")),
8334 Err(e) => Err(format!("proxy dropped: {e}")),
8335 };
8336 cancel_guard.disarm();
8337 result
8338 });
8339 let p = promise_for(scope, id);
8340 if cancellable {
8341 attach_cancel_id(scope, p, request_id);
8342 }
8343 rv.set(p);
8344}
8345
8346fn op_do_call_cancel(
8347 scope: &mut v8::PinScope,
8348 args: v8::FunctionCallbackArguments,
8349 _rv: v8::ReturnValue<v8::Value>,
8350) {
8351 let request_id = args.get(0).to_rust_string_lossy(scope);
8352 let Some(request_id) = parse_request_id(&request_id) else {
8353 return;
8354 };
8355 if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request_id) {
8356 let _ = cancel.send(());
8357 }
8358}
8359
8360/// Allocate a process-wide signal identity. The structured-clone RPC envelope
8361/// carries this identity between isolates, and the registry carries the one
8362/// state transition that a snapshot cannot represent.
8363fn op_rpc_signal_new(
8364 scope: &mut v8::PinScope,
8365 _args: v8::FunctionCallbackArguments,
8366 mut rv: v8::ReturnValue<v8::Value>,
8367) {
8368 let signal = next_request_id();
8369 rpc_signals()
8370 .lock()
8371 .unwrap()
8372 .insert(signal, RpcSignalState::Live(HashMap::new()));
8373 let signal = v8::String::new(scope, &request_id_string(signal)).unwrap();
8374 rv.set(signal.into());
8375}
8376
8377fn op_rpc_signal_abort(
8378 scope: &mut v8::PinScope,
8379 args: v8::FunctionCallbackArguments,
8380 _rv: v8::ReturnValue<v8::Value>,
8381) {
8382 let Some(signal) = parse_request_id(&args.get(0).to_rust_string_lossy(scope)) else {
8383 return;
8384 };
8385 let reason = view_bytes(args.get(1)).unwrap_or_default();
8386 let subscribers = {
8387 let mut signals = rpc_signals().lock().unwrap();
8388 let Some(state) = signals.get_mut(&signal) else {
8389 return;
8390 };
8391 match std::mem::replace(state, RpcSignalState::Aborted(reason.clone())) {
8392 RpcSignalState::Live(subscribers) => subscribers,
8393 RpcSignalState::Aborted(prior) => {
8394 *state = RpcSignalState::Aborted(prior);
8395 return;
8396 }
8397 }
8398 };
8399 for subscriber in subscribers.into_values() {
8400 let _ = subscriber.send(Some(reason.clone()));
8401 }
8402}
8403
8404fn op_rpc_signal_release(
8405 scope: &mut v8::PinScope,
8406 args: v8::FunctionCallbackArguments,
8407 _rv: v8::ReturnValue<v8::Value>,
8408) {
8409 let Some(signal) = parse_request_id(&args.get(0).to_rust_string_lossy(scope)) else {
8410 return;
8411 };
8412 let state = rpc_signals().lock().unwrap().remove(&signal);
8413 if let Some(RpcSignalState::Live(subscribers)) = state {
8414 for subscriber in subscribers.into_values() {
8415 let _ = subscriber.send(None);
8416 }
8417 }
8418}
8419
8420fn op_rpc_signal_unsubscribe(
8421 scope: &mut v8::PinScope,
8422 args: v8::FunctionCallbackArguments,
8423 _rv: v8::ReturnValue<v8::Value>,
8424) {
8425 let Some(signal) = parse_request_id(&args.get(0).to_rust_string_lossy(scope)) else {
8426 return;
8427 };
8428 let Some(subscription) = parse_request_id(&args.get(1).to_rust_string_lossy(scope)) else {
8429 return;
8430 };
8431 if let Some(RpcSignalState::Live(subscribers)) = rpc_signals().lock().unwrap().get_mut(&signal)
8432 {
8433 subscribers.remove(&subscription);
8434 }
8435}
8436
8437fn op_rpc_signal_poll(
8438 scope: &mut v8::PinScope,
8439 args: v8::FunctionCallbackArguments,
8440 mut rv: v8::ReturnValue<v8::Value>,
8441) {
8442 let Some(signal) = parse_request_id(&args.get(0).to_rust_string_lossy(scope)) else {
8443 return;
8444 };
8445 let signals = rpc_signals().lock().unwrap();
8446 match signals.get(&signal) {
8447 Some(RpcSignalState::Aborted(reason)) => {
8448 rv.set(bytes_value(scope, reason.clone()));
8449 }
8450 Some(RpcSignalState::Live(_)) => {}
8451 None => rv.set(v8::null(scope).into()),
8452 }
8453}
8454
8455fn op_rpc_signal_wait(
8456 scope: &mut v8::PinScope,
8457 args: v8::FunctionCallbackArguments,
8458 mut rv: v8::ReturnValue<v8::Value>,
8459) {
8460 let signal_text = args.get(0).to_rust_string_lossy(scope);
8461 let Some(signal) = parse_request_id(&signal_text) else {
8462 return loader_throw(scope, "invalid RPC AbortSignal id");
8463 };
8464 let subscription = next_request_id();
8465 let (tx, rx) = tokio::sync::oneshot::channel();
8466 let immediate = {
8467 let mut signals = rpc_signals().lock().unwrap();
8468 match signals.get_mut(&signal) {
8469 Some(RpcSignalState::Live(subscribers)) => {
8470 subscribers.insert(subscription, tx);
8471 None
8472 }
8473 Some(RpcSignalState::Aborted(reason)) => Some(Some(reason.clone())),
8474 None => Some(None),
8475 }
8476 };
8477 // The subscription must receive aborts while the handler or `waitUntil`
8478 // work is live, but a listener alone is not pending application work. An
8479 // ordinary handler op pins every successful Durable Object event until
8480 // the source aborts, including events unrelated to the retained signal.
8481 let id = asyncrt::enqueue_unrefed(async move {
8482 let _guard = RpcSignalSubscriptionGuard {
8483 signal,
8484 subscription,
8485 };
8486 let reason = match immediate {
8487 Some(reason) => reason,
8488 None => rx.await.unwrap_or(None),
8489 };
8490 Ok(reason.unwrap_or_default())
8491 });
8492 let promise = promise_for(scope, id);
8493 if let Some(object) = promise.to_object(scope) {
8494 let key = v8::String::new(scope, "__celldRpcSignalSubscription").unwrap();
8495 let value = v8::String::new(scope, &request_id_string(subscription)).unwrap();
8496 object.set(scope, key.into(), value.into());
8497 }
8498 rv.set(promise);
8499}
8500
8501/// `__rpc_call(scope, name, method, argsSc)` -> Promise<Uint8Array>;
8502/// arguments and result are V8 structured-clone bytes.
8503fn op_rpc_call(
8504 scope: &mut v8::PinScope,
8505 args: v8::FunctionCallbackArguments,
8506 mut rv: v8::ReturnValue<v8::Value>,
8507) {
8508 let cell = args.get(0).to_rust_string_lossy(scope);
8509 let name_value = args.get(1);
8510 let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
8511 let method = args.get(2).to_rust_string_lossy(scope);
8512 let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default().into());
8513 let (tx, rx) = tokio::sync::oneshot::channel();
8514 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::CellRpc);
8515 let request = RpcCallReq {
8516 scope: cell,
8517 name,
8518 method,
8519 args,
8520 reply: tx,
8521 };
8522 let id = asyncrt::enqueue(async move {
8523 gated_channel_send(gate, &RPC_CALL_TX, request, "no RPC channel").await?;
8524 match rx.await {
8525 Ok(Ok(RpcData::V8(bytes))) => Ok(Vec::<u8>::from(bytes)),
8526 Ok(Ok(RpcData::Json(_))) => Err("RPC answered JSON to a structured-clone call".into()),
8527 Ok(Err(e)) => Err(format!("{e}")),
8528 Err(e) => Err(format!("RPC proxy dropped: {e}")),
8529 }
8530 });
8531 let p = promise_for(scope, id);
8532 rv.set(p);
8533}
8534
8535/// Outbound `fetch` — the op behind the harness's `fetch()`. Resolves to a JSON
8536/// `{status, body, headers}` string.
8537fn op_fetch(
8538 scope: &mut v8::PinScope,
8539 args: v8::FunctionCallbackArguments,
8540 mut rv: v8::ReturnValue<v8::Value>,
8541) {
8542 let context = event_context(scope);
8543 if let Err(error) = context.charge_subrequest() {
8544 return loader_throw(scope, &error);
8545 }
8546 let egress = actor_runtime_state(scope).egress.clone();
8547 // A loaded worker with globalOutbound: null has no ambient egress: it must
8548 // reach the world through `env` capabilities. Message matches workerd.
8549 if egress == EgressPolicy::Deny {
8550 return loader_throw(
8551 scope,
8552 "This worker is not permitted to access the internet via global \
8553 functions like fetch(). It must use capabilities (such as \
8554 bindings in 'env') to talk to the outside world.",
8555 );
8556 }
8557 let method = args.get(0).to_rust_string_lossy(scope);
8558 let url = args.get(1).to_rust_string_lossy(scope);
8559 // A body is a typed array, as it is for `__svc_call`, `__do_call` and
8560 // `__loader_fetch`. `None` and an empty body are different requests — one
8561 // carries no `Content-Length` — so the absent case stays distinct.
8562 let body_arg = args.get(2);
8563 let stream_arg = args.get(5);
8564 let body: Option<RequestBody> = if body_arg.is_undefined() || body_arg.is_null() {
8565 None
8566 } else if stream_arg.is_number() {
8567 Some(RequestBody::Stream(
8568 stream_arg.number_value(scope).unwrap_or(0.0) as u64,
8569 ))
8570 } else {
8571 match view_bytes(body_arg) {
8572 Some(bytes) => Some(RequestBody::Bytes(bytes.into())),
8573 // Answering an unreadable argument with `None` sent the request
8574 // with no body at all: the peer saw something the Worker never
8575 // asked for, and nothing threw and nothing was logged.
8576 None => return loader_throw(scope, "fetch: the request body is not a typed array"),
8577 }
8578 };
8579 let raw_headers = args.get(3).to_rust_string_lossy(scope);
8580 let mut headers: Vec<(String, String)> = match serde_json::from_str(&raw_headers) {
8581 Ok(headers) => headers,
8582 // Same failure as the body: dropping the headers silently sent an
8583 // unauthenticated, unrouted request in place of the real one.
8584 Err(error) => {
8585 return loader_throw(
8586 scope,
8587 &format!("fetch: the request headers are not a name/value list: {error}"),
8588 )
8589 }
8590 };
8591 let redirect = args.get(4).to_rust_string_lossy(scope);
8592 // The harness passes `true` only when the caller supplied an AbortSignal.
8593 // An absent argument is `false`, so a direct caller gets the uncancellable
8594 // request it asked for.
8595 let cancellable = args.get(6).boolean_value(scope);
8596 let mut body_guard = match body.as_ref().and_then(RequestBody::stream_id) {
8597 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
8598 Some(guard) => guard,
8599 None => return loader_throw(scope, "fetch: the body stream is not owned"),
8600 },
8601 None => RequestBodyGuard(None),
8602 };
8603 // Request validates this value in the harness, but the native op is a
8604 // separate trust boundary. Keep this match exhaustive so a future direct
8605 // caller cannot turn an unknown mode into redirect-following behavior.
8606 match redirect.as_str() {
8607 "follow" | "manual" | "error" => {}
8608 other => return loader_throw(scope, &format!("fetch: unknown redirect mode {other}")),
8609 }
8610 if let EgressPolicy::Broker(broker) = egress {
8611 let (request_id, cancel, cancel_guard) = if cancellable {
8612 let request_id = next_do_request_id();
8613 let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
8614 do_call_cancels()
8615 .lock()
8616 .unwrap()
8617 .insert(request_id, cancel_sender);
8618 (
8619 Some(request_id),
8620 Some(cancel_receiver),
8621 Some(DoCallCancelGuard::new(request_id)),
8622 )
8623 } else {
8624 (None, None, None)
8625 };
8626 let (tx, rx) = tokio::sync::oneshot::channel();
8627 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Fetch);
8628 let request = SvcCallReq {
8629 cancel,
8630 generation: broker.generation,
8631 script: broker.script,
8632 entrypoint: broker.entrypoint,
8633 url,
8634 method,
8635 body: body.unwrap_or_else(|| RequestBody::Bytes(Vec::new().into())),
8636 body_guard,
8637 headers,
8638 reply: tx,
8639 };
8640 let stream_service = http_stream_service();
8641 let id = asyncrt::enqueue(async move {
8642 let mut cancel_guard = cancel_guard;
8643 gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?;
8644 let result = match rx.await {
8645 Ok(Ok(response)) => encode_http_response(response, true, &stream_service),
8646 Ok(Err(error)) => Err(format!("{error}")),
8647 Err(error) => Err(format!("globalOutbound Fetcher dropped: {error}")),
8648 };
8649 if let Some(cancel_guard) = cancel_guard.as_mut() {
8650 cancel_guard.disarm();
8651 }
8652 result
8653 });
8654 let promise = promise_for(scope, id);
8655 if let Some(request_id) = request_id {
8656 attach_cancel_id(scope, promise, request_id);
8657 }
8658 rv.set(promise);
8659 return;
8660 }
8661 // Select the client only for direct egress: a broker must not initialize
8662 // an unused network client and its TLS stack.
8663 let client = match redirect.as_str() {
8664 "follow" if context.subrequest_limit.is_some() => context.redirect_counting_client(),
8665 "follow" => HTTP.with(|client| client.clone()),
8666 "manual" => HTTP_MANUAL.with(|client| client.clone()),
8667 "error" => HTTP_ERROR.with(|client| client.clone()),
8668 _ => unreachable!("the redirect mode was validated above"),
8669 };
8670 // The creating context, read here while JS is still running: the op
8671 // future resolves on whatever worker polls it, far from any CPED.
8672 let trace = current_trace_context(scope);
8673 // The child's ids are minted before the request leaves so the
8674 // traceparent header carries them: whatever this fetch reaches can
8675 // join the trace celld is part of.
8676 let child = trace.as_ref().map(crate::telemetry::child_context);
8677 if let Some(child) = child.as_ref() {
8678 if !headers
8679 .iter()
8680 .any(|(name, _)| name.eq_ignore_ascii_case("traceparent"))
8681 {
8682 headers.push(("traceparent".into(), crate::telemetry::traceparent(child)));
8683 }
8684 }
8685 let recording = trace.and_then(crate::telemetry::TraceContext::recording_ids);
8686 let child_recording = child.and_then(crate::telemetry::TraceContext::recording_ids);
8687 let span_url = recording.map(|_| url.clone());
8688 // Whatever this request can reveal must be durable before it leaves: a
8689 // third party that has acted on a write celld then loses cannot be told to
8690 // un-act. That covers a write this handler made and a value it only read,
8691 // because the third party cannot tell the two apart.
8692 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Fetch);
8693 // Shares the cancel registry, the id encoding and the `__do_call_cancel`
8694 // op that a Durable Object call and a service binding call already use.
8695 // Only a caller that supplied an AbortSignal registers: without one there
8696 // is nothing that can cancel, and the op then costs no registry entry.
8697 let (request_id, cancel, cancel_guard) = if cancellable {
8698 let request_id = next_do_request_id();
8699 let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
8700 do_call_cancels()
8701 .lock()
8702 .unwrap()
8703 .insert(request_id, cancel_sender);
8704 (
8705 Some(request_id),
8706 Some(cancel_receiver),
8707 Some(DoCallCancelGuard::new(request_id)),
8708 )
8709 } else {
8710 (None, None, None)
8711 };
8712 let stream_service = http_stream_service();
8713 let id = asyncrt::enqueue(async move {
8714 // Held, not disarmed: this op has several early returns, and the guard
8715 // removes its registry entry on every one of them when it drops. The
8716 // cancel it sends then reaches a receiver this block already consumed,
8717 // which is the same no-op as a disarm.
8718 let _cancel_guard = cancel_guard;
8719 let span_started = recording.map(|_| crate::telemetry::now_unix_us());
8720 let mut span = recording.zip(child_recording).map(|(parent, child)| {
8721 let mut span =
8722 crate::telemetry::Span::new(child, "fetch", crate::telemetry::KIND_CLIENT);
8723 span.parent_span_id = Some(parent.span_id);
8724 span.parent_remote = Some(false);
8725 span.url = span_url;
8726 span
8727 });
8728 let mut finish = |ok: bool, status: Option<u16>, error: Option<String>| {
8729 if let Some(mut span) = span.take() {
8730 span.start_unix_us = span_started.unwrap_or_default();
8731 span.duration_us = crate::telemetry::now_unix_us() - span.start_unix_us;
8732 span.ok = ok;
8733 span.http_status = status;
8734 span.error = error;
8735 crate::telemetry::record(span);
8736 }
8737 };
8738 await_egress_gate(gate).await.inspect_err(|error| {
8739 finish(false, None, Some(error.clone()));
8740 })?;
8741 let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET);
8742 // a timeout bounds a black-hole host: the future settles (Err) instead
8743 // of parking run_loop forever — the hang the Drop guard can't catch.
8744 let fetch_timeout = crate::env_vars::positive_or("CELLD_FETCH_TIMEOUT_S", 120)
8745 .expect("validated CELLD_FETCH_TIMEOUT_S");
8746 let mut rb = client
8747 .request(m, &url)
8748 .timeout(std::time::Duration::from_secs(fetch_timeout));
8749 // reqwest omits Content-Length for an empty Vec, which collapses the
8750 // wire representation of `Some([])` into the representation of
8751 // `None`. Install the zero length here unless the Worker supplied a
8752 // framing header, so the body distinction survives the HTTP client.
8753 let empty_body_needs_length = body
8754 .as_ref()
8755 .is_some_and(|body| matches!(body, RequestBody::Bytes(bytes) if bytes.is_empty()))
8756 && !headers.iter().any(|(name, _)| {
8757 name.eq_ignore_ascii_case("content-length")
8758 || name.eq_ignore_ascii_case("transfer-encoding")
8759 });
8760 for (name, value) in headers {
8761 rb = rb.header(name, value);
8762 }
8763 if let Some(body) = body {
8764 rb = match body {
8765 RequestBody::Bytes(bytes) => rb.body(bytes),
8766 RequestBody::Stream(stream_id) => match body_guard.take_stream(stream_id) {
8767 Ok(stream) => rb.body(reqwest::Body::wrap_stream(stream)),
8768 Err(error) => {
8769 finish(false, None, Some(error.clone()));
8770 return Err(error);
8771 }
8772 },
8773 };
8774 }
8775 if empty_body_needs_length {
8776 rb = rb.header(reqwest::header::CONTENT_LENGTH, 0);
8777 }
8778 // The cancellable window is the request itself: connect, send, and wait
8779 // for the response head. Dropping the send future here closes the
8780 // connection, which is what tells the upstream to stop producing. After
8781 // this point the response body is a registered stream, and
8782 // `__http_stream_cancel` is what ends it.
8783 let sent = match cancel {
8784 Some(cancel) => crate::asyncrt::select_biased! {
8785 "a cancel that is ready wins a tie, so an aborted request never \
8786 hands back a response and never leaves a body stream nobody reads";
8787 _ = cancel => None,
8788 result = rb.send() => Some(result),
8789 },
8790 None => Some(rb.send().await),
8791 };
8792 let Some(sent) = sent else {
8793 let error = "fetch: the request was aborted".to_string();
8794 finish(false, None, Some(error.clone()));
8795 return Err(error);
8796 };
8797 match sent {
8798 Ok(resp) => {
8799 let status = resp.status().as_u16();
8800 let headers = resp
8801 .headers()
8802 .iter()
8803 .map(|(name, value)| {
8804 (
8805 name.as_str().to_string(),
8806 // A header value is decoded as UTF-8 with
8807 // replacement, as workerd decodes it.
8808 String::from_utf8_lossy(value.as_bytes()).into_owned(),
8809 )
8810 })
8811 .collect::<Vec<_>>();
8812 let Some(stream_id) =
8813 stream_service.register_source(HttpStreamSource::Response(resp))
8814 else {
8815 let error = format!("fetch: {HTTP_STREAM_REGISTRATION_CLOSED}");
8816 finish(false, Some(status), Some(error.clone()));
8817 return Err(error);
8818 };
8819 finish(true, Some(status), None);
8820 Ok(serde_json::json!({
8821 "status": status, "streamId": stream_id, "headers": headers,
8822 })
8823 .to_string())
8824 }
8825 Err(e) => {
8826 let error = fetch_request_error(&e);
8827 finish(false, None, Some(error.clone()));
8828 Err(error)
8829 }
8830 }
8831 });
8832 let p = promise_for(scope, id);
8833 if let Some(request_id) = request_id {
8834 attach_cancel_id(scope, p, request_id);
8835 }
8836 rv.set(p);
8837}
8838
8839fn op_asset_fetch(
8840 scope: &mut v8::PinScope,
8841 args: v8::FunctionCallbackArguments,
8842 mut rv: v8::ReturnValue<v8::Value>,
8843) {
8844 let script = args.get(0).to_rust_string_lossy(scope);
8845 let method = args.get(1).to_rust_string_lossy(scope);
8846 let url = args.get(2).to_rust_string_lossy(scope);
8847 let headers: Vec<(String, String)> =
8848 match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) {
8849 Ok(headers) => headers,
8850 Err(error) => {
8851 return loader_throw(
8852 scope,
8853 &format!("assets: the request headers are not a name/value list: {error}"),
8854 )
8855 }
8856 };
8857 let generation = current_generation(scope);
8858 let (tx, rx) = tokio::sync::oneshot::channel();
8859 let sent = ASSET_CALL_TX.get().is_some_and(|sender| {
8860 sender
8861 .send(AssetCallReq {
8862 generation,
8863 script,
8864 url,
8865 method,
8866 headers,
8867 reply: tx,
8868 })
8869 .is_ok()
8870 });
8871 let stream_service = http_stream_service();
8872 let id = asyncrt::enqueue(async move {
8873 if !sent {
8874 return Err("no asset resolver channel".to_string());
8875 }
8876 match rx.await {
8877 Ok(Ok(response)) => encode_http_response(response, false, &stream_service),
8878 Ok(Err(error)) => Err(format!("asset fetch: {error}")),
8879 Err(error) => Err(format!("asset resolver dropped: {error}")),
8880 }
8881 });
8882 rv.set(promise_for(scope, id));
8883}
8884
8885fn tee_http_stream(
8886 service: &Arc<HttpStreamService>,
8887 source: HttpTransferredStream,
8888) -> Result<(u64, u64), &'static str> {
8889 let (ids, pump) = prepare_http_stream_tee(service, source)?;
8890 asyncrt::op_handle().spawn(pump);
8891 Ok(ids)
8892}
8893
8894fn op_http_stream_read(
8895 scope: &mut v8::PinScope,
8896 args: v8::FunctionCallbackArguments,
8897 mut rv: v8::ReturnValue<v8::Value>,
8898) {
8899 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8900 let service = http_stream_service();
8901 let read = http_stream_read(service, stream_id);
8902 let id = asyncrt::enqueue(async move {
8903 match read.await? {
8904 Some(bytes) => Ok(asyncrt::OpOut::Bytes(bytes)),
8905 None => Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())),
8906 }
8907 });
8908 rv.set(promise_for(scope, id));
8909}
8910
8911fn op_http_stream_tee(
8912 scope: &mut v8::PinScope,
8913 args: v8::FunctionCallbackArguments,
8914 mut rv: v8::ReturnValue<v8::Value>,
8915) {
8916 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8917 let service = http_stream_service();
8918 let source = service.checkout_transfer(stream_id, None).ok();
8919 let Some(source) = source else {
8920 let message = v8::String::new(scope, "response stream is no longer available").unwrap();
8921 let exception = v8::Exception::type_error(scope, message);
8922 scope.throw_exception(exception);
8923 return;
8924 };
8925 let ids = match tee_http_stream(&service, source) {
8926 Ok(ids) => ids,
8927 Err(error) => {
8928 let message = v8::String::new(scope, error).unwrap();
8929 let exception = v8::Exception::type_error(scope, message);
8930 scope.throw_exception(exception);
8931 return;
8932 }
8933 };
8934 current_context().replace_body_stream(stream_id, &service, ids);
8935 let json = serde_json::to_string(&ids).unwrap();
8936 rv.set(v8::String::new(scope, &json).unwrap().into());
8937}
8938
8939fn op_http_stream_cancel(
8940 scope: &mut v8::PinScope,
8941 args: v8::FunctionCallbackArguments,
8942 _rv: v8::ReturnValue<v8::Value>,
8943) {
8944 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8945 http_stream_service().cancel_source(stream_id);
8946}
8947
8948fn op_response_stream_create(
8949 scope: &mut v8::PinScope,
8950 _args: v8::FunctionCallbackArguments,
8951 mut rv: v8::ReturnValue<v8::Value>,
8952) {
8953 let (writer, receiver) = tokio::sync::mpsc::channel(1);
8954 let (finished, _) = tokio::sync::watch::channel(false);
8955 let Some(stream_id) = http_stream_service()
8956 .register_response_pair(receiver, ResponseStreamWriter::new(writer, finished))
8957 else {
8958 let message = v8::String::new(scope, HTTP_STREAM_REGISTRATION_CLOSED).unwrap();
8959 let exception = v8::Exception::type_error(scope, message);
8960 scope.throw_exception(exception);
8961 return;
8962 };
8963 rv.set(v8::Number::new(scope, stream_id as f64).into());
8964}
8965
8966fn op_response_stream_write(
8967 scope: &mut v8::PinScope,
8968 args: v8::FunctionCallbackArguments,
8969 mut rv: v8::ReturnValue<v8::Value>,
8970) {
8971 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8972 let bytes = args
8973 .get(1)
8974 .try_cast::<v8::ArrayBufferView>()
8975 .ok()
8976 .map(|view| {
8977 let mut bytes = vec![0; view.byte_length()];
8978 view.copy_contents(&mut bytes);
8979 bytes
8980 });
8981 // A response is gated once, when it is released, but a body that streams
8982 // keeps producing after that. A later chunk can carry a commit that
8983 // another event made after the release, and that chunk leaves the process
8984 // as surely as the response head did. So each chunk takes its own ticket,
8985 // sampled here while JS still runs, exactly as `fetch` does.
8986 //
8987 // The pump in `__bridgeResponseStream` awaits each write before it asks
8988 // the producer for the next chunk, so one chunk is in flight at a time and
8989 // a held chunk cannot overtake a released one. The ticket is taken before
8990 // `response_stream_write` reserves the stream's write activity, so a long
8991 // wait for a proof holds no lease on the stream. The stream's inactivity
8992 // expiry still runs during the wait, so a proof that never lands ends the
8993 // body with an error rather than releasing the chunk, which is the
8994 // direction this gate exists to fail in.
8995 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Response);
8996 let service = http_stream_service();
8997 let id = asyncrt::enqueue(async move {
8998 await_egress_gate(gate).await?;
8999 response_stream_write(service, stream_id, bytes).await?;
9000 Ok(String::new())
9001 });
9002 rv.set(promise_for(scope, id));
9003}
9004
9005fn op_response_stream_closed(
9006 scope: &mut v8::PinScope,
9007 args: v8::FunctionCallbackArguments,
9008 mut rv: v8::ReturnValue<v8::Value>,
9009) {
9010 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9011 let (writer, mut finished) = http_stream_service()
9012 .writer_close_watch(stream_id)
9013 .map(|(writer, finished)| (Some(writer), Some(finished)))
9014 .unwrap_or((None, None));
9015 let id = asyncrt::enqueue(async move {
9016 let cancelled = match (writer, finished.as_mut()) {
9017 (Some(writer), Some(finished)) => crate::asyncrt::select_biased! {
9018 "stream completion wins a tie so a completed response is not reported as cancelled";
9019 result = finished.changed() => result.is_err(),
9020 _ = writer.closed() => true,
9021 },
9022 _ => false,
9023 };
9024 Ok(String::from(if cancelled {
9025 "cancelled"
9026 } else {
9027 "finished"
9028 }))
9029 });
9030 rv.set(promise_for(scope, id));
9031}
9032
9033fn op_response_stream_close(
9034 scope: &mut v8::PinScope,
9035 args: v8::FunctionCallbackArguments,
9036 mut rv: v8::ReturnValue<v8::Value>,
9037) {
9038 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9039 let error = args.get(1).to_rust_string_lossy(scope);
9040 let close = response_stream_close(http_stream_service(), stream_id, error);
9041 let id = asyncrt::enqueue(async move {
9042 close.await?;
9043 Ok(String::new())
9044 });
9045 rv.set(promise_for(scope, id));
9046}
9047
9048/// Timer op behind `setTimeout`: a promise resolving after `ms`.
9049fn op_timer(
9050 scope: &mut v8::PinScope,
9051 args: v8::FunctionCallbackArguments,
9052 mut rv: v8::ReturnValue<v8::Value>,
9053) {
9054 let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9055 let ms = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64;
9056 let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
9057 timer_cancels().lock().unwrap().insert(timer_id, cancel_tx);
9058 let id = asyncrt::enqueue(async move {
9059 crate::asyncrt::select! {
9060 _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => {}
9061 _ = &mut cancel_rx => {}
9062 }
9063 timer_cancels().lock().unwrap().remove(&timer_id);
9064 Ok(String::new())
9065 });
9066 let p = promise_for(scope, id);
9067 rv.set(p);
9068}
9069
9070/// `__io_context_id(operationDriver = false)` — return the live context id.
9071///
9072/// The default returns the resource origin. A true argument returns the
9073/// operation driver, so a nested block can refuse a retained stale context.
9074fn op_io_context_id(
9075 scope: &mut v8::PinScope,
9076 args: v8::FunctionCallbackArguments,
9077 mut rv: v8::ReturnValue<v8::Value>,
9078) {
9079 let driver = args.get(0).boolean_value(scope);
9080 let id = if driver {
9081 operation_continuation_id(scope).filter(|id| {
9082 actor_runtime_state(scope)
9083 .io_context(*id)
9084 .is_some_and(|context| context.accepts_handed_ops())
9085 })
9086 } else {
9087 current_reaction_io_context(scope).and_then(|context| context.continuation_id())
9088 };
9089 let id = id.map(|id| id.to_string()).unwrap_or_default();
9090 rv.set(v8::String::new(scope, &id).unwrap().into());
9091}
9092
9093fn return_gate_acquisition(
9094 scope: &mut v8::PinScope,
9095 mut rv: v8::ReturnValue<v8::Value>,
9096 event: celld_logic::gate::EventId,
9097 owner: Option<u64>,
9098 promise: v8::Local<v8::Value>,
9099) {
9100 let event = v8::String::new(scope, &event.to_string()).unwrap();
9101 let owner =
9102 v8::String::new(scope, &owner.map(|id| id.to_string()).unwrap_or_default()).unwrap();
9103 let values = [event.into(), owner.into(), promise];
9104 rv.set(v8::Array::new_with_elements(scope, &values).into());
9105}
9106
9107/// `__gate_acquire(scope)` — take the cell's input gate for a
9108/// `blockConcurrencyWhile`, waiting if another block holds it.
9109///
9110/// Answers a promise of the event id, not the id itself. It was synchronous,
9111/// and that was right while a cell's events came off one channel: only one
9112/// ran at a time, a delivery point had already found the gate open, and
9113/// yielding even one microtask reopened a window in which a nested delivery
9114/// could wait on a gate nothing would release. Neither half holds now —
9115/// events are independent tasks, several run at once, and nothing nests —
9116/// so two blocks can meet and the second must queue.
9117fn op_gate_acquire(
9118 scope: &mut v8::PinScope,
9119 args: v8::FunctionCallbackArguments,
9120 rv: v8::ReturnValue<v8::Value>,
9121) {
9122 let cell = args.get(0).to_rust_string_lossy(scope);
9123 let event = NEXT_GATE_EVENT.fetch_add(1, Ordering::Relaxed);
9124 let contexts = current_reaction_io_context(scope).zip(
9125 operation_continuation_id(scope).and_then(|id| actor_runtime_state(scope).io_context(id)),
9126 );
9127 let Some((context, owner_context)) = contexts else {
9128 // A promise can retain user code after its event has retired. It must
9129 // not borrow the context of whichever event happens to run the stale
9130 // reaction's checkpoint.
9131 let promise = rejected_promise(scope, RETIRED_INPUT_GATE);
9132 return_gate_acquisition(scope, rv, event, None, promise);
9133 return;
9134 };
9135 // The harness installs the driver before acquisition. A missing driver
9136 // is rejected above instead of transferring a stale block to its origin.
9137 let owner = owner_context.continuation_id();
9138 // Queued until taken or refused, either way once: the guard counts the
9139 // event out when the future ends, however it ends.
9140 struct Queued {
9141 cell: String,
9142 owner: Option<u64>,
9143 }
9144 impl Queued {
9145 fn new(cell: String, owner: Option<u64>) -> Self {
9146 if let Some(owner) = owner {
9147 *cell_gates()
9148 .lock()
9149 .unwrap()
9150 .entry(cell.clone())
9151 .or_default()
9152 .queued
9153 .entry(owner)
9154 .or_default() += 1;
9155 GATE_ENGAGEMENTS.fetch_add(1, Ordering::Relaxed);
9156 }
9157 Self { cell, owner }
9158 }
9159 }
9160 impl Drop for Queued {
9161 fn drop(&mut self) {
9162 let Some(owner) = self.owner else {
9163 return;
9164 };
9165 let mut gates = cell_gates().lock().unwrap();
9166 let remove = if let Some(gate) = gates.get_mut(&self.cell) {
9167 if let Some(count) = gate.queued.get_mut(&owner) {
9168 *count -= 1;
9169 if *count == 0 {
9170 gate.queued.remove(&owner);
9171 }
9172 }
9173 gate.is_unused()
9174 } else {
9175 false
9176 };
9177 if remove {
9178 gates.remove(&self.cell);
9179 }
9180 drop(gates);
9181 GATE_ENGAGEMENTS.fetch_sub(1, Ordering::Relaxed);
9182 }
9183 }
9184 let mut origin = if Arc::ptr_eq(&context, &owner_context) {
9185 None
9186 } else {
9187 let Some(claim) = context.claim_cross_entry_gate() else {
9188 let promise = rejected_promise(scope, RETIRED_INPUT_GATE);
9189 return_gate_acquisition(scope, rv, event, None, promise);
9190 return;
9191 };
9192 Some(claim)
9193 };
9194 let id = match acquire_cell_gate(&owner_context, &cell, event, owner, &mut origin) {
9195 CellGateAcquisition::Acquired => {
9196 asyncrt::enqueue_io_context(async move { Ok(String::new()) })
9197 }
9198 CellGateAcquisition::Waiting {
9199 mut gate,
9200 mut retirement,
9201 } => {
9202 let queued = Queued::new(cell.clone(), owner);
9203 let context = Arc::downgrade(&owner_context);
9204 asyncrt::enqueue_io_context(async move {
9205 let _queued = queued;
9206 loop {
9207 let outcome = crate::asyncrt::select_biased! {
9208 "a settled gate failure remains visible when its event retires at the same instant";
9209 outcome = &mut gate => Some(outcome),
9210 retired = retirement.wait_for(|retired| *retired) => {
9211 let _ = retired;
9212 None
9213 }
9214 };
9215 let Some(outcome) = outcome else {
9216 return Err(RETIRED_INPUT_GATE.to_string());
9217 };
9218 match outcome {
9219 Ok(Ok(())) => {}
9220 // The block ahead failed and reset the actor. This event
9221 // was sent to that old actor, so it cannot compete for the
9222 // fresh gate.
9223 Ok(Err(failure)) => return Err(failure),
9224 Err(_) => {
9225 return Err("cell stopped while waiting for its input gate".to_string())
9226 }
9227 }
9228 let Some(context) = context.upgrade() else {
9229 return Err(RETIRED_INPUT_GATE.to_string());
9230 };
9231 match acquire_cell_gate(&context, &cell, event, owner, &mut origin) {
9232 CellGateAcquisition::Acquired => {
9233 return Ok(String::new());
9234 }
9235 CellGateAcquisition::Waiting {
9236 gate: next_gate,
9237 retirement: next_retirement,
9238 } => {
9239 gate = next_gate;
9240 retirement = next_retirement;
9241 }
9242 CellGateAcquisition::Retired => return Err(RETIRED_INPUT_GATE.to_string()),
9243 }
9244 }
9245 })
9246 }
9247 CellGateAcquisition::Retired => {
9248 let promise = rejected_promise(scope, RETIRED_INPUT_GATE);
9249 return_gate_acquisition(scope, rv, event, None, promise);
9250 return;
9251 }
9252 };
9253 let promise = promise_for(scope, id);
9254 return_gate_acquisition(scope, rv, event, owner, promise);
9255}
9256
9257/// `__gate_wait(scope)` — settle when the cell's input gate is open.
9258///
9259/// The gate's other side. `op_gate_acquire` is for something that wants to
9260/// *hold* the gate; this is for something that only has to arrive after it,
9261/// which is every event the gate exists to hold back. A drive does this in
9262/// Rust before it begins a turn; an RPC stub op does it here, because it is
9263/// dispatched inside the isolate and never becomes a drive.
9264///
9265/// Rejecting matters as much as resolving: a critical section that failed
9266/// reset the cell, so what waited behind it is refused with the reason
9267/// rather than run against state that no longer exists.
9268fn op_gate_wait(
9269 scope: &mut v8::PinScope,
9270 args: v8::FunctionCallbackArguments,
9271 mut rv: v8::ReturnValue<v8::Value>,
9272) {
9273 let cell = args.get(0).to_rust_string_lossy(scope);
9274 let id = asyncrt::enqueue(async move {
9275 loop {
9276 match cell_gate_wait(&cell) {
9277 None => return Ok(String::new()),
9278 Some(open) => match open.await {
9279 Ok(Ok(())) => {}
9280 Ok(Err(failure)) => return Err(failure),
9281 Err(_) => {
9282 return Err("cell stopped while waiting for its input gate".to_string())
9283 }
9284 },
9285 }
9286 }
9287 });
9288 rv.set(promise_for(scope, id));
9289}
9290
9291/// `__gate_release(scope, event, owner)` — the block is over. The next
9292/// delivery point to run takes whatever queued behind it.
9293fn op_gate_release(
9294 scope: &mut v8::PinScope,
9295 args: v8::FunctionCallbackArguments,
9296 _rv: v8::ReturnValue<v8::Value>,
9297) {
9298 let cell = args.get(0).to_rust_string_lossy(scope);
9299 let event = args.get(1).number_value(scope).unwrap_or_default() as celld_logic::gate::EventId;
9300 let owner = args.get(2).to_rust_string_lossy(scope).parse::<u64>().ok();
9301 // A fourth argument means the block failed and the actor was reset, so
9302 // what queued behind it is refused with that reason rather than
9303 // delivered to a cell whose state is gone.
9304 let failure = args.get(3);
9305 let outcome = if failure.is_null_or_undefined() {
9306 Ok(())
9307 } else {
9308 Err(failure.to_rust_string_lossy(scope))
9309 };
9310 let Some(owner) = owner else {
9311 return;
9312 };
9313 let active = current_context();
9314 let context = if active.continuation_id() == Some(owner) {
9315 Some(active)
9316 } else {
9317 actor_runtime_state(scope).io_context(owner)
9318 };
9319 let Some(context) = context else {
9320 return;
9321 };
9322 if !context.release_input_gate(&cell, event) {
9323 return;
9324 }
9325 release_cell_gate(&cell, event, outcome);
9326}
9327
9328fn op_timer_alloc(
9329 scope: &mut v8::PinScope,
9330 _args: v8::FunctionCallbackArguments,
9331 mut rv: v8::ReturnValue<v8::Value>,
9332) {
9333 let id = v8::Number::new(scope, NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64);
9334 rv.set(id.into());
9335}
9336
9337fn op_timer_cancel(
9338 scope: &mut v8::PinScope,
9339 args: v8::FunctionCallbackArguments,
9340 _rv: v8::ReturnValue<v8::Value>,
9341) {
9342 let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9343 if let Some(cancel) = timer_cancels().lock().unwrap().remove(&timer_id) {
9344 let _ = cancel.send(());
9345 }
9346}
9347
9348fn throw_durable_object_id_error(scope: &mut v8::PinScope, message: &str) {
9349 let message = v8::String::new(scope, message).unwrap();
9350 let exception = v8::Exception::type_error(scope, message);
9351 scope.throw_exception(exception);
9352}
9353
9354fn register_actor_name(
9355 scope: &mut v8::PinScope,
9356 actor_scope: &str,
9357 name: Option<&str>,
9358) -> Result<()> {
9359 let Some(name) = name else {
9360 return Ok(());
9361 };
9362 let cell = cell_state(scope)?;
9363 let names_key = v8::String::new(scope, "idNames").unwrap();
9364 let names = cell
9365 .get(scope, names_key.into())
9366 .and_then(|value| value.to_object(scope))
9367 .ok_or_else(|| anyhow!("missing Durable Object name registry"))?;
9368 let actor_scope_key = v8::String::new(scope, actor_scope).unwrap();
9369 if let Some(existing) = names.get(scope, actor_scope_key.into()) {
9370 if !existing.is_undefined() {
9371 if existing.to_rust_string_lossy(scope) == name {
9372 return Ok(());
9373 }
9374 anyhow::bail!("actor name conflicts with active identity for {actor_scope}");
9375 }
9376 }
9377
9378 let (class_name, id) = actor_scope
9379 .split_once(':')
9380 .ok_or_else(|| anyhow!("named Durable Object scope has no class separator"))?;
9381 let namespace_keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
9382 let namespace_keys = cell
9383 .get(scope, namespace_keys_key.into())
9384 .and_then(|value| value.to_object(scope))
9385 .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
9386 let class_name_key = v8::String::new(scope, class_name).unwrap();
9387 let namespace_key = namespace_keys
9388 .get(scope, class_name_key.into())
9389 .filter(|value| value.is_string())
9390 .ok_or_else(|| anyhow!("missing namespace key for Durable Object class {class_name}"))?
9391 .to_rust_string_lossy(scope);
9392 let expected = durable_object_id_hex(&durable_object_id_for_name(&namespace_key, name));
9393 if id != expected {
9394 anyhow::bail!("actor name does not match Durable Object ID for {actor_scope}");
9395 }
9396 storage::set_actor_name(actor_scope, name)?;
9397
9398 let name_value = v8::String::new(scope, name).unwrap();
9399 if !names
9400 .set(scope, actor_scope_key.into(), name_value.into())
9401 .unwrap_or(false)
9402 {
9403 anyhow::bail!("could not register Durable Object name");
9404 }
9405 Ok(())
9406}
9407
9408fn op_do_id(
9409 scope: &mut v8::PinScope,
9410 args: v8::FunctionCallbackArguments,
9411 mut rv: v8::ReturnValue<v8::Value>,
9412) {
9413 use hmac::Mac;
9414
9415 let namespace_key = args.get(0).to_rust_string_lossy(scope);
9416 let operation = args.get(1).to_rust_string_lossy(scope);
9417 let input = args.get(2).to_rust_string_lossy(scope);
9418 let key = durable_object_id_key(&namespace_key);
9419 let mut id = [0_u8; 32];
9420
9421 match operation.as_str() {
9422 "name" => {
9423 id = durable_object_id_for_name(&namespace_key, &input);
9424 rv.set(
9425 v8::String::new(scope, &durable_object_id_hex(&id))
9426 .unwrap()
9427 .into(),
9428 );
9429 return;
9430 }
9431 "unique" => {
9432 if getrandom::fill(&mut id[..16]).is_err() {
9433 throw_durable_object_id_error(scope, "secure random generation failed");
9434 return;
9435 }
9436 }
9437 "validate" => {
9438 let Some(decoded) = decode_durable_object_id(&input) else {
9439 throw_durable_object_id_error(
9440 scope,
9441 "Invalid Durable Object ID: must be 64 hex digits",
9442 );
9443 return;
9444 };
9445 if durable_object_id_hmac(&key, &decoded[..16])
9446 .verify_truncated_left(&decoded[16..])
9447 .is_err()
9448 {
9449 throw_durable_object_id_error(
9450 scope,
9451 "Durable Object ID is not valid for this namespace",
9452 );
9453 return;
9454 }
9455 rv.set(
9456 v8::String::new(scope, &input.to_ascii_lowercase())
9457 .unwrap()
9458 .into(),
9459 );
9460 return;
9461 }
9462 _ => {
9463 throw_durable_object_id_error(scope, "unknown Durable Object ID operation");
9464 return;
9465 }
9466 }
9467
9468 let digest = durable_object_id_hmac(&key, &id[..16])
9469 .finalize()
9470 .into_bytes();
9471 id[16..].copy_from_slice(&digest[..16]);
9472 rv.set(
9473 v8::String::new(scope, &durable_object_id_hex(&id))
9474 .unwrap()
9475 .into(),
9476 );
9477}
9478
9479fn view_bytes(value: v8::Local<v8::Value>) -> Option<Vec<u8>> {
9480 let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
9481 let mut bytes = vec![0_u8; view.byte_length()];
9482 view.copy_contents(&mut bytes);
9483 Some(bytes)
9484}
9485
9486fn webcrypto_return_bytes(
9487 scope: &mut v8::PinScope,
9488 mut rv: v8::ReturnValue<v8::Value>,
9489 bytes: &[u8],
9490) {
9491 let buffer = v8::ArrayBuffer::new(scope, bytes.len());
9492 if !bytes.is_empty() {
9493 let store = buffer.get_backing_store();
9494 let destination = unsafe {
9495 std::slice::from_raw_parts_mut(store.data().unwrap().as_ptr() as *mut u8, bytes.len())
9496 };
9497 destination.copy_from_slice(bytes);
9498 }
9499 let view = v8::Uint8Array::new(scope, buffer, 0, bytes.len()).unwrap();
9500 rv.set(view.into());
9501}
9502
9503mod container;
9504mod crypto;
9505mod html_rewriter;
9506mod tcp;
9507#[cfg(celld_internal_tests)]
9508pub use tcp::test_extra_tls_root;
9509mod zlib;
9510
9511fn op_actor_abort(
9512 scope: &mut v8::PinScope,
9513 args: v8::FunctionCallbackArguments,
9514 _rv: v8::ReturnValue<v8::Value>,
9515) {
9516 let Some(context) = current_reaction_io_context(scope) else {
9517 return;
9518 };
9519 let cell = args.get(0).to_rust_string_lossy(scope);
9520 let reason = args.get(1).to_rust_string_lossy(scope);
9521 let state = actor_runtime_state(scope);
9522 state
9523 .pending_puts
9524 .lock()
9525 .expect("pending puts lock poisoned")
9526 .remove(&cell);
9527 *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
9528 error: format!("__CELLD_ACTOR_ABORT__:{reason}"),
9529 actor_scope: Some(cell),
9530 context_id: context.continuation_id(),
9531 });
9532 scope.terminate_execution();
9533}
9534
9535fn op_process_exit(
9536 scope: &mut v8::PinScope,
9537 args: v8::FunctionCallbackArguments,
9538 _rv: v8::ReturnValue<v8::Value>,
9539) {
9540 let code = args.get(0).integer_value(scope).unwrap_or(0);
9541 let Some(context) = current_reaction_or_untracked_io_context(scope) else {
9542 tracing::warn!(
9543 code,
9544 "process.exit called without an active request; ignoring"
9545 );
9546 return;
9547 };
9548 if context.depth() == 0 {
9549 tracing::warn!(
9550 code,
9551 "process.exit called without an active request; ignoring"
9552 );
9553 return;
9554 }
9555 let actor_scope = args.get(1).to_rust_string_lossy(scope);
9556 let actor_scope = (!actor_scope.is_empty()).then_some(actor_scope);
9557 let state = actor_runtime_state(scope);
9558 if let Some(actor_scope) = actor_scope.as_deref() {
9559 state
9560 .pending_puts
9561 .lock()
9562 .expect("pending puts lock poisoned")
9563 .remove(actor_scope);
9564 }
9565 *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
9566 error: format!("__CELLD_PROCESS_EXIT__:The Node.js process.exit({code}) API was called."),
9567 actor_scope,
9568 context_id: context.continuation_id(),
9569 });
9570 scope.terminate_execution();
9571}
9572
9573fn op_log(
9574 scope: &mut v8::PinScope,
9575 args: v8::FunctionCallbackArguments,
9576 _rv: v8::ReturnValue<v8::Value>,
9577) {
9578 let mut msg: Vec<String> = (0..args.length())
9579 .map(|i| args.get(i).to_rust_string_lossy(scope))
9580 .collect();
9581 let level = if msg.len() >= 2
9582 && matches!(
9583 msg.first().map(String::as_str),
9584 Some("debug" | "error" | "info" | "log" | "warn")
9585 ) {
9586 msg.remove(0)
9587 } else {
9588 "log".to_string()
9589 };
9590 let body = msg.join(" ");
9591 if let Some(context) = current_reaction_or_untracked_io_context(scope) {
9592 context.record_tail_log(&level, &body);
9593 }
9594 let displayed = match level.as_str() {
9595 "error" => format!("ERROR {body}"),
9596 "warn" => format!("WARN {body}"),
9597 _ => body,
9598 };
9599 // Correlated by CPED, so a continuation logging after an await — or
9600 // another entry's continuation running in this turn's checkpoint —
9601 // lands on the trace that owns it, not on whoever holds the isolate.
9602 if crate::telemetry::active() {
9603 if let Some(ids) =
9604 current_trace_context(scope).and_then(crate::telemetry::TraceContext::recording_ids)
9605 {
9606 crate::telemetry::record_log(crate::telemetry::Log {
9607 trace_id: Some(ids.trace_id),
9608 span_id: Some(ids.span_id),
9609 time_unix_us: crate::telemetry::now_unix_us(),
9610 body: displayed.clone(),
9611 });
9612 }
9613 }
9614 tracing::info!(target: "cell_console", "{}", displayed);
9615}
9616fn op_heap_limit_excessively_exceeded(
9617 scope: &mut v8::PinScope,
9618 _args: v8::FunctionCallbackArguments,
9619 mut rv: v8::ReturnValue<v8::Value>,
9620) {
9621 let exceeded = scope
9622 .get_slot::<Arc<HeapLimitState>>()
9623 .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed));
9624 rv.set(v8::Boolean::new(scope, exceeded).into());
9625}
9626/// Whether this isolate is too close to its heap limit to retain more state.
9627fn op_heap_over_admission_share(
9628 scope: &mut v8::PinScope,
9629 _args: v8::FunctionCallbackArguments,
9630 mut rv: v8::ReturnValue<v8::Value>,
9631) {
9632 let state = scope.get_slot::<Arc<HeapLimitState>>().cloned();
9633 let over = match state {
9634 // A condemned isolate admits nothing, whatever the heap now reads.
9635 Some(state)
9636 if state.excessively_exceeded.load(Ordering::Relaxed)
9637 || admission_refusal_forced(&state) =>
9638 {
9639 true
9640 }
9641 Some(state) => heap_share(scope, state.limit) >= HEAP_ADMISSION_SHARE,
9642 None => false,
9643 };
9644 rv.set(v8::Boolean::new(scope, over).into());
9645}
9646#[cfg(celld_internal_tests)]
9647fn op_test_set_heap_limit_excessively_exceeded(
9648 scope: &mut v8::PinScope,
9649 args: v8::FunctionCallbackArguments,
9650 _rv: v8::ReturnValue<v8::Value>,
9651) {
9652 if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() {
9653 state
9654 .excessively_exceeded
9655 .store(args.get(0).boolean_value(scope), Ordering::Relaxed);
9656 }
9657}
9658#[cfg(celld_internal_tests)]
9659fn op_test_force_heap_admission_refusal(
9660 scope: &mut v8::PinScope,
9661 args: v8::FunctionCallbackArguments,
9662 _rv: v8::ReturnValue<v8::Value>,
9663) {
9664 if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() {
9665 state
9666 .forced_admission_refusal
9667 .store(args.get(0).boolean_value(scope), Ordering::Relaxed);
9668 }
9669}
9670#[cfg(celld_internal_tests)]
9671fn op_test_gc(
9672 scope: &mut v8::PinScope,
9673 _args: v8::FunctionCallbackArguments,
9674 _rv: v8::ReturnValue<v8::Value>,
9675) {
9676 scope.request_garbage_collection_for_testing(v8::GarbageCollectionType::Full);
9677}
9678
9679#[cfg(celld_internal_tests)]
9680thread_local! {
9681 static FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION: std::cell::Cell<bool> = const {
9682 std::cell::Cell::new(false)
9683 };
9684 static FAIL_NEXT_WORKFLOW_META_CREATION: std::cell::Cell<bool> = const {
9685 std::cell::Cell::new(false)
9686 };
9687 static FAIL_NEXT_WORKFLOW_TERMINAL_ALARM_SET: std::cell::Cell<bool> = const {
9688 std::cell::Cell::new(false)
9689 };
9690 static FAIL_NEXT_QUEUE_DLQ_ACCEPT: std::cell::Cell<bool> = const {
9691 std::cell::Cell::new(false)
9692 };
9693 static QUEUE_DLQ_ACCEPT_CALLS: std::cell::Cell<usize> = const {
9694 std::cell::Cell::new(0)
9695 };
9696 static QUEUE_METRICS_MATERIALIZED: std::cell::Cell<bool> = const {
9697 std::cell::Cell::new(false)
9698 };
9699 static QUEUE_PRODUCER_GROUPS: std::cell::RefCell<Vec<(usize, usize)>> = const {
9700 std::cell::RefCell::new(Vec::new())
9701 };
9702 static QUEUE_PRODUCER_WRITE_POSITIONS: std::cell::RefCell<Vec<Option<u64>>> = const {
9703 std::cell::RefCell::new(Vec::new())
9704 };
9705 static QUEUE_REARM_OBSERVED: std::cell::Cell<bool> = const {
9706 std::cell::Cell::new(false)
9707 };
9708 static QUEUE_REARM_POSITIVE: std::cell::Cell<bool> = const {
9709 std::cell::Cell::new(false)
9710 };
9711 static QUEUE_REARM_BOUND_VIOLATED: std::cell::Cell<bool> = const {
9712 std::cell::Cell::new(false)
9713 };
9714 static QUEUE_SETTLEMENT_POLICY_OBSERVED: std::cell::Cell<bool> = const {
9715 std::cell::Cell::new(false)
9716 };
9717 static QUEUE_LEASE_LOOKUP_PLANS: std::cell::RefCell<Vec<String>> = const {
9718 std::cell::RefCell::new(Vec::new())
9719 };
9720 static KV_LIST_PLANS: std::cell::RefCell<Vec<String>> = const {
9721 std::cell::RefCell::new(Vec::new())
9722 };
9723}
9724
9725#[cfg(celld_internal_tests)]
9726#[doc(hidden)]
9727pub fn fail_next_workflow_event_consumption_for_test() {
9728 FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION.with(|fail| fail.set(true));
9729}
9730
9731#[cfg(celld_internal_tests)]
9732#[doc(hidden)]
9733pub fn fail_next_workflow_meta_creation_for_test() {
9734 FAIL_NEXT_WORKFLOW_META_CREATION.with(|fail| fail.set(true));
9735}
9736
9737#[cfg(celld_internal_tests)]
9738#[doc(hidden)]
9739pub fn fail_next_workflow_terminal_alarm_set_for_test() {
9740 FAIL_NEXT_WORKFLOW_TERMINAL_ALARM_SET.with(|fail| fail.set(true));
9741}
9742
9743#[cfg(celld_internal_tests)]
9744#[doc(hidden)]
9745pub fn fail_next_queue_dlq_accept_for_test() {
9746 FAIL_NEXT_QUEUE_DLQ_ACCEPT.with(|fail| fail.set(true));
9747}
9748
9749#[cfg(celld_internal_tests)]
9750pub fn reset_queue_dlq_accept_calls_for_test() {
9751 QUEUE_DLQ_ACCEPT_CALLS.with(|calls| calls.set(0));
9752}
9753
9754#[cfg(celld_internal_tests)]
9755#[doc(hidden)]
9756pub fn queue_dlq_accept_calls_for_test() -> usize {
9757 QUEUE_DLQ_ACCEPT_CALLS.with(std::cell::Cell::get)
9758}
9759
9760#[cfg(celld_internal_tests)]
9761pub fn reset_queue_hot_path_observations_for_test() {
9762 QUEUE_METRICS_MATERIALIZED.with(|observed| observed.set(false));
9763 QUEUE_REARM_OBSERVED.with(|observed| observed.set(false));
9764 QUEUE_REARM_POSITIVE.with(|observed| observed.set(false));
9765 QUEUE_REARM_BOUND_VIOLATED.with(|violated| violated.set(false));
9766}
9767
9768#[cfg(celld_internal_tests)]
9769#[doc(hidden)]
9770pub fn queue_hot_path_observations_for_test() -> (bool, bool, bool) {
9771 let materialized = QUEUE_METRICS_MATERIALIZED.with(std::cell::Cell::get);
9772 let bounded = QUEUE_REARM_OBSERVED.with(std::cell::Cell::get)
9773 && QUEUE_REARM_POSITIVE.with(std::cell::Cell::get)
9774 && !QUEUE_REARM_BOUND_VIOLATED.with(std::cell::Cell::get);
9775 let violated = QUEUE_REARM_BOUND_VIOLATED.with(std::cell::Cell::get);
9776 (materialized, bounded, violated)
9777}
9778
9779#[cfg(celld_internal_tests)]
9780pub fn reset_queue_producer_groups_for_test() {
9781 QUEUE_PRODUCER_GROUPS.with(|groups| groups.borrow_mut().clear());
9782 QUEUE_PRODUCER_WRITE_POSITIONS.with(|positions| positions.borrow_mut().clear());
9783}
9784
9785#[cfg(celld_internal_tests)]
9786#[doc(hidden)]
9787pub fn queue_producer_groups_for_test() -> Vec<(usize, usize)> {
9788 QUEUE_PRODUCER_GROUPS.with(|groups| groups.borrow().clone())
9789}
9790
9791#[cfg(celld_internal_tests)]
9792#[doc(hidden)]
9793pub fn queue_producer_write_positions_for_test() -> Vec<Option<u64>> {
9794 QUEUE_PRODUCER_WRITE_POSITIONS.with(|positions| positions.borrow().clone())
9795}
9796
9797#[cfg(celld_internal_tests)]
9798#[doc(hidden)]
9799pub fn reset_queue_lease_lookup_plans_for_test() {
9800 QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow_mut().clear());
9801}
9802
9803#[cfg(celld_internal_tests)]
9804#[doc(hidden)]
9805pub fn queue_lease_lookup_plans_for_test() -> Vec<String> {
9806 QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow().clone())
9807}
9808
9809#[cfg(celld_internal_tests)]
9810#[doc(hidden)]
9811pub fn reset_kv_list_plans_for_test() {
9812 KV_LIST_PLANS.with(|plans| plans.borrow_mut().clear());
9813}
9814
9815#[cfg(celld_internal_tests)]
9816#[doc(hidden)]
9817pub fn kv_list_plans_for_test() -> Vec<String> {
9818 KV_LIST_PLANS.with(|plans| plans.borrow().clone())
9819}
9820
9821#[cfg(celld_internal_tests)]
9822#[doc(hidden)]
9823pub fn reset_queue_settlement_policy_observation_for_test() {
9824 QUEUE_SETTLEMENT_POLICY_OBSERVED.with(|observed| observed.set(false));
9825}
9826
9827#[cfg(celld_internal_tests)]
9828#[doc(hidden)]
9829pub fn queue_settlement_policy_observed_for_test() -> bool {
9830 QUEUE_SETTLEMENT_POLICY_OBSERVED.with(std::cell::Cell::get)
9831}
9832
9833#[cfg(celld_internal_tests)]
9834fn op_test_workflow_event_consumed(
9835 scope: &mut v8::PinScope,
9836 _args: v8::FunctionCallbackArguments,
9837 _rv: v8::ReturnValue<v8::Value>,
9838) {
9839 let fail = FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION.with(|fail| fail.replace(false));
9840 if fail {
9841 throw_storage_error(
9842 scope,
9843 "workflow event consumption",
9844 "injected failure after workflow event delete",
9845 );
9846 }
9847}
9848
9849#[cfg(celld_internal_tests)]
9850fn op_test_workflow_meta_created(
9851 scope: &mut v8::PinScope,
9852 _args: v8::FunctionCallbackArguments,
9853 _rv: v8::ReturnValue<v8::Value>,
9854) {
9855 let fail = FAIL_NEXT_WORKFLOW_META_CREATION.with(|fail| fail.replace(false));
9856 if fail {
9857 throw_storage_error(
9858 scope,
9859 "workflow creation",
9860 "injected failure after workflow metadata write",
9861 );
9862 }
9863}
9864
9865#[cfg(celld_internal_tests)]
9866fn op_test_workflow_terminal_alarm_set(
9867 scope: &mut v8::PinScope,
9868 _args: v8::FunctionCallbackArguments,
9869 _rv: v8::ReturnValue<v8::Value>,
9870) {
9871 let fail = FAIL_NEXT_WORKFLOW_TERMINAL_ALARM_SET.with(|fail| fail.replace(false));
9872 if fail {
9873 throw_storage_error(
9874 scope,
9875 "workflow terminal alarm installation",
9876 "injected failure after workflow terminal alarm installation",
9877 );
9878 }
9879}
9880
9881#[cfg(celld_internal_tests)]
9882fn op_test_queue_dlq_accepted(
9883 scope: &mut v8::PinScope,
9884 _args: v8::FunctionCallbackArguments,
9885 _rv: v8::ReturnValue<v8::Value>,
9886) {
9887 QUEUE_DLQ_ACCEPT_CALLS.with(|calls| calls.set(calls.get() + 1));
9888 let fail = FAIL_NEXT_QUEUE_DLQ_ACCEPT.with(|fail| fail.replace(false));
9889 if fail {
9890 throw_storage_error(
9891 scope,
9892 "Queue DLQ transfer",
9893 "injected failure after the target accepted the message",
9894 );
9895 }
9896}
9897
9898#[cfg(celld_internal_tests)]
9899fn op_test_queue_metrics_materialized(
9900 _scope: &mut v8::PinScope,
9901 _args: v8::FunctionCallbackArguments,
9902 _rv: v8::ReturnValue<v8::Value>,
9903) {
9904 QUEUE_METRICS_MATERIALIZED.with(|observed| observed.set(true));
9905}
9906
9907#[cfg(celld_internal_tests)]
9908fn op_test_queue_producer_group(
9909 scope: &mut v8::PinScope,
9910 args: v8::FunctionCallbackArguments,
9911 _rv: v8::ReturnValue<v8::Value>,
9912) {
9913 let calls = args.get(0).integer_value(scope).unwrap_or(0).max(0) as usize;
9914 let messages = args.get(1).integer_value(scope).unwrap_or(0).max(0) as usize;
9915 QUEUE_PRODUCER_GROUPS.with(|groups| groups.borrow_mut().push((calls, messages)));
9916}
9917
9918#[cfg(celld_internal_tests)]
9919fn op_test_queue_lease_lookup_plan(
9920 scope: &mut v8::PinScope,
9921 args: v8::FunctionCallbackArguments,
9922 _rv: v8::ReturnValue<v8::Value>,
9923) {
9924 let plan = args.get(0).to_rust_string_lossy(scope);
9925 QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow_mut().push(plan));
9926}
9927
9928#[cfg(celld_internal_tests)]
9929fn op_test_kv_list_plan(
9930 scope: &mut v8::PinScope,
9931 args: v8::FunctionCallbackArguments,
9932 _rv: v8::ReturnValue<v8::Value>,
9933) {
9934 let plan = args.get(0).to_rust_string_lossy(scope);
9935 KV_LIST_PLANS.with(|plans| plans.borrow_mut().push(plan));
9936}
9937
9938#[cfg(celld_internal_tests)]
9939fn op_test_queue_rearm_bounded(
9940 scope: &mut v8::PinScope,
9941 args: v8::FunctionCallbackArguments,
9942 _rv: v8::ReturnValue<v8::Value>,
9943) {
9944 QUEUE_REARM_OBSERVED.with(|observed| observed.set(true));
9945 QUEUE_REARM_POSITIVE.with(|observed| observed.set(observed.get() || args.get(1).is_true()));
9946 if !args.get(0).boolean_value(scope) {
9947 QUEUE_REARM_BOUND_VIOLATED.with(|violated| violated.set(true));
9948 }
9949}
9950// `celld r2` writes an object a binding then reads, so the operator command
9951// calls the very functions the ops call rather than a second implementation
9952// of the object record.
9953pub(crate) mod r2_ops;
9954mod storage_ops;
9955use storage_ops::{actor_runtime_state, throw_storage_error};
9956
9957/// $$urlParse(input, base?) -> {protocol,username,password,host,port,pathname,search,hash,href}
9958/// Backed by the WHATWG-conformant `url` crate.
9959fn op_url_parse(
9960 scope: &mut v8::PinScope,
9961 args: v8::FunctionCallbackArguments,
9962 mut rv: v8::ReturnValue<v8::Value>,
9963) {
9964 let input = args.get(0).to_rust_string_lossy(scope);
9965 let base = args.get(1);
9966 let parsed = if base.is_undefined() {
9967 url::Url::parse(&input)
9968 } else {
9969 url::Url::options()
9970 .base_url(
9971 url::Url::parse(&base.to_rust_string_lossy(scope))
9972 .ok()
9973 .as_ref(),
9974 )
9975 .parse(&input)
9976 };
9977 let u = match parsed {
9978 Ok(u) => u,
9979 Err(e) => {
9980 let msg = v8::String::new(scope, &format!("Invalid URL: {e}")).unwrap();
9981 let exc = v8::Exception::type_error(scope, msg);
9982 scope.throw_exception(exc);
9983 return;
9984 }
9985 };
9986 let o = v8::Object::new(scope);
9987 // The nine keys are fixed, so they come from the constant table rather
9988 // than from nine fresh `v8::String`s per `new URL(...)`.
9989 //
9990 // A set can still fail — a throwing setter on `Object.prototype` reaches
9991 // this plain object — and a URL record missing a component is worse than
9992 // no record at all, so the first refusal stops the build.
9993 let port = u.port().map(|p| p.to_string()).unwrap_or_default();
9994 let fields: [(&'static v8::OneByteConst, &str); 9] = [
9995 (&v8_strings::URL_PROTOCOL, u.scheme()),
9996 (&v8_strings::URL_USERNAME, u.username()),
9997 (&v8_strings::URL_PASSWORD, u.password().unwrap_or("")),
9998 (&v8_strings::URL_HOST, u.host_str().unwrap_or("")),
9999 (&v8_strings::URL_PORT, &port),
10000 (&v8_strings::URL_PATHNAME, u.path()),
10001 (&v8_strings::URL_SEARCH, u.query().unwrap_or("")),
10002 (&v8_strings::URL_HASH, u.fragment().unwrap_or("")),
10003 (&v8_strings::URL_HREF, u.as_str()),
10004 ];
10005 for (k, v) in fields {
10006 let key = static_key(scope, k);
10007 let val = v8::String::new(scope, v).unwrap();
10008 match o.set(scope, key.into(), val.into()) {
10009 Some(true) => {}
10010 // The setter threw. Its exception is already pending, and it names
10011 // the real cause, so it propagates unchanged. Throwing a generic
10012 // TypeError here would overwrite it and hide that cause.
10013 None => return,
10014 // A refusal that does not throw — a non-writable inherited data
10015 // property, in sloppy mode — leaves no pending exception, so this
10016 // path has to raise one of its own.
10017 Some(false) => {
10018 let name = key.to_rust_string_lossy(scope);
10019 let msg = v8::String::new(
10020 scope,
10021 &format!("Invalid URL: the {name} property of the URL record was refused"),
10022 )
10023 .unwrap();
10024 let exc = v8::Exception::type_error(scope, msg);
10025 scope.throw_exception(exc);
10026 return;
10027 }
10028 }
10029 }
10030 rv.set(o.into());
10031}
10032
10033// URLPattern host seam, split like Deno's: pattern parsing and match-input
10034// canonicalization run in Rust via the `urlpattern` crate; per-match regex
10035// execution stays in JS `RegExp` (src/js/url_pattern.js). JSON is the
10036// boundary — both ops run at construct/match-canonicalize time only.
10037
10038/// `$$urlPatternParse(inputJson, baseURL?, ignoreCase)` -> json. Input is a
10039/// pattern string or an init object of string components. Returns
10040/// per-component `{ patternString, regexpString, groupNameList }` plus
10041/// `hasRegexpGroups`. Throws TypeError on an invalid pattern.
10042fn op_urlpattern_parse(
10043 scope: &mut v8::PinScope,
10044 args: v8::FunctionCallbackArguments,
10045 mut rv: v8::ReturnValue<v8::Value>,
10046) {
10047 use urlpattern::quirks;
10048 let input = args.get(0).to_rust_string_lossy(scope);
10049 let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
10050 let base = args.get(1);
10051 let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
10052 let options = urlpattern::UrlPatternOptions {
10053 ignore_case: args.get(2).boolean_value(scope),
10054 };
10055 let pattern = quirks::process_construct_pattern_input(input, base.as_deref())
10056 .and_then(|init| quirks::parse_pattern(init, options));
10057 let p = match pattern {
10058 Ok(p) => p,
10059 Err(e) => {
10060 let msg = v8::String::new(scope, &e.to_string()).unwrap();
10061 let exc = v8::Exception::type_error(scope, msg);
10062 scope.throw_exception(exc);
10063 return;
10064 }
10065 };
10066 let component = |c: &quirks::UrlPatternComponent| {
10067 serde_json::json!({
10068 "patternString": c.pattern_string,
10069 "regexpString": c.regexp_string,
10070 "groupNameList": c.group_name_list,
10071 })
10072 };
10073 let out = serde_json::json!({
10074 "protocol": component(&p.protocol),
10075 "username": component(&p.username),
10076 "password": component(&p.password),
10077 "hostname": component(&p.hostname),
10078 "port": component(&p.port),
10079 "pathname": component(&p.pathname),
10080 "search": component(&p.search),
10081 "hash": component(&p.hash),
10082 "hasRegexpGroups": p.has_regexp_groups,
10083 });
10084 rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
10085}
10086
10087/// `$$urlPatternMatchInput(inputJson, baseURL?)` -> json `[8 strings]` in
10088/// component order (protocol..hash), or `null` when the input does not parse
10089/// as a URL. Throws TypeError for an init combined with a baseURL argument.
10090fn op_urlpattern_match_input(
10091 scope: &mut v8::PinScope,
10092 args: v8::FunctionCallbackArguments,
10093 mut rv: v8::ReturnValue<v8::Value>,
10094) {
10095 use urlpattern::quirks;
10096 let input = args.get(0).to_rust_string_lossy(scope);
10097 let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
10098 let base = args.get(1);
10099 let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
10100 let null = v8::null(scope).into();
10101 let m = match quirks::process_match_input(input, base.as_deref()) {
10102 Ok(Some((input_, _inputs))) => match quirks::parse_match_input(input_) {
10103 Some(m) => m,
10104 None => return rv.set(null),
10105 },
10106 Ok(None) => return rv.set(null),
10107 Err(e) => {
10108 let msg = v8::String::new(scope, &e.to_string()).unwrap();
10109 let exc = v8::Exception::type_error(scope, msg);
10110 scope.throw_exception(exc);
10111 return;
10112 }
10113 };
10114 let out = serde_json::json!([
10115 m.protocol, m.username, m.password, m.hostname, m.port, m.pathname, m.search, m.hash,
10116 ]);
10117 rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
10118}
10119
10120fn op_atob(
10121 scope: &mut v8::PinScope,
10122 args: v8::FunctionCallbackArguments,
10123 mut rv: v8::ReturnValue<v8::Value>,
10124) {
10125 use base64::engine::{GeneralPurpose, GeneralPurposeConfig};
10126 use base64::Engine;
10127 let input = args.get(0).to_rust_string_lossy(scope);
10128 // https://infra.spec.whatwg.org/#forgiving-base64-decode
10129 //
10130 // Only the five ASCII whitespace characters are ignored. `is_whitespace`
10131 // covers the Unicode White_Space property, so it also stripped U+00A0 and
10132 // U+3000 and made `atob("YQ==\u{a0}")` decode, which Workerd rejects.
10133 let cleaned: Vec<u8> = input
10134 .bytes()
10135 .filter(|b| !matches!(b, b'\t' | b'\n' | b'\x0c' | b'\r' | b' '))
10136 .collect();
10137 let mut data = cleaned.as_slice();
10138 if data.len().is_multiple_of(4) {
10139 data = data
10140 .strip_suffix(b"==")
10141 .or_else(|| data.strip_suffix(b"="))
10142 .unwrap_or(data);
10143 }
10144 // Padding is removed above, so the decoder must now reject every `=` that
10145 // is left. `RequireNone` is the mode that does this; `Indifferent` would
10146 // accept the malformed partial padding of `atob("YQ=")`, which Workerd
10147 // rejects. `allow_trailing_bits` is what makes the decode forgiving: the
10148 // spec discards the unused trailing bits of an unpadded group even when
10149 // they are not zero, so `atob("YR==")` returns "a" instead of throwing.
10150 const FORGIVING: GeneralPurpose = GeneralPurpose::new(
10151 &base64::alphabet::STANDARD,
10152 GeneralPurposeConfig::new()
10153 .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
10154 .with_decode_allow_trailing_bits(true),
10155 );
10156 match FORGIVING.decode(data) {
10157 Ok(bytes) => {
10158 // The public `atob()` wrapper omits this argument and keeps the
10159 // required binary-string result. The KV operator protocol asks
10160 // for a typed view, so a 25 MiB value does not become 25 million
10161 // JavaScript numbers before the cell can store it.
10162 if args.get(1).boolean_value(scope) {
10163 rv.set(bytes_value(scope, bytes));
10164 return;
10165 }
10166 // atob returns a binary string (latin1)
10167 let s: String = bytes.iter().map(|&b| b as char).collect();
10168 rv.set(v8::String::new(scope, &s).unwrap().into());
10169 }
10170 Err(_) => {
10171 let msg = v8::String::new(scope, "Invalid base64").unwrap();
10172 let exc = v8::Exception::error(scope, msg);
10173 scope.throw_exception(exc);
10174 }
10175 }
10176}
10177
10178// node:util introspection seam: V8-level queries that JS cannot perform,
10179// mirroring Workerd's C++ `node-internal:util` builtin. Only the lazy
10180// node:async_hooks prelude calls these. The value is V8's
10181// continuation-preserved embedder data — the primitive Workerd's
10182// AsyncContextFrame rides — which V8 itself captures and restores
10183// around every promise reaction. No promise hooks are installed. A stateless
10184// isolate that never touches AsyncLocalStorage leaves the frame absent; a cell
10185// event still carries the separate native context token described below.
10186
10187#[derive(Default)]
10188struct IoEventFrame {
10189 wait_until: Vec<v8::Global<v8::Promise>>,
10190 arm_gates: Vec<ArmGateRx>,
10191}
10192
10193#[derive(Default)]
10194struct IoEventState {
10195 frames: Vec<IoEventFrame>,
10196 /// Registrations made by active `waitUntil` work after the handler's
10197 /// frame ended. The driver folds each batch into a new aggregate before
10198 /// it retires the event, so one callback can extend the same lifetime.
10199 late_wait_until: Vec<v8::Global<v8::Promise>>,
10200 /// True from the top-level frame's first non-empty drain until the driver
10201 /// observes that drain settled with no later registrations. Keeping this
10202 /// state on the request prevents a foreign event in the same isolate from
10203 /// lending or taking away registration authority.
10204 wait_until_active: bool,
10205 ended_arm_gates: Vec<ArmGateRx>,
10206 arm_gates_sealed: bool,
10207}
10208
10209/// The writable directory subset of Workerd's per-request virtual filesystem.
10210///
10211/// The first compatibility slice stores directories only. Keeping the tree on
10212/// `IoContext` is the isolation mechanism: async continuations for one request
10213/// share it, while a concurrent or later request receives a different tree.
10214/// No path can escape into the host filesystem.
10215struct RequestVfs {
10216 nodes: HashMap<String, VfsNode>,
10217}
10218
10219/// Keep the node kind in the tree, even while the first slice can only create
10220/// directories. Deno's VFS uses the same entry-typed shape; a path-only set
10221/// would make a later file node indistinguishable from its parent directory.
10222enum VfsNode {
10223 Directory { writable: bool },
10224}
10225
10226/// The read-only `/bundle` projection of a worker's own modules.
10227///
10228/// This is isolate state, not request state. The bytes are immutable and
10229/// identical for every request the isolate serves, so building the tree per
10230/// request would repeat the work and re-copy every module body. `BundleFs`
10231/// below keeps one `Arc` and hands a clone to each reader.
10232struct BundleTree {
10233 nodes: HashMap<String, BundleNode>,
10234}
10235
10236/// A projected node. A file owns `Bytes` so a read is a refcount bump rather
10237/// than a copy, and so a wasm module's bytes are shared with the config
10238/// instead of duplicated.
10239enum BundleNode {
10240 Directory,
10241 File(bytes::Bytes),
10242}
10243
10244/// The bundle tree and the config it projects, materialized on first use.
10245///
10246/// Workerd builds `/bundle` through a lazy directory for the same reason (see
10247/// `getBundleDirectory` in `src/workerd/io/bundle-fs.c++`): a worker that never
10248/// calls `node:fs` must not pay to walk its module list or to copy a module
10249/// body into the filesystem. Holding the `Arc<WorkerConfig>` keeps the source
10250/// alive, so materialization does not need its own copy of a module name.
10251struct BundleFs {
10252 config: Arc<WorkerConfig>,
10253 tree: OnceLock<Arc<BundleTree>>,
10254}
10255
10256impl BundleFs {
10257 /// Materialize once, then share. Returns an `Arc` clone so a caller can
10258 /// read without holding an isolate borrow across the read.
10259 fn tree(&self) -> Arc<BundleTree> {
10260 self.tree
10261 .get_or_init(|| Arc::new(BundleTree::project(&self.config)))
10262 .clone()
10263 }
10264}
10265
10266impl BundleTree {
10267 /// Project every bundle module into `/bundle`, keyed by its name as a path.
10268 ///
10269 /// A module name is a path, not a flat key: workerd parses it against
10270 /// `file:///`, so `a/esModule` becomes `/bundle/a/esModule` and creates the
10271 /// intervening directory. The entry module is projected under the name it
10272 /// compiles as, matching workerd's `mainScriptName` entry.
10273 fn project(config: &WorkerConfig) -> Self {
10274 let mut nodes = HashMap::new();
10275 nodes.insert("/bundle".to_string(), BundleNode::Directory);
10276 let entry = std::iter::once((
10277 ENTRY_MODULE_NAME,
10278 bytes::Bytes::copy_from_slice(config.src.as_bytes()),
10279 ));
10280 let modules = config.modules.iter().map(|(name, source)| {
10281 let bytes = match source {
10282 // A text or ES module body is a `String` in the config, so the
10283 // projection copies it once per isolate. A wasm body is already
10284 // `Bytes`, so it is shared rather than copied.
10285 ModuleSource::Text(source) | ModuleSource::EsModule(source) => {
10286 bytes::Bytes::copy_from_slice(source.as_bytes())
10287 }
10288 ModuleSource::Wasm(bytes) => bytes.clone(),
10289 };
10290 (name.as_str(), bytes)
10291 });
10292 for (name, bytes) in entry.chain(modules) {
10293 // A leading or doubled separator would otherwise create an empty
10294 // segment, which no path can address.
10295 let segments: Vec<&str> = name.split('/').filter(|part| !part.is_empty()).collect();
10296 let Some((file, directories)) = segments.split_last() else {
10297 continue;
10298 };
10299 let mut path = String::from("/bundle");
10300 for directory in directories {
10301 path.push('/');
10302 path.push_str(directory);
10303 nodes.entry(path.clone()).or_insert(BundleNode::Directory);
10304 }
10305 path.push('/');
10306 path.push_str(file);
10307 nodes.insert(path, BundleNode::File(bytes));
10308 }
10309 Self { nodes }
10310 }
10311}
10312
10313enum VfsMkdirResult {
10314 Created(Option<String>),
10315 Error(&'static str),
10316}
10317
10318impl Default for RequestVfs {
10319 fn default() -> Self {
10320 Self {
10321 nodes: [
10322 ("/", false),
10323 ("/bundle", false),
10324 ("/dev", false),
10325 ("/tmp", true),
10326 ]
10327 .into_iter()
10328 .map(|(path, writable)| (path.to_string(), VfsNode::Directory { writable }))
10329 .collect(),
10330 }
10331 }
10332}
10333
10334struct InputGateClaims {
10335 /// Set before the turn owner releases its final `IoContext` owner. The
10336 /// watch wakes its pending gate acquisition even when the promise
10337 /// reaction that requested the gate belongs to another event.
10338 retired: bool,
10339 held: HashMap<celld_logic::gate::EventId, String>,
10340 retirement: tokio::sync::watch::Sender<bool>,
10341}
10342
10343impl Default for InputGateClaims {
10344 fn default() -> Self {
10345 let (retirement, _) = tokio::sync::watch::channel(false);
10346 Self {
10347 retired: false,
10348 held: HashMap::new(),
10349 retirement,
10350 }
10351 }
10352}
10353
10354impl RequestVfs {
10355 fn stat(&self, path: &str) -> Option<bool> {
10356 self.nodes.get(path).map(|node| match node {
10357 VfsNode::Directory { writable } => *writable,
10358 })
10359 }
10360
10361 fn mkdir(&mut self, path: &str, recursive: bool) -> VfsMkdirResult {
10362 if path != "/tmp" && !path.starts_with("/tmp/") {
10363 return VfsMkdirResult::Error("EPERM");
10364 }
10365 if self.stat(path).is_some() {
10366 return VfsMkdirResult::Created(None);
10367 }
10368 if recursive {
10369 let mut current = "/tmp".to_string();
10370 let mut first_created = None;
10371 for segment in path.trim_start_matches("/tmp/").split('/') {
10372 current.push('/');
10373 current.push_str(segment);
10374 if self
10375 .nodes
10376 .insert(current.clone(), VfsNode::Directory { writable: true })
10377 .is_none()
10378 && first_created.is_none()
10379 {
10380 first_created = Some(current.clone());
10381 }
10382 }
10383 return VfsMkdirResult::Created(first_created);
10384 }
10385 let parent =
10386 path.rsplit_once('/').map_or(
10387 "/",
10388 |(parent, _)| {
10389 if parent.is_empty() {
10390 "/"
10391 } else {
10392 parent
10393 }
10394 },
10395 );
10396 if self.stat(parent).is_none() {
10397 return VfsMkdirResult::Error("ENOENT");
10398 }
10399 self.nodes
10400 .insert(path.to_string(), VfsNode::Directory { writable: true });
10401 VfsMkdirResult::Created(None)
10402 }
10403}
10404
10405/// The per-request context: everything a request owns while it is in flight.
10406///
10407/// Modelled on workerd's `IoContext`. The host owns it, not JS: a request's
10408/// event frames and the `waitUntil` promises inside them live here, and JS
10409/// reaches them only through ops that ask for the *current* context. That
10410/// inversion is the point. While an isolate serves one request at a time,
10411/// JS-side per-request state is indistinguishable from isolate-side state,
10412/// and the two silently diverge the moment requests interleave — one
10413/// request's `__endEvent` popping another's event, its `waitUntil` work
10414/// attributed to a request that never asked for it.
10415///
10416/// `current()` is a thread-local the host installs for the duration of a
10417/// turn and restores on the way out, exactly as `threadLocalRequest` is set
10418/// in `IoContext::runInContextScope` and restored by `SuppressIoContextScope`.
10419/// An op that needs a context and finds none is a bug in the host, not in
10420/// the script, so it says so rather than inventing one.
10421///
10422/// **It is `Send + Sync`, and that is load-bearing.** Under D1 a request is
10423/// a tokio task that suspends between turns and can resume on any worker, so
10424/// the context it carries has to cross threads with it. `Rc` and `RefCell`
10425/// would forbid that. The isolate keeps one narrow weak lookup from a CPED
10426/// continuation token to this context, because a reaction can run during a
10427/// different event's checkpoint. That lookup owns no context, operation, or
10428/// resolver, and `IoContext::drop` removes it. It therefore attributes the
10429/// running reaction without rebuilding the pump's lifetime-owning `idmap`.
10430/// A cross-entry input gate is the narrow exception: it claims the originating
10431/// context so the event and its resources stay active until the callback ends.
10432/// The gate releases that claim when the block ends. The interiors are
10433/// `Mutex`; only the isolate's holder reaches them.
10434pub struct IoContext {
10435 /// A process-wide identity captured by V8 with each promise reaction.
10436 /// The process-wide cell-gate map also uses it, so another isolate must
10437 /// not reuse it. The isolate registry holds only a `Weak`, so a
10438 /// continuation does not extend the request lifetime by itself. A
10439 /// cross-entry input gate adds an explicit claim that prevents this
10440 /// context's `InFlight` from retiring while its callback still runs.
10441 continuation: Option<(u64, Weak<ActorRuntimeState>)>,
10442 /// This caller's delivery order for each cell it has called. See
10443 /// `CallOrder` — it is here rather than in a process-wide map because
10444 /// nothing outside this caller ever reads it.
10445 pub call_chains: Mutex<CallChains>,
10446 /// Event frames, innermost last. A frame collects the `waitUntil`
10447 /// promises registered while it is the innermost one.
10448 ///
10449 /// Nesting is per-request and strictly LIFO — a service-binding
10450 /// dispatch, an RPC entry, or a DO construction pushes its own frame so
10451 /// its `waitUntil` binds to that dispatch, matching workerd.
10452 events: Mutex<IoEventState>,
10453 /// Workerd gives every request an empty, memory-backed `/tmp`. Directory
10454 /// state belongs here so it follows the request across promise turns and
10455 /// disappears with the request instead of leaking across isolate reuse.
10456 /// The tree stays unallocated when the application does not use `node:fs`.
10457 vfs: OnceLock<Mutex<RequestVfs>>,
10458 /// Isolate-polled sockets this request opened. Dropping the request's
10459 /// pending ops aborts everything the isolate is waiting on, but a socket
10460 /// is a host-side resource that abort cannot reach: its connector task
10461 /// exits only when the isolate stops reading. So the request closes its
10462 /// own sockets, and [`IoContext::drop`] is what makes that unforgettable.
10463 ///
10464 /// Flat rather than a stack. Only sockets that belong to no cell land
10465 /// here, and one `IoContext` is one request, so there is nothing to nest:
10466 /// a service-binding dispatch or a Durable Object call gets a context of
10467 /// its own rather than a frame inside this one.
10468 sockets: Mutex<Vec<u64>>,
10469 /// HTMLRewriter instances this request created. Each holds a parked
10470 /// parser thread; freeing them at retirement is what reclaims the
10471 /// thread when a transform is abandoned unread — nothing else can,
10472 /// because the pending event promise roots the output stream.
10473 rewriters: Mutex<Vec<u64>>,
10474 /// Outbound TCP sockets this event opened. A socket cannot outlive
10475 /// its event: retirement drops the registry entries, which closes
10476 /// the connections.
10477 tcp_sockets: Mutex<Vec<u64>>,
10478 /// Input-gate holds and pending acquisitions for this event.
10479 ///
10480 /// The event owns the cell and host id together, and retirement wakes a
10481 /// pending acquisition. A timeout or cancellation can therefore abandon
10482 /// only its own hold and cannot resume after its event has gone away.
10483 input_gates: Mutex<InputGateClaims>,
10484 /// Blocks created by this event but run during another event's turn.
10485 /// These claims keep this event's native operations and resources alive;
10486 /// their watch wakes the drive when the final block ends.
10487 cross_entry_gates: CrossEntryGateClaims,
10488 /// Host-backed request bodies this handler owns. A subrequest transfers
10489 /// an id out before its target takes ownership, so only one request can
10490 /// reclaim an unread tail.
10491 body_streams: Mutex<HashMap<u64, HttpStreamClaim>>,
10492 /// Output-gate capture. While a `webSocketMessage` runs, the frames it
10493 /// sends are collected here instead of reaching the wire, so the shell
10494 /// can hold them until the message's write is durable. A stack, so a
10495 /// nested dispatch keeps its frames apart from the outer one's.
10496 ///
10497 /// On the event and not on the thread, because an event outlives the
10498 /// turn that began it: capture starts in one turn and is taken in a
10499 /// later one, which tokio may run on a different worker.
10500 ws_capture: Mutex<Vec<websocket::WsCapture>>,
10501 /// What each running event's outbound effects gate against, innermost
10502 /// last. An outbound effect raised during the event consults this: if the
10503 /// handler has advanced the position, the effect waits for the output gate
10504 /// before it leaves the process.
10505 ///
10506 /// Empty for stateless Worker code, which owns no cell and gates
10507 /// nothing.
10508 egress: Mutex<Vec<EgressFrame>>,
10509 /// Ops another event's turn enqueued for this event, waiting for this
10510 /// event's driver to take them. See `adopt`: a continuation that resumes
10511 /// inside a foreign turn still enqueues through that turn, and only the
10512 /// driver of the event it belongs to may poll and cancel its work.
10513 ///
10514 /// `None` once this event retired: the mailbox is closed, and a hand-off
10515 /// that arrives after that is refused rather than parked. A parked op no
10516 /// driver will ever take is a `Global<PromiseResolver>` held for the life
10517 /// of the isolate, which is the leak `InFlight::abandon` exists to
10518 /// prevent; refusing lets the handing turn drop the resolver instead,
10519 /// while it still owns the isolate.
10520 handed: Mutex<Option<Vec<HandedOp>>>,
10521 /// How many ops `handed` holds, readable without taking its lock.
10522 ///
10523 /// Every pass of a driver's wake loop asks whether a foreign turn left it
10524 /// an op, and for all but a few passes in a cell's life the answer is no.
10525 /// The lock is uncontended, so this saves only the lock itself, but it
10526 /// pays that back on a loop that turns once per operation the event
10527 /// completes.
10528 handed_len: AtomicUsize,
10529 /// Wakes this event's driver when `handed` grows or a pending entrypoint
10530 /// starts. Both changes can make the driver's current wait obsolete.
10531 handed_wake: tokio::sync::Notify,
10532 /// IDs of nested `WorkerEntrypoint` calls that have not settled. The
10533 /// driver consumes these IDs only when the request has no native work, so
10534 /// it can reject the calls instead of timing out the enclosing event.
10535 pending_events: Mutex<HashSet<u64>>,
10536 /// The invocation-local subrequest budget. The count lives with the
10537 /// request context, so two concurrent calls into one loaded isolate never
10538 /// spend one another's allowance.
10539 subrequest_limit: Option<u32>,
10540 subrequests: AtomicUsize,
10541 /// A request-scoped client counts redirects against this request. A weak
10542 /// capture avoids a client/context cycle, and one client retains the
10543 /// connection pool across all fetches in the invocation.
10544 redirect_client: OnceLock<reqwest::Client>,
10545 cpu_limit_nanos: Option<u64>,
10546 cpu_used_nanos: AtomicU64,
10547 cpu_turn: Mutex<Option<CpuTurnStart>>,
10548 /// Whether this event records console calls for a Dynamic Worker tail.
10549 tail_reporting: bool,
10550 tail_logs: Mutex<TailLogCapture>,
10551}
10552
10553/// An op enqueued by one event's continuation during another event's turn: the
10554/// promise id, the work, and its complete lifetime classification.
10555type HandedOp = (u64, asyncrt::OpFuture, asyncrt::OpLifetime);
10556
10557impl IoContext {
10558 fn record_tail_log(&self, level: &str, body: &str) {
10559 if !self.tail_reporting {
10560 return;
10561 }
10562 let mut capture = self.tail_logs.lock().unwrap();
10563 if capture.full {
10564 return;
10565 }
10566 let separator = usize::from(!capture.records.is_empty());
10567 // A serialized string cannot be shorter than its UTF-8 input. This
10568 // rejects an obviously oversized call without allocating another
10569 // buffer or scanning it for JSON escapes.
10570 let minimum_bytes = capture
10571 .serialized_bytes
10572 .saturating_add(separator)
10573 .saturating_add(body.len())
10574 .saturating_add(2);
10575 if minimum_bytes > TAIL_LOG_LIMIT_BYTES {
10576 capture.full = true;
10577 return;
10578 }
10579 let record = TailLog {
10580 timestamp: crate::telemetry::now_unix_us() / 1_000,
10581 level: level.to_string(),
10582 message: vec![body.to_string()],
10583 };
10584 let record_bytes = serialized_json_bytes(&record);
10585 let next_bytes = capture
10586 .serialized_bytes
10587 .saturating_add(separator)
10588 .saturating_add(record_bytes);
10589 if next_bytes.saturating_add(2) > TAIL_LOG_LIMIT_BYTES {
10590 capture.full = true;
10591 return;
10592 }
10593 capture.serialized_bytes = next_bytes;
10594 capture.records.push(record);
10595 }
10596
10597 fn take_tail_logs(&self) -> Vec<TailLog> {
10598 std::mem::take(&mut *self.tail_logs.lock().unwrap()).records
10599 }
10600
10601 /// The continuation id this context is registered under, which names
10602 /// the event to the cell's gate. `None` for a context V8 never captures.
10603 fn continuation_id(&self) -> Option<u64> {
10604 self.continuation.as_ref().map(|(id, _)| *id)
10605 }
10606
10607 fn cpu_limit_ms(&self) -> Option<u32> {
10608 self.cpu_limit_nanos
10609 .and_then(|limit| u32::try_from(limit / 1_000_000).ok())
10610 }
10611
10612 fn redirect_counting_client(self: &Arc<Self>) -> reqwest::Client {
10613 self.redirect_client
10614 .get_or_init(|| {
10615 let context = Arc::downgrade(self);
10616 reqwest::Client::builder()
10617 .redirect(reqwest::redirect::Policy::custom(move |attempt| {
10618 if attempt.previous().len() >= 10 {
10619 return attempt.error("too many redirects");
10620 }
10621 if let Some(context) = context.upgrade() {
10622 if let Err(error) = context.charge_subrequest() {
10623 return attempt.error(RedirectSubrequestLimit(error));
10624 }
10625 }
10626 attempt.follow()
10627 }))
10628 .build()
10629 .expect("build the redirect-counting HTTP client")
10630 })
10631 .clone()
10632 }
10633
10634 /// Spend one subrequest from this invocation before the operation leaves
10635 /// the isolate. The failed attempt is counted too, so repeated catches
10636 /// cannot retry an operation that already exhausted the budget.
10637 fn charge_subrequest(&self) -> Result<(), String> {
10638 let Some(limit) = self.subrequest_limit else {
10639 return Ok(());
10640 };
10641 let used = self.subrequests.fetch_add(1, Ordering::Relaxed) + 1;
10642 if used > limit as usize {
10643 return Err(format!("Worker exceeded subrequest limit of {limit}"));
10644 }
10645 Ok(())
10646 }
10647
10648 fn begin_cpu_turn(&self) {
10649 if self.cpu_limit_nanos.is_none() {
10650 return;
10651 }
10652 *self.cpu_turn.lock().unwrap() = Some(CpuTurnStart {
10653 thread_nanos: thread_cpu_nanos(),
10654 wall: Instant::now(),
10655 });
10656 }
10657
10658 fn remaining_cpu_budget(&self) -> Option<Duration> {
10659 self.cpu_limit_nanos.map(|limit| {
10660 Duration::from_nanos(limit.saturating_sub(self.cpu_used_nanos.load(Ordering::Relaxed)))
10661 })
10662 }
10663
10664 fn finish_cpu_turn(&self) -> Result<(), String> {
10665 let Some(limit) = self.cpu_limit_nanos else {
10666 return Ok(());
10667 };
10668 let Some(started) = self.cpu_turn.lock().unwrap().take() else {
10669 return Ok(());
10670 };
10671 let elapsed = started
10672 .thread_nanos
10673 .zip(thread_cpu_nanos())
10674 .map(|(started, finished)| finished.saturating_sub(started))
10675 .unwrap_or_else(|| started.wall.elapsed().as_nanos() as u64);
10676 let used = self.cpu_used_nanos.fetch_add(elapsed, Ordering::Relaxed) + elapsed;
10677 if used > limit {
10678 return Err(format!(
10679 "Worker exceeded CPU limit of {} ms",
10680 limit / 1_000_000
10681 ));
10682 }
10683 Ok(())
10684 }
10685
10686 #[allow(clippy::new_ret_no_self, clippy::new_without_default)]
10687 #[doc(hidden)]
10688 pub fn new() -> Arc<Self> {
10689 Self::with_resource_limits(None)
10690 }
10691
10692 fn with_resource_limits(limits: Option<ResourceLimits>) -> Arc<Self> {
10693 Self::with_options(limits, false)
10694 }
10695
10696 #[cfg(all(test, celld_internal_tests))]
10697 fn with_tail_reporting(tail_reporting: bool) -> Arc<Self> {
10698 Self::with_options(None, tail_reporting)
10699 }
10700
10701 fn with_options(limits: Option<ResourceLimits>, tail_reporting: bool) -> Arc<Self> {
10702 Arc::new(Self {
10703 continuation: None,
10704 call_chains: Mutex::new(CallChains::default()),
10705 events: Mutex::new(IoEventState::default()),
10706 vfs: OnceLock::new(),
10707 sockets: Mutex::new(Vec::new()),
10708 rewriters: Mutex::new(Vec::new()),
10709 tcp_sockets: Mutex::new(Vec::new()),
10710 input_gates: Mutex::new(InputGateClaims::default()),
10711 cross_entry_gates: CrossEntryGateClaims::default(),
10712 body_streams: Mutex::new(HashMap::new()),
10713 ws_capture: Mutex::new(Vec::new()),
10714 egress: Mutex::new(Vec::new()),
10715 handed: Mutex::new(Some(Vec::new())),
10716 handed_len: AtomicUsize::new(0),
10717 handed_wake: tokio::sync::Notify::new(),
10718 pending_events: Mutex::new(HashSet::new()),
10719 subrequest_limit: limits.and_then(|limits| limits.sub_requests),
10720 subrequests: AtomicUsize::new(0),
10721 redirect_client: OnceLock::new(),
10722 cpu_limit_nanos: limits
10723 .and_then(|limits| limits.cpu_ms)
10724 .map(|milliseconds| u64::from(milliseconds).saturating_mul(1_000_000)),
10725 cpu_used_nanos: AtomicU64::new(0),
10726 cpu_turn: Mutex::new(None),
10727 tail_reporting,
10728 tail_logs: Mutex::new(TailLogCapture::default()),
10729 })
10730 }
10731
10732 fn tracked(runtime_state: &Arc<ActorRuntimeState>) -> Arc<Self> {
10733 let id = allocate_io_context_id();
10734 let context = Arc::new(Self {
10735 continuation: Some((id, Arc::downgrade(runtime_state))),
10736 call_chains: Mutex::new(CallChains::default()),
10737 events: Mutex::new(IoEventState::default()),
10738 vfs: OnceLock::new(),
10739 sockets: Mutex::new(Vec::new()),
10740 rewriters: Mutex::new(Vec::new()),
10741 tcp_sockets: Mutex::new(Vec::new()),
10742 input_gates: Mutex::new(InputGateClaims::default()),
10743 cross_entry_gates: CrossEntryGateClaims::default(),
10744 body_streams: Mutex::new(HashMap::new()),
10745 ws_capture: Mutex::new(Vec::new()),
10746 egress: Mutex::new(Vec::new()),
10747 handed: Mutex::new(Some(Vec::new())),
10748 handed_len: AtomicUsize::new(0),
10749 handed_wake: tokio::sync::Notify::new(),
10750 pending_events: Mutex::new(HashSet::new()),
10751 subrequest_limit: runtime_state
10752 .resource_limits
10753 .and_then(|limits| limits.sub_requests),
10754 subrequests: AtomicUsize::new(0),
10755 redirect_client: OnceLock::new(),
10756 cpu_limit_nanos: runtime_state
10757 .resource_limits
10758 .and_then(|limits| limits.cpu_ms)
10759 .map(|milliseconds| u64::from(milliseconds).saturating_mul(1_000_000)),
10760 cpu_used_nanos: AtomicU64::new(0),
10761 cpu_turn: Mutex::new(None),
10762 // Tracked contexts drive cell and RPC events. Dynamic Worker tail
10763 // reports currently belong only to fetch jobs, whose untracked
10764 // context is constructed from the report sender in `begin`.
10765 tail_reporting: false,
10766 tail_logs: Mutex::new(TailLogCapture::default()),
10767 });
10768 runtime_state
10769 .io_contexts
10770 .lock()
10771 .unwrap()
10772 .insert(id, Arc::downgrade(&context));
10773 context
10774 }
10775
10776 /// Take an op that another event's turn enqueued for this event.
10777 ///
10778 /// Reports whether the mailbox accepted it. A closed mailbox refuses, and
10779 /// the caller must then drop the op's resolver: this event will never run
10780 /// the continuation waiting on it.
10781 #[must_use]
10782 fn hand_op(&self, id: u64, future: asyncrt::OpFuture, lifetime: asyncrt::OpLifetime) -> bool {
10783 let mut handed = self.handed.lock().unwrap();
10784 let Some(queue) = handed.as_mut() else {
10785 return false;
10786 };
10787 queue.push((id, future, lifetime));
10788 // Published under the lock, so a reader that sees this count can take
10789 // the lock and find the op there.
10790 self.handed_len.store(queue.len(), Ordering::Release);
10791 drop(handed);
10792 self.handed_wake.notify_one();
10793 true
10794 }
10795
10796 /// Whether a foreign turn has left this event an op, without locking.
10797 ///
10798 /// A `false` answer is authoritative for the driver that asks it. Only
10799 /// that driver empties the queue, so nothing it must see can appear and
10800 /// vanish behind this read; a hand-off that lands immediately after it
10801 /// wakes the driver through `handed_ready` instead.
10802 fn has_handed_ops(&self) -> bool {
10803 self.handed_len.load(Ordering::Acquire) != 0
10804 }
10805
10806 fn accepts_handed_ops(&self) -> bool {
10807 self.handed.lock().unwrap().is_some()
10808 }
10809
10810 fn register_pending_event(&self, id: u64) {
10811 self.pending_events.lock().unwrap().insert(id);
10812 // The call can start during another event's microtask checkpoint,
10813 // after this context's driver has already parked. Wake that driver so
10814 // it can reject the call when no native operation can resume it.
10815 self.handed_wake.notify_one();
10816 }
10817
10818 fn finish_pending_event(&self, id: u64) {
10819 self.pending_events.lock().unwrap().remove(&id);
10820 }
10821
10822 fn has_pending_events(&self) -> bool {
10823 !self.pending_events.lock().unwrap().is_empty()
10824 }
10825
10826 fn take_pending_events(&self) -> Vec<u64> {
10827 let mut pending = self.pending_events.lock().unwrap();
10828 let mut ids = pending.drain().collect::<Vec<_>>();
10829 ids.sort_unstable();
10830 ids
10831 }
10832
10833 /// Resolve once another turn has handed this event an op or started a
10834 /// pending entrypoint call.
10835 ///
10836 /// This can also resolve with nothing to take, and a caller must treat
10837 /// an empty queue as ordinary. `notify_one` stores a permit when no
10838 /// driver is parked, and the driver takes the op on its next pass
10839 /// through `has_handed_ops` before it waits again, so the permit
10840 /// outlives the op it announced and releases one later wait early. That
10841 /// wait costs one atomic read and parks again, which is why the permit
10842 /// is left alone: cancelling it needs a second piece of state, and that
10843 /// state has to stay consistent with the queue.
10844 pub(crate) async fn handed_ready(&self) {
10845 self.handed_wake.notified().await;
10846 }
10847
10848 /// Hand this event's driver everything a foreign turn left for it.
10849 fn take_handed_ops(&self) -> Vec<HandedOp> {
10850 let mut handed = self.handed.lock().unwrap();
10851 self.handed_len.store(0, Ordering::Release);
10852 handed.as_mut().map(std::mem::take).unwrap_or_default()
10853 }
10854
10855 /// Close the mailbox and return whatever no driver took.
10856 ///
10857 /// Called when the event retires. The caller drops the resolvers of the
10858 /// ops that come back, and every later hand-off is refused at the source,
10859 /// so no op can sit here waiting for a driver that will never run again.
10860 #[must_use]
10861 fn close_handed_ops(&self) -> Vec<HandedOp> {
10862 let mut handed = self.handed.lock().unwrap();
10863 self.handed_len.store(0, Ordering::Release);
10864 handed.take().unwrap_or_default()
10865 }
10866
10867 fn begin_event(&self) {
10868 self.events
10869 .lock()
10870 .unwrap()
10871 .frames
10872 .push(IoEventFrame::default());
10873 }
10874
10875 fn release_input_gate(&self, cell: &str, event: celld_logic::gate::EventId) -> bool {
10876 let mut claims = self.input_gates.lock().unwrap();
10877 if !claims.held.get(&event).is_some_and(|owned| owned == cell) {
10878 return false;
10879 }
10880 claims.held.remove(&event);
10881 true
10882 }
10883
10884 fn retire_input_gates(&self) -> Vec<(String, celld_logic::gate::EventId)> {
10885 let mut claims = self.input_gates.lock().unwrap();
10886 claims.retired = true;
10887 claims.retirement.send_replace(true);
10888 let mut held = claims
10889 .held
10890 .drain()
10891 .map(|(event, cell)| (cell, event))
10892 .collect::<Vec<_>>();
10893 held.sort_unstable();
10894 held
10895 }
10896
10897 /// Pop the innermost frame and hand back what it collected. `None` when
10898 /// there is no frame, which is a script calling `waitUntil` outside any
10899 /// event; the harness turns that into workerd's global-scope error.
10900 fn end_event(&self) -> Option<Vec<v8::Global<v8::Promise>>> {
10901 let mut events = self.events.lock().unwrap();
10902 let mut frame = events.frames.pop()?;
10903 if events.arm_gates_sealed {
10904 drop(frame.arm_gates);
10905 } else if let Some(parent) = events.frames.last_mut() {
10906 parent.arm_gates.append(&mut frame.arm_gates);
10907 } else {
10908 events.ended_arm_gates.append(&mut frame.arm_gates);
10909 }
10910 if events.frames.is_empty() && !frame.wait_until.is_empty() {
10911 events.wait_until_active = true;
10912 }
10913 Some(frame.wait_until)
10914 }
10915
10916 fn register_wait_until(&self, promise: v8::Global<v8::Promise>) {
10917 let mut events = self.events.lock().unwrap();
10918 if let Some(frame) = events.frames.last_mut() {
10919 frame.wait_until.push(promise);
10920 } else if events.wait_until_active {
10921 events.late_wait_until.push(promise);
10922 }
10923 }
10924
10925 /// Whether imported `waitUntil()` has request-associated work to extend.
10926 fn accepts_wait_until(&self) -> bool {
10927 let events = self.events.lock().unwrap();
10928 !events.frames.is_empty() || events.wait_until_active
10929 }
10930
10931 /// Take registrations made while the current background aggregate ran.
10932 /// An empty batch seals the registration window together with the
10933 /// driver's decision to retire that aggregate.
10934 fn take_late_wait_until(&self) -> Vec<v8::Global<v8::Promise>> {
10935 let mut events = self.events.lock().unwrap();
10936 let late = std::mem::take(&mut events.late_wait_until);
10937 if late.is_empty() {
10938 events.wait_until_active = false;
10939 }
10940 late
10941 }
10942
10943 fn seal_wait_until(&self) {
10944 let mut events = self.events.lock().unwrap();
10945 events.wait_until_active = false;
10946 events.late_wait_until.clear();
10947 }
10948
10949 fn register_arm_gate(&self, gate: ArmGateRx) -> Result<(), ArmGateRx> {
10950 let mut events = self.events.lock().unwrap();
10951 if events.arm_gates_sealed {
10952 return Err(gate);
10953 }
10954 if let Some(frame) = events.frames.last_mut() {
10955 frame.arm_gates.push(gate);
10956 } else {
10957 // `op_event_end` pops the final frame before `Promise.allSettled`
10958 // can invoke a user-defined `then`. A gate created during that
10959 // call still belongs to this event until `take_arm_gates` seals
10960 // the response boundary.
10961 events.ended_arm_gates.push(gate);
10962 }
10963 Ok(())
10964 }
10965
10966 /// Take every response gate that this event owns.
10967 ///
10968 /// The normal path takes gates moved out by `end_event`. Active frames
10969 /// cover failures that cannot run JavaScript again, such as a timeout or
10970 /// an isolate termination.
10971 fn take_arm_gates(&self) -> Vec<ArmGateRx> {
10972 let mut events = self.events.lock().unwrap();
10973 if events.arm_gates_sealed {
10974 return Vec::new();
10975 }
10976 events.arm_gates_sealed = true;
10977 let mut gates = std::mem::take(&mut events.ended_arm_gates);
10978 for frame in &mut events.frames {
10979 gates.append(&mut frame.arm_gates);
10980 }
10981 gates
10982 }
10983
10984 fn depth(&self) -> usize {
10985 self.events.lock().unwrap().frames.len()
10986 }
10987
10988 /// Close every isolate-polled socket this request opened.
10989 ///
10990 /// Draining makes the operation idempotent. The drive loop calls it when
10991 /// the request retires, and `drop` covers every earlier failure path.
10992 fn close_sockets(&self) {
10993 let opened = self.sockets.lock().unwrap().drain(..).collect();
10994 ws_close_request_sockets(opened);
10995 let rewriters: Vec<u64> = self.rewriters.lock().unwrap().drain(..).collect();
10996 for id in rewriters {
10997 html_rewriter::free(id);
10998 }
10999 let tcp: Vec<u64> = self.tcp_sockets.lock().unwrap().drain(..).collect();
11000 for id in tcp {
11001 tcp::free(id);
11002 }
11003 }
11004
11005 #[doc(hidden)]
11006 pub fn own_body_stream(&self, stream_id: u64) {
11007 let Some(claim) = claim_http_stream(stream_id) else {
11008 return;
11009 };
11010 let replaced = self.body_streams.lock().unwrap().insert(stream_id, claim);
11011 // Releasing a claim can drop an arbitrary source. Keep that work out
11012 // of the request-ownership lock.
11013 drop(replaced);
11014 }
11015
11016 fn transfer_body_stream(&self, stream_id: u64) -> Option<RequestBodyGuard> {
11017 let claim = self.body_streams.lock().unwrap().remove(&stream_id)?;
11018 // Move the exact service claim into the guard. A later asynchronous
11019 // drop cannot resolve through another ambient Domain.
11020 Some(RequestBodyGuard::transferred(claim))
11021 }
11022
11023 /// Replace one request-owned source with the two sources created by a
11024 /// native tee. Response streams are not request-owned, so they keep the
11025 /// registry's ordinary unowned lifecycle.
11026 fn replace_body_stream(
11027 &self,
11028 stream_id: u64,
11029 service: &Arc<HttpStreamService>,
11030 branches: (u64, u64),
11031 ) {
11032 let original = self.body_streams.lock().unwrap().remove(&stream_id);
11033 let Some(original) = original else {
11034 return;
11035 };
11036 debug_assert!(Arc::ptr_eq(&original.service, service));
11037 let mut branch_claims = Vec::new();
11038 for branch in [branches.0, branches.1] {
11039 if let Some(claim) = service.claim(branch) {
11040 branch_claims.push((branch, claim));
11041 }
11042 }
11043 let replaced = {
11044 let mut owned = self.body_streams.lock().unwrap();
11045 branch_claims
11046 .into_iter()
11047 .filter_map(|(branch, claim)| owned.insert(branch, claim))
11048 .collect::<Vec<_>>()
11049 };
11050 // The original entry was consumed by tee, so releasing this claim is
11051 // a no-op. Replaced claims still release through their bound service.
11052 drop(original);
11053 drop(replaced);
11054 }
11055
11056 #[cfg(celld_internal_tests)]
11057 #[doc(hidden)]
11058 pub fn begin_event_for_test(&self) {
11059 self.begin_event();
11060 }
11061
11062 #[cfg(celld_internal_tests)]
11063 #[doc(hidden)]
11064 pub fn end_event_for_test(&self) -> Option<()> {
11065 self.end_event().map(drop)
11066 }
11067
11068 #[cfg(celld_internal_tests)]
11069 #[doc(hidden)]
11070 pub fn register_arm_gate_for_test(
11071 &self,
11072 gate: tokio::sync::oneshot::Receiver<Result<(), String>>,
11073 ) -> Result<(), tokio::sync::oneshot::Receiver<Result<(), String>>> {
11074 self.register_arm_gate(gate)
11075 }
11076
11077 #[cfg(celld_internal_tests)]
11078 #[doc(hidden)]
11079 pub fn take_arm_gates_for_test(
11080 &self,
11081 ) -> Vec<tokio::sync::oneshot::Receiver<Result<(), String>>> {
11082 self.take_arm_gates()
11083 }
11084}
11085
11086#[cfg(celld_internal_tests)]
11087#[doc(hidden)]
11088#[derive(Default)]
11089pub struct IoContextRegistryForTest(Arc<ActorRuntimeState>);
11090
11091#[cfg(celld_internal_tests)]
11092impl IoContextRegistryForTest {
11093 #[doc(hidden)]
11094 pub fn track(&self) -> (u64, Arc<IoContext>) {
11095 let context = IoContext::tracked(&self.0);
11096 let id = context
11097 .continuation
11098 .as_ref()
11099 .map(|(id, _)| *id)
11100 .expect("a tracked IoContext has a continuation id");
11101 (id, context)
11102 }
11103
11104 #[doc(hidden)]
11105 pub fn resolves_to(&self, id: u64, expected: &Arc<IoContext>) -> bool {
11106 self.0
11107 .io_context(id)
11108 .is_some_and(|context| Arc::ptr_eq(&context, expected))
11109 }
11110
11111 #[doc(hidden)]
11112 pub fn contains(&self, id: u64) -> bool {
11113 self.0.io_contexts.lock().unwrap().contains_key(&id)
11114 }
11115
11116 #[doc(hidden)]
11117 pub fn is_empty(&self) -> bool {
11118 self.0.io_contexts.lock().unwrap().is_empty()
11119 }
11120
11121 /// Hand `context` an op that never completes, and report whether its
11122 /// mailbox accepted it. The future stands in for real work: the mailbox
11123 /// only stores it, so nothing here polls it.
11124 #[doc(hidden)]
11125 pub fn hand_pending_op(&self, context: &Arc<IoContext>, id: u64) -> bool {
11126 context.hand_op(
11127 id,
11128 Box::pin(std::future::pending()),
11129 asyncrt::OpLifetime::Handler,
11130 )
11131 }
11132
11133 /// The op ids `context` still holds for a driver that has not taken them.
11134 #[doc(hidden)]
11135 pub fn handed_op_ids(&self, context: &Arc<IoContext>) -> Vec<u64> {
11136 context
11137 .handed
11138 .lock()
11139 .unwrap()
11140 .as_ref()
11141 .map(|queue| queue.iter().map(|(id, _, _)| *id).collect())
11142 .unwrap_or_default()
11143 }
11144
11145 /// Run the mailbox half of an event's retirement: close it, and report
11146 /// the ops whose resolvers `InFlight::abandon` must then drop.
11147 #[doc(hidden)]
11148 pub fn close_handed_ops(&self, context: &Arc<IoContext>) -> Vec<u64> {
11149 context
11150 .close_handed_ops()
11151 .into_iter()
11152 .map(|(id, _, _)| id)
11153 .collect()
11154 }
11155}
11156
11157/// A Worker socket lives and dies with its request, exactly as it does on
11158/// Cloudflare. Closing it here rather than at each of the drive loops' exits
11159/// is the difference between a rule every exit path has to remember and one
11160/// it cannot get wrong: a request that times out, that is abandoned as stuck,
11161/// or whose client disconnects drops its context on a path of its own.
11162impl Drop for IoContext {
11163 fn drop(&mut self) {
11164 let already_panicking = std::thread::panicking();
11165 // The drive loop also abandons these while it still owns the isolate,
11166 // because that path resets the JavaScript actor state. Drop is the
11167 // final host-side invariant for an earlier exit: no request context
11168 // can leave a process-wide input gate active after it is gone.
11169 let _ = abandon_context_input_gates(self);
11170 self.close_sockets();
11171 let mut claims = self
11172 .body_streams
11173 .get_mut()
11174 .unwrap()
11175 .drain()
11176 .collect::<Vec<_>>();
11177 // A claim can drop an arbitrary source. Fix the first-panic order even
11178 // when the request map uses a different randomized hash seed.
11179 claims.sort_unstable_by_key(|(stream_id, _)| *stream_id);
11180 let mut first_panic = None;
11181 for (_, claim) in claims {
11182 retain_first_http_cleanup_panic(
11183 &mut first_panic,
11184 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(claim))),
11185 );
11186 }
11187 if let Some((id, runtime_state)) = &self.continuation {
11188 if let Some(runtime_state) = runtime_state.upgrade() {
11189 runtime_state.io_contexts.lock().unwrap().remove(id);
11190 }
11191 }
11192 if let Some(payload) = first_panic {
11193 if already_panicking {
11194 std::mem::forget(payload);
11195 } else {
11196 std::panic::resume_unwind(payload);
11197 }
11198 }
11199 }
11200}
11201
11202/// What `OwnedIsolate::into_shared` demands of us: every slot value on a
11203/// shared isolate is reachable, and droppable, from whichever thread holds
11204/// the lock. The type system cannot check it at the call site, so it is
11205/// checked here instead.
11206const _: fn() = || {
11207 fn assert_send_sync<T: Send + Sync>() {}
11208 assert_send_sync::<HeapLimitState>();
11209 assert_send_sync::<ActorRuntimeState>();
11210 assert_send_sync::<ModuleRegistry>();
11211 assert_send_sync::<LoaderOwner>();
11212};
11213
11214/// A request must be able to carry its own context across a suspension. A
11215/// compile-time check, because losing it would surface as an unrelated
11216/// `Send` error wherever the request task is spawned.
11217const _: fn() = || {
11218 fn assert_send_sync<T: Send + Sync>() {}
11219 assert_send_sync::<Arc<IoContext>>();
11220};
11221
11222thread_local! {
11223 /// The request whose turn is running on this thread, or none between
11224 /// turns. Never set by JS.
11225 static CURRENT: RefCell<Option<Arc<IoContext>>> =
11226 const { RefCell::new(None) };
11227}
11228
11229/// Install `context` for the duration of a turn, restoring whatever was
11230/// current when the guard drops.
11231///
11232/// Restoring rather than clearing is what makes nested host dispatch safe: a
11233/// service binding runs a second handler inside the first one's turn, and the
11234/// outer request must still be current when it returns.
11235pub struct CurrentGuard(Option<Arc<IoContext>>);
11236
11237impl CurrentGuard {
11238 pub fn enter(context: Arc<IoContext>) -> Self {
11239 CurrentGuard(CURRENT.with(|current| current.borrow_mut().replace(context)))
11240 }
11241}
11242
11243impl Drop for CurrentGuard {
11244 fn drop(&mut self) {
11245 CURRENT.with(|current| *current.borrow_mut() = self.0.take());
11246 }
11247}
11248
11249/// The context this turn belongs to.
11250///
11251/// A thread that has not had one installed gets a default: every path that
11252/// runs JS without an explicit request context — a cell isolate, which the
11253/// DO contract already serializes, an RPC entry, a DO constructor — keeps
11254/// exactly the semantics it had when the stack lived in JS, one per isolate.
11255/// Isolation is a property of *installing* a context, so it arrives with the
11256/// paths that need it rather than being retrofitted to every caller at once.
11257fn current_context() -> Arc<IoContext> {
11258 CURRENT.with(|current| {
11259 let mut current = current.borrow_mut();
11260 current.get_or_insert_with(IoContext::new).clone()
11261 })
11262}
11263
11264#[cfg(celld_internal_tests)]
11265fn installed_context() -> Option<Arc<IoContext>> {
11266 CURRENT.with(|current| current.borrow().clone())
11267}
11268
11269fn op_event_begin(
11270 scope: &mut v8::PinScope,
11271 _args: v8::FunctionCallbackArguments,
11272 _rv: v8::ReturnValue<v8::Value>,
11273) {
11274 let _ = scope;
11275 current_context().begin_event();
11276}
11277
11278/// Pop the innermost event and return the aggregate of its `waitUntil`
11279/// promises, or null when it collected none. The aggregate is built here
11280/// rather than in JS because the promises live here: the host holds them for
11281/// the request, and the request is what the frame belongs to.
11282fn op_event_end<'s>(
11283 scope: &mut v8::PinScope<'s, '_>,
11284 _args: v8::FunctionCallbackArguments,
11285 mut rv: v8::ReturnValue<v8::Value>,
11286) {
11287 let Some(frame) = current_context().end_event() else {
11288 rv.set_null();
11289 return;
11290 };
11291 match wait_until_aggregate(scope, &frame) {
11292 Some(aggregate) => rv.set(aggregate.into()),
11293 None => rv.set_null(),
11294 }
11295}
11296
11297/// Resolve the request whose code is running, even when its reaction executes
11298/// during another request's microtask checkpoint. A missing captured context
11299/// is retired, so it must not fall back to the request driving this turn.
11300fn reaction_or_current_context(scope: &mut v8::PinScope) -> Option<Arc<IoContext>> {
11301 match reaction_continuation_id(scope) {
11302 Some(id) => actor_runtime_state(scope).io_context(id),
11303 None => Some(current_context()),
11304 }
11305}
11306
11307fn op_pending_event_begin(
11308 scope: &mut v8::PinScope,
11309 args: v8::FunctionCallbackArguments,
11310 _rv: v8::ReturnValue<v8::Value>,
11311) {
11312 let Some(id) = args.get(0).integer_value(scope) else {
11313 return;
11314 };
11315 if let Some(context) = reaction_or_current_context(scope) {
11316 context.register_pending_event(id as u64);
11317 }
11318}
11319
11320fn op_pending_event_end(
11321 scope: &mut v8::PinScope,
11322 args: v8::FunctionCallbackArguments,
11323 _rv: v8::ReturnValue<v8::Value>,
11324) {
11325 let Some(id) = args.get(0).integer_value(scope) else {
11326 return;
11327 };
11328 if let Some(context) = reaction_or_current_context(scope) {
11329 context.finish_pending_event(id as u64);
11330 }
11331}
11332
11333/// Create one directory in the current request's virtual `/tmp` tree.
11334/// A created path starts with `/`, an error is a Node code, and an empty string
11335/// means that no path must be returned. The disjoint representation keeps the
11336/// result and its meaning together without allocating a JS object for each
11337/// directory segment.
11338fn op_vfs_mkdir(
11339 scope: &mut v8::PinScope,
11340 args: v8::FunctionCallbackArguments,
11341 mut rv: v8::ReturnValue<v8::Value>,
11342) {
11343 let path = args.get(0).to_rust_string_lossy(scope);
11344 let recursive = args.get(1).boolean_value(scope);
11345 let result = current_context()
11346 .vfs
11347 .get_or_init(|| Mutex::new(RequestVfs::default()))
11348 .lock()
11349 .unwrap()
11350 .mkdir(&path, recursive);
11351 let result = match result {
11352 VfsMkdirResult::Created(Some(path)) => path,
11353 VfsMkdirResult::Created(None) => String::new(),
11354 VfsMkdirResult::Error(code) => code.to_string(),
11355 };
11356 rv.set(v8::String::new(scope, &result).unwrap().into());
11357}
11358
11359/// Return `[kind, size]`, where kind is 0 for a missing path, 1 for a
11360/// read-only directory, 2 for a writable directory, and 3 for a read-only
11361/// file. Only a file has a size; a directory reports 0, matching workerd.
11362///
11363/// The pair travels together because a caller that knows a path is a file
11364/// always needs its size to build `Stats`, and a second lookup could observe a
11365/// different tree.
11366fn op_vfs_stat(
11367 scope: &mut v8::PinScope,
11368 args: v8::FunctionCallbackArguments,
11369 mut rv: v8::ReturnValue<v8::Value>,
11370) {
11371 let path = args.get(0).to_rust_string_lossy(scope);
11372 let (kind, size) = match current_context()
11373 .vfs
11374 .get_or_init(|| Mutex::new(RequestVfs::default()))
11375 .lock()
11376 .unwrap()
11377 .stat(&path)
11378 {
11379 Some(writable) => (if writable { 2 } else { 1 }, 0),
11380 // Only a path the writable tree does not claim can be a bundle path,
11381 // so the request tree stays authoritative for `/tmp`.
11382 None => match bundle_node(scope, &path) {
11383 Some(BundleStat::Directory) => (1, 0),
11384 Some(BundleStat::File(size)) => (3, size),
11385 None => (0, 0),
11386 },
11387 };
11388 let pair = v8::Array::new(scope, 2);
11389 let kind = v8::Integer::new(scope, kind).into();
11390 let size = v8::Number::new(scope, size as f64).into();
11391 pair.set_index(scope, 0, kind);
11392 pair.set_index(scope, 1, size);
11393 rv.set(pair.into());
11394}
11395
11396/// What a bundle path is, without copying the bytes a stat does not need.
11397enum BundleStat {
11398 Directory,
11399 File(usize),
11400}
11401
11402/// Materializes `/bundle` on the first call that reaches it.
11403fn bundle_node(scope: &mut v8::PinScope, path: &str) -> Option<BundleStat> {
11404 let bundle = scope.get_slot::<Arc<BundleFs>>().cloned()?;
11405 match bundle.tree().nodes.get(path)? {
11406 BundleNode::Directory => Some(BundleStat::Directory),
11407 BundleNode::File(bytes) => Some(BundleStat::File(bytes.len())),
11408 }
11409}
11410
11411/// Read a whole bundle file. Returns an `ArrayBuffer` of the module's bytes,
11412/// or `null` when the path is not a bundle file, so the caller raises the
11413/// `ENOENT` that names the syscall it was performing.
11414fn op_vfs_read_file(
11415 scope: &mut v8::PinScope,
11416 args: v8::FunctionCallbackArguments,
11417 mut rv: v8::ReturnValue<v8::Value>,
11418) {
11419 let path = args.get(0).to_rust_string_lossy(scope);
11420 let Some(bundle) = scope.get_slot::<Arc<BundleFs>>().cloned() else {
11421 return;
11422 };
11423 let tree = bundle.tree();
11424 let Some(BundleNode::File(bytes)) = tree.nodes.get(&path) else {
11425 return;
11426 };
11427 // One copy into the V8 heap. The projected `Bytes` stays shared, so a
11428 // second read of the same module does not re-copy the config's source.
11429 let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes.to_vec()).make_shared();
11430 let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);
11431 rv.set(buffer.into());
11432}
11433
11434fn op_wait_until<'s>(
11435 scope: &mut v8::PinScope<'s, '_>,
11436 args: v8::FunctionCallbackArguments<'s>,
11437 _rv: v8::ReturnValue<v8::Value>,
11438) {
11439 let value = args.get(0);
11440 let promise = match value.try_cast::<v8::Promise>() {
11441 Ok(promise) => promise,
11442 Err(_) => match resolved_promise(scope, value) {
11443 Ok(promise) => promise,
11444 Err(_) => return,
11445 },
11446 };
11447 if let Some(context) = reaction_or_current_context(scope) {
11448 context.register_wait_until(v8::Global::new(scope, promise));
11449 }
11450}
11451
11452fn op_wait_until_active(
11453 scope: &mut v8::PinScope,
11454 _args: v8::FunctionCallbackArguments,
11455 mut rv: v8::ReturnValue<v8::Value>,
11456) {
11457 let active =
11458 reaction_or_current_context(scope).is_some_and(|context| context.accepts_wait_until());
11459 rv.set(v8::Boolean::new(scope, active).into());
11460}
11461
11462/// How many event frames are open on the current request.
11463fn op_event_depth(
11464 scope: &mut v8::PinScope,
11465 _args: v8::FunctionCallbackArguments,
11466 mut rv: v8::ReturnValue<v8::Value>,
11467) {
11468 let depth = current_context().depth();
11469 rv.set(v8::Integer::new(scope, depth as i32).into());
11470}
11471
11472/// `Promise.allSettled(values)`, from the context's own realm.
11473fn all_settled<'s>(
11474 scope: &mut v8::PinScope<'s, '_>,
11475 values: v8::Local<'s, v8::Value>,
11476) -> Option<v8::Local<'s, v8::Value>> {
11477 let global = scope.get_current_context().global(scope);
11478 let key = v8::String::new(scope, "Promise").unwrap();
11479 let promise_ctor: v8::Local<v8::Object> = global.get(scope, key.into())?.try_into().ok()?;
11480 let key = v8::String::new(scope, "allSettled").unwrap();
11481 let all_settled: v8::Local<v8::Function> =
11482 promise_ctor.get(scope, key.into())?.try_into().ok()?;
11483 all_settled.call(scope, promise_ctor.into(), &[values])
11484}
11485
11486fn op_als_get(
11487 scope: &mut v8::PinScope,
11488 _args: v8::FunctionCallbackArguments,
11489 mut rv: v8::ReturnValue<v8::Value>,
11490) {
11491 rv.set(cped_frame(scope));
11492}
11493
11494fn op_als_set(
11495 scope: &mut v8::PinScope,
11496 args: v8::FunctionCallbackArguments,
11497 _rv: v8::ReturnValue<v8::Value>,
11498) {
11499 let trace = cped_trace(scope);
11500 let io_context = cped_io_context(scope);
11501 set_cped(scope, args.get(0), trace, io_context);
11502}
11503
11504// node:util prelude calls these; registration is the sole per-isolate cost.
11505
11506/// Type-check bitmask. Bit order must match `T` in src/js/node_util.js.
11507fn op_util_type_flags(
11508 _scope: &mut v8::PinScope,
11509 args: v8::FunctionCallbackArguments,
11510 mut rv: v8::ReturnValue<v8::Value>,
11511) {
11512 let v = args.get(0);
11513 let checks: [bool; 27] = [
11514 v.is_external(),
11515 v.is_date(),
11516 v.is_arguments_object(),
11517 v.is_big_int_object(),
11518 v.is_boolean_object(),
11519 v.is_number_object(),
11520 v.is_string_object(),
11521 v.is_symbol_object(),
11522 v.is_native_error(),
11523 v.is_reg_exp(),
11524 v.is_async_function(),
11525 v.is_generator_function(),
11526 v.is_generator_object(),
11527 v.is_promise(),
11528 v.is_map(),
11529 v.is_set(),
11530 v.is_map_iterator(),
11531 v.is_set_iterator(),
11532 v.is_weak_map(),
11533 v.is_weak_set(),
11534 v.is_array_buffer(),
11535 v.is_data_view(),
11536 v.is_shared_array_buffer(),
11537 v.is_proxy(),
11538 v.is_module_namespace_object(),
11539 v.is_typed_array(),
11540 v.is_array_buffer_view(),
11541 ];
11542 let mut flags: u32 = 0;
11543 for (i, hit) in checks.iter().enumerate() {
11544 if *hit {
11545 flags |= 1 << i;
11546 }
11547 }
11548 rv.set_uint32(flags);
11549}
11550
11551fn op_util_constructor_name(
11552 _scope: &mut v8::PinScope,
11553 args: v8::FunctionCallbackArguments,
11554 mut rv: v8::ReturnValue<v8::Value>,
11555) {
11556 let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
11557 return; // undefined
11558 };
11559 rv.set(obj.get_constructor_name().into());
11560}
11561
11562/// `[target, handler]` for a proxy, undefined otherwise.
11563fn op_util_proxy_details(
11564 scope: &mut v8::PinScope,
11565 args: v8::FunctionCallbackArguments,
11566 mut rv: v8::ReturnValue<v8::Value>,
11567) {
11568 let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(args.get(0)) else {
11569 return;
11570 };
11571 let target = proxy.get_target(scope);
11572 let handler = proxy.get_handler(scope);
11573 rv.set(v8::Array::new_with_elements(scope, &[target, handler]).into());
11574}
11575
11576/// `[state]` for a pending promise, `[state, result]` otherwise,
11577/// undefined for a non-promise. States: 0 pending, 1 fulfilled, 2 rejected.
11578fn op_util_promise_details(
11579 scope: &mut v8::PinScope,
11580 args: v8::FunctionCallbackArguments,
11581 mut rv: v8::ReturnValue<v8::Value>,
11582) {
11583 let Ok(promise) = v8::Local::<v8::Promise>::try_from(args.get(0)) else {
11584 return;
11585 };
11586 let state = match promise.state() {
11587 v8::PromiseState::Pending => 0,
11588 v8::PromiseState::Fulfilled => 1,
11589 v8::PromiseState::Rejected => 2,
11590 };
11591 let pending = state == 0;
11592 let state: v8::Local<v8::Value> = v8::Integer::new(scope, state).into();
11593 let elements = if pending {
11594 vec![state]
11595 } else {
11596 vec![state, promise.result(scope)]
11597 };
11598 rv.set(v8::Array::new_with_elements(scope, &elements).into());
11599}
11600
11601/// `[entries, isKeyValue]` for collections and their iterators (V8's
11602/// PreviewEntries), undefined when V8 has no preview.
11603fn op_util_preview_entries(
11604 scope: &mut v8::PinScope,
11605 args: v8::FunctionCallbackArguments,
11606 mut rv: v8::ReturnValue<v8::Value>,
11607) {
11608 let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
11609 return;
11610 };
11611 let (entries, is_key_value) = obj.preview_entries(scope);
11612 let Some(entries) = entries else { return };
11613 let flag: v8::Local<v8::Value> = v8::Boolean::new(scope, is_key_value).into();
11614 rv.set(v8::Array::new_with_elements(scope, &[entries.into(), flag]).into());
11615}
11616
11617fn op_alarm_set(
11618 scope: &mut v8::PinScope,
11619 args: v8::FunctionCallbackArguments,
11620 _rv: v8::ReturnValue<v8::Value>,
11621) {
11622 let s = args.get(0).to_rust_string_lossy(scope);
11623 let at = args.get(1).number_value(scope).unwrap_or(0.0) as i64;
11624 let timing_started = (tracing::enabled!(target: "queue_timing", tracing::Level::DEBUG)
11625 && s.split_once(':')
11626 .is_some_and(|(class, _)| class == crate::deploy::QUEUE_CLASS))
11627 .then(crate::asyncrt::mono_us);
11628 let result = storage::set_alarm(&s, at);
11629 if let Some(timing_started) = timing_started {
11630 tracing::debug!(
11631 target: "queue_timing",
11632 event = "queue_alarm_write_timing",
11633 total_us = crate::asyncrt::mono_us().saturating_sub(timing_started),
11634 ok = result.is_ok(),
11635 "Queue alarm write completed"
11636 );
11637 }
11638 match result {
11639 Err(error) => throw_storage_error(scope, "setAlarm", error),
11640 // Committed immediately: register the wake-entry PUT against the
11641 // current event's output gate. Inside an explicit transaction (`Ok(None)`)
11642 // the gate registers at that transaction's commit instead.
11643 Ok(Some(committed)) if committed >= 0 => {
11644 spawn_arm_gate(&s, committed, current_reaction_io_context(scope))
11645 }
11646 Ok(_) => {}
11647 }
11648}
11649
11650/// Queue producer groups resolve promises from several cell events after one
11651/// event rearms the broker. The ordinary event-local arm gate cannot migrate
11652/// to those other events, so this internal variant awaits the wake-entry PUT
11653/// before the shared promise resolves. The later output gate still proves the
11654/// SQLite/LTX write; together they preserve the same acknowledgement boundary
11655/// as an ungrouped `setAlarm` call.
11656fn op_queue_alarm_set_wait(
11657 scope: &mut v8::PinScope,
11658 args: v8::FunctionCallbackArguments,
11659 mut rv: v8::ReturnValue<v8::Value>,
11660) {
11661 let cell = args.get(0).to_rust_string_lossy(scope);
11662 let at_ms = args.get(1).number_value(scope).unwrap_or(0.0) as i64;
11663 let committed = match storage::set_alarm(&cell, at_ms) {
11664 Ok(committed) => committed,
11665 Err(error) => {
11666 throw_storage_error(scope, "Queue setAlarm", error);
11667 return;
11668 }
11669 };
11670 let Some(committed) = committed.filter(|committed| *committed >= 0) else {
11671 return;
11672 };
11673 let Some(gate) = launch_arm_gate(&cell, observe_alarm(&cell, Some(committed))) else {
11674 return;
11675 };
11676 let id = asyncrt::enqueue(async move {
11677 match gate.await {
11678 Ok(Ok(())) => Ok(String::new()),
11679 Ok(Err(error)) => Err(format!("Queue wake-entry gate: {error}")),
11680 Err(_) => Err("Queue wake-entry gate task dropped".to_string()),
11681 }
11682 });
11683 rv.set(promise_for(scope, id));
11684}
11685fn op_alarm_get(
11686 scope: &mut v8::PinScope,
11687 args: v8::FunctionCallbackArguments,
11688 mut rv: v8::ReturnValue<v8::Value>,
11689) {
11690 let s = args.get(0).to_rust_string_lossy(scope);
11691 match storage::get_alarm(&s) {
11692 Some(at) => rv.set(v8::Number::new(scope, at as f64).into()),
11693 None => rv.set(v8::null(scope).into()),
11694 }
11695}
11696fn op_alarm_delete(
11697 scope: &mut v8::PinScope,
11698 args: v8::FunctionCallbackArguments,
11699 _rv: v8::ReturnValue<v8::Value>,
11700) {
11701 let s = args.get(0).to_rust_string_lossy(scope);
11702 if let Err(error) = storage::delete_alarm(&s) {
11703 throw_storage_error(scope, "deleteAlarm", error);
11704 }
11705}
11706
11707/// The reserved cron cell's whole schedule decision, in one call so the policy
11708/// has one home in `celld_logic::cron` rather than a JavaScript copy that can
11709/// drift from it.
11710///
11711/// `firedMs` is the occurrence being handled, or negative when the cell is
11712/// only arming. Returns `{ matching, armAt, armIsRetry }`: which expressions
11713/// the occurrence belongs to, by index into the list passed in, when to arm
11714/// next — `null` when the schedule is exhausted and the cell should retire —
11715/// and whether that deadline is the failure backoff rather than the next
11716/// occurrence.
11717fn op_cron_plan(
11718 scope: &mut v8::PinScope,
11719 args: v8::FunctionCallbackArguments,
11720 mut rv: v8::ReturnValue<v8::Value>,
11721) {
11722 let Ok(list) = v8::Local::<v8::Array>::try_from(args.get(0)) else {
11723 return;
11724 };
11725 let mut crons = Vec::with_capacity(list.length() as usize);
11726 // Where each parsed expression sits in the list the caller passed. A
11727 // malformed expression is already refused by `celld deploy`, but the
11728 // control plane checks only the field count, so one can still arrive here.
11729 // Skipping it keeps one bad entry from silencing a script's other crons,
11730 // and this map is what keeps the skip from renumbering them: the caller
11731 // reports `controller.cron` by index, so a shifted index names the wrong
11732 // expression for every entry after the bad one.
11733 let mut positions = Vec::with_capacity(list.length() as usize);
11734 for index in 0..list.length() {
11735 let Some(value) = list.get_index(scope, index) else {
11736 continue;
11737 };
11738 if let Ok(cron) = celld_logic::cron::parse(&value.to_rust_string_lossy(scope)) {
11739 crons.push(cron);
11740 positions.push(index as usize);
11741 }
11742 }
11743 let fired_ms = args.get(1).number_value(scope).unwrap_or(-1.0) as i64;
11744 let now_ms = args.get(2).number_value(scope).unwrap_or(0.0) as i64;
11745 let retry = args.get(3).number_value(scope).unwrap_or(0.0) as i64;
11746 let failed = args.get(4).boolean_value(scope);
11747
11748 let celld_logic::cron::Plan {
11749 matching,
11750 arm_at,
11751 arm_is_retry,
11752 } = celld_logic::cron::plan(
11753 &crons,
11754 (fired_ms >= 0).then_some(fired_ms),
11755 now_ms,
11756 retry,
11757 failed,
11758 );
11759
11760 let indices = v8::Array::new(scope, matching.len() as i32);
11761 for (slot, index) in matching.iter().enumerate() {
11762 let value = v8::Number::new(scope, positions[*index] as f64);
11763 indices.set_index(scope, slot as u32, value.into());
11764 }
11765 let result = v8::Object::new(scope);
11766 let key = v8::String::new(scope, "matching").unwrap();
11767 result.set(scope, key.into(), indices.into());
11768 let key = v8::String::new(scope, "armAt").unwrap();
11769 let value: v8::Local<v8::Value> = match arm_at {
11770 Some(at) => v8::Number::new(scope, at as f64).into(),
11771 None => v8::null(scope).into(),
11772 };
11773 result.set(scope, key.into(), value);
11774 let key = v8::String::new(scope, "armIsRetry").unwrap();
11775 let value = v8::Boolean::new(scope, arm_is_retry);
11776 result.set(scope, key.into(), value.into());
11777 rv.set(result.into());
11778}
11779
11780fn op_btoa(
11781 scope: &mut v8::PinScope,
11782 args: v8::FunctionCallbackArguments,
11783 mut rv: v8::ReturnValue<v8::Value>,
11784) {
11785 use base64::Engine;
11786 // The public `btoa()` wrapper always supplies a string. The KV operator
11787 // protocol supplies a typed view directly, which avoids constructing a
11788 // second 25 MiB binary string only to encode it here.
11789 let bytes = view_bytes(args.get(0)).unwrap_or_else(|| {
11790 args.get(0)
11791 .to_rust_string_lossy(scope)
11792 .chars()
11793 .map(|c| c as u8)
11794 .collect()
11795 });
11796 let s = base64::engine::general_purpose::STANDARD.encode(bytes);
11797 rv.set(v8::String::new(scope, &s).unwrap().into());
11798}
11799
11800// ---- WHATWG text decoders (encoding_rs) ----
11801//
11802// These ops back every TextDecoder decode. src/js/text_encoding.js
11803// resolves the label and owns the decoder's lifetime, and encoding_rs
11804// does the decoding — for utf-8 and utf-16 as much as for every other
11805// WHATWG label (windows-1252, Big5, GBK/GB18030, ISO-2022-JP,
11806// x-user-defined, …). Previous utf-8 and utf-16 JS decoders were slower
11807// than these ops at every measured size.
11808// Streaming decoders live in a per-isolate table keyed by id; JS frees
11809// one on the final decode (last=true), on a fatal error (encoding_rs
11810// poisons an errored decoder), or via FinalizationRegistry when a
11811// mid-stream decoder is abandoned. Ids are never reused, so a late
11812// finalizer free of an already-closed id is a no-op.
11813
11814/// Live streaming decoders for one isolate, keyed by an id JS holds across
11815/// awaits.
11816///
11817/// An isolate slot rather than a process-wide `Mutex<HashMap<..>>` like
11818/// [`zlib_streams`]. The reason that one is process-wide holds here too — a
11819/// `TextDecoder` in streaming mode outlives the turn that made it, and the
11820/// next turn can run on a different tokio worker — but it argues against a
11821/// *thread-local*, not against this. A `TextDecoder` is a JS object, so it
11822/// never leaves the isolate that made it, and every op that touches its
11823/// decoder runs under that isolate's `v8::Locker`. The lock the embedder
11824/// already holds is what makes the access exclusive, which `&mut Isolate`
11825/// on the slot then proves. A second lock inside it buys nothing.
11826///
11827/// This removes a ceiling rather than a measured regression, and the
11828/// difference matters. In isolation the pattern does collapse: replayed on
11829/// its own — remove, decode outside the lock, insert — 256-byte chunks
11830/// peaked at two threads and then went *backwards*, 8 threads serving
11831/// 0.46x what 1 thread served against 6.7x for the same decoding with no
11832/// table. But celld end to end shows no difference between the two, at any
11833/// concurrency this hardware can drive, because a chunk costs about 42us
11834/// of stream and turn machinery around a lock held for about 100ns. So the
11835/// mutex was not what any cell was waiting on. It was a process-wide
11836/// serialisation point on a path that every stream now takes, and it went
11837/// because it does not need to exist, not because it was costing anything
11838/// yet.
11839///
11840/// Dropping the isolate drops the table, so a decoder abandoned by a cell
11841/// that goes away needs no finalizer to run.
11842#[derive(Default)]
11843struct TextDecoders(HashMap<u64, encoding_rs::Decoder>);
11844
11845static TEXT_DECODER_NEXT: AtomicU64 = AtomicU64::new(1);
11846
11847/// The calling isolate's decoder table, created on first use.
11848fn text_decoders<'a>(scope: &'a mut v8::PinScope) -> &'a mut HashMap<u64, encoding_rs::Decoder> {
11849 if scope.get_slot::<TextDecoders>().is_none() {
11850 scope.set_slot(TextDecoders::default());
11851 }
11852 &mut scope.get_slot_mut::<TextDecoders>().expect("just set").0
11853}
11854
11855/// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined
11856/// for unknown labels and the replacement encoding (RangeError in JS).
11857fn op_text_decoder_label(
11858 scope: &mut v8::PinScope,
11859 args: v8::FunctionCallbackArguments,
11860 mut rv: v8::ReturnValue<v8::Value>,
11861) {
11862 let label = args.get(0).to_rust_string_lossy(scope);
11863 if let Some(enc) = encoding_rs::Encoding::for_label_no_replacement(label.as_bytes()) {
11864 let name = enc.name().to_ascii_lowercase();
11865 rv.set(v8::String::new(scope, &name).unwrap().into());
11866 }
11867}
11868
11869/// `$$textDecoderNew(name, ignoreBOM)` -> id.
11870fn op_text_decoder_new(
11871 scope: &mut v8::PinScope,
11872 args: v8::FunctionCallbackArguments,
11873 mut rv: v8::ReturnValue<v8::Value>,
11874) {
11875 let name = args.get(0).to_rust_string_lossy(scope);
11876 let ignore_bom = args.get(1).boolean_value(scope);
11877 let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label");
11878 let dec = if ignore_bom {
11879 enc.new_decoder_without_bom_handling()
11880 } else {
11881 enc.new_decoder_with_bom_removal()
11882 };
11883 let id = TEXT_DECODER_NEXT.fetch_add(1, Ordering::Relaxed);
11884 text_decoders(scope).insert(id, dec);
11885 rv.set(v8::Number::new(scope, id as f64).into());
11886}
11887
11888/// `$$textDecoderDecode(id, view, fatal, last)` -> string. Frees the
11889/// decoder when `last` is true or on a fatal malformed sequence
11890/// (TypeError).
11891fn op_text_decoder_decode(
11892 scope: &mut v8::PinScope,
11893 args: v8::FunctionCallbackArguments,
11894 mut rv: v8::ReturnValue<v8::Value>,
11895) {
11896 let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
11897 let bytes = view_bytes(args.get(1)).unwrap_or_default();
11898 let fatal = args.get(2).boolean_value(scope);
11899 let last = args.get(3).boolean_value(scope);
11900 // Per spec an empty streaming chunk is a no-op, but encoding_rs
11901 // 0.8 flushes a pending multibyte lead when fed an empty non-last
11902 // slice (e.g. Shift_JIS 0x82, "", 0xA0 would yield U+FFFD instead
11903 // of あ). Skip the decoder entirely.
11904 if bytes.is_empty() && !last {
11905 rv.set(v8::String::empty(scope).into());
11906 return;
11907 }
11908 let mut dec = text_decoders(scope)
11909 .remove(&id)
11910 .expect("JS holds the only live id");
11911 let Ok(out) = run_decoder(&mut dec, &bytes, fatal, last) else {
11912 throw_invalid_encoded_data(scope);
11913 return;
11914 };
11915 if !last {
11916 text_decoders(scope).insert(id, dec);
11917 }
11918 rv.set(v8::String::new(scope, &out).unwrap().into());
11919}
11920
11921/// `$$textDecoderDecodeOnce(name, view, fatal, ignoreBOM)` -> string, for
11922/// a complete buffer.
11923///
11924/// The whole decode is one call, so the decoder never outlives it and
11925/// never reaches [`text_decoders`]. That saves an insert and a remove,
11926/// and it keeps every non-streaming decode on the node off a table that
11927/// is one mutex for the whole process — which is most decodes, because
11928/// `request.text()` and `response.text()` are not streams. A stream
11929/// still takes that lock twice per chunk, which is a cost per chunk
11930/// rather than per byte, and it has not been measured under load;
11931/// sharding the table is the answer if it ever shows.
11932fn op_text_decoder_decode_once(
11933 scope: &mut v8::PinScope,
11934 args: v8::FunctionCallbackArguments,
11935 mut rv: v8::ReturnValue<v8::Value>,
11936) {
11937 let name = args.get(0).to_rust_string_lossy(scope);
11938 let bytes = view_bytes(args.get(1)).unwrap_or_default();
11939 let fatal = args.get(2).boolean_value(scope);
11940 let ignore_bom = args.get(3).boolean_value(scope);
11941 let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label");
11942 let mut dec = if ignore_bom {
11943 enc.new_decoder_without_bom_handling()
11944 } else {
11945 enc.new_decoder_with_bom_removal()
11946 };
11947 match run_decoder(&mut dec, &bytes, fatal, true) {
11948 Ok(out) => rv.set(v8::String::new(scope, &out).unwrap().into()),
11949 Err(()) => throw_invalid_encoded_data(scope),
11950 }
11951}
11952
11953/// Feeds `bytes` to `dec` and answers the text. `Err` means `fatal` was
11954/// set and the input was malformed.
11955fn run_decoder(
11956 dec: &mut encoding_rs::Decoder,
11957 bytes: &[u8],
11958 fatal: bool,
11959 last: bool,
11960) -> Result<String, ()> {
11961 let mut out = String::new();
11962 if fatal {
11963 let cap = dec
11964 .max_utf8_buffer_length_without_replacement(bytes.len())
11965 .unwrap();
11966 out.reserve(cap);
11967 if !matches!(
11968 dec.decode_to_string_without_replacement(bytes, &mut out, last),
11969 (encoding_rs::DecoderResult::InputEmpty, _),
11970 ) {
11971 return Err(());
11972 }
11973 } else {
11974 let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap();
11975 out.reserve(cap);
11976 let _ = dec.decode_to_string(bytes, &mut out, last);
11977 }
11978 Ok(out)
11979}
11980
11981fn throw_invalid_encoded_data(scope: &mut v8::PinScope) {
11982 let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap();
11983 let exc = v8::Exception::type_error(scope, msg);
11984 scope.throw_exception(exc);
11985}
11986
11987/// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder
11988/// abandoned mid-stream.
11989fn op_text_decoder_free(
11990 scope: &mut v8::PinScope,
11991 args: v8::FunctionCallbackArguments,
11992 _rv: v8::ReturnValue<v8::Value>,
11993) {
11994 let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
11995 text_decoders(scope).remove(&id);
11996}
11997
11998// ---- the JS harness: Web API + the DO object model ----
11999
12000#[doc(hidden)]
12001pub mod bootstrap;
12002pub mod modules;
12003mod v8_strings;
12004use bootstrap::{
12005 adopt_cell, adopt_embedded_cell, begin_event_context, build_env, end_event_context,
12006 harness_env, inject_compatibility_flags, inject_containers, inject_crons, inject_kv_limits,
12007 inject_namespace_keys, inject_queue_config, inject_routing, inject_storage_compatibility,
12008 inject_workflows, install_harness, install_prelude, populate_cf_exports, register_class,
12009 register_entrypoints, validate_workflow_classes, EmbeddedStartup,
12010};
12011use modules::{
12012 compile_module, host_import_module_dynamically, install_lazy_globals, op_builtin_module,
12013 register_loader_modules, register_stubs, register_wasm_modules, resolve_external,
12014 ModuleRegistry,
12015};
12016use v8_strings::key as static_key;
12017/// Like `make_request`, but marks the request as incoming. Its signal is
12018/// registered only if the handler actually suspends, preserving the
12019/// synchronous request path.
12020fn make_incoming_request<'s>(
12021 tc: &mut v8::PinScope<'s, '_>,
12022 url: &str,
12023 method: &str,
12024 body: RequestBody,
12025 headers: &[(String, String)],
12026) -> Result<v8::Local<'s, v8::Value>> {
12027 let f = internal_function(tc, "__makeIncomingRequest")?;
12028 let url = v8::String::new(tc, url).unwrap();
12029 let method = v8::String::new(tc, method).unwrap();
12030 let headers = v8::String::new(
12031 tc,
12032 &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()),
12033 )
12034 .unwrap();
12035 // A streamed body passes its id, and the harness builds the body
12036 // stream around that id. A held body passes the bytes.
12037 let stream_id = body.stream_id();
12038 let (body, stream_id) = match stream_id {
12039 None => (
12040 bytes_value(tc, body.into_held_bytes().unwrap()),
12041 v8::undefined(tc).into(),
12042 ),
12043 Some(id) => (
12044 v8::undefined(tc).into(),
12045 v8::Number::new(tc, id as f64).into(),
12046 ),
12047 };
12048 let recv = v8::undefined(tc).into();
12049 f.call(
12050 tc,
12051 recv,
12052 &[url.into(), method.into(), body, headers.into(), stream_id],
12053 )
12054 .ok_or_else(|| anyhow!("__makeIncomingRequest threw"))
12055}
12056
12057fn register_incoming_request(
12058 tc: &mut v8::PinScope,
12059 request_id: RequestId,
12060 request: v8::Local<v8::Value>,
12061) -> Result<()> {
12062 let function = internal_function(tc, "__registerIncomingRequest")?;
12063 let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
12064 let recv = v8::undefined(tc).into();
12065 function
12066 .call(tc, recv, &[id.into(), request])
12067 .ok_or_else(|| anyhow!("__registerIncomingRequest threw"))?;
12068 Ok(())
12069}
12070
12071fn finish_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) {
12072 let Ok(function) = internal_function(tc, "__finishIncomingRequest") else {
12073 return;
12074 };
12075 let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
12076 let recv = v8::undefined(tc).into();
12077 let _ = function.call(tc, recv, &[id.into()]);
12078}
12079
12080fn make_request<'s>(
12081 tc: &mut v8::PinScope<'s, '_>,
12082 url: &str,
12083 method: &str,
12084 body: RequestBody,
12085 headers: &[(String, String)],
12086) -> Result<v8::Local<'s, v8::Value>> {
12087 let f = internal_function(tc, "__makeRequest")?;
12088 let u = v8::String::new(tc, url).unwrap();
12089 let m = v8::String::new(tc, method).unwrap();
12090 let bytes = body.into_held_bytes().unwrap_or_default();
12091 let b = bytes_value(tc, bytes);
12092 let h = v8::String::new(tc, &serde_json::to_string(headers)?).unwrap();
12093 let recv = v8::undefined(tc).into();
12094 f.call(tc, recv, &[u.into(), m.into(), b, h.into()])
12095 .ok_or_else(|| anyhow!("makeRequest threw"))
12096}
12097
12098fn read_response(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> Result<HttpResponse> {
12099 let f = internal_function(scope, "__readResponse")?;
12100 let recv = v8::undefined(scope).into();
12101 let out = f
12102 .call(scope, recv, &[ret])
12103 .ok_or_else(|| anyhow!("readResponse threw"))?;
12104 // The harness response reader is synchronous. Keeping this assertion at
12105 // the native boundary prevents a future harness change from quietly
12106 // reintroducing a nested async runtime while an isolate is entered.
12107 if out.is_promise() {
12108 return Err(anyhow!("__readResponse returned a promise"));
12109 }
12110 let out = out.to_object(scope).ok_or_else(|| anyhow!("not object"))?;
12111 let ek = v8::String::new(scope, "error").unwrap();
12112 if let Some(error) = out.get(scope, ek.into()).filter(|value| value.is_string()) {
12113 return Err(anyhow!(error.to_rust_string_lossy(scope)));
12114 }
12115 let sk = v8::String::new(scope, "status").unwrap();
12116 let bk = v8::String::new(scope, "bodyBytes").unwrap();
12117 let tk = v8::String::new(scope, "bodyStreamId").unwrap();
12118 let hk = v8::String::new(scope, "headersJson").unwrap();
12119 let wk = v8::String::new(scope, "wsTargetJson").unwrap();
12120 let worker_wk = v8::String::new(scope, "workerSocketId").unwrap();
12121 let status = out
12122 .get(scope, sk.into())
12123 .and_then(|v| v.uint32_value(scope))
12124 .unwrap_or(200) as u16;
12125 // Body bytes cross as a Uint8Array copied directly out of V8 — no JSON
12126 // number array (which was ~4x the bytes to serialize + parse per response).
12127 let body = out
12128 .get(scope, bk.into())
12129 .and_then(|v| v8::Local::<v8::ArrayBufferView>::try_from(v).ok())
12130 .map(|view| {
12131 let mut buf = vec![0u8; view.byte_length()];
12132 view.copy_contents(&mut buf);
12133 buf
12134 })
12135 .unwrap_or_default();
12136 let stream_id = out
12137 .get(scope, tk.into())
12138 .and_then(|value| value.integer_value(scope))
12139 .unwrap_or(0)
12140 .max(0) as u64;
12141 let stream = if stream_id == 0 {
12142 None
12143 } else {
12144 http_stream_service()
12145 .checkout_transfer(stream_id, None)
12146 .ok()
12147 .map(|source| Box::pin(source) as HttpChunkStream)
12148 };
12149 if stream_id != 0 && stream.is_none() {
12150 return Err(anyhow!(
12151 "response stream {stream_id} is no longer available"
12152 ));
12153 }
12154 let headers = out
12155 .get(scope, hk.into())
12156 .and_then(|v| serde_json::from_str(&v.to_rust_string_lossy(scope)).ok())
12157 .unwrap_or_default();
12158 let ws_json = out
12159 .get(scope, wk.into())
12160 .map(|v| v.to_rust_string_lossy(scope))
12161 .unwrap_or_else(|| "null".into());
12162 let ws = serde_json::from_str(&ws_json).ok();
12163 let worker_id = out
12164 .get(scope, worker_wk.into())
12165 .and_then(|value| value.integer_value(scope))
12166 .unwrap_or(0)
12167 .max(0) as u64;
12168 let worker_ws = if worker_id == 0 {
12169 None
12170 } else {
12171 Some(
12172 websocket::transfer_worker_websocket_handoff(worker_id)
12173 .ok_or_else(|| anyhow!("Worker WebSocket {worker_id} has no frame handoff"))?,
12174 )
12175 };
12176 if status == 101 {
12177 tracing::info!(%ws_json, has_target = ws.is_some(), "JS WebSocket response");
12178 }
12179 let websocket = match (ws, worker_ws) {
12180 (Some(target), None) => Some(HttpResponseWebSocket::Cell(target)),
12181 (None, Some(worker)) => Some(HttpResponseWebSocket::Worker(worker)),
12182 (None, None) => None,
12183 (Some(_), Some(_)) => return Err(anyhow!("Worker response has two WebSocket targets")),
12184 };
12185 Ok(HttpResponse {
12186 status,
12187 body,
12188 stream,
12189 headers,
12190 websocket,
12191 write_position: None,
12192 observed_position: None,
12193 })
12194}
12195
12196#[cfg(celld_internal_tests)]
12197#[doc(hidden)]
12198pub fn init_engine_for_tests() {
12199 Engine::init();
12200}
12201
12202#[cfg(celld_internal_tests)]
12203include!(env!("CELLD_INTERNAL_JS_OBSERVERS"));