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