Skip to main content

quickjs_jit_stdlib/llrt/llrt_context/
lib.rs

1// Vendored from LLRT d9fd873e793c (libs/llrt_context/src/lib.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5use std::future::Future;
6use std::sync::OnceLock;
7
8use crate::utils::primordials::{BasePrimordials, Primordial};
9use rquickjs::{atom::PredefinedAtom, CatchResultExt, CaughtError, Ctx, Object, Result};
10use tokio::sync::oneshot::{self, Receiver};
11use tracing::trace;
12
13#[allow(clippy::type_complexity)]
14static ERROR_HANDLER: OnceLock<Box<dyn for<'js> Fn(&Ctx<'js>, CaughtError<'js>) + Sync + Send>> =
15    OnceLock::new();
16
17pub trait CtxExtension<'js> {
18    /// Despite naming, this will not necessarily exit the parent process.
19    /// It depends on the handler set by `set_spawn_error_handler`.
20    fn spawn_exit<F, R>(&self, future: F) -> Result<Receiver<R>>
21    where
22        F: Future<Output = Result<R>> + 'js,
23        R: 'js;
24
25    fn spawn_exit_simple<F>(&self, future: F)
26    where
27        F: Future<Output = Result<()>> + 'js;
28}
29
30impl<'js> CtxExtension<'js> for Ctx<'js> {
31    fn spawn_exit<F, R>(&self, future: F) -> Result<Receiver<R>>
32    where
33        F: Future<Output = Result<R>> + 'js,
34        R: 'js,
35    {
36        let ctx = self.clone();
37
38        let primordials = BasePrimordials::get(self)?;
39        let type_error: Object = primordials.constructor_type_error.construct(())?;
40        let stack: Option<String> = type_error.get(PredefinedAtom::Stack).ok();
41
42        let (join_channel_tx, join_channel_rx) = oneshot::channel();
43
44        self.spawn(async move {
45            match future.await.catch(&ctx) {
46                Ok(res) => {
47                    //result here doesn't matter if receiver has dropped
48                    let _ = join_channel_tx.send(res);
49                }
50                Err(err) => handle_spawn_error(&ctx, err, stack),
51            }
52        });
53        Ok(join_channel_rx)
54    }
55
56    /// Same as above but fire & forget and without a forced stack trace collection
57    fn spawn_exit_simple<F>(&self, future: F)
58    where
59        F: Future<Output = Result<()>> + 'js,
60    {
61        let ctx = self.clone();
62        self.spawn(async move {
63            if let Err(err) = future.await.catch(&ctx) {
64                handle_spawn_error(&ctx, err, None)
65            }
66        });
67    }
68}
69
70fn handle_spawn_error<'js>(ctx: &Ctx<'js>, err: CaughtError<'js>, stack: Option<String>) {
71    let error_handler = if let Some(handler) = ERROR_HANDLER.get() {
72        handler
73    } else {
74        trace!("Future error: {:?}", err);
75        return;
76    };
77    if let CaughtError::Exception(err) = err {
78        if err.stack().is_none() {
79            if let Some(stack) = stack {
80                err.set(PredefinedAtom::Stack, stack).unwrap();
81            }
82        }
83        error_handler(ctx, CaughtError::Exception(err));
84    } else {
85        error_handler(ctx, err);
86    }
87}
88
89pub fn set_spawn_error_handler<F>(handler: F)
90where
91    F: for<'js> Fn(&Ctx<'js>, CaughtError<'js>) + Sync + Send + 'static,
92{
93    _ = ERROR_HANDLER.set(Box::new(handler));
94}