Diffinery

homeflare/celldpublic

celld/crates/celld/js/bootstrap.rs
602 lines · 24.7 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.
17type BootstrapCache = std::collections::HashMap<&'static str, std::sync::Arc<Vec<u8>>>;
18
19fn bootstrap_code_cache() -> &'static std::sync::Mutex<BootstrapCache> {
20 static CACHE: std::sync::OnceLock<std::sync::Mutex<BootstrapCache>> =
21 std::sync::OnceLock::new();
22 CACHE.get_or_init(Default::default)
23}
24
25fn run_bootstrap_script(scope: &mut v8::PinScope, name: &'static str, src: &str) -> Result<()> {
26 use v8::script_compiler::CompileOptions;
27 use v8::script_compiler::NoCacheReason;
28 let code = v8::String::new(scope, src).unwrap();
29 let cached = bootstrap_code_cache().lock().unwrap().get(name).cloned();
30 let unbound = match cached {
31 // `CachedData` borrows `bytes`; the Arc binding outlives the Source.
32 Some(bytes) => {
33 let data = v8::script_compiler::CachedData::new(&bytes);
34 let mut source = v8::script_compiler::Source::new_with_cached_data(code, None, data);
35 let unbound = v8::script_compiler::compile_unbound_script(
36 scope,
37 &mut source,
38 CompileOptions::ConsumeCodeCache,
39 NoCacheReason::NoReason,
40 )
41 .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
42 debug_assert!(
43 !source.get_cached_data().is_some_and(|data| data.rejected()),
44 "code cache rejected for {name}"
45 );
46 unbound
47 }
48 None => {
49 let mut source = v8::script_compiler::Source::new(code, None);
50 // Eager: a lazily-compiled cache would push function-body compile
51 // cost back into every consumer's first request.
52 let unbound = v8::script_compiler::compile_unbound_script(
53 scope,
54 &mut source,
55 CompileOptions::EagerCompile,
56 NoCacheReason::NoReason,
57 )
58 .ok_or_else(|| anyhow!("bootstrap compile {name}"))?;
59 if let Some(data) = unbound.create_code_cache() {
60 bootstrap_code_cache()
61 .lock()
62 .unwrap()
63 .insert(name, std::sync::Arc::new(data.to_vec()));
64 }
65 unbound
66 }
67 };
68 unbound
69 .bind_to_current_context(scope)
70 .run(scope)
71 .ok_or_else(|| anyhow!("bootstrap run {name}"))?;
72 Ok(())
73}
74
75/// WPT-conformant Web APIs: TextEncoder, URL/URLSearchParams, atob/btoa, and
76/// Headers. Run once per isolate before the Cells/Cloudflare-specific harness.
77pub(super) fn install_prelude(scope: &mut v8::PinScope) -> Result<()> {
78 const PRELUDE: &[(&str, &str)] = &[
79 ("text_encoding.js", include_str!("text_encoding.js")),
80 ("url_search_params.js", include_str!("url_search_params.js")),
81 ("url.js", include_str!("url.js")),
82 ("atob_btoa.js", include_str!("atob_btoa.js")),
83 ("headers.js", include_str!("headers.js")),
84 ("streams.js", include_str!("streams.js")),
85 ("writable_stream.js", include_str!("writable_stream.js")),
86 (
87 "text_encoding_streams.js",
88 include_str!("text_encoding_streams.js"),
89 ),
90 ];
91 for (name, src) in PRELUDE {
92 run_bootstrap_script(scope, name, src)?;
93 }
94 Ok(())
95}
96
97pub(super) fn install_harness(scope: &mut v8::PinScope) -> Result<()> {
98 run_bootstrap_script(scope, "harness.js", include_str!("harness.js"))?;
99 run_bootstrap_script(scope, "crypto.js", include_str!("crypto.js"))
100}
101
102pub(super) fn register_class(
103 scope: &mut v8::PinScope,
104 name: &str,
105 cls: v8::Local<v8::Value>,
106) -> Result<()> {
107 let ctx = scope.get_current_context();
108 let global = ctx.global(scope);
109 let ck = v8::String::new(scope, "__cell").unwrap();
110 let cell = global
111 .get(scope, ck.into())
112 .unwrap()
113 .to_object(scope)
114 .unwrap();
115 let clk = v8::String::new(scope, "classes").unwrap();
116 let classes = cell
117 .get(scope, clk.into())
118 .unwrap()
119 .to_object(scope)
120 .unwrap();
121 let nk = v8::String::new(scope, name).unwrap();
122 classes.set(scope, nk.into(), cls);
123 Ok(())
124}
125
126/// Populate `cloudflare:workers` `exports` with the worker module's own exports:
127/// a Durable Object class is exposed as its namespace (idFromName/get/RPC), any
128/// other export by value. `default` is omitted (it is the fetch entrypoint, not
129/// an importable export). Mirrors Workerd's `import { exports }` surface.
130pub(super) fn populate_cf_exports(
131 scope: &mut v8::PinScope,
132 ns: v8::Local<v8::Object>,
133 do_classes: &[String],
134) -> Result<()> {
135 let context = scope.get_current_context();
136 let global = context.global(scope);
137 let cf = global
138 .get(scope, v8::String::new(scope, "__cf").unwrap().into())
139 .and_then(|value| value.to_object(scope))
140 .ok_or_else(|| anyhow!("missing __cf runtime state"))?;
141 let exports = cf
142 .get(scope, v8::String::new(scope, "exports").unwrap().into())
143 .and_then(|value| value.to_object(scope))
144 .ok_or_else(|| anyhow!("missing __cf.exports"))?;
145 let cell = global
146 .get(scope, v8::String::new(scope, "__cell").unwrap().into())
147 .and_then(|value| value.to_object(scope))
148 .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
149 let make_ns: v8::Local<v8::Function> = cell
150 .get(
151 scope,
152 v8::String::new(scope, "makeNamespace").unwrap().into(),
153 )
154 .and_then(|value| value.try_into().ok())
155 .ok_or_else(|| anyhow!("missing __cell.makeNamespace"))?;
156 let do_set: std::collections::HashSet<&str> = do_classes.iter().map(String::as_str).collect();
157 let names = ns
158 .get_own_property_names(scope, Default::default())
159 .ok_or_else(|| anyhow!("no module export names"))?;
160 for index in 0..names.length() {
161 let name_value = names.get_index(scope, index).unwrap();
162 let name = name_value.to_rust_string_lossy(scope);
163 if name == "default" {
164 continue;
165 }
166 let export_value = if do_set.contains(name.as_str()) {
167 let arg = v8::String::new(scope, &name).unwrap().into();
168 make_ns
169 .call(scope, cell.into(), &[arg])
170 .ok_or_else(|| anyhow!("makeNamespace({name}) failed"))?
171 } else {
172 ns.get(scope, name_value)
173 .ok_or_else(|| anyhow!("export {name}"))?
174 };
175 let key = v8::String::new(scope, &name).unwrap();
176 exports.set(scope, key.into(), export_value);
177 }
178 Ok(())
179}
180
181pub(super) fn inject_namespace_keys(
182 scope: &mut v8::PinScope,
183 script_name: &str,
184 do_classes: &[String],
185) -> Result<()> {
186 let context = scope.get_current_context();
187 let global = context.global(scope);
188 let cell_key = v8::String::new(scope, "__cell").unwrap();
189 let cell = global
190 .get(scope, cell_key.into())
191 .and_then(|value| value.to_object(scope))
192 .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
193 let keys_key = v8::String::new(scope, "namespaceKeys").unwrap();
194 let keys = cell
195 .get(scope, keys_key.into())
196 .and_then(|value| value.to_object(scope))
197 .ok_or_else(|| anyhow!("missing Durable Object namespace registry"))?;
198 let script_key = v8::String::new(scope, "script").unwrap();
199 let script_value = v8::String::new(scope, script_name).unwrap();
200 cell.set(scope, script_key.into(), script_value.into());
201 for class_name in do_classes {
202 let class_key = v8::String::new(scope, class_name).unwrap();
203 let namespace_key = super::namespace_key(script_name, class_name);
204 let namespace_key = v8::String::new(scope, &namespace_key).unwrap();
205 if !keys
206 .set(scope, class_key.into(), namespace_key.into())
207 .unwrap_or(false)
208 {
209 anyhow::bail!("could not register namespace key for {class_name}");
210 }
211 }
212 Ok(())
213}
214
215/// `__cell.crons`: the deployment's cron trigger expressions, verbatim as the
216/// developer wrote them. The reserved cron cell reads them at each activation,
217/// so a schedule change arrives with the deployment and needs no migration of
218/// an alarm the previous deployment armed. Absent `triggers.crons`, the list
219/// is empty and the cron cell retires itself.
220pub(super) fn inject_crons(scope: &mut v8::PinScope, crons: &[String]) -> Result<()> {
221 let context = scope.get_current_context();
222 let global = context.global(scope);
223 let cell = global
224 .get(scope, v8::String::new(scope, "__cell").unwrap().into())
225 .and_then(|value| value.to_object(scope))
226 .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
227 let list = v8::Array::new(scope, crons.len() as i32);
228 for (index, cron) in crons.iter().enumerate() {
229 let value = v8::String::new(scope, cron).ok_or_else(|| anyhow!("cron expression"))?;
230 list.set_index(scope, index as u32, value.into());
231 }
232 let key = v8::String::new(scope, "crons").unwrap();
233 cell.set(scope, key.into(), list.into());
234 Ok(())
235}
236
237/// `globalThis.Cloudflare.compatibilityFlags`. Only flags Cells actually
238/// honours are listed; a flag Cells does not model is absent (falsy) rather
239/// than reported as enabled.
240///
241/// Built through the V8 object API rather than by compiling a snippet: this
242/// runs on every isolate load, and a separate `Script::compile` there cost
243/// ~100us per worker.
244pub(super) fn inject_compatibility_flags(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
245 let context = scope.get_current_context();
246 let global = context.global(scope);
247 let flags = v8::Object::new(scope);
248 let set_flag = |scope: &mut v8::PinScope, name: &str, value: bool| {
249 let key = v8::String::new(scope, name).unwrap();
250 let value = v8::Boolean::new(scope, value);
251 flags.set(scope, key.into(), value.into());
252 };
253 set_flag(scope, "upper_case_all_http_methods", true);
254 // Cells' async stream/pipe methods return rejected promises
255 // rather than throwing synchronously, which is exactly the
256 // behavior this flag names.
257 set_flag(scope, "capture_async_api_throws", true);
258 set_flag(
259 scope,
260 "delete_all_deletes_alarm",
261 compat.delete_all_deletes_alarm,
262 );
263 set_flag(scope, "js_rpc", compat.js_rpc);
264 set_flag(scope, "sqlite_vec", compat.sqlite_vec);
265 set_flag(
266 scope,
267 "fetcher_no_get_put_delete",
268 !compat.fetcher_get_put_delete,
269 );
270 let cloudflare = v8::Object::new(scope);
271 let key = v8::String::new(scope, "compatibilityFlags").unwrap();
272 cloudflare.set(scope, key.into(), flags.into());
273 let key = v8::String::new(scope, "Cloudflare").unwrap();
274 global.set(scope, key.into(), cloudflare.into());
275 Ok(())
276}
277
278pub(super) fn build_env(scope: &mut v8::PinScope, config: &WorkerConfig) -> Result<()> {
279 let script_name = config.script_name.as_str();
280 let bindings = config.bindings.as_slice();
281 let r2_bindings = config.r2_bindings.as_slice();
282 let d1_bindings = config.d1_bindings.as_slice();
283 let ai_binding = config.ai_binding.as_deref();
284 let vars = config.vars.as_slice();
285 let services = config.services.as_slice();
286 let asset_binding = config.asset_binding.as_deref();
287 // call the harness: for each binding, env[bindingName] = makeNamespace(className)
288 let src = {
289 let mut lines = String::from("(() => { const e = __cell.env;\n");
290 for (bname, cname) in bindings {
291 lines.push_str(&format!(
292 "e[{:?}] = __cell.makeNamespace({:?});\n",
293 bname, cname
294 ));
295 }
296 for name in r2_bindings {
297 lines.push_str(&format!("e[{:?}] = __makeR2Bucket({:?});\n", name, name));
298 }
299 for (name, database) in d1_bindings {
300 lines.push_str(&format!(
301 "e[{:?}] = __makeD1Database({:?});\n",
302 name, database
303 ));
304 }
305 if let (Some(name), Ok(url)) = (ai_binding, std::env::var("CELLD_AI_URL")) {
306 lines.push_str(&format!("e[{:?}] = __makeAiBinding({:?});\n", name, url));
307 }
308 for (binding, script, entrypoint) in services {
309 let entrypoint = match entrypoint {
310 Some(name) => format!("{name:?}"),
311 None => "null".to_string(),
312 };
313 lines.push_str(&format!(
314 "e[{:?}] = __makeServiceBinding({:?}, {});\n",
315 binding, script, entrypoint
316 ));
317 }
318 for (name, value) in vars {
319 lines.push_str(&format!("e[{:?}] = {:?};\n", name, value));
320 }
321 if let Some(name) = asset_binding {
322 lines.push_str(&format!(
323 "e[{:?}] = __makeAssetsBinding({:?});\n",
324 name, script_name
325 ));
326 }
327 if let Some(name) = config.loader_binding.as_deref() {
328 lines.push_str(&format!("e[{:?}] = __makeLoader();\n", name));
329 }
330 // A loaded worker's caller-supplied `env` (plain JSON values only in
331 // the walking skeleton) merges last, over the declared bindings.
332 if let Some(env) = config.loader_env.as_deref() {
333 lines.push_str(&format!("Object.assign(e, {});\n", env));
334 }
335 lines.push_str("})();");
336 lines
337 };
338 let code = v8::String::new(scope, &src).unwrap();
339 let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("env compile"))?;
340 s.run(scope).ok_or_else(|| anyhow!("env run"))?;
341 Ok(())
342}
343
344/// Record every exported class deriving from `WorkerEntrypoint` in
345/// `__cell.entrypoints`, so a service binding with `entrypoint = "Name"` can
346/// resolve it, and every export deriving from `DurableObject` in
347/// `__cell.doExports`, so misrouting a DO class as a stateless entrypoint is
348/// reported as such (Workerd getExportedHandler()). Runs once per load; the
349/// check is a prototype walk, not a call into user code.
350pub(super) fn register_entrypoints(
351 scope: &mut v8::PinScope,
352 ns: v8::Local<v8::Object>,
353) -> Result<()> {
354 let context = scope.get_current_context();
355 let global = context.global(scope);
356 let cell_key = v8::String::new(scope, "__cell").unwrap();
357 let cell = global
358 .get(scope, cell_key.into())
359 .and_then(|value| value.to_object(scope))
360 .ok_or_else(|| anyhow!("missing __cell runtime state"))?;
361 let key = v8::String::new(scope, "entrypoints").unwrap();
362 let entrypoints = cell
363 .get(scope, key.into())
364 .and_then(|value| value.to_object(scope))
365 .ok_or_else(|| anyhow!("missing entrypoint registry"))?;
366 let key = v8::String::new(scope, "objectEntrypoints").unwrap();
367 let object_entrypoints = cell
368 .get(scope, key.into())
369 .and_then(|value| value.to_object(scope))
370 .ok_or_else(|| anyhow!("missing object-entrypoint registry"))?;
371 let key = v8::String::new(scope, "doExports").unwrap();
372 let do_exports = cell
373 .get(scope, key.into())
374 .and_then(|value| value.to_object(scope))
375 .ok_or_else(|| anyhow!("missing doExports registry"))?;
376 let cf_key = v8::String::new(scope, "__cf").unwrap();
377 let cf = global
378 .get(scope, cf_key.into())
379 .and_then(|value| value.to_object(scope))
380 .ok_or_else(|| anyhow!("missing __cf"))?;
381 let key = v8::String::new(scope, "WorkerEntrypoint").unwrap();
382 let entrypoint_base = cf
383 .get(scope, key.into())
384 .ok_or_else(|| anyhow!("missing WorkerEntrypoint base"))?;
385 let key = v8::String::new(scope, "DurableObject").unwrap();
386 let durable_base = cf
387 .get(scope, key.into())
388 .ok_or_else(|| anyhow!("missing DurableObject base"))?;
389 let Some(names) = ns.get_own_property_names(scope, Default::default()) else {
390 return Ok(());
391 };
392 let yes = v8::Boolean::new(scope, true);
393 let extends = compile_fn(scope, EXTENDS_SRC)?;
394 for index in 0..names.length() {
395 let Some(name) = names.get_index(scope, index) else {
396 continue;
397 };
398 let Some(value) = ns.get(scope, name) else {
399 continue;
400 };
401 if !value.is_function() {
402 // A plain-object export is Workerd's non-class entrypoint; its
403 // handler functions dispatch as fn(arg, env, ctx).
404 if value.is_object() {
405 object_entrypoints.set(scope, name, value);
406 }
407 continue;
408 }
409 // Walk the prototype chain rather than calling anything. The walk
410 // runs in JS: Reflect.getPrototypeOf honors Proxy exports (SDK shims
411 // like workers-rs wrap their classes), which the host-side
412 // Object::GetPrototype does not.
413 if call_extends(scope, extends, value, entrypoint_base)? {
414 entrypoints.set(scope, name, value);
415 } else if call_extends(scope, extends, value, durable_base)? {
416 do_exports.set(scope, name, yes.into());
417 }
418 }
419 Ok(())
420}
421
422/// `(cls, base) => base is on cls's prototype chain`, via Reflect so Proxy
423/// wrappers report the prototype their handler exposes. A getPrototypeOf trap
424/// also makes the chain user-controlled (a cycle, or a fresh Proxy per hop,
425/// is spec-legal on an extensible target), so track visited links and cap the
426/// walk rather than let it hang the load.
427const EXTENDS_SRC: &str = "((cls, base) => { \
428 const seen = new Set(); \
429 for (let p = Reflect.getPrototypeOf(cls); p; p = Reflect.getPrototypeOf(p)) { \
430 if (p === base) return true; \
431 if (seen.has(p) || seen.size >= 1000) return false; \
432 seen.add(p); \
433 } \
434 return false; })";
435
436/// The walk crosses into user code when an export is a Proxy, so it can throw
437/// (a revoked Proxy, a throwing getPrototypeOf trap). Pin a TryCatch and
438/// surface that as a load error rather than misclassifying the export.
439fn call_extends(
440 scope: &mut v8::PinScope,
441 extends: v8::Local<v8::Function>,
442 class: v8::Local<v8::Value>,
443 base: v8::Local<v8::Value>,
444) -> Result<bool> {
445 let tc = std::pin::pin!(v8::TryCatch::new(scope));
446 let scope = &mut tc.init();
447 let recv = v8::undefined(scope).into();
448 match extends.call(scope, recv, &[class, base]) {
449 Some(result) => Ok(result.is_true()),
450 None => Err(anyhow!("inspect export prototype chain: {}", exc!(scope))),
451 }
452}
453
454/// Mark which cell scopes are local to this node and record the node id. Every
455/// other scope routes cross-node via `__do_call`.
456pub(super) fn inject_routing(scope: &mut v8::PinScope, owned: &[String], node: &str) -> Result<()> {
457 let mut src = format!("(() => {{ __cell.node = {node:?};\n");
458 for s in owned {
459 src.push_str(&format!("__cell.owned[{s:?}] = true;\n"));
460 }
461 src.push_str("})();");
462 let code = v8::String::new(scope, &src).unwrap();
463 let s = v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("routing compile"))?;
464 s.run(scope).ok_or_else(|| anyhow!("routing run"))?;
465 Ok(())
466}
467
468/// Amend `inject_routing` for one cell, release its instance, and restore its
469/// id name.
470///
471/// The isolate-side half of taking a cell in or giving it back. Kept beside
472/// `inject_routing` because it edits the table that function builds.
473pub(super) fn adopt_cell(
474 tc: &mut v8::PinScope,
475 cell: &str,
476 db_path: Option<&str>,
477 owned: bool,
478 compat: Compat,
479) -> Result<Option<i64>> {
480 if owned {
481 if let Some(path) = db_path {
482 storage::open_with_compat(cell, path, compat.sqlite_vec)
483 .context("cell storage open failed")?;
484 }
485 }
486 // NOT marked local, deliberately. `__cell.owned[scope]` turns a cell
487 // dispatch into an in-isolate call, and with one cell per isolate the
488 // only reachable case was a cell calling itself. Now that cells share an
489 // isolate the same flag makes A->B run B's handler *nested inside* A's,
490 // and a cycle back to A nests again on one thread — which times out
491 // (`actor lab self and cycle paths`).
492 //
493 // So every cell dispatch goes back out through the host and arrives as
494 // an ordinary reentrant `CellJob::Fetch`, which the run loop already
495 // supports. That costs a round trip and is the behaviour cells had
496 // before they shared isolates. Re-enabling the fast path needs the
497 // target checked against what is already on the stack; correctness
498 // first.
499 //
500 // The script also releases everything the isolate holds for this cell's
501 // residency, on both edges: the give-back frees what the application left
502 // behind — memory the node cannot shed, because the cell has left
503 // residency — and the take-in stops state spanning two epochs, which
504 // corrupts rather than leaks. `__cell.release` lives in the harness
505 // because what a residency owns is decided by the maps that hold it; this
506 // side only says when.
507 //
508 // The release loses nothing the cell needs back: `register_actor_name`
509 // persists the id name before writing it here, so the take-in below reads
510 // it back.
511 let source = format!(
512 "(() => {{ const s = {cell:?}; \
513 delete __cell.owned[s]; \
514 __cell.release(s); }})();"
515 );
516 let code = v8::String::new(tc, &source).unwrap();
517 let script = v8::Script::compile(tc, code, None).ok_or_else(|| anyhow!("adopt compile"))?;
518 script.run(tc).ok_or_else(|| anyhow!("adopt run"))?;
519 if !owned {
520 storage::close(cell);
521 return Ok(None);
522 }
523 let name = storage::get_actor_name(cell).context("read actor name")?;
524 register_actor_name(tc, cell, name.as_deref())?;
525 Ok(storage::get_alarm(cell))
526}
527
528pub(super) fn inject_storage_compatibility(scope: &mut v8::PinScope, compat: Compat) -> Result<()> {
529 let source = format!(
530 "__cell.deleteAllDeletesAlarm = {};\n\
531 __cell.compat.jsRpc = {};\n\
532 __cell.compat.fetcherGetPutDelete = {};\n\
533 __cell.compat.websocketStandardBinaryType = {};",
534 compat.delete_all_deletes_alarm,
535 compat.js_rpc,
536 compat.fetcher_get_put_delete,
537 compat.websocket_standard_binary_type,
538 );
539 let code = v8::String::new(scope, &source).unwrap();
540 let script =
541 v8::Script::compile(scope, code, None).ok_or_else(|| anyhow!("compatibility compile"))?;
542 script
543 .run(scope)
544 .ok_or_else(|| anyhow!("compatibility run"))?;
545 Ok(())
546}
547
548pub(super) fn harness_env<'s>(
549 scope: &mut v8::PinScope<'s, '_>,
550) -> Result<v8::Local<'s, v8::Value>> {
551 let ctx = scope.get_current_context();
552 let global = ctx.global(scope);
553 let ck = v8::String::new(scope, "__cell").unwrap();
554 let cell = global
555 .get(scope, ck.into())
556 .unwrap()
557 .to_object(scope)
558 .unwrap();
559 let ek = v8::String::new(scope, "env").unwrap();
560 Ok(cell.get(scope, ek.into()).unwrap())
561}
562
563pub(super) fn begin_event_context<'s>(
564 scope: &mut v8::PinScope<'s, '_>,
565) -> Result<v8::Local<'s, v8::Value>> {
566 let global = scope.get_current_context().global(scope);
567 let key = v8::String::new(scope, "__beginEvent").unwrap();
568 let function: v8::Local<v8::Function> = global
569 .get(scope, key.into())
570 .ok_or_else(|| anyhow!("no __beginEvent"))?
571 .try_into()
572 .map_err(|_| anyhow!("__beginEvent is not a function"))?;
573 let recv = v8::undefined(scope).into();
574 function
575 .call(scope, recv, &[])
576 .ok_or_else(|| anyhow!("__beginEvent threw"))
577}
578
579pub(super) fn end_event_context<'s>(
580 scope: &mut v8::PinScope<'s, '_>,
581) -> Result<Option<v8::Local<'s, v8::Promise>>> {
582 let global = scope.get_current_context().global(scope);
583 let key = v8::String::new(scope, "__endEvent").unwrap();
584 let function: v8::Local<v8::Function> = global
585 .get(scope, key.into())
586 .ok_or_else(|| anyhow!("no __endEvent"))?
587 .try_into()
588 .map_err(|_| anyhow!("__endEvent is not a function"))?;
589 let recv = v8::undefined(scope).into();
590 let value = function
591 .call(scope, recv, &[])
592 .ok_or_else(|| anyhow!("__endEvent threw"))?;
593 if value.is_null_or_undefined() {
594 Ok(None)
595 } else {
596 Ok(Some(value.try_into().map_err(|_| {
597 anyhow!("__endEvent did not return a promise")
598 })?))
599 }
600}
601
602// ---- module compilation + request/response marshalling ----