Diffinery

homeflare/celldpublic

12394 lines · 483.0 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 /// Released after the first turn, so the socket can deliver the next
618 /// message in order without waiting for this handler's async work.
619 started: Option<tokio::sync::oneshot::Sender<()>>,
620 reply: tokio::sync::oneshot::Sender<Result<WsDispatch>>,
621 },
622 WsClosed {
623 scope: String,
624 ws_id: u64,
625 code: u16,
626 reason: String,
627 was_clean: bool,
628 reply: tokio::sync::oneshot::Sender<Result<Option<u64>>>,
629 },
630 Alarm {
631 /// The shell task identity used to interrupt a firing during drain.
632 request_id: Option<RequestId>,
633 scope: String,
634 scheduled_ms: i64,
635 /// Which alarm to run, and who owns the bookkeeping.
636 claim: AlarmDispatch,
637 /// Replies with (next alarm, the handler's write delta). The delta is
638 /// sampled inside the turn — cell storage must never be reached from
639 /// the shell — and the shell uses it to prove the consuming commit
640 /// durable before the core settles. Every answer shape samples it the
641 /// same way now, in `InFlight::answer_settled`.
642 reply:
643 tokio::sync::oneshot::Sender<Result<(celld_logic::wake::AlarmSnapshot, Option<u64>)>>,
644 },
645 #[cfg(celld_internal_tests)]
646 SyncErrorForTest {
647 scope: String,
648 gate: ArmGateRx,
649 socket_id: Option<u64>,
650 terminate: bool,
651 reply: tokio::sync::oneshot::Sender<Result<Option<u64>>>,
652 },
653}
654
655impl CellJob {
656 /// The cell this event addresses, which is also the realm it runs in.
657 pub fn scope(&self) -> &str {
658 match self {
659 CellJob::Fetch { scope, .. }
660 | CellJob::Rpc { scope, .. }
661 | CellJob::WsOpen { scope, .. }
662 | CellJob::WsMessage { scope, .. }
663 | CellJob::WsClosed { scope, .. }
664 | CellJob::Alarm { scope, .. } => scope,
665 #[cfg(celld_internal_tests)]
666 CellJob::SyncErrorForTest { scope, .. } => scope,
667 }
668 }
669
670 /// The client request that can cancel this event, when it is a fetch.
671 pub(crate) fn request_id(&self) -> Option<RequestId> {
672 match self {
673 CellJob::Fetch { request_id, .. } => *request_id,
674 _ => None,
675 }
676 }
677
678 /// Queue sends use native RPC, so the method is the narrow seam where the
679 /// owner can bound producer events without limiting an ordinary Durable
680 /// Object RPC or a Queue alarm and settlement.
681 pub(crate) fn is_queue_producer(&self) -> bool {
682 matches!(self, CellJob::Rpc { scope, method, .. }
683 if scope.split_once(':').is_some_and(|(class, _)|
684 class == crate::deploy::QUEUE_CLASS) && method == "__queueSend")
685 }
686
687 /// This event's place in its caller's order, taken out so the drive can
688 /// wait on it and then release the call behind it.
689 pub fn take_order(&mut self) -> Option<CallOrder> {
690 match self {
691 CellJob::Fetch { order, .. } => order.take(),
692 _ => None,
693 }
694 }
695
696 /// Fail this event without running it.
697 pub fn fail(self, error: anyhow::Error) {
698 match self {
699 CellJob::Fetch { reply, .. } => drop(reply.send(Err(error))),
700 CellJob::Rpc { reply, .. } => drop(reply.send(Err(error))),
701 CellJob::WsOpen { reply, .. } => drop(reply.send(Err(error))),
702 CellJob::WsMessage { reply, .. } => drop(reply.send(Err(error))),
703 CellJob::WsClosed { reply, .. } => drop(reply.send(Err(error))),
704 CellJob::Alarm { reply, .. } => drop(reply.send(Err(error))),
705 #[cfg(celld_internal_tests)]
706 CellJob::SyncErrorForTest { reply, .. } => drop(reply.send(Err(error))),
707 }
708 }
709}
710
711thread_local! {
712 // One outbound HTTP client per JS thread — building it per fetch rebuilds
713 // the TLS stack every call (async-op-hazards.md).
714 static HTTP: reqwest::Client = reqwest::Client::new();
715 static HTTP_MANUAL: reqwest::Client = reqwest::Client::builder()
716 .redirect(reqwest::redirect::Policy::none()).build().unwrap();
717 // A separate policy stops an `error` request before reqwest can replay it
718 // at the destination. Inspecting the final response would be too late:
719 // the method, body, and credentials could already have left the process.
720 static HTTP_ERROR: reqwest::Client = reqwest::Client::builder()
721 .redirect(reqwest::redirect::Policy::custom(|attempt| {
722 attempt.error("fetch redirect mode is error")
723 })).build().unwrap();
724}
725
726#[derive(Debug)]
727struct RedirectSubrequestLimit(String);
728
729impl std::fmt::Display for RedirectSubrequestLimit {
730 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
731 formatter.write_str(&self.0)
732 }
733}
734
735impl std::error::Error for RedirectSubrequestLimit {}
736
737fn fetch_request_error(error: &reqwest::Error) -> String {
738 let mut source: &(dyn std::error::Error + 'static) = error;
739 loop {
740 if let Some(limit) = source.downcast_ref::<RedirectSubrequestLimit>() {
741 return limit.0.clone();
742 }
743 let Some(next) = source.source() else {
744 return format!("fetch: {error}");
745 };
746 source = next;
747 }
748}
749
750#[doc(hidden)]
751pub mod websocket;
752use crate::host_channels::GateRefusal;
753pub(crate) use websocket::WebSocketService;
754pub use websocket::*;
755use websocket::{
756 ws_capture_begin, ws_capture_discard, ws_capture_flush_touched, ws_capture_set_promise,
757 ws_capture_take, ws_close_request_sockets,
758};
759
760/// What an outbound effect must trail before it leaves the process.
761///
762/// The three cases are named rather than nested inside one another because
763/// two of them once shared a representation and lost this distinction:
764/// a reader that starts after another request committed samples the new
765/// position as its own baseline and advances nothing, so a two-state gate read
766/// it as code that owns no cell at all and let its side effect out ungated.
767/// A variant per case makes the distinction one the compiler keeps.
768enum EgressGate {
769 /// No cell event is running. Stateless Worker code owns no cell state, so
770 /// its egress reveals nothing that can still be lost and leaves directly.
771 NoCell,
772 /// This event wrote through the position. The effect waits for that
773 /// write. The last field is the activation epoch the position belongs to.
774 Wrote(String, celld_logic::Channel, u64, Option<u64>),
775 /// A read-only output. It reveals whatever the cell holds, so it carries
776 /// the position it observed above the cell's published baseline, for the
777 /// core to hold it behind the proof of a commit whose handler has not
778 /// taken a ticket yet, and it trails the newest write barrier still open
779 /// on the cell otherwise. Only the core knows which writes are
780 /// outstanding, so this asks rather than guesses. The last field is the
781 /// activation epoch the sample was taken at.
782 ReadOnly(String, celld_logic::Channel, Option<u64>, Option<u64>),
783 /// A facet's storage failed. No proof can cover its write, so the effect
784 /// fails closed. The field is the storage failure.
785 Unpersisted(String),
786 /// An effect of a facet that wrote: the facet's own stream proves the
787 /// write before the root cell's gate verdicts the rest, as workerd's
788 /// facet output gate holds the effect. Fields: the root cell's gate, the
789 /// facet's stream, and the activation epoch.
790 Facet(Box<EgressGate>, String, u64),
791}
792
793impl EgressGate {
794 /// Whether the effect must consult the gate before it leaves. True for a
795 /// read as well as a write: a read whose cell has no barrier is released
796 /// at once, but only the core can say so.
797 fn is_gated(&self) -> bool {
798 !matches!(self, EgressGate::NoCell)
799 }
800
801 /// The cell whose event raised the effect. The host derives this from the
802 /// active event, so JavaScript cannot claim another cell's authority.
803 fn cell_scope(&self) -> Option<&str> {
804 match self {
805 EgressGate::NoCell | EgressGate::Unpersisted(_) => None,
806 EgressGate::Wrote(cell, ..) | EgressGate::ReadOnly(cell, ..) => Some(cell),
807 EgressGate::Facet(root, ..) => root.cell_scope(),
808 }
809 }
810}
811
812/// The cell event the executing JavaScript belongs to.
813///
814/// The continuation's own context first, from CPED: V8 runs a promise
815/// reaction of cell A inside another event's microtask checkpoint, and the
816/// thread-local turn owner then names that other event. An effect raised by
817/// A's reaction would otherwise be gated against the wrong cell's position, or
818/// refused as belonging to the wrong cell. The turn owner remains the answer
819/// for a context that installs no continuation token.
820fn event_context(scope: &mut v8::PinScope) -> Arc<IoContext> {
821 current_reaction_io_context(scope).unwrap_or_else(current_context)
822}
823
824/// What one cell event's outbound effects gate against.
825#[derive(Clone)]
826struct EgressFrame {
827 /// The scope whose connection records this event's writes: the cell for an
828 /// ordinary event, and the facet for an event of an embedded facet.
829 storage: String,
830 /// The committed-write position of `storage` when the event started.
831 before: u64,
832 /// The root cell's gate, when `storage` names an embedded facet. Kept
833 /// beside the scope it stores under, so an effect cannot take one without
834 /// the other and charge a facet's egress to the facet.
835 root: Option<storage::RootGate>,
836}
837
838/// The frame of the running event, if a cell event is running at all.
839fn current_cell_event(context: &IoContext) -> Option<EgressFrame> {
840 context.egress.lock().unwrap().last().cloned()
841}
842
843/// Return and clear the number of output-gate samples for one test cell.
844#[cfg(all(test, celld_internal_tests))]
845pub(crate) fn take_egress_gate_samples_for_test(scope: &str, channel: celld_logic::Channel) -> u64 {
846 test_host_services()
847 .wake_entry()
848 .egress_gate_samples
849 .lock()
850 .unwrap()
851 .remove(&(scope.to_string(), channel))
852 .unwrap_or(0)
853}
854
855/// Sample what the running handler's outbound effects must trail. Answers for
856/// every active cell event, including a read whose core lookup can settle
857/// immediately. Every sample here happens in the calling turn; the ticket
858/// carries them to the host loop, which must not reach cell storage itself.
859fn egress_gate_request(context: &IoContext, channel: celld_logic::Channel) -> EgressGate {
860 let Some(frame) = current_cell_event(context) else {
861 return EgressGate::NoCell;
862 };
863 #[cfg(all(test, celld_internal_tests))]
864 {
865 let cell = frame
866 .root
867 .as_ref()
868 .map(|root| root.cell.clone())
869 .unwrap_or_else(|| frame.storage.clone());
870 *test_host_services()
871 .wake_entry()
872 .egress_gate_samples
873 .lock()
874 .unwrap()
875 .entry((cell, channel))
876 .or_default() += 1;
877 }
878 let (cell, before) = (frame.storage, frame.before);
879 let sample = match storage::write_position(&cell) {
880 Ok(sample) => sample,
881 Err(error) => return EgressGate::Unpersisted(error.to_string()),
882 };
883 if let Some(root) = frame.root {
884 return facet_egress_gate(&cell, root, channel);
885 }
886 let epoch = storage::activation_epoch(&cell);
887 match sample.filter(|position| *position > before) {
888 Some(position) => EgressGate::Wrote(cell, channel, position, epoch),
889 // A read-only output in a process that configured no output gate has
890 // nothing to trail. Such a process cannot acknowledge a write either
891 // -- `await_egress_gate` fails a write closed for want of the same
892 // channel -- so no committed-but-unproven write exists for a read to
893 // reveal. Answer as
894 // if no cell event were running, which keeps the effect on the direct,
895 // synchronous path it has always taken; a WebSocket frame in
896 // particular must not join a deferred queue whose flush needs a gate
897 // to release it. A write still takes a ticket and still fails closed.
898 None if GATE_TX.get().is_none() => EgressGate::NoCell,
899 None => {
900 let observed = storage::observed_position(&cell, sample);
901 EgressGate::ReadOnly(cell, channel, observed, epoch)
902 }
903 }
904}
905
906/// Sample an effect raised by an event of an embedded facet.
907///
908/// A facet is not a cell: no Worker exports its class under the id
909/// `facet_scope` builds, so a ticket in the facet's name activates a cell
910/// that cannot start. The effect can reveal what the root cell showed the
911/// facet, so it trails the root cell's reader gate with the sample the parent
912/// took for the call; a write of the facet's own is proved on its stream.
913fn facet_egress_gate(
914 facet: &str,
915 root: storage::RootGate,
916 channel: celld_logic::Channel,
917) -> EgressGate {
918 if let Some(error) = storage::sql_critical_error(facet) {
919 return EgressGate::Unpersisted(error);
920 }
921 // A process with no output gate has nothing to trail, and a WebSocket
922 // frame must keep its direct path (see `egress_gate_request`).
923 if GATE_TX.get().is_none() {
924 return EgressGate::NoCell;
925 }
926 let gate = EgressGate::ReadOnly(root.cell, channel, root.observed, Some(root.epoch));
927 // Any effect can reveal a facet write, this event's or an earlier one's,
928 // so every effect waits for the facet's stream, as workerd's facet
929 // output gate holds it.
930 EgressGate::Facet(Box::new(gate), root.stream, root.epoch)
931}
932
933/// Prove a facet's stream through the host loop, which owns the replicator.
934async fn prove_facet(stream: String, epoch: u64) -> std::result::Result<(), GateRefusal> {
935 // No host loop means no replicator, so nothing can prove the write and
936 // nothing can lose it to a later proof either.
937 let Some(sender) = FACET_TX.get() else {
938 return Ok(());
939 };
940 let (reply, receive) = tokio::sync::oneshot::channel();
941 let request = FacetReq::Prove {
942 stream,
943 epoch,
944 reply,
945 };
946 sender.send(request).map_err(|_| GateRefusal::Dropped)?;
947 match receive.await {
948 Ok(Ok(())) => Ok(()),
949 Ok(Err(error)) => Err(GateRefusal::Unpersisted(format!("{error:#}"))),
950 Err(_) => Err(GateRefusal::Dropped),
951 }
952}
953
954/// Take one ticket on the output gate and wait for the core's verdict.
955///
956/// This is the output gate applied to an in-handler effect rather than to the
957/// response. It cannot deadlock the handler that is awaiting it: the ticket is
958/// served by `dispatch_gate` on the host's own loop and resolved by the
959/// replicator's independent task, neither of which needs the isolate's event
960/// loop to run. A read-only ticket carries `None` and the core releases it at
961/// once when the cell has no barrier open, so an ordinary read pays one actor
962/// hop and no replica write.
963async fn egress_gate_verdict(gate: EgressGate) -> std::result::Result<(), GateRefusal> {
964 let gate = match gate {
965 EgressGate::Facet(root, stream, epoch) => {
966 prove_facet(stream, epoch).await?;
967 *root
968 }
969 gate => gate,
970 };
971 let (cell, channel, position, observed, epoch) = match gate {
972 EgressGate::Facet(..) => unreachable!("a facet gate nests no facet gate"),
973 EgressGate::NoCell => return Ok(()),
974 EgressGate::Unpersisted(error) => return Err(GateRefusal::Unpersisted(error)),
975 EgressGate::Wrote(cell, channel, position, epoch) => {
976 (cell, channel, Some(position), None, epoch)
977 }
978 EgressGate::ReadOnly(cell, channel, observed, epoch) => {
979 (cell, channel, None, observed, epoch)
980 }
981 };
982 crate::host_channels::request_gate(
983 GATE_TX.get(),
984 cell,
985 crate::actor::GateTicket {
986 channel,
987 position,
988 observed,
989 epoch,
990 },
991 )
992 .await
993}
994
995/// Wait for the writes an outbound effect can reveal to be proven durable
996/// before it leaves the process. See `egress_gate_verdict`.
997async fn await_egress_gate(gate: EgressGate) -> std::result::Result<(), String> {
998 egress_gate_verdict(gate)
999 .await
1000 .map_err(|refusal| match refusal {
1001 GateRefusal::Unproven(_) | GateRefusal::Unpersisted(_) => {
1002 format!("refusing to send: {refusal}")
1003 }
1004 GateRefusal::NoChannel | GateRefusal::Dropped => refusal.to_string(),
1005 })
1006}
1007
1008/// Hold an outbound request until the write it follows is durable, then hand
1009/// it to the host.
1010///
1011/// The send moves inside the future deliberately. These channels dispatch as
1012/// soon as `send` is called, so gating anywhere after it would let the effect
1013/// leave first -- the request would already be on its way while the caller
1014/// waited for a durability answer that no longer decides anything.
1015async fn gated_channel_send<T>(
1016 gate: EgressGate,
1017 channel: &'static OnceLock<tokio::sync::mpsc::UnboundedSender<T>>,
1018 request: T,
1019 missing: &'static str,
1020) -> std::result::Result<(), String> {
1021 crate::host_channels::send_after_gate(
1022 await_egress_gate(gate),
1023 || channel.get(),
1024 request,
1025 missing,
1026 )
1027 .await
1028}
1029
1030/// One `celld_logic::gate::InputGate` per cell.
1031///
1032/// The logic decides; this is only the map and the ids. It replaces the
1033/// promise chain that used to live in `harness.js`, which serialised blocks
1034/// against each other but did nothing about *delivery* — so a second event
1035/// could arrive mid-block, and under real concurrency that wedged the cell.
1036///
1037/// Keyed by cell scope rather than held on the isolate, because a gate
1038/// belongs to a cell and cells share isolates.
1039static CELL_GATES: OnceLock<Mutex<HashMap<String, CellGate>>> = OnceLock::new();
1040static NEXT_GATE_EVENT: AtomicU64 = AtomicU64::new(1);
1041// Cell gates are process-wide, so their owner ids must not repeat in another
1042// isolate. A per-isolate sequence can make one event appear to own another
1043// isolate's gate and keep the wrong event alive.
1044static NEXT_IO_CONTEXT_ID: AtomicU64 = AtomicU64::new(0);
1045
1046fn allocate_io_context_id() -> u64 {
1047 NEXT_IO_CONTEXT_ID
1048 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
1049 current.checked_add(1)
1050 })
1051 .unwrap_or_else(|_| panic!("the process exhausted its IoContext ids"))
1052 + 1
1053}
1054
1055/// One cell's input gate, with the event that holds it and the events queued
1056/// to take it, named by the continuation id of their `IoContext`.
1057///
1058/// The critical section binds this owner to its continuation's operation
1059/// driver before acquisition. An ordinary continuation belongs to its origin;
1060/// a critical section retains the driver that started it, even when a foreign
1061/// checkpoint resumes its callback. The origin claim preserves the separate
1062/// resource context. Recording only the ambient turn here lets that event
1063/// retire while another driver polls the acquisition, rejecting a live block.
1064#[derive(Default)]
1065struct CellGate {
1066 gate: celld_logic::gate::InputGate,
1067 holder: Option<u64>,
1068 /// A reaction can belong to an event other than the turn owner. The claim
1069 /// keeps that originating event and its resources active until the block
1070 /// ends. A same-event block needs no claim because its `InFlight` owns the
1071 /// gate itself.
1072 origin: Option<CrossEntryGateClaim>,
1073 /// Counted, because one event can start several blocks at once.
1074 queued: HashMap<u64, u32>,
1075}
1076
1077/// How many holds and queued takes exist across every gate, so the checks
1078/// every turn makes can skip the map while no event blocks at all, which is
1079/// nearly always.
1080static GATE_ENGAGEMENTS: AtomicUsize = AtomicUsize::new(0);
1081
1082fn cell_gates() -> &'static Mutex<HashMap<String, CellGate>> {
1083 CELL_GATES.get_or_init(|| Mutex::new(HashMap::new()))
1084}
1085
1086impl CellGate {
1087 fn take(
1088 &mut self,
1089 event: celld_logic::gate::EventId,
1090 owner: Option<u64>,
1091 origin: &mut Option<CrossEntryGateClaim>,
1092 ) -> bool {
1093 let was_open = self.gate.is_open();
1094 let taken = self.gate.acquire(event);
1095 if taken && was_open {
1096 self.set_holder(owner, origin.take());
1097 }
1098 taken
1099 }
1100
1101 fn set_holder(&mut self, owner: Option<u64>, origin: Option<CrossEntryGateClaim>) {
1102 if self.holder.is_none() && owner.is_some() {
1103 GATE_ENGAGEMENTS.fetch_add(1, Ordering::Relaxed);
1104 }
1105 self.holder = owner;
1106 self.origin = origin;
1107 }
1108
1109 fn clear_holder(&mut self) -> Option<CrossEntryGateClaim> {
1110 if self.holder.take().is_some() {
1111 GATE_ENGAGEMENTS.fetch_sub(1, Ordering::Relaxed);
1112 }
1113 self.origin.take()
1114 }
1115
1116 fn release(
1117 &mut self,
1118 event: celld_logic::gate::EventId,
1119 ) -> (bool, Option<CrossEntryGateClaim>) {
1120 if !self.gate.release(event) {
1121 return (false, None);
1122 }
1123 (true, self.clear_holder())
1124 }
1125
1126 fn abandon(
1127 &mut self,
1128 event: celld_logic::gate::EventId,
1129 ) -> (bool, Option<CrossEntryGateClaim>) {
1130 if !self.gate.abandon(event) {
1131 return (false, None);
1132 }
1133 (true, self.clear_holder())
1134 }
1135
1136 fn is_unused(&self) -> bool {
1137 self.gate.is_open() && self.queued.is_empty()
1138 }
1139}
1140
1141/// How the event running under `context` is engaged with the cells' gates:
1142/// it holds one, it is queued to take one, or neither.
1143///
1144/// Every gate is searched, not only the gate of the event's own cell: a
1145/// reaction of cell A's event can run inside cell B's checkpoint, and the
1146/// block it starts then belongs to A's gate while its ops belong to B's
1147/// entry. B's entry is the one that must keep them, and it finds itself
1148/// through its own id whichever gate names it.
1149#[derive(Clone, Copy, PartialEq, Eq)]
1150enum GateEngagement {
1151 Holds,
1152 Queued,
1153 None,
1154}
1155
1156fn gate_engagement(cell: Option<&str>, context: &Arc<IoContext>) -> GateEngagement {
1157 if GATE_ENGAGEMENTS.load(Ordering::Relaxed) == 0 {
1158 return GateEngagement::None;
1159 }
1160 let Some(id) = context.continuation_id() else {
1161 return GateEngagement::None;
1162 };
1163 fn of(gate: &CellGate, id: u64) -> GateEngagement {
1164 if !gate.gate.is_open() && gate.holder == Some(id) {
1165 GateEngagement::Holds
1166 } else if gate.queued.contains_key(&id) {
1167 GateEngagement::Queued
1168 } else {
1169 GateEngagement::None
1170 }
1171 }
1172 let gates = cell_gates().lock().unwrap();
1173 // The event's own cell first: nearly every block is on it, and the walk
1174 // below is the price of the cross-cell case alone.
1175 if let Some(gate) = cell.and_then(|cell| gates.get(cell)) {
1176 let engagement = of(gate, id);
1177 if engagement != GateEngagement::None {
1178 return engagement;
1179 }
1180 }
1181 let mut engagement = GateEngagement::None;
1182 for gate in gates.values() {
1183 match of(gate, id) {
1184 GateEngagement::Holds => return GateEngagement::Holds,
1185 GateEngagement::Queued => engagement = GateEngagement::Queued,
1186 GateEngagement::None => {}
1187 }
1188 }
1189 engagement
1190}
1191
1192/// What a waiting event is told when the gate finally opens: nothing, or
1193/// the reason the holder failed.
1194type GateWake = tokio::sync::oneshot::Sender<Result<(), String>>;
1195
1196static GATE_WAITERS: OnceLock<Mutex<HashMap<String, Vec<GateWake>>>> = OnceLock::new();
1197
1198/// Events waiting for a cell's input gate to open, in arrival order.
1199///
1200/// An earlier implementation deleted this queue because an event the gate
1201/// refused stayed on the cell's job channel until a later delivery point
1202/// took it, so the channel *was* the queue and a second one could disagree
1203/// with it. Drives have no channel, so a refused event needs somewhere to
1204/// wait, and workerd keeps the same structure for the same reason
1205/// (`io-gate.h`, `kj::List<Waiter, &Waiter::link> waiters`).
1206///
1207/// In the shell rather than in `celld_logic::gate`, because what waits is a
1208/// tokio task and the core is sans-IO. The core still owns the decision —
1209/// `is_open` — and this owns only the waking.
1210fn gate_waiters() -> &'static Mutex<HashMap<String, Vec<GateWake>>> {
1211 GATE_WAITERS.get_or_init(|| Mutex::new(HashMap::new()))
1212}
1213
1214/// Take a ticket to be woken when `cell`'s gate opens, or `None` if it is
1215/// open now.
1216///
1217/// The gate's lock is held across the check and the enqueue, so a release
1218/// that lands between the two cannot leave an event waiting on a gate that
1219/// is already open.
1220pub fn cell_gate_wait(cell: &str) -> Option<tokio::sync::oneshot::Receiver<Result<(), String>>> {
1221 let gates = cell_gates().lock().unwrap();
1222 if gates.get(cell).is_none_or(|gate| gate.gate.is_open()) {
1223 return None;
1224 }
1225 let (wake, waiter) = tokio::sync::oneshot::channel();
1226 gate_waiters()
1227 .lock()
1228 .unwrap()
1229 .entry(cell.to_string())
1230 .or_default()
1231 .push(wake);
1232 drop(gates);
1233 Some(waiter)
1234}
1235
1236enum CellGateAcquisition {
1237 Acquired,
1238 Waiting {
1239 gate: tokio::sync::oneshot::Receiver<Result<(), String>>,
1240 retirement: tokio::sync::watch::Receiver<bool>,
1241 },
1242 Retired,
1243}
1244
1245/// Acquire `cell` for `event`, or enqueue its next attempt before the gate can
1246/// change state.
1247///
1248/// A failed holder wakes its existing waiters with an error. Separating the
1249/// failed acquisition from waiter registration lets that failure land between
1250/// the two, so the event can miss the error and run against the reset actor.
1251/// The context lock also covers the successful host claim, so event retirement
1252/// cannot land between acquiring the process gate and recording its owner.
1253fn acquire_cell_gate(
1254 context: &IoContext,
1255 cell: &str,
1256 event: celld_logic::gate::EventId,
1257 owner: Option<u64>,
1258 origin: &mut Option<CrossEntryGateClaim>,
1259) -> CellGateAcquisition {
1260 let mut claims = context.input_gates.lock().unwrap();
1261 if claims.retired {
1262 return CellGateAcquisition::Retired;
1263 }
1264 let mut gates = cell_gates().lock().unwrap();
1265 if gates
1266 .entry(cell.to_string())
1267 .or_default()
1268 .take(event, owner, origin)
1269 {
1270 let previous = claims.held.insert(event, cell.to_string());
1271 assert!(previous.is_none(), "an input-gate event id was reused");
1272 return CellGateAcquisition::Acquired;
1273 }
1274 let (wake, waiter) = tokio::sync::oneshot::channel();
1275 gate_waiters()
1276 .lock()
1277 .unwrap()
1278 .entry(cell.to_string())
1279 .or_default()
1280 .push(wake);
1281 let retirement = claims.retirement.subscribe();
1282 drop(gates);
1283 CellGateAcquisition::Waiting {
1284 gate: waiter,
1285 retirement,
1286 }
1287}
1288
1289/// Wake everything waiting on `cell`'s gate. Each re-checks and re-queues if
1290/// another block took the gate first, so waking all of them is correct and
1291/// the order they resume in is theirs to lose, not this function's to keep.
1292fn wake_gate_waiters(cell: &str, outcome: Result<(), String>) {
1293 let waiters = gate_waiters().lock().unwrap().remove(cell);
1294 for wake in waiters.into_iter().flatten() {
1295 let _ = wake.send(outcome.clone());
1296 }
1297}
1298
1299const ABANDONED_INPUT_GATE: &str = "the cell's critical section ended without releasing";
1300const RETIRED_INPUT_GATE: &str = "the cell event ended before it could acquire an input gate";
1301
1302/// Release one completed block and remove the open gate from the process map.
1303fn release_cell_gate(cell: &str, event: celld_logic::gate::EventId, outcome: Result<(), String>) {
1304 let origin = {
1305 let mut gates = cell_gates().lock().unwrap();
1306 let Some(gate) = gates.get_mut(cell) else {
1307 return;
1308 };
1309 let (opened, origin) = gate.release(event);
1310 // A stale release or a remaining nested hold cannot wake the waiters.
1311 // In particular, a stale error must not fail a replacement holder's
1312 // queued events.
1313 if !opened {
1314 return;
1315 }
1316 if gate.is_unused() {
1317 gates.remove(cell);
1318 }
1319 origin
1320 };
1321 // Releasing the origin claim can wake its drive and eventually run
1322 // `IoContext::drop`, which also locks the gate map. Keep that work outside
1323 // the map's lock.
1324 drop(origin);
1325 wake_gate_waiters(cell, outcome);
1326}
1327
1328/// Retire `context`'s waiters and abandon every input gate that it still owns.
1329///
1330/// The event id is part of each claim. A concurrent event can already be
1331/// running when this one dies, so a cell name alone cannot safely decide
1332/// which holder to release. Removing the open map entry also prevents an old
1333/// cell incarnation from leaving process-wide state for a later one.
1334fn abandon_context_input_gates(context: &IoContext) -> Vec<(String, celld_logic::gate::EventId)> {
1335 let claims = context.retire_input_gates();
1336 for (cell, event) in &claims {
1337 let (abandoned, origin) = {
1338 let mut gates = cell_gates().lock().unwrap();
1339 let (abandoned, origin) = gates
1340 .get_mut(cell)
1341 .map_or((false, None), |gate| gate.abandon(*event));
1342 if abandoned {
1343 gates.remove(cell);
1344 }
1345 (abandoned, origin)
1346 };
1347 // See `release_cell_gate`: releasing an origin can re-enter this map
1348 // from its eventual context destructor.
1349 drop(origin);
1350 if abandoned {
1351 wake_gate_waiters(cell, Err(ABANDONED_INPUT_GATE.to_string()));
1352 }
1353 }
1354 claims
1355}
1356
1357/// JS promise resolvers awaiting an async op, keyed by the op's id.
1358///
1359/// **Per isolate, and shared across threads.** Under D1 a request's turns run
1360/// on whichever tokio worker picks them up, so a resolver registered on one
1361/// thread is resolved from another; a thread-local map loses it, and
1362/// `resolve_res` fails to find the resolver and returns silently, leaving the
1363/// handler awaiting a promise nothing will ever settle. The `Mutex` is what
1364/// makes that safe, not the map's location.
1365///
1366/// It lives on `ActorRuntimeState` — one per isolate, reached from a scope —
1367/// so a resolver is only ever looked up in the heap that owns it. One map for
1368/// the whole process would also work, because op ids come from a single
1369/// counter (`asyncrt::NEXT_ID`) and an id names exactly one resolver. But that
1370/// makes an id-allocation bug into cross-isolate handle confusion, where this
1371/// makes it a miss.
1372type PromiseMap = HashMap<u64, v8::Global<v8::PromiseResolver>>;
1373
1374/// Requests cancelled by a reentrant `AbortFetch`. Global for the same reason
1375/// as [`promises`]: the turn that observes a cancellation need not be on the
1376/// thread that recorded it.
1377static CANCELLED_REQUESTS: OnceLock<Mutex<HashSet<RequestId>>> = OnceLock::new();
1378
1379fn cancelled_requests() -> &'static Mutex<HashSet<RequestId>> {
1380 CANCELLED_REQUESTS.get_or_init(|| Mutex::new(HashSet::new()))
1381}
1382
1383fn promise_store(scope: &mut v8::PinScope, id: u64, r: v8::Global<v8::PromiseResolver>) {
1384 actor_runtime_state(scope)
1385 .promises
1386 .lock()
1387 .unwrap()
1388 .insert(id, r);
1389}
1390
1391/// Resolve or reject op `id`'s promise with its outcome.
1392fn resolve_res(tc: &mut v8::PinScope, id: u64, res: Result<asyncrt::OpOut, String>) {
1393 let g = match actor_runtime_state(tc).promises.lock().unwrap().remove(&id) {
1394 Some(g) => g,
1395 None => return,
1396 };
1397 let r = v8::Local::new(tc, g);
1398 match res {
1399 Ok(asyncrt::OpOut::Str(v)) => {
1400 let s = v8::String::new(tc, &v).unwrap();
1401 r.resolve(tc, s.into());
1402 }
1403 Ok(asyncrt::OpOut::Bytes(b)) => {
1404 let v = bytes_value(tc, b);
1405 r.resolve(tc, v);
1406 }
1407 Err(e) => {
1408 let s = v8::String::new(tc, &e).unwrap();
1409 let ex = v8::Exception::error(tc, s);
1410 r.reject(tc, ex);
1411 }
1412 }
1413}
1414
1415/// Move `bytes` into a `Uint8Array` without copying.
1416fn bytes_value<'s>(scope: &mut v8::PinScope<'s, '_>, bytes: Vec<u8>) -> v8::Local<'s, v8::Value> {
1417 #[cfg(celld_internal_tests)]
1418 let input = bytes.as_ptr() as usize;
1419 let len = bytes.len();
1420 let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes).make_shared();
1421 let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);
1422 #[cfg(celld_internal_tests)]
1423 record_bytes_value_allocation_for_test(
1424 input,
1425 buffer
1426 .get_backing_store()
1427 .data()
1428 .map(|data| data.as_ptr() as usize),
1429 );
1430 v8::Uint8Array::new(scope, buffer, 0, len).unwrap().into()
1431}
1432
1433#[cfg(celld_internal_tests)]
1434static BYTES_VALUE_ALLOCATION_PROBE: Mutex<Option<(usize, Option<usize>)>> = Mutex::new(None);
1435
1436#[cfg(celld_internal_tests)]
1437#[doc(hidden)]
1438pub fn capture_bytes_value_allocation_for_test(expected: *const u8) {
1439 *BYTES_VALUE_ALLOCATION_PROBE.lock().unwrap() = Some((expected as usize, None));
1440}
1441
1442#[cfg(celld_internal_tests)]
1443fn record_bytes_value_allocation_for_test(input: usize, output: Option<usize>) {
1444 let mut probe = BYTES_VALUE_ALLOCATION_PROBE.lock().unwrap();
1445 if probe
1446 .as_ref()
1447 .is_some_and(|(expected, _)| *expected == input)
1448 {
1449 *probe = Some((input, output));
1450 }
1451}
1452
1453#[cfg(celld_internal_tests)]
1454#[doc(hidden)]
1455pub fn take_bytes_value_allocation_for_test() -> Option<usize> {
1456 BYTES_VALUE_ALLOCATION_PROBE
1457 .lock()
1458 .unwrap()
1459 .take()
1460 .and_then(|(_, output)| output)
1461}
1462
1463#[cfg(unix)]
1464fn clock_nanos(clock: libc::clockid_t) -> Option<u64> {
1465 // SAFETY: `clock_gettime` initializes the complete `timespec` on success,
1466 // and the pointer remains valid for the call.
1467 let mut time = std::mem::MaybeUninit::<libc::timespec>::uninit();
1468 if unsafe { libc::clock_gettime(clock, time.as_mut_ptr()) } != 0 {
1469 return None;
1470 }
1471 // SAFETY: The successful call above initialized `time`.
1472 let time = unsafe { time.assume_init() };
1473 let seconds = u64::try_from(time.tv_sec).ok()?;
1474 let nanos = u64::try_from(time.tv_nsec).ok()?;
1475 seconds.checked_mul(1_000_000_000)?.checked_add(nanos)
1476}
1477
1478#[cfg(unix)]
1479fn platform_thread_cpu_nanos() -> Option<u64> {
1480 clock_nanos(libc::CLOCK_THREAD_CPUTIME_ID)
1481}
1482
1483#[cfg(not(unix))]
1484fn platform_thread_cpu_nanos() -> Option<u64> {
1485 None
1486}
1487
1488fn thread_cpu_nanos() -> Option<u64> {
1489 #[cfg(all(test, celld_internal_tests))]
1490 if let Some(sample) =
1491 THREAD_CPU_NANOS_SAMPLES_FOR_TEST.with(|samples| samples.borrow_mut().pop_front())
1492 {
1493 return sample;
1494 }
1495 platform_thread_cpu_nanos()
1496}
1497
1498#[cfg(target_os = "linux")]
1499#[derive(Clone, Copy)]
1500struct TargetThreadCpuClock(libc::clockid_t);
1501
1502#[cfg(target_os = "linux")]
1503impl TargetThreadCpuClock {
1504 fn current() -> Option<Self> {
1505 unsafe extern "C" {
1506 fn pthread_getcpuclockid(
1507 thread: libc::pthread_t,
1508 clock_id: *mut libc::clockid_t,
1509 ) -> libc::c_int;
1510 }
1511 let mut clock_id = std::mem::MaybeUninit::<libc::clockid_t>::uninit();
1512 // SAFETY: `pthread_self` returns the calling thread, and the output
1513 // pointer remains valid for the call.
1514 if unsafe { pthread_getcpuclockid(libc::pthread_self(), clock_id.as_mut_ptr()) } != 0 {
1515 return None;
1516 }
1517 // SAFETY: The successful call above initialized `clock_id`.
1518 Some(Self(unsafe { clock_id.assume_init() }))
1519 }
1520
1521 fn nanos(self) -> Option<u64> {
1522 clock_nanos(self.0)
1523 }
1524}
1525
1526#[cfg(target_os = "macos")]
1527#[derive(Clone, Copy)]
1528struct TargetThreadCpuClock(libc::mach_port_t);
1529
1530#[cfg(target_os = "macos")]
1531impl TargetThreadCpuClock {
1532 fn current() -> Option<Self> {
1533 // SAFETY: Both calls inspect the calling thread and transfer no
1534 // ownership. The returned Mach thread port remains valid while this
1535 // turn holds the execution thread.
1536 Some(Self(unsafe {
1537 libc::pthread_mach_thread_np(libc::pthread_self())
1538 }))
1539 }
1540
1541 fn nanos(self) -> Option<u64> {
1542 let mut info = std::mem::MaybeUninit::<libc::thread_basic_info>::uninit();
1543 let mut count = libc::THREAD_BASIC_INFO_COUNT;
1544 // SAFETY: `info` has the size described by `count`, and `thread_info`
1545 // initializes it completely when the call succeeds.
1546 let status = unsafe {
1547 libc::thread_info(
1548 self.0,
1549 u32::try_from(libc::THREAD_BASIC_INFO).expect("thread info flavor is positive"),
1550 info.as_mut_ptr().cast::<libc::integer_t>(),
1551 &mut count,
1552 )
1553 };
1554 if status != libc::KERN_SUCCESS {
1555 return None;
1556 }
1557 // SAFETY: The successful call above initialized `info`.
1558 let info = unsafe { info.assume_init() };
1559 let user_seconds = u64::try_from(info.user_time.seconds).ok()?;
1560 let user_micros = u64::try_from(info.user_time.microseconds).ok()?;
1561 let system_seconds = u64::try_from(info.system_time.seconds).ok()?;
1562 let system_micros = u64::try_from(info.system_time.microseconds).ok()?;
1563 user_seconds
1564 .checked_add(system_seconds)?
1565 .checked_mul(1_000_000_000)?
1566 .checked_add(user_micros.checked_add(system_micros)?.checked_mul(1_000)?)
1567 }
1568}
1569
1570#[cfg(not(any(target_os = "linux", target_os = "macos")))]
1571#[derive(Clone, Copy)]
1572struct TargetThreadCpuClock;
1573
1574#[cfg(not(any(target_os = "linux", target_os = "macos")))]
1575impl TargetThreadCpuClock {
1576 fn current() -> Option<Self> {
1577 None
1578 }
1579
1580 fn nanos(self) -> Option<u64> {
1581 None
1582 }
1583}
1584
1585/// Aborts raised by an HTTP or service-binding caller disconnecting while the
1586/// target runs in the stateless isolate pool. Durable Object aborts can also
1587/// arrive as a reentrant `CellJob::AbortFetch`, so the abort has to be visible
1588/// from whichever turn observes it.
1589///
1590/// The counter keeps the common path to one relaxed atomic load per loop turn:
1591/// with nothing pending, the mutex is never taken.
1592static PENDING_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> =
1593 OnceLock::new();
1594static SHUTDOWN_ABORTS: OnceLock<std::sync::Mutex<std::collections::HashSet<RequestId>>> =
1595 OnceLock::new();
1596static PENDING_ABORT_COUNT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1597
1598fn pending_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> {
1599 PENDING_ABORTS.get_or_init(Default::default)
1600}
1601
1602fn shutdown_aborts() -> &'static std::sync::Mutex<std::collections::HashSet<RequestId>> {
1603 SHUTDOWN_ABORTS.get_or_init(Default::default)
1604}
1605
1606#[cfg(all(test, celld_internal_tests))]
1607type AbortRequestPauseForTest = (
1608 RequestId,
1609 std::sync::mpsc::Sender<()>,
1610 std::sync::mpsc::Receiver<()>,
1611);
1612
1613#[cfg(all(test, celld_internal_tests))]
1614static ABORT_REQUEST_PAUSE_FOR_TEST: Mutex<Option<AbortRequestPauseForTest>> = Mutex::new(None);
1615
1616#[cfg(all(test, celld_internal_tests))]
1617pub(crate) struct AbortRequestPauseHandleForTest {
1618 entered: std::sync::mpsc::Receiver<()>,
1619 release: Option<std::sync::mpsc::Sender<()>>,
1620}
1621
1622#[cfg(all(test, celld_internal_tests))]
1623impl AbortRequestPauseHandleForTest {
1624 pub(crate) fn wait_until_entered(&self) {
1625 self.entered
1626 .recv()
1627 .expect("the abort publisher dropped before its publication seam");
1628 }
1629
1630 pub(crate) fn release(mut self) {
1631 self.release
1632 .take()
1633 .expect("the abort publication pause was released twice")
1634 .send(())
1635 .expect("the abort publisher dropped while paused");
1636 }
1637}
1638
1639#[cfg(all(test, celld_internal_tests))]
1640pub(crate) fn pause_abort_request_for_test(
1641 request_id: RequestId,
1642) -> AbortRequestPauseHandleForTest {
1643 let (entered_tx, entered) = std::sync::mpsc::channel();
1644 let (release, release_rx) = std::sync::mpsc::channel();
1645 let previous = ABORT_REQUEST_PAUSE_FOR_TEST
1646 .lock()
1647 .unwrap()
1648 .replace((request_id, entered_tx, release_rx));
1649 assert!(
1650 previous.is_none(),
1651 "an abort publication pause is already armed"
1652 );
1653 AbortRequestPauseHandleForTest {
1654 entered,
1655 release: Some(release),
1656 }
1657}
1658
1659#[cfg(all(test, celld_internal_tests))]
1660pub(crate) fn pause_abort_request_if_armed_for_test(request_id: RequestId) {
1661 let pause = {
1662 let mut pause = ABORT_REQUEST_PAUSE_FOR_TEST.lock().unwrap();
1663 if pause
1664 .as_ref()
1665 .is_some_and(|(expected, _, _)| *expected == request_id)
1666 {
1667 pause.take()
1668 } else {
1669 None
1670 }
1671 };
1672 if let Some((_, entered, release)) = pause {
1673 entered
1674 .send(())
1675 .expect("the abort publication test dropped its observer");
1676 release
1677 .recv()
1678 .expect("the abort publication test dropped its release");
1679 }
1680}
1681
1682#[cfg(all(test, celld_internal_tests))]
1683pub(crate) fn request_cancellation_state_for_test(request_id: RequestId) -> (bool, bool) {
1684 (
1685 pending_aborts().lock().unwrap().contains(&request_id),
1686 cancelled_requests().lock().unwrap().contains(&request_id),
1687 )
1688}
1689
1690/// Mark an in-flight request cancelled from any thread.
1691pub fn abort_request(request_id: RequestId) {
1692 #[cfg(all(test, celld_internal_tests))]
1693 pause_abort_request_if_armed_for_test(request_id);
1694 if pending_aborts().lock().unwrap().insert(request_id) {
1695 PENDING_ABORT_COUNT.fetch_add(1, Ordering::Relaxed);
1696 }
1697}
1698
1699/// Force a cell event to retire for a lifecycle transition. Unlike a client
1700/// disconnect, shutdown cannot preserve `waitUntil` work because the runtime
1701/// and its ownership are about to leave this process.
1702pub fn abort_request_for_shutdown(request_id: RequestId) {
1703 shutdown_aborts().lock().unwrap().insert(request_id);
1704 abort_request(request_id);
1705}
1706
1707pub(crate) fn clear_request_cancellation(request_id: RequestId) {
1708 let _ = take_pending_abort(request_id);
1709 cancelled_requests().lock().unwrap().remove(&request_id);
1710 shutdown_aborts().lock().unwrap().remove(&request_id);
1711}
1712
1713pub fn take_shutdown_cancellation(request_id: Option<RequestId>) -> bool {
1714 request_id.is_some_and(|request_id| shutdown_aborts().lock().unwrap().remove(&request_id))
1715}
1716
1717#[cfg(celld_internal_tests)]
1718#[doc(hidden)]
1719pub fn clear_request_cancellation_for_test(request_id: RequestId) {
1720 clear_request_cancellation(request_id);
1721}
1722
1723fn take_pending_abort(request_id: RequestId) -> bool {
1724 if PENDING_ABORT_COUNT.load(Ordering::Relaxed) == 0 {
1725 return false;
1726 }
1727 if pending_aborts().lock().unwrap().remove(&request_id) {
1728 PENDING_ABORT_COUNT.fetch_sub(1, Ordering::Relaxed);
1729 return true;
1730 }
1731 false
1732}
1733
1734pub fn take_request_cancellation(request_id: Option<RequestId>) -> bool {
1735 request_id.is_some_and(|request_id| {
1736 cancelled_requests().lock().unwrap().remove(&request_id) || take_pending_abort(request_id)
1737 })
1738}
1739
1740fn resolved_promise<'s>(
1741 tc: &mut v8::PinScope<'s, '_>,
1742 value: v8::Local<'s, v8::Value>,
1743) -> Result<v8::Local<'s, v8::Promise>> {
1744 let resolver =
1745 v8::PromiseResolver::new(tc).ok_or_else(|| anyhow!("could not create event promise"))?;
1746 resolver.resolve(tc, value);
1747 Ok(resolver.get_promise(tc))
1748}
1749
1750fn abort_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) -> Result<bool> {
1751 let function = event_hook(tc, |hooks| &hooks.abort_incoming_request)?;
1752 let request_id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
1753 let recv = v8::undefined(tc).into();
1754 let result = function
1755 .call(tc, recv, &[request_id.into()])
1756 .ok_or_else(|| anyhow!("__abortIncomingRequest threw"))?;
1757 Ok(result.boolean_value(tc))
1758}
1759
1760/// The rejection reason of a settled-rejected promise, with a little stack.
1761fn reject_reason(tc: &mut v8::PinScope, p: v8::Local<v8::Promise>) -> String {
1762 let r = p.result(tc);
1763 let msg = r.to_rust_string_lossy(tc);
1764 let stk = r
1765 .to_object(tc)
1766 .and_then(|o| {
1767 let k = v8::String::new(tc, "stack")?;
1768 o.get(tc, k.into())
1769 })
1770 .map(|s| s.to_rust_string_lossy(tc))
1771 .unwrap_or_default();
1772 let tail = stk
1773 .lines()
1774 .skip(1)
1775 .take(3)
1776 .map(|l| l.trim())
1777 .collect::<Vec<_>>()
1778 .join(" <- ");
1779 if tail.is_empty() {
1780 msg
1781 } else {
1782 format!("{msg} [{tail}]")
1783 }
1784}
1785
1786pub struct Engine;
1787impl Engine {
1788 pub fn init() {
1789 // V8 is process-global, so the guard belongs to the initializer. A
1790 // guard at each caller allowed two callers to each initialize V8 once,
1791 // which poisoned the global state when both ran.
1792 static INIT: std::sync::Once = std::sync::Once::new();
1793 INIT.call_once(|| {
1794 #[cfg(celld_internal_tests)]
1795 v8::V8::set_flags_from_string("--expose-gc");
1796 // No `v8::icu::set_common_data_78` call: the rusty_v8 152 prebuilt
1797 // statically links the complete ICU data (full locale tables and
1798 // regex property-of-strings, e.g. /\p{RGI_Emoji}/v — verified
1799 // empirically), so overriding it with an embedded icudtl.dat only
1800 // duplicated 10.8 MB in the binary. The required coverage is
1801 // explicit, so a future v8 bump that reduces the builtin data
1802 // fails rather than silently narrowing it; the fix would be to
1803 // re-embed rusty_v8's `third_party/icu/common/icudtl.dat`,
1804 // 16-byte-aligned.
1805 let platform = v8::new_default_platform(0, false).make_shared();
1806 v8::V8::initialize_platform(platform);
1807 v8::V8::initialize();
1808 });
1809 }
1810}
1811
1812/// The resource name the entry module compiles under. It is also the name the
1813/// entry module is projected under in `/bundle`, so a stack frame and a bundle
1814/// path name the same file.
1815const ENTRY_MODULE_NAME: &str = "worker.js";
1816
1817/// One queue's push consumer after the owning script has been resolved.
1818#[derive(Clone)]
1819pub struct QueueConsumerRegistration {
1820 pub script: String,
1821 pub config: crate::protocol::QueueConsumerConfig,
1822}
1823
1824#[derive(Clone, Copy, PartialEq, Eq)]
1825enum WorkerOrigin {
1826 Deployment,
1827 Dynamic,
1828}
1829
1830type ResourceLimits = crate::WorkerInvocationLimits;
1831
1832fn effective_resource_limits(
1833 configured: Option<ResourceLimits>,
1834 invocation: Option<ResourceLimits>,
1835) -> Option<ResourceLimits> {
1836 let lower = |configured: Option<u32>, invocation: Option<u32>| match (configured, invocation) {
1837 (Some(configured), Some(invocation)) => Some(configured.min(invocation)),
1838 (configured, invocation) => configured.or(invocation),
1839 };
1840 let limits = ResourceLimits {
1841 cpu_ms: lower(
1842 configured.and_then(|limits| limits.cpu_ms),
1843 invocation.and_then(|limits| limits.cpu_ms),
1844 ),
1845 sub_requests: lower(
1846 configured.and_then(|limits| limits.sub_requests),
1847 invocation.and_then(|limits| limits.sub_requests),
1848 ),
1849 };
1850 (limits.cpu_ms.is_some() || limits.sub_requests.is_some()).then_some(limits)
1851}
1852
1853struct CpuTurnStart {
1854 thread_nanos: Option<u64>,
1855 wall: Instant,
1856}
1857
1858#[derive(Clone)]
1859struct LoaderEnvRoute {
1860 script: String,
1861 entrypoint: Option<String>,
1862 props: Vec<u8>,
1863}
1864
1865#[derive(Clone)]
1866struct LoaderEnv {
1867 bytes: Vec<u8>,
1868 routes: Vec<LoaderEnvRoute>,
1869}
1870
1871pub struct WorkerConfig {
1872 src: String,
1873 /// The canonical module name for `src`. Dynamic Workers preserve the
1874 /// caller's `mainModule` path so relative imports use its directory.
1875 main_module_name: String,
1876 pub script_name: String,
1877 /// The construction path that grants Dynamic Worker load semantics.
1878 /// A script name is caller-controlled, so it cannot prove this origin.
1879 origin: WorkerOrigin,
1880 do_classes: Vec<String>,
1881 bindings: Vec<(String, String)>,
1882 /// `r2_buckets`: (environment name, bucket name). The bucket name is
1883 /// the key space the binding owns inside the fleet bucket; see [[r2]].
1884 r2_bindings: Vec<(String, String)>,
1885 /// `d1_databases`: (environment name, stable database identity). The
1886 /// identity addresses the cell that holds the database; see [[d1]].
1887 d1_bindings: Vec<(String, String)>,
1888 /// `kv_namespaces`: (environment name, namespace identity). The identity is
1889 /// the config's `id` verbatim, and it addresses the namespace's cells; see
1890 /// [[kv]].
1891 kv_bindings: Vec<(String, String)>,
1892 queue_bindings: Vec<QueueBinding>,
1893 pub(crate) queue_consumers: Vec<QueueConsumerRegistration>,
1894 /// This script declared a consumer in its own manifest. The deployment-
1895 /// wide catalog later replaces `queue_consumers` in every isolate, so the
1896 /// catalog cannot answer whether this particular default export can omit
1897 /// `fetch` and provide only `queue`.
1898 declares_queue_consumer: bool,
1899 workflow_bindings: Vec<WorkflowBinding>,
1900 vars: Vec<(String, String)>,
1901 node: String,
1902 /// The worker's non-main modules, so the main module can import siblings.
1903 modules: Vec<(String, ModuleSource)>,
1904 compat: Compat,
1905 /// `[[services]]`: (binding name, target script, optional entrypoint).
1906 /// The target runs in this process; see [[service-bindings]].
1907 services: Vec<(String, String, Option<String>)>,
1908 asset_binding: Option<String>,
1909 /// `env` names of the Worker Loader bindings, if this Worker can spawn
1910 /// dynamic isolates. A config can declare more than one loader, and each
1911 /// binding gets a cache of its own, so a name loaded through one loader
1912 /// is a different Worker from the same name loaded through another.
1913 loader_bindings: Vec<String>,
1914 /// Ambient outbound authority. Loaded workers may be denied.
1915 egress: EgressPolicy,
1916 /// Structured-clone values and host-minted service routes that a loaded
1917 /// worker receives. Loader-only; empty for a normal worker.
1918 loader_env: Option<LoaderEnv>,
1919 /// Per-invocation limits supplied with a dynamically loaded Worker.
1920 /// Deployment Workers leave this empty.
1921 resource_limits: Option<ResourceLimits>,
1922 /// Whether a Dynamic Worker can receive a tail report sender on a fetch.
1923 tail_reporting: bool,
1924 /// `triggers.crons` from the deployment. Empty for a loaded worker and for
1925 /// any script without cron triggers.
1926 pub crons: Vec<String>,
1927 /// `containers` from the deployment: the classes whose `ctx.container`
1928 /// exists. Empty for a loaded worker.
1929 pub containers: Vec<crate::container::ContainerSpec>,
1930 /// The application generation this configuration belongs to. Every
1931 /// isolate built from it carries the value as a slot, so its host calls
1932 /// resolve against the deployment graph it was built with.
1933 pub generation: crate::generation::GenerationId,
1934 /// The external (`node:*`/`cloudflare:*`) imports of `src`.
1935 ///
1936 /// The scan walks the whole bundle, which an esbuild artifact makes
1937 /// megabytes, and its answer depends only on `src` — a field nothing
1938 /// mutates after construction. It used to run inside `load_config`,
1939 /// so a deployment paid it again on every cell wake and on every
1940 /// stateless pool thread. One `Arc<WorkerConfig>` backs all of those
1941 /// isolates, so scanning here pays it once instead.
1942 main_imports: modules::ExternalImports,
1943 /// The same scan for each `ModuleSource::EsModule` sibling, in the order
1944 /// `es_module_sources` yields them. Read through
1945 /// [`WorkerConfig::es_modules`], which hands a module and its scan out
1946 /// together so no caller can pair a module with another module's scan.
1947 module_imports: Vec<modules::ExternalImports>,
1948}
1949
1950/// The `ModuleSource::EsModule` siblings of a worker, as (name, source).
1951///
1952/// The single definition of that order: `WorkerConfig::new` scans in it and
1953/// `WorkerConfig::es_modules` zips against it, so the two cannot disagree.
1954fn es_module_sources(modules: &[(String, ModuleSource)]) -> impl Iterator<Item = (&str, &str)> {
1955 modules.iter().filter_map(|(name, source)| match source {
1956 ModuleSource::EsModule(source) => Some((name.as_str(), source.as_str())),
1957 _ => None,
1958 })
1959}
1960
1961#[derive(Clone, serde::Serialize)]
1962#[serde(rename_all = "camelCase")]
1963struct TailLog {
1964 timestamp: i64,
1965 level: String,
1966 message: Vec<String>,
1967}
1968
1969const TAIL_LOG_LIMIT_BYTES: usize = 256 * 1024;
1970
1971#[derive(Default)]
1972struct TailLogCapture {
1973 records: Vec<TailLog>,
1974 /// The serialized record bytes, including separators but excluding the
1975 /// two array delimiters. The records and this measure share one lock, so
1976 /// no caller can retain a record without charging it to the same budget.
1977 serialized_bytes: usize,
1978 /// A record that crosses the limit ends capture for this invocation.
1979 /// Continuing after that record would expose later context that Workerd
1980 /// omits, even when a smaller record could fit in the remaining budget.
1981 full: bool,
1982}
1983
1984#[derive(Default)]
1985struct JsonByteCounter(usize);
1986
1987impl std::io::Write for JsonByteCounter {
1988 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
1989 self.0 = self.0.saturating_add(bytes.len());
1990 Ok(bytes.len())
1991 }
1992
1993 fn flush(&mut self) -> std::io::Result<()> {
1994 Ok(())
1995 }
1996}
1997
1998fn serialized_json_bytes(value: &impl serde::Serialize) -> usize {
1999 let mut counter = JsonByteCounter::default();
2000 serde_json::to_writer(&mut counter, value).expect("TailLog serialization is infallible");
2001 counter.0
2002}
2003
2004#[cfg(all(test, celld_internal_tests))]
2005fn tail_log_limit_bytes_for_test() -> usize {
2006 TAIL_LOG_LIMIT_BYTES
2007}
2008
2009impl WorkerConfig {
2010 pub fn new(options: WorkerConfigOptions) -> Self {
2011 let WorkerConfigOptions {
2012 src,
2013 script_name,
2014 do_classes,
2015 bindings,
2016 r2_bindings,
2017 d1_bindings,
2018 kv_bindings,
2019 queue_bindings,
2020 queue_consumers,
2021 workflow_bindings,
2022 vars,
2023 node,
2024 modules,
2025 compat,
2026 } = options;
2027 let main_imports = modules::scan_external_imports(&src);
2028 let module_imports = es_module_sources(&modules)
2029 .map(|(_name, source)| modules::scan_external_imports(source))
2030 .collect();
2031 let declares_queue_consumer = !queue_consumers.is_empty();
2032 let queue_consumers = queue_consumers
2033 .into_iter()
2034 .map(|config| QueueConsumerRegistration {
2035 script: script_name.clone(),
2036 config,
2037 })
2038 .collect();
2039 Self {
2040 src,
2041 main_module_name: ENTRY_MODULE_NAME.to_string(),
2042 script_name,
2043 origin: WorkerOrigin::Deployment,
2044 do_classes,
2045 bindings,
2046 r2_bindings,
2047 d1_bindings,
2048 kv_bindings,
2049 queue_bindings,
2050 queue_consumers,
2051 declares_queue_consumer,
2052 workflow_bindings,
2053 vars,
2054 node,
2055 modules,
2056 compat,
2057 services: Vec::new(),
2058 asset_binding: None,
2059 loader_bindings: Vec::new(),
2060 egress: EgressPolicy::Allow,
2061 loader_env: None,
2062 resource_limits: None,
2063 tail_reporting: false,
2064 crons: Vec::new(),
2065 containers: Vec::new(),
2066 generation: 0,
2067 main_imports,
2068 module_imports,
2069 }
2070 }
2071
2072 pub fn with_containers(mut self, containers: Vec<crate::container::ContainerSpec>) -> Self {
2073 self.containers = containers;
2074 self
2075 }
2076
2077 /// Whether cells of `class` supervise a container.
2078 pub fn container_class(&self, class: &str) -> bool {
2079 self.containers.iter().any(|spec| spec.class_name == class)
2080 }
2081
2082 /// Stamp this Worker with the application generation it serves.
2083 pub fn with_generation(mut self, generation: crate::generation::GenerationId) -> Self {
2084 self.generation = generation;
2085 self
2086 }
2087
2088 pub fn with_queue_consumers(mut self, consumers: Vec<QueueConsumerRegistration>) -> Self {
2089 self.queue_consumers = consumers;
2090 self
2091 }
2092
2093 /// Grant the relaxed load contract used only by a Worker Loader isolate.
2094 fn into_dynamic_worker(mut self) -> Self {
2095 self.origin = WorkerOrigin::Dynamic;
2096 self
2097 }
2098
2099 fn with_main_module_name(mut self, name: String) -> Self {
2100 self.main_module_name = name;
2101 self
2102 }
2103
2104 fn with_tail_reporting(mut self, enabled: bool) -> Self {
2105 self.tail_reporting = enabled;
2106 self
2107 }
2108 /// Every `ModuleSource::EsModule` sibling with its name, its source and
2109 /// its scanned external imports.
2110 fn es_modules(&self) -> impl Iterator<Item = (&str, &str, &modules::ExternalImports)> {
2111 // `zip` would truncate silently if the two ever disagreed, and a
2112 // truncated scan means a sibling links against a stub missing its
2113 // names. Both are filled from `es_module_sources` in `new`, so a
2114 // disagreement is a bug in a future mutator, not a reachable state.
2115 debug_assert_eq!(
2116 es_module_sources(&self.modules).count(),
2117 self.module_imports.len(),
2118 "an ES sibling lost its scanned imports",
2119 );
2120 es_module_sources(&self.modules)
2121 .zip(&self.module_imports)
2122 .map(|((name, source), imports)| (name, source, imports))
2123 }
2124
2125 /// Give this Worker the deployment's cron trigger expressions.
2126 pub fn with_crons(mut self, crons: Vec<String>) -> Self {
2127 self.crons = crons;
2128 self
2129 }
2130
2131 /// Grant this Worker a Worker Loader binding at each `env` name.
2132 pub fn with_loaders(mut self, bindings: Vec<String>) -> Self {
2133 self.loader_bindings = bindings;
2134 self
2135 }
2136
2137 /// Set this Worker's ambient outbound authority (loaded workers only).
2138 fn with_egress(mut self, egress: EgressPolicy) -> Self {
2139 self.egress = egress;
2140 self
2141 }
2142
2143 /// Install the limits that every invocation of this Dynamic Worker owns.
2144 fn with_resource_limits(mut self, limits: Option<ResourceLimits>) -> Self {
2145 self.resource_limits = limits;
2146 self
2147 }
2148
2149 /// Merge the caller's structured-clone `env` onto a loaded worker's env.
2150 fn with_loader_env(mut self, env: Option<LoaderEnv>) -> Self {
2151 self.loader_env = env;
2152 self
2153 }
2154
2155 /// Declare the service bindings this Worker may call.
2156 pub fn with_services(mut self, services: Vec<(String, String, Option<String>)>) -> Self {
2157 self.services = services;
2158 self
2159 }
2160
2161 pub fn with_asset_binding(mut self, binding: Option<String>) -> Self {
2162 self.asset_binding = binding;
2163 self
2164 }
2165}
2166
2167/// The storage authority installed when a cell enters an isolate.
2168///
2169/// The path and epoch form one value because opening either one without the
2170/// other would let later asynchronous work use the wrong ownership epoch.
2171#[doc(hidden)]
2172pub struct CellStorage<'a> {
2173 pub path: &'a str,
2174 pub epoch: u64,
2175 /// Fleet ownership supplies persistent writer epochs. Standalone ownership
2176 /// resets on restart and never publishes discovery objects.
2177 pub replicated_wake: bool,
2178 /// The activation's paged VFS, when its restore paged. The file at `path`
2179 /// is then sparse; opening it without this VFS reads holes as data.
2180 pub vfs: Option<&'a str>,
2181}
2182
2183pub struct Worker {
2184 inner: Option<WorkerIsolate>,
2185}
2186
2187pub struct WorkerIsolate {
2188 /// Shared rather than owned: under D1 an isolate belongs to no thread,
2189 /// and a worker enters it by taking its `v8::Locker`.
2190 ///
2191 /// Every `lock()` below blocks until the current holder releases. That is
2192 /// only safe because the pool takes an async permit for this isolate
2193 /// first, so the lock is uncontended by construction; a `lock()` reached
2194 /// without that permit would be a blocking call on a tokio worker.
2195 isolate: v8::SharedIsolate,
2196 runtime_state: Arc<ActorRuntimeState>,
2197 /// The one realm this isolate has: its context, and the entry `fetch`
2198 /// that lives in it.
2199 ///
2200 /// It was a `HashMap` keyed by cell, on the premise that a cell needs a
2201 /// realm of its own. It does not, and nothing ever put a second one in.
2202 /// The harness already keys instances by scope (`__cell.instances`), and
2203 /// Durable Objects **share** a context per script rather than getting one
2204 /// each — a context per cell would also duplicate the compiled module per
2205 /// cell, which is most of what sharing an isolate saves.
2206 realm: Realm,
2207 original_heap_limit: usize,
2208 compat: Compat,
2209 /// Identity used to reclaim every dynamic Worker this isolate created.
2210 /// Named Worker Loader identity lives in this isolate's JavaScript heap,
2211 /// so no child can remain charged to the registry after its owner is gone.
2212 loader_owner: LoaderOwner,
2213 /// The storage of the cells this isolate hosts.
2214 ///
2215 /// It lives here, and not in a thread-local, because a driven cell's
2216 /// turns run on whatever tokio worker holds the isolate. See
2217 /// `storage::Cells`.
2218 cells: storage::Cells,
2219}
2220
2221/// An isolate's context and the entry `fetch` that lives in it.
2222///
2223/// `fetch` is here rather than beside the isolate because a function is a
2224/// value in the realm that created it.
2225struct Realm {
2226 context: v8::Global<v8::Context>,
2227 fetch: v8::Global<v8::Function>,
2228}
2229
2230impl WorkerIsolate {
2231 fn cpu_watchdog(
2232 &self,
2233 remaining: Option<Duration>,
2234 declared_ms: Option<u32>,
2235 ) -> Option<CpuWatchdog> {
2236 CpuWatchdog::start(
2237 remaining,
2238 declared_ms,
2239 self.isolate.thread_safe_handle(),
2240 self.runtime_state.clone(),
2241 )
2242 }
2243
2244 fn initial_cpu_budget(&self) -> Option<Duration> {
2245 self.runtime_state
2246 .resource_limits
2247 .and_then(|limits| limits.cpu_ms)
2248 .map(|milliseconds| Duration::from_millis(u64::from(milliseconds)))
2249 }
2250
2251 /// Take the isolate for one turn, and make the cells it hosts reachable
2252 /// while it is held.
2253 ///
2254 /// The two belong together. The lock is what makes this thread the only
2255 /// one that can touch the isolate, and a cell's SQLite handles are part
2256 /// of what it may touch — so a locker taken without installing them
2257 /// would let a turn reach no storage at all, or another isolate's.
2258 /// Pairing them here is why no call site has to remember.
2259 fn lock(&self) -> (v8::Locker<'_>, storage::Installed) {
2260 (self.isolate.lock(), self.cells.install())
2261 }
2262
2263 /// Lift condemnation from an isolate whose heap has drained.
2264 ///
2265 /// `near_heap_limit` latches a flag that nothing used to clear, so a cell
2266 /// that reached its limit once stayed condemned until the process
2267 /// restarted. The flag is re-read here, between turns rather than inside
2268 /// one, because a handler must not see the isolate recover halfway
2269 /// through.
2270 ///
2271 /// A heap still over the line buys one `low_memory_notification` and a
2272 /// second reading. V8 stops collecting once it is past the limit, so a
2273 /// drained isolate holds the dead heap until something allocates again —
2274 /// without the forced collection the reading that decides recovery is a
2275 /// reading of garbage. `HEAP_GC_NUDGE_INTERVAL` bounds the cost.
2276 ///
2277 /// Removing the callback with the original limit puts back the limit
2278 /// `near_heap_limit` raised; re-adding it re-arms the guard.
2279 fn recover_heap(&self, locker: &mut v8::Locker<'_>) {
2280 let Some(state) = locker.get_slot::<Arc<HeapLimitState>>().cloned() else {
2281 return;
2282 };
2283 if !state.excessively_exceeded.load(Ordering::Relaxed) {
2284 return;
2285 }
2286 if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE {
2287 if !state.due_for_gc_nudge() {
2288 return;
2289 }
2290 locker.low_memory_notification();
2291 if heap_share(locker, state.limit) >= HEAP_RECOVERY_SHARE {
2292 return;
2293 }
2294 }
2295 state.excessively_exceeded.store(false, Ordering::Relaxed);
2296 let data = Arc::as_ptr(&state) as *mut HeapLimitState as *mut std::ffi::c_void;
2297 locker.remove_near_heap_limit_callback(near_heap_limit, state.limit);
2298 locker.add_near_heap_limit_callback(near_heap_limit, data);
2299 tracing::info!(
2300 event = "isolate_heap_recovered",
2301 limit_bytes = state.limit,
2302 "isolate heap fell back under its limit, so it serves again"
2303 );
2304 }
2305
2306 /// Localise the realm for one turn.
2307 ///
2308 /// **Taking the scope is the point.** Reaching a realm means touching
2309 /// `Global` handles, which on a shared isolate is only legal while its
2310 /// `Locker` is held — and there is no scope to pass until the isolate is
2311 /// locked. So the requirement is structural rather than a comment asking
2312 /// callers to remember it. It was a comment, and the one call site that
2313 /// forgot cloned two `Global`s a line too early; the panic happened
2314 /// inside a spawned request task, where tokio swallowed it and it
2315 /// surfaced only as a poisoned mutex on every later request.
2316 fn realm<'s>(&self, hs: &mut v8::PinScope<'s, '_, ()>) -> Entered<'s> {
2317 Entered {
2318 context: v8::Local::new(hs, &self.realm.context),
2319 fetch: v8::Local::new(hs, &self.realm.fetch),
2320 }
2321 }
2322}
2323
2324/// One realm, entered. Valid only for the scope that produced it, which is
2325/// what ties it to the isolate being locked.
2326struct Entered<'s> {
2327 context: v8::Local<'s, v8::Context>,
2328 fetch: v8::Local<'s, v8::Function>,
2329}
2330
2331impl std::ops::Deref for Worker {
2332 type Target = WorkerIsolate;
2333
2334 fn deref(&self) -> &Self::Target {
2335 self.inner.as_ref().expect("Worker isolate unavailable")
2336 }
2337}
2338
2339impl std::ops::DerefMut for Worker {
2340 fn deref_mut(&mut self) -> &mut Self::Target {
2341 self.inner.as_mut().expect("Worker isolate unavailable")
2342 }
2343}
2344
2345const DEFAULT_V8_HEAP_LIMIT_BYTES: usize = 128 * 1024 * 1024;
2346const V8_HEAP_EMERGENCY_BYTES: usize = 16 * 1024 * 1024;
2347
2348/// Share of the heap limit past which an isolate takes on no more retained
2349/// state. It sits below the near-limit callback on purpose: this refuses one
2350/// hibernatable socket while the isolate still works, where the callback
2351/// fires once it no longer does.
2352const HEAP_ADMISSION_SHARE: f64 = 0.9;
2353
2354/// Share of the heap limit under which a condemned isolate is condemned no
2355/// more. Under `HEAP_ADMISSION_SHARE` by enough that recovery does not
2356/// immediately re-admit into a heap that is about to fail again.
2357const HEAP_RECOVERY_SHARE: f64 = 0.75;
2358
2359/// The shortest gap between two collections forced by `recover_heap`. A full
2360/// collection of a 128 MB heap costs tens of milliseconds and a loaded cell
2361/// begins many turns each second, so an unbounded nudge would spend more of a
2362/// condemned isolate on collecting than on serving.
2363const HEAP_GC_NUDGE_INTERVAL: Duration = Duration::from_secs(1);
2364
2365struct HeapLimitState {
2366 excessively_exceeded: AtomicBool,
2367 /// The limit V8 gave this isolate, before any emergency extension.
2368 /// Recovery measures against this one because `near_heap_limit` raises
2369 /// the current one.
2370 limit: usize,
2371 last_gc_nudge: Mutex<Option<Instant>>,
2372 /// An explicit admission refusal cannot use the condemnation flag because
2373 /// recovery clears that flag at the next turn.
2374 #[cfg(celld_internal_tests)]
2375 forced_admission_refusal: AtomicBool,
2376}
2377
2378impl HeapLimitState {
2379 /// Whether a condemned isolate can pay for another forced collection.
2380 ///
2381 /// Rate-limited rather than once for each condemnation: the load can
2382 /// still be live at the first reading and gone by the second, so a
2383 /// one-shot nudge would leave the cell condemned exactly as before.
2384 fn due_for_gc_nudge(&self) -> bool {
2385 let Ok(mut last) = self.last_gc_nudge.lock() else {
2386 return false;
2387 };
2388 let now = Instant::now();
2389 if last.is_some_and(|at| now.duration_since(at) < HEAP_GC_NUDGE_INTERVAL) {
2390 return false;
2391 }
2392 *last = Some(now);
2393 true
2394 }
2395}
2396
2397#[cfg(celld_internal_tests)]
2398fn admission_refusal_forced(state: &HeapLimitState) -> bool {
2399 state.forced_admission_refusal.load(Ordering::Relaxed)
2400}
2401
2402#[cfg(not(celld_internal_tests))]
2403fn admission_refusal_forced(_state: &HeapLimitState) -> bool {
2404 false
2405}
2406
2407type SerializedPut = (String, Vec<u8>);
2408type PendingPuts = HashMap<String, Vec<SerializedPut>>;
2409
2410/// One Fetcher route transferred from a Worker Loader parent into its child.
2411/// The generation and the complete target travel together, so a loaded Worker
2412/// cannot accidentally resolve the route against a later deployment.
2413#[derive(Clone, Debug, PartialEq)]
2414struct OutboundBroker {
2415 generation: crate::generation::GenerationId,
2416 script: String,
2417 entrypoint: Option<crate::WorkerFetchEntrypoint>,
2418}
2419
2420/// Ambient outbound authority for an isolate. Normal workers keep `Allow`; a
2421/// Worker Loader can deny egress or route it through a transferred Fetcher.
2422#[derive(Clone, Default, PartialEq)]
2423enum EgressPolicy {
2424 #[default]
2425 Allow,
2426 Deny,
2427 Broker(OutboundBroker),
2428}
2429
2430#[derive(Default)]
2431struct ActorRuntimeState {
2432 promises: std::sync::Mutex<PromiseMap>,
2433 termination: std::sync::Mutex<Option<ExecutionTermination>>,
2434 pending_puts: std::sync::Mutex<PendingPuts>,
2435 io_contexts: std::sync::Mutex<HashMap<u64, Weak<IoContext>>>,
2436 /// WebSocket captures that received a frame in the current isolate turn.
2437 /// Weak references record every continuation context without extending
2438 /// an event's lifetime merely to flush its output.
2439 ws_capture_touched: Mutex<Vec<Weak<IoContext>>>,
2440 egress: EgressPolicy,
2441 resource_limits: Option<ResourceLimits>,
2442 tail_reporting: bool,
2443 script_name: String,
2444 event_hooks: OnceLock<EventHooks>,
2445 /// See [`internals`].
2446 internals: OnceLock<v8::Global<v8::Object>>,
2447 /// Set once a patch is installed, so an unpatched isolate pays one
2448 /// relaxed load per op and not a lock: the patch check runs on every op
2449 /// call of every test, and the lock cost 18% on an op-bound loop.
2450 #[cfg(celld_internal_tests)]
2451 op_patched: AtomicBool,
2452 #[cfg(celld_internal_tests)]
2453 op_patches: Mutex<HashMap<&'static str, v8::Global<v8::Function>>>,
2454 #[cfg(celld_internal_tests)]
2455 op_patches_active: Mutex<HashSet<&'static str>>,
2456}
2457
2458/// The harness functions the host calls on the boundary of every cell event.
2459///
2460/// `harness.js` installs `__beginEvent`, `__endEvent`, `__advanceIoTime`, and
2461/// `__abortIncomingRequest` on the internals object once per isolate and
2462/// never replaces them. Reading each one back by name per event costs a fresh
2463/// `v8::String` plus a lookup for a result that cannot change; holding the
2464/// functions removes the string and the lookup together.
2465///
2466/// The four are resolved together on purpose. A partial resolution would
2467/// leave one hook still reached by name, so `install_harness` builds all four
2468/// or the isolate fails to load, and no caller has to remember which of them
2469/// is cached.
2470///
2471/// A `v8::Global` is only valid in the isolate that created it, which is why
2472/// this hangs off `ActorRuntimeState` — an isolate slot — and not off a
2473/// process-wide `static`. `ModuleRegistry` documents the same constraint.
2474struct EventHooks {
2475 begin_event: v8::Global<v8::Function>,
2476 end_event: v8::Global<v8::Function>,
2477 advance_io_time: v8::Global<v8::Function>,
2478 abort_incoming_request: v8::Global<v8::Function>,
2479}
2480
2481/// One cached hook, opened into `scope`.
2482///
2483/// `pick` names the hook rather than a getter per hook, so the four call
2484/// sites stay one line each.
2485fn event_hook<'s>(
2486 scope: &mut v8::PinScope<'s, '_>,
2487 pick: fn(&EventHooks) -> &v8::Global<v8::Function>,
2488) -> Result<v8::Local<'s, v8::Function>> {
2489 let state = actor_runtime_state(scope);
2490 let hooks = state
2491 .event_hooks
2492 .get()
2493 .ok_or_else(|| anyhow!("event hooks are not installed"))?;
2494 Ok(v8::Local::new(scope, pick(hooks)))
2495}
2496
2497/// Advance the isolate clock at an I/O boundary before JavaScript resumes.
2498///
2499/// The cached hook is installed before user code loads, so a script cannot
2500/// replace the function that owns this invariant. Each caller is a complete
2501/// JavaScript turn caused by external input or by a completed native op.
2502/// The return value is the sample that an alarm turn must use for its due
2503/// comparison, so the host and JavaScript observe one event time.
2504fn advance_io_time(scope: &mut v8::PinScope) -> i64 {
2505 let timestamp_ms = unix_now_ms();
2506 let hook = event_hook(scope, |hooks| &hooks.advance_io_time)
2507 .expect("the isolate clock hook is installed");
2508 let timestamp = v8::Number::new(scope, timestamp_ms as f64);
2509 let recv = v8::undefined(scope).into();
2510 hook.call(scope, recv, &[timestamp.into()])
2511 .expect("the isolate clock hook cannot throw");
2512 timestamp_ms
2513}
2514
2515impl ActorRuntimeState {
2516 fn io_context(&self, id: u64) -> Option<Arc<IoContext>> {
2517 let mut contexts = self.io_contexts.lock().unwrap();
2518 let context = contexts.get(&id)?.upgrade();
2519 if context.is_none() {
2520 contexts.remove(&id);
2521 }
2522 context
2523 }
2524}
2525
2526struct ExecutionTermination {
2527 error: String,
2528 actor_scope: Option<String>,
2529 context_id: Option<u64>,
2530}
2531
2532#[cfg(all(test, celld_internal_tests))]
2533static CPU_FINISH_TERMINATION_FOR_TEST: Mutex<Option<(usize, usize)>> = Mutex::new(None);
2534
2535#[cfg(all(test, celld_internal_tests))]
2536fn terminate_on_cpu_finish_for_test(runtime_state: &Arc<ActorRuntimeState>, finish: usize) {
2537 let previous = CPU_FINISH_TERMINATION_FOR_TEST
2538 .lock()
2539 .unwrap()
2540 .replace((Arc::as_ptr(runtime_state) as usize, finish));
2541 assert!(
2542 previous.is_none(),
2543 "a CPU finish termination is already armed"
2544 );
2545}
2546
2547#[cfg(all(test, celld_internal_tests))]
2548fn inject_cpu_finish_termination_for_test(
2549 tc: &mut v8::PinScope,
2550 entry: &InFlight,
2551) -> Option<String> {
2552 let mut armed = CPU_FINISH_TERMINATION_FOR_TEST.lock().unwrap();
2553 let (runtime_state, remaining) = armed.as_mut()?;
2554 if *runtime_state != Arc::as_ptr(&entry.runtime_state) as usize {
2555 return None;
2556 }
2557 *remaining = remaining.saturating_sub(1);
2558 if *remaining != 0 {
2559 return None;
2560 }
2561 armed.take();
2562 let error = "Worker exceeded CPU limit of 10 ms".to_string();
2563 *entry
2564 .runtime_state
2565 .termination
2566 .lock()
2567 .expect("termination lock poisoned") = Some(ExecutionTermination {
2568 error: error.clone(),
2569 actor_scope: None,
2570 context_id: None,
2571 });
2572 tc.terminate_execution();
2573 Some(error)
2574}
2575
2576fn finish_cpu_turn(_tc: &mut v8::PinScope, entry: &InFlight) -> Result<(), String> {
2577 #[cfg(all(test, celld_internal_tests))]
2578 if let Some(error) = inject_cpu_finish_termination_for_test(_tc, entry) {
2579 return Err(error);
2580 }
2581 entry.context.finish_cpu_turn()
2582}
2583
2584/// A backstop for JavaScript that never returns to the host's exact CPU
2585/// sample. Exact accounting rejects finite turns in `finish_cpu_turn`; this
2586/// scheduler exists because an infinite loop has no later boundary at which
2587/// that sample can run. One process-wide thread watches all isolates. A thread
2588/// per turn consumed a PID under cgroup `pids.max` and paid an OS thread spawn
2589/// and join for every JavaScript continuation.
2590struct CpuWatchdog {
2591 id: u64,
2592}
2593
2594struct CpuWatch {
2595 limit: Duration,
2596 declared_ms: u32,
2597 target_clock: Option<TargetThreadCpuClock>,
2598 target_started: Option<u64>,
2599 next_check: Instant,
2600 isolate: v8::IsolateHandle,
2601 runtime_state: Arc<ActorRuntimeState>,
2602}
2603
2604#[derive(Default)]
2605struct CpuWatchdogState {
2606 next_id: u64,
2607 watches: HashMap<u64, CpuWatch>,
2608}
2609
2610struct CpuWatchdogService {
2611 shared: Arc<(Mutex<CpuWatchdogState>, std::sync::Condvar)>,
2612}
2613
2614static CPU_WATCHDOG_SERVICE: OnceLock<CpuWatchdogService> = OnceLock::new();
2615
2616fn cpu_watchdog_remaining(
2617 limit: Duration,
2618 started_nanos: Option<u64>,
2619 current_nanos: Option<u64>,
2620) -> Option<Duration> {
2621 let elapsed = started_nanos
2622 .zip(current_nanos)
2623 .map(|(started, current)| current.saturating_sub(started))?;
2624 let limit_nanos = u64::try_from(limit.as_nanos()).unwrap_or(u64::MAX);
2625 (elapsed < limit_nanos).then(|| Duration::from_nanos(limit_nanos - elapsed))
2626}
2627
2628impl CpuWatchdog {
2629 fn start(
2630 limit: Option<Duration>,
2631 declared_ms: Option<u32>,
2632 isolate: v8::IsolateHandle,
2633 runtime_state: Arc<ActorRuntimeState>,
2634 ) -> Option<Self> {
2635 let limit = limit?;
2636 let declared_ms = declared_ms?;
2637 let service = cpu_watchdog_service();
2638 let target_clock = TargetThreadCpuClock::current();
2639 let watch = CpuWatch {
2640 limit,
2641 declared_ms,
2642 target_clock,
2643 target_started: target_clock.and_then(TargetThreadCpuClock::nanos),
2644 next_check: Instant::now() + limit,
2645 isolate,
2646 runtime_state,
2647 };
2648 let (state, wake) = &*service.shared;
2649 let mut state = state.lock().unwrap();
2650 let id = state.next_id;
2651 state.next_id = state.next_id.wrapping_add(1);
2652 state.watches.insert(id, watch);
2653 drop(state);
2654 wake.notify_one();
2655 Some(Self { id })
2656 }
2657
2658 #[cfg(all(test, celld_internal_tests))]
2659 fn is_registered_for_test(&self) -> bool {
2660 cpu_watchdog_service()
2661 .shared
2662 .0
2663 .lock()
2664 .unwrap()
2665 .watches
2666 .contains_key(&self.id)
2667 }
2668}
2669
2670impl Drop for CpuWatchdog {
2671 fn drop(&mut self) {
2672 let (state, wake) = &*cpu_watchdog_service().shared;
2673 state.lock().unwrap().watches.remove(&self.id);
2674 wake.notify_one();
2675 }
2676}
2677
2678fn cpu_watchdog_service() -> &'static CpuWatchdogService {
2679 CPU_WATCHDOG_SERVICE.get_or_init(|| {
2680 let shared = Arc::new((
2681 Mutex::new(CpuWatchdogState::default()),
2682 std::sync::Condvar::new(),
2683 ));
2684 let scheduler = shared.clone();
2685 std::thread::Builder::new()
2686 .name("celld-cpu-watchdog".to_string())
2687 .spawn(move || run_cpu_watchdog_service(&scheduler))
2688 .expect("spawn the process CPU watchdog");
2689 CpuWatchdogService { shared }
2690 })
2691}
2692
2693fn run_cpu_watchdog_service(shared: &Arc<(Mutex<CpuWatchdogState>, std::sync::Condvar)>) -> ! {
2694 let (state, wake) = &**shared;
2695 let mut state = state.lock().unwrap();
2696 loop {
2697 let Some(next_check) = state.watches.values().map(|watch| watch.next_check).min() else {
2698 state = wake.wait(state).unwrap();
2699 continue;
2700 };
2701 let now = Instant::now();
2702 if now < next_check {
2703 let (next_state, _) = wake.wait_timeout(state, next_check - now).unwrap();
2704 state = next_state;
2705 continue;
2706 }
2707
2708 let due = state
2709 .watches
2710 .iter()
2711 .filter_map(|(id, watch)| (watch.next_check <= now).then_some(*id))
2712 .collect::<Vec<_>>();
2713 for id in due {
2714 let Some(watch) = state.watches.get_mut(&id) else {
2715 continue;
2716 };
2717 if let Some(remaining) = cpu_watchdog_remaining(
2718 watch.limit,
2719 watch.target_started,
2720 watch.target_clock.and_then(TargetThreadCpuClock::nanos),
2721 ) {
2722 watch.next_check = Instant::now() + remaining;
2723 continue;
2724 }
2725 let watch = state.watches.remove(&id).unwrap();
2726 let mut termination = watch
2727 .runtime_state
2728 .termination
2729 .lock()
2730 .expect("termination lock poisoned");
2731 if termination.is_none() {
2732 *termination = Some(ExecutionTermination {
2733 error: format!("Worker exceeded CPU limit of {} ms", watch.declared_ms),
2734 actor_scope: None,
2735 context_id: None,
2736 });
2737 drop(termination);
2738 watch.isolate.terminate_execution();
2739 }
2740 }
2741 }
2742}
2743
2744fn cpu_watchdog_for_context(scope: &mut v8::PinScope, context: &IoContext) -> Option<CpuWatchdog> {
2745 let runtime_state = actor_runtime_state(scope);
2746 let declared_ms = context
2747 .cpu_limit_nanos
2748 .and_then(|limit| u32::try_from(limit / 1_000_000).ok());
2749 CpuWatchdog::start(
2750 context.remaining_cpu_budget(),
2751 declared_ms,
2752 scope.thread_safe_handle(),
2753 runtime_state,
2754 )
2755}
2756
2757fn finish_terminated_actor_event(scope: &mut v8::PinScope, context: &IoContext) {
2758 finish_retired_input_gate_context(scope, context);
2759}
2760
2761fn finish_retired_input_gate_context(scope: &mut v8::PinScope, context: &IoContext) {
2762 context.force_retire_cross_entry_gates();
2763 let _ = abandon_context_input_gates(context);
2764 let context_id = context.continuation_id().unwrap_or_default();
2765 retire_input_gate_js_context(scope, context_id);
2766}
2767
2768fn retire_input_gate_js_context(scope: &mut v8::PinScope, context_id: u64) {
2769 let Ok(function) = internal_function(scope, "__retireInputGateContext") else {
2770 return;
2771 };
2772 let context_id = v8::String::new(scope, &context_id.to_string()).unwrap();
2773 let recv = v8::undefined(scope).into();
2774 let _ = function.call(scope, recv, &[context_id.into()]);
2775}
2776
2777/// The fetch handler of a loaded Worker that exports none: workerd's text,
2778/// thrown when a request reaches it, as on Cloudflare.
2779const NO_FETCH_HANDLER: &str =
2780 "() => { throw new Error('Handler does not export a fetch() function.'); }";
2781
2782/// Evaluate a host-written JS expression, with `__celld` bound, to a function.
2783fn compile_fn<'s>(
2784 scope: &mut v8::PinScope<'s, '_>,
2785 src: &str,
2786) -> Result<v8::Local<'s, v8::Function>> {
2787 let value = run_internal_snippet(scope, &format!("return {src};"))
2788 .ok_or_else(|| anyhow!("compile shim: {src}"))?;
2789 value
2790 .try_into()
2791 .map_err(|_| anyhow!("shim is not a function: {src}"))
2792}
2793
2794/// Whether `register_entrypoints` put `name` in the `__cell.<registry>`
2795/// object (e.g. `entrypoints`, `doExports`).
2796fn cell_registry_has(scope: &mut v8::PinScope, registry: &str, name: &str) -> Result<bool> {
2797 let cell = cell_state(scope)?;
2798 let registry_key = v8::String::new(scope, registry).unwrap();
2799 let registry_obj = cell
2800 .get(scope, registry_key.into())
2801 .and_then(|value| value.to_object(scope))
2802 .ok_or_else(|| anyhow!("missing __cell.{registry} registry"))?;
2803 let name_key = v8::String::new(scope, name).unwrap();
2804 Ok(registry_obj
2805 .has_own_property(scope, name_key.into())
2806 .unwrap_or(false))
2807}
2808
2809fn take_execution_termination_in_context(
2810 scope: &mut v8::PinScope,
2811 context: Option<&IoContext>,
2812) -> Option<anyhow::Error> {
2813 let state = scope.get_slot::<Arc<ActorRuntimeState>>().cloned();
2814 let termination = state
2815 .as_ref()
2816 .and_then(|state| state.termination.lock().ok()?.take());
2817 let is_terminating = scope.is_execution_terminating();
2818 if termination.is_some() || is_terminating {
2819 scope.cancel_terminate_execution();
2820 }
2821 if let Some(termination) = termination {
2822 if termination.actor_scope.is_some() {
2823 if let Some(context_id) = termination.context_id {
2824 if let Some(context) = state
2825 .as_ref()
2826 .and_then(|state| state.io_context(context_id))
2827 {
2828 finish_terminated_actor_event(scope, &context);
2829 }
2830 } else if let Some(context) = context {
2831 finish_terminated_actor_event(scope, context);
2832 } else {
2833 finish_terminated_actor_event(scope, &current_context());
2834 }
2835 }
2836 return Some(anyhow!(termination.error));
2837 }
2838 is_terminating.then(|| anyhow!("JavaScript execution was terminated"))
2839}
2840
2841fn take_execution_termination(scope: &mut v8::PinScope) -> Option<anyhow::Error> {
2842 take_execution_termination_in_context(scope, None)
2843}
2844
2845extern "C" fn near_heap_limit(
2846 data: *mut std::ffi::c_void,
2847 current_heap_limit: usize,
2848 _initial_heap_limit: usize,
2849) -> usize {
2850 // SAFETY: `data` points into the Arc stored in the isolate slot. Worker::drop
2851 // removes this callback before the isolate (and its slots) are destroyed.
2852 let state = unsafe { &*(data as *const HeapLimitState) };
2853 state.excessively_exceeded.store(true, Ordering::Relaxed);
2854 // V8 fatally aborts the process if a near-limit callback does not extend
2855 // the limit. This reserve lets JS observe condemnation and unwind.
2856 //
2857 // The extension must also cover one allocation as large as the limit
2858 // itself: flattening a 128 MiB cons string asks V8 for a single 128 MiB
2859 // block, and V8 re-invokes this callback across last-resort GC rounds
2860 // only unreliably (under parallel load it often stops after one round
2861 // and aborts the process). Doubling the original limit makes the first
2862 // invocation sufficient on its own; `recover_heap` and `Drop` still
2863 // restore the original limit, so nothing else changes.
2864 current_heap_limit
2865 .saturating_add(V8_HEAP_EMERGENCY_BYTES)
2866 .max(state.limit.saturating_mul(2))
2867}
2868
2869/// Live heap use, as a share of `limit`.
2870fn heap_share(isolate: &mut v8::Isolate, limit: usize) -> f64 {
2871 if limit == 0 {
2872 return 0.0;
2873 }
2874 isolate.get_heap_statistics().used_heap_size() as f64 / limit as f64
2875}
2876
2877fn v8_heap_limit_bytes() -> usize {
2878 crate::env_vars::positive::<usize>("CELLD_V8_HEAP_LIMIT_MB")
2879 .expect("validated CELLD_V8_HEAP_LIMIT_MB")
2880 .map(|megabytes| {
2881 megabytes
2882 .checked_mul(1024 * 1024)
2883 .expect("validated CELLD_V8_HEAP_LIMIT_MB range")
2884 })
2885 .unwrap_or(DEFAULT_V8_HEAP_LIMIT_BYTES)
2886}
2887
2888impl Drop for WorkerIsolate {
2889 fn drop(&mut self) {
2890 // Detach children while their IDs are still attributable to this
2891 // parent, but do not drop their V8 isolates while this one is entered.
2892 // In-flight child calls hold their own receiver clones and finish
2893 // normally; this removes only the registry's ownership reference.
2894 let loaded_children = take_loader_owner(&self.loader_owner);
2895 let limit = self.original_heap_limit;
2896 {
2897 let (mut locker, _cells) = self.lock();
2898 locker.remove_near_heap_limit_callback(near_heap_limit, limit);
2899 }
2900 drop(loaded_children);
2901 }
2902}
2903
2904/// One in-flight request inside a shared isolate.
2905///
2906/// Owned by the request's own tokio task, which is why every field is
2907/// `Send`: the task suspends between turns and can resume on any worker,
2908/// then re-enters the isolate it is affiliated with.
2909/// Where a finished handler's result goes, and in what shape.
2910///
2911/// A fetch answers an `HttpResponse` and an entrypoint RPC answers bytes.
2912/// Everything between — the turn loop, the op region, cancellation, the
2913/// budget — is identical, so the difference lives here rather than in two
2914/// copies of `drive`.
2915pub enum Answer {
2916 Fetch(tokio::sync::oneshot::Sender<Result<HttpResponse>>),
2917 Rpc(tokio::sync::oneshot::Sender<Result<Vec<u8>>>),
2918 Queue(tokio::sync::oneshot::Sender<Result<QueueDispatchResult>>),
2919 /// A DO method call, which answers a value rather than a response.
2920 CellRpc(tokio::sync::oneshot::Sender<Result<RpcOutcome>>),
2921 /// A `webSocketMessage`, which answers the frames the output gate held
2922 /// and the write they are gated on.
2923 WsMessage(tokio::sync::oneshot::Sender<Result<WsDispatch>>),
2924 /// An event whose result is that it finished: `webSocketOpen`,
2925 /// `webSocketClose`. It answers the position its writes reached, so the
2926 /// shell can open the barrier they need.
2927 Ack(tokio::sync::oneshot::Sender<Result<Option<u64>>>),
2928 /// An alarm, which answers whatever alarm the handler left armed.
2929 Alarm(tokio::sync::oneshot::Sender<Result<(celld_logic::wake::AlarmSnapshot, Option<u64>)>>),
2930}
2931
2932/// The invocation data that becomes one Tail Worker event after all referenced
2933/// work finishes. The response sender stays independent, so tail delivery
2934/// cannot delay or replace the Dynamic Worker response.
2935struct TailReportState {
2936 reply: tokio::sync::oneshot::Sender<String>,
2937 script_name: String,
2938 event_timestamp: i64,
2939 url: String,
2940 method: String,
2941 headers: serde_json::Map<String, serde_json::Value>,
2942 response_status: Option<u16>,
2943 failure: Option<TailException>,
2944}
2945
2946/// A failure and the instant it occurred. Tail delivery can wait for
2947/// `waitUntil` work, so sampling the clock when the report finishes would
2948/// move the exception forward by the duration of that work.
2949#[derive(serde::Serialize)]
2950struct TailException {
2951 timestamp: i64,
2952 name: &'static str,
2953 message: String,
2954}
2955
2956impl TailException {
2957 fn new(message: String) -> Self {
2958 Self {
2959 timestamp: crate::telemetry::now_unix_us() / 1_000,
2960 name: "Error",
2961 message,
2962 }
2963 }
2964}
2965
2966fn tail_request_headers(
2967 headers: &[(String, String)],
2968) -> serde_json::Map<String, serde_json::Value> {
2969 let mut normalized = serde_json::Map::new();
2970 for (name, value) in headers {
2971 match normalized.entry(name.to_ascii_lowercase()) {
2972 serde_json::map::Entry::Vacant(entry) => {
2973 entry.insert(serde_json::Value::String(value.clone()));
2974 }
2975 serde_json::map::Entry::Occupied(mut entry) => {
2976 let serde_json::Value::String(joined) = entry.get_mut() else {
2977 unreachable!("tail request headers contain only strings");
2978 };
2979 joined.push_str(", ");
2980 joined.push_str(value);
2981 }
2982 }
2983 }
2984 normalized
2985}
2986
2987impl TailReportState {
2988 fn record_failure(&mut self, message: String) {
2989 self.failure = Some(TailException::new(message));
2990 }
2991
2992 fn finish(self, context: &IoContext) {
2993 let outcome = if self.failure.is_some() {
2994 "exception"
2995 } else {
2996 "ok"
2997 };
2998 let exceptions: Vec<_> = self.failure.into_iter().collect();
2999 let event = serde_json::json!([{
3000 "scriptName": self.script_name,
3001 "event": {
3002 "request": {
3003 "cf": {},
3004 "headers": self.headers,
3005 "method": self.method,
3006 "url": self.url,
3007 },
3008 "response": self.response_status.map(|status| serde_json::json!({
3009 "status": status,
3010 })),
3011 },
3012 "eventTimestamp": self.event_timestamp,
3013 "logs": context.take_tail_logs(),
3014 "exceptions": exceptions,
3015 "outcome": outcome,
3016 }]);
3017 let _ = self.reply.send(event.to_string());
3018 }
3019}
3020
3021impl Answer {
3022 /// Send an error, whichever shape the caller is waiting for.
3023 fn fail(self, error: anyhow::Error) {
3024 let _ = self.fail_with_arm_gates(error, Vec::new());
3025 }
3026
3027 fn fail_with_arm_gates(
3028 self,
3029 error: anyhow::Error,
3030 gates: Vec<ArmGateRx>,
3031 ) -> Option<GatedReplyRx> {
3032 match self {
3033 Answer::Fetch(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3034 Answer::Rpc(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3035 Answer::Queue(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3036 Answer::CellRpc(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3037 Answer::WsMessage(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3038 Answer::Ack(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3039 Answer::Alarm(reply) => send_answer_after_arm_gates(reply, Err(error), gates),
3040 }
3041 }
3042}
3043
3044async fn await_arm_gates(gates: Vec<ArmGateRx>) -> Result<(), String> {
3045 let mut first_failure = None;
3046 for gate in gates {
3047 let failure = match gate.await {
3048 Ok(Ok(())) => None,
3049 Ok(Err(error)) => Some(error),
3050 Err(_) => Some("wake-entry gate task dropped".into()),
3051 };
3052 if first_failure.is_none() {
3053 first_failure = failure;
3054 }
3055 }
3056 match first_failure {
3057 Some(failure) => Err(failure),
3058 None => Ok(()),
3059 }
3060}
3061
3062fn send_answer_after_arm_gates<T: Send + 'static>(
3063 mut reply: tokio::sync::oneshot::Sender<Result<T>>,
3064 value: Result<T>,
3065 gates: Vec<ArmGateRx>,
3066) -> Option<GatedReplyRx> {
3067 if gates.is_empty() {
3068 drop(reply.send(value));
3069 return None;
3070 }
3071 let (completed, completion) = tokio::sync::oneshot::channel();
3072 let (cancel, mut cancelled) = tokio::sync::oneshot::channel();
3073 #[cfg(celld_internal_tests)]
3074 let drop_task = asyncrt::services()
3075 .wake_entry()
3076 .drop_next_gated_reply_task
3077 .swap(false, Ordering::AcqRel);
3078 asyncrt::spawn(async move {
3079 #[cfg(celld_internal_tests)]
3080 if drop_task {
3081 return;
3082 }
3083 enum GateWait {
3084 Completed(Result<(), String>),
3085 CallerClosed,
3086 Cancelled,
3087 DriverDropped,
3088 }
3089 let gate_wait = {
3090 let mut waiting = Box::pin(await_arm_gates(gates));
3091 let result = asyncrt::select_biased! {
3092 "a completed gate aggregate wins a tie with caller cancellation";
3093 result = &mut waiting => GateWait::Completed(result),
3094 cancellation = async {
3095 asyncrt::select_biased! {
3096 "a closed caller wins a tie with an explicit cancellation signal";
3097 _ = reply.closed() => GateWait::CallerClosed,
3098 cancelled = &mut cancelled => match cancelled {
3099 Ok(()) => GateWait::Cancelled,
3100 Err(_) => GateWait::DriverDropped,
3101 },
3102 }
3103 } => cancellation,
3104 };
3105 // On either cancellation path this drops every unobserved gate
3106 // receiver before the completion becomes visible to the driver.
3107 drop(waiting);
3108 result
3109 };
3110 let value = match gate_wait {
3111 GateWait::Completed(gate_result) => match (value, gate_result) {
3112 (value, Ok(())) => value,
3113 (Ok(_), Err(error)) => Err(anyhow!("wake-entry gate: {error}")),
3114 (Err(primary), Err(error)) => {
3115 tracing::error!(
3116 event = "wake_entry_gate_failed_after_handler_error",
3117 handler_error = %primary,
3118 gate_error = %error,
3119 );
3120 Err(primary.context(format!("wake-entry gate also failed: {error}")))
3121 }
3122 },
3123 GateWait::CallerClosed => {
3124 let failure = value
3125 .as_ref()
3126 .err()
3127 .map(|error| crate::telemetry::cap_error(format!("{error:#}")));
3128 drop(value);
3129 let _ = completed.send(GatedReplyCompletion::CallerClosed { failure });
3130 return;
3131 }
3132 // The driver observed a request cancellation after the handler
3133 // fixed its reply. Do not enter JavaScript again: the handler is
3134 // already over. A successful answer becomes a disconnect error,
3135 // while an existing handler error remains the primary failure.
3136 GateWait::Cancelled => match value {
3137 Ok(_) => Err(anyhow!("The client has disconnected")),
3138 Err(primary) => Err(primary),
3139 },
3140 // Dropping the driver drops both halves of its completion handle.
3141 // Release every detached resource, but do not let an abandoned
3142 // driver manufacture a reply that nothing owns any longer.
3143 GateWait::DriverDropped => {
3144 drop(value);
3145 return;
3146 }
3147 };
3148 let failure = value
3149 .as_ref()
3150 .err()
3151 .map(|error| crate::telemetry::cap_error(format!("{error:#}")));
3152 let completion = match reply.send(value) {
3153 Ok(()) => GatedReplyCompletion::Sent { failure },
3154 Err(value) => {
3155 drop(value);
3156 GatedReplyCompletion::CallerClosed { failure }
3157 }
3158 };
3159 let _ = completed.send(completion);
3160 })
3161 .detach();
3162 Some(GatedReplyRx {
3163 completion,
3164 cancel: Some(cancel),
3165 })
3166}
3167
3168pub(crate) enum GatedReplyCompletion {
3169 /// The final reply value is now visible to the receiver.
3170 Sent { failure: Option<String> },
3171 /// The receiver disappeared, so no reply remains to deliver.
3172 CallerClosed { failure: Option<String> },
3173}
3174
3175pub(crate) struct GatedReplyRx {
3176 completion: tokio::sync::oneshot::Receiver<GatedReplyCompletion>,
3177 cancel: Option<tokio::sync::oneshot::Sender<()>>,
3178}
3179
3180impl GatedReplyRx {
3181 /// Stop waiting on event gates after a request cancellation. The detached
3182 /// task owns the reply value and gate receivers, so it performs their
3183 /// ordered cleanup and reports completion back to the driver.
3184 pub(crate) fn cancel(&mut self) {
3185 if let Some(cancel) = self.cancel.take() {
3186 let _ = cancel.send(());
3187 }
3188 }
3189}
3190
3191impl std::future::Future for GatedReplyRx {
3192 type Output = Result<GatedReplyCompletion, tokio::sync::oneshot::error::RecvError>;
3193
3194 fn poll(
3195 self: Pin<&mut Self>,
3196 context: &mut std::task::Context<'_>,
3197 ) -> std::task::Poll<Self::Output> {
3198 Pin::new(&mut self.get_mut().completion).poll(context)
3199 }
3200}
3201
3202#[cfg(celld_internal_tests)]
3203#[doc(hidden)]
3204pub async fn await_arm_gates_for_test(
3205 gates: Vec<tokio::sync::oneshot::Receiver<Result<(), String>>>,
3206) -> Result<(), String> {
3207 await_arm_gates(gates).await
3208}
3209
3210#[cfg(celld_internal_tests)]
3211#[doc(hidden)]
3212pub enum GatedReplyCompletionForTest {
3213 Sent { failure: Option<String> },
3214 CallerClosed { failure: Option<String> },
3215}
3216
3217#[cfg(celld_internal_tests)]
3218#[doc(hidden)]
3219pub struct GatedReplyForTest(GatedReplyRx);
3220
3221#[cfg(celld_internal_tests)]
3222impl std::future::Future for GatedReplyForTest {
3223 type Output = Result<GatedReplyCompletionForTest, tokio::sync::oneshot::error::RecvError>;
3224
3225 fn poll(
3226 self: Pin<&mut Self>,
3227 context: &mut std::task::Context<'_>,
3228 ) -> std::task::Poll<Self::Output> {
3229 Pin::new(&mut self.get_mut().0).poll(context).map(|result| {
3230 result.map(|completion| match completion {
3231 GatedReplyCompletion::Sent { failure } => {
3232 GatedReplyCompletionForTest::Sent { failure }
3233 }
3234 GatedReplyCompletion::CallerClosed { failure } => {
3235 GatedReplyCompletionForTest::CallerClosed { failure }
3236 }
3237 })
3238 })
3239 }
3240}
3241
3242#[cfg(celld_internal_tests)]
3243#[doc(hidden)]
3244pub fn send_answer_after_arm_gates_for_test<T: Send + 'static>(
3245 reply: tokio::sync::oneshot::Sender<Result<T>>,
3246 value: Result<T>,
3247 gates: Vec<tokio::sync::oneshot::Receiver<Result<(), String>>>,
3248) -> Option<GatedReplyForTest> {
3249 send_answer_after_arm_gates(reply, value, gates).map(GatedReplyForTest)
3250}
3251
3252#[cfg(celld_internal_tests)]
3253#[doc(hidden)]
3254pub fn drop_next_gated_reply_task_for_test() {
3255 asyncrt::services()
3256 .wake_entry()
3257 .drop_next_gated_reply_task
3258 .store(true, Ordering::Release);
3259}
3260
3261pub struct InFlight {
3262 /// The handler's promise. A `Global` because it outlives the turn that
3263 /// created it: Locals never cross a turn, exactly as workerd's
3264 /// `Worker::Lock` never does.
3265 promise: v8::Global<v8::Promise>,
3266 context: Arc<IoContext>,
3267 /// The cell this event belongs to, and `None` for stateless work.
3268 ///
3269 /// It is what the storage-shaped parts of settling — the durability
3270 /// position, a fatal SQL error — are read against.
3271 scope: Option<String>,
3272 /// The cell's committed-write position before the handler ran.
3273 ///
3274 /// The answer carries a write position only if the handler advanced it,
3275 /// so the output gate sees a write this event made and ignores celld's
3276 /// own activation writes (the actor name, alarm bookkeeping).
3277 writes_before: Option<u64>,
3278 request_id: Option<RequestId>,
3279 active_request_id: Option<RequestId>,
3280 reply: Option<Answer>,
3281 gated_reply: Option<GatedReplyRx>,
3282 /// `waitUntil` work still running after the response was sent. The
3283 /// request stays in flight until it settles, as the single-request loop
3284 /// keeps driving it.
3285 background: Option<v8::Global<v8::Promise>>,
3286 /// A successfully completed Durable Object event keeps every referenced
3287 /// native operation alive. Workerd does not require `waitUntil` for this
3288 /// I/O, so dropping these operations loses detached timers and subrequests.
3289 completed_cell_event: bool,
3290 /// Ops this request is waiting on, so a completion can be attributed to
3291 /// the request whose context must be current while its continuation runs.
3292 ops: std::collections::HashSet<u64>,
3293 /// The subset of `ops` whose resource owns this event's `IoContext`.
3294 /// These operations continue after the handler and `waitUntil` settle.
3295 io_context_ops: std::collections::HashSet<u64>,
3296 /// The subset of `ops` that can run while referenced work is live but
3297 /// cannot keep this event alive by themselves.
3298 unrefed_ops: std::collections::HashSet<u64>,
3299 /// The alarm bookkeeping this entry still owes, if it is one.
3300 alarm: Option<AlarmClaim>,
3301 started: Instant,
3302 /// The propagation context for this entry. A rejected foreign context
3303 /// stays here with `sampled` clear, so continuations can forward it
3304 /// without treating it as permission to record spans or logs.
3305 trace: Option<crate::telemetry::TraceContext>,
3306 /// Why the event failed, captured for the span's `error` so a query sees
3307 /// the reason, not only that it failed. This also records an output-gate
3308 /// failure after a successful handler.
3309 failure: Option<String>,
3310 /// The report owed to the loader isolate after this invocation retires.
3311 tail_report: Option<TailReportState>,
3312 /// The isolate this entry's ops belong to, so `abandon` can drop their
3313 /// resolvers without a scope to reach the isolate through.
3314 runtime_state: Arc<ActorRuntimeState>,
3315}
3316
3317impl InFlight {
3318 /// Read the handler's settled value in the shape this entry answers, end
3319 /// the event, and reply.
3320 ///
3321 /// Every shape ends the event exactly once, whether it produced a value
3322 /// or an error — ending it is what yields the `waitUntil` work the entry
3323 /// keeps driving afterwards, and a shape that skipped it on the error
3324 /// path would leave the context open.
3325 fn answer_settled<'s>(
3326 &mut self,
3327 tc: &mut v8::PinScope<'s, '_>,
3328 value: v8::Local<'s, v8::Value>,
3329 ) {
3330 let Some(reply) = self.reply.take() else {
3331 return;
3332 };
3333 // A cell whose SQL failed fatally cannot answer whatever the handler
3334 // returned: the storage the handler read may not be what the cell
3335 // has.
3336 if let Some(error) = self.scope.as_deref().and_then(storage::sql_critical_error) {
3337 let _ = end_event_context(tc);
3338 self.context.seal_wait_until();
3339 if self.trace.is_some_and(|trace| trace.sampled) {
3340 self.failure = Some(crate::telemetry::cap_error(error.to_string()));
3341 }
3342 self.gated_reply =
3343 reply.fail_with_arm_gates(anyhow!(error), self.context.take_arm_gates());
3344 return;
3345 }
3346 self.completed_cell_event = self.scope.is_some();
3347 let (background, gated_reply) = match reply {
3348 Answer::Fetch(reply) => {
3349 // A value the decoder refuses is a failure in the turn like a
3350 // throw is, so it carries the same positions.
3351 let read = self.gate_positions().and_then(|positions| {
3352 let (write_position, observed_position) = positions;
3353 read_response(tc, value)
3354 .map(|mut response| {
3355 response.write_position = write_position;
3356 response.observed_position = observed_position;
3357 response
3358 })
3359 .map_err(|error| fail_in_turn_error(error, positions))
3360 });
3361 if let Some(report) = &mut self.tail_report {
3362 match &read {
3363 Ok(response) => report.response_status = Some(response.status),
3364 Err(error) => report.record_failure(format!("{error:#}")),
3365 }
3366 }
3367 send_and_end(tc, &self.context, reply, read)
3368 }
3369 Answer::Rpc(reply) => {
3370 let read =
3371 view_bytes(value).ok_or_else(|| anyhow!("entrypoint RPC answered non-bytes"));
3372 send_and_end(tc, &self.context, reply, read)
3373 }
3374 Answer::Queue(reply) => {
3375 let read = read_queue_result(tc, value);
3376 if let Ok(result) = &read {
3377 if result.outcome == QueueOutcome::Exception
3378 && self.trace.is_some_and(|trace| trace.sampled)
3379 {
3380 self.failure = Some(crate::telemetry::cap_error(
3381 result
3382 .error
3383 .clone()
3384 .unwrap_or_else(|| "queue handler rejected".to_string()),
3385 ));
3386 }
3387 }
3388 send_and_end(tc, &self.context, reply, read)
3389 }
3390 Answer::CellRpc(reply) => {
3391 let outcome = self
3392 .gate_positions()
3393 .map(|(write_position, observed_position)| {
3394 #[cfg(celld_internal_tests)]
3395 if self.scope.as_deref().is_some_and(|scope| {
3396 scope
3397 .split_once(':')
3398 .is_some_and(|(class, _)| class == crate::deploy::QUEUE_CLASS)
3399 }) {
3400 QUEUE_PRODUCER_WRITE_POSITIONS
3401 .with(|positions| positions.borrow_mut().push(write_position));
3402 }
3403 RpcOutcome {
3404 data: rpc_data_ret(tc, value),
3405 write_position,
3406 observed_position,
3407 }
3408 });
3409 send_and_end(tc, &self.context, reply, outcome)
3410 }
3411 Answer::WsMessage(reply) => {
3412 // Taken before the sample, because the capture reserved each
3413 // frame's place in its socket's queue when the script sent it.
3414 // A failed sample authorizes no output, so its frames are
3415 // discarded as a rejected handler's are. Left on the context,
3416 // the reservation holds every later frame on the socket until
3417 // the context drops, and then closes the socket with 1011.
3418 let frames = ws_capture_take();
3419 let dispatch = match self.gate_positions() {
3420 Ok((write_position, observed_position)) => Ok(WsDispatch {
3421 frames,
3422 write_position,
3423 observed_position,
3424 }),
3425 Err(error) => {
3426 frames.discard();
3427 Err(error)
3428 }
3429 };
3430 send_and_end(tc, &self.context, reply, dispatch)
3431 }
3432 Answer::Ack(reply) => send_and_end(tc, &self.context, reply, self.write_delta()),
3433 Answer::Alarm(reply) => {
3434 // The handler ran and returned, so close the claim as a
3435 // success. This is the only path that does: every other
3436 // `settle_alarm` call site records a failure, and without
3437 // this one a *successful* alarm was recorded as one to
3438 // retry — which re-armed it forever, kept the cell busy,
3439 // and meant an eviction waiting for the cell to go quiet
3440 // never got its turn.
3441 self.settle_alarm(true, false);
3442 // Read what stands *after* that cleanup, and take the delta
3443 // last so it covers the cleanup's own commit — which is the
3444 // write the core must prove durable before it settles the
3445 // alarm.
3446 let alarm = self
3447 .scope
3448 .as_deref()
3449 .map(|cell| observe_alarm(cell, storage::get_alarm(cell)))
3450 .unwrap_or_else(|| celld_logic::wake::AlarmSnapshot::without_wake(None));
3451 send_and_end(
3452 tc,
3453 &self.context,
3454 reply,
3455 self.write_delta().map(|write| (alarm, write)),
3456 )
3457 }
3458 };
3459 self.background = background;
3460 self.gated_reply = gated_reply;
3461 }
3462
3463 /// The write position to gate this answer on: `None` unless the handler
3464 /// advanced the cell's committed writes past where they were.
3465 fn write_delta(&self) -> Result<Option<u64>> {
3466 self.gate_positions().map(|(write, _)| write)
3467 }
3468
3469 /// The positions this answer's ticket carries: the write position when
3470 /// the handler advanced the cell's committed writes past where they were,
3471 /// and the position the answer observed above the cell's published
3472 /// baseline. One sample serves both, so they cannot disagree about what
3473 /// the cell holds.
3474 fn gate_positions(&self) -> Result<(Option<u64>, Option<u64>)> {
3475 match self.scope.as_deref() {
3476 Some(scope) => gate_positions(scope, self.writes_before),
3477 None => Ok((None, None)),
3478 }
3479 }
3480
3481 /// Fail whichever shape is waiting, without knowing which.
3482 ///
3483 /// This must not touch cell storage: a budget overrun and a stuck
3484 /// handler are found on the driving task, between turns, where the
3485 /// storage thread-local is null — settling the alarm claim here
3486 /// panicked the node (denoland/celld#170). The claim stays put, and
3487 /// the drive loop's `owes_alarm` turn records it as not counting
3488 /// against the retry limit, because a failure here is not the
3489 /// handler's. A handler that threw is recorded by `settle`, which
3490 /// knows that it did, before it reaches this.
3491 ///
3492 /// For the same reason the error leaves here without the position the
3493 /// handler's commits reached: `fail_in_turn` is the half that can sample
3494 /// it. A write a handler made before it ran out of budget is therefore
3495 /// still an unproven commit with no barrier of its own.
3496 fn fail(&mut self, error: anyhow::Error) {
3497 if let Some(report) = &mut self.tail_report {
3498 report.record_failure(format!("{error:#}"));
3499 }
3500 if let Some(reply) = self.reply.take() {
3501 if matches!(&reply, Answer::WsMessage(_)) {
3502 // A failed message has no successful dispatch whose barrier
3503 // can authorize its output. Discard the still-active capture
3504 // here so rejection, cancellation, and turn failures cannot
3505 // leave frames for the turn-end flush to publish.
3506 ws_capture_discard(&self.context);
3507 }
3508 if self.trace.is_some_and(|trace| trace.sampled) {
3509 self.failure = Some(crate::telemetry::cap_error(error.to_string()));
3510 }
3511 self.gated_reply = reply.fail_with_arm_gates(error, self.context.take_arm_gates());
3512 }
3513 }
3514
3515 /// Fail the event from inside its isolate turn, where the cell's storage
3516 /// is at hand. The error carries the positions the turn sampled, so the
3517 /// shell gates it as it gates a success. A commit a handler made before it
3518 /// threw is as unproven as one it answered with, and without a ticket it
3519 /// opened no barrier, so a read-only request that followed revealed it
3520 /// while a crash could still lose it. A handler that only read carries the
3521 /// observed position for the same reason: the message it throws with can
3522 /// quote what it read, and the error answer reveals that state as a
3523 /// response body does. An alarm that rejected settled its claim before
3524 /// this, so the delta covers its retry record too; one that failed any
3525 /// other way still owes that record, and `turn_finish_alarm` samples again
3526 /// after writing it.
3527 fn fail_in_turn(&mut self, error: anyhow::Error) {
3528 let error = match self.gate_positions() {
3529 Ok(positions) => fail_in_turn_error(error, positions),
3530 Err(sample) => sample,
3531 };
3532 self.fail(error);
3533 }
3534
3535 /// Fail the event of a client that has hung up. The write half of
3536 /// `fail_in_turn` applies — a commit the handler made still needs its
3537 /// barrier — but the read-only half does not: there is no client left to
3538 /// tell, so no message carries what the handler read, and a read-only
3539 /// ticket would only hold the request's pin, and a shutdown, for a
3540 /// durability round trip that proves nothing.
3541 fn fail_cancelled(&mut self, error: anyhow::Error) {
3542 let error = match self.write_delta() {
3543 Ok(write_position) => fail_in_turn_error(error, (write_position, None)),
3544 Err(sample) => sample,
3545 };
3546 self.fail(error);
3547 }
3548
3549 /// Record how a claimed alarm ended. Runs once; later calls do nothing.
3550 fn settle_alarm(&mut self, ok: bool, counts_against_limit: bool) {
3551 let (Some(scope), Some(claim)) = (self.scope.as_deref(), self.alarm.take()) else {
3552 return;
3553 };
3554 if ok {
3555 storage::finish_alarm_handler(scope, true, claim.now_ms);
3556 } else {
3557 storage::finish_alarm_handler_with_retry_policy(
3558 scope,
3559 false,
3560 claim.now_ms,
3561 counts_against_limit,
3562 );
3563 }
3564 }
3565
3566 /// Whether a claimed alarm's outcome is still unrecorded. True only
3567 /// where the event ended without ever entering the isolate again.
3568 pub fn owes_alarm(&self) -> bool {
3569 self.alarm.is_some()
3570 }
3571
3572 /// Done when the response is sent and no referenced work remains.
3573 pub fn finished(&self) -> bool {
3574 self.retired() && !self.has_refed_ops()
3575 }
3576
3577 /// Whether an operation can keep this event alive.
3578 pub(crate) fn has_refed_ops(&self) -> bool {
3579 self.ops != self.unrefed_ops
3580 }
3581
3582 /// Borrow the reply gate and operation mailbox together. The wake loop
3583 /// must listen to both while the detached gate owns the response, and a
3584 /// split borrow avoids cloning the context on every operation pass.
3585 pub(crate) fn gated_reply_and_io_context(
3586 &mut self,
3587 ) -> (Option<&mut GatedReplyRx>, &Arc<IoContext>) {
3588 (self.gated_reply.as_mut(), &self.context)
3589 }
3590
3591 #[cfg(celld_internal_tests)]
3592 #[doc(hidden)]
3593 pub fn has_gated_reply_for_test(&self) -> bool {
3594 self.gated_reply.is_some()
3595 }
3596
3597 #[cfg(celld_internal_tests)]
3598 #[doc(hidden)]
3599 pub async fn finish_gated_reply_for_test(&mut self) -> bool {
3600 let Some(gated_reply) = self.gated_reply.as_mut() else {
3601 return false;
3602 };
3603 let completion = gated_reply.await;
3604 self.finish_gated_reply(completion);
3605 true
3606 }
3607
3608 /// Ask the detached gate owner to release every event gate and finish the
3609 /// reply edge. The driver waits for its completion before it retires the
3610 /// event, so response resources cannot outlive that cleanup.
3611 pub(crate) fn cancel_gated_reply(&mut self) {
3612 if let Some(gated_reply) = &mut self.gated_reply {
3613 gated_reply.cancel();
3614 }
3615 }
3616
3617 /// Retire a gate waiter after it sent the reply or observed caller-close.
3618 ///
3619 /// This method also closes request sockets when the completion makes the
3620 /// entry retire. `finish_turn` cannot do that earlier because the reply
3621 /// value can still own response resources while the gate is pending.
3622 pub(crate) fn finish_gated_reply(
3623 &mut self,
3624 completion: Result<GatedReplyCompletion, tokio::sync::oneshot::error::RecvError>,
3625 ) {
3626 self.gated_reply = None;
3627 if self.trace.is_some_and(|trace| trace.sampled) {
3628 match completion {
3629 Ok(GatedReplyCompletion::Sent {
3630 failure: Some(failure),
3631 })
3632 | Ok(GatedReplyCompletion::CallerClosed {
3633 failure: Some(failure),
3634 }) => self.failure = Some(failure),
3635 Ok(GatedReplyCompletion::Sent { failure: None }) => {}
3636 Ok(GatedReplyCompletion::CallerClosed { failure: None }) => {
3637 if self.failure.is_none() {
3638 self.failure = Some("The client has disconnected".to_string());
3639 }
3640 }
3641 Err(_) => {
3642 if self.failure.is_none() {
3643 self.failure = Some("wake-entry reply gate task dropped".to_string());
3644 }
3645 }
3646 }
3647 }
3648 if self.retired() {
3649 self.context.close_sockets();
3650 }
3651 }
3652
3653 /// The request has answered and its `waitUntil` work has settled.
3654 ///
3655 /// An isolate-polled WebSocket can still own an op after this point, and
3656 /// that op must not defer retirement. Retiring closes the sockets the
3657 /// request opened, and the pump of an outbound socket ends only with a
3658 /// close, so a retirement that waited for the pump waited for itself and
3659 /// the request never left the drive loop. The op keeps the entry's ops
3660 /// alive instead, through `keeps_native_ops`, which is what a socket the
3661 /// response took over needs: that socket left the request's set at the
3662 /// handoff, so retiring does not close it, and its pump runs until the
3663 /// client closes it.
3664 fn retired(&self) -> bool {
3665 self.reply.is_none()
3666 && self.gated_reply.is_none()
3667 && self.background.is_none()
3668 // A block that holds the gate is still this event's work:
3669 // retiring would close the sockets its callback may still read.
3670 && !self.holds_gate()
3671 // A reaction from this event can run its block during another
3672 // event's turn. Retain this event until that block releases its
3673 // claim, or retirement closes resources the callback still uses.
3674 && self.context.retire_without_cross_entry_gate()
3675 }
3676
3677 /// Why the event failed, when a sampled trace captured it.
3678 pub fn failure(&self) -> Option<&str> {
3679 self.failure.as_deref()
3680 }
3681
3682 pub(crate) fn finish_tail_report(&mut self) {
3683 if let Some(report) = self.tail_report.take() {
3684 report.finish(&self.context);
3685 }
3686 }
3687
3688 /// How long this handler may still run, or `None` once it has answered.
3689 ///
3690 /// The budget bounds the *response*, not the request: `waitUntil` work
3691 /// continues after the client has been served and is not charged for the
3692 /// time the handler already spent.
3693 pub fn remaining(&self, budget: Duration) -> Option<Duration> {
3694 self.reply
3695 .is_some()
3696 .then(|| budget.saturating_sub(self.started.elapsed()))
3697 }
3698
3699 /// Give up on a handler that will not settle.
3700 pub fn time_out(&mut self, budget: Duration) {
3701 self.fail(anyhow!("handler exceeded {}s budget", budget.as_secs()));
3702 }
3703
3704 /// Nothing this request awaits can move it, so it will never settle on
3705 /// its own. Reachable when a handler awaits a promise only some *other*
3706 /// request could resolve — which the pump concealed, because it settled
3707 /// every entry on every turn whoever the turn belonged to.
3708 pub fn stuck(&mut self) {
3709 self.fail(anyhow!("handler is waiting on nothing"));
3710 self.background = None;
3711 self.context.seal_wait_until();
3712 }
3713
3714 /// Whether a nested `WorkerEntrypoint` call is still pending. When no
3715 /// native operation can resume JavaScript, the call itself must reject;
3716 /// failing the enclosing event would prevent its caller from catching the
3717 /// Workerd cancellation.
3718 pub(crate) fn has_pending_events(&self) -> bool {
3719 self.context.has_pending_events()
3720 }
3721
3722 /// Has the client been answered? `waitUntil` work can still be running.
3723 pub fn answered(&self) -> bool {
3724 self.reply.is_none() && self.gated_reply.is_none()
3725 }
3726
3727 /// Whether a native operation can still resume JavaScript for this event.
3728 ///
3729 /// A detached reply gate is host work. It cannot keep handler operations
3730 /// alive after the handler ends. A successfully completed Durable Object
3731 /// event keeps its pending I/O without `waitUntil`, as Workerd does. An
3732 /// operation that owns the event's `IoContext` and a block that holds or
3733 /// is queued to take a cell's input gate can also continue. The block
3734 /// belongs to the object, not to the client: it runs to completion as
3735 /// workerd's critical section does, and its `finally` opens the gate.
3736 /// Dropping its ops with the reply dropped the timer or subrequest it
3737 /// awaited, and the gate stayed shut for every later event (#733).
3738 pub(crate) fn keeps_native_ops(&self) -> bool {
3739 self.reply.is_some()
3740 || self.completed_cell_event
3741 || !self.io_context_ops.is_empty()
3742 || self.keeps_native_ops_after_disconnect()
3743 }
3744
3745 /// Whether work that survives a normal client disconnect still needs
3746 /// this event's native operations.
3747 ///
3748 /// An origin claim covers operations started before a cross-entry block.
3749 /// Its callback can already hold their promises even though another
3750 /// event owns the block's turn and therefore owns the gate engagement.
3751 fn keeps_native_ops_after_disconnect(&self) -> bool {
3752 self.background.is_some()
3753 || self.engages_gate()
3754 || self.context.has_cross_entry_gate_claim()
3755 }
3756
3757 /// Complete the resource-retirement edge that a claim release woke.
3758 pub(crate) fn finish_cross_entry_gates(&self) {
3759 if self.retired() {
3760 self.context.close_sockets();
3761 }
3762 }
3763
3764 /// Whether this event holds a cell's input gate now, or is queued to
3765 /// take one.
3766 fn engages_gate(&self) -> bool {
3767 gate_engagement(self.scope.as_deref(), &self.context) != GateEngagement::None
3768 }
3769
3770 /// Whether this event holds a cell's input gate now. A queued block has
3771 /// not started, so only a held one keeps the event's sockets: a stale
3772 /// queue count from a future that was never adopted must not keep the
3773 /// event from retiring.
3774 fn holds_gate(&self) -> bool {
3775 gate_engagement(self.scope.as_deref(), &self.context) == GateEngagement::Holds
3776 }
3777
3778 /// Whether a client can still disconnect from this request. A request
3779 /// with no id is internal and has no client to hang up.
3780 pub fn cancellable(&self) -> bool {
3781 self.reply.is_some() && self.request_id.is_some()
3782 }
3783
3784 pub fn request_id(&self) -> Option<RequestId> {
3785 self.request_id
3786 }
3787
3788 /// The request is over and its remaining ops are being dropped. Purge
3789 /// their resolvers.
3790 ///
3791 /// An op that never completes would otherwise leave its
3792 /// `Global<PromiseResolver>` in the isolate's map for as long as the
3793 /// isolate lives. A request that drives itself has to purge them on its
3794 /// own way out.
3795 pub fn abandon(&mut self) {
3796 self.context.seal_wait_until();
3797 self.io_context_ops.clear();
3798 self.unrefed_ops.clear();
3799 // An op a foreign turn handed this event after its driver's last pass
3800 // never reached `ops`, so the drain below cannot reach its resolver.
3801 // Closing the mailbox both yields those ops and refuses every later
3802 // hand-off, which is what bounds this to one place instead of a race
3803 // the driver would have to keep re-checking on its way out.
3804 let handed = self.context.close_handed_ops();
3805 if self.ops.is_empty() && handed.is_empty() {
3806 return;
3807 }
3808 let mut promises = self.runtime_state.promises.lock().unwrap();
3809 for id in self.ops.drain() {
3810 promises.remove(&id);
3811 }
3812 for (id, _, _) in handed {
3813 promises.remove(&id);
3814 }
3815 }
3816
3817 /// The context whose mailbox carries the ops other turns enqueued for
3818 /// this event.
3819 ///
3820 /// Borrowed, not cloned. The driver reads this once per pass of a loop
3821 /// that turns for every operation the event completes, and it holds the
3822 /// entry alive for longer than it holds this.
3823 pub(crate) fn io_context(&self) -> &Arc<IoContext> {
3824 &self.context
3825 }
3826
3827 /// Give an op to the event whose continuation enqueued it.
3828 ///
3829 /// The owner's driver polls it, so the owner's retirement decides when it
3830 /// is cancelled and this event's retirement cannot take it away. An owner
3831 /// that is already gone can never run the continuation again, so its
3832 /// resolver goes with the op, exactly as `abandon` drops this event's own.
3833 fn hand_op(
3834 &mut self,
3835 owner: u64,
3836 id: u64,
3837 future: asyncrt::OpFuture,
3838 lifetime: asyncrt::OpLifetime,
3839 ) {
3840 // One branch for both refusals — an owner that is already gone, and
3841 // one whose mailbox closed while this turn ran. Splitting them let the
3842 // second forget to drop the resolver, which is the whole defect.
3843 let delivered = self
3844 .runtime_state
3845 .io_context(owner)
3846 .is_some_and(|context| context.hand_op(id, future, lifetime));
3847 if !delivered {
3848 self.runtime_state.promises.lock().unwrap().remove(&id);
3849 }
3850 }
3851
3852 /// Take the ops another turn enqueued for this event, and record them as
3853 /// this event's own so that `deliver` and `abandon` treat them alike.
3854 pub(crate) fn take_handed_ops(&mut self) -> Vec<Op> {
3855 // The common answer is "none", and reaching it without the queue's
3856 // lock is why the count exists.
3857 if !self.context.has_handed_ops() {
3858 return Vec::new();
3859 }
3860 let handed = self.context.take_handed_ops();
3861 let mut ops = Vec::with_capacity(handed.len());
3862 for (id, future, lifetime) in handed {
3863 self.ops.insert(id);
3864 if lifetime == asyncrt::OpLifetime::IoContext {
3865 self.io_context_ops.insert(id);
3866 }
3867 if lifetime == asyncrt::OpLifetime::Unrefed {
3868 self.unrefed_ops.insert(id);
3869 }
3870 ops.push((id, future));
3871 }
3872 ops
3873 }
3874
3875 fn retire_background_for_shutdown(&mut self) {
3876 self.background = None;
3877 self.context.seal_wait_until();
3878 self.context.close_sockets();
3879 }
3880}
3881
3882/// The CPED slot carries three riders in one immutable record: the
3883/// harness's async-context frame (`__als_get`/`__als_set` — ALS and
3884/// request-context confinement), telemetry's trace context, and the native
3885/// `IoContext` token. Each write builds a fresh three-element array preserving
3886/// the other riders, so V8's per-reaction snapshots restore them atomically.
3887/// Telemetry once took the whole slot and exposed this collision.
3888///
3889/// When all three riders are absent, the slot stays undefined and V8 can use
3890/// its empty-state fast path. Stateless code can retain that path. A cell
3891/// event intentionally installs the native token even when telemetry is off.
3892///
3893/// This reads one rider and leaves the other two unmaterialized. Reading a
3894/// single rider is what every caller wants, so the layout rule lives here
3895/// once and each accessor names its own index. Returning all three instead
3896/// made a caller that wanted one rider pay three `get_index` calls, and a
3897/// caller that wanted two pay six across two reads of the slot. Op
3898/// attribution wants only the token and runs for every operation a
3899/// JavaScript call enqueues, so that difference sits on a hot path.
3900fn cped_rider<'s>(scope: &mut v8::PinScope<'s, '_>, index: u32) -> v8::Local<'s, v8::Value> {
3901 let data = scope.get_continuation_preserved_embedder_data();
3902 let record = match v8::Local::<v8::Array>::try_from(data) {
3903 // Length 2 is the former layout. Its snapshots can still be live
3904 // while an isolate upgrades across this code boundary, and they
3905 // carry no token, so the token rider reads undefined from them.
3906 Ok(record) if record.length() == 3 || record.length() == 2 => record,
3907 // Any non-record value is a bare frame from before this scheme, or
3908 // the empty slot. Only the frame rider can read anything from it,
3909 // and that path returns without asking V8 for anything further.
3910 _ => {
3911 return if index == 0 {
3912 data
3913 } else {
3914 v8::undefined(scope).into()
3915 };
3916 }
3917 };
3918 if index >= record.length() {
3919 return v8::undefined(scope).into();
3920 }
3921 let undefined = v8::undefined(scope).into();
3922 record.get_index(scope, index).unwrap_or(undefined)
3923}
3924
3925fn cped_frame<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
3926 cped_rider(scope, 0)
3927}
3928
3929fn cped_trace<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
3930 cped_rider(scope, 1)
3931}
3932
3933fn cped_io_context<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Value> {
3934 cped_rider(scope, 2)
3935}
3936
3937fn set_cped(
3938 scope: &mut v8::PinScope,
3939 frame: v8::Local<v8::Value>,
3940 trace: v8::Local<v8::Value>,
3941 io_context: v8::Local<v8::Value>,
3942) {
3943 if frame.is_undefined() && trace.is_undefined() && io_context.is_undefined() {
3944 let undefined = v8::undefined(scope).into();
3945 scope.set_continuation_preserved_embedder_data(undefined);
3946 return;
3947 }
3948 let record = v8::Array::new(scope, 3);
3949 record.set_index(scope, 0, frame);
3950 record.set_index(scope, 1, trace);
3951 record.set_index(scope, 2, io_context);
3952 scope.set_continuation_preserved_embedder_data(record.into());
3953}
3954
3955/// Install a trace context into the isolate's CPED slot for one turn.
3956///
3957/// V8 snapshots continuation-preserved embedder data when a promise
3958/// reaction is registered and restores it while the reaction runs. That
3959/// is the exactness `console.log` correlation needs: a continuation
3960/// belonging to a *different* entry that runs during this turn's
3961/// microtask checkpoint carries its own context, not this turn's. The
3962/// layout is 16 trace-id bytes, 8 span-id bytes, and one sampling byte
3963/// in one ArrayBuffer. Sampled contexts pay the existing cost, and only a
3964/// rejected foreign context adds this cost to an unsampled request.
3965///
3966/// Returns the previous slot value *only when a trace was installed*; the
3967/// caller restores it before releasing the isolate. An untraced turn does not
3968/// install the trace rider. A cell event separately installs its `IoContext`
3969/// token, so V8 can attribute a continuation that runs during another event's
3970/// checkpoint.
3971fn install_trace<'s>(
3972 scope: &mut v8::PinScope<'s, '_>,
3973 trace: Option<&crate::telemetry::TraceContext>,
3974) -> Option<v8::Local<'s, v8::Value>> {
3975 let context = trace?;
3976 let previous = scope.get_continuation_preserved_embedder_data();
3977 let buffer = v8::ArrayBuffer::new(scope, 25);
3978 let data = buffer.get_backing_store().data()?;
3979 let bytes = data.as_ptr() as *mut u8;
3980 // SAFETY: a freshly created 25-byte buffer, written before any JS
3981 // can see it.
3982 unsafe {
3983 std::ptr::copy_nonoverlapping(context.trace_id.as_ptr(), bytes, 16);
3984 std::ptr::copy_nonoverlapping(context.span_id.as_ptr(), bytes.add(16), 8);
3985 bytes.add(24).write(u8::from(context.sampled));
3986 }
3987 let frame = cped_frame(scope);
3988 let io_context = cped_io_context(scope);
3989 set_cped(scope, frame, buffer.into(), io_context);
3990 Some(previous)
3991}
3992
3993fn restore_trace(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) {
3994 if let Some(previous) = previous {
3995 scope.set_continuation_preserved_embedder_data(previous);
3996 }
3997}
3998
3999/// Install the current cell event's native context in CPED. V8 restores this
4000/// token for each reaction, including a reaction that runs during another
4001/// event's microtask checkpoint.
4002fn install_io_context<'s>(
4003 scope: &mut v8::PinScope<'s, '_>,
4004 context: &IoContext,
4005) -> Option<v8::Local<'s, v8::Value>> {
4006 let (id, _) = context.continuation.as_ref()?;
4007 let previous = scope.get_continuation_preserved_embedder_data();
4008 let frame = cped_frame(scope);
4009 let trace = cped_trace(scope);
4010 let token: v8::Local<v8::Value> = v8::BigInt::new_from_u64(scope, *id).into();
4011 set_cped(scope, frame, trace, token);
4012 Some(previous)
4013}
4014
4015fn restore_io_context(scope: &mut v8::PinScope, previous: Option<v8::Local<v8::Value>>) {
4016 if let Some(previous) = previous {
4017 scope.set_continuation_preserved_embedder_data(previous);
4018 }
4019}
4020
4021fn current_reaction_io_context(scope: &mut v8::PinScope) -> Option<Arc<IoContext>> {
4022 let id = reaction_continuation_id(scope)?;
4023 actor_runtime_state(scope).io_context(id)
4024}
4025
4026/// The `IoContext` id of the code running at this exact point, read from CPED.
4027///
4028/// It is the running turn's id, or the id of a continuation V8 restored — the
4029/// resource identity of the code, even when a critical section has a separate
4030/// driver for its native operations.
4031fn reaction_continuation_id(scope: &mut v8::PinScope) -> Option<u64> {
4032 continuation_context_id(scope, 0)
4033}
4034
4035/// A plain token names both the resource context and the operation driver.
4036/// A critical section carries [origin, driver] instead: its driver owns the
4037/// gate and must also poll its operations, while storage and resource access
4038/// must still resolve to the origin. Keeping both in the same CPED rider
4039/// preserves this relationship across foreign microtask checkpoints and ALS
4040/// frame changes without charging ordinary continuations for another rider.
4041fn continuation_context_id(scope: &mut v8::PinScope, index: u32) -> Option<u64> {
4042 let token = cped_io_context(scope);
4043 let token = if let Ok(pair) = v8::Local::<v8::Array>::try_from(token) {
4044 pair.get_index(scope, index)?
4045 } else {
4046 token
4047 };
4048 let token = v8::Local::<v8::BigInt>::try_from(token).ok()?;
4049 let (id, lossless) = token.u64_value();
4050 lossless.then_some(id)
4051}
4052
4053fn operation_continuation_id(scope: &mut v8::PinScope) -> Option<u64> {
4054 continuation_context_id(scope, 1)
4055}
4056
4057/// Enter a critical section with its gate owner and operation driver bound
4058/// together. Only the callback's continuations inherit the pair; restoring
4059/// the previous slot leaves the caller's subsequent work with its own event.
4060fn op_with_input_gate_context(
4061 scope: &mut v8::PinScope,
4062 args: v8::FunctionCallbackArguments,
4063 mut rv: v8::ReturnValue<v8::Value>,
4064) {
4065 let Ok(callback) = v8::Local::<v8::Function>::try_from(args.get(0)) else {
4066 return;
4067 };
4068 let previous = scope.get_continuation_preserved_embedder_data();
4069 let token = cped_io_context(scope);
4070 // A nested block inherits its driver's identity, even if a third event
4071 // runs the checkpoint. A new block uses the entry driving this turn.
4072 if !token.is_array() {
4073 if let Some(origin) = reaction_continuation_id(scope) {
4074 let driver = current_context().continuation_id().unwrap_or(origin);
4075 let origin = v8::BigInt::new_from_u64(scope, origin);
4076 let driver = v8::BigInt::new_from_u64(scope, driver);
4077 let pair = v8::Array::new_with_elements(scope, &[origin.into(), driver.into()]);
4078 let frame = cped_frame(scope);
4079 let trace = cped_trace(scope);
4080 set_cped(scope, frame, trace, pair.into());
4081 }
4082 }
4083 let receiver = v8::undefined(scope).into();
4084 let result = callback.call(scope, receiver, &[]);
4085 scope.set_continuation_preserved_embedder_data(previous);
4086 if let Some(result) = result {
4087 rv.set(result);
4088 }
4089}
4090
4091/// Resolve the exact tracked reaction, or use the active context when this
4092/// isolate does not track reactions at all.
4093///
4094/// Cell events always install a token. A token that no longer resolves names
4095/// a retired event and must not borrow another event's ambient context.
4096/// Stateless requests install no token, so their current turn remains the
4097/// only context that can own a synchronous operation such as `process.exit`.
4098fn current_reaction_or_untracked_io_context(scope: &mut v8::PinScope) -> Option<Arc<IoContext>> {
4099 if cped_io_context(scope).is_undefined() {
4100 return Some(current_context());
4101 }
4102 current_reaction_io_context(scope)
4103}
4104
4105/// The trace context current at this exact point of JS execution, read
4106/// from CPED — the running turn's, or the running continuation's if V8
4107/// restored one. `None` when telemetry is off or execution is outside an
4108/// entry. An unsampled foreign context remains present with its flag clear.
4109pub(crate) fn current_trace_context(
4110 scope: &mut v8::PinScope,
4111) -> Option<crate::telemetry::TraceContext> {
4112 if !crate::telemetry::active() {
4113 return None;
4114 }
4115 let data = cped_trace(scope);
4116 let buffer = v8::Local::<v8::ArrayBuffer>::try_from(data).ok()?;
4117 if buffer.byte_length() != 25 {
4118 return None;
4119 }
4120 let data = buffer.get_backing_store().data()?;
4121 let bytes = data.as_ptr() as *const u8;
4122 let mut trace_id = [0u8; 16];
4123 let mut span_id = [0u8; 8];
4124 // SAFETY: length checked; the buffer is alive for this scope.
4125 unsafe {
4126 std::ptr::copy_nonoverlapping(bytes, trace_id.as_mut_ptr(), 16);
4127 std::ptr::copy_nonoverlapping(bytes.add(16), span_id.as_mut_ptr(), 8);
4128 }
4129 let sampled = unsafe { bytes.add(24).read() != 0 };
4130 Some(crate::telemetry::TraceContext {
4131 trace_id,
4132 span_id,
4133 sampled,
4134 })
4135}
4136
4137/// The isolate, entered for one turn. Everything a request does to a shared
4138/// isolate goes through one of these, and none of them may be held across an
4139/// await: the caller takes the pool's async permit first, runs a turn, and
4140/// leaves.
4141/// An isolate's heap as V8 accounts for it, for `/state`.
4142#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
4143pub struct HeapBytes {
4144 /// Physical memory committed to the heap.
4145 pub physical: u64,
4146 /// External memory the isolate tracks: array buffer stores and the like.
4147 pub external: u64,
4148}
4149
4150impl Worker {
4151 /// The heap V8 reports for this isolate. Takes the isolate lock, so the
4152 /// caller must hold the pool's permit for this worker, exactly as a turn
4153 /// does; `None` once the isolate has been freed.
4154 pub fn heap_bytes(&self) -> Option<HeapBytes> {
4155 let inner = self.inner.as_ref()?;
4156 let (mut locker, _cells) = inner.lock();
4157 let statistics = locker.get_heap_statistics();
4158 Some(HeapBytes {
4159 physical: statistics.total_physical_size() as u64,
4160 external: statistics.external_memory() as u64,
4161 })
4162 }
4163
4164 /// Run a request's first turn.
4165 ///
4166 /// Returns what is now in flight — `None` when nothing is, the reply
4167 /// already carrying the error — and the ops the handler enqueued, which
4168 /// the caller awaits with no isolate held.
4169 pub fn turn_begin(
4170 &mut self,
4171 job: crate::WorkerJob,
4172 trace: Option<crate::telemetry::TraceContext>,
4173 ) -> (Option<InFlight>, Vec<Op>) {
4174 let Some(inner) = self.inner.as_mut() else {
4175 return (None, Vec::new());
4176 };
4177 let (mut locker, _cells) = inner.lock();
4178 inner.recover_heap(&mut locker);
4179 v8::scope!(let hs, &mut *locker);
4180 let realm = inner.realm(hs);
4181 let context = realm.context;
4182 let cs = &mut v8::ContextScope::new(hs, context);
4183 let tc = std::pin::pin!(v8::TryCatch::new(cs));
4184 let tc = &mut tc.init();
4185
4186 advance_io_time(tc);
4187 let previous = install_trace(tc, trace.as_ref());
4188 let invocation_limits = match &job {
4189 crate::WorkerJob::Fetch {
4190 invocation_limits, ..
4191 }
4192 | crate::WorkerJob::Rpc {
4193 invocation_limits, ..
4194 } => *invocation_limits,
4195 crate::WorkerJob::Queue { .. } => None,
4196 };
4197 let initial_limits =
4198 effective_resource_limits(inner.runtime_state.resource_limits, invocation_limits);
4199 let declared_ms = initial_limits.and_then(|limits| limits.cpu_ms);
4200 let cpu_watchdog = inner.cpu_watchdog(
4201 declared_ms.map(|milliseconds| Duration::from_millis(u64::from(milliseconds))),
4202 declared_ms,
4203 );
4204 let begun = begin(tc, realm.fetch, job);
4205 drop(cpu_watchdog);
4206 let out = match begun {
4207 Begun::Running(mut entry) => {
4208 entry.trace = trace;
4209 // A handler that returned an already-resolved promise is
4210 // finished before it ever suspends, and must not wait for an
4211 // op it will never start.
4212 let ops = finish_turn(tc, &mut entry);
4213 (Some(*entry), ops)
4214 }
4215 Begun::Threw(failure) => {
4216 let BegunFailure {
4217 answer,
4218 cpu_error,
4219 tail_report,
4220 } = *failure;
4221 let error = take_execution_termination(tc)
4222 .or_else(|| cpu_error.map(anyhow::Error::msg))
4223 .unwrap_or_else(|| anyhow!("fetch threw: {}", exc!(tc)));
4224 if let Some((mut report, context)) = tail_report {
4225 report.record_failure(format!("{error:#}"));
4226 report.finish(&context);
4227 }
4228 answer.fail(error);
4229 (None, Vec::new())
4230 }
4231 Begun::Nothing => (None, Vec::new()),
4232 };
4233 restore_trace(tc, previous);
4234 out
4235 }
4236
4237 /// Enter the isolate solely to end a request whose client has hung up.
4238 ///
4239 /// A suspended request notices the disconnect without any isolate — the
4240 /// flag is host state — so this is reached only when it has actually
4241 /// fired, rather than on a timer as the blocking run loop did.
4242 pub fn turn_cancel(&mut self, entry: &mut InFlight) -> Vec<Op> {
4243 self.cancel_turn(entry, false)
4244 }
4245
4246 /// The runtime is stopping: end the event as a client hang-up does, but
4247 /// keep nothing running for it, a critical section included. The block
4248 /// would not reach its end before the process exits, so its gate is
4249 /// abandoned and the events queued behind it are refused now rather
4250 /// than left waiting through the shutdown.
4251 pub fn turn_cancel_for_shutdown(&mut self, entry: &mut InFlight) -> Vec<Op> {
4252 self.cancel_turn(entry, true)
4253 }
4254
4255 fn cancel_turn(&mut self, entry: &mut InFlight, shutdown: bool) -> Vec<Op> {
4256 let Some(inner) = self.inner.as_mut() else {
4257 return Vec::new();
4258 };
4259 let (mut locker, _cells) = inner.lock();
4260 v8::scope!(let hs, &mut *locker);
4261 let realm = inner.realm(hs);
4262 let context = realm.context;
4263 let cs = &mut v8::ContextScope::new(hs, context);
4264 let tc = std::pin::pin!(v8::TryCatch::new(cs));
4265 let tc = &mut tc.init();
4266
4267 advance_io_time(tc);
4268 let previous_io_context = install_io_context(tc, &entry.context);
4269 let previous = install_trace(tc, entry.trace.as_ref());
4270 entry.context.begin_cpu_turn();
4271 let cpu_watchdog = inner.cpu_watchdog(
4272 entry.context.remaining_cpu_budget(),
4273 entry.context.cpu_limit_ms(),
4274 );
4275 cancel(tc, entry, shutdown);
4276 drop(cpu_watchdog);
4277 let ops = finish_turn(tc, entry);
4278 restore_trace(tc, previous);
4279 restore_io_context(tc, previous_io_context);
4280 ops
4281 }
4282
4283 /// Retire input-gate work for an event that cannot run JavaScript again.
4284 ///
4285 /// The host claims are taken before the isolate lock because the caller
4286 /// already owns this slot. A newly woken event can queue for the slot, but
4287 /// it cannot enter the isolate until the stale actor state is removed.
4288 pub(crate) fn turn_retire_input_gates(&mut self, entry: &InFlight) {
4289 entry.context.force_retire_cross_entry_gates();
4290 let _ = abandon_context_input_gates(&entry.context);
4291 self.turn_retire_input_gate_context(entry);
4292 }
4293
4294 /// Enforce the host-side invariant when an ordinarily completed event
4295 /// drops its final owner. The JavaScript `finally` normally released every
4296 /// gate, so entering the isolate is necessary only when a hold remains.
4297 pub(crate) fn turn_abandon_input_gates(&mut self, entry: &InFlight) {
4298 let abandoned = abandon_context_input_gates(&entry.context);
4299 if abandoned.is_empty() {
4300 return;
4301 }
4302 self.turn_retire_input_gate_context(entry);
4303 }
4304
4305 fn turn_retire_input_gate_context(&mut self, entry: &InFlight) {
4306 let Some(inner) = self.inner.as_mut() else {
4307 return;
4308 };
4309 let (mut locker, _cells) = inner.lock();
4310 v8::scope!(let hs, &mut *locker);
4311 let realm = inner.realm(hs);
4312 let context = realm.context;
4313 let cs = &mut v8::ContextScope::new(hs, context);
4314 let context_id = entry.context.continuation_id().unwrap_or_default();
4315 retire_input_gate_js_context(cs, context_id);
4316 }
4317
4318 /// Run a later turn: resolve one of this request's ops, drain the
4319 /// microtasks that follow, and answer if the handler settled.
4320 pub fn turn_deliver(
4321 &mut self,
4322 entry: &mut InFlight,
4323 op: u64,
4324 res: Result<asyncrt::OpOut, String>,
4325 ) -> Vec<Op> {
4326 let Some(inner) = self.inner.as_mut() else {
4327 return Vec::new();
4328 };
4329 let (mut locker, _cells) = inner.lock();
4330 v8::scope!(let hs, &mut *locker);
4331 let realm = inner.realm(hs);
4332 let context = realm.context;
4333 let cs = &mut v8::ContextScope::new(hs, context);
4334 let tc = std::pin::pin!(v8::TryCatch::new(cs));
4335 let tc = &mut tc.init();
4336
4337 advance_io_time(tc);
4338 let previous_io_context = install_io_context(tc, &entry.context);
4339 let previous = install_trace(tc, entry.trace.as_ref());
4340 entry.context.begin_cpu_turn();
4341 let cpu_watchdog = inner.cpu_watchdog(
4342 entry.context.remaining_cpu_budget(),
4343 entry.context.cpu_limit_ms(),
4344 );
4345 deliver(tc, entry, op, res);
4346 cancelled(tc, entry);
4347 drop(cpu_watchdog);
4348 let ops = finish_turn(tc, entry);
4349 restore_trace(tc, previous);
4350 restore_io_context(tc, previous_io_context);
4351 ops
4352 }
4353}
4354
4355/// Close a turn, whatever the turn did.
4356///
4357/// Every step earns its place and the order is the whole point:
4358///
4359/// 1. **settle** — the handler's promise may have resolved, so marshal the
4360/// response and answer. Marshalling can start a JS-to-host body pump and
4361/// register it with `waitUntil`.
4362/// 2. **checkpoint** — that pump's native ops exist only once the microtasks
4363/// which create them run.
4364/// 3. **release the facet gate** — the second facet flush can now cover every
4365/// write exposed by the checkpoint, or reject the held response.
4366/// 4. **settle again** — the checkpoint may itself have settled the promise,
4367/// or the `waitUntil` aggregate.
4368/// 5. **flush captured frames** — a `webSocketMessage` handler that has not
4369/// answered is suspended, so the frames it has sent so far leave now
4370/// rather than at the end of the handler.
4371/// 6. **adopt** — only now is the set of ops this request waits on complete.
4372/// 7. **close** — close the sockets the request opened, once it has retired.
4373/// A socket the response took over left that set at the handoff.
4374///
4375/// Draining before step 2 is the bug that made a streaming handler answer
4376/// with nothing outstanding and conclude it was waiting on nothing.
4377/// The checkpoint before adoption is what makes response-body pumps visible.
4378///
4379/// An accepted Worker socket starts its next `__ws_next` before the fetch
4380/// response retires. The driver used to drop that receive future with the
4381/// handler's other ops once the handler answered, so later frames hung. An op
4382/// that owns the `IoContext` therefore keeps the entry's ops alive after the
4383/// answer, through `keeps_native_ops`. The lifetime travels in the spawn
4384/// record rather than in a separate op-id tag: a tag can outlive a failed
4385/// turn, and the spawn and its classification drain together. Such an op
4386/// does not defer retirement: see `retired`.
4387fn finish_turn(tc: &mut v8::PinScope, entry: &mut InFlight) -> Vec<Op> {
4388 if let Err(error) = finish_cpu_turn(tc, entry) {
4389 let error = take_execution_termination_in_context(tc, Some(&entry.context))
4390 .unwrap_or_else(|| anyhow!(error));
4391 entry.fail_in_turn(error);
4392 entry.background = None;
4393 entry.abandon();
4394 ws_capture_flush_touched(tc, &entry.runtime_state);
4395 return Vec::new();
4396 }
4397 entry.context.begin_cpu_turn();
4398 {
4399 let _cpu_watchdog = cpu_watchdog_for_context(tc, &entry.context);
4400 settle(tc, entry);
4401 tc.perform_microtask_checkpoint();
4402 // V8 schedules FinalizationRegistry cleanup as a foreground task,
4403 // not a microtask. Without driving that queue, collected loader
4404 // lifetimes never release their host registry entries. Run one task
4405 // per turn under the same CPU watchdog, so cleanup cannot monopolize
4406 // the isolate by continually scheduling more foreground work.
4407 v8::Platform::pump_message_loop(&v8::V8::get_current_platform(), tc, false);
4408 tc.perform_microtask_checkpoint();
4409 }
4410 if let Err(error) = finish_cpu_turn(tc, entry) {
4411 let error = take_execution_termination_in_context(tc, Some(&entry.context))
4412 .unwrap_or_else(|| anyhow!(error));
4413 entry.fail_in_turn(error);
4414 entry.background = None;
4415 entry.abandon();
4416 ws_capture_flush_touched(tc, &entry.runtime_state);
4417 return Vec::new();
4418 }
4419 // `abort()` and `process.exit()` terminate execution without settling
4420 // the handler's promise, so an entry that only watched the promise would
4421 // wait on it forever and then report that it was waiting on nothing.
4422 // The blocking loop broke out of its loop here; an entry fails here.
4423 if let Some(error) = take_execution_termination_in_context(tc, Some(&entry.context)) {
4424 entry.fail_in_turn(error);
4425 entry.background = None;
4426 entry.abandon();
4427 ws_capture_flush_touched(tc, &entry.runtime_state);
4428 return Vec::new();
4429 }
4430 settle(tc, entry);
4431 // 5. **release what suspended WebSocket handlers have sent** — after the
4432 // settles above, so a handler that answered in this turn keeps the
4433 // whole-batch path its answer carries. The set comes from each capture
4434 // write rather than the turn owner, because the checkpoint can run a
4435 // continuation from another event.
4436 ws_capture_flush_touched(tc, &entry.runtime_state);
4437 let ops = adopt(entry);
4438 // 7. **close the request's sockets** — see above.
4439 if entry.retired() {
4440 entry.context.close_sockets();
4441 }
4442 ops
4443}
4444
4445/// An op the JS enqueued, and the id whose promise it resolves.
4446pub type Op = (u64, asyncrt::OpFuture);
4447
4448/// Take the ops this turn enqueued that belong to this event, and hand every
4449/// other event its own.
4450///
4451/// Drained after `settle`, not before: ending an event runs JS, and anything
4452/// that starts there belongs to this request too. The pump drained first and
4453/// so could attribute those to whichever entry it settled next.
4454///
4455/// A turn is not proof of ownership. V8 runs a *foreign* continuation during
4456/// this turn's microtask checkpoint — a cell event resumed by the promise this
4457/// event just settled — and an op that continuation enqueues arrives here
4458/// exactly like this event's own. Adopting it made the wrong driver poll it,
4459/// and retiring then cancelled it together with the resolver, so the event
4460/// really waiting never settled and every later event queued behind it. The op
4461/// layer names the enqueueing continuation,
4462/// so an op with a foreign name goes to that event's driver instead. Critical
4463/// sections carry an explicit driver alongside their resource context; the
4464/// op wrapper uses that driver so gate retirement and op cancellation agree.
4465fn adopt(entry: &mut InFlight) -> Vec<Op> {
4466 let spawns = asyncrt::drain_spawns();
4467 let mine = entry.context.continuation_id();
4468 let mut ops = Vec::with_capacity(spawns.len());
4469 for (id, future, lifetime, owner) in spawns {
4470 if let Some(owner) = owner.filter(|owner| Some(*owner) != mine) {
4471 entry.hand_op(owner, id, future, lifetime);
4472 continue;
4473 }
4474 entry.ops.insert(id);
4475 if lifetime == asyncrt::OpLifetime::IoContext {
4476 entry.io_context_ops.insert(id);
4477 }
4478 if lifetime == asyncrt::OpLifetime::Unrefed {
4479 entry.unrefed_ops.insert(id);
4480 }
4481 ops.push((id, future));
4482 }
4483 ops
4484}
4485
4486/// What starting a request produced.
4487enum Begun {
4488 /// In flight. Its ops must be adopted and its promise driven.
4489 Running(Box<InFlight>),
4490 /// The handler threw before it could suspend, so nothing is in flight.
4491 /// The exception belongs to the caller's `TryCatch` — an unnameable type
4492 /// no signature here can take — so the caller reads it and answers.
4493 Threw(Box<BegunFailure>),
4494 /// Nothing started: the job was not a fetch, or the reply already
4495 /// carries the error.
4496 Nothing,
4497}
4498
4499struct BegunFailure {
4500 answer: Answer,
4501 cpu_error: Option<String>,
4502 tail_report: Option<(TailReportState, Arc<IoContext>)>,
4503}
4504
4505/// Start a request: build it, call the Worker's `fetch`, and hand back what
4506/// is now in flight.
4507///
4508/// The half of a turn that runs *before* anything can suspend.
4509fn begin<'s>(
4510 tc: &mut v8::PinScope<'s, '_>,
4511 fetch: v8::Local<'s, v8::Function>,
4512 job: crate::WorkerJob,
4513) -> Begun {
4514 let job = match job {
4515 crate::WorkerJob::Rpc {
4516 entrypoint,
4517 operation,
4518 props,
4519 invocation_limits,
4520 reply,
4521 } => {
4522 return begin_entrypoint_rpc(
4523 tc,
4524 &entrypoint,
4525 operation,
4526 props,
4527 invocation_limits,
4528 reply,
4529 );
4530 }
4531 crate::WorkerJob::Queue { batch, reply, .. } => {
4532 return begin_queue(tc, batch, reply);
4533 }
4534 job => job,
4535 };
4536 let crate::WorkerJob::Fetch {
4537 entrypoint,
4538 invocation_limits,
4539 url,
4540 method,
4541 body,
4542 headers,
4543 request_id,
4544 tail_report,
4545 reply,
4546 ..
4547 } = job
4548 else {
4549 return Begun::Nothing;
4550 };
4551 let runtime_state = actor_runtime_state(tc);
4552 let tail_reporting = tail_report.is_some();
4553 debug_assert!(
4554 !tail_reporting || runtime_state.tail_reporting,
4555 "a tail report reached a Worker that was loaded without tails",
4556 );
4557 // The report sender is the invocation-level authority. The isolate-level
4558 // option also applies to RPC and cell events, but those events have no
4559 // report to consume retained logs, so enabling capture for them only
4560 // holds records until their IoContext retires.
4561 let context = IoContext::with_options(
4562 effective_resource_limits(runtime_state.resource_limits, invocation_limits),
4563 tail_reporting,
4564 );
4565 if let Some(stream_id) = body.stream_id() {
4566 context.own_body_stream(stream_id);
4567 }
4568 let guard = CurrentGuard::enter(context.clone());
4569 context.begin_cpu_turn();
4570 let target = match entrypoint {
4571 Some(entrypoint) => FetchTarget::Entrypoint(entrypoint),
4572 None => FetchTarget::Default(fetch),
4573 };
4574 let started = start_fetch(tc, target, &url, &method, body, &headers, request_id);
4575 let tail_headers = tail_request_headers(&headers);
4576 let mut tail_report = tail_report.map(|reply| TailReportState {
4577 reply,
4578 script_name: runtime_state.script_name.clone(),
4579 event_timestamp: unix_now_ms(),
4580 url,
4581 method,
4582 headers: tail_headers,
4583 response_status: None,
4584 failure: None,
4585 });
4586 let promise = match started {
4587 Ok(Started::Running(ret, active)) => match ret.try_cast::<v8::Promise>() {
4588 Ok(promise) => Ok((promise, active)),
4589 Err(_) => resolved_promise(tc, ret).map(|promise| (promise, active)),
4590 },
4591 Ok(Started::Threw) => {
4592 let cpu_error = context.finish_cpu_turn().err();
4593 drop(guard);
4594 return Begun::Threw(Box::new(BegunFailure {
4595 answer: Answer::Fetch(reply),
4596 cpu_error,
4597 tail_report: tail_report.take().map(|report| (report, context)),
4598 }));
4599 }
4600 Err(error) => Err(error),
4601 };
4602 match promise {
4603 Ok((promise, active_request_id)) => {
4604 tc.perform_microtask_checkpoint();
4605 let entry = InFlight {
4606 runtime_state,
4607 promise: v8::Global::new(tc, promise),
4608 context,
4609 scope: None,
4610 writes_before: None,
4611 request_id,
4612 active_request_id,
4613 reply: Some(Answer::Fetch(reply)),
4614 gated_reply: None,
4615 background: None,
4616 completed_cell_event: false,
4617 ops: std::collections::HashSet::new(),
4618 io_context_ops: std::collections::HashSet::new(),
4619 unrefed_ops: std::collections::HashSet::new(),
4620 alarm: None,
4621 started: Instant::now(),
4622 trace: None,
4623 failure: None,
4624 tail_report,
4625 };
4626 drop(guard);
4627 Begun::Running(Box::new(entry))
4628 }
4629 Err(error) => {
4630 let cpu_error = context.finish_cpu_turn().err().map(anyhow::Error::msg);
4631 let error = take_execution_termination(tc)
4632 .or(cpu_error)
4633 .unwrap_or(error);
4634 if let Some(mut report) = tail_report.take() {
4635 report.record_failure(format!("{error:#}"));
4636 report.finish(&context);
4637 }
4638 drop(guard);
4639 let _ = reply.send(Err(error));
4640 Begun::Nothing
4641 }
4642 }
4643}
4644
4645/// Start an entrypoint RPC's first turn.
4646///
4647/// The same shape as a fetch and deliberately so: call the handler, keep the
4648/// promise, and let `drive` pump it with no isolate held across the awaits.
4649/// The old dispatcher blocked until the promise settled, which is why RPC
4650/// needed a thread of its own and why `WorkerPool` outlived the fetch path.
4651fn begin_entrypoint_rpc(
4652 tc: &mut v8::PinScope,
4653 entrypoint: &str,
4654 operation: crate::WorkerRpcOperation,
4655 props: Vec<u8>,
4656 invocation_limits: Option<ResourceLimits>,
4657 reply: tokio::sync::oneshot::Sender<Result<Vec<u8>>>,
4658) -> Begun {
4659 let context = IoContext::with_resource_limits(effective_resource_limits(
4660 actor_runtime_state(tc).resource_limits,
4661 invocation_limits,
4662 ));
4663 let guard = CurrentGuard::enter(context.clone());
4664 context.begin_cpu_turn();
4665 let started = (|| {
4666 let f = internal_function(tc, "__dispatchEntrypointRpc")?;
4667 let entrypoint = v8::String::new(tc, entrypoint).unwrap();
4668 let (path, args) = match operation {
4669 crate::WorkerRpcOperation::Get { path } => (path, v8::null(tc).into()),
4670 crate::WorkerRpcOperation::Call { path, args } => (path, bytes_value(tc, args)),
4671 };
4672 let path = path
4673 .iter()
4674 .map(|part| v8::String::new(tc, part).unwrap().into())
4675 .collect::<Vec<v8::Local<v8::Value>>>();
4676 let path = v8::Array::new_with_elements(tc, &path);
4677 // The caller's props, structured-clone bytes like `args`. `local` stays
4678 // false: the call crossed an isolate boundary.
4679 let local = v8::Boolean::new(tc, false);
4680 let props = bytes_value(tc, props);
4681 let recv = v8::undefined(tc).into();
4682 begin_event_context(tc)?;
4683 let ret = f
4684 .call(
4685 tc,
4686 recv,
4687 &[entrypoint.into(), path.into(), args, local.into(), props],
4688 )
4689 .ok_or_else(|| anyhow!("entrypoint RPC threw"))?;
4690 match ret.try_cast::<v8::Promise>() {
4691 Ok(promise) => Ok(promise),
4692 Err(_) => resolved_promise(tc, ret),
4693 }
4694 })();
4695 let event_started = Instant::now();
4696 match started {
4697 Ok(promise) => {
4698 tc.perform_microtask_checkpoint();
4699 let entry = InFlight {
4700 runtime_state: actor_runtime_state(tc),
4701 promise: v8::Global::new(tc, promise),
4702 context,
4703 scope: None,
4704 writes_before: None,
4705 request_id: None,
4706 active_request_id: None,
4707 reply: Some(Answer::Rpc(reply)),
4708 gated_reply: None,
4709 background: None,
4710 completed_cell_event: false,
4711 ops: std::collections::HashSet::new(),
4712 io_context_ops: std::collections::HashSet::new(),
4713 unrefed_ops: std::collections::HashSet::new(),
4714 alarm: None,
4715 started: event_started,
4716 trace: None,
4717 failure: None,
4718 tail_report: None,
4719 };
4720 drop(guard);
4721 Begun::Running(Box::new(entry))
4722 }
4723 Err(error) => {
4724 let _ = end_event_context(tc);
4725 let cpu_error = context.finish_cpu_turn().err().map(anyhow::Error::msg);
4726 let error = take_execution_termination(tc)
4727 .or(cpu_error)
4728 .unwrap_or(error);
4729 drop(guard);
4730 let _ = reply.send(Err(error));
4731 Begun::Nothing
4732 }
4733 }
4734}
4735
4736fn queue_property<'s>(
4737 scope: &mut v8::PinScope<'s, '_>,
4738 object: v8::Local<'s, v8::Object>,
4739 name: &str,
4740) -> Result<v8::Local<'s, v8::Value>> {
4741 let key = v8::String::new(scope, name).unwrap();
4742 object
4743 .get(scope, key.into())
4744 .ok_or_else(|| anyhow!("queue result has no {name}"))
4745}
4746
4747fn queue_bool<'s>(
4748 scope: &mut v8::PinScope<'s, '_>,
4749 object: v8::Local<'s, v8::Object>,
4750 name: &str,
4751) -> Result<bool> {
4752 let value = queue_property(scope, object, name)?;
4753 anyhow::ensure!(value.is_boolean(), "queue result {name} is not a boolean");
4754 Ok(value.boolean_value(scope))
4755}
4756
4757fn queue_delay<'s>(
4758 scope: &mut v8::PinScope<'s, '_>,
4759 object: v8::Local<'s, v8::Object>,
4760) -> Result<Option<i32>> {
4761 let value = queue_property(scope, object, "delaySeconds")?;
4762 if value.is_undefined() {
4763 return Ok(None);
4764 }
4765 value
4766 .int32_value(scope)
4767 .map(Some)
4768 .ok_or_else(|| anyhow!("queue retry delaySeconds is not a 32-bit integer"))
4769}
4770
4771fn queue_string_array<'s>(
4772 scope: &mut v8::PinScope<'s, '_>,
4773 object: v8::Local<'s, v8::Object>,
4774 name: &str,
4775) -> Result<Vec<String>> {
4776 let value = queue_property(scope, object, name)?;
4777 let array: v8::Local<v8::Array> = value
4778 .try_into()
4779 .map_err(|_| anyhow!("queue result {name} is not an array"))?;
4780 (0..array.length())
4781 .map(|index| {
4782 let value = array
4783 .get_index(scope, index)
4784 .ok_or_else(|| anyhow!("queue result {name}[{index}] is missing"))?;
4785 anyhow::ensure!(
4786 value.is_string(),
4787 "queue result {name}[{index}] is not a string"
4788 );
4789 Ok(value.to_rust_string_lossy(scope))
4790 })
4791 .collect()
4792}
4793
4794fn read_queue_result<'s>(
4795 scope: &mut v8::PinScope<'s, '_>,
4796 value: v8::Local<'s, v8::Value>,
4797) -> Result<QueueDispatchResult> {
4798 let object: v8::Local<v8::Object> = value
4799 .try_into()
4800 .map_err(|_| anyhow!("queue handler answered a non-object"))?;
4801 let outcome = queue_property(scope, object, "outcome")?;
4802 anyhow::ensure!(outcome.is_string(), "queue result outcome is not a string");
4803 let outcome = match outcome.to_rust_string_lossy(scope).as_str() {
4804 "ok" => QueueOutcome::Ok,
4805 "exception" => QueueOutcome::Exception,
4806 outcome => return Err(anyhow!("unknown queue result outcome {outcome}")),
4807 };
4808 let error = queue_property(scope, object, "error")?;
4809 let error = if error.is_undefined() {
4810 None
4811 } else {
4812 anyhow::ensure!(error.is_string(), "queue result error is not a string");
4813 Some(error.to_rust_string_lossy(scope))
4814 };
4815 let retry_batch: v8::Local<v8::Object> = queue_property(scope, object, "retryBatch")?
4816 .try_into()
4817 .map_err(|_| anyhow!("queue result retryBatch is not an object"))?;
4818 let retries = queue_property(scope, object, "retryMessages")?;
4819 let retries: v8::Local<v8::Array> = retries
4820 .try_into()
4821 .map_err(|_| anyhow!("queue result retryMessages is not an array"))?;
4822 let mut retry_messages = Vec::with_capacity(retries.length() as usize);
4823 for index in 0..retries.length() {
4824 let retry: v8::Local<v8::Object> = retries
4825 .get_index(scope, index)
4826 .ok_or_else(|| anyhow!("queue result retryMessages[{index}] is missing"))?
4827 .try_into()
4828 .map_err(|_| anyhow!("queue result retryMessages[{index}] is not an object"))?;
4829 let msg_id = queue_property(scope, retry, "msgId")?;
4830 anyhow::ensure!(
4831 msg_id.is_string(),
4832 "queue result retryMessages[{index}].msgId is not a string"
4833 );
4834 retry_messages.push(QueueRetryMessage {
4835 msg_id: msg_id.to_rust_string_lossy(scope),
4836 delay_seconds: queue_delay(scope, retry)?,
4837 });
4838 }
4839 Ok(QueueDispatchResult {
4840 outcome,
4841 error,
4842 ack_all: queue_bool(scope, object, "ackAll")?,
4843 retry_batch: QueueRetryBatch {
4844 retry: queue_bool(scope, retry_batch, "retry")?,
4845 delay_seconds: queue_delay(scope, retry_batch)?,
4846 },
4847 explicit_acks: queue_string_array(scope, object, "explicitAcks")?,
4848 retry_messages,
4849 })
4850}
4851
4852fn set_queue_property<'s>(
4853 scope: &mut v8::PinScope<'s, '_>,
4854 object: v8::Local<'s, v8::Object>,
4855 name: &str,
4856 value: v8::Local<'s, v8::Value>,
4857) -> Result<()> {
4858 let key = v8::String::new(scope, name).unwrap();
4859 anyhow::ensure!(
4860 object.create_data_property(scope, key.into(), value) == Some(true),
4861 "could not construct queue batch field {name}"
4862 );
4863 Ok(())
4864}
4865
4866fn queue_batch_value<'s>(
4867 scope: &mut v8::PinScope<'s, '_>,
4868 batch: QueueBatch,
4869) -> Result<v8::Local<'s, v8::Value>> {
4870 let QueueBatch {
4871 queue,
4872 messages,
4873 metrics,
4874 } = batch;
4875 let mut message_values = Vec::with_capacity(messages.len());
4876 for message in messages {
4877 let object = v8::Object::new(scope);
4878 let id = v8::String::new(scope, &message.id).unwrap();
4879 set_queue_property(scope, object, "id", id.into())?;
4880 let timestamp = v8::Number::new(scope, message.timestamp_ms as f64);
4881 set_queue_property(scope, object, "timestamp", timestamp.into())?;
4882 let body = bytes_value(scope, message.body);
4883 set_queue_property(scope, object, "body", body)?;
4884 let content_type = v8::String::new(scope, message.content_type.as_str()).unwrap();
4885 set_queue_property(scope, object, "contentType", content_type.into())?;
4886 let attempts = v8::Integer::new_from_unsigned(scope, u32::from(message.attempts));
4887 set_queue_property(scope, object, "attempts", attempts.into())?;
4888 message_values.push(object.into());
4889 }
4890
4891 let metrics_value = v8::Object::new(scope);
4892 let count = v8::Number::new(scope, metrics.backlog_count);
4893 set_queue_property(scope, metrics_value, "backlogCount", count.into())?;
4894 let bytes = v8::Number::new(scope, metrics.backlog_bytes);
4895 set_queue_property(scope, metrics_value, "backlogBytes", bytes.into())?;
4896 let oldest = match metrics.oldest_message_timestamp_ms {
4897 Some(timestamp) => v8::Number::new(scope, timestamp as f64).into(),
4898 None => v8::undefined(scope).into(),
4899 };
4900 set_queue_property(scope, metrics_value, "oldestMessageTimestamp", oldest)?;
4901
4902 let value = v8::Object::new(scope);
4903 let queue = v8::String::new(scope, &queue).unwrap();
4904 set_queue_property(scope, value, "queue", queue.into())?;
4905 let messages = v8::Array::new_with_elements(scope, &message_values);
4906 set_queue_property(scope, value, "messages", messages.into())?;
4907 set_queue_property(scope, value, "metrics", metrics_value.into())?;
4908 Ok(value.into())
4909}
4910
4911/// Start a queue consumer's first turn. The batch body bytes move directly
4912/// into V8, and only the small settlement record crosses back out.
4913fn begin_queue(
4914 tc: &mut v8::PinScope,
4915 batch: QueueBatch,
4916 reply: tokio::sync::oneshot::Sender<Result<QueueDispatchResult>>,
4917) -> Begun {
4918 let context = IoContext::with_resource_limits(actor_runtime_state(tc).resource_limits);
4919 let guard = CurrentGuard::enter(context.clone());
4920 context.begin_cpu_turn();
4921 let started = (|| {
4922 let dispatch = internal_function(tc, "__dispatchEntrypointQueue")?;
4923 let batch = queue_batch_value(tc, batch)?;
4924 let entrypoint = v8::String::new(tc, "default").unwrap();
4925 let recv = v8::undefined(tc).into();
4926 begin_event_context(tc)?;
4927 let ret = dispatch
4928 .call(tc, recv, &[entrypoint.into(), batch])
4929 .ok_or_else(|| anyhow!("queue dispatch threw"))?;
4930 match ret.try_cast::<v8::Promise>() {
4931 Ok(promise) => Ok(promise),
4932 Err(_) => resolved_promise(tc, ret),
4933 }
4934 })();
4935 match started {
4936 Ok(promise) => {
4937 tc.perform_microtask_checkpoint();
4938 let entry = InFlight {
4939 runtime_state: actor_runtime_state(tc),
4940 promise: v8::Global::new(tc, promise),
4941 context,
4942 scope: None,
4943 writes_before: None,
4944 request_id: None,
4945 active_request_id: None,
4946 reply: Some(Answer::Queue(reply)),
4947 gated_reply: None,
4948 background: None,
4949 completed_cell_event: false,
4950 ops: std::collections::HashSet::new(),
4951 io_context_ops: std::collections::HashSet::new(),
4952 unrefed_ops: std::collections::HashSet::new(),
4953 alarm: None,
4954 started: Instant::now(),
4955 trace: None,
4956 failure: None,
4957 tail_report: None,
4958 };
4959 drop(guard);
4960 Begun::Running(Box::new(entry))
4961 }
4962 Err(error) => {
4963 let _ = end_event_context(tc);
4964 let cpu_error = context.finish_cpu_turn().err().map(anyhow::Error::msg);
4965 let error = take_execution_termination(tc)
4966 .or(cpu_error)
4967 .unwrap_or(error);
4968 drop(guard);
4969 let _ = reply.send(Err(error));
4970 Begun::Nothing
4971 }
4972 }
4973}
4974
4975/// for the JSON flavor, a `Uint8Array` for structured clone.
4976fn rpc_data_value<'s>(scope: &mut v8::PinScope<'s, '_>, data: RpcData) -> v8::Local<'s, v8::Value> {
4977 match data {
4978 RpcData::Json(json) => v8::String::new(scope, &json).unwrap().into(),
4979 RpcData::V8(bytes) => bytes_value(scope, bytes.into()),
4980 }
4981}
4982
4983/// The inverse: `__dispatchRpc` answers in the flavor it was asked in.
4984fn rpc_data_ret(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> RpcData {
4985 match view_bytes(ret) {
4986 Some(bytes) => RpcData::V8(bytes.into()),
4987 None => RpcData::Json(ret.to_rust_string_lossy(scope)),
4988 }
4989}
4990
4991fn unix_now_ms() -> i64 {
4992 #[cfg(all(test, celld_internal_tests))]
4993 if let Some(timestamp_ms) = unix_now_ms_for_test() {
4994 return timestamp_ms;
4995 }
4996 std::time::SystemTime::now()
4997 .duration_since(std::time::UNIX_EPOCH)
4998 .unwrap_or_default()
4999 .as_millis()
5000 .min(i64::MAX as u128) as i64
5001}
5002
5003/// End the event, then answer with what the handler produced.
5004///
5005/// Ending it is what yields the `waitUntil` aggregate the entry keeps
5006/// driving after the caller has been served, so it happens for every answer
5007/// shape and on the error path too.
5008fn send_and_end<T>(
5009 tc: &mut v8::PinScope,
5010 context: &IoContext,
5011 reply: tokio::sync::oneshot::Sender<Result<T>>,
5012 value: Result<T>,
5013) -> (Option<v8::Global<v8::Promise>>, Option<GatedReplyRx>)
5014where
5015 T: Send + 'static,
5016{
5017 let background = end_event_context(tc).ok().flatten();
5018 let gated_reply = send_answer_after_arm_gates(reply, value, context.take_arm_gates());
5019 (
5020 background.map(|promise| v8::Global::new(tc, promise)),
5021 gated_reply,
5022 )
5023}
5024
5025/// The positions an answer's ticket carries, sampled from a cell's storage:
5026/// the write position when the handler advanced the cell's committed writes
5027/// past `writes_before`, and otherwise the position the answer observed above
5028/// the cell's published baseline. One sample serves both, so they cannot
5029/// disagree about what the cell holds, and they are returned together because
5030/// a site that gates on one alone releases the output the other covers.
5031fn gate_positions(scope: &str, writes_before: Option<u64>) -> Result<(Option<u64>, Option<u64>)> {
5032 let sample = storage::write_position(scope)?;
5033 let write = write_delta(writes_before, sample);
5034 let observed = if write.is_none() {
5035 storage::observed_position(scope, sample)
5036 } else {
5037 None
5038 };
5039 Ok((write, observed))
5040}
5041
5042/// A committed-write position only counts when the handler advanced it; celld's
5043/// own activation writes are already below `before`.
5044pub(crate) fn write_delta(before: Option<u64>, after: Option<u64>) -> Option<u64> {
5045 match (before, after) {
5046 (Some(before), Some(after)) if after > before => Some(after),
5047 _ => None,
5048 }
5049}
5050
5051/// What a claimed alarm still owes its bookkeeping.
5052///
5053/// `finish_alarm_handler` must run exactly once however the event ends, and
5054/// an event can now end without running JS at all — a budget overrun, a
5055/// handler waiting on nothing — so the entry carries the claim rather than
5056/// the caller that made it.
5057struct AlarmClaim {
5058 /// The instant the dispatch was judged due against, so the outcome is
5059 /// recorded against the same one.
5060 now_ms: i64,
5061}
5062
5063/// Start one cell event: the half that runs before the handler can suspend.
5064///
5065/// Every cell event does the same four things — name the cell it belongs to,
5066/// sample the writes its answer will be gated on, open an event context, and
5067/// keep the promise the dispatcher returned. Only the call and the shape of
5068/// the answer differ, which is what the arguments say.
5069fn start_cell_event<'s>(
5070 tc: &mut v8::PinScope<'s, '_>,
5071 scope: &str,
5072 answer: Answer,
5073 request_id: Option<RequestId>,
5074 body_stream_id: Option<u64>,
5075 capture_frames: bool,
5076 call: impl FnOnce(&mut v8::PinScope<'s, '_>) -> Result<v8::Local<'s, v8::Value>>,
5077) -> Begun {
5078 let runtime_state = actor_runtime_state(tc);
5079 let context = IoContext::tracked(&runtime_state);
5080 if let Some(stream_id) = body_stream_id {
5081 context.own_body_stream(stream_id);
5082 }
5083 let guard = CurrentGuard::enter(context.clone());
5084 let previous_io_context = install_io_context(tc, &context);
5085 context.begin_cpu_turn();
5086 // Sampled before the handler runs so the output gate can tell a write
5087 // this event made from celld's own activation writes. The first sample of
5088 // an activation is also the baseline a read-only answer observes above.
5089 let writes_before = storage::event_start_position(scope);
5090 // No guard: this frame is the context's outermost one and the context
5091 // ends with the event, so there is nothing to pop it before.
5092 context.egress.lock().unwrap().push(EgressFrame {
5093 storage: scope.to_string(),
5094 before: writes_before.unwrap_or(0),
5095 // A facet event stores here and gates on the cell that owns the root
5096 // database. Read once, with the position, so no later effect can take
5097 // one without the other.
5098 root: storage::embedded_root_gate(scope),
5099 });
5100 if capture_frames {
5101 ws_capture_begin();
5102 }
5103 let event_started = Instant::now();
5104 let started = (|| {
5105 begin_event_context(tc)?;
5106 let ret = call(tc)?;
5107 match ret.try_cast::<v8::Promise>() {
5108 Ok(promise) => Ok(promise),
5109 Err(_) => resolved_promise(tc, ret),
5110 }
5111 })();
5112 match started {
5113 Ok(promise) => {
5114 tc.perform_microtask_checkpoint();
5115 if capture_frames {
5116 ws_capture_set_promise(&context, v8::Global::new(tc, promise));
5117 }
5118 let entry = InFlight {
5119 runtime_state: runtime_state.clone(),
5120 promise: v8::Global::new(tc, promise),
5121 context,
5122 scope: Some(scope.to_string()),
5123 writes_before,
5124 request_id,
5125 // A cell's dispatcher registers the incoming request itself,
5126 // so there is nothing for the shell to finish; `cancel`
5127 // aborts by the job's own id.
5128 active_request_id: None,
5129 reply: Some(answer),
5130 gated_reply: None,
5131 background: None,
5132 completed_cell_event: false,
5133 ops: std::collections::HashSet::new(),
5134 io_context_ops: std::collections::HashSet::new(),
5135 unrefed_ops: std::collections::HashSet::new(),
5136 alarm: None,
5137 started: event_started,
5138 trace: None,
5139 failure: None,
5140 tail_report: None,
5141 };
5142 restore_io_context(tc, previous_io_context);
5143 drop(guard);
5144 Begun::Running(Box::new(entry))
5145 }
5146 Err(error) => {
5147 // A V8 termination has a concrete stored cause. The dispatcher
5148 // wrapper can only report that its call returned no value, so do
5149 // not replace process.exit or actor-abort with that generic seam.
5150 let cpu_error = context.finish_cpu_turn().err().map(anyhow::Error::msg);
5151 let error = take_execution_termination(tc)
5152 .or(cpu_error)
5153 .unwrap_or(error);
5154 // The handler ran synchronously before it threw, and a
5155 // synchronous storage call both commits and reads, so the error
5156 // carries the positions it reached like a rejection does.
5157 let error = match gate_positions(scope, writes_before) {
5158 Ok(positions) => fail_in_turn_error(error, positions),
5159 Err(sample) => sample,
5160 };
5161 let background = end_event_context(tc)
5162 .ok()
5163 .flatten()
5164 .map(|promise| v8::Global::new(tc, promise));
5165 let failure = crate::telemetry::cap_error(format!("{error:#}"));
5166 if matches!(&answer, Answer::WsMessage(_)) {
5167 ws_capture_discard(&context);
5168 }
5169 let gated_reply = answer.fail_with_arm_gates(error, context.take_arm_gates());
5170 let begun = if gated_reply.is_none() && background.is_none() {
5171 Begun::Nothing
5172 } else {
5173 let undefined = v8::undefined(tc).into();
5174 let promise = resolved_promise(tc, undefined)
5175 .expect("a finishing cell event can create a resolved promise");
5176 Begun::Running(Box::new(InFlight {
5177 runtime_state,
5178 promise: v8::Global::new(tc, promise),
5179 context,
5180 scope: Some(scope.to_string()),
5181 writes_before,
5182 request_id,
5183 active_request_id: None,
5184 reply: None,
5185 gated_reply,
5186 background,
5187 completed_cell_event: false,
5188 ops: std::collections::HashSet::new(),
5189 io_context_ops: std::collections::HashSet::new(),
5190 unrefed_ops: std::collections::HashSet::new(),
5191 alarm: None,
5192 started: event_started,
5193 trace: None,
5194 failure: Some(failure),
5195 tail_report: None,
5196 }))
5197 };
5198 restore_io_context(tc, previous_io_context);
5199 drop(guard);
5200 begun
5201 }
5202 }
5203}
5204
5205/// Start a cell event's first turn.
5206///
5207/// The counterpart of `begin` for the events a cell receives. Where the
5208/// blocking loop ran each of these to completion inside one call — and
5209/// serviced other cells' events inside *that* — each is now an entry a tokio
5210/// task drives, so two events of one cell interleave by suspending rather
5211/// than by nesting.
5212fn begin_cell(tc: &mut v8::PinScope, job: CellJob, event_time: i64) -> Begun {
5213 match job {
5214 CellJob::Fetch {
5215 request_id,
5216 scope,
5217 name,
5218 url,
5219 method,
5220 body,
5221 headers,
5222 reply,
5223 order: _,
5224 } => {
5225 if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) {
5226 let _ = reply.send(Err(error));
5227 return Begun::Nothing;
5228 }
5229 let body_stream_id = body.stream_id();
5230 start_cell_event(
5231 tc,
5232 &scope,
5233 Answer::Fetch(reply),
5234 request_id,
5235 body_stream_id,
5236 false,
5237 |tc| {
5238 let f = internal_function(tc, "__dispatchTo")?;
5239 // A held body crosses as its bytes; a streamed body crosses as
5240 // its host stream id, so the handler reads it in parts instead
5241 // of the routing seam collecting it first.
5242 let (body_value, stream_id) = match body {
5243 RequestBody::Bytes(bytes) => {
5244 (bytes_value(tc, bytes.into()), v8::null(tc).into())
5245 }
5246 RequestBody::Stream(id) => (
5247 v8::undefined(tc).into(),
5248 v8::Number::new(tc, id as f64).into(),
5249 ),
5250 };
5251 let arguments = [
5252 v8::String::new(tc, &scope).unwrap().into(),
5253 v8::String::new(tc, &url).unwrap().into(),
5254 v8::String::new(tc, &method).unwrap().into(),
5255 body_value,
5256 v8::String::new(tc, &serde_json::to_string(&headers)?)
5257 .unwrap()
5258 .into(),
5259 match request_id {
5260 Some(id) => v8::String::new(tc, &request_id_string(id)).unwrap().into(),
5261 None => v8::null(tc).into(),
5262 },
5263 stream_id,
5264 ];
5265 let recv = v8::undefined(tc).into();
5266 f.call(tc, recv, &arguments)
5267 .ok_or_else(|| anyhow!("dispatchTo threw"))
5268 },
5269 )
5270 }
5271 CellJob::Rpc {
5272 request_id,
5273 scope,
5274 name,
5275 method,
5276 args,
5277 reply,
5278 } => {
5279 if let Err(error) = register_actor_name(tc, &scope, name.as_deref()) {
5280 let _ = reply.send(Err(error));
5281 return Begun::Nothing;
5282 }
5283 start_cell_event(
5284 tc,
5285 &scope,
5286 Answer::CellRpc(reply),
5287 request_id,
5288 None,
5289 false,
5290 |tc| {
5291 let f = internal_function(tc, "__dispatchRpc")?;
5292 let arguments = [
5293 v8::String::new(tc, &scope).unwrap().into(),
5294 v8::String::new(tc, &method).unwrap().into(),
5295 rpc_data_value(tc, args),
5296 ];
5297 let recv = v8::undefined(tc).into();
5298 f.call(tc, recv, &arguments)
5299 .ok_or_else(|| anyhow!("dispatchRpc threw"))
5300 },
5301 )
5302 }
5303 CellJob::WsOpen {
5304 scope,
5305 ws_id,
5306 protocol,
5307 reply,
5308 } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5309 let f = internal_function(tc, "__wsOpen")?;
5310 let arguments = [
5311 v8::String::new(tc, &scope).unwrap().into(),
5312 v8::Number::new(tc, ws_id as f64).into(),
5313 v8::String::new(tc, &protocol).unwrap().into(),
5314 ];
5315 let recv = v8::undefined(tc).into();
5316 f.call(tc, recv, &arguments)
5317 .ok_or_else(|| anyhow!("wsOpen threw"))
5318 }),
5319 CellJob::WsMessage {
5320 scope,
5321 ws_id,
5322 data,
5323 reply,
5324 ..
5325 } => start_cell_event(
5326 tc,
5327 &scope,
5328 Answer::WsMessage(reply),
5329 None,
5330 None,
5331 true,
5332 |tc| {
5333 let (name, data) = match data {
5334 WsIn::Text(text) => ("__wsMessage", v8::String::new(tc, &text).unwrap().into()),
5335 WsIn::Binary(bytes) => ("__wsBinary", bytes_value(tc, bytes)),
5336 };
5337 let f = internal_function(tc, name)?;
5338 let arguments = [
5339 v8::String::new(tc, &scope).unwrap().into(),
5340 v8::Number::new(tc, ws_id as f64).into(),
5341 data,
5342 ];
5343 let recv = v8::undefined(tc).into();
5344 f.call(tc, recv, &arguments)
5345 .ok_or_else(|| anyhow!("WebSocket message dispatch threw"))
5346 },
5347 ),
5348 CellJob::WsClosed {
5349 scope,
5350 ws_id,
5351 code,
5352 reason,
5353 was_clean,
5354 reply,
5355 } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5356 let f = internal_function(tc, "__wsClosed")?;
5357 let arguments = [
5358 v8::String::new(tc, &scope).unwrap().into(),
5359 v8::Number::new(tc, ws_id as f64).into(),
5360 v8::Number::new(tc, f64::from(code)).into(),
5361 v8::String::new(tc, &reason).unwrap().into(),
5362 v8::Boolean::new(tc, was_clean).into(),
5363 ];
5364 let recv = v8::undefined(tc).into();
5365 f.call(tc, recv, &arguments)
5366 .ok_or_else(|| anyhow!("wsClosed threw"))
5367 }),
5368 CellJob::Alarm {
5369 request_id,
5370 scope,
5371 scheduled_ms,
5372 claim,
5373 reply,
5374 } => begin_alarm(
5375 tc,
5376 &scope,
5377 scheduled_ms,
5378 claim,
5379 request_id,
5380 reply,
5381 event_time,
5382 ),
5383 #[cfg(celld_internal_tests)]
5384 CellJob::SyncErrorForTest {
5385 scope,
5386 gate,
5387 socket_id,
5388 terminate,
5389 reply,
5390 } => start_cell_event(tc, &scope, Answer::Ack(reply), None, None, false, |tc| {
5391 register_arm_gate_with_current_event(gate, installed_context());
5392 if let Some(socket_id) = socket_id {
5393 current_context().sockets.lock().unwrap().push(socket_id);
5394 }
5395 if terminate {
5396 let state = actor_runtime_state(tc);
5397 *state.termination.lock().expect("termination lock poisoned") =
5398 Some(ExecutionTermination {
5399 error: "synchronous V8 termination sentinel".to_string(),
5400 actor_scope: None,
5401 context_id: None,
5402 });
5403 tc.terminate_execution();
5404 Err(anyhow!("generic synchronous dispatch failure"))
5405 } else {
5406 Err(anyhow!("synchronous cell dispatch sentinel"))
5407 }
5408 }),
5409 }
5410}
5411
5412/// Start an alarm, claiming the due entry so nothing else fires it.
5413///
5414/// The claim is recorded on the entry rather than closed here, because the
5415/// handler has not run yet: the outcome is known only when the event ends,
5416/// which is now many turns away.
5417fn begin_alarm(
5418 tc: &mut v8::PinScope,
5419 scope: &str,
5420 scheduled_ms: i64,
5421 claim: AlarmDispatch,
5422 request_id: Option<RequestId>,
5423 reply: tokio::sync::oneshot::Sender<Result<(celld_logic::wake::AlarmSnapshot, Option<u64>)>>,
5424 event_time: i64,
5425) -> Begun {
5426 if event_time < scheduled_ms {
5427 let _ = reply.send(Err(anyhow!("alarm dispatched before its deadline")));
5428 return Begun::Nothing;
5429 }
5430 #[cfg(celld_internal_tests)]
5431 if let AlarmDispatch::Claimed(retry) = claim {
5432 let Some(scheduled_at) = storage::active_alarm_scheduled_time(scope) else {
5433 let _ = reply.send(Err(anyhow!("alarm dispatched without a claim")));
5434 return Begun::Nothing;
5435 };
5436 return fire_alarm_handler(tc, scope, scheduled_at, retry, None, request_id, reply);
5437 }
5438 let due_by = match claim {
5439 #[cfg(celld_internal_tests)]
5440 AlarmDispatch::Armed => i64::MAX,
5441 AlarmDispatch::Due => event_time,
5442 #[cfg(celld_internal_tests)]
5443 AlarmDispatch::Claimed(_) => unreachable!("claimed alarms return above"),
5444 };
5445 let Some((scheduled_at, retry)) = storage::due_alarm_entry(scope, due_by) else {
5446 // Nothing is due: another dispatch already ran it, or the handler
5447 // that armed it cleared it. Answer what stands now, with no delta —
5448 // no handler ran, so there is nothing written to prove.
5449 let _ = reply.send(Ok((observe_alarm(scope, storage::get_alarm(scope)), None)));
5450 return Begun::Nothing;
5451 };
5452 storage::begin_alarm_handler(scope, scheduled_at);
5453 fire_alarm_handler(
5454 tc,
5455 scope,
5456 scheduled_at,
5457 retry,
5458 Some(AlarmClaim { now_ms: event_time }),
5459 request_id,
5460 reply,
5461 )
5462}
5463
5464/// Call `alarm()`, carrying whatever claim its outcome must close.
5465fn fire_alarm_handler(
5466 tc: &mut v8::PinScope,
5467 scope: &str,
5468 scheduled_at: i64,
5469 retry: i64,
5470 claim: Option<AlarmClaim>,
5471 request_id: Option<RequestId>,
5472 reply: tokio::sync::oneshot::Sender<Result<(celld_logic::wake::AlarmSnapshot, Option<u64>)>>,
5473) -> Begun {
5474 let begun = start_cell_event(
5475 tc,
5476 scope,
5477 Answer::Alarm(reply),
5478 request_id,
5479 None,
5480 false,
5481 |tc| {
5482 let f = internal_function(tc, "__fireAlarm")?;
5483 let arguments = [
5484 v8::String::new(tc, scope).unwrap().into(),
5485 v8::Number::new(tc, scheduled_at as f64).into(),
5486 v8::Number::new(tc, retry as f64).into(),
5487 ];
5488 let recv = v8::undefined(tc).into();
5489 f.call(tc, recv, &arguments)
5490 .ok_or_else(|| anyhow!("alarm threw"))
5491 },
5492 );
5493 match begun {
5494 Begun::Running(mut entry) => {
5495 entry.alarm = claim;
5496 Begun::Running(entry)
5497 }
5498 // The dispatcher never ran, so nothing can have changed the alarm.
5499 // Give the claim back as a failure that does not count against the
5500 // retry limit: the handler is not what failed.
5501 begun => {
5502 if let Some(claim) = claim {
5503 storage::finish_alarm_handler_with_retry_policy(scope, false, claim.now_ms, false);
5504 }
5505 begun
5506 }
5507 }
5508}
5509
5510/// Resolve one completed op and run the microtasks that follow, with the
5511/// owning request's context current.
5512///
5513/// The half of a turn that resumes a suspended request. It knows nothing
5514/// about any other request: the caller has already established that this op
5515/// is `entry`'s.
5516fn deliver(
5517 tc: &mut v8::PinScope,
5518 entry: &mut InFlight,
5519 op: u64,
5520 res: Result<asyncrt::OpOut, String>,
5521) {
5522 entry.ops.remove(&op);
5523 entry.io_context_ops.remove(&op);
5524 entry.unrefed_ops.remove(&op);
5525 let guard = CurrentGuard::enter(entry.context.clone());
5526 resolve_res(tc, op, res);
5527 tc.perform_microtask_checkpoint();
5528 drop(guard);
5529}
5530
5531/// End a request whose client has hung up, so its handler stops running.
5532fn cancelled(tc: &mut v8::PinScope, entry: &mut InFlight) {
5533 if entry.reply.is_none() || !take_request_cancellation(entry.request_id) {
5534 return;
5535 }
5536 let shutdown = take_shutdown_cancellation(entry.request_id);
5537 cancel(tc, entry, shutdown);
5538}
5539
5540/// End a request whose cancellation has already been taken.
5541///
5542/// Split from [`cancelled`] because a suspended request observes the
5543/// cancellation *outside* the isolate — the flag is host state and costs no
5544/// V8 — and only then enters to act on it.
5545fn cancel(tc: &mut v8::PinScope, entry: &mut InFlight, shutdown: bool) {
5546 let guard = CurrentGuard::enter(entry.context.clone());
5547 // The id that names this request to the JS side. A stateless handler is
5548 // registered by the shell, and only once it suspends, so the shell holds
5549 // the id; a cell's dispatcher registers the request itself, so the job's
5550 // own id is the one to abort. Aborting the wrong one — or neither —
5551 // leaves the target's `request.signal` unfired while the caller is told
5552 // the client has gone.
5553 if let Some(id) = entry.active_request_id.or(entry.request_id) {
5554 let _ = abort_incoming_request(tc, id);
5555 }
5556 // Finishing is the shell's to undo only where the shell registered.
5557 if let Some(id) = entry.active_request_id {
5558 finish_incoming_request(tc, id);
5559 }
5560 let background = end_event_context(tc).ok().flatten();
5561 entry.background = background.map(|promise| v8::Global::new(tc, promise));
5562 if shutdown {
5563 finish_retired_input_gate_context(tc, &entry.context);
5564 }
5565 drop(guard);
5566 entry.fail_cancelled(anyhow!("The client has disconnected"));
5567 if shutdown {
5568 // A lifecycle cancellation can be consumed either between turns or
5569 // during an operation turn. Keep the background cleanup here so both
5570 // paths retire the same work.
5571 entry.retire_background_for_shutdown();
5572 }
5573 // A cancelled handler with no waitUntil work has nothing left to drive.
5574 // Drop its host ops now, so their guards cancel routed work. Explicit
5575 // waitUntil work keeps its ops and continues after the client disconnects.
5576 //
5577 // So does a handler that holds or awaits the cell's input gate, or whose
5578 // cross-entry block can still use an operation started by this event.
5579 // Not at shutdown: nothing will run the block to its end, so its gate is
5580 // given up instead.
5581 if shutdown || !entry.keeps_native_ops_after_disconnect() {
5582 entry.abandon();
5583 }
5584}
5585
5586/// Answer a request whose handler promise has settled, and retire its
5587/// `waitUntil` work once that settles too.
5588fn settle(tc: &mut v8::PinScope, entry: &mut InFlight) {
5589 if entry.reply.is_some() {
5590 let promise = v8::Local::new(tc, &entry.promise);
5591 match promise.state() {
5592 v8::PromiseState::Pending => {}
5593 v8::PromiseState::Fulfilled => {
5594 let guard = CurrentGuard::enter(entry.context.clone());
5595 let value = promise.result(tc);
5596 entry.answer_settled(tc, value);
5597 if let Some(request_id) = entry.active_request_id {
5598 finish_incoming_request(tc, request_id);
5599 }
5600 drop(guard);
5601 }
5602 v8::PromiseState::Rejected => {
5603 let guard = CurrentGuard::enter(entry.context.clone());
5604 let reason = reject_reason(tc, promise);
5605 // The handler is what failed, so an alarm's failure here
5606 // counts against its retry limit — unlike a budget overrun
5607 // or a disconnect, which `fail` records as not counting.
5608 entry.settle_alarm(false, true);
5609 let _ = end_event_context(tc);
5610 entry.context.seal_wait_until();
5611 if let Some(request_id) = entry.active_request_id {
5612 finish_incoming_request(tc, request_id);
5613 }
5614 drop(guard);
5615 entry.fail_in_turn(anyhow!("rejected: {reason}"));
5616 }
5617 }
5618 }
5619 if let Some(background) = &entry.background {
5620 let promise = v8::Local::new(tc, background);
5621 if !matches!(promise.state(), v8::PromiseState::Pending) {
5622 let late = entry.context.take_late_wait_until();
5623 entry.background =
5624 wait_until_aggregate(tc, &late).map(|promise| v8::Global::new(tc, promise));
5625 if !late.is_empty() && entry.background.is_none() {
5626 entry.context.seal_wait_until();
5627 }
5628 }
5629 }
5630}
5631
5632fn wait_until_aggregate<'s>(
5633 scope: &mut v8::PinScope<'s, '_>,
5634 promises: &[v8::Global<v8::Promise>],
5635) -> Option<v8::Local<'s, v8::Promise>> {
5636 if promises.is_empty() {
5637 return None;
5638 }
5639 let values = promises
5640 .iter()
5641 .map(|promise| v8::Local::new(scope, promise).into())
5642 .collect::<Vec<v8::Local<v8::Value>>>();
5643 let array = v8::Array::new_with_elements(scope, &values);
5644 all_settled(scope, array.into())?.try_cast().ok()
5645}
5646
5647enum FetchTarget<'s> {
5648 Default(v8::Local<'s, v8::Function>),
5649 Entrypoint(crate::WorkerFetchEntrypoint),
5650}
5651
5652/// Begin a stateless request: build it, call the Worker's `fetch`, and hand
5653/// back the promise it returned.
5654///
5655/// The half of a request that runs *before* it can suspend. Split out from
5656/// driving it to completion so a caller can start several and drive them
5657/// together; the single-request path starts one and drives it immediately,
5658/// which is what it always did.
5659///
5660/// The caller owns the `IoContext` and must have it current: `__beginEvent`
5661/// runs here, and the frame it pushes belongs to this request.
5662fn start_fetch<'s>(
5663 tc: &mut v8::PinScope<'s, '_>,
5664 target: FetchTarget<'s>,
5665 url: &str,
5666 method: &str,
5667 body: RequestBody,
5668 headers: &[(String, String)],
5669 request_id: Option<RequestId>,
5670) -> Result<Started<'s>> {
5671 let req = match request_id {
5672 Some(_) => make_incoming_request(tc, url, method, body, headers),
5673 None => make_request(tc, url, method, body, headers),
5674 }?;
5675 let recv = v8::undefined(tc).into();
5676 let ret = match target {
5677 FetchTarget::Entrypoint(entrypoint) => {
5678 let dispatch = internal_function(tc, "__dispatchEntrypointFetch")?;
5679 let name = v8::String::new(tc, &entrypoint.name).unwrap();
5680 let props = bytes_value(tc, entrypoint.props);
5681 // Settlement and synchronous-throw cleanup both close this host
5682 // frame. The dispatcher supplies its own handler context, but
5683 // omitting the outer frame would leave those paths unbalanced.
5684 begin_event_context(tc)?;
5685 dispatch.call(tc, recv, &[name.into(), req, props])
5686 }
5687 FetchTarget::Default(fetch) => {
5688 let env = harness_env(tc)?;
5689 let execution_ctx = begin_event_context(tc)?;
5690 fetch.call(tc, recv, &[req, env, execution_ctx])
5691 }
5692 };
5693 let Some(ret) = ret else {
5694 // The handler threw synchronously. Termination carries its own error;
5695 // otherwise the pending exception is on the caller's TryCatch, which
5696 // is the only scope that can read it, so it formats the message.
5697 let error = take_execution_termination(tc);
5698 let _ = end_event_context(tc);
5699 return match error {
5700 Some(error) => Err(error),
5701 None => Ok(Started::Threw),
5702 };
5703 };
5704 // A handler that suspends must be reachable by an abort: register it as an
5705 // incoming request so a client disconnect can cancel it. One that already
5706 // settled cannot be cancelled, so its registration is cleared instead.
5707 let active_request_id = match request_id {
5708 Some(request_id)
5709 if ret
5710 .try_cast::<v8::Promise>()
5711 .is_ok_and(|promise| promise.state() == v8::PromiseState::Pending) =>
5712 {
5713 if let Err(error) = register_incoming_request(tc, request_id, req) {
5714 clear_request_cancellation(request_id);
5715 let _ = end_event_context(tc);
5716 return Err(error);
5717 }
5718 Some(request_id)
5719 }
5720 Some(request_id) => {
5721 clear_request_cancellation(request_id);
5722 None
5723 }
5724 None => None,
5725 };
5726 Ok(Started::Running(ret, active_request_id))
5727}
5728
5729/// What `start_fetch` produced: a running handler, or a synchronous throw
5730/// whose exception only the caller's `TryCatch` can read.
5731enum Started<'s> {
5732 Running(v8::Local<'s, v8::Value>, Option<RequestId>),
5733 Threw,
5734}
5735
5736fn settle_isolate_heap(isolate: &mut v8::Isolate) {
5737 #[cfg(all(test, celld_internal_tests))]
5738 let _observation = HeapSettlementObservationForTest::begin();
5739 isolate.low_memory_notification();
5740}
5741
5742impl Worker {
5743 /// Compile the worker module, wire the DO harness, and extract the entry
5744 /// `fetch`. `do_classes` come from the manifest; `bindings` maps a binding
5745 /// name to a DO class name (from wrangler metadata).
5746 ///
5747 /// The runtime builds a `WorkerConfig` directly. This cfg-gated helper
5748 /// constructs the same value from individual options.
5749 #[cfg(celld_internal_tests)]
5750 pub fn load(options: WorkerConfigOptions) -> Result<Worker> {
5751 Self::load_config(Arc::new(WorkerConfig::new(options)))
5752 }
5753
5754 pub fn load_config(config: Arc<WorkerConfig>) -> Result<Worker> {
5755 let src = config.src.as_str();
5756 let script_name = config.script_name.as_str();
5757 let do_classes = config.do_classes.as_slice();
5758 let node = config.node.as_str();
5759 let compat = config.compat;
5760 let params = v8::CreateParams::default().heap_limits(0, v8_heap_limit_bytes());
5761 let mut isolate = v8::Isolate::new(params);
5762 // Dynamic `import()` of builtin specifiers; per-import()-call only.
5763 isolate.set_host_import_module_dynamically_callback(host_import_module_dynamically);
5764 let original_heap_limit = isolate.get_heap_statistics().heap_size_limit();
5765 let heap_limit_state = Arc::new(HeapLimitState {
5766 excessively_exceeded: AtomicBool::new(false),
5767 limit: original_heap_limit,
5768 last_gc_nudge: Mutex::new(None),
5769 #[cfg(celld_internal_tests)]
5770 forced_admission_refusal: AtomicBool::new(false),
5771 });
5772 let runtime_state = Arc::new(ActorRuntimeState {
5773 promises: std::sync::Mutex::new(PromiseMap::new()),
5774 egress: config.egress.clone(),
5775 resource_limits: config.resource_limits,
5776 tail_reporting: config.tail_reporting,
5777 script_name: script_name.to_string(),
5778 ..Default::default()
5779 });
5780 let loader_owner = LoaderOwner::fresh(script_name, config.generation);
5781 let heap_limit_state_ptr =
5782 Arc::as_ptr(&heap_limit_state) as *mut HeapLimitState as *mut std::ffi::c_void;
5783 isolate.set_slot(heap_limit_state);
5784 isolate.set_slot(runtime_state.clone());
5785 isolate.set_slot(Arc::new(ModuleRegistry::default()));
5786 isolate.set_slot(loader_owner.clone());
5787 isolate.set_slot(crate::generation::GenerationTag(config.generation));
5788 // Retains the config so `/bundle` can project it later. Nothing is
5789 // walked or copied here: a worker that never reads its own bundle pays
5790 // only this `Arc` clone.
5791 isolate.set_slot(Arc::new(BundleFs {
5792 config: config.clone(),
5793 tree: OnceLock::new(),
5794 }));
5795 isolate.add_near_heap_limit_callback(near_heap_limit, heap_limit_state_ptr);
5796 let (context, fetch) = {
5797 v8::scope!(let hs, &mut isolate);
5798 let context = v8::Context::new(hs, Default::default());
5799 let cs = &mut v8::ContextScope::new(hs, context);
5800 let tc = std::pin::pin!(v8::TryCatch::new(cs));
5801 let scope = &mut tc.init();
5802
5803 let arguments = install_ops(scope);
5804 install_prelude(scope, &arguments)?; // Web Platform APIs
5805 install_harness(scope, &arguments)?; // DO object model + minimal Response
5806 install_lazy_globals(scope)?;
5807 // A global, so it must exist before the module evaluates: bundles
5808 // read Cloudflare.compatibilityFlags at module scope.
5809 inject_compatibility_flags(scope, compat)?;
5810 inject_storage_compatibility(scope, compat)?;
5811
5812 let module = match compile_module(scope, &config.main_module_name, src) {
5813 Some(m) => m,
5814 None => return Err(anyhow!("compile: {}", exc!(scope))),
5815 };
5816 register_stubs(scope, &config); // cloudflare:*/node:* + text modules
5817 register_wasm_modules(scope, &config.modules);
5818 register_loader_modules(scope, &config, module);
5819 module
5820 .instantiate_module(scope, resolve_external)
5821 .ok_or_else(|| anyhow!("instantiate: {}", exc!(scope)))?;
5822 let ev = match module.evaluate(scope) {
5823 Some(value) => value,
5824 None => {
5825 if let Some(error) = take_execution_termination(scope) {
5826 return Err(error);
5827 }
5828 return Err(anyhow!("evaluate: {}", exc!(scope)));
5829 }
5830 };
5831 if let Some(error) = take_execution_termination(scope) {
5832 return Err(error);
5833 }
5834 if let Ok(p) = ev.try_cast::<v8::Promise>() {
5835 if p.state() == v8::PromiseState::Rejected {
5836 let r = p.result(scope);
5837 let stk = r
5838 .to_object(scope)
5839 .and_then(|o| {
5840 let k = v8::String::new(scope, "stack")?;
5841 o.get(scope, k.into())
5842 })
5843 .map(|s| s.to_rust_string_lossy(scope))
5844 .unwrap_or_default();
5845 return Err(anyhow!(
5846 "top-level rejected: {}\n{}",
5847 r.to_rust_string_lossy(scope),
5848 stk
5849 ));
5850 }
5851 }
5852
5853 let ns = module
5854 .get_module_namespace()
5855 .to_object(scope)
5856 .ok_or_else(|| anyhow!("ns"))?;
5857 // workerd reads every export of the main module as a handler or
5858 // a class, so a primitive export fails the Worker's start.
5859 let names = ns
5860 .get_own_property_names(scope, Default::default())
5861 .ok_or_else(|| anyhow!("ns names"))?;
5862 for index in 0..names.length() {
5863 let name = names.get_index(scope, index).unwrap();
5864 let value = ns.get(scope, name).unwrap();
5865 if !value.is_object() {
5866 return Err(anyhow!(
5867 "Uncaught TypeError: Incorrect type for map entry '{}': the \
5868 provided value is not of type 'function or ExportedHandler'.",
5869 name.to_rust_string_lossy(scope)
5870 ));
5871 }
5872 }
5873
5874 // register each exported DO class into the harness registry
5875 for cn in do_classes {
5876 // The D1 class is the runtime's own and is never a worker
5877 // export. It is in `do_classes` so that it gets a namespace
5878 // key; reading it off the module namespace would find
5879 // `undefined` and overwrite the harness's registration.
5880 if crate::deploy::is_reserved_class(cn) {
5881 continue;
5882 }
5883 let key = v8::String::new(scope, cn).unwrap();
5884 let cls = ns
5885 .get(scope, key.into())
5886 .ok_or_else(|| anyhow!("DO class {cn} not exported"))?;
5887 register_class(scope, cn, cls)?;
5888 }
5889 inject_namespace_keys(scope, script_name, do_classes)?;
5890 inject_crons(scope, &config.crons)?;
5891 inject_workflows(scope, script_name, &config.workflow_bindings)?;
5892 inject_containers(scope, &config.containers)?;
5893 inject_kv_limits(scope)?;
5894 inject_queue_config(scope, &config)?;
5895 populate_cf_exports(scope, ns, do_classes)?;
5896 register_entrypoints(scope, ns)?;
5897 validate_workflow_classes(scope, ns, &config.workflow_bindings)?;
5898 // build env from bindings and stash it in the harness
5899 build_env(scope, &config)?;
5900 // tell the harness which cells are local (route the rest cross-node)
5901 inject_routing(scope, node)?;
5902
5903 // entry fetch. A loaded Worker often exists for its Durable
5904 // Object class alone, and workerd loads such a module without a
5905 // default export, so one reads as an empty object here. A
5906 // deployment's own script keeps the refusal: a bundle that lost
5907 // its handler must fail adoption, so the serving generation stays
5908 // up instead of answering 500 to every request.
5909 let loaded = config.origin == WorkerOrigin::Dynamic;
5910 let dk = v8::String::new(scope, "default").unwrap();
5911 let default_value = ns
5912 .get(scope, dk.into())
5913 .ok_or_else(|| anyhow!("no default export"))?;
5914 let default = if default_value.is_object() {
5915 default_value.to_object(scope).expect("an object")
5916 } else if loaded && default_value.is_undefined() {
5917 v8::Object::new(scope)
5918 } else {
5919 return Err(anyhow!("default not object"));
5920 };
5921 let fk = v8::String::new(scope, "fetch").unwrap();
5922 let fetch_value = default
5923 .get(scope, fk.into())
5924 .ok_or_else(|| anyhow!("no fetch"))?;
5925 let default_is_entrypoint =
5926 default.is_function() && cell_registry_has(scope, "entrypoints", "default")?;
5927 let class_fetch = default_is_entrypoint
5928 && default
5929 .get(scope, v8::String::new(scope, "prototype").unwrap().into())
5930 .and_then(|prototype| prototype.to_object(scope))
5931 .and_then(|prototype| prototype.get(scope, fk.into()))
5932 .is_some_and(|handler| handler.is_function());
5933 let qk = v8::String::new(scope, "queue").unwrap();
5934 let own_queue = default
5935 .get(scope, qk.into())
5936 .is_some_and(|handler| handler.is_function());
5937 let class_queue = default_is_entrypoint
5938 && default
5939 .get(scope, v8::String::new(scope, "prototype").unwrap().into())
5940 .and_then(|prototype| prototype.to_object(scope))
5941 .and_then(|prototype| prototype.get(scope, qk.into()))
5942 .is_some_and(|handler| handler.is_function());
5943 let has_queue_handler = own_queue || class_queue;
5944 anyhow::ensure!(
5945 !config.declares_queue_consumer || has_queue_handler,
5946 "queue consumer has no queue handler"
5947 );
5948 let f: v8::Local<v8::Function> = if fetch_value.is_function() {
5949 fetch_value.try_into().expect("function casts to Function")
5950 } else if default_is_entrypoint && class_fetch {
5951 // A class-based default entrypoint (extends WorkerEntrypoint)
5952 // keeps fetch on the prototype, so route through the
5953 // harness's invocation instance like a named entrypoint. Only a
5954 // registered entrypoint dispatches that way — any other
5955 // callable would load fine and then 500 on every request.
5956 compile_fn(
5957 scope,
5958 "(req) => __celld.__dispatchEntrypointFetch('default', req)",
5959 )?
5960 } else if default.is_function() && cell_registry_has(scope, "doExports", "default")? {
5961 return Err(anyhow!(
5962 "the default export is a Durable Object class; export a fetch \
5963 handler or a WorkerEntrypoint class as the default"
5964 ));
5965 } else if config.declares_queue_consumer {
5966 // A push-consumer Worker needs no HTTP handler. Keep the
5967 // stateless pool's fetch slot total, but fail closed if this
5968 // deployment becomes the fleet's HTTP entry point. Test the
5969 // prototype above before the entrypoint fallback below: a
5970 // queue-only class is still a registered entrypoint, but
5971 // routing fetch through it throws instead of returning 404.
5972 compile_fn(scope, "() => new Response('Not found', { status: 404 })")?
5973 } else if default_is_entrypoint {
5974 // Preserve an RPC-only default entrypoint. Its HTTP path
5975 // reports the harness's specific missing-fetch error, while
5976 // its named methods remain callable through RPC.
5977 compile_fn(
5978 scope,
5979 "(req) => __celld.__dispatchEntrypointFetch('default', req)",
5980 )?
5981 } else if loaded {
5982 compile_fn(scope, NO_FETCH_HANDLER)?
5983 } else {
5984 return Err(anyhow!("fetch not fn"));
5985 };
5986
5987 // Lets a self-targeted service binding invoke the handler in
5988 // this isolate instead of crossing to a pool thread.
5989 {
5990 if let Ok(cell) = cell_state(scope) {
5991 let key = v8::String::new(scope, "selfFetch").unwrap();
5992 cell.set(scope, key.into(), f.into());
5993 // Optional scheduled handler, reached by a self-targeted
5994 // service binding's scheduled().
5995 let sk = v8::String::new(scope, "scheduled").unwrap();
5996 let key_ = v8::String::new(scope, "selfScheduled").unwrap();
5997 let own = default
5998 .get(scope, sk.into())
5999 .filter(|handler| handler.is_function());
6000 if let Some(handler) = own {
6001 cell.set(scope, key_.into(), handler);
6002 } else if default_is_entrypoint {
6003 // A class-based default entrypoint keeps scheduled on
6004 // the prototype; dispatch through an invocation instance
6005 // like fetch above.
6006 let pk = v8::String::new(scope, "prototype").unwrap();
6007 let proto_scheduled = default
6008 .get(scope, pk.into())
6009 .and_then(|proto| proto.to_object(scope))
6010 .and_then(|proto| proto.get(scope, sk.into()));
6011 if proto_scheduled.is_some_and(|handler| handler.is_function()) {
6012 let shim = compile_fn(
6013 scope,
6014 "(ctrl) => __celld.__dispatchEntrypointScheduled('default', ctrl)",
6015 )?;
6016 cell.set(scope, key_.into(), shim.into());
6017 }
6018 }
6019 }
6020 }
6021 (v8::Global::new(scope, context), v8::Global::new(scope, f))
6022 };
6023 // Module evaluation and harness installation allocate temporary V8
6024 // objects. No request can reuse them after these scopes close, and a
6025 // new cell isolate can otherwise retain their pages indefinitely.
6026 // Observe only post-setup collection, so bootstrap GC cannot make
6027 // a missing settlement notification pass the regression.
6028 #[cfg(all(test, celld_internal_tests))]
6029 install_heap_collection_observer_for_test(&mut isolate);
6030 settle_isolate_heap(&mut isolate);
6031 Ok(Worker {
6032 inner: Some(WorkerIsolate {
6033 // Every setup scope above has closed, so nothing is entered
6034 // on top of this isolate and it can be handed over.
6035 // SAFETY: `into_shared` requires every piece of embedder
6036 // state hanging off this isolate to be `Send`, because it
6037 // migrates between threads and is dropped on whichever one
6038 // holds the lock last. This isolate carries exactly:
6039 //
6040 // - four slots, whose types the assertion below pins as
6041 // `Send + Sync`;
6042 // - `near_heap_limit`, a bare fn pointer whose only captured
6043 // state is a raw pointer into the `HeapLimitState` above;
6044 // - `host_import_module_dynamically`, a bare fn pointer that
6045 // captures nothing;
6046 // - a default `CreateParams` allocator, owned by V8.
6047 //
6048 // Nothing else is attached, and the assertion fails the build
6049 // if a slot type ever stops being thread-safe.
6050 //
6051 // 152.1.0 made this fallible. None of the four refusals can
6052 // hold here — this isolate is entered, is not a snapshot
6053 // creator, has no C++ heap, and has taken no weak handles —
6054 // so a refusal is a bug in the setup above, not a condition
6055 // to recover from. It panics with the reason named.
6056 isolate: unsafe { isolate.try_into_shared() }
6057 .unwrap_or_else(|error| panic!("cell isolate cannot be shared: {error}")),
6058 runtime_state,
6059 realm: Realm { context, fetch },
6060 original_heap_limit,
6061 compat,
6062 loader_owner,
6063 cells: storage::Cells::default(),
6064 }),
6065 })
6066 }
6067
6068 /// Restore an idFromName() actor's human-readable identity before its
6069 /// constructor runs. The host calls this on activation and before a named
6070 /// request is dispatched.
6071 /// Take a cell into this isolate or give it back.
6072 ///
6073 /// Taking it opens the cell's SQLite -- which the isolate owns, not the
6074 /// caller -- and restores the persisted id name. Giving it back releases
6075 /// what the isolate holds for the residency and closes the database, so
6076 /// state cannot span two epochs.
6077 ///
6078 /// Dispatch does not depend on this: every cell call goes out through the
6079 /// host whichever isolate hosts the target.
6080 pub fn own_cell(
6081 &mut self,
6082 cell: &str,
6083 storage: Option<CellStorage<'_>>,
6084 ) -> Result<celld_logic::wake::AlarmSnapshot> {
6085 let compat = self.inner.as_ref().expect("live worker isolate").compat;
6086 let (mut locker, _cells) = self.lock();
6087 v8::scope!(let hs, &mut *locker);
6088 let realm = self.realm(hs);
6089 let context = realm.context;
6090 let cs = &mut v8::ContextScope::new(hs, context);
6091 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6092 let alarm = adopt_cell(&mut tc.init(), cell, storage, compat)?;
6093 // The source identity belongs to this installed SQLite turn. Reading
6094 // it from the pool after this guard drops reaches no cell connection.
6095 Ok(observe_alarm(cell, alarm))
6096 }
6097
6098 /// Collect objects left by cell adoption after an isolate becomes full.
6099 /// The pool calls this when completed adoptions reach the resident limit,
6100 /// because collecting after every adoption slows activation.
6101 pub(crate) fn settle_heap(&mut self) {
6102 let (mut locker, _cells) = self.lock();
6103 settle_isolate_heap(&mut locker);
6104 }
6105
6106 fn own_embedded_cell(
6107 &mut self,
6108 cell: &str,
6109 parent: &storage::StorageIdentity,
6110 name: &str,
6111 id_sc: Vec<u8>,
6112 props_sc: Vec<u8>,
6113 file: (std::path::PathBuf, bool),
6114 ) -> Result<Option<i64>> {
6115 let compat = self.inner.as_ref().expect("live worker isolate").compat;
6116 let (mut locker, _cells) = self.lock();
6117 if storage::activation_epoch(cell).is_some() {
6118 // The facet is already open, but this call carries a newer sample
6119 // of the root cell. Take it: the egress of this call must wait for
6120 // what the root cell had committed when the call left it.
6121 storage::refresh_embedded_root(cell, parent);
6122 return Ok(None);
6123 }
6124 v8::scope!(let hs, &mut *locker);
6125 let realm = self.realm(hs);
6126 let context = realm.context;
6127 let cs = &mut v8::ContextScope::new(hs, context);
6128 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6129 let tc = &mut tc.init();
6130 let (path, restored) = file;
6131 adopt_embedded_cell(
6132 tc,
6133 cell,
6134 parent,
6135 name,
6136 EmbeddedStartup {
6137 id_sc,
6138 props_sc,
6139 path,
6140 restored,
6141 },
6142 compat,
6143 )
6144 }
6145
6146 /// Drain the alarm moves the last turn committed in this isolate.
6147 ///
6148 /// An alarm move is a turn output, exactly like the ops a turn starts:
6149 /// the drive that ran the turn reports it to the host, so a handler
6150 /// that arms an alarm and then awaits it is schedulable immediately,
6151 /// not when the request ends. A separate call rather than part of the
6152 /// turn methods' return because stateless turns cannot move an alarm
6153 /// and never pay for it.
6154 /// Bind the revision under the isolate lock too. A later reporter callback
6155 /// can run after another turn arms the cell; sampling there would combine
6156 /// the old value with the new arm's authority to change its wake entry.
6157 pub fn take_alarm_moves(&mut self) -> Vec<(String, celld_logic::wake::AlarmSnapshot)> {
6158 let Some(inner) = self.inner.as_mut() else {
6159 return Vec::new();
6160 };
6161 let (_locker, _cells) = inner.lock();
6162 storage::take_alarm_moves()
6163 }
6164
6165 pub fn set_id_name(&mut self, scope: &str, name: &str) -> Result<()> {
6166 let (mut locker, _cells) = self.lock();
6167 v8::scope!(let hs, &mut *locker);
6168 let realm = self.realm(hs);
6169 let context = realm.context;
6170 let cs = &mut v8::ContextScope::new(hs, context);
6171 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6172 register_actor_name(&mut tc.init(), scope, Some(name))
6173 }
6174
6175 /// Start a cell event's first turn.
6176 ///
6177 /// The cell counterpart of `turn_begin`: it hands back what is now in
6178 /// flight for `runtime::drive_cell` to pump.
6179 pub fn turn_begin_cell(
6180 &mut self,
6181 job: CellJob,
6182 trace: Option<crate::telemetry::TraceContext>,
6183 ) -> (Option<InFlight>, Vec<Op>) {
6184 let Some(inner) = self.inner.as_mut() else {
6185 return (None, Vec::new());
6186 };
6187 let (mut locker, _cells) = inner.lock();
6188 inner.recover_heap(&mut locker);
6189 v8::scope!(let hs, &mut *locker);
6190 let realm = inner.realm(hs);
6191 let context = realm.context;
6192 let cs = &mut v8::ContextScope::new(hs, context);
6193 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6194 let tc = &mut tc.init();
6195
6196 let event_time = advance_io_time(tc);
6197 let previous = install_trace(tc, trace.as_ref());
6198 let cpu_watchdog = inner.cpu_watchdog(
6199 inner.initial_cpu_budget(),
6200 inner
6201 .runtime_state
6202 .resource_limits
6203 .and_then(|limits| limits.cpu_ms),
6204 );
6205 let begun = begin_cell(tc, job, event_time);
6206 drop(cpu_watchdog);
6207 let out = match begun {
6208 Begun::Running(mut entry) => {
6209 entry.trace = trace;
6210 let previous_io_context = install_io_context(tc, &entry.context);
6211 let ops = finish_turn(tc, &mut entry);
6212 restore_io_context(tc, previous_io_context);
6213 (Some(*entry), ops)
6214 }
6215 Begun::Threw(failure) => {
6216 let BegunFailure {
6217 answer, cpu_error, ..
6218 } = *failure;
6219 answer.fail(
6220 take_execution_termination(tc)
6221 .or_else(|| cpu_error.map(anyhow::Error::msg))
6222 .unwrap_or_else(|| anyhow!("cell event threw: {}", exc!(tc))),
6223 );
6224 (None, Vec::new())
6225 }
6226 Begun::Nothing => (None, Vec::new()),
6227 };
6228 restore_trace(tc, previous);
6229 out
6230 }
6231
6232 /// Enter the isolate solely to see whether another event settled this
6233 /// one's promise.
6234 ///
6235 /// A promise resolved by a different entry has no waker pointing here,
6236 /// so the driving task cannot be told and has to look. That is why this
6237 /// is a poll and not an event, and it is the same reason the blocking
6238 /// loop woke every 10 ms.
6239 pub fn turn_poll(&mut self, entry: &mut InFlight) -> Vec<Op> {
6240 let Some(inner) = self.inner.as_mut() else {
6241 return Vec::new();
6242 };
6243 let (mut locker, _cells) = inner.lock();
6244 v8::scope!(let hs, &mut *locker);
6245 let realm = inner.realm(hs);
6246 let context = realm.context;
6247 let cs = &mut v8::ContextScope::new(hs, context);
6248 let tc = std::pin::pin!(v8::TryCatch::new(cs));
6249 let tc = &mut tc.init();
6250
6251 let previous_io_context = install_io_context(tc, &entry.context);
6252 let previous = install_trace(tc, entry.trace.as_ref());
6253 entry.context.begin_cpu_turn();
6254 let ops = finish_turn(tc, entry);
6255 restore_trace(tc, previous);
6256 restore_io_context(tc, previous_io_context);
6257 ops
6258 }
6259
6260 /// Reject each pending `WorkerEntrypoint` call that has no native work.
6261 /// The rejection runs inside the owning request, so the enclosing handler
6262 /// can catch it and continue exactly as it can in Workerd.
6263 pub(crate) fn turn_cancel_pending_events(&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 cpu_watchdog = inner.cpu_watchdog(
6279 entry.context.remaining_cpu_budget(),
6280 entry.context.cpu_limit_ms(),
6281 );
6282 let ids = entry.context.take_pending_events();
6283 let called = (|| {
6284 let function = internal_function(tc, "__cancelPendingEvents").ok()?;
6285 let values = ids
6286 .iter()
6287 .map(|id| v8::Number::new(tc, *id as f64).into())
6288 .collect::<Vec<v8::Local<v8::Value>>>();
6289 let values = v8::Array::new_with_elements(tc, &values);
6290 let receiver = v8::undefined(tc).into();
6291 function.call(tc, receiver, &[values.into()])
6292 })();
6293 if called.is_none() {
6294 entry.fail_in_turn(anyhow!("pending-event cancellation threw"));
6295 }
6296 drop(cpu_watchdog);
6297 let ops = finish_turn(tc, entry);
6298 restore_trace(tc, previous);
6299 restore_io_context(tc, previous_io_context);
6300 ops
6301 }
6302
6303 /// Enter the isolate solely to record how a claimed alarm ended.
6304 ///
6305 /// Reached only when the event ended without running JS again — a budget
6306 /// overrun, or a handler waiting on nothing — or threw before it could
6307 /// suspend. The bookkeeping is storage the isolate owns, so it cannot be
6308 /// done from the driving task.
6309 ///
6310 /// Answers the position the event's commits reached, sampled after the
6311 /// retry record is written: that record and whatever the handler wrote
6312 /// before it failed are unproven, and the error that already left carried
6313 /// at most the handler's part, so `fire_alarm` gates on this instead.
6314 pub fn turn_finish_alarm(&mut self, entry: &mut InFlight) -> Result<Option<u64>> {
6315 debug_assert!(
6316 self.inner.is_some(),
6317 "the final alarm turn runs on a live worker"
6318 );
6319 let Some(inner) = self.inner.as_mut() else {
6320 return Ok(None);
6321 };
6322 let (_locker, _cells) = inner.lock();
6323 entry.settle_alarm(false, false);
6324 entry.write_delta()
6325 }
6326}
6327
6328// ---- native ops exposed to JS ----
6329
6330/// One host op per entry. The macro names the table and the installer
6331/// together, so the parameter list every internal script is compiled with
6332/// and the functions it is called with come from one source and cannot
6333/// drift apart.
6334///
6335/// The ops are runtime internals and never globals: `for (const k in
6336/// globalThis) new globalThis[k]()` once reached `__actor_abort` and killed
6337/// the actor, and a loaded worker once reached `__do_call` around its
6338/// `globalOutbound: null` (denoland/celld#192).
6339macro_rules! ops {
6340 ($names:ident, $install:ident, $($name:literal => $op:path),* $(,)?) => {
6341 const $names: &[&str] = &[$($name),*];
6342 fn $install<'s>(
6343 scope: &mut v8::PinScope<'s, '_>,
6344 functions: &mut Vec<v8::Local<'s, v8::Function>>,
6345 ) {
6346 $({
6347 // Each expansion defines its own `attributed`, so every op
6348 // keeps a distinct callback. It records which continuation
6349 // enqueued the op, and only when the call enqueued one: the
6350 // count is a thread-local read, while the name costs a CPED
6351 // lookup.
6352 fn attributed<'s>(
6353 scope: &mut v8::PinScope<'s, '_>,
6354 args: v8::FunctionCallbackArguments<'s>,
6355 rv: v8::ReturnValue<'s, v8::Value>,
6356 ) {
6357 #[cfg(celld_internal_tests)]
6358 let mut rv = rv;
6359 #[cfg(celld_internal_tests)]
6360 if call_op_patch(scope, $name, &args, &mut rv) {
6361 return;
6362 }
6363 let before = asyncrt::spawn_count();
6364 $op(scope, args, rv);
6365 if asyncrt::spawn_count() != before {
6366 if let Some(owner) = operation_continuation_id(scope) {
6367 asyncrt::attribute_spawns(before, owner);
6368 }
6369 }
6370 }
6371 functions.push(v8::Function::new(scope, attributed).unwrap());
6372 })*
6373 }
6374 };
6375}
6376
6377/// The parameters every internal script is compiled with: the internals
6378/// object, then one binding per host op in table order. The values are what
6379/// the script is called with, in the same order.
6380///
6381/// Ops reach the harness as parameters and not as globals, so a bundle cannot
6382/// name `__do_call` and address a cell it holds no stub for, and a loaded
6383/// worker with `globalOutbound: null` cannot reach the host at all except
6384/// through the capabilities in its `env`. A parameter is also a binding user
6385/// code cannot replace, which is what the event hooks already required.
6386///
6387/// Parameters rather than `__celld.__op(...)` at every call site: the
6388/// internal scripts name an op in several hundred places, a bare identifier
6389/// keeps each of those lines as it was, and a closure binding costs a
6390/// context-slot load where a property costs a lookup. The same op is also a
6391/// property of `__celld`, read-only, for the host and for the test hatch.
6392pub(super) struct InternalArguments<'s> {
6393 names: Vec<v8::Local<'s, v8::String>>,
6394 values: Vec<v8::Local<'s, v8::Value>>,
6395}
6396
6397fn op_names() -> impl Iterator<Item = &'static str> {
6398 #[cfg(celld_internal_tests)]
6399 let test = TEST_OP_NAMES.iter().copied();
6400 #[cfg(not(celld_internal_tests))]
6401 let test = std::iter::empty();
6402 OP_NAMES.iter().copied().chain(test)
6403}
6404
6405impl<'s> InternalArguments<'s> {
6406 /// `__celld` first, then `ops` in `op_names()` order.
6407 fn new(
6408 scope: &mut v8::PinScope<'s, '_>,
6409 internals: v8::Local<'s, v8::Object>,
6410 ops: impl FnMut(
6411 &mut v8::PinScope<'s, '_>,
6412 v8::Local<'s, v8::String>,
6413 ) -> v8::Local<'s, v8::Value>,
6414 ) -> Self {
6415 let mut ops = ops;
6416 let mut names = vec![v8_strings::key(scope, &v8_strings::INTERNALS)];
6417 let mut values = vec![internals.into()];
6418 for name in op_names() {
6419 let key = v8::String::new(scope, name).unwrap();
6420 values.push(ops(scope, key));
6421 names.push(key);
6422 }
6423 Self { names, values }
6424 }
6425}
6426
6427/// Build the ops, hold them on the internals object, and return them as the
6428/// arguments of the bootstrap scripts. Nothing here touches the global.
6429fn install_ops<'s>(scope: &mut v8::PinScope<'s, '_>) -> InternalArguments<'s> {
6430 let internals = v8::Object::new(scope);
6431 let mut functions = Vec::new();
6432 install_op_functions(scope, &mut functions);
6433 #[cfg(celld_internal_tests)]
6434 install_test_op_functions(scope, &mut functions);
6435 let mut functions = functions.into_iter();
6436 // Read-only: a test that assigns `__celld.__op = fn`, the idiom that
6437 // patching a global once allowed, throws instead of binding a script that
6438 // compiles later to a function the bootstrap harness never saw.
6439 let arguments = InternalArguments::new(scope, internals, |scope, key| {
6440 let function = functions.next().expect("one function per op name");
6441 internals.define_own_property(
6442 scope,
6443 key.into(),
6444 function.into(),
6445 v8::PropertyAttribute::READ_ONLY | v8::PropertyAttribute::DONT_DELETE,
6446 );
6447 function.into()
6448 });
6449 actor_runtime_state(scope)
6450 .internals
6451 .set(v8::Global::new(scope, internals))
6452 .unwrap_or_else(|_| panic!("internals were already installed"));
6453 // A test build exposes the internals object, so an engine test can reach
6454 // ops and harness state by name and patch an op through
6455 // `__test_patch_op`. A shipping isolate has no `__`-prefixed global.
6456 #[cfg(celld_internal_tests)]
6457 {
6458 let global = scope.get_current_context().global(scope);
6459 let key = v8_strings::key(scope, &v8_strings::INTERNALS);
6460 global.define_own_property(
6461 scope,
6462 key.into(),
6463 internals.into(),
6464 v8::PropertyAttribute::DONT_ENUM,
6465 );
6466 }
6467 arguments
6468}
6469
6470/// The same arguments, rebuilt from the internals object for a script that
6471/// compiles after bootstrap: a lazy global or a lazy builtin module.
6472pub(super) fn internal_arguments<'s>(scope: &mut v8::PinScope<'s, '_>) -> InternalArguments<'s> {
6473 let internals = internals(scope);
6474 InternalArguments::new(scope, internals, |scope, key| {
6475 internals.get(scope, key.into()).unwrap()
6476 })
6477}
6478
6479/// The internals object of this isolate: every host op and every harness
6480/// function the host calls, reachable from Rust and from internal scripts
6481/// but from no user code.
6482pub(super) fn internals<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::Object> {
6483 let state = actor_runtime_state(scope);
6484 let internals = state
6485 .internals
6486 .get()
6487 .expect("internals are installed before any script runs");
6488 v8::Local::new(scope, internals)
6489}
6490
6491pub(super) fn internal_value<'s>(
6492 scope: &mut v8::PinScope<'s, '_>,
6493 name: &str,
6494) -> Option<v8::Local<'s, v8::Value>> {
6495 let internals = internals(scope);
6496 let key = v8::String::new(scope, name).unwrap();
6497 internals
6498 .get(scope, key.into())
6499 .filter(|value| !value.is_undefined())
6500}
6501
6502pub(super) fn internal_function<'s>(
6503 scope: &mut v8::PinScope<'s, '_>,
6504 name: &str,
6505) -> Result<v8::Local<'s, v8::Function>> {
6506 internal_value(scope, name)
6507 .ok_or_else(|| anyhow!("no {name}"))?
6508 .try_into()
6509 .map_err(|_| anyhow!("{name} is not a function"))
6510}
6511
6512pub(super) fn internal_object<'s>(
6513 scope: &mut v8::PinScope<'s, '_>,
6514 name: &str,
6515) -> Result<v8::Local<'s, v8::Object>> {
6516 internal_value(scope, name)
6517 .and_then(|value| value.to_object(scope))
6518 .ok_or_else(|| anyhow!("missing {name} runtime state"))
6519}
6520
6521/// `__cell`, the harness's runtime-state object.
6522pub(super) fn cell_state<'s>(
6523 scope: &mut v8::PinScope<'s, '_>,
6524) -> Result<v8::Local<'s, v8::Object>> {
6525 let internals = internals(scope);
6526 let key = v8_strings::key(scope, &v8_strings::CELL);
6527 internals
6528 .get(scope, key.into())
6529 .and_then(|value| value.to_object(scope))
6530 .ok_or_else(|| anyhow!("missing __cell runtime state"))
6531}
6532
6533/// Run a small host-generated snippet with `__celld` bound. The snippet
6534/// differs per load, so it is compiled without the bootstrap cache.
6535pub(super) fn run_internal_snippet<'s>(
6536 scope: &mut v8::PinScope<'s, '_>,
6537 source: &str,
6538) -> Option<v8::Local<'s, v8::Value>> {
6539 let code = v8::String::new(scope, source)?;
6540 let arguments = InternalArguments {
6541 names: vec![v8_strings::key(scope, &v8_strings::INTERNALS)],
6542 values: vec![internals(scope).into()],
6543 };
6544 bootstrap::run_internal_script(scope, None, code, &arguments).ok()
6545}
6546
6547/// `__test_patch_op(name, fn | null)`: route the named op through `fn` for
6548/// the rest of the isolate's life, or restore it. The patch receives the op's
6549/// arguments and `this`; an op it calls itself runs the real op, so a patch
6550/// can observe or clamp arguments and then forward them.
6551///
6552/// The forward must happen before the patch returns. The re-entrancy guard
6553/// is held for that synchronous extent only, so a forward after an `await`
6554/// meets the patch again and recurses.
6555#[cfg(celld_internal_tests)]
6556fn op_test_patch_op(
6557 scope: &mut v8::PinScope,
6558 args: v8::FunctionCallbackArguments,
6559 _rv: v8::ReturnValue<v8::Value>,
6560) {
6561 let requested = args.get(0).to_rust_string_lossy(scope);
6562 let Some(name) = op_names()
6563 .filter(|name| *name != "__test_patch_op")
6564 .find(|name| *name == requested)
6565 else {
6566 return loader_throw(
6567 scope,
6568 &format!("__test_patch_op: {requested} is not a patchable op"),
6569 );
6570 };
6571 let state = actor_runtime_state(scope);
6572 let mut patches = state.op_patches.lock().unwrap();
6573 match v8::Local::<v8::Function>::try_from(args.get(1)) {
6574 Ok(patch) => {
6575 state.op_patched.store(true, Ordering::Relaxed);
6576 patches.insert(name, v8::Global::new(scope, patch));
6577 }
6578 Err(_) => {
6579 patches.remove(name);
6580 }
6581 }
6582}
6583
6584#[cfg(celld_internal_tests)]
6585fn call_op_patch(
6586 scope: &mut v8::PinScope,
6587 name: &'static str,
6588 args: &v8::FunctionCallbackArguments,
6589 rv: &mut v8::ReturnValue<v8::Value>,
6590) -> bool {
6591 let state = actor_runtime_state(scope);
6592 if !state.op_patched.load(Ordering::Relaxed) {
6593 return false;
6594 }
6595 let patch = state
6596 .op_patches
6597 .lock()
6598 .unwrap()
6599 .get(name)
6600 .map(|patch| v8::Local::new(scope, patch));
6601 let Some(patch) = patch else {
6602 return false;
6603 };
6604 // Re-entered from inside the patch: this call is the forward to the real
6605 // op.
6606 if !state.op_patches_active.lock().unwrap().insert(name) {
6607 return false;
6608 }
6609 let values: Vec<v8::Local<v8::Value>> = (0..args.length()).map(|i| args.get(i)).collect();
6610 let result = patch.call(scope, args.this().into(), &values);
6611 state.op_patches_active.lock().unwrap().remove(name);
6612 if let Some(result) = result {
6613 rv.set(result);
6614 }
6615 true
6616}
6617
6618ops! { OP_NAMES, install_op_functions,
6619 "__heap_limit_excessively_exceeded" =>
6620 op_heap_limit_excessively_exceeded,
6621 "__heap_over_admission_share" => op_heap_over_admission_share,
6622 "__ws_send" => websocket::op_ws_send,
6623 "__ws_send_binary" => websocket::op_ws_send_binary,
6624 "__ws_close" => websocket::op_ws_close,
6625 "__ws_alloc" => websocket::op_ws_alloc,
6626 "__ws_prepare_worker_handoff" => websocket::op_ws_prepare_worker_handoff,
6627 "__ws_accept" => websocket::op_ws_accept,
6628 "__ws_accept_regular" => websocket::op_ws_accept_regular,
6629 "__ws_list" => websocket::op_ws_list,
6630 "__ws_attachment_set" => websocket::op_ws_attachment_set,
6631 "__ws_auto_response_set" => websocket::op_ws_auto_response_set,
6632 "__ws_auto_response_get" => websocket::op_ws_auto_response_get,
6633 "__ws_auto_response_ts" => websocket::op_ws_auto_response_ts,
6634 "__ws_connect" => websocket::op_ws_connect,
6635 "__ws_bind_target" => websocket::op_ws_bind_target,
6636 "__ws_next" => websocket::op_ws_next,
6637 "__ws_upgrade" => websocket::op_ws_upgrade,
6638 "__hr_create" => html_rewriter::op_hr_create,
6639 "__hr_write" => html_rewriter::op_hr_write,
6640 "__hr_end" => html_rewriter::op_hr_end,
6641 "__hr_cmd" => html_rewriter::op_hr_cmd,
6642 "__hr_event" => html_rewriter::op_hr_event,
6643 "__hr_take" => html_rewriter::op_hr_take,
6644 "__hr_free" => html_rewriter::op_hr_free,
6645 "__tcp_connect" => tcp::op_tcp_connect,
6646 "__tcp_read" => tcp::op_tcp_read,
6647 "__tcp_write" => tcp::op_tcp_write,
6648 "__tcp_shutdown" => tcp::op_tcp_shutdown,
6649 "__tcp_close" => tcp::op_tcp_close,
6650 "__tcp_starttls" => tcp::op_tcp_starttls,
6651 "__container_running" => container::op_container_running,
6652 "__container_address" => container::op_container_address,
6653 "__container_start" => container::op_container_start,
6654 "__container_monitor" => container::op_container_monitor,
6655 "__container_destroy" => container::op_container_destroy,
6656 "__container_signal" => container::op_container_signal,
6657 "__container_inactivity" => container::op_container_inactivity,
6658 "__container_exec" => container::op_container_exec,
6659 "__container_exec_read" => container::op_container_exec_read,
6660 "__container_exec_write" => container::op_container_exec_write,
6661 "__container_exec_close" => container::op_container_exec_close,
6662 "__container_exec_wait" => container::op_container_exec_wait,
6663 "__container_exec_kill" => container::op_container_exec_kill,
6664 "__container_exec_drop" => container::op_container_exec_drop,
6665 "__storage_get" => storage_ops::op_storage_get,
6666 "__storage_get_many" => storage_ops::op_storage_get_many,
6667 "__sql_ingest" => storage_ops::op_sql_ingest,
6668 "__sql_cursor_start" => storage_ops::op_sql_cursor_start,
6669 "__sql_cursor_next" => storage_ops::op_sql_cursor_next,
6670 "__sql_cursor_close" => storage_ops::op_sql_cursor_close,
6671 "__sql_database_size" => storage_ops::op_sql_database_size,
6672 "__d1_run" => storage_ops::op_d1_run,
6673 "__storage_transaction_control" => storage_ops::op_storage_transaction_control,
6674 "__log" => op_log,
6675 "__storage_put" => storage_ops::op_storage_put,
6676 "__storage_put_many" => storage_ops::op_storage_put_many,
6677 "__storage_queue_put" => storage_ops::op_storage_queue_put,
6678 "__storage_queue_put_many" => storage_ops::op_storage_queue_put_many,
6679 "__storage_put_serialized" => storage_ops::op_storage_put_serialized,
6680 "__storage_queue_put_serialized" => storage_ops::op_storage_queue_put_serialized,
6681 "__storage_flush_pending_puts" => storage_ops::op_storage_flush_pending_puts,
6682 "__storage_sync" => storage_ops::op_storage_sync,
6683 "__storage_cancel_pending_puts" => storage_ops::op_storage_cancel_pending_puts,
6684 "__actor_abort" => op_actor_abort,
6685 "__cron_plan" => op_cron_plan,
6686 "__kv_blob" => op_kv_blob,
6687 "__process_exit" => op_process_exit,
6688 "__storage_delete" => storage_ops::op_storage_delete,
6689 "__storage_delete_many" => storage_ops::op_storage_delete_many,
6690 "__storage_list" => storage_ops::op_storage_list,
6691 "__storage_sync_list_start" => storage_ops::op_storage_sync_list_start,
6692 "__storage_sync_list_next" => storage_ops::op_storage_sync_list_next,
6693 "__storage_delete_all" => storage_ops::op_storage_delete_all,
6694 "$$urlParse" => op_url_parse,
6695 "$$urlPatternParse" => op_urlpattern_parse,
6696 "$$urlPatternMatchInput" => op_urlpattern_match_input,
6697 "$$atob" => op_atob,
6698 "$$btoa" => op_btoa,
6699 "$$textDecoderLabel" => op_text_decoder_label,
6700 "$$textDecoderNew" => op_text_decoder_new,
6701 "$$textDecoderDecode" => op_text_decoder_decode,
6702 "$$textDecoderDecodeOnce" => op_text_decoder_decode_once,
6703 "$$textDecoderFree" => op_text_decoder_free,
6704 "__alarm_set" => op_alarm_set,
6705 "__queue_alarm_set_wait" => op_queue_alarm_set_wait,
6706 "__alarm_get" => op_alarm_get,
6707 "__alarm_delete" => op_alarm_delete,
6708 "__loader_load" => op_loader_load,
6709 "__loader_fetch" => op_loader_fetch,
6710 "__loader_rpc" => op_loader_rpc,
6711 "__loader_drop" => op_loader_drop,
6712 "__facet_fetch" => op_facet_fetch,
6713 "__facet_rpc" => op_facet_rpc,
6714 "__facet_abort" => op_facet_abort,
6715 "__facet_delete" => op_facet_delete,
6716 "__do_call" => op_do_call,
6717 "__svc_call" => op_svc_call,
6718 "__svc_call_cancellable" => op_svc_call_cancellable,
6719 "__svc_rpc" => op_svc_rpc,
6720 "__queue_dispatch" => op_queue_dispatch,
6721 "__queue_policy" => op_queue_policy,
6722 "__do_call_cancellable" => op_do_call_cancellable,
6723 "__do_call_cancel" => op_do_call_cancel,
6724 "__rpc_signal_new" => op_rpc_signal_new,
6725 "__rpc_signal_abort" => op_rpc_signal_abort,
6726 "__rpc_signal_release" => op_rpc_signal_release,
6727 "__rpc_signal_poll" => op_rpc_signal_poll,
6728 "__rpc_signal_wait" => op_rpc_signal_wait,
6729 "__rpc_signal_unsubscribe" => op_rpc_signal_unsubscribe,
6730 "__do_id" => op_do_id,
6731 "__rpc_call" => op_rpc_call,
6732 "__sc_encode" => storage_ops::op_sc_encode,
6733 "__sc_decode" => storage_ops::op_sc_decode,
6734 "__structured_clone" => storage_ops::op_structured_clone,
6735 "__op_fetch" => op_fetch,
6736 "__r2_head" => r2_ops::op_r2_head,
6737 "__r2_get" => r2_ops::op_r2_get,
6738 "__r2_put" => r2_ops::op_r2_put,
6739 "__r2_put_begin" => r2_ops::op_r2_put_begin,
6740 "__r2_put_chunk" => r2_ops::op_r2_put_chunk,
6741 "__r2_put_end" => r2_ops::op_r2_put_end,
6742 "__r2_delete" => r2_ops::op_r2_delete,
6743 "__r2_list" => r2_ops::op_r2_list,
6744 "__r2_mp_begin" => r2_ops::op_r2_mp_begin,
6745 "__r2_mp_resume" => r2_ops::op_r2_mp_resume,
6746 "__r2_mp_part" => r2_ops::op_r2_mp_part,
6747 "__r2_mp_complete" => r2_ops::op_r2_mp_complete,
6748 "__r2_mp_abort" => r2_ops::op_r2_mp_abort,
6749 "__asset_fetch" => op_asset_fetch,
6750 "__http_stream_read" => op_http_stream_read,
6751 "__http_stream_cancel" => op_http_stream_cancel,
6752 "__http_stream_tee" => op_http_stream_tee,
6753 "__response_stream_create" => op_response_stream_create,
6754 "__response_stream_write" => op_response_stream_write,
6755 "__response_stream_closed" => op_response_stream_closed,
6756 "__response_stream_close" => op_response_stream_close,
6757 "__op_timer" => op_timer,
6758 "__isolate_condemn" => op_isolate_condemn,
6759 "__timer_alloc" => op_timer_alloc,
6760 "__io_context_id" => op_io_context_id,
6761 "__with_input_gate_context" => op_with_input_gate_context,
6762 "__gate_acquire" => op_gate_acquire,
6763 "__gate_wait" => op_gate_wait,
6764 "__gate_release" => op_gate_release,
6765 "__timer_cancel" => op_timer_cancel,
6766 "__crypto_operation" => crypto::op_crypto_operation,
6767 "$$randomValues" => crypto::op_webcrypto_random,
6768 "$$digest" => crypto::op_webcrypto_digest,
6769 "$$hmacSign" => crypto::op_webcrypto_hmac_sign,
6770 "$$hmacVerify" => crypto::op_webcrypto_hmac_verify,
6771 "$$aesEncrypt" => crypto::op_webcrypto_aes_encrypt,
6772 "$$aesDecrypt" => crypto::op_webcrypto_aes_decrypt,
6773 "$$pbkdf2" => crypto::op_node_pbkdf2,
6774 "$$hkdf" => crypto::op_node_hkdf,
6775 "$$timingSafeEqual" => crypto::op_timing_safe_equal,
6776 "__event_begin" => op_event_begin,
6777 "__event_end" => op_event_end,
6778 "__pending_event_begin" => op_pending_event_begin,
6779 "__pending_event_end" => op_pending_event_end,
6780 "__vfs_mkdir" => op_vfs_mkdir,
6781 "__vfs_read_file" => op_vfs_read_file,
6782 "__vfs_stat" => op_vfs_stat,
6783 "__wait_until" => op_wait_until,
6784 "__wait_until_active" => op_wait_until_active,
6785 "__event_depth" => op_event_depth,
6786 "__als_get" => op_als_get,
6787 "__als_set" => op_als_set,
6788 "__util_type_flags" => op_util_type_flags,
6789 "__util_constructor_name" => op_util_constructor_name,
6790 "__util_proxy_details" => op_util_proxy_details,
6791 "__util_promise_details" => op_util_promise_details,
6792 "__util_preview_entries" => op_util_preview_entries,
6793 "__builtin_module" => op_builtin_module,
6794 "__zlib" => zlib::op_zlib,
6795 "__zlib_stream_new" => zlib::op_zlib_stream_new,
6796 "__zlib_stream_push" => zlib::op_zlib_stream_push,
6797 "__zlib_stream_end" => zlib::op_zlib_stream_end,
6798 "__zlib_stream_drop" => zlib::op_zlib_stream_drop,
6799}
6800
6801#[cfg(celld_internal_tests)]
6802ops! { TEST_OP_NAMES, install_test_op_functions,
6803 "__test_patch_op" => op_test_patch_op,
6804 "__test_gc" => op_test_gc,
6805 "__loader_count" => op_loader_count,
6806 "__test_set_heap_limit_excessively_exceeded" =>
6807 op_test_set_heap_limit_excessively_exceeded,
6808 "__test_force_heap_admission_refusal" =>
6809 op_test_force_heap_admission_refusal,
6810 "__test_heap_share" => op_test_heap_share,
6811 "__test_external_memory" => op_test_external_memory,
6812 "__test_workflow_event_consumed" => op_test_workflow_event_consumed,
6813 "__test_workflow_meta_created" => op_test_workflow_meta_created,
6814 "__test_workflow_terminal_alarm_set" => op_test_workflow_terminal_alarm_set,
6815 "__test_queue_dlq_accepted" => op_test_queue_dlq_accepted,
6816 "__test_queue_metrics_materialized" => op_test_queue_metrics_materialized,
6817 "__test_queue_producer_group" => op_test_queue_producer_group,
6818 "__test_queue_rearm_bounded" => op_test_queue_rearm_bounded,
6819 "__test_queue_lease_lookup_plan" => op_test_queue_lease_lookup_plan,
6820 "__test_kv_list_plan" => op_test_kv_list_plan,
6821 "__sql_set_max_page_count_for_test" =>
6822 storage_ops::op_sql_set_max_page_count_for_test,
6823 "__sql_set_write_fault_for_test" => storage_ops::op_sql_set_write_fault_for_test,
6824 "__sql_set_cache_size_for_test" => storage_ops::op_sql_set_cache_size_for_test,
6825 "__sql_set_interrupt_fault_for_test" =>
6826 storage_ops::op_sql_set_interrupt_fault_for_test,
6827 "__sql_register_nomem_function_for_test" =>
6828 storage_ops::op_sql_register_nomem_function_for_test,
6829}
6830
6831/// `__kv_blob(requestJson, bytes?)` -> Promise<string | Uint8Array>.
6832///
6833/// One op for the whole large-value path, following `__d1_run` rather than
6834/// exposing get, put and sweep as three. A put copies one typed view into Rust,
6835/// and a successful get resolves directly to a `Uint8Array`. JSON arrays would
6836/// turn a valid 25 MiB value into millions of heap objects and crash the
6837/// isolate before the bucket I/O began.
6838///
6839/// JSON remains the control envelope for an absent get and a swept count. The
6840/// cell scope is host-derived, so JavaScript cannot read or collect another
6841/// namespace's objects by changing the request.
6842fn op_kv_blob(
6843 scope: &mut v8::PinScope,
6844 args: v8::FunctionCallbackArguments,
6845 mut rv: v8::ReturnValue<v8::Value>,
6846) {
6847 let request = args.get(0).to_rust_string_lossy(scope);
6848 let value = view_bytes(args.get(1));
6849 // Bucket I/O is egress, so it waits on the same gate a service call does
6850 // rather than escaping the shed the node applies under pressure.
6851 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
6852 // Blob authority follows the storage installed for this exact cell
6853 // activation. Capturing it before enqueue prevents a later ownership
6854 // lookup from lending a deposed collector the new owner's epoch.
6855 let authority = gate
6856 .cell_scope()
6857 .and_then(|cell| storage::activation_epoch(cell).map(|epoch| (cell.to_string(), epoch)));
6858 let id = asyncrt::enqueue(async move {
6859 let (cell, activation_epoch) =
6860 authority.ok_or_else(|| "KV blob I/O requires active cell storage".to_string())?;
6861 await_egress_gate(gate).await?;
6862 match crate::kv_blob::run(&cell, activation_epoch, &request, value).await? {
6863 crate::kv_blob::BlobReply::Bytes(bytes) => Ok(asyncrt::OpOut::Bytes(bytes)),
6864 crate::kv_blob::BlobReply::Json(reply) => Ok(asyncrt::OpOut::Str(reply.to_string())),
6865 }
6866 });
6867 rv.set(promise_for(scope, id));
6868}
6869
6870/// Create a JS promise for an async op `id` and return it to JS.
6871fn promise_for<'s>(scope: &mut v8::PinScope<'s, '_>, id: u64) -> v8::Local<'s, v8::Value> {
6872 let resolver = v8::PromiseResolver::new(scope).unwrap();
6873 let promise = resolver.get_promise(scope);
6874 promise_store(scope, id, v8::Global::new(scope, resolver));
6875 promise.into()
6876}
6877
6878fn rejected_promise<'s>(
6879 scope: &mut v8::PinScope<'s, '_>,
6880 message: &str,
6881) -> v8::Local<'s, v8::Value> {
6882 let resolver = v8::PromiseResolver::new(scope).unwrap();
6883 let promise = resolver.get_promise(scope);
6884 let message = v8::String::new(scope, message).unwrap();
6885 let exception = v8::Exception::error(scope, message);
6886 resolver.reject(scope, exception);
6887 promise.into()
6888}
6889
6890fn op_queue_dispatch(
6891 scope: &mut v8::PinScope,
6892 args: v8::FunctionCallbackArguments,
6893 mut rv: v8::ReturnValue<v8::Value>,
6894) {
6895 let script = args.get(0).to_rust_string_lossy(scope);
6896 let queue = args.get(1).to_rust_string_lossy(scope);
6897 let envelope = args.get(2).to_rust_string_lossy(scope);
6898 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Queue);
6899 let cell = gate.cell_scope().map(str::to_string).unwrap_or_default();
6900 let request = match crate::queue_policy::dispatch_request(
6901 current_generation(scope),
6902 cell,
6903 script,
6904 queue,
6905 &envelope,
6906 ) {
6907 Ok(request) => request,
6908 Err(error) => return loader_throw(scope, &format!("{error:#}")),
6909 };
6910 let id = asyncrt::enqueue(async move {
6911 if request.scope.is_empty() {
6912 return Err("Queue dispatch requires a cell event".to_string());
6913 }
6914 gated_channel_send(
6915 gate,
6916 &QUEUE_DISPATCH_TX,
6917 request,
6918 "no Queue dispatch channel",
6919 )
6920 .await?;
6921 Ok(asyncrt::OpOut::Str(String::new()))
6922 });
6923 rv.set(promise_for(scope, id));
6924}
6925
6926/// The Queue policy boundary, `crate::queue_policy::run` behind one
6927/// synchronous op.
6928fn op_queue_policy(
6929 scope: &mut v8::PinScope,
6930 args: v8::FunctionCallbackArguments,
6931 mut rv: v8::ReturnValue<v8::Value>,
6932) {
6933 let request: serde_json::Value =
6934 match serde_json::from_str(&args.get(0).to_rust_string_lossy(scope)) {
6935 Ok(request) => request,
6936 Err(error) => {
6937 return loader_throw(scope, &format!("invalid Queue policy input: {error}"))
6938 }
6939 };
6940 #[cfg(celld_internal_tests)]
6941 if request.get("op").and_then(serde_json::Value::as_str) == Some("settlement") {
6942 QUEUE_SETTLEMENT_POLICY_OBSERVED.with(|observed| observed.set(true));
6943 }
6944 match crate::queue_policy::run(&request) {
6945 Ok(value) => {
6946 let value = v8::String::new(scope, &value.to_string()).unwrap();
6947 rv.set(value.into());
6948 }
6949 Err(error) => loader_throw(scope, &error.to_string()),
6950 }
6951}
6952
6953/// Async cross-node dispatch: hand the fetch to the tokio proxy task and await
6954/// its reply off-thread — the JS thread is never blocked. Resolves to a JSON
6955/// `{status, body, headers}` string the harness turns back into a Response.
6956/// `__svc_rpc(script, entrypoint, pathJson, argsSc, propsSc)` ->
6957/// Promise<Uint8Array>; arguments, props, and the result are structured-clone
6958/// bytes.
6959/// The application generation the calling isolate was built for, from the
6960/// slot `load_config` installs. Zero for an isolate built outside any
6961/// generation, which the runtime resolves as the current one.
6962fn current_generation(scope: &mut v8::PinScope) -> crate::generation::GenerationId {
6963 scope
6964 .get_slot::<crate::generation::GenerationTag>()
6965 .map(|tag| tag.0)
6966 .unwrap_or(0)
6967}
6968
6969fn op_svc_rpc(
6970 scope: &mut v8::PinScope,
6971 args: v8::FunctionCallbackArguments,
6972 mut rv: v8::ReturnValue<v8::Value>,
6973) {
6974 let context = event_context(scope);
6975 if let Err(error) = context.charge_subrequest() {
6976 return loader_throw(scope, &error);
6977 }
6978 let script = args.get(0).to_rust_string_lossy(scope);
6979 let entrypoint = args.get(1).to_rust_string_lossy(scope);
6980 let path = match serde_json::from_str(&args.get(2).to_rust_string_lossy(scope)) {
6981 Ok(path) => path,
6982 Err(error) => return loader_throw(scope, &format!("service RPC path is invalid: {error}")),
6983 };
6984 let call_args = args.get(3);
6985 let operation = if call_args.is_null() {
6986 crate::WorkerRpcOperation::Get { path }
6987 } else {
6988 crate::WorkerRpcOperation::Call {
6989 path,
6990 args: view_bytes(call_args).unwrap_or_default(),
6991 }
6992 };
6993 let props = view_bytes(args.get(4)).unwrap_or_default();
6994 let (tx, rx) = tokio::sync::oneshot::channel();
6995 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
6996 let request = SvcRpcReq {
6997 generation: current_generation(scope),
6998 script,
6999 entrypoint,
7000 props,
7001 operation,
7002 reply: tx,
7003 };
7004 let id = asyncrt::enqueue(async move {
7005 gated_channel_send(gate, &SVC_RPC_TX, request, "no service binding channel").await?;
7006 match rx.await {
7007 Ok(Ok(result)) => Ok(result),
7008 Ok(Err(error)) => Err(format!("{error}")),
7009 Err(error) => Err(format!("service dropped: {error}")),
7010 }
7011 });
7012 rv.set(promise_for(scope, id));
7013}
7014
7015/// `__svc_call(script, url, method, body, headersJson, streamId, entrypoint,
7016/// propsSc)` -> Promise<json>.
7017/// The service-binding equivalent of `__do_call`: no scope to resolve and no
7018/// cancellation token, just a handoff to the target script's pool.
7019fn op_svc_call(
7020 scope: &mut v8::PinScope,
7021 args: v8::FunctionCallbackArguments,
7022 mut rv: v8::ReturnValue<v8::Value>,
7023) {
7024 op_svc_call_impl(scope, args, &mut rv, false);
7025}
7026
7027fn op_svc_call_cancellable(
7028 scope: &mut v8::PinScope,
7029 args: v8::FunctionCallbackArguments,
7030 mut rv: v8::ReturnValue<v8::Value>,
7031) {
7032 op_svc_call_impl(scope, args, &mut rv, true);
7033}
7034
7035fn op_svc_call_impl(
7036 scope: &mut v8::PinScope,
7037 args: v8::FunctionCallbackArguments,
7038 rv: &mut v8::ReturnValue<v8::Value>,
7039 cancellable: bool,
7040) {
7041 if let Err(error) = event_context(scope).charge_subrequest() {
7042 return loader_throw(scope, &error);
7043 }
7044 let script = args.get(0).to_rust_string_lossy(scope);
7045 let url = args.get(1).to_rust_string_lossy(scope);
7046 let method = args.get(2).to_rust_string_lossy(scope);
7047 let stream_arg = args.get(5);
7048 let entrypoint_arg = args.get(6);
7049 let props = view_bytes(args.get(7)).unwrap_or_default();
7050 let entrypoint = entrypoint_arg
7051 .is_string()
7052 .then(|| crate::WorkerFetchEntrypoint {
7053 name: entrypoint_arg.to_rust_string_lossy(scope),
7054 props,
7055 });
7056 let body = if stream_arg.is_number() {
7057 RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64)
7058 } else {
7059 let Some(bytes) = view_bytes(args.get(3)) else {
7060 return loader_throw(
7061 scope,
7062 "service binding: the request body is not a typed array",
7063 );
7064 };
7065 RequestBody::Bytes(bytes.into())
7066 };
7067 let headers: Vec<(String, String)> =
7068 match serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)) {
7069 Ok(headers) => headers,
7070 Err(error) => {
7071 return loader_throw(
7072 scope,
7073 &format!(
7074 "service binding: the request headers are not a name/value list: {error}"
7075 ),
7076 )
7077 }
7078 };
7079 let body_guard = match body.stream_id() {
7080 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
7081 Some(guard) => guard,
7082 None => return loader_throw(scope, "service binding: the body stream is not owned"),
7083 },
7084 None => RequestBodyGuard::of(&body),
7085 };
7086 let (tx, rx) = tokio::sync::oneshot::channel();
7087 // Shares the Durable Object cancel registry and the id encoding
7088 // `attach_cancel_id` writes, so `__do_call_cancel` works unchanged for a
7089 // service call. Only a cancellable call registers: a caller with no
7090 // AbortSignal has nothing that can cancel it, and the router already ends
7091 // the call when the reply sender drops.
7092 let (request_id, cancel, cancel_guard) = if cancellable {
7093 let request_id = next_do_request_id();
7094 let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
7095 do_call_cancels()
7096 .lock()
7097 .unwrap()
7098 .insert(request_id, cancel_sender);
7099 (
7100 Some(request_id),
7101 Some(cancel_receiver),
7102 Some(DoCallCancelGuard::new(request_id)),
7103 )
7104 } else {
7105 (None, None, None)
7106 };
7107 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
7108 let request = SvcCallReq {
7109 cancel,
7110 generation: current_generation(scope),
7111 script,
7112 entrypoint,
7113 url,
7114 method,
7115 body,
7116 body_guard,
7117 headers,
7118 reply: tx,
7119 };
7120 let stream_service = http_stream_service();
7121 let id = asyncrt::enqueue(async move {
7122 let mut cancel_guard = cancel_guard;
7123 gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?;
7124 let result = match rx.await {
7125 Ok(Ok(response)) => encode_http_response(response, true, &stream_service),
7126 Ok(Err(error)) => Err(format!("{error}")),
7127 Err(error) => Err(format!("service dropped: {error}")),
7128 };
7129 if let Some(cancel_guard) = cancel_guard.as_mut() {
7130 cancel_guard.disarm();
7131 }
7132 result
7133 });
7134 let promise = promise_for(scope, id);
7135 if let Some(request_id) = request_id {
7136 attach_cancel_id(scope, promise, request_id);
7137 }
7138 rv.set(promise);
7139}
7140
7141// --- Worker Loader: dynamic isolates for Code Mode ---
7142// A running Worker creates a fresh isolate from code it supplies at runtime
7143// and invokes it. The loaded isolate uses the same turn driver as every
7144// stateless Worker, so an awaited operation holds no thread or isolate.
7145
7146// Default to workerd's module-byte ceiling. A fleet operator may admit larger
7147// compiled runtimes; loaded guest code cannot change this host policy.
7148const DEFAULT_MAX_DYNAMIC_WORKER_CODE_SIZE: usize = 64 * 1024 * 1024;
7149const MAX_DYNAMIC_WORKER_ENV_SIZE: usize = 1024 * 1024;
7150
7151fn dynamic_worker_code_limit() -> usize {
7152 static LIMIT: OnceLock<usize> = OnceLock::new();
7153 *LIMIT.get_or_init(|| {
7154 crate::env_vars::positive_or(
7155 "CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES",
7156 DEFAULT_MAX_DYNAMIC_WORKER_CODE_SIZE,
7157 )
7158 .expect("validated CELLD_MAX_DYNAMIC_WORKER_CODE_BYTES")
7159 })
7160}
7161
7162/// The largest `props` value one loaded entrypoint or Durable Object class can
7163/// carry, as structured-clone bytes. Workerd does not impose this bound, but
7164/// celld holds the value on a host job for the whole call. The harness shares
7165/// the caller's isolate and cannot prevent that unbounded host allocation, so
7166/// every op that accepts call props must enforce the limit.
7167const MAX_DYNAMIC_WORKER_PROPS_SIZE: usize = 1024 * 1024;
7168
7169fn loader_props_bytes(value: v8::Local<v8::Value>) -> Result<Vec<u8>, String> {
7170 // RPC and facet calls use undefined for absent props. A different
7171 // non-typed value is a malformed transport argument, not empty props.
7172 let props = if value.is_undefined() {
7173 Vec::new()
7174 } else {
7175 view_bytes(value)
7176 .ok_or_else(|| "worker loader: the props are not a typed array".to_string())?
7177 };
7178 if props.len() > MAX_DYNAMIC_WORKER_PROPS_SIZE {
7179 return Err(format!(
7180 "Dynamic Worker props size ({} bytes) exceeds the maximum \
7181 allowed size of {MAX_DYNAMIC_WORKER_PROPS_SIZE} bytes.",
7182 props.len()
7183 ));
7184 }
7185 Ok(props)
7186}
7187
7188#[derive(Clone)]
7189enum LoaderState {
7190 Loading,
7191 Ready(Arc<crate::pool::Slot>),
7192 Failed(Arc<str>),
7193}
7194
7195#[derive(Clone, Eq, PartialEq)]
7196struct LoaderPrincipal {
7197 script: Arc<str>,
7198 generation: crate::generation::GenerationId,
7199}
7200
7201#[derive(Clone, Eq, PartialEq)]
7202struct LoaderOwner {
7203 id: u64,
7204 principal: LoaderPrincipal,
7205}
7206
7207impl LoaderOwner {
7208 fn fresh(script: &str, generation: crate::generation::GenerationId) -> Self {
7209 Self {
7210 id: LOADER_NEXT_OWNER.fetch_add(1, Ordering::Relaxed),
7211 principal: LoaderPrincipal {
7212 script: Arc::from(script),
7213 generation,
7214 },
7215 }
7216 }
7217}
7218
7219#[doc(hidden)]
7220pub struct LoaderEntry {
7221 owner: LoaderOwner,
7222 state: tokio::sync::watch::Receiver<LoaderState>,
7223}
7224
7225type LoaderRegistry = HashMap<u64, LoaderEntry>;
7226static LOADER_REGISTRY: OnceLock<std::sync::Mutex<LoaderRegistry>> = OnceLock::new();
7227static LOADER_NEXT_ID: AtomicU64 = AtomicU64::new(1);
7228static LOADER_NEXT_OWNER: AtomicU64 = AtomicU64::new(1);
7229
7230#[doc(hidden)]
7231pub fn loader_registry() -> &'static std::sync::Mutex<LoaderRegistry> {
7232 LOADER_REGISTRY.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
7233}
7234
7235/// Remove the registry references for every child of `owner`. The caller
7236/// chooses when to drop the returned states, because they can own V8 isolates
7237/// and no other isolate can be entered on that thread at destruction time.
7238fn take_loader_owner(owner: &LoaderOwner) -> Vec<tokio::sync::watch::Receiver<LoaderState>> {
7239 let mut registry = loader_registry().lock().unwrap();
7240 let ids: Vec<u64> = registry
7241 .iter()
7242 .filter_map(|(id, entry)| (&entry.owner == owner).then_some(*id))
7243 .collect();
7244 ids.into_iter()
7245 .filter_map(|id| registry.remove(&id).map(|entry| entry.state))
7246 .collect()
7247}
7248
7249// Bound live Dynamic Workers so a runaway loader cannot exhaust isolates.
7250// Keep admission policy inside the registry: a caller-selected bound would let
7251// different entry points disagree about how much process capacity remains.
7252const MAX_LOADED_WORKERS: usize = 256;
7253// Reserve only the final process slot. A fixed fraction needlessly reduces
7254// single-script capacity without giving every competing principal a share.
7255const MAX_LOADED_WORKERS_PER_PRINCIPAL: usize = MAX_LOADED_WORKERS - 1;
7256
7257/// Check both limits and install the live state under one registry lock. A
7258/// separate check and insert lets concurrent isolates exceed either limit.
7259fn admit_loaded_worker(
7260 owner: LoaderOwner,
7261 state: tokio::sync::watch::Receiver<LoaderState>,
7262) -> Result<u64, String> {
7263 let mut registry = loader_registry().lock().unwrap();
7264 let principal_limit = MAX_LOADED_WORKERS_PER_PRINCIPAL;
7265 let principal_count = registry
7266 .values()
7267 .filter(|entry| entry.owner.principal == owner.principal)
7268 .count();
7269 if principal_count >= principal_limit {
7270 return Err(format!(
7271 "worker loader: too many loaded workers for script \"{}\" in generation {} (limit {principal_limit})",
7272 owner.principal.script, owner.principal.generation
7273 ));
7274 }
7275 if registry.len() >= MAX_LOADED_WORKERS {
7276 return Err(format!(
7277 "worker loader: too many loaded workers (limit {MAX_LOADED_WORKERS})"
7278 ));
7279 }
7280
7281 let id = LOADER_NEXT_ID.fetch_add(1, Ordering::Relaxed);
7282 registry.insert(id, LoaderEntry { owner, state });
7283 Ok(id)
7284}
7285
7286fn loader_throw(scope: &mut v8::PinScope, message: &str) {
7287 let message = v8::String::new(scope, message).unwrap();
7288 let exception = v8::Exception::error(scope, message);
7289 scope.throw_exception(exception);
7290}
7291
7292fn loader_invocation_limits(
7293 scope: &mut v8::PinScope,
7294 value: v8::Local<v8::Value>,
7295) -> Result<Option<ResourceLimits>, String> {
7296 let json = value.to_rust_string_lossy(scope);
7297 serde_json::from_str(&json)
7298 .map_err(|error| format!("worker loader: invalid invocation limits: {error}"))
7299}
7300
7301async fn loaded_worker_slot(
7302 mut state: tokio::sync::watch::Receiver<LoaderState>,
7303) -> Result<Arc<crate::pool::Slot>, String> {
7304 loop {
7305 match state.borrow().clone() {
7306 LoaderState::Ready(slot) => return Ok(slot),
7307 LoaderState::Failed(error) => return Err(error.to_string()),
7308 LoaderState::Loading => {}
7309 }
7310 state
7311 .changed()
7312 .await
7313 .map_err(|_| "worker loader: load task dropped".to_string())?;
7314 }
7315}
7316
7317/// `__loader_load(codeJson, wasm, outbound, outboundProps, envSc, envRoutes,
7318/// tailReporting)` -> stub id. Builds a WorkerConfig from the supplied modules
7319/// and registers its asynchronous load state. Compilation runs on Tokio's
7320/// blocking pool. Calls wait for that result and use the normal turn driver.
7321fn op_loader_load(
7322 scope: &mut v8::PinScope,
7323 args: v8::FunctionCallbackArguments,
7324 mut rv: v8::ReturnValue<v8::Value>,
7325) {
7326 let generation = current_generation(scope);
7327 let code_json = args.get(0).to_rust_string_lossy(scope);
7328 let code: serde_json::Value = match serde_json::from_str(&code_json) {
7329 Ok(code) => code,
7330 Err(e) => return loader_throw(scope, &format!("worker loader: {e}")),
7331 };
7332 // These fields change the security or observability contract of the
7333 // loaded Worker. Ignoring one makes a Worker run without the contract its
7334 // caller requested, which is more dangerous than refusing the load. Keep
7335 // this check in the host op so both load() and the lazy get() path cross
7336 // the same enforcement boundary.
7337 if code.get("allowExperimental").is_some() {
7338 return loader_throw(
7339 scope,
7340 "worker loader: WorkerCode field `allowExperimental` is not supported",
7341 );
7342 }
7343 let limits = match code.get("limits") {
7344 Some(value) => match serde_json::from_value::<ResourceLimits>(value.clone()) {
7345 Ok(limits) => Some(limits),
7346 Err(error) => {
7347 return loader_throw(scope, &format!("worker loader: invalid limits: {error}"));
7348 }
7349 },
7350 None => None,
7351 };
7352 let tail_reporting = args.get(6).boolean_value(scope);
7353 let Some(main) = code.get("mainModule").and_then(|v| v.as_str()) else {
7354 return loader_throw(scope, "worker loader: missing mainModule");
7355 };
7356 let Some(src) = code
7357 .get("modules")
7358 .and_then(|m| m.get(main))
7359 .and_then(|v| v.as_str())
7360 .map(str::to_string)
7361 else {
7362 return loader_throw(
7363 scope,
7364 &format!("worker loader: module {main:?} missing or not a string"),
7365 );
7366 };
7367 // Every module other than the main one is a sibling the main module may
7368 // import. JS modules arrive in the JSON as strings; anything else there is
7369 // rejected — JSON.stringify would already have mangled it, and dropping it
7370 // silently leaves the loaded worker failing instantiation with an
7371 // unresolved specifier that never names the cause. Wasm modules arrive
7372 // out of band as the second argument, an array of `[name, Uint8Array]`
7373 // pairs, which keeps the blobs out of the JSON payload entirely.
7374 let mut modules: Vec<(String, ModuleSource)> = Vec::new();
7375 if let Some(map) = code.get("modules").and_then(|m| m.as_object()) {
7376 for (name, value) in map.iter().filter(|(name, _)| name.as_str() != main) {
7377 let Some(source) = value.as_str() else {
7378 return loader_throw(
7379 scope,
7380 &format!("worker loader: module {name:?} must be a string or wasm bytes"),
7381 );
7382 };
7383 modules.push((name.clone(), ModuleSource::EsModule(source.to_string())));
7384 }
7385 }
7386 let sideband = args.get(1);
7387 if !sideband.is_undefined() {
7388 let Ok(entries) = v8::Local::<v8::Array>::try_from(sideband) else {
7389 return loader_throw(scope, "worker loader: wasm modules must be an array");
7390 };
7391 for index in 0..entries.length() {
7392 let entry = entries
7393 .get_index(scope, index)
7394 .and_then(|entry| v8::Local::<v8::Array>::try_from(entry).ok())
7395 .and_then(|pair| Some((pair.get_index(scope, 0)?, pair.get_index(scope, 1)?)))
7396 .filter(|(name, _)| name.is_string())
7397 .and_then(|(name, value)| {
7398 let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
7399 Some((name.to_rust_string_lossy(scope), view))
7400 });
7401 let Some((name, view)) = entry else {
7402 return loader_throw(scope, "worker loader: malformed wasm module entry");
7403 };
7404 // A name carried by both the JSON map and the side-band would
7405 // silently shadow one module with the other in the registry;
7406 // refuse it the way a non-string JSON module is refused.
7407 if name == main || modules.iter().any(|(existing, _)| *existing == name) {
7408 return loader_throw(
7409 scope,
7410 &format!("worker loader: duplicate module name {name:?}"),
7411 );
7412 }
7413 let mut bytes = vec![0u8; view.byte_length()];
7414 view.copy_contents(&mut bytes);
7415 modules.push((name, ModuleSource::Wasm(bytes.into())));
7416 }
7417 }
7418 // Total module bytes, checked before compiling anything (the oversized
7419 // module is never parsed) — the extra modules are not yet loaded but do
7420 // count against the ceiling, as upstream.
7421 let code_size: usize = src.len()
7422 + modules
7423 .iter()
7424 .map(|(_, source)| match source {
7425 ModuleSource::Text(source) | ModuleSource::EsModule(source) => source.len(),
7426 ModuleSource::Wasm(bytes) => bytes.len(),
7427 })
7428 .sum::<usize>();
7429 let max_code_bytes = dynamic_worker_code_limit();
7430 if code_size > max_code_bytes {
7431 return loader_throw(
7432 scope,
7433 &format!(
7434 "Dynamic Worker code size ({code_size} bytes) exceeds the \
7435 maximum allowed size of {max_code_bytes} bytes."
7436 ),
7437 );
7438 }
7439 // The environment crosses as structured-clone bytes. Service Binding
7440 // capabilities use a separate host-minted route table, so application
7441 // data can select only a route that the parent already supplied.
7442 let env_arg = args.get(4);
7443 let loader_env = if env_arg.is_undefined() {
7444 None
7445 } else {
7446 let Some(bytes) = view_bytes(env_arg) else {
7447 return loader_throw(scope, "worker loader: env is not a typed array");
7448 };
7449 let routes_arg = args.get(5);
7450 let Ok(route_entries) = v8::Local::<v8::Array>::try_from(routes_arg) else {
7451 return loader_throw(scope, "worker loader: env routes are not an array");
7452 };
7453 let mut routes = Vec::with_capacity(route_entries.length() as usize);
7454 let mut total_size = bytes.len();
7455 for index in 0..route_entries.length() {
7456 let Some(entry) = route_entries
7457 .get_index(scope, index)
7458 .and_then(|value| v8::Local::<v8::Array>::try_from(value).ok())
7459 else {
7460 return loader_throw(scope, "worker loader: malformed env capability route");
7461 };
7462 let Some(script_value) = entry.get_index(scope, 0).filter(|value| value.is_string())
7463 else {
7464 return loader_throw(scope, "worker loader: malformed env capability script");
7465 };
7466 let Some(entrypoint_value) = entry.get_index(scope, 1) else {
7467 return loader_throw(scope, "worker loader: malformed env capability entrypoint");
7468 };
7469 let entrypoint = if entrypoint_value.is_null_or_undefined() {
7470 None
7471 } else if entrypoint_value.is_string() {
7472 Some(entrypoint_value.to_rust_string_lossy(scope))
7473 } else {
7474 return loader_throw(scope, "worker loader: malformed env capability entrypoint");
7475 };
7476 let Some(props_value) = entry.get_index(scope, 2) else {
7477 return loader_throw(scope, "worker loader: malformed env capability props");
7478 };
7479 let Some(props) = view_bytes(props_value) else {
7480 return loader_throw(scope, "worker loader: env capability props are not bytes");
7481 };
7482 total_size = total_size.saturating_add(props.len());
7483 routes.push(LoaderEnvRoute {
7484 script: script_value.to_rust_string_lossy(scope),
7485 entrypoint,
7486 props,
7487 });
7488 }
7489 if total_size > MAX_DYNAMIC_WORKER_ENV_SIZE {
7490 return loader_throw(
7491 scope,
7492 &format!(
7493 "Dynamic Worker env size ({total_size} bytes) exceeds the maximum \
7494 allowed size of {MAX_DYNAMIC_WORKER_ENV_SIZE} bytes.",
7495 ),
7496 );
7497 }
7498 Some(LoaderEnv { bytes, routes })
7499 };
7500 // The harness removes the live Fetcher from the JSON and sends only the
7501 // route that its private WeakMap minted. This op supplies the generation,
7502 // so neither application data nor a stale child can select another graph.
7503 #[derive(serde::Deserialize)]
7504 struct BrokerRoute {
7505 script: String,
7506 entrypoint: Option<String>,
7507 }
7508 let outbound = args.get(2);
7509 let outbound_props = args.get(3);
7510 let egress = if outbound.is_undefined() {
7511 actor_runtime_state(scope).egress.clone()
7512 } else if outbound.is_null() {
7513 EgressPolicy::Deny
7514 } else {
7515 let route: BrokerRoute = match serde_json::from_str(&outbound.to_rust_string_lossy(scope)) {
7516 Ok(route) => route,
7517 Err(error) => {
7518 return loader_throw(
7519 scope,
7520 &format!("worker loader: malformed globalOutbound route: {error}"),
7521 )
7522 }
7523 };
7524 let props = match view_bytes(outbound_props) {
7525 Some(props) => props,
7526 None => {
7527 return loader_throw(
7528 scope,
7529 "worker loader: globalOutbound props are not a typed array",
7530 )
7531 }
7532 };
7533 let entrypoint = match route.entrypoint {
7534 Some(name) => Some(crate::WorkerFetchEntrypoint { name, props }),
7535 None if props.is_empty() => None,
7536 None => {
7537 return loader_throw(
7538 scope,
7539 "worker loader: globalOutbound props require an entrypoint",
7540 )
7541 }
7542 };
7543 EgressPolicy::Broker(OutboundBroker {
7544 generation,
7545 script: route.script,
7546 entrypoint,
7547 })
7548 };
7549 let owner = scope
7550 .get_slot::<LoaderOwner>()
7551 .expect("Worker isolate has a Loader owner")
7552 .clone();
7553 // Honor the WorkerCode's declared compatibility (workerd worker_compat
7554 // reads snake_case keys); Code Mode workers keep RPC on regardless.
7555 let mut compat = crate::worker_compat(&serde_json::json!({
7556 "compatibility_date": code.get("compatibilityDate"),
7557 "compatibility_flags": code.get("compatibilityFlags"),
7558 }));
7559 compat.js_rpc = true;
7560 let handle = match tokio::runtime::Handle::try_current() {
7561 Ok(handle) => handle,
7562 Err(error) => return loader_throw(scope, &format!("worker loader: {error}")),
7563 };
7564 let (loaded, state) = tokio::sync::watch::channel(LoaderState::Loading);
7565 let id = match admit_loaded_worker(owner, state) {
7566 Ok(id) => id,
7567 Err(error) => return loader_throw(scope, &error),
7568 };
7569 let config = Arc::new(
7570 WorkerConfig::new(WorkerConfigOptions {
7571 src,
7572 script_name: format!("__loader:{id}"),
7573 do_classes: Vec::new(),
7574 bindings: Vec::new(),
7575 r2_bindings: Vec::new(),
7576 // A loaded worker reaches D1 only if its parent injects a stub;
7577 // ambient bindings are exactly what Code Mode withholds.
7578 d1_bindings: Vec::new(),
7579 kv_bindings: Vec::new(),
7580 queue_bindings: Vec::new(),
7581 queue_consumers: Vec::new(),
7582 workflow_bindings: Vec::new(),
7583 vars: Vec::new(),
7584 node: String::new(),
7585 modules,
7586 compat,
7587 })
7588 .into_dynamic_worker()
7589 .with_main_module_name(main.to_string())
7590 .with_generation(generation)
7591 .with_egress(egress)
7592 .with_resource_limits(limits)
7593 .with_tail_reporting(tail_reporting)
7594 .with_loader_env(loader_env),
7595 );
7596 handle.spawn(async move {
7597 let state = match tokio::task::spawn_blocking(move || Worker::load_config(config)).await {
7598 Ok(Ok(worker)) => LoaderState::Ready(crate::pool::Slot::standalone(worker)),
7599 Ok(Err(error)) => LoaderState::Failed(Arc::from(format!("{error}"))),
7600 Err(error) => LoaderState::Failed(Arc::from(format!(
7601 "worker loader: load task failed: {error}"
7602 ))),
7603 };
7604 loaded.send_replace(state);
7605 });
7606 rv.set(v8::Number::new(scope, id as f64).into());
7607}
7608
7609/// `__loader_fetch(id, url, method, body, headersJson, streamId, entrypoint,
7610/// propsSc, limitsJson, tailReporting)` -> Promise<json> or
7611/// [Promise<json>, Promise<json>].
7612/// The loaded-worker analog of `__svc_call`: it encodes the response the same
7613/// way and can return a separate report after the invocation finishes.
7614fn op_loader_fetch(
7615 scope: &mut v8::PinScope,
7616 args: v8::FunctionCallbackArguments,
7617 mut rv: v8::ReturnValue<v8::Value>,
7618) {
7619 let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
7620 let url = args.get(1).to_rust_string_lossy(scope);
7621 let method = args.get(2).to_rust_string_lossy(scope);
7622 let entrypoint = args.get(6);
7623 if !entrypoint.is_string() {
7624 return loader_throw(scope, "worker loader: the entrypoint is not a string");
7625 }
7626 let entrypoint = entrypoint.to_rust_string_lossy(scope);
7627 let props = match loader_props_bytes(args.get(7)) {
7628 Ok(props) => props,
7629 Err(error) => return loader_throw(scope, &error),
7630 };
7631 let invocation_limits = match loader_invocation_limits(scope, args.get(8)) {
7632 Ok(limits) => limits,
7633 Err(error) => return loader_throw(scope, &error),
7634 };
7635 // The Worker already stores its default handler, including the synthetic
7636 // missing-handler function for a class-only module. A named entrypoint
7637 // must instead use the harness dispatcher, so an absent name fails rather
7638 // than falling back to the default export. A props-carrying default fetch
7639 // also needs that dispatcher because the direct path cannot install props.
7640 let entrypoint =
7641 (entrypoint != "default" || !props.is_empty()).then_some(crate::WorkerFetchEntrypoint {
7642 name: entrypoint,
7643 props,
7644 });
7645 let stream_arg = args.get(5);
7646 let body = if stream_arg.is_number() {
7647 RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64)
7648 } else {
7649 let Some(bytes) = view_bytes(args.get(3)) else {
7650 return loader_throw(
7651 scope,
7652 "worker loader: the request body is not a typed array",
7653 );
7654 };
7655 RequestBody::Bytes(bytes.into())
7656 };
7657 let headers: Vec<(String, String)> =
7658 match serde_json::from_str(&args.get(4).to_rust_string_lossy(scope)) {
7659 Ok(headers) => headers,
7660 Err(error) => {
7661 return loader_throw(
7662 scope,
7663 &format!(
7664 "worker loader: the request headers are not a name/value list: {error}"
7665 ),
7666 )
7667 }
7668 };
7669 let want_tail_report = args.get(9).boolean_value(scope);
7670 let (tail_report, tail_receive) = if want_tail_report {
7671 let (send, receive) = tokio::sync::oneshot::channel();
7672 (Some(send), Some(receive))
7673 } else {
7674 (None, None)
7675 };
7676 let mut body_guard = match body.stream_id() {
7677 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
7678 Some(guard) => guard,
7679 None => return loader_throw(scope, "worker loader: the body stream is not owned"),
7680 },
7681 None => RequestBodyGuard::of(&body),
7682 };
7683 let loaded = loader_registry()
7684 .lock()
7685 .unwrap()
7686 .get(&id)
7687 .map(|entry| entry.state.clone());
7688 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
7689 let stream_service = http_stream_service();
7690 let async_id = asyncrt::enqueue(async move {
7691 // The child's own `IoContext` has an empty egress stack, so nothing
7692 // inside it gates what it sends onward. Holding the call until the
7693 // caller's writes are proven makes every effect of the loaded worker
7694 // trail that proof, as a service-binding call already does.
7695 await_egress_gate(gate).await?;
7696 let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?;
7697 let slot = loaded_worker_slot(state).await?;
7698 let (reply, receive) = tokio::sync::oneshot::channel();
7699 let job = crate::WorkerJob::Fetch {
7700 queued_at: Instant::now(),
7701 entrypoint,
7702 invocation_limits,
7703 url,
7704 method,
7705 body,
7706 headers,
7707 // A loaded Worker receives an incoming request like a service
7708 // target does. The id selects the stream-aware construction path
7709 // and gives an abandoned request a lifecycle owner.
7710 request_id: Some(next_request_id()),
7711 tail_report,
7712 reply,
7713 };
7714 let driving = tokio::spawn(crate::runtime::drive(slot, job, None));
7715 match receive.await {
7716 Ok(Ok(response)) => {
7717 // The response proves that the loaded Worker installed its
7718 // request context. That context owns an unread body tail
7719 // through its waitUntil work.
7720 body_guard.disarm();
7721 encode_http_response(response, false, &stream_service)
7722 }
7723 Ok(Err(error)) => Err(format!("{error}")),
7724 Err(_) => match driving.await {
7725 Err(error) => Err(format!("loaded worker task died: {error}")),
7726 Ok(()) => Err("loaded worker dropped response".to_string()),
7727 },
7728 }
7729 });
7730 let response = promise_for(scope, async_id);
7731 let Some(tail_receive) = tail_receive else {
7732 rv.set(response);
7733 return;
7734 };
7735 let report_id = asyncrt::enqueue(async move {
7736 tail_receive
7737 .await
7738 .map_err(|error| format!("loaded worker dropped tail report: {error}"))
7739 });
7740 let report = promise_for(scope, report_id);
7741 let pair = v8::Array::new_with_elements(scope, &[response, report]);
7742 rv.set(pair.into());
7743}
7744
7745/// `__loader_rpc(id, entrypoint, method, argsSc, propsSc, limitsJson)` ->
7746/// Promise<Uint8Array>. The loaded-worker analog of `__svc_rpc`: a
7747/// named-entrypoint method call whose args and result are V8 structured-clone
7748/// bytes. `propsSc` carries `getEntrypoint(name, {props})` to the callee's
7749/// `ctx.props` in the same encoding; it is empty for no props.
7750fn op_loader_rpc(
7751 scope: &mut v8::PinScope,
7752 args: v8::FunctionCallbackArguments,
7753 mut rv: v8::ReturnValue<v8::Value>,
7754) {
7755 let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
7756 let entrypoint = args.get(1).to_rust_string_lossy(scope);
7757 let method = args.get(2).to_rust_string_lossy(scope);
7758 let call_args = view_bytes(args.get(3)).unwrap_or_default();
7759 let props = match loader_props_bytes(args.get(4)) {
7760 Ok(props) => props,
7761 Err(error) => return loader_throw(scope, &error),
7762 };
7763 let invocation_limits = match loader_invocation_limits(scope, args.get(5)) {
7764 Ok(limits) => limits,
7765 Err(error) => return loader_throw(scope, &error),
7766 };
7767 // The props ride on `WorkerJob::Rpc` for the whole call, so an unbounded
7768 // value is an unbounded per-call allocation in the host. The harness checks
7769 // nothing here: it runs in the calling worker's isolate beside the
7770 // application's code, so only this op can bound the value.
7771 let loaded = loader_registry()
7772 .lock()
7773 .unwrap()
7774 .get(&id)
7775 .map(|entry| entry.state.clone());
7776 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Service);
7777 let async_id = asyncrt::enqueue(async move {
7778 // The same rule as `op_loader_fetch`: the call carries cell state.
7779 await_egress_gate(gate).await?;
7780 let state = loaded.ok_or_else(|| "worker loader: unknown worker".to_string())?;
7781 let slot = loaded_worker_slot(state).await?;
7782 let (reply, receive) = tokio::sync::oneshot::channel();
7783 let job = crate::WorkerJob::Rpc {
7784 entrypoint,
7785 operation: crate::WorkerRpcOperation::Call {
7786 path: vec![method],
7787 args: call_args,
7788 },
7789 props,
7790 invocation_limits,
7791 reply,
7792 };
7793 let driving = tokio::spawn(crate::runtime::drive(slot, job, None));
7794 match receive.await {
7795 Ok(Ok(result)) => Ok(result),
7796 Ok(Err(error)) => Err(format!("{error}")),
7797 Err(_) => match driving.await {
7798 Err(error) => Err(format!("loaded worker task died: {error}")),
7799 Ok(()) => Err("loaded worker dropped RPC result".to_string()),
7800 },
7801 }
7802 });
7803 rv.set(promise_for(scope, async_id));
7804}
7805
7806fn facet_scope(class_name: &str, parent_scope: &str, owner: &str, name: &str) -> String {
7807 use sha2::Digest as _;
7808 let mut digest = sha2::Sha256::new();
7809 digest.update(parent_scope.as_bytes());
7810 digest.update([0]);
7811 digest.update(owner.as_bytes());
7812 digest.update([0]);
7813 digest.update(name.as_bytes());
7814 let digest: [u8; 32] = digest.finalize().into();
7815 format!("{class_name}:{}", durable_object_id_hex(&digest))
7816}
7817
7818/// Activate a facet's stream through the host loop, which owns the
7819/// replicator, and answer its database file and whether it was restored.
7820async fn open_facet_file(
7821 parent: &storage::StorageIdentity,
7822 name: &str,
7823) -> Result<(std::path::PathBuf, bool), String> {
7824 let mut names = parent.facet_path.clone();
7825 names.push(name.to_string());
7826 let Some(sender) = FACET_TX.get() else {
7827 // No host loop runs the replicator, so the file sits beside the
7828 // root's database and is named after it, as workerd names a facet
7829 // `<id>.<facet>.sqlite`.
7830 let stream = crate::engine_api::facet_cell(&parent.root_scope, &names);
7831 let facet = stream[parent.root_scope.len()..]
7832 .trim_start_matches('/')
7833 .replace('/', "-");
7834 let root = std::path::Path::new(&parent.root_path);
7835 let file = root.file_name().unwrap().to_string_lossy();
7836 return Ok((root.with_file_name(format!("{file}.{facet}.sqlite")), false));
7837 };
7838 let (reply, receive) = tokio::sync::oneshot::channel();
7839 let request = FacetReq::Open {
7840 root: parent.root_scope.clone(),
7841 epoch: parent.epoch,
7842 names,
7843 reply,
7844 };
7845 sender
7846 .send(request)
7847 .map_err(|_| "the facet channel closed".to_string())?;
7848 receive
7849 .await
7850 .map_err(|_| "the facet open was dropped".to_string())?
7851 .map_err(|error| format!("open the facet database: {error:#}"))
7852}
7853
7854struct FacetStart {
7855 class_name: String,
7856 parent_scope: String,
7857 owner: String,
7858 name: String,
7859 id_sc: Vec<u8>,
7860 props_sc: Vec<u8>,
7861 parent: storage::StorageIdentity,
7862}
7863
7864/// A facet ready for one call, with what its reply must wait for.
7865struct LoadedFacet {
7866 slot: Arc<crate::pool::Slot>,
7867 scope: String,
7868 stream: String,
7869 epoch: u64,
7870}
7871
7872impl LoadedFacet {
7873 /// A facet's reply leaves as workerd's facet output gate lets it: after
7874 /// every write the facet committed is durable on its own stream. That
7875 /// covers an earlier call's write this reply can reveal as well as the
7876 /// call's own, and an error reply as well as a result.
7877 async fn gate_reply(&self) -> Result<(), String> {
7878 prove_facet(self.stream.clone(), self.epoch)
7879 .await
7880 .map_err(|refusal| format!("facet reply: {refusal}"))
7881 }
7882}
7883
7884/// The loader id of a class from the script's own `ctx.exports`. Loaded
7885/// Workers' ids start at 1.
7886const OWN_SCRIPT_LOADER: u64 = 0;
7887
7888/// The isolate a facet's class runs in: a loaded Worker's, or, for a class
7889/// of the root's own script, the root's own, as workerd runs it.
7890enum FacetHost {
7891 Loaded(tokio::sync::watch::Receiver<LoaderState>),
7892 Own(Arc<crate::pool::Slot>),
7893}
7894
7895impl FacetHost {
7896 /// Resolved in the op, while the root's turn names its slot.
7897 fn of(loader: u64) -> Result<Self, String> {
7898 if loader == OWN_SCRIPT_LOADER {
7899 return crate::pool::current_slot()
7900 .map(Self::Own)
7901 .ok_or_else(|| "facet: no isolate runs this turn".to_string());
7902 }
7903 loader_registry()
7904 .lock()
7905 .unwrap()
7906 .get(&loader)
7907 .map(|entry| Self::Loaded(entry.state.clone()))
7908 .ok_or_else(|| "worker loader: unknown worker".to_string())
7909 }
7910
7911 async fn slot(self) -> Result<Arc<crate::pool::Slot>, String> {
7912 match self {
7913 Self::Loaded(loaded) => loaded_worker_slot(loaded).await,
7914 Self::Own(slot) => Ok(slot),
7915 }
7916 }
7917}
7918
7919/// The facets that each root runs in loaded Workers' isolates, by the root's
7920/// cell and epoch.
7921///
7922/// A loaded Worker can outlive a root through another stub or until garbage
7923/// collection. Neither lifetime tells the loaded isolate when a root stops,
7924/// so connection closure cannot depend on collection. The root's own
7925/// `facets._release()` invalidates its stubs synchronously: the give-back
7926/// turn cannot drive an asynchronous abort. Previously, each reactivation
7927/// left a connection open on an unlinked file, with the facet's JavaScript
7928/// state. The adoption turn records each facet here, and the root's
7929/// give-back closes them.
7930///
7931/// A facet of the root's own class is not recorded: `finish_cell_adoption`
7932/// closes it in the root's give-back turn, and its slot can be freed while a
7933/// reference is held, so a later turn on it would panic.
7934static ROOT_FACETS: OnceLock<Mutex<HashMap<(String, u64), RootFacets>>> = OnceLock::new();
7935
7936fn root_facets() -> std::sync::MutexGuard<'static, HashMap<(String, u64), RootFacets>> {
7937 ROOT_FACETS
7938 .get_or_init(Mutex::default)
7939 .lock()
7940 .expect("root facets poisoned")
7941}
7942
7943#[derive(Default)]
7944struct RootFacets {
7945 /// Facet calls between their start and their adoption turn. The entry
7946 /// lives while one runs, so a call that adopts after the root stopped
7947 /// finds `stopped` rather than a fresh entry.
7948 pending: usize,
7949 /// The root gave its residency back and does not run again at this
7950 /// epoch, so no facet of it can be adopted.
7951 stopped: bool,
7952 /// Each slot keeps its loaded isolate alive until the release closes
7953 /// the facet in it.
7954 open: Vec<(Arc<crate::pool::Slot>, String)>,
7955}
7956
7957/// One facet call of a root, from its start until its adoption turn.
7958struct PendingFacet {
7959 key: (String, u64),
7960}
7961
7962impl PendingFacet {
7963 fn begin(root: &str, epoch: u64) -> Result<Self, String> {
7964 let key = (root.to_string(), epoch);
7965 let mut roots = root_facets();
7966 let entry = roots.entry(key.clone()).or_default();
7967 if entry.stopped {
7968 return Err(format!("{root} epoch {epoch} stopped"));
7969 }
7970 entry.pending += 1;
7971 Ok(Self { key })
7972 }
7973
7974 /// Record the facet before its adoption. Call inside the adoption turn:
7975 /// a release that takes the record queues its close behind this turn on
7976 /// the same slot, and a release that came first makes this refuse.
7977 fn record(&self, slot: &Arc<crate::pool::Slot>, scope: &str) -> Result<(), String> {
7978 let mut roots = root_facets();
7979 let entry = roots
7980 .get_mut(&self.key)
7981 .expect("a pending facet keeps its entry");
7982 if entry.stopped {
7983 return Err(format!("{} epoch {} stopped", self.key.0, self.key.1));
7984 }
7985 if !entry
7986 .open
7987 .iter()
7988 .any(|(open, name)| Arc::ptr_eq(open, slot) && name == scope)
7989 {
7990 entry.open.push((slot.clone(), scope.to_string()));
7991 }
7992 Ok(())
7993 }
7994}
7995
7996impl Drop for PendingFacet {
7997 fn drop(&mut self) {
7998 let mut roots = root_facets();
7999 if let Some(entry) = roots.get_mut(&self.key) {
8000 entry.pending -= 1;
8001 if entry.pending == 0 && entry.open.is_empty() {
8002 roots.remove(&self.key);
8003 }
8004 }
8005 }
8006}
8007
8008/// How a root leaves the isolate that runs it.
8009#[derive(Clone, Copy)]
8010pub(crate) enum RootRelease {
8011 /// The root stops at this epoch: its facets close, and none opens again.
8012 Stop,
8013 /// The root restarts at the same epoch on another generation. It builds
8014 /// a new facet manager there, so the facets of this one close, but the
8015 /// new instance can open its own.
8016 ///
8017 /// A call of the old instance can still adopt after this release, and
8018 /// that is bounded. The facet ops read the root's storage identity
8019 /// synchronously, and the give-back closed that storage, so only a call
8020 /// that started before the swap turn gets here. It records under the
8021 /// same root and epoch, so the root's next release closes it. Marking
8022 /// the epoch stopped instead would refuse the new instance's facets.
8023 Swap,
8024}
8025
8026/// Close each facet that `root` runs in a loaded Worker's isolate. The
8027/// caller gives the root back first, so the root cannot start a facet call
8028/// after the facets are taken.
8029pub(crate) async fn release_root_facets(root: &str, epoch: u64, release: RootRelease) {
8030 let key = (root.to_string(), epoch);
8031 let open = {
8032 let mut roots = root_facets();
8033 let Some(entry) = roots.get_mut(&key) else {
8034 return;
8035 };
8036 if matches!(release, RootRelease::Stop) {
8037 entry.stopped = true;
8038 }
8039 let open = std::mem::take(&mut entry.open);
8040 if entry.pending == 0 {
8041 roots.remove(&key);
8042 }
8043 open
8044 };
8045 // A nested facet records after its parent, so it closes first.
8046 for (slot, scope) in open.into_iter().rev() {
8047 if let Err(error) = slot.turn(|worker| worker.own_cell(&scope, None)).await {
8048 tracing::warn!(root, epoch, facet = %scope, %error, "a facet did not close with its root");
8049 }
8050 }
8051}
8052
8053/// Drop an aborted facet's record, which its abort closed already.
8054fn forget_root_facet(root: &str, epoch: u64, slot: &Arc<crate::pool::Slot>, scope: &str) {
8055 let key = (root.to_string(), epoch);
8056 let mut roots = root_facets();
8057 if let Some(entry) = roots.get_mut(&key) {
8058 entry
8059 .open
8060 .retain(|(open, name)| !(Arc::ptr_eq(open, slot) && name == scope));
8061 if entry.pending == 0 && entry.open.is_empty() {
8062 roots.remove(&key);
8063 }
8064 }
8065}
8066
8067async fn prepare_facet(host: FacetHost, start: FacetStart) -> Result<LoadedFacet, String> {
8068 let pending = match host {
8069 FacetHost::Loaded(_) => Some(PendingFacet::begin(
8070 &start.parent.root_scope,
8071 start.parent.epoch,
8072 )?),
8073 FacetHost::Own(_) => None,
8074 };
8075 let slot = host.slot().await?;
8076 let file = open_facet_file(&start.parent, &start.name).await?;
8077 let mut names = start.parent.facet_path.clone();
8078 names.push(start.name.clone());
8079 let stream = crate::engine_api::facet_cell(&start.parent.root_scope, &names);
8080 let epoch = start.parent.epoch;
8081 let scope = facet_scope(
8082 &start.class_name,
8083 &start.parent_scope,
8084 &start.owner,
8085 &start.name,
8086 );
8087 slot.turn(|worker| {
8088 if let Some(pending) = &pending {
8089 pending.record(&slot, &scope)?;
8090 }
8091 worker
8092 .own_embedded_cell(
8093 &scope,
8094 &start.parent,
8095 &start.name,
8096 start.id_sc,
8097 start.props_sc,
8098 file,
8099 )
8100 .map_err(|error| format!("{error}"))
8101 })
8102 .await
8103 .map_err(|error| format!("worker loader facet: {error}"))?;
8104 Ok(LoadedFacet {
8105 slot,
8106 scope,
8107 stream,
8108 epoch,
8109 })
8110}
8111
8112fn op_facet_rpc(
8113 scope: &mut v8::PinScope,
8114 args: v8::FunctionCallbackArguments,
8115 mut rv: v8::ReturnValue<v8::Value>,
8116) {
8117 let loader = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8118 let class_name = args.get(1).to_rust_string_lossy(scope);
8119 let parent_scope = args.get(2).to_rust_string_lossy(scope);
8120 let owner = args.get(3).to_rust_string_lossy(scope);
8121 let name = args.get(4).to_rust_string_lossy(scope);
8122 let Some(id_sc) = view_bytes(args.get(5)) else {
8123 return loader_throw(scope, "facet identity is not a typed array");
8124 };
8125 let props_sc = match loader_props_bytes(args.get(6)) {
8126 Ok(props) => props,
8127 Err(error) => return loader_throw(scope, &error),
8128 };
8129 let method = args.get(7).to_rust_string_lossy(scope);
8130 let call_args = view_bytes(args.get(8)).unwrap_or_default();
8131 let parent = match storage::storage_identity(&parent_scope) {
8132 Ok(Some(parent)) => parent,
8133 Ok(None) => {
8134 return loader_throw(
8135 scope,
8136 "facets are available only inside a Durable Object event",
8137 )
8138 }
8139 Err(error) => return loader_throw(scope, &error.to_string()),
8140 };
8141 let host = FacetHost::of(loader);
8142 let trace = current_trace_context(scope);
8143 let async_id = asyncrt::enqueue(async move {
8144 let facet = prepare_facet(
8145 host?,
8146 FacetStart {
8147 class_name,
8148 parent_scope,
8149 owner,
8150 name,
8151 id_sc,
8152 props_sc,
8153 parent,
8154 },
8155 )
8156 .await?;
8157 let (reply, receive) = tokio::sync::oneshot::channel();
8158 let job = CellJob::Rpc {
8159 request_id: None,
8160 scope: facet.scope.clone(),
8161 name: None,
8162 method,
8163 args: RpcData::V8(call_args.into()),
8164 reply,
8165 };
8166 let driving = tokio::spawn(crate::runtime::drive_cell(
8167 facet.slot.affiliate(),
8168 job,
8169 None,
8170 trace,
8171 ));
8172 let replied = receive.await;
8173 if replied.is_ok() {
8174 facet.gate_reply().await?;
8175 }
8176 match replied {
8177 Ok(Ok(outcome)) => match outcome.data {
8178 RpcData::V8(bytes) => {
8179 facet.gate_reply().await?;
8180 Ok(Vec::<u8>::from(bytes))
8181 }
8182 RpcData::Json(_) => Err("facet RPC answered JSON".to_string()),
8183 },
8184 Ok(Err(error)) => Err(format!("{error}")),
8185 Err(_) => match driving.await {
8186 Err(error) => Err(format!("facet RPC task died: {error}")),
8187 Ok(()) => Err("facet dropped RPC result".to_string()),
8188 },
8189 }
8190 });
8191 rv.set(promise_for(scope, async_id));
8192}
8193
8194fn op_facet_fetch(
8195 scope: &mut v8::PinScope,
8196 args: v8::FunctionCallbackArguments,
8197 mut rv: v8::ReturnValue<v8::Value>,
8198) {
8199 let loader = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8200 let class_name = args.get(1).to_rust_string_lossy(scope);
8201 let parent_scope = args.get(2).to_rust_string_lossy(scope);
8202 let owner = args.get(3).to_rust_string_lossy(scope);
8203 let name = args.get(4).to_rust_string_lossy(scope);
8204 let Some(id_sc) = view_bytes(args.get(5)) else {
8205 return loader_throw(scope, "facet identity is not a typed array");
8206 };
8207 let props_sc = match loader_props_bytes(args.get(6)) {
8208 Ok(props) => props,
8209 Err(error) => return loader_throw(scope, &error),
8210 };
8211 let url = args.get(7).to_rust_string_lossy(scope);
8212 let method = args.get(8).to_rust_string_lossy(scope);
8213 let stream_arg = args.get(11);
8214 let body = if stream_arg.is_number() {
8215 RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64)
8216 } else {
8217 let Some(bytes) = view_bytes(args.get(9)) else {
8218 return loader_throw(scope, "facet: the request body is not a typed array");
8219 };
8220 RequestBody::Bytes(bytes.into())
8221 };
8222 let headers: Vec<(String, String)> =
8223 match serde_json::from_str(&args.get(10).to_rust_string_lossy(scope)) {
8224 Ok(headers) => headers,
8225 Err(error) => return loader_throw(scope, &format!("facet headers: {error}")),
8226 };
8227 let mut body_guard = match body.stream_id() {
8228 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
8229 Some(guard) => guard,
8230 None => return loader_throw(scope, "facet: the body stream is not owned"),
8231 },
8232 None => RequestBodyGuard::of(&body),
8233 };
8234 let parent = match storage::storage_identity(&parent_scope) {
8235 Ok(Some(parent)) => parent,
8236 Ok(None) => {
8237 return loader_throw(
8238 scope,
8239 "facets are available only inside a Durable Object event",
8240 )
8241 }
8242 Err(error) => return loader_throw(scope, &error.to_string()),
8243 };
8244 let host = FacetHost::of(loader);
8245 let trace = current_trace_context(scope);
8246 let stream_service = http_stream_service();
8247 let async_id = asyncrt::enqueue(async move {
8248 let facet = prepare_facet(
8249 host?,
8250 FacetStart {
8251 class_name,
8252 parent_scope,
8253 owner,
8254 name,
8255 id_sc,
8256 props_sc,
8257 parent,
8258 },
8259 )
8260 .await?;
8261 let (reply, receive) = tokio::sync::oneshot::channel();
8262 let job = CellJob::Fetch {
8263 request_id: None,
8264 scope: facet.scope.clone(),
8265 name: None,
8266 url,
8267 method,
8268 body,
8269 headers,
8270 reply,
8271 order: None,
8272 };
8273 let driving = tokio::spawn(crate::runtime::drive_cell(
8274 facet.slot.affiliate(),
8275 job,
8276 None,
8277 trace,
8278 ));
8279 let replied = receive.await;
8280 if replied.is_ok() {
8281 facet.gate_reply().await?;
8282 }
8283 match replied {
8284 Ok(Ok(response)) => {
8285 body_guard.disarm();
8286 facet.gate_reply().await?;
8287 encode_http_response(response, false, &stream_service)
8288 }
8289 Ok(Err(error)) => Err(format!("{error}")),
8290 Err(_) => match driving.await {
8291 Err(error) => Err(format!("facet fetch task died: {error}")),
8292 Ok(()) => Err("facet dropped fetch response".to_string()),
8293 },
8294 }
8295 });
8296 rv.set(promise_for(scope, async_id));
8297}
8298
8299fn op_facet_abort(
8300 scope: &mut v8::PinScope,
8301 args: v8::FunctionCallbackArguments,
8302 mut rv: v8::ReturnValue<v8::Value>,
8303) {
8304 let loader = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8305 let class_name = args.get(1).to_rust_string_lossy(scope);
8306 let parent_scope = args.get(2).to_rust_string_lossy(scope);
8307 let owner = args.get(3).to_rust_string_lossy(scope);
8308 let name = args.get(4).to_rust_string_lossy(scope);
8309 let host = FacetHost::of(loader);
8310 let facet_scope = facet_scope(&class_name, &parent_scope, &owner, &name);
8311 // The root that recorded the facet. A parent without storage has no
8312 // record to drop.
8313 let root = storage::storage_identity(&parent_scope)
8314 .ok()
8315 .flatten()
8316 .map(|parent| (parent.root_scope, parent.epoch));
8317 let async_id = asyncrt::enqueue(async move {
8318 let host = host?;
8319 let loaded = matches!(host, FacetHost::Loaded(_));
8320 let slot = host.slot().await?;
8321 slot.turn(|worker| worker.own_cell(&facet_scope, None))
8322 .await
8323 .map_err(|error| format!("abort facet: {error}"))?;
8324 if let (true, Some((root, epoch))) = (loaded, root) {
8325 forget_root_facet(&root, epoch, &slot, &facet_scope);
8326 }
8327 Ok(Vec::new())
8328 });
8329 rv.set(promise_for(scope, async_id));
8330}
8331
8332fn op_facet_delete(
8333 scope: &mut v8::PinScope,
8334 args: v8::FunctionCallbackArguments,
8335 mut rv: v8::ReturnValue<v8::Value>,
8336) {
8337 let parent_scope = args.get(0).to_rust_string_lossy(scope);
8338 let name = args.get(1).to_rust_string_lossy(scope);
8339 let parent = match storage::storage_identity(&parent_scope) {
8340 Ok(Some(parent)) => parent,
8341 Ok(None) => {
8342 return loader_throw(
8343 scope,
8344 "facets are available only inside a Durable Object event",
8345 )
8346 }
8347 Err(error) => return loader_throw(scope, &error.to_string()),
8348 };
8349 if let Err(error) = storage::delete_legacy_facet(&parent, &name) {
8350 return loader_throw(scope, &format!("delete facet storage: {error}"));
8351 }
8352 let mut names = parent.facet_path.clone();
8353 names.push(name);
8354 let async_id = asyncrt::enqueue(async move {
8355 let Some(sender) = FACET_TX.get() else {
8356 let (path, _) = open_facet_file(&parent, names.last().unwrap()).await?;
8357 for suffix in ["", "-wal", "-shm"] {
8358 let mut file = path.clone().into_os_string();
8359 file.push(suffix);
8360 let _ = asyncrt::fs().remove_file(std::path::Path::new(&file));
8361 }
8362 return Ok(Vec::new());
8363 };
8364 let (reply, receive) = tokio::sync::oneshot::channel();
8365 let request = FacetReq::Delete {
8366 root: parent.root_scope,
8367 epoch: parent.epoch,
8368 names,
8369 reply,
8370 };
8371 sender
8372 .send(request)
8373 .map_err(|_| "the facet channel closed".to_string())?;
8374 receive
8375 .await
8376 .map_err(|_| "the facet delete was dropped".to_string())?
8377 .map_err(|error| format!("delete facet storage: {error:#}"))?;
8378 Ok(Vec::new())
8379 });
8380 rv.set(promise_for(scope, async_id));
8381}
8382
8383/// `__loader_drop(id)` — release the loader's ownership on explicit disposal
8384/// or collection of the shared JavaScript load lifetime. In-flight calls and
8385/// root facet records retain their own references until they finish.
8386fn op_loader_drop(
8387 scope: &mut v8::PinScope,
8388 args: v8::FunctionCallbackArguments,
8389 _rv: v8::ReturnValue<v8::Value>,
8390) {
8391 let id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
8392 if let Some(entry) = loader_registry().lock().unwrap().remove(&id) {
8393 // This op runs while the parent isolate is entered. The load state can
8394 // own the loaded isolate, and V8 forbids dropping one isolate while a
8395 // different isolate is entered on the same thread. Hand the final
8396 // reference to the host scheduler so destruction happens after this
8397 // turn has left V8.
8398 asyncrt::op_handle().spawn(async move { drop(entry.state) });
8399 }
8400}
8401
8402fn op_do_call(
8403 scope: &mut v8::PinScope,
8404 args: v8::FunctionCallbackArguments,
8405 mut rv: v8::ReturnValue<v8::Value>,
8406) {
8407 op_do_call_impl(scope, args, &mut rv, false);
8408}
8409
8410fn op_do_call_cancellable(
8411 scope: &mut v8::PinScope,
8412 args: v8::FunctionCallbackArguments,
8413 mut rv: v8::ReturnValue<v8::Value>,
8414) {
8415 op_do_call_impl(scope, args, &mut rv, true);
8416}
8417
8418fn op_do_call_impl(
8419 scope: &mut v8::PinScope,
8420 args: v8::FunctionCallbackArguments,
8421 rv: &mut v8::ReturnValue<v8::Value>,
8422 cancellable: bool,
8423) {
8424 let cell = args.get(0).to_rust_string_lossy(scope);
8425 let name_value = args.get(1);
8426 let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
8427 let url = args.get(2).to_rust_string_lossy(scope);
8428 let method = args.get(3).to_rust_string_lossy(scope);
8429 // arg 4 is the held bytes; arg 6, when a number, is a host stream id for a
8430 // body that must not be collected here (a large or unbounded upload). The
8431 // owning cell reads that stream directly; only a cross-node hop collects it.
8432 let stream_arg = args.get(6);
8433 let body = if stream_arg.is_number() {
8434 RequestBody::Stream(stream_arg.number_value(scope).unwrap_or(0.0) as u64)
8435 } else {
8436 let Some(bytes) = view_bytes(args.get(4)) else {
8437 return loader_throw(
8438 scope,
8439 "durable object: the request body is not a typed array",
8440 );
8441 };
8442 RequestBody::Bytes(bytes.into())
8443 };
8444 let headers: Vec<(String, String)> =
8445 match serde_json::from_str(&args.get(5).to_rust_string_lossy(scope)) {
8446 Ok(headers) => headers,
8447 Err(error) => {
8448 return loader_throw(
8449 scope,
8450 &format!(
8451 "durable object: the request headers are not a name/value list: {error}"
8452 ),
8453 )
8454 }
8455 };
8456 let body_guard = match body.stream_id() {
8457 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
8458 Some(guard) => guard,
8459 None => return loader_throw(scope, "durable object: the body stream is not owned"),
8460 },
8461 None => RequestBodyGuard::of(&body),
8462 };
8463 let (tx, rx) = tokio::sync::oneshot::channel();
8464 // Taken here and nowhere later: this is the last point that still runs
8465 // in the order the script made the calls.
8466 let order = Some(enter_call_order(current_context(), &cell));
8467 // Every host op needs an internal cancellation channel. A caller without
8468 // an AbortSignal cannot cancel from JavaScript, but its enclosing Worker
8469 // can still disappear and drop this op before routing completes.
8470 let request_id = next_do_request_id();
8471 let (cancel_sender, cancel) = tokio::sync::oneshot::channel();
8472 do_call_cancels()
8473 .lock()
8474 .unwrap()
8475 .insert(request_id, cancel_sender);
8476 let mut cancel_guard = DoCallCancelGuard::new(request_id);
8477 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::CellRpc);
8478 let request = DoCallReq {
8479 request_id: Some(request_id),
8480 cancel: Some(cancel),
8481 deliver_abort_to_handler: cancellable,
8482 scope: cell,
8483 name,
8484 url,
8485 method,
8486 body,
8487 body_guard,
8488 headers,
8489 reply: tx,
8490 order,
8491 parent: current_trace_context(scope),
8492 };
8493 let stream_service = http_stream_service();
8494 let id = asyncrt::enqueue(async move {
8495 gated_channel_send(gate, &DO_CALL_TX, request, "no proxy channel").await?;
8496 let result = match rx.await {
8497 Ok(Ok(response)) => encode_http_response(response, true, &stream_service),
8498 Ok(Err(e)) => Err(format!("{e}")),
8499 Err(e) => Err(format!("proxy dropped: {e}")),
8500 };
8501 cancel_guard.disarm();
8502 result
8503 });
8504 let p = promise_for(scope, id);
8505 if cancellable {
8506 attach_cancel_id(scope, p, request_id);
8507 }
8508 rv.set(p);
8509}
8510
8511fn op_do_call_cancel(
8512 scope: &mut v8::PinScope,
8513 args: v8::FunctionCallbackArguments,
8514 _rv: v8::ReturnValue<v8::Value>,
8515) {
8516 let request_id = args.get(0).to_rust_string_lossy(scope);
8517 let Some(request_id) = parse_request_id(&request_id) else {
8518 return;
8519 };
8520 if let Some(cancel) = do_call_cancels().lock().unwrap().remove(&request_id) {
8521 let _ = cancel.send(());
8522 }
8523}
8524
8525/// Allocate a process-wide signal identity. The structured-clone RPC envelope
8526/// carries this identity between isolates, and the registry carries the one
8527/// state transition that a snapshot cannot represent.
8528fn op_rpc_signal_new(
8529 scope: &mut v8::PinScope,
8530 _args: v8::FunctionCallbackArguments,
8531 mut rv: v8::ReturnValue<v8::Value>,
8532) {
8533 let signal = next_request_id();
8534 rpc_signals()
8535 .lock()
8536 .unwrap()
8537 .insert(signal, RpcSignalState::Live(HashMap::new()));
8538 let signal = v8::String::new(scope, &request_id_string(signal)).unwrap();
8539 rv.set(signal.into());
8540}
8541
8542fn op_rpc_signal_abort(
8543 scope: &mut v8::PinScope,
8544 args: v8::FunctionCallbackArguments,
8545 _rv: v8::ReturnValue<v8::Value>,
8546) {
8547 let Some(signal) = parse_request_id(&args.get(0).to_rust_string_lossy(scope)) else {
8548 return;
8549 };
8550 let reason = view_bytes(args.get(1)).unwrap_or_default();
8551 let subscribers = {
8552 let mut signals = rpc_signals().lock().unwrap();
8553 let Some(state) = signals.get_mut(&signal) else {
8554 return;
8555 };
8556 match std::mem::replace(state, RpcSignalState::Aborted(reason.clone())) {
8557 RpcSignalState::Live(subscribers) => subscribers,
8558 RpcSignalState::Aborted(prior) => {
8559 *state = RpcSignalState::Aborted(prior);
8560 return;
8561 }
8562 }
8563 };
8564 for subscriber in subscribers.into_values() {
8565 let _ = subscriber.send(Some(reason.clone()));
8566 }
8567}
8568
8569fn op_rpc_signal_release(
8570 scope: &mut v8::PinScope,
8571 args: v8::FunctionCallbackArguments,
8572 _rv: v8::ReturnValue<v8::Value>,
8573) {
8574 let Some(signal) = parse_request_id(&args.get(0).to_rust_string_lossy(scope)) else {
8575 return;
8576 };
8577 let state = rpc_signals().lock().unwrap().remove(&signal);
8578 if let Some(RpcSignalState::Live(subscribers)) = state {
8579 for subscriber in subscribers.into_values() {
8580 let _ = subscriber.send(None);
8581 }
8582 }
8583}
8584
8585fn op_rpc_signal_unsubscribe(
8586 scope: &mut v8::PinScope,
8587 args: v8::FunctionCallbackArguments,
8588 _rv: v8::ReturnValue<v8::Value>,
8589) {
8590 let Some(signal) = parse_request_id(&args.get(0).to_rust_string_lossy(scope)) else {
8591 return;
8592 };
8593 let Some(subscription) = parse_request_id(&args.get(1).to_rust_string_lossy(scope)) else {
8594 return;
8595 };
8596 if let Some(RpcSignalState::Live(subscribers)) = rpc_signals().lock().unwrap().get_mut(&signal)
8597 {
8598 subscribers.remove(&subscription);
8599 }
8600}
8601
8602fn op_rpc_signal_poll(
8603 scope: &mut v8::PinScope,
8604 args: v8::FunctionCallbackArguments,
8605 mut rv: v8::ReturnValue<v8::Value>,
8606) {
8607 let Some(signal) = parse_request_id(&args.get(0).to_rust_string_lossy(scope)) else {
8608 return;
8609 };
8610 let signals = rpc_signals().lock().unwrap();
8611 match signals.get(&signal) {
8612 Some(RpcSignalState::Aborted(reason)) => {
8613 rv.set(bytes_value(scope, reason.clone()));
8614 }
8615 Some(RpcSignalState::Live(_)) => {}
8616 None => rv.set(v8::null(scope).into()),
8617 }
8618}
8619
8620fn op_rpc_signal_wait(
8621 scope: &mut v8::PinScope,
8622 args: v8::FunctionCallbackArguments,
8623 mut rv: v8::ReturnValue<v8::Value>,
8624) {
8625 let signal_text = args.get(0).to_rust_string_lossy(scope);
8626 let Some(signal) = parse_request_id(&signal_text) else {
8627 return loader_throw(scope, "invalid RPC AbortSignal id");
8628 };
8629 let subscription = next_request_id();
8630 let (tx, rx) = tokio::sync::oneshot::channel();
8631 let immediate = {
8632 let mut signals = rpc_signals().lock().unwrap();
8633 match signals.get_mut(&signal) {
8634 Some(RpcSignalState::Live(subscribers)) => {
8635 subscribers.insert(subscription, tx);
8636 None
8637 }
8638 Some(RpcSignalState::Aborted(reason)) => Some(Some(reason.clone())),
8639 None => Some(None),
8640 }
8641 };
8642 // The subscription must receive aborts while the handler or `waitUntil`
8643 // work is live, but a listener alone is not pending application work. An
8644 // ordinary handler op pins every successful Durable Object event until
8645 // the source aborts, including events unrelated to the retained signal.
8646 let id = asyncrt::enqueue_unrefed(async move {
8647 let _guard = RpcSignalSubscriptionGuard {
8648 signal,
8649 subscription,
8650 };
8651 let reason = match immediate {
8652 Some(reason) => reason,
8653 None => rx.await.unwrap_or(None),
8654 };
8655 Ok(reason.unwrap_or_default())
8656 });
8657 let promise = promise_for(scope, id);
8658 if let Some(object) = promise.to_object(scope) {
8659 let key = v8::String::new(scope, "__celldRpcSignalSubscription").unwrap();
8660 let value = v8::String::new(scope, &request_id_string(subscription)).unwrap();
8661 object.set(scope, key.into(), value.into());
8662 }
8663 rv.set(promise);
8664}
8665
8666/// `__rpc_call(scope, name, method, argsSc)` -> Promise<Uint8Array>;
8667/// arguments and result are V8 structured-clone bytes.
8668fn op_rpc_call(
8669 scope: &mut v8::PinScope,
8670 args: v8::FunctionCallbackArguments,
8671 mut rv: v8::ReturnValue<v8::Value>,
8672) {
8673 let cell = args.get(0).to_rust_string_lossy(scope);
8674 let name_value = args.get(1);
8675 let name = (!name_value.is_null_or_undefined()).then(|| name_value.to_rust_string_lossy(scope));
8676 let method = args.get(2).to_rust_string_lossy(scope);
8677 let args = RpcData::V8(view_bytes(args.get(3)).unwrap_or_default().into());
8678 let (tx, rx) = tokio::sync::oneshot::channel();
8679 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::CellRpc);
8680 let request = RpcCallReq {
8681 scope: cell,
8682 name,
8683 method,
8684 args,
8685 reply: tx,
8686 };
8687 let id = asyncrt::enqueue(async move {
8688 gated_channel_send(gate, &RPC_CALL_TX, request, "no RPC channel").await?;
8689 match rx.await {
8690 Ok(Ok(RpcData::V8(bytes))) => Ok(Vec::<u8>::from(bytes)),
8691 Ok(Ok(RpcData::Json(_))) => Err("RPC answered JSON to a structured-clone call".into()),
8692 Ok(Err(e)) => Err(format!("{e}")),
8693 Err(e) => Err(format!("RPC proxy dropped: {e}")),
8694 }
8695 });
8696 let p = promise_for(scope, id);
8697 rv.set(p);
8698}
8699
8700/// Outbound `fetch` — the op behind the harness's `fetch()`. Resolves to a JSON
8701/// `{status, body, headers}` string.
8702fn op_fetch(
8703 scope: &mut v8::PinScope,
8704 args: v8::FunctionCallbackArguments,
8705 mut rv: v8::ReturnValue<v8::Value>,
8706) {
8707 let context = event_context(scope);
8708 if let Err(error) = context.charge_subrequest() {
8709 return loader_throw(scope, &error);
8710 }
8711 let egress = actor_runtime_state(scope).egress.clone();
8712 // A loaded worker with globalOutbound: null has no ambient egress: it must
8713 // reach the world through `env` capabilities. Message matches workerd.
8714 if egress == EgressPolicy::Deny {
8715 return loader_throw(
8716 scope,
8717 "This worker is not permitted to access the internet via global \
8718 functions like fetch(). It must use capabilities (such as \
8719 bindings in 'env') to talk to the outside world.",
8720 );
8721 }
8722 let method = args.get(0).to_rust_string_lossy(scope);
8723 let url = args.get(1).to_rust_string_lossy(scope);
8724 // A body is a typed array, as it is for `__svc_call`, `__do_call` and
8725 // `__loader_fetch`. `None` and an empty body are different requests — one
8726 // carries no `Content-Length` — so the absent case stays distinct.
8727 let body_arg = args.get(2);
8728 let stream_arg = args.get(5);
8729 let body: Option<RequestBody> = if body_arg.is_undefined() || body_arg.is_null() {
8730 None
8731 } else if stream_arg.is_number() {
8732 Some(RequestBody::Stream(
8733 stream_arg.number_value(scope).unwrap_or(0.0) as u64,
8734 ))
8735 } else {
8736 match view_bytes(body_arg) {
8737 Some(bytes) => Some(RequestBody::Bytes(bytes.into())),
8738 // Answering an unreadable argument with `None` sent the request
8739 // with no body at all: the peer saw something the Worker never
8740 // asked for, and nothing threw and nothing was logged.
8741 None => return loader_throw(scope, "fetch: the request body is not a typed array"),
8742 }
8743 };
8744 let raw_headers = args.get(3).to_rust_string_lossy(scope);
8745 let mut headers: Vec<(String, String)> = match serde_json::from_str(&raw_headers) {
8746 Ok(headers) => headers,
8747 // Same failure as the body: dropping the headers silently sent an
8748 // unauthenticated, unrouted request in place of the real one.
8749 Err(error) => {
8750 return loader_throw(
8751 scope,
8752 &format!("fetch: the request headers are not a name/value list: {error}"),
8753 )
8754 }
8755 };
8756 let redirect = args.get(4).to_rust_string_lossy(scope);
8757 // The harness passes `true` only when the caller supplied an AbortSignal.
8758 // An absent argument is `false`, so a direct caller gets the uncancellable
8759 // request it asked for.
8760 let cancellable = args.get(6).boolean_value(scope);
8761 let mut body_guard = match body.as_ref().and_then(RequestBody::stream_id) {
8762 Some(stream_id) => match current_context().transfer_body_stream(stream_id) {
8763 Some(guard) => guard,
8764 None => return loader_throw(scope, "fetch: the body stream is not owned"),
8765 },
8766 None => RequestBodyGuard(None),
8767 };
8768 // Request validates this value in the harness, but the native op is a
8769 // separate trust boundary. Keep this match exhaustive so a future direct
8770 // caller cannot turn an unknown mode into redirect-following behavior.
8771 match redirect.as_str() {
8772 "follow" | "manual" | "error" => {}
8773 other => return loader_throw(scope, &format!("fetch: unknown redirect mode {other}")),
8774 }
8775 if let EgressPolicy::Broker(broker) = egress {
8776 let (request_id, cancel, cancel_guard) = if cancellable {
8777 let request_id = next_do_request_id();
8778 let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
8779 do_call_cancels()
8780 .lock()
8781 .unwrap()
8782 .insert(request_id, cancel_sender);
8783 (
8784 Some(request_id),
8785 Some(cancel_receiver),
8786 Some(DoCallCancelGuard::new(request_id)),
8787 )
8788 } else {
8789 (None, None, None)
8790 };
8791 let (tx, rx) = tokio::sync::oneshot::channel();
8792 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Fetch);
8793 let request = SvcCallReq {
8794 cancel,
8795 generation: broker.generation,
8796 script: broker.script,
8797 entrypoint: broker.entrypoint,
8798 url,
8799 method,
8800 body: body.unwrap_or_else(|| RequestBody::Bytes(Vec::new().into())),
8801 body_guard,
8802 headers,
8803 reply: tx,
8804 };
8805 let stream_service = http_stream_service();
8806 let id = asyncrt::enqueue(async move {
8807 let mut cancel_guard = cancel_guard;
8808 gated_channel_send(gate, &SVC_CALL_TX, request, "no service binding channel").await?;
8809 let result = match rx.await {
8810 Ok(Ok(response)) => encode_http_response(response, true, &stream_service),
8811 Ok(Err(error)) => Err(format!("{error}")),
8812 Err(error) => Err(format!("globalOutbound Fetcher dropped: {error}")),
8813 };
8814 if let Some(cancel_guard) = cancel_guard.as_mut() {
8815 cancel_guard.disarm();
8816 }
8817 result
8818 });
8819 let promise = promise_for(scope, id);
8820 if let Some(request_id) = request_id {
8821 attach_cancel_id(scope, promise, request_id);
8822 }
8823 rv.set(promise);
8824 return;
8825 }
8826 // Select the client only for direct egress: a broker must not initialize
8827 // an unused network client and its TLS stack.
8828 let client = match redirect.as_str() {
8829 "follow" if context.subrequest_limit.is_some() => context.redirect_counting_client(),
8830 "follow" => HTTP.with(|client| client.clone()),
8831 "manual" => HTTP_MANUAL.with(|client| client.clone()),
8832 "error" => HTTP_ERROR.with(|client| client.clone()),
8833 _ => unreachable!("the redirect mode was validated above"),
8834 };
8835 // The creating context, read here while JS is still running: the op
8836 // future resolves on whatever worker polls it, far from any CPED.
8837 let trace = current_trace_context(scope);
8838 // The child's ids are minted before the request leaves so the
8839 // traceparent header carries them: whatever this fetch reaches can
8840 // join the trace celld is part of.
8841 let child = trace.as_ref().map(crate::telemetry::child_context);
8842 if let Some(child) = child.as_ref() {
8843 if !headers
8844 .iter()
8845 .any(|(name, _)| name.eq_ignore_ascii_case("traceparent"))
8846 {
8847 headers.push(("traceparent".into(), crate::telemetry::traceparent(child)));
8848 }
8849 }
8850 let recording = trace.and_then(crate::telemetry::TraceContext::recording_ids);
8851 let child_recording = child.and_then(crate::telemetry::TraceContext::recording_ids);
8852 let span_url = recording.map(|_| url.clone());
8853 // Whatever this request can reveal must be durable before it leaves: a
8854 // third party that has acted on a write celld then loses cannot be told to
8855 // un-act. That covers a write this handler made and a value it only read,
8856 // because the third party cannot tell the two apart.
8857 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Fetch);
8858 // Shares the cancel registry, the id encoding and the `__do_call_cancel`
8859 // op that a Durable Object call and a service binding call already use.
8860 // Only a caller that supplied an AbortSignal registers: without one there
8861 // is nothing that can cancel, and the op then costs no registry entry.
8862 let (request_id, cancel, cancel_guard) = if cancellable {
8863 let request_id = next_do_request_id();
8864 let (cancel_sender, cancel_receiver) = tokio::sync::oneshot::channel();
8865 do_call_cancels()
8866 .lock()
8867 .unwrap()
8868 .insert(request_id, cancel_sender);
8869 (
8870 Some(request_id),
8871 Some(cancel_receiver),
8872 Some(DoCallCancelGuard::new(request_id)),
8873 )
8874 } else {
8875 (None, None, None)
8876 };
8877 let stream_service = http_stream_service();
8878 let id = asyncrt::enqueue(async move {
8879 // Held, not disarmed: this op has several early returns, and the guard
8880 // removes its registry entry on every one of them when it drops. The
8881 // cancel it sends then reaches a receiver this block already consumed,
8882 // which is the same no-op as a disarm.
8883 let _cancel_guard = cancel_guard;
8884 let span_started = recording.map(|_| crate::telemetry::now_unix_us());
8885 let mut span = recording.zip(child_recording).map(|(parent, child)| {
8886 let mut span =
8887 crate::telemetry::Span::new(child, "fetch", crate::telemetry::KIND_CLIENT);
8888 span.parent_span_id = Some(parent.span_id);
8889 span.parent_remote = Some(false);
8890 span.url = span_url;
8891 span
8892 });
8893 let mut finish = |ok: bool, status: Option<u16>, error: Option<String>| {
8894 if let Some(mut span) = span.take() {
8895 span.start_unix_us = span_started.unwrap_or_default();
8896 span.duration_us = crate::telemetry::now_unix_us() - span.start_unix_us;
8897 span.ok = ok;
8898 span.http_status = status;
8899 span.error = error;
8900 crate::telemetry::record(span);
8901 }
8902 };
8903 await_egress_gate(gate).await.inspect_err(|error| {
8904 finish(false, None, Some(error.clone()));
8905 })?;
8906 let m = reqwest::Method::from_bytes(method.as_bytes()).unwrap_or(reqwest::Method::GET);
8907 // a timeout bounds a black-hole host: the future settles (Err) instead
8908 // of parking run_loop forever — the hang the Drop guard can't catch.
8909 let fetch_timeout = crate::env_vars::positive_or("CELLD_FETCH_TIMEOUT_S", 120)
8910 .expect("validated CELLD_FETCH_TIMEOUT_S");
8911 let mut rb = client
8912 .request(m, &url)
8913 .timeout(std::time::Duration::from_secs(fetch_timeout));
8914 // reqwest omits Content-Length for an empty Vec, which collapses the
8915 // wire representation of `Some([])` into the representation of
8916 // `None`. Install the zero length here unless the Worker supplied a
8917 // framing header, so the body distinction survives the HTTP client.
8918 let empty_body_needs_length = body
8919 .as_ref()
8920 .is_some_and(|body| matches!(body, RequestBody::Bytes(bytes) if bytes.is_empty()))
8921 && !headers.iter().any(|(name, _)| {
8922 name.eq_ignore_ascii_case("content-length")
8923 || name.eq_ignore_ascii_case("transfer-encoding")
8924 });
8925 for (name, value) in headers {
8926 rb = rb.header(name, value);
8927 }
8928 if let Some(body) = body {
8929 rb = match body {
8930 RequestBody::Bytes(bytes) => rb.body(bytes),
8931 RequestBody::Stream(stream_id) => match body_guard.take_stream(stream_id) {
8932 Ok(stream) => rb.body(reqwest::Body::wrap_stream(stream)),
8933 Err(error) => {
8934 finish(false, None, Some(error.clone()));
8935 return Err(error);
8936 }
8937 },
8938 };
8939 }
8940 if empty_body_needs_length {
8941 rb = rb.header(reqwest::header::CONTENT_LENGTH, 0);
8942 }
8943 // The cancellable window is the request itself: connect, send, and wait
8944 // for the response head. Dropping the send future here closes the
8945 // connection, which is what tells the upstream to stop producing. After
8946 // this point the response body is a registered stream, and
8947 // `__http_stream_cancel` is what ends it.
8948 let sent = match cancel {
8949 Some(cancel) => crate::asyncrt::select_biased! {
8950 "a cancel that is ready wins a tie, so an aborted request never \
8951 hands back a response and never leaves a body stream nobody reads";
8952 _ = cancel => None,
8953 result = rb.send() => Some(result),
8954 },
8955 None => Some(rb.send().await),
8956 };
8957 let Some(sent) = sent else {
8958 let error = "fetch: the request was aborted".to_string();
8959 finish(false, None, Some(error.clone()));
8960 return Err(error);
8961 };
8962 match sent {
8963 Ok(resp) => {
8964 let status = resp.status().as_u16();
8965 let headers = resp
8966 .headers()
8967 .iter()
8968 .map(|(name, value)| {
8969 (
8970 name.as_str().to_string(),
8971 // A header value is decoded as UTF-8 with
8972 // replacement, as workerd decodes it.
8973 String::from_utf8_lossy(value.as_bytes()).into_owned(),
8974 )
8975 })
8976 .collect::<Vec<_>>();
8977 let Some(stream_id) =
8978 stream_service.register_source(HttpStreamSource::Response(resp))
8979 else {
8980 let error = format!("fetch: {HTTP_STREAM_REGISTRATION_CLOSED}");
8981 finish(false, Some(status), Some(error.clone()));
8982 return Err(error);
8983 };
8984 finish(true, Some(status), None);
8985 Ok(serde_json::json!({
8986 "status": status, "streamId": stream_id, "headers": headers,
8987 })
8988 .to_string())
8989 }
8990 Err(e) => {
8991 let error = fetch_request_error(&e);
8992 finish(false, None, Some(error.clone()));
8993 Err(error)
8994 }
8995 }
8996 });
8997 let p = promise_for(scope, id);
8998 if let Some(request_id) = request_id {
8999 attach_cancel_id(scope, p, request_id);
9000 }
9001 rv.set(p);
9002}
9003
9004fn op_asset_fetch(
9005 scope: &mut v8::PinScope,
9006 args: v8::FunctionCallbackArguments,
9007 mut rv: v8::ReturnValue<v8::Value>,
9008) {
9009 let script = args.get(0).to_rust_string_lossy(scope);
9010 let method = args.get(1).to_rust_string_lossy(scope);
9011 let url = args.get(2).to_rust_string_lossy(scope);
9012 let headers: Vec<(String, String)> =
9013 match serde_json::from_str(&args.get(3).to_rust_string_lossy(scope)) {
9014 Ok(headers) => headers,
9015 Err(error) => {
9016 return loader_throw(
9017 scope,
9018 &format!("assets: the request headers are not a name/value list: {error}"),
9019 )
9020 }
9021 };
9022 let generation = current_generation(scope);
9023 let (tx, rx) = tokio::sync::oneshot::channel();
9024 let sent = ASSET_CALL_TX.get().is_some_and(|sender| {
9025 sender
9026 .send(AssetCallReq {
9027 generation,
9028 script,
9029 url,
9030 method,
9031 headers,
9032 reply: tx,
9033 })
9034 .is_ok()
9035 });
9036 let stream_service = http_stream_service();
9037 let id = asyncrt::enqueue(async move {
9038 if !sent {
9039 return Err("no asset resolver channel".to_string());
9040 }
9041 match rx.await {
9042 Ok(Ok(response)) => encode_http_response(response, false, &stream_service),
9043 Ok(Err(error)) => Err(format!("asset fetch: {error}")),
9044 Err(error) => Err(format!("asset resolver dropped: {error}")),
9045 }
9046 });
9047 rv.set(promise_for(scope, id));
9048}
9049
9050fn tee_http_stream(
9051 service: &Arc<HttpStreamService>,
9052 source: HttpTransferredStream,
9053) -> Result<(u64, u64), &'static str> {
9054 let (ids, pump) = prepare_http_stream_tee(service, source)?;
9055 asyncrt::op_handle().spawn(pump);
9056 Ok(ids)
9057}
9058
9059fn op_http_stream_read(
9060 scope: &mut v8::PinScope,
9061 args: v8::FunctionCallbackArguments,
9062 mut rv: v8::ReturnValue<v8::Value>,
9063) {
9064 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9065 let service = http_stream_service();
9066 let read = http_stream_read(service, stream_id);
9067 let id = asyncrt::enqueue(async move {
9068 match read.await? {
9069 Some(bytes) => Ok(asyncrt::OpOut::Bytes(bytes)),
9070 None => Ok(asyncrt::OpOut::Str(HTTP_STREAM_DONE.into())),
9071 }
9072 });
9073 rv.set(promise_for(scope, id));
9074}
9075
9076fn op_http_stream_tee(
9077 scope: &mut v8::PinScope,
9078 args: v8::FunctionCallbackArguments,
9079 mut rv: v8::ReturnValue<v8::Value>,
9080) {
9081 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9082 let service = http_stream_service();
9083 let source = service.checkout_transfer(stream_id, None).ok();
9084 let Some(source) = source else {
9085 let message = v8::String::new(scope, "response stream is no longer available").unwrap();
9086 let exception = v8::Exception::type_error(scope, message);
9087 scope.throw_exception(exception);
9088 return;
9089 };
9090 let ids = match tee_http_stream(&service, source) {
9091 Ok(ids) => ids,
9092 Err(error) => {
9093 let message = v8::String::new(scope, error).unwrap();
9094 let exception = v8::Exception::type_error(scope, message);
9095 scope.throw_exception(exception);
9096 return;
9097 }
9098 };
9099 current_context().replace_body_stream(stream_id, &service, ids);
9100 let json = serde_json::to_string(&ids).unwrap();
9101 rv.set(v8::String::new(scope, &json).unwrap().into());
9102}
9103
9104fn op_http_stream_cancel(
9105 scope: &mut v8::PinScope,
9106 args: v8::FunctionCallbackArguments,
9107 _rv: v8::ReturnValue<v8::Value>,
9108) {
9109 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9110 http_stream_service().cancel_source(stream_id);
9111}
9112
9113fn op_response_stream_create(
9114 scope: &mut v8::PinScope,
9115 _args: v8::FunctionCallbackArguments,
9116 mut rv: v8::ReturnValue<v8::Value>,
9117) {
9118 let (writer, receiver) = tokio::sync::mpsc::channel(1);
9119 let (finished, _) = tokio::sync::watch::channel(false);
9120 let Some(stream_id) = http_stream_service()
9121 .register_response_pair(receiver, ResponseStreamWriter::new(writer, finished))
9122 else {
9123 let message = v8::String::new(scope, HTTP_STREAM_REGISTRATION_CLOSED).unwrap();
9124 let exception = v8::Exception::type_error(scope, message);
9125 scope.throw_exception(exception);
9126 return;
9127 };
9128 rv.set(v8::Number::new(scope, stream_id as f64).into());
9129}
9130
9131fn op_response_stream_write(
9132 scope: &mut v8::PinScope,
9133 args: v8::FunctionCallbackArguments,
9134 mut rv: v8::ReturnValue<v8::Value>,
9135) {
9136 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9137 let bytes = args
9138 .get(1)
9139 .try_cast::<v8::ArrayBufferView>()
9140 .ok()
9141 .map(|view| {
9142 let mut bytes = vec![0; view.byte_length()];
9143 view.copy_contents(&mut bytes);
9144 bytes
9145 });
9146 // A response is gated once, when it is released, but a body that streams
9147 // keeps producing after that. A later chunk can carry a commit that
9148 // another event made after the release, and that chunk leaves the process
9149 // as surely as the response head did. So each chunk takes its own ticket,
9150 // sampled here while JS still runs, exactly as `fetch` does.
9151 //
9152 // The pump in `__bridgeResponseStream` awaits each write before it asks
9153 // the producer for the next chunk, so one chunk is in flight at a time and
9154 // a held chunk cannot overtake a released one. The ticket is taken before
9155 // `response_stream_write` reserves the stream's write activity, so a long
9156 // wait for a proof holds no lease on the stream. The stream's inactivity
9157 // expiry still runs during the wait, so a proof that never lands ends the
9158 // body with an error rather than releasing the chunk, which is the
9159 // direction this gate exists to fail in.
9160 let gate = egress_gate_request(&event_context(scope), celld_logic::Channel::Response);
9161 let service = http_stream_service();
9162 let id = asyncrt::enqueue(async move {
9163 await_egress_gate(gate).await?;
9164 response_stream_write(service, stream_id, bytes).await?;
9165 Ok(String::new())
9166 });
9167 rv.set(promise_for(scope, id));
9168}
9169
9170fn op_response_stream_closed(
9171 scope: &mut v8::PinScope,
9172 args: v8::FunctionCallbackArguments,
9173 mut rv: v8::ReturnValue<v8::Value>,
9174) {
9175 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9176 let (writer, mut finished) = http_stream_service()
9177 .writer_close_watch(stream_id)
9178 .map(|(writer, finished)| (Some(writer), Some(finished)))
9179 .unwrap_or((None, None));
9180 let id = asyncrt::enqueue(async move {
9181 let cancelled = match (writer, finished.as_mut()) {
9182 (Some(writer), Some(finished)) => crate::asyncrt::select_biased! {
9183 "stream completion wins a tie so a completed response is not reported as cancelled";
9184 result = finished.changed() => result.is_err(),
9185 _ = writer.closed() => true,
9186 },
9187 _ => false,
9188 };
9189 Ok(String::from(if cancelled {
9190 "cancelled"
9191 } else {
9192 "finished"
9193 }))
9194 });
9195 rv.set(promise_for(scope, id));
9196}
9197
9198fn op_response_stream_close(
9199 scope: &mut v8::PinScope,
9200 args: v8::FunctionCallbackArguments,
9201 mut rv: v8::ReturnValue<v8::Value>,
9202) {
9203 let stream_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9204 let error = args.get(1).to_rust_string_lossy(scope);
9205 let close = response_stream_close(http_stream_service(), stream_id, error);
9206 let id = asyncrt::enqueue(async move {
9207 close.await?;
9208 Ok(String::new())
9209 });
9210 rv.set(promise_for(scope, id));
9211}
9212
9213/// Timer op behind `setTimeout`: a promise resolving after `ms`.
9214fn op_timer(
9215 scope: &mut v8::PinScope,
9216 args: v8::FunctionCallbackArguments,
9217 mut rv: v8::ReturnValue<v8::Value>,
9218) {
9219 let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9220 let ms = args.get(1).number_value(scope).unwrap_or(0.0).max(0.0) as u64;
9221 let (cancel_tx, mut cancel_rx) = tokio::sync::oneshot::channel();
9222 timer_cancels().lock().unwrap().insert(timer_id, cancel_tx);
9223 let id = asyncrt::enqueue(async move {
9224 crate::asyncrt::select! {
9225 _ = tokio::time::sleep(std::time::Duration::from_millis(ms)) => {}
9226 _ = &mut cancel_rx => {}
9227 }
9228 timer_cancels().lock().unwrap().remove(&timer_id);
9229 Ok(String::new())
9230 });
9231 let p = promise_for(scope, id);
9232 rv.set(p);
9233}
9234
9235/// `__io_context_id(operationDriver = false)` — return the live context id.
9236///
9237/// The default returns the resource origin. A true argument returns the
9238/// operation driver, so a nested block can refuse a retained stale context.
9239fn op_io_context_id(
9240 scope: &mut v8::PinScope,
9241 args: v8::FunctionCallbackArguments,
9242 mut rv: v8::ReturnValue<v8::Value>,
9243) {
9244 let driver = args.get(0).boolean_value(scope);
9245 let id = if driver {
9246 operation_continuation_id(scope).filter(|id| {
9247 actor_runtime_state(scope)
9248 .io_context(*id)
9249 .is_some_and(|context| context.accepts_handed_ops())
9250 })
9251 } else {
9252 current_reaction_io_context(scope).and_then(|context| context.continuation_id())
9253 };
9254 let id = id.map(|id| id.to_string()).unwrap_or_default();
9255 rv.set(v8::String::new(scope, &id).unwrap().into());
9256}
9257
9258fn return_gate_acquisition(
9259 scope: &mut v8::PinScope,
9260 mut rv: v8::ReturnValue<v8::Value>,
9261 event: celld_logic::gate::EventId,
9262 owner: Option<u64>,
9263 promise: v8::Local<v8::Value>,
9264) {
9265 let event = v8::String::new(scope, &event.to_string()).unwrap();
9266 let owner =
9267 v8::String::new(scope, &owner.map(|id| id.to_string()).unwrap_or_default()).unwrap();
9268 let values = [event.into(), owner.into(), promise];
9269 rv.set(v8::Array::new_with_elements(scope, &values).into());
9270}
9271
9272/// `__gate_acquire(scope)` — take the cell's input gate for a
9273/// `blockConcurrencyWhile`, waiting if another block holds it.
9274///
9275/// Answers a promise of the event id, not the id itself. It was synchronous,
9276/// and that was right while a cell's events came off one channel: only one
9277/// ran at a time, a delivery point had already found the gate open, and
9278/// yielding even one microtask reopened a window in which a nested delivery
9279/// could wait on a gate nothing would release. Neither half holds now —
9280/// events are independent tasks, several run at once, and nothing nests —
9281/// so two blocks can meet and the second must queue.
9282fn op_gate_acquire(
9283 scope: &mut v8::PinScope,
9284 args: v8::FunctionCallbackArguments,
9285 rv: v8::ReturnValue<v8::Value>,
9286) {
9287 let cell = args.get(0).to_rust_string_lossy(scope);
9288 let event = NEXT_GATE_EVENT.fetch_add(1, Ordering::Relaxed);
9289 let contexts = current_reaction_io_context(scope).zip(
9290 operation_continuation_id(scope).and_then(|id| actor_runtime_state(scope).io_context(id)),
9291 );
9292 let Some((context, owner_context)) = contexts else {
9293 // A promise can retain user code after its event has retired. It must
9294 // not borrow the context of whichever event happens to run the stale
9295 // reaction's checkpoint.
9296 let promise = rejected_promise(scope, RETIRED_INPUT_GATE);
9297 return_gate_acquisition(scope, rv, event, None, promise);
9298 return;
9299 };
9300 // The harness installs the driver before acquisition. A missing driver
9301 // is rejected above instead of transferring a stale block to its origin.
9302 let owner = owner_context.continuation_id();
9303 // Queued until taken or refused, either way once: the guard counts the
9304 // event out when the future ends, however it ends.
9305 struct Queued {
9306 cell: String,
9307 owner: Option<u64>,
9308 }
9309 impl Queued {
9310 fn new(cell: String, owner: Option<u64>) -> Self {
9311 if let Some(owner) = owner {
9312 *cell_gates()
9313 .lock()
9314 .unwrap()
9315 .entry(cell.clone())
9316 .or_default()
9317 .queued
9318 .entry(owner)
9319 .or_default() += 1;
9320 GATE_ENGAGEMENTS.fetch_add(1, Ordering::Relaxed);
9321 }
9322 Self { cell, owner }
9323 }
9324 }
9325 impl Drop for Queued {
9326 fn drop(&mut self) {
9327 let Some(owner) = self.owner else {
9328 return;
9329 };
9330 let mut gates = cell_gates().lock().unwrap();
9331 let remove = if let Some(gate) = gates.get_mut(&self.cell) {
9332 if let Some(count) = gate.queued.get_mut(&owner) {
9333 *count -= 1;
9334 if *count == 0 {
9335 gate.queued.remove(&owner);
9336 }
9337 }
9338 gate.is_unused()
9339 } else {
9340 false
9341 };
9342 if remove {
9343 gates.remove(&self.cell);
9344 }
9345 drop(gates);
9346 GATE_ENGAGEMENTS.fetch_sub(1, Ordering::Relaxed);
9347 }
9348 }
9349 let mut origin = if Arc::ptr_eq(&context, &owner_context) {
9350 None
9351 } else {
9352 let Some(claim) = context.claim_cross_entry_gate() else {
9353 let promise = rejected_promise(scope, RETIRED_INPUT_GATE);
9354 return_gate_acquisition(scope, rv, event, None, promise);
9355 return;
9356 };
9357 Some(claim)
9358 };
9359 let id = match acquire_cell_gate(&owner_context, &cell, event, owner, &mut origin) {
9360 CellGateAcquisition::Acquired => {
9361 asyncrt::enqueue_io_context(async move { Ok(String::new()) })
9362 }
9363 CellGateAcquisition::Waiting {
9364 mut gate,
9365 mut retirement,
9366 } => {
9367 let queued = Queued::new(cell.clone(), owner);
9368 let context = Arc::downgrade(&owner_context);
9369 asyncrt::enqueue_io_context(async move {
9370 let _queued = queued;
9371 loop {
9372 let outcome = crate::asyncrt::select_biased! {
9373 "a settled gate failure remains visible when its event retires at the same instant";
9374 outcome = &mut gate => Some(outcome),
9375 retired = retirement.wait_for(|retired| *retired) => {
9376 let _ = retired;
9377 None
9378 }
9379 };
9380 let Some(outcome) = outcome else {
9381 return Err(RETIRED_INPUT_GATE.to_string());
9382 };
9383 match outcome {
9384 Ok(Ok(())) => {}
9385 // The block ahead failed and reset the actor. This event
9386 // was sent to that old actor, so it cannot compete for the
9387 // fresh gate.
9388 Ok(Err(failure)) => return Err(failure),
9389 Err(_) => {
9390 return Err("cell stopped while waiting for its input gate".to_string())
9391 }
9392 }
9393 let Some(context) = context.upgrade() else {
9394 return Err(RETIRED_INPUT_GATE.to_string());
9395 };
9396 match acquire_cell_gate(&context, &cell, event, owner, &mut origin) {
9397 CellGateAcquisition::Acquired => {
9398 return Ok(String::new());
9399 }
9400 CellGateAcquisition::Waiting {
9401 gate: next_gate,
9402 retirement: next_retirement,
9403 } => {
9404 gate = next_gate;
9405 retirement = next_retirement;
9406 }
9407 CellGateAcquisition::Retired => return Err(RETIRED_INPUT_GATE.to_string()),
9408 }
9409 }
9410 })
9411 }
9412 CellGateAcquisition::Retired => {
9413 let promise = rejected_promise(scope, RETIRED_INPUT_GATE);
9414 return_gate_acquisition(scope, rv, event, None, promise);
9415 return;
9416 }
9417 };
9418 let promise = promise_for(scope, id);
9419 return_gate_acquisition(scope, rv, event, owner, promise);
9420}
9421
9422/// `__gate_wait(scope)` — settle when the cell's input gate is open.
9423///
9424/// The gate's other side. `op_gate_acquire` is for something that wants to
9425/// *hold* the gate; this is for something that only has to arrive after it,
9426/// which is every event the gate exists to hold back. A drive does this in
9427/// Rust before it begins a turn; an RPC stub op does it here, because it is
9428/// dispatched inside the isolate and never becomes a drive.
9429///
9430/// Rejecting matters as much as resolving: a critical section that failed
9431/// reset the cell, so what waited behind it is refused with the reason
9432/// rather than run against state that no longer exists.
9433fn op_gate_wait(
9434 scope: &mut v8::PinScope,
9435 args: v8::FunctionCallbackArguments,
9436 mut rv: v8::ReturnValue<v8::Value>,
9437) {
9438 let cell = args.get(0).to_rust_string_lossy(scope);
9439 let id = asyncrt::enqueue(async move {
9440 loop {
9441 match cell_gate_wait(&cell) {
9442 None => return Ok(String::new()),
9443 Some(open) => match open.await {
9444 Ok(Ok(())) => {}
9445 Ok(Err(failure)) => return Err(failure),
9446 Err(_) => {
9447 return Err("cell stopped while waiting for its input gate".to_string())
9448 }
9449 },
9450 }
9451 }
9452 });
9453 rv.set(promise_for(scope, id));
9454}
9455
9456/// `__gate_release(scope, event, owner)` — the block is over. The next
9457/// delivery point to run takes whatever queued behind it.
9458fn op_gate_release(
9459 scope: &mut v8::PinScope,
9460 args: v8::FunctionCallbackArguments,
9461 _rv: v8::ReturnValue<v8::Value>,
9462) {
9463 let cell = args.get(0).to_rust_string_lossy(scope);
9464 let event = args.get(1).number_value(scope).unwrap_or_default() as celld_logic::gate::EventId;
9465 let owner = args.get(2).to_rust_string_lossy(scope).parse::<u64>().ok();
9466 // A fourth argument means the block failed and the actor was reset, so
9467 // what queued behind it is refused with that reason rather than
9468 // delivered to a cell whose state is gone.
9469 let failure = args.get(3);
9470 let outcome = if failure.is_null_or_undefined() {
9471 Ok(())
9472 } else {
9473 Err(failure.to_rust_string_lossy(scope))
9474 };
9475 let Some(owner) = owner else {
9476 return;
9477 };
9478 let active = current_context();
9479 let context = if active.continuation_id() == Some(owner) {
9480 Some(active)
9481 } else {
9482 actor_runtime_state(scope).io_context(owner)
9483 };
9484 let Some(context) = context else {
9485 return;
9486 };
9487 if !context.release_input_gate(&cell, event) {
9488 return;
9489 }
9490 release_cell_gate(&cell, event, outcome);
9491}
9492
9493fn op_timer_alloc(
9494 scope: &mut v8::PinScope,
9495 _args: v8::FunctionCallbackArguments,
9496 mut rv: v8::ReturnValue<v8::Value>,
9497) {
9498 let id = v8::Number::new(scope, NEXT_TIMER_ID.fetch_add(1, Ordering::Relaxed) as f64);
9499 rv.set(id.into());
9500}
9501
9502fn op_timer_cancel(
9503 scope: &mut v8::PinScope,
9504 args: v8::FunctionCallbackArguments,
9505 _rv: v8::ReturnValue<v8::Value>,
9506) {
9507 let timer_id = args.get(0).integer_value(scope).unwrap_or(0).max(0) as u64;
9508 if let Some(cancel) = timer_cancels().lock().unwrap().remove(&timer_id) {
9509 let _ = cancel.send(());
9510 }
9511}
9512
9513fn throw_durable_object_id_error(scope: &mut v8::PinScope, message: &str) {
9514 let message = v8::String::new(scope, message).unwrap();
9515 let exception = v8::Exception::type_error(scope, message);
9516 scope.throw_exception(exception);
9517}
9518
9519fn register_actor_name(
9520 scope: &mut v8::PinScope,
9521 actor_scope: &str,
9522 name: Option<&str>,
9523) -> Result<()> {
9524 let Some(name) = name else {
9525 return Ok(());
9526 };
9527 let cell = cell_state(scope)?;
9528 let names_key = v8::String::new(scope, "idNames").unwrap();
9529 let names = cell
9530 .get(scope, names_key.into())
9531 .and_then(|value| value.to_object(scope))
9532 .ok_or_else(|| anyhow!("missing Durable Object name registry"))?;
9533 let actor_scope_key = v8::String::new(scope, actor_scope).unwrap();
9534 if let Some(existing) = names.get(scope, actor_scope_key.into()) {
9535 if !existing.is_undefined() {
9536 if existing.to_rust_string_lossy(scope) == name {
9537 return Ok(());
9538 }
9539 anyhow::bail!("actor name conflicts with active identity for {actor_scope}");
9540 }
9541 }
9542
9543 let (class_name, id) = actor_scope
9544 .split_once(':')
9545 .ok_or_else(|| anyhow!("named Durable Object scope has no class separator"))?;
9546 let namespace_keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
9547 let namespace_keys = cell
9548 .get(scope, namespace_keys_key.into())
9549 .and_then(|value| value.to_object(scope))
9550 .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
9551 let class_name_key = v8::String::new(scope, class_name).unwrap();
9552 let namespace_key = namespace_keys
9553 .get(scope, class_name_key.into())
9554 .filter(|value| value.is_string())
9555 .ok_or_else(|| anyhow!("missing namespace key for Durable Object class {class_name}"))?
9556 .to_rust_string_lossy(scope);
9557 let expected = durable_object_id_hex(&durable_object_id_for_name(&namespace_key, name));
9558 if id != expected {
9559 anyhow::bail!("actor name does not match Durable Object ID for {actor_scope}");
9560 }
9561 storage::set_actor_name(actor_scope, name)?;
9562
9563 let name_value = v8::String::new(scope, name).unwrap();
9564 if !names
9565 .set(scope, actor_scope_key.into(), name_value.into())
9566 .unwrap_or(false)
9567 {
9568 anyhow::bail!("could not register Durable Object name");
9569 }
9570 Ok(())
9571}
9572
9573fn op_do_id(
9574 scope: &mut v8::PinScope,
9575 args: v8::FunctionCallbackArguments,
9576 mut rv: v8::ReturnValue<v8::Value>,
9577) {
9578 use hmac::Mac;
9579
9580 let namespace_key = args.get(0).to_rust_string_lossy(scope);
9581 let operation = args.get(1).to_rust_string_lossy(scope);
9582 let input = args.get(2).to_rust_string_lossy(scope);
9583 let key = durable_object_id_key(&namespace_key);
9584 let mut id = [0_u8; 32];
9585
9586 match operation.as_str() {
9587 "name" => {
9588 id = durable_object_id_for_name(&namespace_key, &input);
9589 rv.set(
9590 v8::String::new(scope, &durable_object_id_hex(&id))
9591 .unwrap()
9592 .into(),
9593 );
9594 return;
9595 }
9596 "unique" => {
9597 if getrandom::fill(&mut id[..16]).is_err() {
9598 throw_durable_object_id_error(scope, "secure random generation failed");
9599 return;
9600 }
9601 }
9602 "validate" => {
9603 let Some(decoded) = decode_durable_object_id(&input) else {
9604 throw_durable_object_id_error(
9605 scope,
9606 "Invalid Durable Object ID: must be 64 hex digits",
9607 );
9608 return;
9609 };
9610 if durable_object_id_hmac(&key, &decoded[..16])
9611 .verify_truncated_left(&decoded[16..])
9612 .is_err()
9613 {
9614 throw_durable_object_id_error(
9615 scope,
9616 "Durable Object ID is not valid for this namespace",
9617 );
9618 return;
9619 }
9620 rv.set(
9621 v8::String::new(scope, &input.to_ascii_lowercase())
9622 .unwrap()
9623 .into(),
9624 );
9625 return;
9626 }
9627 _ => {
9628 throw_durable_object_id_error(scope, "unknown Durable Object ID operation");
9629 return;
9630 }
9631 }
9632
9633 let digest = durable_object_id_hmac(&key, &id[..16])
9634 .finalize()
9635 .into_bytes();
9636 id[16..].copy_from_slice(&digest[..16]);
9637 rv.set(
9638 v8::String::new(scope, &durable_object_id_hex(&id))
9639 .unwrap()
9640 .into(),
9641 );
9642}
9643
9644fn view_bytes(value: v8::Local<v8::Value>) -> Option<Vec<u8>> {
9645 let view = v8::Local::<v8::ArrayBufferView>::try_from(value).ok()?;
9646 let mut bytes = vec![0_u8; view.byte_length()];
9647 view.copy_contents(&mut bytes);
9648 Some(bytes)
9649}
9650
9651fn webcrypto_return_bytes(
9652 scope: &mut v8::PinScope,
9653 mut rv: v8::ReturnValue<v8::Value>,
9654 bytes: &[u8],
9655) {
9656 let buffer = v8::ArrayBuffer::new(scope, bytes.len());
9657 if !bytes.is_empty() {
9658 let store = buffer.get_backing_store();
9659 let destination = unsafe {
9660 std::slice::from_raw_parts_mut(store.data().unwrap().as_ptr() as *mut u8, bytes.len())
9661 };
9662 destination.copy_from_slice(bytes);
9663 }
9664 let view = v8::Uint8Array::new(scope, buffer, 0, bytes.len()).unwrap();
9665 rv.set(view.into());
9666}
9667
9668mod container;
9669mod crypto;
9670mod html_rewriter;
9671mod tcp;
9672#[cfg(celld_internal_tests)]
9673pub use tcp::test_extra_tls_root;
9674mod zlib;
9675
9676fn op_actor_abort(
9677 scope: &mut v8::PinScope,
9678 args: v8::FunctionCallbackArguments,
9679 _rv: v8::ReturnValue<v8::Value>,
9680) {
9681 let Some(context) = current_reaction_io_context(scope) else {
9682 return;
9683 };
9684 let cell = args.get(0).to_rust_string_lossy(scope);
9685 let reason = args.get(1).to_rust_string_lossy(scope);
9686 let state = actor_runtime_state(scope);
9687 state
9688 .pending_puts
9689 .lock()
9690 .expect("pending puts lock poisoned")
9691 .remove(&cell);
9692 *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
9693 error: format!("__CELLD_ACTOR_ABORT__:{reason}"),
9694 actor_scope: Some(cell),
9695 context_id: context.continuation_id(),
9696 });
9697 scope.terminate_execution();
9698}
9699
9700fn op_process_exit(
9701 scope: &mut v8::PinScope,
9702 args: v8::FunctionCallbackArguments,
9703 _rv: v8::ReturnValue<v8::Value>,
9704) {
9705 let code = args.get(0).integer_value(scope).unwrap_or(0);
9706 let Some(context) = current_reaction_or_untracked_io_context(scope) else {
9707 tracing::warn!(
9708 code,
9709 "process.exit called without an active request; ignoring"
9710 );
9711 return;
9712 };
9713 if context.depth() == 0 {
9714 tracing::warn!(
9715 code,
9716 "process.exit called without an active request; ignoring"
9717 );
9718 return;
9719 }
9720 let actor_scope = args.get(1).to_rust_string_lossy(scope);
9721 let actor_scope = (!actor_scope.is_empty()).then_some(actor_scope);
9722 let state = actor_runtime_state(scope);
9723 if let Some(actor_scope) = actor_scope.as_deref() {
9724 state
9725 .pending_puts
9726 .lock()
9727 .expect("pending puts lock poisoned")
9728 .remove(actor_scope);
9729 }
9730 *state.termination.lock().expect("termination lock poisoned") = Some(ExecutionTermination {
9731 error: format!("__CELLD_PROCESS_EXIT__:The Node.js process.exit({code}) API was called."),
9732 actor_scope,
9733 context_id: context.continuation_id(),
9734 });
9735 scope.terminate_execution();
9736}
9737
9738fn op_log(
9739 scope: &mut v8::PinScope,
9740 args: v8::FunctionCallbackArguments,
9741 _rv: v8::ReturnValue<v8::Value>,
9742) {
9743 let mut msg: Vec<String> = (0..args.length())
9744 .map(|i| args.get(i).to_rust_string_lossy(scope))
9745 .collect();
9746 let level = if msg.len() >= 2
9747 && matches!(
9748 msg.first().map(String::as_str),
9749 Some("debug" | "error" | "info" | "log" | "warn")
9750 ) {
9751 msg.remove(0)
9752 } else {
9753 "log".to_string()
9754 };
9755 let body = msg.join(" ");
9756 if let Some(context) = current_reaction_or_untracked_io_context(scope) {
9757 context.record_tail_log(&level, &body);
9758 }
9759 // Correlated by CPED, so a continuation logging after an await — or
9760 // another entry's continuation running in this turn's checkpoint —
9761 // lands on the trace that owns it, not on whoever holds the isolate.
9762 // The record carries the level as its severity, so its body omits the
9763 // prefix that the console line needs.
9764 if crate::telemetry::active() {
9765 if let Some(ids) =
9766 current_trace_context(scope).and_then(crate::telemetry::TraceContext::recording_ids)
9767 {
9768 crate::telemetry::record_log(crate::telemetry::Log {
9769 trace_id: Some(ids.trace_id),
9770 span_id: Some(ids.span_id),
9771 time_unix_us: crate::telemetry::now_unix_us(),
9772 severity: crate::telemetry::Severity::from_console_level(&level),
9773 body: body.clone(),
9774 });
9775 }
9776 }
9777 let displayed = match level.as_str() {
9778 "error" => format!("ERROR {body}"),
9779 "warn" => format!("WARN {body}"),
9780 _ => body,
9781 };
9782 tracing::info!(target: "cell_console", "{}", displayed);
9783}
9784/// `__isolate_condemn(reason)` -> whether this isolate will be replaced.
9785///
9786/// The guest's own verdict that it cannot run here again: the Python bundle
9787/// calls it from Pyodide's fatal hook, where Cloudflare aborts the isolate.
9788/// It condemns only the isolate running the call, so a guest can cost itself
9789/// a cold start and nothing else. `false` for a Dynamic Worker, whose slot
9790/// has no pool to replace it.
9791fn op_isolate_condemn(
9792 scope: &mut v8::PinScope,
9793 args: v8::FunctionCallbackArguments,
9794 mut rv: v8::ReturnValue<v8::Value>,
9795) {
9796 let mut reason = args.get(0).to_rust_string_lossy(scope);
9797 // The reason is guest text bound for the node log.
9798 if let Some((cut, _)) = reason.char_indices().nth(MAX_CONDEMN_REASON_CHARS) {
9799 reason.truncate(cut);
9800 }
9801 let condemned = crate::pool::current_slot().is_some_and(|slot| slot.condemn(&reason));
9802 rv.set(v8::Boolean::new(scope, condemned).into());
9803}
9804
9805const MAX_CONDEMN_REASON_CHARS: usize = 256;
9806
9807fn op_heap_limit_excessively_exceeded(
9808 scope: &mut v8::PinScope,
9809 _args: v8::FunctionCallbackArguments,
9810 mut rv: v8::ReturnValue<v8::Value>,
9811) {
9812 let exceeded = scope
9813 .get_slot::<Arc<HeapLimitState>>()
9814 .is_some_and(|state| state.excessively_exceeded.load(Ordering::Relaxed));
9815 rv.set(v8::Boolean::new(scope, exceeded).into());
9816}
9817/// Whether this isolate is too close to its heap limit to retain more state.
9818fn op_heap_over_admission_share(
9819 scope: &mut v8::PinScope,
9820 _args: v8::FunctionCallbackArguments,
9821 mut rv: v8::ReturnValue<v8::Value>,
9822) {
9823 let state = scope.get_slot::<Arc<HeapLimitState>>().cloned();
9824 let over = match state {
9825 // A condemned isolate admits nothing, whatever the heap now reads.
9826 Some(state)
9827 if state.excessively_exceeded.load(Ordering::Relaxed)
9828 || admission_refusal_forced(&state) =>
9829 {
9830 true
9831 }
9832 Some(state) => heap_share(scope, state.limit) >= HEAP_ADMISSION_SHARE,
9833 None => false,
9834 };
9835 rv.set(v8::Boolean::new(scope, over).into());
9836}
9837#[cfg(celld_internal_tests)]
9838fn op_test_set_heap_limit_excessively_exceeded(
9839 scope: &mut v8::PinScope,
9840 args: v8::FunctionCallbackArguments,
9841 _rv: v8::ReturnValue<v8::Value>,
9842) {
9843 if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() {
9844 state
9845 .excessively_exceeded
9846 .store(args.get(0).boolean_value(scope), Ordering::Relaxed);
9847 }
9848}
9849#[cfg(celld_internal_tests)]
9850fn op_test_force_heap_admission_refusal(
9851 scope: &mut v8::PinScope,
9852 args: v8::FunctionCallbackArguments,
9853 _rv: v8::ReturnValue<v8::Value>,
9854) {
9855 if let Some(state) = scope.get_slot::<Arc<HeapLimitState>>() {
9856 state
9857 .forced_admission_refusal
9858 .store(args.get(0).boolean_value(scope), Ordering::Relaxed);
9859 }
9860}
9861#[cfg(celld_internal_tests)]
9862fn op_test_gc(
9863 scope: &mut v8::PinScope,
9864 _args: v8::FunctionCallbackArguments,
9865 _rv: v8::ReturnValue<v8::Value>,
9866) {
9867 scope.request_garbage_collection_for_testing(v8::GarbageCollectionType::Full);
9868}
9869
9870#[cfg(celld_internal_tests)]
9871thread_local! {
9872 static FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION: std::cell::Cell<bool> = const {
9873 std::cell::Cell::new(false)
9874 };
9875 static FAIL_NEXT_WORKFLOW_META_CREATION: std::cell::Cell<bool> = const {
9876 std::cell::Cell::new(false)
9877 };
9878 static FAIL_NEXT_WORKFLOW_TERMINAL_ALARM_SET: std::cell::Cell<bool> = const {
9879 std::cell::Cell::new(false)
9880 };
9881 static FAIL_NEXT_QUEUE_DLQ_ACCEPT: std::cell::Cell<bool> = const {
9882 std::cell::Cell::new(false)
9883 };
9884 static QUEUE_DLQ_ACCEPT_CALLS: std::cell::Cell<usize> = const {
9885 std::cell::Cell::new(0)
9886 };
9887 static QUEUE_METRICS_MATERIALIZED: std::cell::Cell<bool> = const {
9888 std::cell::Cell::new(false)
9889 };
9890 static QUEUE_PRODUCER_GROUPS: std::cell::RefCell<Vec<(usize, usize)>> = const {
9891 std::cell::RefCell::new(Vec::new())
9892 };
9893 static QUEUE_PRODUCER_WRITE_POSITIONS: std::cell::RefCell<Vec<Option<u64>>> = const {
9894 std::cell::RefCell::new(Vec::new())
9895 };
9896 static QUEUE_REARM_OBSERVED: std::cell::Cell<bool> = const {
9897 std::cell::Cell::new(false)
9898 };
9899 static QUEUE_REARM_POSITIVE: std::cell::Cell<bool> = const {
9900 std::cell::Cell::new(false)
9901 };
9902 static QUEUE_REARM_BOUND_VIOLATED: std::cell::Cell<bool> = const {
9903 std::cell::Cell::new(false)
9904 };
9905 static QUEUE_SETTLEMENT_POLICY_OBSERVED: std::cell::Cell<bool> = const {
9906 std::cell::Cell::new(false)
9907 };
9908 static QUEUE_LEASE_LOOKUP_PLANS: std::cell::RefCell<Vec<String>> = const {
9909 std::cell::RefCell::new(Vec::new())
9910 };
9911 static KV_LIST_PLANS: std::cell::RefCell<Vec<String>> = const {
9912 std::cell::RefCell::new(Vec::new())
9913 };
9914}
9915
9916#[cfg(celld_internal_tests)]
9917#[doc(hidden)]
9918pub fn fail_next_workflow_event_consumption_for_test() {
9919 FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION.with(|fail| fail.set(true));
9920}
9921
9922#[cfg(celld_internal_tests)]
9923#[doc(hidden)]
9924pub fn fail_next_workflow_meta_creation_for_test() {
9925 FAIL_NEXT_WORKFLOW_META_CREATION.with(|fail| fail.set(true));
9926}
9927
9928#[cfg(celld_internal_tests)]
9929#[doc(hidden)]
9930pub fn fail_next_workflow_terminal_alarm_set_for_test() {
9931 FAIL_NEXT_WORKFLOW_TERMINAL_ALARM_SET.with(|fail| fail.set(true));
9932}
9933
9934#[cfg(celld_internal_tests)]
9935#[doc(hidden)]
9936pub fn fail_next_queue_dlq_accept_for_test() {
9937 FAIL_NEXT_QUEUE_DLQ_ACCEPT.with(|fail| fail.set(true));
9938}
9939
9940#[cfg(celld_internal_tests)]
9941pub fn reset_queue_dlq_accept_calls_for_test() {
9942 QUEUE_DLQ_ACCEPT_CALLS.with(|calls| calls.set(0));
9943}
9944
9945#[cfg(celld_internal_tests)]
9946#[doc(hidden)]
9947pub fn queue_dlq_accept_calls_for_test() -> usize {
9948 QUEUE_DLQ_ACCEPT_CALLS.with(std::cell::Cell::get)
9949}
9950
9951#[cfg(celld_internal_tests)]
9952pub fn reset_queue_hot_path_observations_for_test() {
9953 QUEUE_METRICS_MATERIALIZED.with(|observed| observed.set(false));
9954 QUEUE_REARM_OBSERVED.with(|observed| observed.set(false));
9955 QUEUE_REARM_POSITIVE.with(|observed| observed.set(false));
9956 QUEUE_REARM_BOUND_VIOLATED.with(|violated| violated.set(false));
9957}
9958
9959#[cfg(celld_internal_tests)]
9960#[doc(hidden)]
9961pub fn queue_hot_path_observations_for_test() -> (bool, bool, bool) {
9962 let materialized = QUEUE_METRICS_MATERIALIZED.with(std::cell::Cell::get);
9963 let bounded = QUEUE_REARM_OBSERVED.with(std::cell::Cell::get)
9964 && QUEUE_REARM_POSITIVE.with(std::cell::Cell::get)
9965 && !QUEUE_REARM_BOUND_VIOLATED.with(std::cell::Cell::get);
9966 let violated = QUEUE_REARM_BOUND_VIOLATED.with(std::cell::Cell::get);
9967 (materialized, bounded, violated)
9968}
9969
9970#[cfg(celld_internal_tests)]
9971pub fn reset_queue_producer_groups_for_test() {
9972 QUEUE_PRODUCER_GROUPS.with(|groups| groups.borrow_mut().clear());
9973 QUEUE_PRODUCER_WRITE_POSITIONS.with(|positions| positions.borrow_mut().clear());
9974}
9975
9976#[cfg(celld_internal_tests)]
9977#[doc(hidden)]
9978pub fn queue_producer_groups_for_test() -> Vec<(usize, usize)> {
9979 QUEUE_PRODUCER_GROUPS.with(|groups| groups.borrow().clone())
9980}
9981
9982#[cfg(celld_internal_tests)]
9983#[doc(hidden)]
9984pub fn queue_producer_write_positions_for_test() -> Vec<Option<u64>> {
9985 QUEUE_PRODUCER_WRITE_POSITIONS.with(|positions| positions.borrow().clone())
9986}
9987
9988#[cfg(celld_internal_tests)]
9989#[doc(hidden)]
9990pub fn reset_queue_lease_lookup_plans_for_test() {
9991 QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow_mut().clear());
9992}
9993
9994#[cfg(celld_internal_tests)]
9995#[doc(hidden)]
9996pub fn queue_lease_lookup_plans_for_test() -> Vec<String> {
9997 QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow().clone())
9998}
9999
10000#[cfg(celld_internal_tests)]
10001#[doc(hidden)]
10002pub fn reset_kv_list_plans_for_test() {
10003 KV_LIST_PLANS.with(|plans| plans.borrow_mut().clear());
10004}
10005
10006#[cfg(celld_internal_tests)]
10007#[doc(hidden)]
10008pub fn kv_list_plans_for_test() -> Vec<String> {
10009 KV_LIST_PLANS.with(|plans| plans.borrow().clone())
10010}
10011
10012#[cfg(celld_internal_tests)]
10013#[doc(hidden)]
10014pub fn reset_queue_settlement_policy_observation_for_test() {
10015 QUEUE_SETTLEMENT_POLICY_OBSERVED.with(|observed| observed.set(false));
10016}
10017
10018#[cfg(celld_internal_tests)]
10019#[doc(hidden)]
10020pub fn queue_settlement_policy_observed_for_test() -> bool {
10021 QUEUE_SETTLEMENT_POLICY_OBSERVED.with(std::cell::Cell::get)
10022}
10023
10024#[cfg(celld_internal_tests)]
10025fn op_test_workflow_event_consumed(
10026 scope: &mut v8::PinScope,
10027 _args: v8::FunctionCallbackArguments,
10028 _rv: v8::ReturnValue<v8::Value>,
10029) {
10030 let fail = FAIL_NEXT_WORKFLOW_EVENT_CONSUMPTION.with(|fail| fail.replace(false));
10031 if fail {
10032 throw_storage_error(
10033 scope,
10034 "workflow event consumption",
10035 "injected failure after workflow event delete",
10036 );
10037 }
10038}
10039
10040#[cfg(celld_internal_tests)]
10041fn op_test_workflow_meta_created(
10042 scope: &mut v8::PinScope,
10043 _args: v8::FunctionCallbackArguments,
10044 _rv: v8::ReturnValue<v8::Value>,
10045) {
10046 let fail = FAIL_NEXT_WORKFLOW_META_CREATION.with(|fail| fail.replace(false));
10047 if fail {
10048 throw_storage_error(
10049 scope,
10050 "workflow creation",
10051 "injected failure after workflow metadata write",
10052 );
10053 }
10054}
10055
10056#[cfg(celld_internal_tests)]
10057fn op_test_workflow_terminal_alarm_set(
10058 scope: &mut v8::PinScope,
10059 _args: v8::FunctionCallbackArguments,
10060 _rv: v8::ReturnValue<v8::Value>,
10061) {
10062 let fail = FAIL_NEXT_WORKFLOW_TERMINAL_ALARM_SET.with(|fail| fail.replace(false));
10063 if fail {
10064 throw_storage_error(
10065 scope,
10066 "workflow terminal alarm installation",
10067 "injected failure after workflow terminal alarm installation",
10068 );
10069 }
10070}
10071
10072#[cfg(celld_internal_tests)]
10073fn op_test_queue_dlq_accepted(
10074 scope: &mut v8::PinScope,
10075 _args: v8::FunctionCallbackArguments,
10076 _rv: v8::ReturnValue<v8::Value>,
10077) {
10078 QUEUE_DLQ_ACCEPT_CALLS.with(|calls| calls.set(calls.get() + 1));
10079 let fail = FAIL_NEXT_QUEUE_DLQ_ACCEPT.with(|fail| fail.replace(false));
10080 if fail {
10081 throw_storage_error(
10082 scope,
10083 "Queue DLQ transfer",
10084 "injected failure after the target accepted the message",
10085 );
10086 }
10087}
10088
10089#[cfg(celld_internal_tests)]
10090fn op_test_queue_metrics_materialized(
10091 _scope: &mut v8::PinScope,
10092 _args: v8::FunctionCallbackArguments,
10093 _rv: v8::ReturnValue<v8::Value>,
10094) {
10095 QUEUE_METRICS_MATERIALIZED.with(|observed| observed.set(true));
10096}
10097
10098#[cfg(celld_internal_tests)]
10099fn op_test_queue_producer_group(
10100 scope: &mut v8::PinScope,
10101 args: v8::FunctionCallbackArguments,
10102 _rv: v8::ReturnValue<v8::Value>,
10103) {
10104 let calls = args.get(0).integer_value(scope).unwrap_or(0).max(0) as usize;
10105 let messages = args.get(1).integer_value(scope).unwrap_or(0).max(0) as usize;
10106 QUEUE_PRODUCER_GROUPS.with(|groups| groups.borrow_mut().push((calls, messages)));
10107}
10108
10109#[cfg(celld_internal_tests)]
10110fn op_test_queue_lease_lookup_plan(
10111 scope: &mut v8::PinScope,
10112 args: v8::FunctionCallbackArguments,
10113 _rv: v8::ReturnValue<v8::Value>,
10114) {
10115 let plan = args.get(0).to_rust_string_lossy(scope);
10116 QUEUE_LEASE_LOOKUP_PLANS.with(|plans| plans.borrow_mut().push(plan));
10117}
10118
10119#[cfg(celld_internal_tests)]
10120fn op_test_kv_list_plan(
10121 scope: &mut v8::PinScope,
10122 args: v8::FunctionCallbackArguments,
10123 _rv: v8::ReturnValue<v8::Value>,
10124) {
10125 let plan = args.get(0).to_rust_string_lossy(scope);
10126 KV_LIST_PLANS.with(|plans| plans.borrow_mut().push(plan));
10127}
10128
10129#[cfg(celld_internal_tests)]
10130fn op_test_queue_rearm_bounded(
10131 scope: &mut v8::PinScope,
10132 args: v8::FunctionCallbackArguments,
10133 _rv: v8::ReturnValue<v8::Value>,
10134) {
10135 QUEUE_REARM_OBSERVED.with(|observed| observed.set(true));
10136 QUEUE_REARM_POSITIVE.with(|observed| observed.set(observed.get() || args.get(1).is_true()));
10137 if !args.get(0).boolean_value(scope) {
10138 QUEUE_REARM_BOUND_VIOLATED.with(|violated| violated.set(true));
10139 }
10140}
10141// `celld r2` writes an object a binding then reads, so the operator command
10142// calls the very functions the ops call rather than a second implementation
10143// of the object record.
10144pub(crate) mod r2_ops;
10145mod storage_ops;
10146use storage_ops::{actor_runtime_state, throw_storage_error};
10147
10148/// $$urlParse(input, base?) -> {protocol,username,password,host,port,pathname,search,hash,href}
10149/// Backed by the WHATWG-conformant `url` crate.
10150fn op_url_parse(
10151 scope: &mut v8::PinScope,
10152 args: v8::FunctionCallbackArguments,
10153 mut rv: v8::ReturnValue<v8::Value>,
10154) {
10155 let input = args.get(0).to_rust_string_lossy(scope);
10156 let base = args.get(1);
10157 let parsed = if base.is_undefined() {
10158 url::Url::parse(&input)
10159 } else {
10160 url::Url::options()
10161 .base_url(
10162 url::Url::parse(&base.to_rust_string_lossy(scope))
10163 .ok()
10164 .as_ref(),
10165 )
10166 .parse(&input)
10167 };
10168 let u = match parsed {
10169 Ok(u) => u,
10170 Err(e) => {
10171 let msg = v8::String::new(scope, &format!("Invalid URL: {e}")).unwrap();
10172 let exc = v8::Exception::type_error(scope, msg);
10173 scope.throw_exception(exc);
10174 return;
10175 }
10176 };
10177 let o = v8::Object::new(scope);
10178 // The nine keys are fixed, so they come from the constant table rather
10179 // than from nine fresh `v8::String`s per `new URL(...)`.
10180 //
10181 // A set can still fail — a throwing setter on `Object.prototype` reaches
10182 // this plain object — and a URL record missing a component is worse than
10183 // no record at all, so the first refusal stops the build.
10184 let port = u.port().map(|p| p.to_string()).unwrap_or_default();
10185 let fields: [(&'static v8::OneByteConst, &str); 9] = [
10186 (&v8_strings::URL_PROTOCOL, u.scheme()),
10187 (&v8_strings::URL_USERNAME, u.username()),
10188 (&v8_strings::URL_PASSWORD, u.password().unwrap_or("")),
10189 (&v8_strings::URL_HOST, u.host_str().unwrap_or("")),
10190 (&v8_strings::URL_PORT, &port),
10191 (&v8_strings::URL_PATHNAME, u.path()),
10192 (&v8_strings::URL_SEARCH, u.query().unwrap_or("")),
10193 (&v8_strings::URL_HASH, u.fragment().unwrap_or("")),
10194 (&v8_strings::URL_HREF, u.as_str()),
10195 ];
10196 for (k, v) in fields {
10197 let key = static_key(scope, k);
10198 let val = v8::String::new(scope, v).unwrap();
10199 match o.set(scope, key.into(), val.into()) {
10200 Some(true) => {}
10201 // The setter threw. Its exception is already pending, and it names
10202 // the real cause, so it propagates unchanged. Throwing a generic
10203 // TypeError here would overwrite it and hide that cause.
10204 None => return,
10205 // A refusal that does not throw — a non-writable inherited data
10206 // property, in sloppy mode — leaves no pending exception, so this
10207 // path has to raise one of its own.
10208 Some(false) => {
10209 let name = key.to_rust_string_lossy(scope);
10210 let msg = v8::String::new(
10211 scope,
10212 &format!("Invalid URL: the {name} property of the URL record was refused"),
10213 )
10214 .unwrap();
10215 let exc = v8::Exception::type_error(scope, msg);
10216 scope.throw_exception(exc);
10217 return;
10218 }
10219 }
10220 }
10221 rv.set(o.into());
10222}
10223
10224// URLPattern host seam, split like Deno's: pattern parsing and match-input
10225// canonicalization run in Rust via the `urlpattern` crate; per-match regex
10226// execution stays in JS `RegExp` (src/js/url_pattern.js). JSON is the
10227// boundary — both ops run at construct/match-canonicalize time only.
10228
10229/// `$$urlPatternParse(inputJson, baseURL?, ignoreCase)` -> json. Input is a
10230/// pattern string or an init object of string components. Returns
10231/// per-component `{ patternString, regexpString, groupNameList }` plus
10232/// `hasRegexpGroups`. Throws TypeError on an invalid pattern.
10233fn op_urlpattern_parse(
10234 scope: &mut v8::PinScope,
10235 args: v8::FunctionCallbackArguments,
10236 mut rv: v8::ReturnValue<v8::Value>,
10237) {
10238 use urlpattern::quirks;
10239 let input = args.get(0).to_rust_string_lossy(scope);
10240 let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
10241 let base = args.get(1);
10242 let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
10243 let options = urlpattern::UrlPatternOptions {
10244 ignore_case: args.get(2).boolean_value(scope),
10245 };
10246 let pattern = quirks::process_construct_pattern_input(input, base.as_deref())
10247 .and_then(|init| quirks::parse_pattern(init, options));
10248 let p = match pattern {
10249 Ok(p) => p,
10250 Err(e) => {
10251 let msg = v8::String::new(scope, &e.to_string()).unwrap();
10252 let exc = v8::Exception::type_error(scope, msg);
10253 scope.throw_exception(exc);
10254 return;
10255 }
10256 };
10257 let component = |c: &quirks::UrlPatternComponent| {
10258 serde_json::json!({
10259 "patternString": c.pattern_string,
10260 "regexpString": c.regexp_string,
10261 "groupNameList": c.group_name_list,
10262 })
10263 };
10264 let out = serde_json::json!({
10265 "protocol": component(&p.protocol),
10266 "username": component(&p.username),
10267 "password": component(&p.password),
10268 "hostname": component(&p.hostname),
10269 "port": component(&p.port),
10270 "pathname": component(&p.pathname),
10271 "search": component(&p.search),
10272 "hash": component(&p.hash),
10273 "hasRegexpGroups": p.has_regexp_groups,
10274 });
10275 rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
10276}
10277
10278/// `$$urlPatternMatchInput(inputJson, baseURL?)` -> json `[8 strings]` in
10279/// component order (protocol..hash), or `null` when the input does not parse
10280/// as a URL. Throws TypeError for an init combined with a baseURL argument.
10281fn op_urlpattern_match_input(
10282 scope: &mut v8::PinScope,
10283 args: v8::FunctionCallbackArguments,
10284 mut rv: v8::ReturnValue<v8::Value>,
10285) {
10286 use urlpattern::quirks;
10287 let input = args.get(0).to_rust_string_lossy(scope);
10288 let input: quirks::StringOrInit = serde_json::from_str(&input).unwrap();
10289 let base = args.get(1);
10290 let base = (!base.is_undefined()).then(|| base.to_rust_string_lossy(scope));
10291 let null = v8::null(scope).into();
10292 let m = match quirks::process_match_input(input, base.as_deref()) {
10293 Ok(Some((input_, _inputs))) => match quirks::parse_match_input(input_) {
10294 Some(m) => m,
10295 None => return rv.set(null),
10296 },
10297 Ok(None) => return rv.set(null),
10298 Err(e) => {
10299 let msg = v8::String::new(scope, &e.to_string()).unwrap();
10300 let exc = v8::Exception::type_error(scope, msg);
10301 scope.throw_exception(exc);
10302 return;
10303 }
10304 };
10305 let out = serde_json::json!([
10306 m.protocol, m.username, m.password, m.hostname, m.port, m.pathname, m.search, m.hash,
10307 ]);
10308 rv.set(v8::String::new(scope, &out.to_string()).unwrap().into());
10309}
10310
10311fn op_atob(
10312 scope: &mut v8::PinScope,
10313 args: v8::FunctionCallbackArguments,
10314 mut rv: v8::ReturnValue<v8::Value>,
10315) {
10316 use base64::engine::{GeneralPurpose, GeneralPurposeConfig};
10317 use base64::Engine;
10318 let input = args.get(0).to_rust_string_lossy(scope);
10319 // https://infra.spec.whatwg.org/#forgiving-base64-decode
10320 //
10321 // Only the five ASCII whitespace characters are ignored. `is_whitespace`
10322 // covers the Unicode White_Space property, so it also stripped U+00A0 and
10323 // U+3000 and made `atob("YQ==\u{a0}")` decode, which Workerd rejects.
10324 let cleaned: Vec<u8> = input
10325 .bytes()
10326 .filter(|b| !matches!(b, b'\t' | b'\n' | b'\x0c' | b'\r' | b' '))
10327 .collect();
10328 let mut data = cleaned.as_slice();
10329 if data.len().is_multiple_of(4) {
10330 data = data
10331 .strip_suffix(b"==")
10332 .or_else(|| data.strip_suffix(b"="))
10333 .unwrap_or(data);
10334 }
10335 // Padding is removed above, so the decoder must now reject every `=` that
10336 // is left. `RequireNone` is the mode that does this; `Indifferent` would
10337 // accept the malformed partial padding of `atob("YQ=")`, which Workerd
10338 // rejects. `allow_trailing_bits` is what makes the decode forgiving: the
10339 // spec discards the unused trailing bits of an unpadded group even when
10340 // they are not zero, so `atob("YR==")` returns "a" instead of throwing.
10341 const FORGIVING: GeneralPurpose = GeneralPurpose::new(
10342 &base64::alphabet::STANDARD,
10343 GeneralPurposeConfig::new()
10344 .with_decode_padding_mode(base64::engine::DecodePaddingMode::RequireNone)
10345 .with_decode_allow_trailing_bits(true),
10346 );
10347 match FORGIVING.decode(data) {
10348 Ok(bytes) => {
10349 // The public `atob()` wrapper omits this argument and keeps the
10350 // required binary-string result. The KV operator protocol asks
10351 // for a typed view, so a 25 MiB value does not become 25 million
10352 // JavaScript numbers before the cell can store it.
10353 if args.get(1).boolean_value(scope) {
10354 rv.set(bytes_value(scope, bytes));
10355 return;
10356 }
10357 // atob returns a binary string (latin1)
10358 let s: String = bytes.iter().map(|&b| b as char).collect();
10359 rv.set(v8::String::new(scope, &s).unwrap().into());
10360 }
10361 Err(_) => {
10362 let msg = v8::String::new(scope, "Invalid base64").unwrap();
10363 let exc = v8::Exception::error(scope, msg);
10364 scope.throw_exception(exc);
10365 }
10366 }
10367}
10368
10369// node:util introspection seam: V8-level queries that JS cannot perform,
10370// mirroring Workerd's C++ `node-internal:util` builtin. Only the lazy
10371// node:async_hooks prelude calls these. The value is V8's
10372// continuation-preserved embedder data — the primitive Workerd's
10373// AsyncContextFrame rides — which V8 itself captures and restores
10374// around every promise reaction. No promise hooks are installed. A stateless
10375// isolate that never touches AsyncLocalStorage leaves the frame absent; a cell
10376// event still carries the separate native context token described below.
10377
10378#[derive(Default)]
10379struct IoEventFrame {
10380 wait_until: Vec<v8::Global<v8::Promise>>,
10381 arm_gates: Vec<ArmGateRx>,
10382}
10383
10384#[derive(Default)]
10385struct IoEventState {
10386 frames: Vec<IoEventFrame>,
10387 /// Registrations made by active `waitUntil` work after the handler's
10388 /// frame ended. The driver folds each batch into a new aggregate before
10389 /// it retires the event, so one callback can extend the same lifetime.
10390 late_wait_until: Vec<v8::Global<v8::Promise>>,
10391 /// True from the top-level frame's first non-empty drain until the driver
10392 /// observes that drain settled with no later registrations. Keeping this
10393 /// state on the request prevents a foreign event in the same isolate from
10394 /// lending or taking away registration authority.
10395 wait_until_active: bool,
10396 ended_arm_gates: Vec<ArmGateRx>,
10397 arm_gates_sealed: bool,
10398}
10399
10400/// The writable directory subset of Workerd's per-request virtual filesystem.
10401///
10402/// The first compatibility slice stores directories only. Keeping the tree on
10403/// `IoContext` is the isolation mechanism: async continuations for one request
10404/// share it, while a concurrent or later request receives a different tree.
10405/// No path can escape into the host filesystem.
10406struct RequestVfs {
10407 nodes: HashMap<String, VfsNode>,
10408}
10409
10410/// Keep the node kind in the tree, even while the first slice can only create
10411/// directories. Deno's VFS uses the same entry-typed shape; a path-only set
10412/// would make a later file node indistinguishable from its parent directory.
10413enum VfsNode {
10414 Directory { writable: bool },
10415}
10416
10417/// The read-only `/bundle` projection of a worker's own modules.
10418///
10419/// This is isolate state, not request state. The bytes are immutable and
10420/// identical for every request the isolate serves, so building the tree per
10421/// request would repeat the work and re-copy every module body. `BundleFs`
10422/// below keeps one `Arc` and hands a clone to each reader.
10423struct BundleTree {
10424 nodes: HashMap<String, BundleNode>,
10425}
10426
10427/// A projected node. A file owns `Bytes` so a read is a refcount bump rather
10428/// than a copy, and so a wasm module's bytes are shared with the config
10429/// instead of duplicated.
10430enum BundleNode {
10431 Directory,
10432 File(bytes::Bytes),
10433}
10434
10435/// The bundle tree and the config it projects, materialized on first use.
10436///
10437/// Workerd builds `/bundle` through a lazy directory for the same reason (see
10438/// `getBundleDirectory` in `src/workerd/io/bundle-fs.c++`): a worker that never
10439/// calls `node:fs` must not pay to walk its module list or to copy a module
10440/// body into the filesystem. Holding the `Arc<WorkerConfig>` keeps the source
10441/// alive, so materialization does not need its own copy of a module name.
10442struct BundleFs {
10443 config: Arc<WorkerConfig>,
10444 tree: OnceLock<Arc<BundleTree>>,
10445}
10446
10447impl BundleFs {
10448 /// Materialize once, then share. Returns an `Arc` clone so a caller can
10449 /// read without holding an isolate borrow across the read.
10450 fn tree(&self) -> Arc<BundleTree> {
10451 self.tree
10452 .get_or_init(|| Arc::new(BundleTree::project(&self.config)))
10453 .clone()
10454 }
10455}
10456
10457impl BundleTree {
10458 /// Project every bundle module into `/bundle`, keyed by its name as a path.
10459 ///
10460 /// A module name is a path, not a flat key: workerd parses it against
10461 /// `file:///`, so `a/esModule` becomes `/bundle/a/esModule` and creates the
10462 /// intervening directory. The entry module is projected under the name it
10463 /// compiles as, matching workerd's `mainScriptName` entry.
10464 fn project(config: &WorkerConfig) -> Self {
10465 let mut nodes = HashMap::new();
10466 nodes.insert("/bundle".to_string(), BundleNode::Directory);
10467 let entry = std::iter::once((
10468 ENTRY_MODULE_NAME,
10469 bytes::Bytes::copy_from_slice(config.src.as_bytes()),
10470 ));
10471 let modules = config.modules.iter().map(|(name, source)| {
10472 let bytes = match source {
10473 // A text or ES module body is a `String` in the config, so the
10474 // projection copies it once per isolate. A wasm body is already
10475 // `Bytes`, so it is shared rather than copied.
10476 ModuleSource::Text(source) | ModuleSource::EsModule(source) => {
10477 bytes::Bytes::copy_from_slice(source.as_bytes())
10478 }
10479 ModuleSource::Wasm(bytes) => bytes.clone(),
10480 };
10481 (name.as_str(), bytes)
10482 });
10483 for (name, bytes) in entry.chain(modules) {
10484 // A leading or doubled separator would otherwise create an empty
10485 // segment, which no path can address.
10486 let segments: Vec<&str> = name.split('/').filter(|part| !part.is_empty()).collect();
10487 let Some((file, directories)) = segments.split_last() else {
10488 continue;
10489 };
10490 let mut path = String::from("/bundle");
10491 for directory in directories {
10492 path.push('/');
10493 path.push_str(directory);
10494 nodes.entry(path.clone()).or_insert(BundleNode::Directory);
10495 }
10496 path.push('/');
10497 path.push_str(file);
10498 nodes.insert(path, BundleNode::File(bytes));
10499 }
10500 Self { nodes }
10501 }
10502}
10503
10504enum VfsMkdirResult {
10505 Created(Option<String>),
10506 Error(&'static str),
10507}
10508
10509impl Default for RequestVfs {
10510 fn default() -> Self {
10511 Self {
10512 nodes: [
10513 ("/", false),
10514 ("/bundle", false),
10515 ("/dev", false),
10516 ("/tmp", true),
10517 ]
10518 .into_iter()
10519 .map(|(path, writable)| (path.to_string(), VfsNode::Directory { writable }))
10520 .collect(),
10521 }
10522 }
10523}
10524
10525struct InputGateClaims {
10526 /// Set before the turn owner releases its final `IoContext` owner. The
10527 /// watch wakes its pending gate acquisition even when the promise
10528 /// reaction that requested the gate belongs to another event.
10529 retired: bool,
10530 held: HashMap<celld_logic::gate::EventId, String>,
10531 retirement: tokio::sync::watch::Sender<bool>,
10532}
10533
10534impl Default for InputGateClaims {
10535 fn default() -> Self {
10536 let (retirement, _) = tokio::sync::watch::channel(false);
10537 Self {
10538 retired: false,
10539 held: HashMap::new(),
10540 retirement,
10541 }
10542 }
10543}
10544
10545impl RequestVfs {
10546 fn stat(&self, path: &str) -> Option<bool> {
10547 self.nodes.get(path).map(|node| match node {
10548 VfsNode::Directory { writable } => *writable,
10549 })
10550 }
10551
10552 fn mkdir(&mut self, path: &str, recursive: bool) -> VfsMkdirResult {
10553 if path != "/tmp" && !path.starts_with("/tmp/") {
10554 return VfsMkdirResult::Error("EPERM");
10555 }
10556 if self.stat(path).is_some() {
10557 return VfsMkdirResult::Created(None);
10558 }
10559 if recursive {
10560 let mut current = "/tmp".to_string();
10561 let mut first_created = None;
10562 for segment in path.trim_start_matches("/tmp/").split('/') {
10563 current.push('/');
10564 current.push_str(segment);
10565 if self
10566 .nodes
10567 .insert(current.clone(), VfsNode::Directory { writable: true })
10568 .is_none()
10569 && first_created.is_none()
10570 {
10571 first_created = Some(current.clone());
10572 }
10573 }
10574 return VfsMkdirResult::Created(first_created);
10575 }
10576 let parent =
10577 path.rsplit_once('/').map_or(
10578 "/",
10579 |(parent, _)| {
10580 if parent.is_empty() {
10581 "/"
10582 } else {
10583 parent
10584 }
10585 },
10586 );
10587 if self.stat(parent).is_none() {
10588 return VfsMkdirResult::Error("ENOENT");
10589 }
10590 self.nodes
10591 .insert(path.to_string(), VfsNode::Directory { writable: true });
10592 VfsMkdirResult::Created(None)
10593 }
10594}
10595
10596/// The per-request context: everything a request owns while it is in flight.
10597///
10598/// Modelled on workerd's `IoContext`. The host owns it, not JS: a request's
10599/// event frames and the `waitUntil` promises inside them live here, and JS
10600/// reaches them only through ops that ask for the *current* context. That
10601/// inversion is the point. While an isolate serves one request at a time,
10602/// JS-side per-request state is indistinguishable from isolate-side state,
10603/// and the two silently diverge the moment requests interleave — one
10604/// request's `__endEvent` popping another's event, its `waitUntil` work
10605/// attributed to a request that never asked for it.
10606///
10607/// `current()` is a thread-local the host installs for the duration of a
10608/// turn and restores on the way out, exactly as `threadLocalRequest` is set
10609/// in `IoContext::runInContextScope` and restored by `SuppressIoContextScope`.
10610/// An op that needs a context and finds none is a bug in the host, not in
10611/// the script, so it says so rather than inventing one.
10612///
10613/// **It is `Send + Sync`, and that is load-bearing.** Under D1 a request is
10614/// a tokio task that suspends between turns and can resume on any worker, so
10615/// the context it carries has to cross threads with it. `Rc` and `RefCell`
10616/// would forbid that. The isolate keeps one narrow weak lookup from a CPED
10617/// continuation token to this context, because a reaction can run during a
10618/// different event's checkpoint. That lookup owns no context, operation, or
10619/// resolver, and `IoContext::drop` removes it. It therefore attributes the
10620/// running reaction without rebuilding the pump's lifetime-owning `idmap`.
10621/// A cross-entry input gate is the narrow exception: it claims the originating
10622/// context so the event and its resources stay active until the callback ends.
10623/// The gate releases that claim when the block ends. The interiors are
10624/// `Mutex`; only the isolate's holder reaches them.
10625pub struct IoContext {
10626 /// A process-wide identity captured by V8 with each promise reaction.
10627 /// The process-wide cell-gate map also uses it, so another isolate must
10628 /// not reuse it. The isolate registry holds only a `Weak`, so a
10629 /// continuation does not extend the request lifetime by itself. A
10630 /// cross-entry input gate adds an explicit claim that prevents this
10631 /// context's `InFlight` from retiring while its callback still runs.
10632 continuation: Option<(u64, Weak<ActorRuntimeState>)>,
10633 /// This caller's delivery order for each cell it has called. See
10634 /// `CallOrder` — it is here rather than in a process-wide map because
10635 /// nothing outside this caller ever reads it.
10636 pub call_chains: Mutex<CallChains>,
10637 /// Event frames, innermost last. A frame collects the `waitUntil`
10638 /// promises registered while it is the innermost one.
10639 ///
10640 /// Nesting is per-request and strictly LIFO — a service-binding
10641 /// dispatch, an RPC entry, or a DO construction pushes its own frame so
10642 /// its `waitUntil` binds to that dispatch, matching workerd.
10643 events: Mutex<IoEventState>,
10644 /// Workerd gives every request an empty, memory-backed `/tmp`. Directory
10645 /// state belongs here so it follows the request across promise turns and
10646 /// disappears with the request instead of leaking across isolate reuse.
10647 /// The tree stays unallocated when the application does not use `node:fs`.
10648 vfs: OnceLock<Mutex<RequestVfs>>,
10649 /// Isolate-polled sockets this request opened. Dropping the request's
10650 /// pending ops aborts everything the isolate is waiting on, but a socket
10651 /// is a host-side resource that abort cannot reach: its connector task
10652 /// exits only when the isolate stops reading. So the request closes its
10653 /// own sockets, and [`IoContext::drop`] is what makes that unforgettable.
10654 ///
10655 /// Flat rather than a stack. Only sockets that belong to no cell land
10656 /// here, and one `IoContext` is one request, so there is nothing to nest:
10657 /// a service-binding dispatch or a Durable Object call gets a context of
10658 /// its own rather than a frame inside this one.
10659 sockets: Mutex<Vec<u64>>,
10660 /// HTMLRewriter instances this request created. Each holds a parked
10661 /// parser thread; freeing them at retirement is what reclaims the
10662 /// thread when a transform is abandoned unread — nothing else can,
10663 /// because the pending event promise roots the output stream.
10664 rewriters: Mutex<Vec<u64>>,
10665 /// Outbound TCP sockets this event opened. A socket cannot outlive
10666 /// its event: retirement drops the registry entries, which closes
10667 /// the connections.
10668 tcp_sockets: Mutex<Vec<u64>>,
10669 /// Input-gate holds and pending acquisitions for this event.
10670 ///
10671 /// The event owns the cell and host id together, and retirement wakes a
10672 /// pending acquisition. A timeout or cancellation can therefore abandon
10673 /// only its own hold and cannot resume after its event has gone away.
10674 input_gates: Mutex<InputGateClaims>,
10675 /// Blocks created by this event but run during another event's turn.
10676 /// These claims keep this event's native operations and resources alive;
10677 /// their watch wakes the drive when the final block ends.
10678 cross_entry_gates: CrossEntryGateClaims,
10679 /// Host-backed request bodies this handler owns. A subrequest transfers
10680 /// an id out before its target takes ownership, so only one request can
10681 /// reclaim an unread tail.
10682 body_streams: Mutex<HashMap<u64, HttpStreamClaim>>,
10683 /// Output-gate capture. While a `webSocketMessage` runs, the frames it
10684 /// sends are collected here instead of reaching the wire, so the shell
10685 /// can hold them until the message's write is durable. A stack, so a
10686 /// nested dispatch keeps its frames apart from the outer one's.
10687 ///
10688 /// On the event and not on the thread, because an event outlives the
10689 /// turn that began it: capture starts in one turn and is taken in a
10690 /// later one, which tokio may run on a different worker.
10691 ws_capture: Mutex<Vec<websocket::WsCapture>>,
10692 /// What each running event's outbound effects gate against, innermost
10693 /// last. An outbound effect raised during the event consults this: if the
10694 /// handler has advanced the position, the effect waits for the output gate
10695 /// before it leaves the process.
10696 ///
10697 /// Empty for stateless Worker code, which owns no cell and gates
10698 /// nothing.
10699 egress: Mutex<Vec<EgressFrame>>,
10700 /// Ops another event's turn enqueued for this event, waiting for this
10701 /// event's driver to take them. See `adopt`: a continuation that resumes
10702 /// inside a foreign turn still enqueues through that turn, and only the
10703 /// driver of the event it belongs to may poll and cancel its work.
10704 ///
10705 /// `None` once this event retired: the mailbox is closed, and a hand-off
10706 /// that arrives after that is refused rather than parked. A parked op no
10707 /// driver will ever take is a `Global<PromiseResolver>` held for the life
10708 /// of the isolate, which is the leak `InFlight::abandon` exists to
10709 /// prevent; refusing lets the handing turn drop the resolver instead,
10710 /// while it still owns the isolate.
10711 handed: Mutex<Option<Vec<HandedOp>>>,
10712 /// How many ops `handed` holds, readable without taking its lock.
10713 ///
10714 /// Every pass of a driver's wake loop asks whether a foreign turn left it
10715 /// an op, and for all but a few passes in a cell's life the answer is no.
10716 /// The lock is uncontended, so this saves only the lock itself, but it
10717 /// pays that back on a loop that turns once per operation the event
10718 /// completes.
10719 handed_len: AtomicUsize,
10720 /// Wakes this event's driver when `handed` grows or a pending entrypoint
10721 /// starts. Both changes can make the driver's current wait obsolete.
10722 handed_wake: tokio::sync::Notify,
10723 /// IDs of nested `WorkerEntrypoint` calls that have not settled. The
10724 /// driver consumes these IDs only when the request has no native work, so
10725 /// it can reject the calls instead of timing out the enclosing event.
10726 pending_events: Mutex<HashSet<u64>>,
10727 /// The invocation-local subrequest budget. The count lives with the
10728 /// request context, so two concurrent calls into one loaded isolate never
10729 /// spend one another's allowance.
10730 subrequest_limit: Option<u32>,
10731 subrequests: AtomicUsize,
10732 /// A request-scoped client counts redirects against this request. A weak
10733 /// capture avoids a client/context cycle, and one client retains the
10734 /// connection pool across all fetches in the invocation.
10735 redirect_client: OnceLock<reqwest::Client>,
10736 cpu_limit_nanos: Option<u64>,
10737 cpu_used_nanos: AtomicU64,
10738 cpu_turn: Mutex<Option<CpuTurnStart>>,
10739 /// Whether this event records console calls for a Dynamic Worker tail.
10740 tail_reporting: bool,
10741 tail_logs: Mutex<TailLogCapture>,
10742}
10743
10744/// An op enqueued by one event's continuation during another event's turn: the
10745/// promise id, the work, and its complete lifetime classification.
10746type HandedOp = (u64, asyncrt::OpFuture, asyncrt::OpLifetime);
10747
10748impl IoContext {
10749 fn record_tail_log(&self, level: &str, body: &str) {
10750 if !self.tail_reporting {
10751 return;
10752 }
10753 let mut capture = self.tail_logs.lock().unwrap();
10754 if capture.full {
10755 return;
10756 }
10757 let separator = usize::from(!capture.records.is_empty());
10758 // A serialized string cannot be shorter than its UTF-8 input. This
10759 // rejects an obviously oversized call without allocating another
10760 // buffer or scanning it for JSON escapes.
10761 let minimum_bytes = capture
10762 .serialized_bytes
10763 .saturating_add(separator)
10764 .saturating_add(body.len())
10765 .saturating_add(2);
10766 if minimum_bytes > TAIL_LOG_LIMIT_BYTES {
10767 capture.full = true;
10768 return;
10769 }
10770 let record = TailLog {
10771 timestamp: crate::telemetry::now_unix_us() / 1_000,
10772 level: level.to_string(),
10773 message: vec![body.to_string()],
10774 };
10775 let record_bytes = serialized_json_bytes(&record);
10776 let next_bytes = capture
10777 .serialized_bytes
10778 .saturating_add(separator)
10779 .saturating_add(record_bytes);
10780 if next_bytes.saturating_add(2) > TAIL_LOG_LIMIT_BYTES {
10781 capture.full = true;
10782 return;
10783 }
10784 capture.serialized_bytes = next_bytes;
10785 capture.records.push(record);
10786 }
10787
10788 fn take_tail_logs(&self) -> Vec<TailLog> {
10789 std::mem::take(&mut *self.tail_logs.lock().unwrap()).records
10790 }
10791
10792 /// The continuation id this context is registered under, which names
10793 /// the event to the cell's gate. `None` for a context V8 never captures.
10794 fn continuation_id(&self) -> Option<u64> {
10795 self.continuation.as_ref().map(|(id, _)| *id)
10796 }
10797
10798 fn cpu_limit_ms(&self) -> Option<u32> {
10799 self.cpu_limit_nanos
10800 .and_then(|limit| u32::try_from(limit / 1_000_000).ok())
10801 }
10802
10803 fn redirect_counting_client(self: &Arc<Self>) -> reqwest::Client {
10804 self.redirect_client
10805 .get_or_init(|| {
10806 let context = Arc::downgrade(self);
10807 reqwest::Client::builder()
10808 .redirect(reqwest::redirect::Policy::custom(move |attempt| {
10809 if attempt.previous().len() >= 10 {
10810 return attempt.error("too many redirects");
10811 }
10812 if let Some(context) = context.upgrade() {
10813 if let Err(error) = context.charge_subrequest() {
10814 return attempt.error(RedirectSubrequestLimit(error));
10815 }
10816 }
10817 attempt.follow()
10818 }))
10819 .build()
10820 .expect("build the redirect-counting HTTP client")
10821 })
10822 .clone()
10823 }
10824
10825 /// Spend one subrequest from this invocation before the operation leaves
10826 /// the isolate. The failed attempt is counted too, so repeated catches
10827 /// cannot retry an operation that already exhausted the budget.
10828 fn charge_subrequest(&self) -> Result<(), String> {
10829 let Some(limit) = self.subrequest_limit else {
10830 return Ok(());
10831 };
10832 let used = self.subrequests.fetch_add(1, Ordering::Relaxed) + 1;
10833 if used > limit as usize {
10834 return Err(format!("Worker exceeded subrequest limit of {limit}"));
10835 }
10836 Ok(())
10837 }
10838
10839 fn begin_cpu_turn(&self) {
10840 if self.cpu_limit_nanos.is_none() {
10841 return;
10842 }
10843 *self.cpu_turn.lock().unwrap() = Some(CpuTurnStart {
10844 thread_nanos: thread_cpu_nanos(),
10845 wall: Instant::now(),
10846 });
10847 }
10848
10849 fn remaining_cpu_budget(&self) -> Option<Duration> {
10850 self.cpu_limit_nanos.map(|limit| {
10851 Duration::from_nanos(limit.saturating_sub(self.cpu_used_nanos.load(Ordering::Relaxed)))
10852 })
10853 }
10854
10855 fn finish_cpu_turn(&self) -> Result<(), String> {
10856 let Some(limit) = self.cpu_limit_nanos else {
10857 return Ok(());
10858 };
10859 let Some(started) = self.cpu_turn.lock().unwrap().take() else {
10860 return Ok(());
10861 };
10862 let elapsed = started
10863 .thread_nanos
10864 .zip(thread_cpu_nanos())
10865 .map(|(started, finished)| finished.saturating_sub(started))
10866 .unwrap_or_else(|| started.wall.elapsed().as_nanos() as u64);
10867 let used = self.cpu_used_nanos.fetch_add(elapsed, Ordering::Relaxed) + elapsed;
10868 if used > limit {
10869 return Err(format!(
10870 "Worker exceeded CPU limit of {} ms",
10871 limit / 1_000_000
10872 ));
10873 }
10874 Ok(())
10875 }
10876
10877 #[allow(clippy::new_ret_no_self, clippy::new_without_default)]
10878 #[doc(hidden)]
10879 pub fn new() -> Arc<Self> {
10880 Self::with_resource_limits(None)
10881 }
10882
10883 fn with_resource_limits(limits: Option<ResourceLimits>) -> Arc<Self> {
10884 Self::with_options(limits, false)
10885 }
10886
10887 #[cfg(all(test, celld_internal_tests))]
10888 fn with_tail_reporting(tail_reporting: bool) -> Arc<Self> {
10889 Self::with_options(None, tail_reporting)
10890 }
10891
10892 fn with_options(limits: Option<ResourceLimits>, tail_reporting: bool) -> Arc<Self> {
10893 Arc::new(Self {
10894 continuation: None,
10895 call_chains: Mutex::new(CallChains::default()),
10896 events: Mutex::new(IoEventState::default()),
10897 vfs: OnceLock::new(),
10898 sockets: Mutex::new(Vec::new()),
10899 rewriters: Mutex::new(Vec::new()),
10900 tcp_sockets: Mutex::new(Vec::new()),
10901 input_gates: Mutex::new(InputGateClaims::default()),
10902 cross_entry_gates: CrossEntryGateClaims::default(),
10903 body_streams: Mutex::new(HashMap::new()),
10904 ws_capture: Mutex::new(Vec::new()),
10905 egress: Mutex::new(Vec::new()),
10906 handed: Mutex::new(Some(Vec::new())),
10907 handed_len: AtomicUsize::new(0),
10908 handed_wake: tokio::sync::Notify::new(),
10909 pending_events: Mutex::new(HashSet::new()),
10910 subrequest_limit: limits.and_then(|limits| limits.sub_requests),
10911 subrequests: AtomicUsize::new(0),
10912 redirect_client: OnceLock::new(),
10913 cpu_limit_nanos: limits
10914 .and_then(|limits| limits.cpu_ms)
10915 .map(|milliseconds| u64::from(milliseconds).saturating_mul(1_000_000)),
10916 cpu_used_nanos: AtomicU64::new(0),
10917 cpu_turn: Mutex::new(None),
10918 tail_reporting,
10919 tail_logs: Mutex::new(TailLogCapture::default()),
10920 })
10921 }
10922
10923 fn tracked(runtime_state: &Arc<ActorRuntimeState>) -> Arc<Self> {
10924 let id = allocate_io_context_id();
10925 let context = Arc::new(Self {
10926 continuation: Some((id, Arc::downgrade(runtime_state))),
10927 call_chains: Mutex::new(CallChains::default()),
10928 events: Mutex::new(IoEventState::default()),
10929 vfs: OnceLock::new(),
10930 sockets: Mutex::new(Vec::new()),
10931 rewriters: Mutex::new(Vec::new()),
10932 tcp_sockets: Mutex::new(Vec::new()),
10933 input_gates: Mutex::new(InputGateClaims::default()),
10934 cross_entry_gates: CrossEntryGateClaims::default(),
10935 body_streams: Mutex::new(HashMap::new()),
10936 ws_capture: Mutex::new(Vec::new()),
10937 egress: Mutex::new(Vec::new()),
10938 handed: Mutex::new(Some(Vec::new())),
10939 handed_len: AtomicUsize::new(0),
10940 handed_wake: tokio::sync::Notify::new(),
10941 pending_events: Mutex::new(HashSet::new()),
10942 subrequest_limit: runtime_state
10943 .resource_limits
10944 .and_then(|limits| limits.sub_requests),
10945 subrequests: AtomicUsize::new(0),
10946 redirect_client: OnceLock::new(),
10947 cpu_limit_nanos: runtime_state
10948 .resource_limits
10949 .and_then(|limits| limits.cpu_ms)
10950 .map(|milliseconds| u64::from(milliseconds).saturating_mul(1_000_000)),
10951 cpu_used_nanos: AtomicU64::new(0),
10952 cpu_turn: Mutex::new(None),
10953 // Tracked contexts drive cell and RPC events. Dynamic Worker tail
10954 // reports currently belong only to fetch jobs, whose untracked
10955 // context is constructed from the report sender in `begin`.
10956 tail_reporting: false,
10957 tail_logs: Mutex::new(TailLogCapture::default()),
10958 });
10959 runtime_state
10960 .io_contexts
10961 .lock()
10962 .unwrap()
10963 .insert(id, Arc::downgrade(&context));
10964 context
10965 }
10966
10967 /// Take an op that another event's turn enqueued for this event.
10968 ///
10969 /// Reports whether the mailbox accepted it. A closed mailbox refuses, and
10970 /// the caller must then drop the op's resolver: this event will never run
10971 /// the continuation waiting on it.
10972 #[must_use]
10973 fn hand_op(&self, id: u64, future: asyncrt::OpFuture, lifetime: asyncrt::OpLifetime) -> bool {
10974 let mut handed = self.handed.lock().unwrap();
10975 let Some(queue) = handed.as_mut() else {
10976 return false;
10977 };
10978 queue.push((id, future, lifetime));
10979 // Published under the lock, so a reader that sees this count can take
10980 // the lock and find the op there.
10981 self.handed_len.store(queue.len(), Ordering::Release);
10982 drop(handed);
10983 self.handed_wake.notify_one();
10984 true
10985 }
10986
10987 /// Whether a foreign turn has left this event an op, without locking.
10988 ///
10989 /// A `false` answer is authoritative for the driver that asks it. Only
10990 /// that driver empties the queue, so nothing it must see can appear and
10991 /// vanish behind this read; a hand-off that lands immediately after it
10992 /// wakes the driver through `handed_ready` instead.
10993 fn has_handed_ops(&self) -> bool {
10994 self.handed_len.load(Ordering::Acquire) != 0
10995 }
10996
10997 fn accepts_handed_ops(&self) -> bool {
10998 self.handed.lock().unwrap().is_some()
10999 }
11000
11001 fn register_pending_event(&self, id: u64) {
11002 self.pending_events.lock().unwrap().insert(id);
11003 // The call can start during another event's microtask checkpoint,
11004 // after this context's driver has already parked. Wake that driver so
11005 // it can reject the call when no native operation can resume it.
11006 self.handed_wake.notify_one();
11007 }
11008
11009 fn finish_pending_event(&self, id: u64) {
11010 self.pending_events.lock().unwrap().remove(&id);
11011 }
11012
11013 fn has_pending_events(&self) -> bool {
11014 !self.pending_events.lock().unwrap().is_empty()
11015 }
11016
11017 fn take_pending_events(&self) -> Vec<u64> {
11018 let mut pending = self.pending_events.lock().unwrap();
11019 let mut ids = pending.drain().collect::<Vec<_>>();
11020 ids.sort_unstable();
11021 ids
11022 }
11023
11024 /// Resolve once another turn has handed this event an op or started a
11025 /// pending entrypoint call.
11026 ///
11027 /// This can also resolve with nothing to take, and a caller must treat
11028 /// an empty queue as ordinary. `notify_one` stores a permit when no
11029 /// driver is parked, and the driver takes the op on its next pass
11030 /// through `has_handed_ops` before it waits again, so the permit
11031 /// outlives the op it announced and releases one later wait early. That
11032 /// wait costs one atomic read and parks again, which is why the permit
11033 /// is left alone: cancelling it needs a second piece of state, and that
11034 /// state has to stay consistent with the queue.
11035 pub(crate) async fn handed_ready(&self) {
11036 self.handed_wake.notified().await;
11037 }
11038
11039 /// Hand this event's driver everything a foreign turn left for it.
11040 fn take_handed_ops(&self) -> Vec<HandedOp> {
11041 let mut handed = self.handed.lock().unwrap();
11042 self.handed_len.store(0, Ordering::Release);
11043 handed.as_mut().map(std::mem::take).unwrap_or_default()
11044 }
11045
11046 /// Close the mailbox and return whatever no driver took.
11047 ///
11048 /// Called when the event retires. The caller drops the resolvers of the
11049 /// ops that come back, and every later hand-off is refused at the source,
11050 /// so no op can sit here waiting for a driver that will never run again.
11051 #[must_use]
11052 fn close_handed_ops(&self) -> Vec<HandedOp> {
11053 let mut handed = self.handed.lock().unwrap();
11054 self.handed_len.store(0, Ordering::Release);
11055 handed.take().unwrap_or_default()
11056 }
11057
11058 fn begin_event(&self) {
11059 self.events
11060 .lock()
11061 .unwrap()
11062 .frames
11063 .push(IoEventFrame::default());
11064 }
11065
11066 fn release_input_gate(&self, cell: &str, event: celld_logic::gate::EventId) -> bool {
11067 let mut claims = self.input_gates.lock().unwrap();
11068 if !claims.held.get(&event).is_some_and(|owned| owned == cell) {
11069 return false;
11070 }
11071 claims.held.remove(&event);
11072 true
11073 }
11074
11075 fn retire_input_gates(&self) -> Vec<(String, celld_logic::gate::EventId)> {
11076 let mut claims = self.input_gates.lock().unwrap();
11077 claims.retired = true;
11078 claims.retirement.send_replace(true);
11079 let mut held = claims
11080 .held
11081 .drain()
11082 .map(|(event, cell)| (cell, event))
11083 .collect::<Vec<_>>();
11084 held.sort_unstable();
11085 held
11086 }
11087
11088 /// Pop the innermost frame and hand back what it collected. `None` when
11089 /// there is no frame, which is a script calling `waitUntil` outside any
11090 /// event; the harness turns that into workerd's global-scope error.
11091 fn end_event(&self) -> Option<Vec<v8::Global<v8::Promise>>> {
11092 let mut events = self.events.lock().unwrap();
11093 let mut frame = events.frames.pop()?;
11094 if events.arm_gates_sealed {
11095 drop(frame.arm_gates);
11096 } else if let Some(parent) = events.frames.last_mut() {
11097 parent.arm_gates.append(&mut frame.arm_gates);
11098 } else {
11099 events.ended_arm_gates.append(&mut frame.arm_gates);
11100 }
11101 if events.frames.is_empty() && !frame.wait_until.is_empty() {
11102 events.wait_until_active = true;
11103 }
11104 Some(frame.wait_until)
11105 }
11106
11107 fn register_wait_until(&self, promise: v8::Global<v8::Promise>) {
11108 let mut events = self.events.lock().unwrap();
11109 if let Some(frame) = events.frames.last_mut() {
11110 frame.wait_until.push(promise);
11111 } else if events.wait_until_active {
11112 events.late_wait_until.push(promise);
11113 }
11114 }
11115
11116 /// Whether imported `waitUntil()` has request-associated work to extend.
11117 fn accepts_wait_until(&self) -> bool {
11118 let events = self.events.lock().unwrap();
11119 !events.frames.is_empty() || events.wait_until_active
11120 }
11121
11122 /// Take registrations made while the current background aggregate ran.
11123 /// An empty batch seals the registration window together with the
11124 /// driver's decision to retire that aggregate.
11125 fn take_late_wait_until(&self) -> Vec<v8::Global<v8::Promise>> {
11126 let mut events = self.events.lock().unwrap();
11127 let late = std::mem::take(&mut events.late_wait_until);
11128 if late.is_empty() {
11129 events.wait_until_active = false;
11130 }
11131 late
11132 }
11133
11134 fn seal_wait_until(&self) {
11135 let mut events = self.events.lock().unwrap();
11136 events.wait_until_active = false;
11137 events.late_wait_until.clear();
11138 }
11139
11140 fn register_arm_gate(&self, gate: ArmGateRx) -> Result<(), ArmGateRx> {
11141 let mut events = self.events.lock().unwrap();
11142 if events.arm_gates_sealed {
11143 return Err(gate);
11144 }
11145 if let Some(frame) = events.frames.last_mut() {
11146 frame.arm_gates.push(gate);
11147 } else {
11148 // `op_event_end` pops the final frame before `Promise.allSettled`
11149 // can invoke a user-defined `then`. A gate created during that
11150 // call still belongs to this event until `take_arm_gates` seals
11151 // the response boundary.
11152 events.ended_arm_gates.push(gate);
11153 }
11154 Ok(())
11155 }
11156
11157 /// Take every response gate that this event owns.
11158 ///
11159 /// The normal path takes gates moved out by `end_event`. Active frames
11160 /// cover failures that cannot run JavaScript again, such as a timeout or
11161 /// an isolate termination.
11162 fn take_arm_gates(&self) -> Vec<ArmGateRx> {
11163 let mut events = self.events.lock().unwrap();
11164 if events.arm_gates_sealed {
11165 return Vec::new();
11166 }
11167 events.arm_gates_sealed = true;
11168 let mut gates = std::mem::take(&mut events.ended_arm_gates);
11169 for frame in &mut events.frames {
11170 gates.append(&mut frame.arm_gates);
11171 }
11172 gates
11173 }
11174
11175 fn depth(&self) -> usize {
11176 self.events.lock().unwrap().frames.len()
11177 }
11178
11179 /// Close every isolate-polled socket this request opened.
11180 ///
11181 /// Draining makes the operation idempotent. The drive loop calls it when
11182 /// the request retires, and `drop` covers every earlier failure path.
11183 fn close_sockets(&self) {
11184 let opened = self.sockets.lock().unwrap().drain(..).collect();
11185 ws_close_request_sockets(opened);
11186 let rewriters: Vec<u64> = self.rewriters.lock().unwrap().drain(..).collect();
11187 for id in rewriters {
11188 html_rewriter::free(id);
11189 }
11190 let tcp: Vec<u64> = self.tcp_sockets.lock().unwrap().drain(..).collect();
11191 for id in tcp {
11192 tcp::free(id);
11193 }
11194 }
11195
11196 #[doc(hidden)]
11197 pub fn own_body_stream(&self, stream_id: u64) {
11198 let Some(claim) = claim_http_stream(stream_id) else {
11199 return;
11200 };
11201 let replaced = self.body_streams.lock().unwrap().insert(stream_id, claim);
11202 // Releasing a claim can drop an arbitrary source. Keep that work out
11203 // of the request-ownership lock.
11204 drop(replaced);
11205 }
11206
11207 fn transfer_body_stream(&self, stream_id: u64) -> Option<RequestBodyGuard> {
11208 let claim = self.body_streams.lock().unwrap().remove(&stream_id)?;
11209 // Move the exact service claim into the guard. A later asynchronous
11210 // drop cannot resolve through another ambient Domain.
11211 Some(RequestBodyGuard::transferred(claim))
11212 }
11213
11214 /// Replace one request-owned source with the two sources created by a
11215 /// native tee. Response streams are not request-owned, so they keep the
11216 /// registry's ordinary unowned lifecycle.
11217 fn replace_body_stream(
11218 &self,
11219 stream_id: u64,
11220 service: &Arc<HttpStreamService>,
11221 branches: (u64, u64),
11222 ) {
11223 let original = self.body_streams.lock().unwrap().remove(&stream_id);
11224 let Some(original) = original else {
11225 return;
11226 };
11227 debug_assert!(Arc::ptr_eq(&original.service, service));
11228 let mut branch_claims = Vec::new();
11229 for branch in [branches.0, branches.1] {
11230 if let Some(claim) = service.claim(branch) {
11231 branch_claims.push((branch, claim));
11232 }
11233 }
11234 let replaced = {
11235 let mut owned = self.body_streams.lock().unwrap();
11236 branch_claims
11237 .into_iter()
11238 .filter_map(|(branch, claim)| owned.insert(branch, claim))
11239 .collect::<Vec<_>>()
11240 };
11241 // The original entry was consumed by tee, so releasing this claim is
11242 // a no-op. Replaced claims still release through their bound service.
11243 drop(original);
11244 drop(replaced);
11245 }
11246
11247 #[cfg(celld_internal_tests)]
11248 #[doc(hidden)]
11249 pub fn begin_event_for_test(&self) {
11250 self.begin_event();
11251 }
11252
11253 #[cfg(celld_internal_tests)]
11254 #[doc(hidden)]
11255 pub fn end_event_for_test(&self) -> Option<()> {
11256 self.end_event().map(drop)
11257 }
11258
11259 #[cfg(celld_internal_tests)]
11260 #[doc(hidden)]
11261 pub fn register_arm_gate_for_test(
11262 &self,
11263 gate: tokio::sync::oneshot::Receiver<Result<(), String>>,
11264 ) -> Result<(), tokio::sync::oneshot::Receiver<Result<(), String>>> {
11265 self.register_arm_gate(gate)
11266 }
11267
11268 #[cfg(celld_internal_tests)]
11269 #[doc(hidden)]
11270 pub fn take_arm_gates_for_test(
11271 &self,
11272 ) -> Vec<tokio::sync::oneshot::Receiver<Result<(), String>>> {
11273 self.take_arm_gates()
11274 }
11275}
11276
11277#[cfg(celld_internal_tests)]
11278#[doc(hidden)]
11279#[derive(Default)]
11280pub struct IoContextRegistryForTest(Arc<ActorRuntimeState>);
11281
11282#[cfg(celld_internal_tests)]
11283impl IoContextRegistryForTest {
11284 #[doc(hidden)]
11285 pub fn track(&self) -> (u64, Arc<IoContext>) {
11286 let context = IoContext::tracked(&self.0);
11287 let id = context
11288 .continuation
11289 .as_ref()
11290 .map(|(id, _)| *id)
11291 .expect("a tracked IoContext has a continuation id");
11292 (id, context)
11293 }
11294
11295 #[doc(hidden)]
11296 pub fn resolves_to(&self, id: u64, expected: &Arc<IoContext>) -> bool {
11297 self.0
11298 .io_context(id)
11299 .is_some_and(|context| Arc::ptr_eq(&context, expected))
11300 }
11301
11302 #[doc(hidden)]
11303 pub fn contains(&self, id: u64) -> bool {
11304 self.0.io_contexts.lock().unwrap().contains_key(&id)
11305 }
11306
11307 #[doc(hidden)]
11308 pub fn is_empty(&self) -> bool {
11309 self.0.io_contexts.lock().unwrap().is_empty()
11310 }
11311
11312 /// Hand `context` an op that never completes, and report whether its
11313 /// mailbox accepted it. The future stands in for real work: the mailbox
11314 /// only stores it, so nothing here polls it.
11315 #[doc(hidden)]
11316 pub fn hand_pending_op(&self, context: &Arc<IoContext>, id: u64) -> bool {
11317 context.hand_op(
11318 id,
11319 Box::pin(std::future::pending()),
11320 asyncrt::OpLifetime::Handler,
11321 )
11322 }
11323
11324 /// The op ids `context` still holds for a driver that has not taken them.
11325 #[doc(hidden)]
11326 pub fn handed_op_ids(&self, context: &Arc<IoContext>) -> Vec<u64> {
11327 context
11328 .handed
11329 .lock()
11330 .unwrap()
11331 .as_ref()
11332 .map(|queue| queue.iter().map(|(id, _, _)| *id).collect())
11333 .unwrap_or_default()
11334 }
11335
11336 /// Run the mailbox half of an event's retirement: close it, and report
11337 /// the ops whose resolvers `InFlight::abandon` must then drop.
11338 #[doc(hidden)]
11339 pub fn close_handed_ops(&self, context: &Arc<IoContext>) -> Vec<u64> {
11340 context
11341 .close_handed_ops()
11342 .into_iter()
11343 .map(|(id, _, _)| id)
11344 .collect()
11345 }
11346}
11347
11348/// A Worker socket lives and dies with its request, exactly as it does on
11349/// Cloudflare. Closing it here rather than at each of the drive loops' exits
11350/// is the difference between a rule every exit path has to remember and one
11351/// it cannot get wrong: a request that times out, that is abandoned as stuck,
11352/// or whose client disconnects drops its context on a path of its own.
11353impl Drop for IoContext {
11354 fn drop(&mut self) {
11355 let already_panicking = std::thread::panicking();
11356 // The drive loop also abandons these while it still owns the isolate,
11357 // because that path resets the JavaScript actor state. Drop is the
11358 // final host-side invariant for an earlier exit: no request context
11359 // can leave a process-wide input gate active after it is gone.
11360 let _ = abandon_context_input_gates(self);
11361 self.close_sockets();
11362 let mut claims = self
11363 .body_streams
11364 .get_mut()
11365 .unwrap()
11366 .drain()
11367 .collect::<Vec<_>>();
11368 // A claim can drop an arbitrary source. Fix the first-panic order even
11369 // when the request map uses a different randomized hash seed.
11370 claims.sort_unstable_by_key(|(stream_id, _)| *stream_id);
11371 let mut first_panic = None;
11372 for (_, claim) in claims {
11373 retain_first_http_cleanup_panic(
11374 &mut first_panic,
11375 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(claim))),
11376 );
11377 }
11378 if let Some((id, runtime_state)) = &self.continuation {
11379 if let Some(runtime_state) = runtime_state.upgrade() {
11380 runtime_state.io_contexts.lock().unwrap().remove(id);
11381 }
11382 }
11383 if let Some(payload) = first_panic {
11384 if already_panicking {
11385 std::mem::forget(payload);
11386 } else {
11387 std::panic::resume_unwind(payload);
11388 }
11389 }
11390 }
11391}
11392
11393/// What `OwnedIsolate::into_shared` demands of us: every slot value on a
11394/// shared isolate is reachable, and droppable, from whichever thread holds
11395/// the lock. The type system cannot check it at the call site, so it is
11396/// checked here instead.
11397const _: fn() = || {
11398 fn assert_send_sync<T: Send + Sync>() {}
11399 assert_send_sync::<HeapLimitState>();
11400 assert_send_sync::<ActorRuntimeState>();
11401 assert_send_sync::<ModuleRegistry>();
11402 assert_send_sync::<LoaderOwner>();
11403};
11404
11405/// A request must be able to carry its own context across a suspension. A
11406/// compile-time check, because losing it would surface as an unrelated
11407/// `Send` error wherever the request task is spawned.
11408const _: fn() = || {
11409 fn assert_send_sync<T: Send + Sync>() {}
11410 assert_send_sync::<Arc<IoContext>>();
11411};
11412
11413thread_local! {
11414 /// The request whose turn is running on this thread, or none between
11415 /// turns. Never set by JS.
11416 static CURRENT: RefCell<Option<Arc<IoContext>>> =
11417 const { RefCell::new(None) };
11418}
11419
11420/// Install `context` for the duration of a turn, restoring whatever was
11421/// current when the guard drops.
11422///
11423/// Restoring rather than clearing is what makes nested host dispatch safe: a
11424/// service binding runs a second handler inside the first one's turn, and the
11425/// outer request must still be current when it returns.
11426pub struct CurrentGuard(Option<Arc<IoContext>>);
11427
11428impl CurrentGuard {
11429 pub fn enter(context: Arc<IoContext>) -> Self {
11430 CurrentGuard(CURRENT.with(|current| current.borrow_mut().replace(context)))
11431 }
11432}
11433
11434impl Drop for CurrentGuard {
11435 fn drop(&mut self) {
11436 CURRENT.with(|current| *current.borrow_mut() = self.0.take());
11437 }
11438}
11439
11440/// The context this turn belongs to.
11441///
11442/// A thread that has not had one installed gets a default: every path that
11443/// runs JS without an explicit request context — a cell isolate, which the
11444/// DO contract already serializes, an RPC entry, a DO constructor — keeps
11445/// exactly the semantics it had when the stack lived in JS, one per isolate.
11446/// Isolation is a property of *installing* a context, so it arrives with the
11447/// paths that need it rather than being retrofitted to every caller at once.
11448fn current_context() -> Arc<IoContext> {
11449 CURRENT.with(|current| {
11450 let mut current = current.borrow_mut();
11451 current.get_or_insert_with(IoContext::new).clone()
11452 })
11453}
11454
11455#[cfg(celld_internal_tests)]
11456fn installed_context() -> Option<Arc<IoContext>> {
11457 CURRENT.with(|current| current.borrow().clone())
11458}
11459
11460fn op_event_begin(
11461 scope: &mut v8::PinScope,
11462 _args: v8::FunctionCallbackArguments,
11463 _rv: v8::ReturnValue<v8::Value>,
11464) {
11465 let _ = scope;
11466 current_context().begin_event();
11467}
11468
11469/// Pop the innermost event and return the aggregate of its `waitUntil`
11470/// promises, or null when it collected none. The aggregate is built here
11471/// rather than in JS because the promises live here: the host holds them for
11472/// the request, and the request is what the frame belongs to.
11473fn op_event_end<'s>(
11474 scope: &mut v8::PinScope<'s, '_>,
11475 _args: v8::FunctionCallbackArguments,
11476 mut rv: v8::ReturnValue<v8::Value>,
11477) {
11478 let Some(frame) = current_context().end_event() else {
11479 rv.set_null();
11480 return;
11481 };
11482 match wait_until_aggregate(scope, &frame) {
11483 Some(aggregate) => rv.set(aggregate.into()),
11484 None => rv.set_null(),
11485 }
11486}
11487
11488/// Resolve the request whose code is running, even when its reaction executes
11489/// during another request's microtask checkpoint. A missing captured context
11490/// is retired, so it must not fall back to the request driving this turn.
11491fn reaction_or_current_context(scope: &mut v8::PinScope) -> Option<Arc<IoContext>> {
11492 match reaction_continuation_id(scope) {
11493 Some(id) => actor_runtime_state(scope).io_context(id),
11494 None => Some(current_context()),
11495 }
11496}
11497
11498fn op_pending_event_begin(
11499 scope: &mut v8::PinScope,
11500 args: v8::FunctionCallbackArguments,
11501 _rv: v8::ReturnValue<v8::Value>,
11502) {
11503 let Some(id) = args.get(0).integer_value(scope) else {
11504 return;
11505 };
11506 if let Some(context) = reaction_or_current_context(scope) {
11507 context.register_pending_event(id as u64);
11508 }
11509}
11510
11511fn op_pending_event_end(
11512 scope: &mut v8::PinScope,
11513 args: v8::FunctionCallbackArguments,
11514 _rv: v8::ReturnValue<v8::Value>,
11515) {
11516 let Some(id) = args.get(0).integer_value(scope) else {
11517 return;
11518 };
11519 if let Some(context) = reaction_or_current_context(scope) {
11520 context.finish_pending_event(id as u64);
11521 }
11522}
11523
11524/// Create one directory in the current request's virtual `/tmp` tree.
11525/// A created path starts with `/`, an error is a Node code, and an empty string
11526/// means that no path must be returned. The disjoint representation keeps the
11527/// result and its meaning together without allocating a JS object for each
11528/// directory segment.
11529fn op_vfs_mkdir(
11530 scope: &mut v8::PinScope,
11531 args: v8::FunctionCallbackArguments,
11532 mut rv: v8::ReturnValue<v8::Value>,
11533) {
11534 let path = args.get(0).to_rust_string_lossy(scope);
11535 let recursive = args.get(1).boolean_value(scope);
11536 let result = current_context()
11537 .vfs
11538 .get_or_init(|| Mutex::new(RequestVfs::default()))
11539 .lock()
11540 .unwrap()
11541 .mkdir(&path, recursive);
11542 let result = match result {
11543 VfsMkdirResult::Created(Some(path)) => path,
11544 VfsMkdirResult::Created(None) => String::new(),
11545 VfsMkdirResult::Error(code) => code.to_string(),
11546 };
11547 rv.set(v8::String::new(scope, &result).unwrap().into());
11548}
11549
11550/// Return `[kind, size]`, where kind is 0 for a missing path, 1 for a
11551/// read-only directory, 2 for a writable directory, and 3 for a read-only
11552/// file. Only a file has a size; a directory reports 0, matching workerd.
11553///
11554/// The pair travels together because a caller that knows a path is a file
11555/// always needs its size to build `Stats`, and a second lookup could observe a
11556/// different tree.
11557fn op_vfs_stat(
11558 scope: &mut v8::PinScope,
11559 args: v8::FunctionCallbackArguments,
11560 mut rv: v8::ReturnValue<v8::Value>,
11561) {
11562 let path = args.get(0).to_rust_string_lossy(scope);
11563 let (kind, size) = match current_context()
11564 .vfs
11565 .get_or_init(|| Mutex::new(RequestVfs::default()))
11566 .lock()
11567 .unwrap()
11568 .stat(&path)
11569 {
11570 Some(writable) => (if writable { 2 } else { 1 }, 0),
11571 // Only a path the writable tree does not claim can be a bundle path,
11572 // so the request tree stays authoritative for `/tmp`.
11573 None => match bundle_node(scope, &path) {
11574 Some(BundleStat::Directory) => (1, 0),
11575 Some(BundleStat::File(size)) => (3, size),
11576 None => (0, 0),
11577 },
11578 };
11579 let pair = v8::Array::new(scope, 2);
11580 let kind = v8::Integer::new(scope, kind).into();
11581 let size = v8::Number::new(scope, size as f64).into();
11582 pair.set_index(scope, 0, kind);
11583 pair.set_index(scope, 1, size);
11584 rv.set(pair.into());
11585}
11586
11587/// What a bundle path is, without copying the bytes a stat does not need.
11588enum BundleStat {
11589 Directory,
11590 File(usize),
11591}
11592
11593/// Materializes `/bundle` on the first call that reaches it.
11594fn bundle_node(scope: &mut v8::PinScope, path: &str) -> Option<BundleStat> {
11595 let bundle = scope.get_slot::<Arc<BundleFs>>().cloned()?;
11596 match bundle.tree().nodes.get(path)? {
11597 BundleNode::Directory => Some(BundleStat::Directory),
11598 BundleNode::File(bytes) => Some(BundleStat::File(bytes.len())),
11599 }
11600}
11601
11602/// Read a whole bundle file. Returns an `ArrayBuffer` of the module's bytes,
11603/// or `null` when the path is not a bundle file, so the caller raises the
11604/// `ENOENT` that names the syscall it was performing.
11605fn op_vfs_read_file(
11606 scope: &mut v8::PinScope,
11607 args: v8::FunctionCallbackArguments,
11608 mut rv: v8::ReturnValue<v8::Value>,
11609) {
11610 let path = args.get(0).to_rust_string_lossy(scope);
11611 let Some(bundle) = scope.get_slot::<Arc<BundleFs>>().cloned() else {
11612 return;
11613 };
11614 let tree = bundle.tree();
11615 let Some(BundleNode::File(bytes)) = tree.nodes.get(&path) else {
11616 return;
11617 };
11618 // One copy into the V8 heap. The projected `Bytes` stays shared, so a
11619 // second read of the same module does not re-copy the config's source.
11620 let store = v8::ArrayBuffer::new_backing_store_from_vec(bytes.to_vec()).make_shared();
11621 let buffer = v8::ArrayBuffer::with_backing_store(scope, &store);
11622 rv.set(buffer.into());
11623}
11624
11625fn op_wait_until<'s>(
11626 scope: &mut v8::PinScope<'s, '_>,
11627 args: v8::FunctionCallbackArguments<'s>,
11628 _rv: v8::ReturnValue<v8::Value>,
11629) {
11630 let value = args.get(0);
11631 let promise = match value.try_cast::<v8::Promise>() {
11632 Ok(promise) => promise,
11633 Err(_) => match resolved_promise(scope, value) {
11634 Ok(promise) => promise,
11635 Err(_) => return,
11636 },
11637 };
11638 if let Some(context) = reaction_or_current_context(scope) {
11639 context.register_wait_until(v8::Global::new(scope, promise));
11640 }
11641}
11642
11643fn op_wait_until_active(
11644 scope: &mut v8::PinScope,
11645 _args: v8::FunctionCallbackArguments,
11646 mut rv: v8::ReturnValue<v8::Value>,
11647) {
11648 let active =
11649 reaction_or_current_context(scope).is_some_and(|context| context.accepts_wait_until());
11650 rv.set(v8::Boolean::new(scope, active).into());
11651}
11652
11653/// How many event frames are open on the current request.
11654fn op_event_depth(
11655 scope: &mut v8::PinScope,
11656 _args: v8::FunctionCallbackArguments,
11657 mut rv: v8::ReturnValue<v8::Value>,
11658) {
11659 let depth = current_context().depth();
11660 rv.set(v8::Integer::new(scope, depth as i32).into());
11661}
11662
11663/// `Promise.allSettled(values)`, from the context's own realm.
11664fn all_settled<'s>(
11665 scope: &mut v8::PinScope<'s, '_>,
11666 values: v8::Local<'s, v8::Value>,
11667) -> Option<v8::Local<'s, v8::Value>> {
11668 let global = scope.get_current_context().global(scope);
11669 let key = v8::String::new(scope, "Promise").unwrap();
11670 let promise_ctor: v8::Local<v8::Object> = global.get(scope, key.into())?.try_into().ok()?;
11671 let key = v8::String::new(scope, "allSettled").unwrap();
11672 let all_settled: v8::Local<v8::Function> =
11673 promise_ctor.get(scope, key.into())?.try_into().ok()?;
11674 all_settled.call(scope, promise_ctor.into(), &[values])
11675}
11676
11677fn op_als_get(
11678 scope: &mut v8::PinScope,
11679 _args: v8::FunctionCallbackArguments,
11680 mut rv: v8::ReturnValue<v8::Value>,
11681) {
11682 rv.set(cped_frame(scope));
11683}
11684
11685fn op_als_set(
11686 scope: &mut v8::PinScope,
11687 args: v8::FunctionCallbackArguments,
11688 _rv: v8::ReturnValue<v8::Value>,
11689) {
11690 let trace = cped_trace(scope);
11691 let io_context = cped_io_context(scope);
11692 set_cped(scope, args.get(0), trace, io_context);
11693}
11694
11695// node:util prelude calls these; registration is the sole per-isolate cost.
11696
11697/// Type-check bitmask. Bit order must match `T` in src/js/node_util.js.
11698fn op_util_type_flags(
11699 _scope: &mut v8::PinScope,
11700 args: v8::FunctionCallbackArguments,
11701 mut rv: v8::ReturnValue<v8::Value>,
11702) {
11703 let v = args.get(0);
11704 let checks: [bool; 27] = [
11705 v.is_external(),
11706 v.is_date(),
11707 v.is_arguments_object(),
11708 v.is_big_int_object(),
11709 v.is_boolean_object(),
11710 v.is_number_object(),
11711 v.is_string_object(),
11712 v.is_symbol_object(),
11713 v.is_native_error(),
11714 v.is_reg_exp(),
11715 v.is_async_function(),
11716 v.is_generator_function(),
11717 v.is_generator_object(),
11718 v.is_promise(),
11719 v.is_map(),
11720 v.is_set(),
11721 v.is_map_iterator(),
11722 v.is_set_iterator(),
11723 v.is_weak_map(),
11724 v.is_weak_set(),
11725 v.is_array_buffer(),
11726 v.is_data_view(),
11727 v.is_shared_array_buffer(),
11728 v.is_proxy(),
11729 v.is_module_namespace_object(),
11730 v.is_typed_array(),
11731 v.is_array_buffer_view(),
11732 ];
11733 let mut flags: u32 = 0;
11734 for (i, hit) in checks.iter().enumerate() {
11735 if *hit {
11736 flags |= 1 << i;
11737 }
11738 }
11739 rv.set_uint32(flags);
11740}
11741
11742fn op_util_constructor_name(
11743 _scope: &mut v8::PinScope,
11744 args: v8::FunctionCallbackArguments,
11745 mut rv: v8::ReturnValue<v8::Value>,
11746) {
11747 let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
11748 return; // undefined
11749 };
11750 rv.set(obj.get_constructor_name().into());
11751}
11752
11753/// `[target, handler]` for a proxy, undefined otherwise.
11754fn op_util_proxy_details(
11755 scope: &mut v8::PinScope,
11756 args: v8::FunctionCallbackArguments,
11757 mut rv: v8::ReturnValue<v8::Value>,
11758) {
11759 let Ok(proxy) = v8::Local::<v8::Proxy>::try_from(args.get(0)) else {
11760 return;
11761 };
11762 let target = proxy.get_target(scope);
11763 let handler = proxy.get_handler(scope);
11764 rv.set(v8::Array::new_with_elements(scope, &[target, handler]).into());
11765}
11766
11767/// `[state]` for a pending promise, `[state, result]` otherwise,
11768/// undefined for a non-promise. States: 0 pending, 1 fulfilled, 2 rejected.
11769fn op_util_promise_details(
11770 scope: &mut v8::PinScope,
11771 args: v8::FunctionCallbackArguments,
11772 mut rv: v8::ReturnValue<v8::Value>,
11773) {
11774 let Ok(promise) = v8::Local::<v8::Promise>::try_from(args.get(0)) else {
11775 return;
11776 };
11777 let state = match promise.state() {
11778 v8::PromiseState::Pending => 0,
11779 v8::PromiseState::Fulfilled => 1,
11780 v8::PromiseState::Rejected => 2,
11781 };
11782 let pending = state == 0;
11783 let state: v8::Local<v8::Value> = v8::Integer::new(scope, state).into();
11784 let elements = if pending {
11785 vec![state]
11786 } else {
11787 vec![state, promise.result(scope)]
11788 };
11789 rv.set(v8::Array::new_with_elements(scope, &elements).into());
11790}
11791
11792/// `[entries, isKeyValue]` for collections and their iterators (V8's
11793/// PreviewEntries), undefined when V8 has no preview.
11794fn op_util_preview_entries(
11795 scope: &mut v8::PinScope,
11796 args: v8::FunctionCallbackArguments,
11797 mut rv: v8::ReturnValue<v8::Value>,
11798) {
11799 let Ok(obj) = v8::Local::<v8::Object>::try_from(args.get(0)) else {
11800 return;
11801 };
11802 let (entries, is_key_value) = obj.preview_entries(scope);
11803 let Some(entries) = entries else { return };
11804 let flag: v8::Local<v8::Value> = v8::Boolean::new(scope, is_key_value).into();
11805 rv.set(v8::Array::new_with_elements(scope, &[entries.into(), flag]).into());
11806}
11807
11808fn op_alarm_set(
11809 scope: &mut v8::PinScope,
11810 args: v8::FunctionCallbackArguments,
11811 _rv: v8::ReturnValue<v8::Value>,
11812) {
11813 let s = args.get(0).to_rust_string_lossy(scope);
11814 let at = args.get(1).number_value(scope).unwrap_or(0.0) as i64;
11815 let timing_started = (tracing::enabled!(target: "queue_timing", tracing::Level::DEBUG)
11816 && s.split_once(':')
11817 .is_some_and(|(class, _)| class == crate::deploy::QUEUE_CLASS))
11818 .then(crate::asyncrt::mono_us);
11819 let result = storage::set_alarm(&s, at);
11820 if let Some(timing_started) = timing_started {
11821 tracing::debug!(
11822 target: "queue_timing",
11823 event = "queue_alarm_write_timing",
11824 total_us = crate::asyncrt::mono_us().saturating_sub(timing_started),
11825 ok = result.is_ok(),
11826 "Queue alarm write completed"
11827 );
11828 }
11829 match result {
11830 Err(error) => throw_storage_error(scope, "setAlarm", error),
11831 // Committed immediately: register the wake-entry PUT against the
11832 // current event's output gate. Inside an explicit transaction (`Ok(None)`)
11833 // the gate registers at that transaction's commit instead.
11834 Ok(Some(committed)) if committed >= 0 => {
11835 spawn_arm_gate(&s, committed, current_reaction_io_context(scope))
11836 }
11837 Ok(_) => {}
11838 }
11839}
11840
11841/// Queue producer groups resolve promises from several cell events after one
11842/// event rearms the broker. The ordinary event-local arm gate cannot migrate
11843/// to those other events, so this internal variant awaits the wake-entry PUT
11844/// before the shared promise resolves. The later output gate still proves the
11845/// SQLite/LTX write; together they preserve the same acknowledgement boundary
11846/// as an ungrouped `setAlarm` call.
11847fn op_queue_alarm_set_wait(
11848 scope: &mut v8::PinScope,
11849 args: v8::FunctionCallbackArguments,
11850 mut rv: v8::ReturnValue<v8::Value>,
11851) {
11852 let cell = args.get(0).to_rust_string_lossy(scope);
11853 let at_ms = args.get(1).number_value(scope).unwrap_or(0.0) as i64;
11854 let committed = match storage::set_alarm(&cell, at_ms) {
11855 Ok(committed) => committed,
11856 Err(error) => {
11857 throw_storage_error(scope, "Queue setAlarm", error);
11858 return;
11859 }
11860 };
11861 let Some(committed) = committed.filter(|committed| *committed >= 0) else {
11862 return;
11863 };
11864 let Some(gate) = launch_arm_gate(&cell, observe_alarm(&cell, Some(committed))) else {
11865 return;
11866 };
11867 let id = asyncrt::enqueue(async move {
11868 match gate.await {
11869 Ok(Ok(())) => Ok(String::new()),
11870 Ok(Err(error)) => Err(format!("Queue wake-entry gate: {error}")),
11871 Err(_) => Err("Queue wake-entry gate task dropped".to_string()),
11872 }
11873 });
11874 rv.set(promise_for(scope, id));
11875}
11876fn op_alarm_get(
11877 scope: &mut v8::PinScope,
11878 args: v8::FunctionCallbackArguments,
11879 mut rv: v8::ReturnValue<v8::Value>,
11880) {
11881 let s = args.get(0).to_rust_string_lossy(scope);
11882 match storage::get_alarm(&s) {
11883 Some(at) => rv.set(v8::Number::new(scope, at as f64).into()),
11884 None => rv.set(v8::null(scope).into()),
11885 }
11886}
11887fn op_alarm_delete(
11888 scope: &mut v8::PinScope,
11889 args: v8::FunctionCallbackArguments,
11890 _rv: v8::ReturnValue<v8::Value>,
11891) {
11892 let s = args.get(0).to_rust_string_lossy(scope);
11893 if let Err(error) = storage::delete_alarm(&s) {
11894 throw_storage_error(scope, "deleteAlarm", error);
11895 }
11896}
11897
11898/// The reserved cron cell's whole schedule decision, in one call so the policy
11899/// has one home in `celld_logic::cron` rather than a JavaScript copy that can
11900/// drift from it.
11901///
11902/// `firedMs` is the occurrence being handled, or negative when the cell is
11903/// only arming. Returns `{ matching, armAt, armIsRetry }`: which expressions
11904/// the occurrence belongs to, by index into the list passed in, when to arm
11905/// next — `null` when the schedule is exhausted and the cell should retire —
11906/// and whether that deadline is the failure backoff rather than the next
11907/// occurrence.
11908fn op_cron_plan(
11909 scope: &mut v8::PinScope,
11910 args: v8::FunctionCallbackArguments,
11911 mut rv: v8::ReturnValue<v8::Value>,
11912) {
11913 let Ok(list) = v8::Local::<v8::Array>::try_from(args.get(0)) else {
11914 return;
11915 };
11916 let mut crons = Vec::with_capacity(list.length() as usize);
11917 // Where each parsed expression sits in the list the caller passed. A
11918 // malformed expression is already refused by `celld deploy`, but the
11919 // control plane checks only the field count, so one can still arrive here.
11920 // Skipping it keeps one bad entry from silencing a script's other crons,
11921 // and this map is what keeps the skip from renumbering them: the caller
11922 // reports `controller.cron` by index, so a shifted index names the wrong
11923 // expression for every entry after the bad one.
11924 let mut positions = Vec::with_capacity(list.length() as usize);
11925 for index in 0..list.length() {
11926 let Some(value) = list.get_index(scope, index) else {
11927 continue;
11928 };
11929 if let Ok(cron) = celld_logic::cron::parse(&value.to_rust_string_lossy(scope)) {
11930 crons.push(cron);
11931 positions.push(index as usize);
11932 }
11933 }
11934 let fired_ms = args.get(1).number_value(scope).unwrap_or(-1.0) as i64;
11935 let now_ms = args.get(2).number_value(scope).unwrap_or(0.0) as i64;
11936 let retry = args.get(3).number_value(scope).unwrap_or(0.0) as i64;
11937 let failed = args.get(4).boolean_value(scope);
11938
11939 let celld_logic::cron::Plan {
11940 matching,
11941 arm_at,
11942 arm_is_retry,
11943 } = celld_logic::cron::plan(
11944 &crons,
11945 (fired_ms >= 0).then_some(fired_ms),
11946 now_ms,
11947 retry,
11948 failed,
11949 );
11950
11951 let indices = v8::Array::new(scope, matching.len() as i32);
11952 for (slot, index) in matching.iter().enumerate() {
11953 let value = v8::Number::new(scope, positions[*index] as f64);
11954 indices.set_index(scope, slot as u32, value.into());
11955 }
11956 let result = v8::Object::new(scope);
11957 let key = v8::String::new(scope, "matching").unwrap();
11958 result.set(scope, key.into(), indices.into());
11959 let key = v8::String::new(scope, "armAt").unwrap();
11960 let value: v8::Local<v8::Value> = match arm_at {
11961 Some(at) => v8::Number::new(scope, at as f64).into(),
11962 None => v8::null(scope).into(),
11963 };
11964 result.set(scope, key.into(), value);
11965 let key = v8::String::new(scope, "armIsRetry").unwrap();
11966 let value = v8::Boolean::new(scope, arm_is_retry);
11967 result.set(scope, key.into(), value.into());
11968 rv.set(result.into());
11969}
11970
11971fn op_btoa(
11972 scope: &mut v8::PinScope,
11973 args: v8::FunctionCallbackArguments,
11974 mut rv: v8::ReturnValue<v8::Value>,
11975) {
11976 use base64::Engine;
11977 // The public `btoa()` wrapper always supplies a string. The KV operator
11978 // protocol supplies a typed view directly, which avoids constructing a
11979 // second 25 MiB binary string only to encode it here.
11980 let bytes = view_bytes(args.get(0)).unwrap_or_else(|| {
11981 args.get(0)
11982 .to_rust_string_lossy(scope)
11983 .chars()
11984 .map(|c| c as u8)
11985 .collect()
11986 });
11987 let s = base64::engine::general_purpose::STANDARD.encode(bytes);
11988 rv.set(v8::String::new(scope, &s).unwrap().into());
11989}
11990
11991// ---- WHATWG text decoders (encoding_rs) ----
11992//
11993// These ops back every TextDecoder decode. src/js/text_encoding.js
11994// resolves the label and owns the decoder's lifetime, and encoding_rs
11995// does the decoding — for utf-8 and utf-16 as much as for every other
11996// WHATWG label (windows-1252, Big5, GBK/GB18030, ISO-2022-JP,
11997// x-user-defined, …). Previous utf-8 and utf-16 JS decoders were slower
11998// than these ops at every measured size.
11999// Streaming decoders live in a per-isolate table keyed by id; JS frees
12000// one on the final decode (last=true), on a fatal error (encoding_rs
12001// poisons an errored decoder), or via FinalizationRegistry when a
12002// mid-stream decoder is abandoned. Ids are never reused, so a late
12003// finalizer free of an already-closed id is a no-op.
12004
12005/// Live streaming decoders for one isolate, keyed by an id JS holds across
12006/// awaits.
12007///
12008/// An isolate slot rather than a process-wide `Mutex<HashMap<..>>` like
12009/// [`zlib_streams`]. The reason that one is process-wide holds here too — a
12010/// `TextDecoder` in streaming mode outlives the turn that made it, and the
12011/// next turn can run on a different tokio worker — but it argues against a
12012/// *thread-local*, not against this. A `TextDecoder` is a JS object, so it
12013/// never leaves the isolate that made it, and every op that touches its
12014/// decoder runs under that isolate's `v8::Locker`. The lock the embedder
12015/// already holds is what makes the access exclusive, which `&mut Isolate`
12016/// on the slot then proves. A second lock inside it buys nothing.
12017///
12018/// This removes a ceiling rather than a measured regression, and the
12019/// difference matters. In isolation the pattern does collapse: replayed on
12020/// its own — remove, decode outside the lock, insert — 256-byte chunks
12021/// peaked at two threads and then went *backwards*, 8 threads serving
12022/// 0.46x what 1 thread served against 6.7x for the same decoding with no
12023/// table. But celld end to end shows no difference between the two, at any
12024/// concurrency this hardware can drive, because a chunk costs about 42us
12025/// of stream and turn machinery around a lock held for about 100ns. So the
12026/// mutex was not what any cell was waiting on. It was a process-wide
12027/// serialisation point on a path that every stream now takes, and it went
12028/// because it does not need to exist, not because it was costing anything
12029/// yet.
12030///
12031/// Dropping the isolate drops the table, so a decoder abandoned by a cell
12032/// that goes away needs no finalizer to run.
12033#[derive(Default)]
12034struct TextDecoders(HashMap<u64, encoding_rs::Decoder>);
12035
12036static TEXT_DECODER_NEXT: AtomicU64 = AtomicU64::new(1);
12037
12038/// The calling isolate's decoder table, created on first use.
12039fn text_decoders<'a>(scope: &'a mut v8::PinScope) -> &'a mut HashMap<u64, encoding_rs::Decoder> {
12040 if scope.get_slot::<TextDecoders>().is_none() {
12041 scope.set_slot(TextDecoders::default());
12042 }
12043 &mut scope.get_slot_mut::<TextDecoders>().expect("just set").0
12044}
12045
12046/// `$$textDecoderLabel(label)` -> canonical lowercase name, or undefined
12047/// for unknown labels and the replacement encoding (RangeError in JS).
12048fn op_text_decoder_label(
12049 scope: &mut v8::PinScope,
12050 args: v8::FunctionCallbackArguments,
12051 mut rv: v8::ReturnValue<v8::Value>,
12052) {
12053 let label = args.get(0).to_rust_string_lossy(scope);
12054 if let Some(enc) = encoding_rs::Encoding::for_label_no_replacement(label.as_bytes()) {
12055 let name = enc.name().to_ascii_lowercase();
12056 rv.set(v8::String::new(scope, &name).unwrap().into());
12057 }
12058}
12059
12060/// `$$textDecoderNew(name, ignoreBOM)` -> id.
12061fn op_text_decoder_new(
12062 scope: &mut v8::PinScope,
12063 args: v8::FunctionCallbackArguments,
12064 mut rv: v8::ReturnValue<v8::Value>,
12065) {
12066 let name = args.get(0).to_rust_string_lossy(scope);
12067 let ignore_bom = args.get(1).boolean_value(scope);
12068 let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label");
12069 let dec = if ignore_bom {
12070 enc.new_decoder_without_bom_handling()
12071 } else {
12072 enc.new_decoder_with_bom_removal()
12073 };
12074 let id = TEXT_DECODER_NEXT.fetch_add(1, Ordering::Relaxed);
12075 text_decoders(scope).insert(id, dec);
12076 rv.set(v8::Number::new(scope, id as f64).into());
12077}
12078
12079/// `$$textDecoderDecode(id, view, fatal, last)` -> string. Frees the
12080/// decoder when `last` is true or on a fatal malformed sequence
12081/// (TypeError).
12082fn op_text_decoder_decode(
12083 scope: &mut v8::PinScope,
12084 args: v8::FunctionCallbackArguments,
12085 mut rv: v8::ReturnValue<v8::Value>,
12086) {
12087 let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
12088 let bytes = view_bytes(args.get(1)).unwrap_or_default();
12089 let fatal = args.get(2).boolean_value(scope);
12090 let last = args.get(3).boolean_value(scope);
12091 // Per spec an empty streaming chunk is a no-op, but encoding_rs
12092 // 0.8 flushes a pending multibyte lead when fed an empty non-last
12093 // slice (e.g. Shift_JIS 0x82, "", 0xA0 would yield U+FFFD instead
12094 // of あ). Skip the decoder entirely.
12095 if bytes.is_empty() && !last {
12096 rv.set(v8::String::empty(scope).into());
12097 return;
12098 }
12099 let mut dec = text_decoders(scope)
12100 .remove(&id)
12101 .expect("JS holds the only live id");
12102 let Ok(out) = run_decoder(&mut dec, &bytes, fatal, last) else {
12103 throw_invalid_encoded_data(scope);
12104 return;
12105 };
12106 if !last {
12107 text_decoders(scope).insert(id, dec);
12108 }
12109 rv.set(v8::String::new(scope, &out).unwrap().into());
12110}
12111
12112/// `$$textDecoderDecodeOnce(name, view, fatal, ignoreBOM)` -> string, for
12113/// a complete buffer.
12114///
12115/// The whole decode is one call, so the decoder never outlives it and
12116/// never reaches [`text_decoders`]. That saves an insert and a remove,
12117/// and it keeps every non-streaming decode on the node off a table that
12118/// is one mutex for the whole process — which is most decodes, because
12119/// `request.text()` and `response.text()` are not streams. A stream
12120/// still takes that lock twice per chunk, which is a cost per chunk
12121/// rather than per byte, and it has not been measured under load;
12122/// sharding the table is the answer if it ever shows.
12123fn op_text_decoder_decode_once(
12124 scope: &mut v8::PinScope,
12125 args: v8::FunctionCallbackArguments,
12126 mut rv: v8::ReturnValue<v8::Value>,
12127) {
12128 let name = args.get(0).to_rust_string_lossy(scope);
12129 let bytes = view_bytes(args.get(1)).unwrap_or_default();
12130 let fatal = args.get(2).boolean_value(scope);
12131 let ignore_bom = args.get(3).boolean_value(scope);
12132 let enc = encoding_rs::Encoding::for_label(name.as_bytes()).expect("JS resolved the label");
12133 let mut dec = if ignore_bom {
12134 enc.new_decoder_without_bom_handling()
12135 } else {
12136 enc.new_decoder_with_bom_removal()
12137 };
12138 match run_decoder(&mut dec, &bytes, fatal, true) {
12139 Ok(out) => rv.set(v8::String::new(scope, &out).unwrap().into()),
12140 Err(()) => throw_invalid_encoded_data(scope),
12141 }
12142}
12143
12144/// Feeds `bytes` to `dec` and answers the text. `Err` means `fatal` was
12145/// set and the input was malformed.
12146fn run_decoder(
12147 dec: &mut encoding_rs::Decoder,
12148 bytes: &[u8],
12149 fatal: bool,
12150 last: bool,
12151) -> Result<String, ()> {
12152 let mut out = String::new();
12153 if fatal {
12154 let cap = dec
12155 .max_utf8_buffer_length_without_replacement(bytes.len())
12156 .unwrap();
12157 out.reserve(cap);
12158 if !matches!(
12159 dec.decode_to_string_without_replacement(bytes, &mut out, last),
12160 (encoding_rs::DecoderResult::InputEmpty, _),
12161 ) {
12162 return Err(());
12163 }
12164 } else {
12165 let cap = dec.max_utf8_buffer_length(bytes.len()).unwrap();
12166 out.reserve(cap);
12167 let _ = dec.decode_to_string(bytes, &mut out, last);
12168 }
12169 Ok(out)
12170}
12171
12172fn throw_invalid_encoded_data(scope: &mut v8::PinScope) {
12173 let msg = v8::String::new(scope, "The encoded data was not valid.").unwrap();
12174 let exc = v8::Exception::type_error(scope, msg);
12175 scope.throw_exception(exc);
12176}
12177
12178/// `$$textDecoderFree(id)` — FinalizationRegistry cleanup for a decoder
12179/// abandoned mid-stream.
12180fn op_text_decoder_free(
12181 scope: &mut v8::PinScope,
12182 args: v8::FunctionCallbackArguments,
12183 _rv: v8::ReturnValue<v8::Value>,
12184) {
12185 let id = args.get(0).integer_value(scope).unwrap_or(0) as u64;
12186 text_decoders(scope).remove(&id);
12187}
12188
12189// ---- the JS harness: Web API + the DO object model ----
12190
12191#[doc(hidden)]
12192pub mod bootstrap;
12193pub mod modules;
12194mod v8_strings;
12195use bootstrap::{
12196 adopt_cell, adopt_embedded_cell, begin_event_context, build_env, end_event_context,
12197 harness_env, inject_compatibility_flags, inject_containers, inject_crons, inject_kv_limits,
12198 inject_namespace_keys, inject_queue_config, inject_routing, inject_storage_compatibility,
12199 inject_workflows, install_harness, install_prelude, populate_cf_exports, register_class,
12200 register_entrypoints, validate_workflow_classes, EmbeddedStartup,
12201};
12202use modules::{
12203 compile_module, host_import_module_dynamically, install_lazy_globals, op_builtin_module,
12204 register_loader_modules, register_stubs, register_wasm_modules, resolve_external,
12205 ModuleRegistry,
12206};
12207use v8_strings::key as static_key;
12208/// Like `make_request`, but marks the request as incoming. Its signal is
12209/// registered only if the handler actually suspends, preserving the
12210/// synchronous request path.
12211fn make_incoming_request<'s>(
12212 tc: &mut v8::PinScope<'s, '_>,
12213 url: &str,
12214 method: &str,
12215 body: RequestBody,
12216 headers: &[(String, String)],
12217) -> Result<v8::Local<'s, v8::Value>> {
12218 let f = internal_function(tc, "__makeIncomingRequest")?;
12219 let url = v8::String::new(tc, url).unwrap();
12220 let method = v8::String::new(tc, method).unwrap();
12221 let headers = v8::String::new(
12222 tc,
12223 &serde_json::to_string(headers).unwrap_or_else(|_| "[]".into()),
12224 )
12225 .unwrap();
12226 // A streamed body passes its id, and the harness builds the body
12227 // stream around that id. A held body passes the bytes.
12228 let stream_id = body.stream_id();
12229 let (body, stream_id) = match stream_id {
12230 None => (
12231 bytes_value(tc, body.into_held_bytes().unwrap()),
12232 v8::undefined(tc).into(),
12233 ),
12234 Some(id) => (
12235 v8::undefined(tc).into(),
12236 v8::Number::new(tc, id as f64).into(),
12237 ),
12238 };
12239 let recv = v8::undefined(tc).into();
12240 f.call(
12241 tc,
12242 recv,
12243 &[url.into(), method.into(), body, headers.into(), stream_id],
12244 )
12245 .ok_or_else(|| anyhow!("__makeIncomingRequest threw"))
12246}
12247
12248fn register_incoming_request(
12249 tc: &mut v8::PinScope,
12250 request_id: RequestId,
12251 request: v8::Local<v8::Value>,
12252) -> Result<()> {
12253 let function = internal_function(tc, "__registerIncomingRequest")?;
12254 let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
12255 let recv = v8::undefined(tc).into();
12256 function
12257 .call(tc, recv, &[id.into(), request])
12258 .ok_or_else(|| anyhow!("__registerIncomingRequest threw"))?;
12259 Ok(())
12260}
12261
12262fn finish_incoming_request(tc: &mut v8::PinScope, request_id: RequestId) {
12263 let Ok(function) = internal_function(tc, "__finishIncomingRequest") else {
12264 return;
12265 };
12266 let id = v8::String::new(tc, &request_id_string(request_id)).unwrap();
12267 let recv = v8::undefined(tc).into();
12268 let _ = function.call(tc, recv, &[id.into()]);
12269}
12270
12271fn make_request<'s>(
12272 tc: &mut v8::PinScope<'s, '_>,
12273 url: &str,
12274 method: &str,
12275 body: RequestBody,
12276 headers: &[(String, String)],
12277) -> Result<v8::Local<'s, v8::Value>> {
12278 let f = internal_function(tc, "__makeRequest")?;
12279 let u = v8::String::new(tc, url).unwrap();
12280 let m = v8::String::new(tc, method).unwrap();
12281 let bytes = body.into_held_bytes().unwrap_or_default();
12282 let b = bytes_value(tc, bytes);
12283 let h = v8::String::new(tc, &serde_json::to_string(headers)?).unwrap();
12284 let recv = v8::undefined(tc).into();
12285 f.call(tc, recv, &[u.into(), m.into(), b, h.into()])
12286 .ok_or_else(|| anyhow!("makeRequest threw"))
12287}
12288
12289fn read_response(scope: &mut v8::PinScope, ret: v8::Local<v8::Value>) -> Result<HttpResponse> {
12290 let f = internal_function(scope, "__readResponse")?;
12291 let recv = v8::undefined(scope).into();
12292 let out = f
12293 .call(scope, recv, &[ret])
12294 .ok_or_else(|| anyhow!("readResponse threw"))?;
12295 // The harness response reader is synchronous. Keeping this assertion at
12296 // the native boundary prevents a future harness change from quietly
12297 // reintroducing a nested async runtime while an isolate is entered.
12298 if out.is_promise() {
12299 return Err(anyhow!("__readResponse returned a promise"));
12300 }
12301 let out = out.to_object(scope).ok_or_else(|| anyhow!("not object"))?;
12302 let ek = v8::String::new(scope, "error").unwrap();
12303 if let Some(error) = out.get(scope, ek.into()).filter(|value| value.is_string()) {
12304 return Err(anyhow!(error.to_rust_string_lossy(scope)));
12305 }
12306 let sk = v8::String::new(scope, "status").unwrap();
12307 let bk = v8::String::new(scope, "bodyBytes").unwrap();
12308 let tk = v8::String::new(scope, "bodyStreamId").unwrap();
12309 let hk = v8::String::new(scope, "headersJson").unwrap();
12310 let wk = v8::String::new(scope, "wsTargetJson").unwrap();
12311 let worker_wk = v8::String::new(scope, "workerSocketId").unwrap();
12312 let status = out
12313 .get(scope, sk.into())
12314 .and_then(|v| v.uint32_value(scope))
12315 .unwrap_or(200) as u16;
12316 // Body bytes cross as a Uint8Array copied directly out of V8 — no JSON
12317 // number array (which was ~4x the bytes to serialize + parse per response).
12318 let body = out
12319 .get(scope, bk.into())
12320 .and_then(|v| v8::Local::<v8::ArrayBufferView>::try_from(v).ok())
12321 .map(|view| {
12322 let mut buf = vec![0u8; view.byte_length()];
12323 view.copy_contents(&mut buf);
12324 buf
12325 })
12326 .unwrap_or_default();
12327 let stream_id = out
12328 .get(scope, tk.into())
12329 .and_then(|value| value.integer_value(scope))
12330 .unwrap_or(0)
12331 .max(0) as u64;
12332 let stream = if stream_id == 0 {
12333 None
12334 } else {
12335 http_stream_service()
12336 .checkout_transfer(stream_id, None)
12337 .ok()
12338 .map(|source| Box::pin(source) as HttpChunkStream)
12339 };
12340 if stream_id != 0 && stream.is_none() {
12341 return Err(anyhow!(
12342 "response stream {stream_id} is no longer available"
12343 ));
12344 }
12345 let headers = out
12346 .get(scope, hk.into())
12347 .and_then(|v| serde_json::from_str(&v.to_rust_string_lossy(scope)).ok())
12348 .unwrap_or_default();
12349 let ws_json = out
12350 .get(scope, wk.into())
12351 .map(|v| v.to_rust_string_lossy(scope))
12352 .unwrap_or_else(|| "null".into());
12353 let ws = serde_json::from_str(&ws_json).ok();
12354 let worker_id = out
12355 .get(scope, worker_wk.into())
12356 .and_then(|value| value.integer_value(scope))
12357 .unwrap_or(0)
12358 .max(0) as u64;
12359 let worker_ws = if worker_id == 0 {
12360 None
12361 } else {
12362 Some(
12363 websocket::transfer_worker_websocket_handoff(worker_id)
12364 .ok_or_else(|| anyhow!("Worker WebSocket {worker_id} has no frame handoff"))?,
12365 )
12366 };
12367 if status == 101 {
12368 tracing::info!(%ws_json, has_target = ws.is_some(), "JS WebSocket response");
12369 }
12370 let websocket = match (ws, worker_ws) {
12371 (Some(target), None) => Some(HttpResponseWebSocket::Cell(target)),
12372 (None, Some(worker)) => Some(HttpResponseWebSocket::Worker(worker)),
12373 (None, None) => None,
12374 (Some(_), Some(_)) => return Err(anyhow!("Worker response has two WebSocket targets")),
12375 };
12376 Ok(HttpResponse {
12377 status,
12378 body,
12379 stream,
12380 headers,
12381 websocket,
12382 write_position: None,
12383 observed_position: None,
12384 })
12385}
12386
12387#[cfg(celld_internal_tests)]
12388#[doc(hidden)]
12389pub fn init_engine_for_tests() {
12390 Engine::init();
12391}
12392
12393#[cfg(celld_internal_tests)]
12394include!(env!("CELLD_INTERNAL_JS_OBSERVERS"));