Skip to main content

ntex_rt/
driver.rs

1//! Interfaces between the runtime and its event-loop driver.
2use std::{any::Any, cell::RefCell, fmt, io, panic, pin::Pin, rc::Rc, time::Duration};
3
4use crate::rt::Runtime;
5
6/// A boxed, pinned future passed to a [`Runner`].
7///
8/// The future may contain thread-local state and is not required to be `Send`.
9pub type BlockFuture = Pin<Box<dyn Future<Output = ()>>>;
10
11/// Operating-system I/O mechanism used by a driver.
12#[derive(Copy, Clone, Debug, PartialEq, Eq)]
13pub enum DriverType {
14    /// Readiness-based polling, such as epoll or kqueue.
15    Poll,
16    /// Linux io-uring.
17    IoUring,
18    /// Windows I/O completion ports.
19    Iocp,
20}
21
22impl DriverType {
23    /// Returns the driver name: `"polling"`, `"io-uring"`, or `"iocp"`.
24    pub const fn name(&self) -> &'static str {
25        match self {
26            DriverType::Poll => "polling",
27            DriverType::IoUring => "io-uring",
28            DriverType::Iocp => "iocp",
29        }
30    }
31
32    /// Returns whether this is a readiness-based polling driver.
33    pub const fn is_polling(&self) -> bool {
34        matches!(self, &DriverType::Poll)
35    }
36}
37
38/// Creates and drives an event loop for a system or arbiter thread.
39///
40/// A system shares its runner between arbiters. Implementations must support
41/// calls from multiple threads, while each supplied future stays on its calling
42/// thread.
43pub trait Runner: Send + Sync + 'static {
44    /// Runs the future to completion.
45    ///
46    /// Return `Ok(())` only after the future completes. A panic of the event loop
47    /// may be returned as an error containing its panic payload or may unwind;
48    /// the system performs cleanup and resumes the panic in either case.
49    fn block_on(&self, fut: BlockFuture) -> Result<(), Box<dyn Any + Send>>;
50}
51
52/// Drives I/O events and scheduled tasks for the native [`Runtime`].
53///
54/// Unlike [`Runner`], a driver belongs to a single runtime thread.
55pub trait Driver: 'static {
56    /// Returns a thread-safe notifier for this driver's event loop.
57    fn handle(&self) -> Box<dyn Notify>;
58
59    /// Drives the runtime until [`Runtime::poll`] returns [`PollResult::Ready`].
60    ///
61    /// Called by [`Runtime::block_on`] with `rt` active on the current thread.
62    /// Process external events between polls, without blocking when the result
63    /// is [`PollResult::PollAgain`]. Call [`Runtime::awake`] after waiting for
64    /// events, before dispatching events that may wake tasks.
65    ///
66    /// Returns an error if the event loop cannot continue.
67    fn run(&self, rt: &Runtime) -> io::Result<()>;
68
69    /// Releases driver-owned state when requested by its owner.
70    ///
71    /// The default implementation does nothing. [`Runtime::block_on`] does not
72    /// call this hook.
73    fn clear(&self) {}
74}
75
76/// Outcome of one call to [`Runtime::poll`].
77///
78/// Part of the native driver interface: [`Driver::run`] implementations inspect
79/// this result to decide whether to stop, wait for events, or run another
80/// nonblocking iteration.
81#[derive(Copy, Clone, Debug, PartialEq, Eq)]
82pub enum PollResult {
83    /// The future supplied to [`Runtime::block_on`] has completed; stop driving.
84    Ready,
85    /// No work is immediately runnable; the driver may wait for events.
86    ///
87    /// Holds the time until the next batch of the runtime timers, measured
88    /// when `poll` returns. The driver must not wait longer and must call
89    /// [`Runtime::poll`] again once it passes. `None` if no timer is armed.
90    /// A timer armed after `poll` returns, outside of the runtime tasks, is
91    /// processed by the next `poll`.
92    Pending(Option<Duration>),
93    /// Work remains; process external events without blocking, then poll again.
94    PollAgain,
95}
96
97/// Wakes a runtime driver, retaining the wakeup if it has not blocked yet.
98///
99/// Internal scheduler notifications retry [`io::ErrorKind::Interrupted`] and
100/// log and abort the process on any other error or if `notify` panics, since
101/// queued work may otherwise remain stranded. Explicit notifications through
102/// [`Runtime::handle`] return errors and propagate panics to their caller.
103pub trait Notify: Send + Sync + fmt::Debug + 'static {
104    /// Wakes the driver or records a notification for its next wait.
105    ///
106    /// Notifications may be coalesced, but a notification racing with entry
107    /// into a blocking wait must not be lost. Returns an error if notification
108    /// fails.
109    fn notify(&self) -> io::Result<()>;
110}
111
112/// Executes a Windows system call and converts its failure sentinel to an I/O error.
113///
114/// The `BOOL` and `SOCKET` forms check for zero and nonzero respectively;
115/// `HANDLE` checks for `INVALID_HANDLE_VALUE`. The general form accepts an
116/// explicit comparison, as in `syscall!(expression, == 0)`.
117#[cfg(windows)]
118#[macro_export]
119macro_rules! syscall {
120    (BOOL, $e:expr) => {
121        $crate::syscall!($e, == 0)
122    };
123    (SOCKET, $e:expr) => {
124        $crate::syscall!($e, != 0)
125    };
126    (HANDLE, $e:expr) => {
127        $crate::syscall!($e, == ::windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE)
128    };
129    ($e:expr, $op: tt $rhs: expr) => {{
130        #[allow(unused_unsafe)]
131        let res = unsafe { $e };
132        if res $op $rhs {
133            Err(::std::io::Error::last_os_error())
134        } else {
135            Ok(res)
136        }
137    }};
138}
139
140/// Executes a Unix system call and converts a `-1` result to the last I/O error.
141///
142/// The `break` form retries interruptions and returns [`std::task::Poll::Pending`]
143/// for `WouldBlock` or `EINPROGRESS`, otherwise returning a ready result.
144#[cfg(unix)]
145#[macro_export]
146macro_rules! syscall {
147    (break $e:expr) => {
148        loop {
149            match $crate::syscall!($e) {
150                Ok(fd) => break ::std::task::Poll::Ready(Ok(fd as usize)),
151                Err(e) if e.kind() == ::std::io::ErrorKind::WouldBlock || e.raw_os_error() == Some(::libc::EINPROGRESS)
152                    => break ::std::task::Poll::Pending,
153                Err(e) if e.kind() == ::std::io::ErrorKind::Interrupted => {},
154                Err(e) => break ::std::task::Poll::Ready(Err(e)),
155            }
156        }
157    };
158    ($e:expr, $f:ident($fd:expr)) => {
159        match $crate::syscall!(break $e) {
160            ::std::task::Poll::Pending => Ok($crate::sys::Decision::$f($fd)),
161            ::std::task::Poll::Ready(Ok(res)) => Ok($crate::sys::Decision::Completed(res)),
162            ::std::task::Poll::Ready(Err(e)) => Err(e),
163        }
164    };
165    ($e:expr) => {{
166        #[allow(unused_unsafe)]
167        let res = unsafe { $e };
168        if res == -1 {
169            Err(::std::io::Error::last_os_error())
170        } else {
171            Ok(res)
172        }
173    }};
174}
175
176/// Execute a future with custom `block_on` method and wait for result
177pub(super) fn block_on<F, R>(run: &dyn Runner, fut: F) -> Result<R, Box<dyn Any + Send>>
178where
179    F: Future<Output = R> + 'static,
180    R: 'static,
181{
182    // run loop
183    let result = Rc::new(RefCell::new(None));
184    let result_inner = result.clone();
185
186    ntex_error::set_backtrace_start_alt("ntex/ntex-rt/src/driver.rs", 0);
187    // finalizes the thread's arbiter once its event loop has exited,
188    // including when the runner returns an error or a shutdown callback panics
189    let finalize = FinalizeArbiter;
190    let fut = Box::pin(async move {
191        let r = fut.await;
192        *result_inner.borrow_mut() = Some(r);
193    });
194    // a panic escaping the runner is returned like a runner error, so the
195    // caller cleans up the same way for unwinding and catching runners
196    let res =
197        panic::catch_unwind(panic::AssertUnwindSafe(|| run.block_on(fut))).unwrap_or_else(Err);
198    if let Err(e) = res {
199        // the event loop panicked, a panic of `on_stop` aborts the process
200        crate::abort_on_panic(|| drop(finalize));
201        return Err(e);
202    }
203
204    crate::arbiter::run_shutdown_callbacks();
205    // SAFETY: The event loop and shutdown callbacks have ended, so storage borrows are released.
206    unsafe {
207        crate::remove_all_items();
208    }
209    Ok(result.borrow_mut().take().unwrap())
210}
211
212struct FinalizeArbiter;
213
214impl Drop for FinalizeArbiter {
215    fn drop(&mut self) {
216        if let Some(arb) = crate::Arbiter::try_current() {
217            arb.finalize();
218        }
219    }
220}
221
222pub(super) fn block_on_panic<F, R>(run: &dyn Runner, fut: F) -> R
223where
224    F: Future<Output = R> + 'static,
225    R: 'static,
226{
227    match block_on(run, fut) {
228        Ok(v) => v,
229        Err(e) => panic::resume_unwind(e),
230    }
231}
232
233#[cfg(test)]
234#[path = "../tests/unit/driver.rs"]
235mod tests;