Diffinery

homeflare/celldpublic

celld/crates/celld/js/bootstrap.rs
1108 lines · 45.3 KBRaw History
1// Copyright 2026 Deno Land Inc. Apache-2.0 license.
2
3//! Isolate bootstrap: what a fresh context needs before user code runs.
4//!
5//! The prelude and the harness compile once per process and are cached, so a
6//! new isolate pays for execution but not for compilation. On top of those go
7//! the bindings — `env`, the routing table, the compatibility flags — which
8//! differ per worker and are therefore built every time.
9use super::*;
10
11/// Per-process compiled-bytecode cache for the fixed bootstrap scripts.
12/// Every cell wake pays a fresh isolate, and without this each one re-parses
13/// and re-compiles the same ~23k lines of prelude + harness — the single
14/// largest slice of cold-wake latency. The first isolate compiles
15/// eagerly and publishes the cache; every later isolate consumes it and only
16/// executes.
17///
18/// Keyed by script name alone. Each script compiles as a function whose
19/// parameter list is `op_names()`, and V8's cache check does not cover that
20/// list, so a cache is only valid while the list is the same for every
21/// isolate of the process. `op_names()` is fixed at build time; an op that
22/// varies per worker would have to enter the key.
23type BootstrapCache = std::collections::HashMap<&'static str, std::sync::Arc<Vec<u8>>>;
24
25macro_rules! static_source {
26 ($name:ident, $file:literal) => {
27 static $name: v8::OneByteConst =
28 v8::String::create_external_onebyte_const(include_bytes!($file));
29 };
30}
31
32struct BootstrapSource {
33 name: &'static str,
34 source: &'static v8::OneByteConst,
35}
36
37static_source!(TEXT_ENCODING_SOURCE, "text_encoding.js");
38static_source!(URL_SEARCH_PARAMS_SOURCE, "url_search_params.js");
39static_source!(URL_SOURCE, "url.js");
40static_source!(ATOB_BTOA_SOURCE, "atob_btoa.js");
41static_source!(HEADERS_SOURCE, "headers.js");
42static_source!(STREAMS_SOURCE, "streams.js");
43static_source!(WRITABLE_STREAM_SOURCE, "writable_stream.js");
44static_source!(TEXT_ENCODING_STREAMS_SOURCE, "text_encoding_streams.js");
45static_source!(MESSAGE_CHANNEL_SOURCE, "message_channel.js");
46static_source!(EVENT_SOURCE_SOURCE, "event_source.js");
47static_source!(CACHE_SOURCE, "cache.js");
48static_source!(SOCKETS_SOURCE, "sockets.js");
49static_source!(HTML_REWRITER_SOURCE, "html_rewriter.js");
50static_source!(CRYPTO_SOURCE, "crypto.js");
51
52static PRELUDE: &[BootstrapSource] = &[
53 BootstrapSource {
54 name: "text_encoding.js",
55 source: &TEXT_ENCODING_SOURCE,
56 },
57 BootstrapSource {
58 name: "url_search_params.js",
59 source: &URL_SEARCH_PARAMS_SOURCE,
60 },
61 BootstrapSource {
62 name: "url.js",
63 source: &URL_SOURCE,
64 },
65 BootstrapSource {
66 name: "atob_btoa.js",
67 source: &ATOB_BTOA_SOURCE,
68 },
69 BootstrapSource {
70 name: "headers.js",
71 source: &HEADERS_SOURCE,
72 },
73 BootstrapSource {
74 name: "streams.js",
75 source: &STREAMS_SOURCE,
76 },
77 BootstrapSource {
78 name: "writable_stream.js",
79 source: &WRITABLE_STREAM_SOURCE,
80 },
81 BootstrapSource {
82 name: "text_encoding_streams.js",
83 source: &TEXT_ENCODING_STREAMS_SOURCE,
84 },
85];
86
87static POST_HARNESS: &[BootstrapSource] = &[
88 BootstrapSource {
89 name: "message_channel.js",
90 source: &MESSAGE_CHANNEL_SOURCE,
91 },
92 BootstrapSource {
93 name: "event_source.js",
94 source: &EVENT_SOURCE_SOURCE,
95 },
96 BootstrapSource {
97 name: "cache.js",
98 source: &CACHE_SOURCE,
99 },
100 BootstrapSource {
101 name: "sockets.js",
102 source: &SOCKETS_SOURCE,
103 },
104 BootstrapSource {
105 name: "html_rewriter.js",
106 source: &HTML_REWRITER_SOURCE,
107 },
108 BootstrapSource {
109 name: "crypto.js",
110 source: &CRYPTO_SOURCE,
111 },
112];
113
114// The harness is fixed process data, so copying its ~450 KiB source into every
115// isolate only gives V8 another owner for the same bytes. `OneByteConst` keeps
116// one external buffer in the binary and checks the ASCII requirement at
117// compile time. Compiled code and the objects created by the script remain
118// isolate-local; this shares only the original source buffer.
119#[cfg(any(not(celld_internal_tests), all(test, celld_internal_tests)))]
120static HARNESS_SOURCE: v8::OneByteConst =
121 v8::String::create_external_onebyte_const(HARNESS.as_bytes());
122
123/// The harness and the services it shares with the workerd engine, which
124/// each end in a function declaration the harness calls.
125const HARNESS: &str = concat!(include_str!("harness.js"), include_str!("services/kv.js"));
126
127fn bootstrap_code_cache() -> &'static std::sync::Mutex<BootstrapCache> {
128 static CACHE: std::sync::OnceLock<std::sync::Mutex<BootstrapCache>> =
129 std::sync::OnceLock::new();
130 CACHE.get_or_init(Default::default)
131}
132
133#[cfg(celld_internal_tests)]
134fn run_bootstrap_script<'s>(
135 scope: &mut v8::PinScope<'s, '_>,
136 name: &'static str,
137 src: &str,
138 arguments: &InternalArguments<'s>,
139) -> Result<()> {
140 let code = v8::String::new(scope, src).unwrap();
141 run_internal_script(scope, Some(name), code, arguments)?;
142 Ok(())
143}
144
145fn run_bootstrap_static_script<'s>(
146 scope: &mut v8::PinScope<'s, '_>,
147 source: &'static BootstrapSource,
148 arguments: &InternalArguments<'s>,
149) -> Result<()> {
150 let code = v8_strings::source(scope, source.source);
151 run_internal_script(scope, Some(source.name), code, arguments)?;
152 Ok(())
153}
154
155/// Compile an internal script as one function whose parameters are the
156/// internals object and the host ops, and run it. A script and not a
157/// module, because the harness is one scope shared by every prelude file;
158/// a function and not a global script, because a global script's top-level
159/// declarations become bindings user code can name, and its ops would have
160/// to be globals too. Returns what the body `return`s: a lazy global's
161/// exports, or undefined.
162pub(super) fn run_internal_script<'s>(
163 scope: &mut v8::PinScope<'s, '_>,
164 cache: Option<&'static str>,
165 code: v8::Local<'s, v8::String>,
166 arguments: &InternalArguments<'s>,
167) -> Result<v8::Local<'s, v8::Value>> {
168 use v8::script_compiler::CompileOptions;
169 use v8::script_compiler::NoCacheReason;
170 let name = cache.unwrap_or("lazy script");
171 let cached = cache.and_then(|name| bootstrap_code_cache().lock().unwrap().get(name).cloned());
172 let function = match cached {
173 // `CachedData` borrows `bytes`; the Arc binding outlives the Source.
174 Some(bytes) => {
175 let data = v8::script_compiler::CachedData::new(&bytes);
176 let mut source = v8::script_compiler::Source::new_with_cached_data(code, None, data);
177 let function = v8::script_compiler::compile_function(
178 scope,
179 &mut source,
180 &arguments.names,
181 &[],
182 CompileOptions::ConsumeCodeCache,
183 NoCacheReason::NoReason,
184 )
185 .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
186 debug_assert!(
187 !source.get_cached_data().is_some_and(|data| data.rejected()),
188 "code cache rejected for {name}"
189 );
190 function
191 }
192 // Eager for a cached bootstrap script: a lazily-compiled cache would
193 // push function-body compile cost back into every consumer's first
194 // request. A lazy script keeps V8's lazy compile: most of a builtin
195 // module is never called.
196 None => {
197 let mut source = v8::script_compiler::Source::new(code, None);
198 let options = match cache {
199 Some(_) => CompileOptions::EagerCompile,
200 None => CompileOptions::NoCompileOptions,
201 };
202 let function = v8::script_compiler::compile_function(
203 scope,
204 &mut source,
205 &arguments.names,
206 &[],
207 options,
208 NoCacheReason::NoReason,
209 )
210 .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
211 if let Some((name, data)) = cache.zip(function.create_code_cache()) {
212 bootstrap_code_cache()
213 .lock()
214 .unwrap()
215 .insert(name, std::sync::Arc::new(data.to_vec()));
216 }
217 function
218 }
219 };
220 // The global receiver keeps top-level `this` what a script had.
221 let receiver = scope.get_current_context().global(scope).into();
222 function
223 .call(scope, receiver, &arguments.values)
224 .ok_or_else(|| anyhow!("bootstrap run {name}"))
225}
226
227#[cfg(all(test, celld_internal_tests))]
228pub(super) fn harness_source_for_test<'s>(
229 scope: &mut v8::PinScope<'s, '_>,
230) -> v8::Local<'s, v8::String> {
231 shipping_harness_source(scope)
232}
233
234#[cfg(all(test, celld_internal_tests))]
235pub(super) fn bootstrap_sources_for_test<'s>(
236 scope: &mut v8::PinScope<'s, '_>,
237) -> Vec<(&'static str, v8::Local<'s, v8::String>)> {
238 PRELUDE
239 .iter()
240 .chain(POST_HARNESS)
241 .map(|source| (source.name, v8_strings::source(scope, source.source)))
242 .collect()
243}
244
245#[cfg(any(not(celld_internal_tests), all(test, celld_internal_tests)))]
246fn shipping_harness_source<'s>(scope: &mut v8::PinScope<'s, '_>) -> v8::Local<'s, v8::String> {
247 v8::String::new_from_onebyte_const(scope, &HARNESS_SOURCE).expect("static harness source")
248}
249
250/// WPT-conformant Web APIs: TextEncoder, URL/URLSearchParams, atob/btoa, and
251/// Headers. Run once per isolate before the Cells/Cloudflare-specific harness.
252pub(super) fn install_prelude<'s>(
253 scope: &mut v8::PinScope<'s, '_>,
254 arguments: &InternalArguments<'s>,
255) -> Result<()> {
256 for source in PRELUDE {
257 run_bootstrap_static_script(scope, source, arguments)?;
258 }
259 Ok(())
260}
261
262pub(super) fn install_harness<'s>(
263 scope: &mut v8::PinScope<'s, '_>,
264 arguments: &InternalArguments<'s>,
265) -> Result<()> {
266 #[cfg(celld_internal_tests)]
267 let harness = HARNESS
268 .replace(
269 "/*__CELLD_TEST_WORKFLOW_EVENT_CONSUMED__*/",
270 "__test_workflow_event_consumed();",
271 )
272 .replace(
273 "/*__CELLD_TEST_WORKFLOW_META_CREATED__*/",
274 "__test_workflow_meta_created();",
275 )
276 .replace(
277 "/*__CELLD_TEST_WORKFLOW_TERMINAL_ALARM_SET__*/",
278 "__test_workflow_terminal_alarm_set();",
279 )
280 .replace(
281 "/*__CELLD_TEST_WORKFLOW_BEFORE_PAUSE_SETTLE__*/",
282 concat!(
283 "if (globalThis.__test_workflow_pause_settle_race === true) { ",
284 "await this.__wfResume(); ",
285 "globalThis.__test_workflow_pause_settle_race = false; }"
286 ),
287 )
288 .replace(
289 "/*__CELLD_TEST_WORKFLOW_AFTER_RUN_STARTED__*/",
290 concat!(
291 "if (globalThis.__test_workflow_pause_settle_race === true) { ",
292 "await globalThis.__test_workflow_callback_started(); ",
293 "await this.__wfPause(); globalThis.__test_workflow_release(); }"
294 ),
295 );
296 #[cfg(celld_internal_tests)]
297 run_bootstrap_script(scope, "harness.js", harness.as_str(), arguments)?;
298 #[cfg(not(celld_internal_tests))]
299 {
300 let harness = shipping_harness_source(scope);
301 run_internal_script(scope, Some("harness.js"), harness, arguments)?;
302 }
303 // After the harness: both build on its EventTarget, and EventSource
304 // uses its fetch and timers.
305 for source in POST_HARNESS {
306 run_bootstrap_static_script(scope, source, arguments)?;
307 }
308 // Resolving the event hooks belongs to installing the harness, not to the
309 // first event: the harness is what defines them, and a caller that
310 // installed the harness without them would silently fall back to nothing
311 // at all. `harness.js` has just run, so all four globals exist here.
312 install_event_hooks(scope)
313}
314
315/// Resolve the per-event harness hooks once and hold them for the isolate.
316/// See [`EventHooks`] for why all four resolve together.
317fn install_event_hooks(scope: &mut v8::PinScope) -> Result<()> {
318 let hooks = EventHooks {
319 begin_event: internal_global(scope, "__beginEvent")?,
320 end_event: internal_global(scope, "__endEvent")?,
321 advance_io_time: internal_global(scope, "__advanceIoTime")?,
322 abort_incoming_request: internal_global(scope, "__abortIncomingRequest")?,
323 };
324 actor_runtime_state(scope)
325 .event_hooks
326 .set(hooks)
327 .map_err(|_| anyhow!("event hooks were already installed"))
328}
329
330fn internal_global(scope: &mut v8::PinScope, name: &str) -> Result<v8::Global<v8::Function>> {
331 let function = internal_function(scope, name)?;
332 Ok(v8::Global::new(scope, function))
333}
334
335pub(super) fn register_class(
336 scope: &mut v8::PinScope,
337 name: &str,
338 cls: v8::Local<v8::Value>,
339) -> Result<()> {
340 let cell = cell_state(scope)?;
341 let clk = v8::String::new(scope, "classes").unwrap();
342 let classes = cell
343 .get(scope, clk.into())
344 .unwrap()
345 .to_object(scope)
346 .unwrap();
347 let nk = v8::String::new(scope, name).unwrap();
348 classes.set(scope, nk.into(), cls);
349 Ok(())
350}
351
352/// Populate `cloudflare:workers` `exports` with the worker module's own exports:
353/// a Durable Object class is exposed as its namespace (idFromName/get/RPC), any
354/// other export by value. `default` is omitted (it is the fetch entrypoint, not
355/// an importable export). Mirrors Workerd's `import { exports }` surface.
356pub(super) fn populate_cf_exports(
357 scope: &mut v8::PinScope,
358 ns: v8::Local<v8::Object>,
359 do_classes: &[String],
360) -> Result<()> {
361 let cf = internal_object(scope, "__cf")?;
362 let exports = cf
363 .get(scope, v8::String::new(scope, "exports").unwrap().into())
364 .and_then(|value| value.to_object(scope))
365 .ok_or_else(|| anyhow!("missing __cf.exports"))?;
366 let cell = cell_state(scope)?;
367 let make_ns: v8::Local<v8::Function> = cell
368 .get(
369 scope,
370 v8::String::new(scope, "makeNamespace").unwrap().into(),
371 )
372 .and_then(|value| value.try_into().ok())
373 .ok_or_else(|| anyhow!("missing __cell.makeNamespace"))?;
374 let do_set: std::collections::HashSet<&str> = do_classes.iter().map(String::as_str).collect();
375 let names = ns
376 .get_own_property_names(scope, Default::default())
377 .ok_or_else(|| anyhow!("no module export names"))?;
378 for index in 0..names.length() {
379 let name_value = names.get_index(scope, index).unwrap();
380 let name = name_value.to_rust_string_lossy(scope);
381 if name == "default" {
382 continue;
383 }
384 let export_value = if do_set.contains(name.as_str()) {
385 let arg = v8::String::new(scope, &name).unwrap().into();
386 make_ns
387 .call(scope, cell.into(), &[arg])
388 .ok_or_else(|| anyhow!("makeNamespace({name}) failed"))?
389 } else {
390 ns.get(scope, name_value)
391 .ok_or_else(|| anyhow!("export {name}"))?
392 };
393 let key = v8::String::new(scope, &name).unwrap();
394 exports.set(scope, key.into(), export_value);
395 }
396 Ok(())
397}
398
399pub(super) fn inject_namespace_keys(
400 scope: &mut v8::PinScope,
401 script_name: &str,
402 do_classes: &[String],
403) -> Result<()> {
404 let cell = cell_state(scope)?;
405 let keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
406 let keys = cell
407 .get(scope, keys_key.into())
408 .and_then(|value| value.to_object(scope))
409 .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
410 let script_key = v8::String::new(scope, "script").unwrap();
411 let script_value = v8::String::new(scope, script_name).unwrap();
412 cell.set(scope, script_key.into(), script_value.into());
413 for class_name in do_classes {
414 let class_key = v8::String::new(scope, class_name).unwrap();
415 let namespace_key = super::namespace_key(script_name, class_name);
416 let namespace_key = v8::String::new(scope, &namespace_key).unwrap();
417 if !keys
418 .set(scope, class_key.into(), namespace_key.into())
419 .unwrap_or(false)
420 {
421 anyhow::bail!("could not register namespace key for {class_name}");
422 }
423 }
424 Ok(())
425}
426
427/// `__cell.crons`: the deployment's cron trigger expressions, verbatim as the
428/// developer wrote them. The reserved cron cell reads them at each activation,
429/// so a schedule change arrives with the deployment and needs no migration of
430/// an alarm the previous deployment armed. Absent `triggers.crons`, the list
431/// is empty and the cron cell retires itself.
432pub(super) fn inject_crons(scope: &mut v8::PinScope, crons: &[String]) -> Result<()> {
433 let cell = cell_state(scope)?;
434 let list = v8::Array::new(scope, crons.len() as i32);
435 for (index, cron) in crons.iter().enumerate() {
436 let value = v8::String::new(scope, cron).ok_or_else(|| anyhow!("cron expression"))?;
437 list.set_index(scope, index as u32, value.into());
438 }
439 let key = v8::String::new(scope, "crons").unwrap();
440 cell.set(scope, key.into(), list.into());
441 Ok(())
442}
443
444/// `__cell.workflows`: the deployment's workflow-name → class-name map. The
445/// reserved workflow cell resolves the user class from it at each replay, so
446/// a redeploy that renames the class takes effect on the next activation and
447/// nothing about a running instance's ledger has to move.
448pub(super) fn inject_workflows(
449 scope: &mut v8::PinScope,
450 script_name: &str,
451 workflow_bindings: &[WorkflowBinding],
452) -> Result<()> {
453 let cell = cell_state(scope)?;
454 let map = v8::Object::new(scope);
455 for binding in workflow_bindings {
456 let key =
457 v8::String::new(scope, &binding.workflow).ok_or_else(|| anyhow!("workflow name"))?;
458 let value =
459 v8::String::new(scope, &binding.class).ok_or_else(|| anyhow!("workflow class"))?;
460 map.set(scope, key.into(), value.into());
461 }
462 let key = v8::String::new(scope, "workflows").unwrap();
463 cell.set(scope, key.into(), map.into());
464 // Only when the deployment declares a workflow. The harness registers
465 // `__WorkflowCell` in every isolate, so aliasing unconditionally would put
466 // a class in the registry that this deployment never declared. It would be
467 // inert -- `cell_configs` is built from the manifest's `do_classes` and
468 // would not name it -- but "the harness registers what the deployment
469 // declares" is worth keeping true rather than nearly true.
470 if !workflow_bindings.is_empty() {
471 alias_workflow_class(scope, cell, script_name)?;
472 }
473 Ok(())
474}
475
476/// `__cell.containers`: the classes whose objects get a `ctx.container`.
477/// A class outside this map gets none, which is what the
478/// `@cloudflare/containers` constructor checks.
479pub(super) fn inject_containers(
480 scope: &mut v8::PinScope,
481 containers: &[crate::container::ContainerSpec],
482) -> Result<()> {
483 let cell = cell_state(scope)?;
484 let map = v8::Object::new(scope);
485 for spec in containers {
486 let key =
487 v8::String::new(scope, &spec.class_name).ok_or_else(|| anyhow!("container class"))?;
488 let value = v8::Boolean::new(scope, true);
489 map.set(scope, key.into(), value.into());
490 }
491 let key = v8::String::new(scope, "containers").unwrap();
492 cell.set(scope, key.into(), map.into());
493 Ok(())
494}
495
496/// Register the workflow cell class under its script-scoped name.
497///
498/// `harness.js` registers `__WorkflowCell` under the bare `__Workflow` at
499/// install time, which is before `__cell.script` exists, so the script-scoped
500/// name cannot be built there. This copies the registration across once the
501/// script is known.
502///
503/// The bare entry stays behind and is inert: `cell_configs` is built from the
504/// manifest's `do_classes`, which carries only the scoped name, so no cell can
505/// start under it. Removing it would buy nothing and would leave the harness
506/// and this function disagreeing about who owns the registration. Done through the V8 object API rather than a compiled
507/// snippet, because this runs on every isolate load and a `Script::compile`
508/// here cost ~100us per worker.
509fn alias_workflow_class(
510 scope: &mut v8::PinScope,
511 cell: v8::Local<v8::Object>,
512 script_name: &str,
513) -> Result<()> {
514 let alias = crate::deploy::workflow_class(script_name);
515 let alias = v8::String::new(scope, &alias).ok_or_else(|| anyhow!("workflow class name"))?;
516 let base = v8::String::new(scope, crate::deploy::WORKFLOW_CLASS).unwrap();
517 for registry in ["classes", "doExports"] {
518 let key = v8::String::new(scope, registry).unwrap();
519 let table = cell
520 .get(scope, key.into())
521 .and_then(|value| value.to_object(scope))
522 .ok_or_else(|| anyhow!("missing __cell.{registry}"))?;
523 let value = table
524 .get(scope, base.into())
525 .ok_or_else(|| anyhow!("harness registered no {registry} entry for a workflow"))?;
526 table.set(scope, alias.into(), value);
527 }
528 Ok(())
529}
530
531/// `__cell.kvLimits`: every bound `celld_logic::kv` declares, as data.
532///
533/// Injected rather than written in `harness.js` so the binding, `celld kv` and
534/// deploy-time validation cannot disagree about what a valid key is. No host
535/// op: a limit is data rather than a decision, so shipping the values is
536/// enough, and D1 set the bar at one op with Workflows coming in under it.
537///
538/// Built through the V8 object API rather than by compiling a snippet, because
539/// this runs on every isolate load.
540pub(super) fn inject_kv_limits(scope: &mut v8::PinScope) -> Result<()> {
541 let cell = cell_state(scope)?;
542 let limits = v8::Object::new(scope);
543 let entries = crate::kv_blob::limits();
544 for (name, value) in entries.as_object().expect("kv limits are an object") {
545 let key = v8::String::new(scope, name).unwrap();
546 let value: v8::Local<v8::Value> = match value {
547 serde_json::Value::Bool(flag) => v8::Boolean::new(scope, *flag).into(),
548 other => v8::Number::new(scope, other.as_f64().expect("kv limit")).into(),
549 };
550 limits.set(scope, key.into(), value);
551 }
552 let key = v8::String::new(scope, "kvLimits").unwrap();
553 cell.set(scope, key.into(), limits.into());
554 Ok(())
555}
556
557/// `globalThis.Cloudflare.compatibilityFlags`. Only flags Cells actually
558/// honours are listed; a flag Cells does not model is absent (falsy) rather
559/// than reported as enabled.
560///
561/// Built through the V8 object API rather than by compiling a snippet: this
562/// runs on every isolate load, and a separate `Script::compile` there cost
563/// ~100us per worker.
564pub(super) fn inject_compatibility_flags(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
565 let context = scope.get_current_context();
566 let global = context.global(scope);
567 let flags = v8::Object::new(scope);
568 let set_flag = |scope: &mut v8::PinScope, name: &str, value: bool| {
569 let key = v8::String::new(scope, name).unwrap();
570 let value = v8::Boolean::new(scope, value);
571 flags.set(scope, key.into(), value.into());
572 };
573 set_flag(scope, "upper_case_all_http_methods", true);
574 // Cells' async stream/pipe methods return rejected promises
575 // rather than throwing synchronously, which is exactly the
576 // behavior this flag names.
577 set_flag(scope, "capture_async_api_throws", true);
578 set_flag(
579 scope,
580 "delete_all_deletes_alarm",
581 compat.delete_all_deletes_alarm,
582 );
583 set_flag(scope, "js_rpc", compat.js_rpc);
584 set_flag(scope, "sqlite_vec", compat.sqlite_vec);
585 set_flag(
586 scope,
587 "fetcher_no_get_put_delete",
588 !compat.fetcher_get_put_delete,
589 );
590 let cloudflare = v8::Object::new(scope);
591 let key = v8::String::new(scope, "compatibilityFlags").unwrap();
592 cloudflare.set(scope, key.into(), flags.into());
593 let key = v8::String::new(scope, "Cloudflare").unwrap();
594 global.set(scope, key.into(), cloudflare.into());
595 Ok(())
596}
597
598pub(super) fn build_env(scope: &mut v8::PinScope, config: &WorkerConfig) -> Result<()> {
599 let script_name = config.script_name.as_str();
600 let bindings = config.bindings.as_slice();
601 let r2_bindings = config.r2_bindings.as_slice();
602 let d1_bindings = config.d1_bindings.as_slice();
603 let kv_bindings = config.kv_bindings.as_slice();
604 let queue_bindings = config.queue_bindings.as_slice();
605 let workflow_bindings = config.workflow_bindings.as_slice();
606 let vars = config.vars.as_slice();
607 let services = config.services.as_slice();
608 let asset_binding = config.asset_binding.as_deref();
609 // call the harness: for each binding, env[bindingName] = makeNamespace(className)
610 let src = {
611 let mut lines = String::from("const e = __celld.__cell.env;\n");
612 for (bname, cname) in bindings {
613 lines.push_str(&format!(
614 "e[{:?}] = __celld.__cell.makeNamespace({:?});\n",
615 bname, cname
616 ));
617 }
618 for (name, bucket) in r2_bindings {
619 lines.push_str(&format!(
620 "e[{:?}] = __celld.__makeR2Bucket({:?}, {:?});\n",
621 name, name, bucket
622 ));
623 }
624 for (binding, id) in kv_bindings {
625 // The cell name comes from `celld_logic::kv::cell_name`, never from
626 // the harness. It carries the shard, and while there is one shard
627 // that is a constant the binding must not be trusted to reproduce:
628 // the name is hashed into the cell scope, so a formatting
629 // disagreement would silently address a second, empty namespace
630 // rather than fail. When shards outnumber one, this becomes a name
631 // per shard and the choice moves here too.
632 lines.push_str(&format!(
633 "e[{:?}] = __celld.__makeKvNamespace({:?}, {:?});\n",
634 binding,
635 id,
636 celld_logic::kv::cell_name(id, 0),
637 ));
638 }
639 for binding in queue_bindings {
640 lines.push_str(&format!(
641 "e[{:?}] = __celld.__makeQueue({:?}, {:?}, {});\n",
642 binding.environment,
643 binding.queue,
644 celld_logic::queue::cell_name(&binding.queue),
645 binding.delivery_delay,
646 ));
647 }
648 for (name, database) in d1_bindings {
649 lines.push_str(&format!(
650 "e[{:?}] = __celld.__makeD1Database({:?});\n",
651 name, database
652 ));
653 }
654 for binding in workflow_bindings {
655 lines.push_str(&format!(
656 "e[{:?}] = __celld.__makeWorkflow({:?});\n",
657 binding.environment, binding.workflow
658 ));
659 }
660 for (binding, script, entrypoint) in services {
661 let entrypoint = match entrypoint {
662 Some(name) => format!("{name:?}"),
663 None => "null".to_string(),
664 };
665 lines.push_str(&format!(
666 "e[{:?}] = __celld.__makeServiceBinding({:?}, {});\n",
667 binding, script, entrypoint
668 ));
669 }
670 for (name, value) in vars {
671 lines.push_str(&format!("e[{:?}] = {:?};\n", name, value));
672 }
673 if let Some(name) = asset_binding {
674 lines.push_str(&format!(
675 "e[{:?}] = __celld.__makeAssetsBinding({:?});\n",
676 name, script_name
677 ));
678 }
679 // One `__makeLoader()` call for each binding. Each call builds its own
680 // `byName` cache, so two loaders are two namespaces, as they are in
681 // workerd. Sharing one loader object between the names would merge the
682 // caches and return one Worker for two different `get()` calls.
683 for name in &config.loader_bindings {
684 lines.push_str(&format!("e[{:?}] = __celld.__makeLoader();\n", name));
685 }
686 // Version metadata (Homeflare patch): a frozen {id, tag, timestamp},
687 // as on Cloudflare.
688 if let Some((name, value)) = &config.version_metadata {
689 lines.push_str(&format!("e[{:?}] = Object.freeze({});\n", name, value));
690 }
691 // Media Transformations (Homeflare patch): the binding posts to the
692 // node's media service, or says it has none.
693 if !config.media_bindings.is_empty() {
694 let service = std::env::var("CELLD_MEDIA_URL")
695 .ok()
696 .filter(|url| !url.trim().is_empty());
697 let service = serde_json::to_string(&service).unwrap_or_else(|_| "null".into());
698 for name in &config.media_bindings {
699 lines.push_str(&format!(
700 "e[{:?}] = __celld.__makeMediaBinding({:?}, {});\n",
701 name, name, service
702 ));
703 }
704 }
705 lines
706 };
707 run_internal_snippet(scope, &src).ok_or_else(|| anyhow!("env install failed"))?;
708 if let Some(env) = &config.loader_env {
709 let installer = internal_function(scope, "__installLoaderEnv")?;
710 // A flat [script, entrypoint, props, ...] array avoids one V8 array
711 // allocation for every capability that the parent transfers.
712 let routes = v8::Array::new(scope, env.routes.len().saturating_mul(3) as i32);
713 for (index, route) in env.routes.iter().enumerate() {
714 let offset = (index * 3) as u32;
715 let script = v8::String::new(scope, &route.script).unwrap();
716 routes.set_index(scope, offset, script.into());
717 let entrypoint: v8::Local<v8::Value> = match &route.entrypoint {
718 Some(name) => v8::String::new(scope, name).unwrap().into(),
719 None => v8::null(scope).into(),
720 };
721 routes.set_index(scope, offset + 1, entrypoint);
722 let props = super::bytes_value(scope, route.props.clone());
723 routes.set_index(scope, offset + 2, props);
724 }
725 let bytes = super::bytes_value(scope, env.bytes.clone());
726 let tc = std::pin::pin!(v8::TryCatch::new(scope));
727 let tc = &mut tc.init();
728 let receiver = v8::undefined(tc).into();
729 installer
730 .call(tc, receiver, &[bytes, routes.into()])
731 .ok_or_else(|| anyhow!("loader env install: {}", exc!(tc)))?;
732 }
733 Ok(())
734}
735
736/// Install the deployment-wide Queue consumer catalog and lease budget.
737///
738/// Every co-hosted config gets the same catalog before an isolate starts, so a
739/// shared `__Queue` class cannot dispatch according to whichever producer
740/// registered the class first.
741pub(super) fn inject_queue_config(scope: &mut v8::PinScope, config: &WorkerConfig) -> Result<()> {
742 let queue = crate::queue_policy::consumer_config(config)?;
743 let source = format!(
744 "const q = {queue};\n\
745 const c = __celld.__cell;\n\
746 c.queueConsumers = q.consumers;\n\
747 c.queueLeaseDurationMs = q.leaseDurationMs;\n\
748 c.queueLimits = q.limits;"
749 );
750 run_internal_snippet(scope, &source).ok_or_else(|| anyhow!("queue config install failed"))?;
751 Ok(())
752}
753
754/// Record every exported class deriving from `WorkerEntrypoint` in
755/// `__cell.entrypoints`, so a service binding with `entrypoint = "Name"` can
756/// resolve it, and every export deriving from `DurableObject` in
757/// `__cell.doExports`, so misrouting a DO class as a stateless entrypoint is
758/// reported as such (Workerd getExportedHandler()). Every class export that
759/// is not an entrypoint or a workflow also lands in `__cell.classes`, so a
760/// facet can start it. Runs once per load; the check is a prototype walk, not a
761/// call into user code.
762pub(super) fn register_entrypoints(
763 scope: &mut v8::PinScope,
764 ns: v8::Local<v8::Object>,
765) -> Result<()> {
766 let cell = cell_state(scope)?;
767 let key = v8::String::new(scope, "entrypoints").unwrap();
768 let entrypoints = cell
769 .get(scope, key.into())
770 .and_then(|value| value.to_object(scope))
771 .ok_or_else(|| anyhow!("missing entrypoint registry"))?;
772 let key = v8::String::new(scope, "objectEntrypoints").unwrap();
773 let object_entrypoints = cell
774 .get(scope, key.into())
775 .and_then(|value| value.to_object(scope))
776 .ok_or_else(|| anyhow!("missing object-entrypoint registry"))?;
777 let key = v8::String::new(scope, "doExports").unwrap();
778 let do_exports = cell
779 .get(scope, key.into())
780 .and_then(|value| value.to_object(scope))
781 .ok_or_else(|| anyhow!("missing doExports registry"))?;
782 let key = v8::String::new(scope, "classes").unwrap();
783 let classes = cell
784 .get(scope, key.into())
785 .and_then(|value| value.to_object(scope))
786 .ok_or_else(|| anyhow!("missing Durable Object class registry"))?;
787 let cf = internal_object(scope, "__cf")?;
788 let key = v8::String::new(scope, "WorkerEntrypoint").unwrap();
789 let entrypoint_base = cf
790 .get(scope, key.into())
791 .ok_or_else(|| anyhow!("missing WorkerEntrypoint base"))?;
792 let key = v8::String::new(scope, "DurableObject").unwrap();
793 let durable_base = cf
794 .get(scope, key.into())
795 .ok_or_else(|| anyhow!("missing DurableObject base"))?;
796 let key = v8::String::new(scope, "WorkflowEntrypoint").unwrap();
797 let workflow_base = cf
798 .get(scope, key.into())
799 .ok_or_else(|| anyhow!("missing WorkflowEntrypoint base"))?;
800 let Some(names) = ns.get_own_property_names(scope, Default::default()) else {
801 return Ok(());
802 };
803 let yes = v8::Boolean::new(scope, true);
804 let extends = compile_fn(scope, EXTENDS_SRC)?;
805 for index in 0..names.length() {
806 let Some(name) = names.get_index(scope, index) else {
807 continue;
808 };
809 let Some(value) = ns.get(scope, name) else {
810 continue;
811 };
812 if !value.is_function() {
813 // A plain-object export is Workerd's non-class entrypoint; its
814 // handler functions dispatch as fn(arg, env, ctx).
815 if value.is_object() {
816 object_entrypoints.set(scope, name, value);
817 }
818 continue;
819 }
820 // Walk the prototype chain rather than calling anything. The walk
821 // runs in JS: Reflect.getPrototypeOf honors Proxy exports (SDK shims
822 // like workers-rs wrap their classes), which the host-side
823 // Object::GetPrototype does not.
824 if call_extends(scope, extends, value, entrypoint_base)? {
825 entrypoints.set(scope, name, value);
826 } else if call_extends(scope, extends, value, durable_base)? {
827 do_exports.set(scope, name, yes.into());
828 classes.set(scope, name, value);
829 } else if !call_extends(scope, extends, value, workflow_base)? {
830 // Workerd processEntrypointClass(): a class that extends none of
831 // the runtime bases is a Durable Object class (missingSuperclass).
832 // A loaded Worker's facet class reaches `_instance` only through
833 // this registry, so without it a plain class fails with "no DO
834 // class". It stays out of `doExports`: that entry grants RPC
835 // without the js_rpc flag, which workerd gives only a subclass.
836 classes.set(scope, name, value);
837 }
838 }
839 Ok(())
840}
841
842/// Validate the deployment's workflow classes at load: each configured
843/// `class_name` must be a module export that extends `WorkflowEntrypoint`
844/// from `cloudflare:workers`, so a wrong class fails the load loudly,
845/// exactly as a Durable Object export does. The per-replay resolution off
846/// `__cell.workflows` and `__cf.exports` is unchanged; this checks the same
847/// names once, up front, instead of erroring the first instance at run time.
848pub(super) fn validate_workflow_classes(
849 scope: &mut v8::PinScope,
850 ns: v8::Local<v8::Object>,
851 workflow_bindings: &[WorkflowBinding],
852) -> Result<()> {
853 if workflow_bindings.is_empty() {
854 return Ok(());
855 }
856 let cf = internal_object(scope, "__cf")?;
857 let key = v8::String::new(scope, "WorkflowEntrypoint").unwrap();
858 let base = cf
859 .get(scope, key.into())
860 .ok_or_else(|| anyhow!("missing WorkflowEntrypoint base"))?;
861 let extends = compile_fn(scope, EXTENDS_SRC)?;
862 for binding in workflow_bindings {
863 let class_name = binding.class.as_str();
864 let key = v8::String::new(scope, class_name).unwrap();
865 let class = ns
866 .get(scope, key.into())
867 .filter(|value| !value.is_undefined())
868 .ok_or_else(|| {
869 anyhow!("workflow class {class_name} is not exported by the Worker module")
870 })?;
871 if !class.is_function() || !call_extends(scope, extends, class, base)? {
872 anyhow::bail!(
873 "workflow class {class_name} must extend WorkflowEntrypoint \
874 from cloudflare:workers"
875 );
876 }
877 }
878 Ok(())
879}
880
881/// `(cls, base) => base is on cls's prototype chain`, via Reflect so Proxy
882/// wrappers report the prototype their handler exposes. A getPrototypeOf trap
883/// also makes the chain user-controlled (a cycle, or a fresh Proxy per hop,
884/// is spec-legal on an extensible target), so track visited links and cap the
885/// walk rather than let it hang the load.
886const EXTENDS_SRC: &str = "((cls, base) => { \
887 const seen = new Set(); \
888 for (let p = Reflect.getPrototypeOf(cls); p; p = Reflect.getPrototypeOf(p)) { \
889 if (p === base) return true; \
890 if (seen.has(p) || seen.size >= 1000) return false; \
891 seen.add(p); \
892 } \
893 return false; })";
894
895/// The walk crosses into user code when an export is a Proxy, so it can throw
896/// (a revoked Proxy, a throwing getPrototypeOf trap). Pin a TryCatch and
897/// surface that as a load error rather than misclassifying the export.
898fn call_extends(
899 scope: &mut v8::PinScope,
900 extends: v8::Local<v8::Function>,
901 class: v8::Local<v8::Value>,
902 base: v8::Local<v8::Value>,
903) -> Result<bool> {
904 let tc = std::pin::pin!(v8::TryCatch::new(scope));
905 let scope = &mut tc.init();
906 let recv = v8::undefined(scope).into();
907 match extends.call(scope, recv, &[class, base]) {
908 Some(result) => Ok(result.is_true()),
909 None => Err(anyhow!("inspect export prototype chain: {}", exc!(scope))),
910 }
911}
912
913/// Record the node id. Every cell scope routes through the host, whichever node
914/// owns it.
915pub(super) fn inject_routing(scope: &mut v8::PinScope, node: &str) -> Result<()> {
916 let src = format!("__celld.__cell.node = {node:?};");
917 run_internal_snippet(scope, &src).ok_or_else(|| anyhow!("routing install failed"))?;
918 Ok(())
919}
920
921/// Release a cell's instance and restore its id name.
922///
923/// The isolate-side half of taking a cell in or giving it back: taking it opens
924/// the cell's storage, giving it back releases what the isolate holds and closes
925/// the database, so state cannot span two epochs.
926pub(super) fn adopt_cell(
927 tc: &mut v8::PinScope,
928 cell: &str,
929 cell_storage: Option<CellStorage<'_>>,
930 compat: Compat,
931) -> Result<Option<i64>> {
932 let owned = cell_storage.is_some();
933 if let Some(cell_storage) = cell_storage {
934 storage::open_at_epoch(
935 cell,
936 cell_storage.path,
937 cell_storage.epoch,
938 cell_storage.replicated_wake,
939 cell_storage.vfs,
940 compat.sqlite_vec,
941 )
942 .context("cell storage open failed")?;
943 }
944 finish_cell_adoption(tc, cell, owned)
945}
946
947pub(super) struct EmbeddedStartup {
948 pub id_sc: Vec<u8>,
949 pub props_sc: Vec<u8>,
950 pub path: std::path::PathBuf,
951 pub restored: bool,
952}
953
954pub(super) fn adopt_embedded_cell(
955 tc: &mut v8::PinScope,
956 cell: &str,
957 parent: &storage::StorageIdentity,
958 name: &str,
959 startup: EmbeddedStartup,
960 compat: Compat,
961) -> Result<Option<i64>> {
962 storage::open_embedded(
963 cell,
964 parent,
965 name,
966 &startup.path,
967 startup.restored,
968 compat.sqlite_vec,
969 )
970 .context("facet storage open failed")?;
971 let alarm = finish_cell_adoption(tc, cell, true)?;
972 let depth = parent.facet_path.len() + 1;
973 // Decode in the loaded isolate and install the value directly. A JSON
974 // source string flattened structured-clone types before the constructor
975 // could read them, and it represented absent props as an explicit null.
976 let cell_state = cell_state(tc)?;
977 let configs_key = v8::String::new(tc, "facetConfigs").unwrap();
978 let configs = cell_state
979 .get(tc, configs_key.into())
980 .and_then(|value| value.to_object(tc))
981 .ok_or_else(|| anyhow!("missing facet config registry"))?;
982 let config = v8::Object::new(tc);
983 let id_key = v8::String::new(tc, "id").unwrap();
984 let id_value =
985 storage_ops::deserialize_storage_value(tc, storage::StoredValue::V8(startup.id_sc))
986 .ok_or_else(|| anyhow!("decode facet identity"))?;
987 config.set(tc, id_key.into(), id_value);
988 let props = if startup.props_sc.is_empty() {
989 v8::undefined(tc).into()
990 } else {
991 storage_ops::deserialize_storage_value(tc, storage::StoredValue::V8(startup.props_sc))
992 .ok_or_else(|| anyhow!("decode facet props"))?
993 };
994 let props_key = v8::String::new(tc, "props").unwrap();
995 config.set(tc, props_key.into(), props);
996 let depth_key = v8::String::new(tc, "depth").unwrap();
997 let depth_value = v8::Integer::new(tc, depth as i32);
998 config.set(tc, depth_key.into(), depth_value.into());
999 let cell_key = v8::String::new(tc, cell).unwrap();
1000 configs.set(tc, cell_key.into(), config.into());
1001 Ok(alarm)
1002}
1003
1004fn finish_cell_adoption(tc: &mut v8::PinScope, cell: &str, owned: bool) -> Result<Option<i64>> {
1005 // Every cell dispatch goes out through the host and arrives as an ordinary
1006 // reentrant `CellJob::Fetch`. There is no same-isolate shortcut, and there
1007 // will not be one.
1008 //
1009 // A dispatch that ran the callee's handler inside the caller's execution
1010 // would skip the callee's IoContext, its input gate, and its request
1011 // accounting: a `blockConcurrencyWhile` held by the callee would not hold
1012 // off such a call. That is a different semantic, not an optimisation. The
1013 // nesting deadlock that first disabled the shortcut -- A calls B, B calls
1014 // back into A, and the stack never unwinds -- was the symptom of crossing
1015 // that boundary rather than the reason to avoid it.
1016 //
1017 // The script releases everything the isolate holds for this cell's
1018 // residency, on both edges: the give-back frees what the application left
1019 // behind — memory the node cannot shed, because the cell has left
1020 // residency — and the take-in stops state spanning two epochs, which
1021 // corrupts rather than leaks. `__cell.release` lives in the harness
1022 // because what a residency owns is decided by the maps that hold it; this
1023 // side only says when.
1024 //
1025 // The release loses nothing the cell needs back: `register_actor_name`
1026 // persists the id name before writing it here, so the take-in below reads
1027 // it back.
1028 let source = format!("__celld.__cell.release({cell:?});");
1029 run_internal_snippet(tc, &source).ok_or_else(|| anyhow!("adopt failed"))?;
1030 if !owned {
1031 // A facet of the root's own class lives in this isolate, and nothing
1032 // else releases it: its realm and connection would outlive the root.
1033 for facet in storage::embedded_facets(cell) {
1034 let source = format!("__celld.__cell.release({facet:?});");
1035 run_internal_snippet(tc, &source).ok_or_else(|| anyhow!("release failed"))?;
1036 storage::close(&facet);
1037 crate::ws_registry::ws_close_facet(&facet, "the parent Durable Object was released");
1038 }
1039 storage::close(cell);
1040 return Ok(None);
1041 }
1042 let name = storage::get_actor_name(cell).context("read actor name")?;
1043 register_actor_name(tc, cell, name.as_deref())?;
1044 Ok(storage::get_alarm(cell))
1045}
1046
1047pub(super) fn inject_storage_compatibility(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
1048 let source = format!(
1049 "const c = __celld.__cell;\n\
1050 c.deleteAllDeletesAlarm = {};\n\
1051 c.compat.jsRpc = {};\n\
1052 c.compat.fetcherGetPutDelete = {};\n\
1053 c.compat.websocketStandardBinaryType = {};\n\
1054 c.compat.queueJsonMessages = {};",
1055 compat.delete_all_deletes_alarm,
1056 compat.js_rpc,
1057 compat.fetcher_get_put_delete,
1058 compat.websocket_standard_binary_type,
1059 compat.queue_json_messages,
1060 );
1061 run_internal_snippet(scope, &source).ok_or_else(|| anyhow!("compatibility install failed"))?;
1062 Ok(())
1063}
1064
1065/// `__cell.env`, the bindings object every handler receives as its second
1066/// argument.
1067///
1068/// This runs per request, so both keys come from the constant table. The
1069/// *value* stays a live lookup: unlike the event hooks, `env` is an ordinary
1070/// data property that a worker's own code can replace, and holding the object
1071/// this returns would make the host ignore that. The saving there is one
1072/// property read, so the correctness question decides it.
1073pub(super) fn harness_env<'s>(
1074 scope: &mut v8::PinScope<'s, '_>,
1075) -> Result<v8::Local<'s, v8::Value>> {
1076 let cell = cell_state(scope)?;
1077 let ek = static_key(scope, &v8_strings::ENV);
1078 Ok(cell.get(scope, ek.into()).unwrap())
1079}
1080
1081pub(super) fn begin_event_context<'s>(
1082 scope: &mut v8::PinScope<'s, '_>,
1083) -> Result<v8::Local<'s, v8::Value>> {
1084 let function = event_hook(scope, |hooks| &hooks.begin_event)?;
1085 let recv = v8::undefined(scope).into();
1086 function
1087 .call(scope, recv, &[])
1088 .ok_or_else(|| anyhow!("__beginEvent threw"))
1089}
1090
1091pub(super) fn end_event_context<'s>(
1092 scope: &mut v8::PinScope<'s, '_>,
1093) -> Result<Option<v8::Local<'s, v8::Promise>>> {
1094 let function = event_hook(scope, |hooks| &hooks.end_event)?;
1095 let recv = v8::undefined(scope).into();
1096 let value = function
1097 .call(scope, recv, &[])
1098 .ok_or_else(|| anyhow!("__endEvent threw"))?;
1099 if value.is_null_or_undefined() {
1100 Ok(None)
1101 } else {
1102 Ok(Some(value.try_into().map_err(|_| {
1103 anyhow!("__endEvent did not return a promise")
1104 })?))
1105 }
1106}
1107
1108// ---- module compilation + request/response marshalling ----