neon/executor/
mod.rs

1use std::{future::Future, pin::Pin};
2
3use crate::{context::Cx, thread::LocalKey};
4
5#[cfg(feature = "tokio-rt")]
6pub(crate) mod tokio;
7
8type BoxFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
9
10pub(crate) static RUNTIME: LocalKey<Box<dyn Runtime>> = LocalKey::new();
11
12pub trait Runtime: Send + Sync + 'static {
13    fn spawn(&self, fut: BoxFuture);
14}
15
16/// Register a [`Future`] executor runtime globally to the addon.
17///
18/// Returns `Ok(())` if a global executor has not been set and `Err(runtime)` if it has.
19///
20/// If the `tokio` feature flag is enabled and the addon does not provide a
21/// [`#[neon::main]`](crate::main) function, a multithreaded tokio runtime will be
22/// automatically registered.
23///
24/// **Note**: Each instance of the addon will have its own runtime. It is recommended
25/// to initialize the async runtime once in a process global and share it across instances.
26///
27/// ```
28/// # fn main() {
29/// # #[cfg(feature = "tokio-rt-multi-thread")]
30/// # fn example() {
31/// # use neon::prelude::*;
32/// use once_cell::sync::OnceCell;
33/// use tokio::runtime::Runtime;
34///
35/// static RUNTIME: OnceCell<Runtime> = OnceCell::new();
36///
37/// #[neon::main]
38/// fn main(mut cx: ModuleContext) -> NeonResult<()> {
39///     let runtime = RUNTIME
40///         .get_or_try_init(Runtime::new)
41///         .or_else(|err| cx.throw_error(err.to_string()))?;
42///
43///     let _ = neon::set_global_executor(&mut cx, runtime);
44///
45///     Ok(())
46/// }
47/// # }
48/// # }
49/// ```
50pub fn set_global_executor<R>(cx: &mut Cx, runtime: R) -> Result<(), R>
51where
52    R: Runtime,
53{
54    if RUNTIME.get(cx).is_some() {
55        return Err(runtime);
56    }
57
58    RUNTIME.get_or_init(cx, || Box::new(runtime));
59
60    Ok(())
61}