Skip to main content

ntex_rt/
lib.rs

1//! Single-threaded asynchronous runtime infrastructure for ntex.
2//!
3//! A [`System`] owns the runtime configuration and coordinates one or more
4//! [`Arbiter`] execution threads. Each arbiter runs local futures on its own
5//! thread, allowing tasks to use types that are not `Send`.
6//!
7//! Use [`System::build()`] to configure a system, [`spawn()`] to start a local
8//! task, and [`spawn_blocking()`] for blocking work.
9//!
10//! Local [`JoinHandle`]s are neither `Send` nor `Sync`, even for `Send` outputs.
11//! They detach on drop by default. Use [`JoinHandle::cancel_on_drop()`] to
12//! request cancellation on drop instead.
13//!
14//! Use [`spawn_sendable()`] to spawn a local future whose `Send` output can be
15//! awaited on another thread. Dropping its returned future requests cancellation.
16//!
17//! [`Handle::spawn()`] submits a `Send` future to the handle's runtime and
18//! returns a [`RemoteJoinHandle`] for the calling thread. On the runtime's own thread
19//! the task is spawned directly. From other threads the future and later its
20//! `Send` output share one allocation, which is passed to the runtime thread:
21//!
22//! ```no_run
23//! # async fn example(handle: ntex_rt::Handle) {
24//! let task = handle.spawn(async { 42 });
25//! assert_eq!(task.await.unwrap(), 42);
26//! # }
27//! ```
28//!
29//! Dropping the handle detaches the task, [`RemoteJoinHandle::cancel()`] cancels it.
30//! A submitted future is polled and dropped on the runtime thread; shutdown or
31//! cancellation before producing a result yields a join error. No task is
32//! guaranteed to finish. Rejected submissions are never polled and their
33//! futures may be dropped on the submitting thread.
34//!
35//! Use [`Handle::spawn_detached()`] for fire-and-forget work. Its output need
36//! not be `Send` and is discarded on the owner.
37//!
38//! Remote join handles also remain on their calling thread, even when the
39//! submission uses the runtime's local fast path. Both the submitted future
40//! and its output must be `Send`:
41//!
42//! ```compile_fail
43//! # fn example(handle: ntex_rt::Handle) {
44//! handle.spawn(async { std::rc::Rc::new(42) });
45//! # }
46//! ```
47//!
48//! [`LocalWaker`] owns a thread-confined wake handle. It specializes native
49//! task wakes on their owner thread and preserves standard waker behavior
50//! for other runtimes and wrapped wakers.
51//!
52//! Runtime backends are selected with Cargo features:
53//!
54//! - no runtime feature uses the native ntex runtime
55//! - `tokio` uses the Tokio-based runtime adapter
56//! - `compio` uses the Compio-based runtime adapter
57//!
58//! The `tokio` and `compio` features are mutually exclusive. The [`rt`] module
59//! always exposes the native scheduler, including [`Runtime`] and
60//! [`RuntimeBuilder`], independently of which adapter supplies the
61//! crate-level spawning functions and [`Handle`].
62//!
63//! A [`Runner`] supplies the event loop used by [`SystemRunner`] and arbiter
64//! threads. Building a system only stores its configuration; execution begins
65//! when the returned system runner is driven.
66//!
67//! Native event-loop integrations implement [`Driver`] and use [`PollResult`]
68//! from [`Runtime::poll`] to decide whether to wait, poll again, or stop.
69//! Runtime, arbiter, and blocking pool metric types are grouped in [`metrics`].
70#![deny(clippy::pedantic)]
71#![allow(
72    clippy::missing_errors_doc,
73    clippy::missing_fields_in_debug,
74    clippy::must_use_candidate
75)]
76
77mod arbiter;
78mod builder;
79mod busy;
80#[cfg(target_os = "linux")]
81mod capture;
82mod driver;
83mod handle;
84mod local_waker;
85pub mod metrics;
86mod pool;
87mod remote;
88pub mod rt;
89pub mod signals;
90mod system;
91mod task;
92#[cfg(test)]
93mod testing;
94mod watchdog;
95
96#[doc(hidden)]
97#[cfg(feature = "compio")]
98pub mod rt_compio;
99#[doc(hidden)]
100#[cfg(feature = "tokio")]
101pub mod rt_tokio;
102
103pub use self::arbiter::{Arbiter, get_item, remove_all_items, set_item, with_item};
104pub use self::builder::{Builder, SystemRunner};
105pub use self::driver::{BlockFuture, Driver, DriverType, Notify, PollResult, Runner};
106pub use self::local_waker::LocalWaker;
107pub use self::pool::{BlockingError, BlockingResult, ThreadPool, spawn_blocking};
108pub use self::rt::{Runtime, RuntimeBuilder};
109pub use self::system::{Id, System};
110pub use self::task::{spawn_sendable, task_callbacks, task_opt_callbacks};
111
112#[cfg(feature = "tokio")]
113pub use self::rt_tokio::*;
114
115#[cfg(all(feature = "compio", not(feature = "tokio")))]
116pub use self::rt_compio::*;
117
118#[cfg(all(not(feature = "tokio"), not(feature = "compio")))]
119pub use self::rt::{Handle, JoinError, JoinHandle, RemoteJoinHandle, now, spawn, spawn_detached};
120
121pub(crate) type HashMap<K, V> = std::collections::HashMap<K, V, foldhash::fast::RandomState>;
122
123/// Runs `f` while an earlier panic is pending, the process aborts if `f`
124/// panics.
125pub(crate) fn abort_on_panic<R>(f: impl FnOnce() -> R) -> R {
126    struct Abort;
127
128    impl Drop for Abort {
129        fn drop(&mut self) {
130            abort_on_second_panic();
131        }
132    }
133
134    let guard = Abort;
135    let result = f();
136    std::mem::forget(guard);
137    result
138}
139
140/// Aborts the process on a panic raised while an earlier panic is unwinding
141/// or held to be resumed.
142#[cold]
143pub(crate) fn abort_on_second_panic() -> ! {
144    if let Err(payload) = std::panic::catch_unwind(|| {
145        log::error!("Panic during shutdown after an earlier panic; aborting");
146    }) {
147        std::mem::forget(payload);
148    }
149    std::process::abort();
150}