Skip to main content

napi_async_runtime/
lib.rs

1//! A shared, tokio-free async runtime for napi-rs addons.
2//!
3//! Two layers, one crate:
4//!
5//! - **Scheduler** (always compiled, napi-free): a pluggable async/CPU/blocking
6//!   scheduler with a MultiThread flavor (Rayon-backed worker pool on native
7//!   targets) and a CurrentThread flavor (host-driven turns; the only flavor on
8//!   WebAssembly). Exposed at the crate root: [`spawn`], [`spawn_blocking`],
9//!   [`block_on`], [`sleep_until`], [`configure`], [`start`], [`shutdown`],
10//!   the host driver SPIs ([`CurrentThreadTaskDriver`], [`TimerDriver`]), and
11//!   the metrics/introspection helpers.
12//! - **napi adapter** (feature `napi`, on by default): an
13//!   `unsafe impl AsyncRuntime` backend for napi-rs' `async-runtime` SPI plus
14//!   the JavaScript-facing host protocol (`registerCurrentThreadTaskHost`,
15//!   `registerTimerHost`, config/metrics exports). Hosts call [`install`] from
16//!   their own `#[napi_derive::module_init]` hook after resolving their
17//!   runtime configuration; this crate deliberately ships no `module_init` of
18//!   its own.
19
20/// Maximum number of physical workers a scheduler owned by this crate may
21/// create.
22pub const MAX_ASYNC_RUNTIME_WORKER_THREADS: usize = 256;
23
24/// Platform-realizable worker ceiling after applying this crate's production
25/// cap.
26#[cfg(not(target_family = "wasm"))]
27pub fn max_async_runtime_worker_threads() -> usize {
28  MAX_ASYNC_RUNTIME_WORKER_THREADS.min(::rayon::max_num_threads())
29}
30
31/// WebAssembly builds use the current-thread executor.
32#[cfg(target_family = "wasm")]
33pub const fn max_async_runtime_worker_threads() -> usize {
34  1
35}
36
37mod async_runtime;
38pub use async_runtime::*;
39
40#[cfg(feature = "napi")]
41mod adapter;
42#[cfg(feature = "napi")]
43pub mod js_callback;
44#[cfg(feature = "napi")]
45pub use adapter::*;