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 on `wasm32-wasip1-threads`) and a CurrentThread flavor
8//! (host-driven turns; the only flavor on threadless WebAssembly targets).
9//! Exposed at the crate root: [`spawn`], [`spawn_blocking`],
10//! [`block_on`], [`sleep_until`], [`configure`], [`start`], [`shutdown`],
11//! the host driver SPIs ([`CurrentThreadTaskDriver`], [`TimerDriver`]), and
12//! the metrics/introspection helpers.
13//! - **napi adapter** (feature `napi`, on by default): an
14//! `unsafe impl AsyncRuntime` backend for napi-rs' `async-runtime` SPI plus
15//! the JavaScript-facing host protocol (`registerCurrentThreadTaskHost`,
16//! `registerTimerHost`, config/metrics exports). Hosts call [`install`] from
17//! their own `#[napi_derive::module_init]` hook after resolving their
18//! runtime configuration; this crate deliberately ships no `module_init` of
19//! its own.
20
21/// Maximum number of physical workers a scheduler owned by this crate may
22/// create.
23pub const MAX_ASYNC_RUNTIME_WORKER_THREADS: usize = 256;
24
25/// Platform-realizable worker ceiling after applying this crate's production
26/// cap.
27///
28/// On `wasm32-wasip1-threads` Rayon reports 255 (`THREADS_BITS = 8` on 32-bit),
29/// so this returns 255 there rather than the native cap of 256.
30#[cfg(napi_runtime_os_threads)]
31pub fn max_async_runtime_worker_threads() -> usize {
32 MAX_ASYNC_RUNTIME_WORKER_THREADS.min(::rayon::max_num_threads())
33}
34
35/// Threadless WebAssembly builds (`wasm32-wasip1`, `wasm32-unknown-unknown`)
36/// use the current-thread executor and can never create a worker.
37#[cfg(not(napi_runtime_os_threads))]
38pub const fn max_async_runtime_worker_threads() -> usize {
39 1
40}
41
42mod async_runtime;
43pub use async_runtime::*;
44
45#[cfg(feature = "napi")]
46mod adapter;
47#[cfg(feature = "napi")]
48pub mod js_callback;
49#[cfg(feature = "napi")]
50pub use adapter::*;