Skip to main content

ntex_rt/rt/
mod.rs

1//! Native single-threaded runtime, task spawning, handles, and clock access.
2//!
3//! This module always uses the native scheduler, regardless of which runtime
4//! backend is selected at the crate root. Its spawning functions and handles
5//! are re-exported at the crate root when neither `tokio` nor `compio` is enabled.
6//! The free spawning functions require an active [`Runtime`], not an active
7//! [`System`](crate::System).
8//!
9//! A [`Driver`] supplies the event loop and interprets the [`PollResult`]
10//! returned by [`Runtime::poll`]. [`Runtime::block_on`] installs the native
11//! runtime while that driver runs, even when Tokio or Compio is selected:
12//!
13//! ```no_run
14//! use ntex_rt::rt;
15//!
16//! # fn example(driver: impl ntex_rt::Driver) {
17//! let runtime = rt::Runtime::new(driver.handle());
18//! runtime.block_on(
19//!     async {
20//!         let task = rt::spawn(async { std::rc::Rc::new(42) });
21//!         assert_eq!(*task.await.unwrap(), 42);
22//!     },
23//!     &driver,
24//! );
25//! # }
26//! ```
27
28use std::cell::{Cell, RefCell};
29use std::sync::{Arc, atomic::Ordering};
30use std::time::{Duration, Instant};
31use std::{fmt, future::Future, io, marker::PhantomData, panic::Location};
32use std::{future::poll_fn, pin::Pin, rc::Rc, task::Poll};
33
34pub use crate::handle::{JoinHandle, RemoteJoinHandle};
35
36use crate::driver::{Driver, Notify, PollResult};
37use crate::handle::SpawnLocation;
38use crate::metrics::Histogram;
39use crate::remote::{Job, RemoteJoin, Runner};
40
41mod queue;
42pub(crate) mod task;
43pub(crate) mod wake;
44
45use self::queue::RunnableQueue;
46
47/// Error returned by [`crate::spawn_sendable()`] when no task output is available.
48///
49/// Native [`JoinHandle`] and [`RemoteJoinHandle`] futures use a separate error
50/// type; this marker is not the error type of their results.
51#[derive(Debug, Copy, Clone)]
52pub struct JoinError;
53
54impl fmt::Display for JoinError {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        write!(f, "JoinError")
57    }
58}
59
60impl std::error::Error for JoinError {}
61
62/// Returns the start of the current runtime turn.
63///
64/// Tasks polled in the same turn observe the same instant, see
65/// [`Runtime::now`]. Returns [`Instant::now()`] outside of a runtime.
66#[inline]
67pub fn now() -> Instant {
68    Runtime::current_now()
69}
70
71/// Spawns a future on the current native runtime and returns its join handle.
72///
73/// The future and its output need not be `Send`. The current system's
74/// [`TaskCallbacks`](crate::TaskCallbacks) wrap the task. Dropping the handle
75/// detaches it unless [`cancel_on_drop`](JoinHandle::cancel_on_drop) is enabled.
76/// Completion is not guaranteed if the runtime shuts down.
77///
78/// # Panics
79///
80/// Panics if no native runtime is active on the current thread.
81#[track_caller]
82pub fn spawn<F>(fut: F) -> JoinHandle<F::Output>
83where
84    F: Future + 'static,
85{
86    let location = Location::caller();
87    let fut = crate::task::wrap(fut);
88    // SAFETY: The current runtime is owner-local, and the wrapped future is `'static`.
89    Runtime::with_current(|rt| unsafe { rt.spawn_at(fut, location) })
90}
91
92/// Spawns a future on the current thread without a join handle.
93///
94/// The future and its output need not be `Send`. The output is dropped on
95/// completion. Like [`spawn()`], this applies registered task callbacks, but
96/// does not create a join handle.
97///
98/// # Panics
99///
100/// Panics if no native runtime is active on the current thread.
101#[track_caller]
102pub fn spawn_detached<F>(fut: F)
103where
104    F: Future + 'static,
105{
106    let location = Location::caller();
107    let fut = crate::task::wrap(fut);
108    // SAFETY: The current runtime is owner-local, and the wrapped future is `'static`.
109    Runtime::with_current(|rt| unsafe { rt.spawn_detached_at(fut, location) });
110}
111
112/// Log target of the scheduler, also used by its submodules.
113const LOG_TARGET: &str = module_path!();
114
115// marks a reported self-wake streak
116pub(crate) const REPORTED: u32 = 1 << 31;
117
118/// Self-wake bookkeeping of a task, used on the runtime thread only.
119pub(crate) trait TaskStats: Copy {
120    /// Returns the task's spawn location for diagnostics.
121    fn location(self) -> SpawnLocation;
122    /// Consecutive self-wakes, `REPORTED` marks a reported streak.
123    fn self_wakes(self) -> u32;
124    /// Stores the self-wake count and its `REPORTED` marker.
125    fn set_self_wakes(self, wakes: u32);
126    /// Start of the self-wake streak, milliseconds since the runtime epoch.
127    fn streak_start(self) -> u32;
128    /// Records the streak's start in milliseconds since the runtime epoch.
129    fn set_streak_start(self, start: u32);
130}
131
132scoped_tls::scoped_thread_local!(static CURRENT_RUNTIME: Runtime);
133
134/// Index of a thread that owns a runtime, never reused within the process.
135#[cfg(not(ntex_loom))]
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub(crate) struct ThreadId(std::num::NonZeroU16);
138
139// loom threads share the OS thread, and its thread locals
140#[cfg(ntex_loom)]
141pub(crate) type ThreadId = loom::thread::ThreadId;
142
143/// The last issued thread index.
144#[cfg(not(ntex_loom))]
145static THREAD_INDEX: std::sync::atomic::AtomicU16 = std::sync::atomic::AtomicU16::new(0);
146
147#[cfg(not(ntex_loom))]
148thread_local!(static THREAD_ID: Cell<Option<ThreadId>> = const { Cell::new(None) });
149
150/// Returns the index of the current thread, assigning one on first use.
151///
152/// Only threads that own a runtime call this, indexes are limited to
153/// `u16::MAX` per process and the process aborts when they run out.
154#[cfg(not(ntex_loom))]
155#[inline]
156pub(crate) fn current_thread_id() -> ThreadId {
157    /// Assigns a never-reused index on the thread's first use.
158    #[cold]
159    fn initialize(slot: &Cell<Option<ThreadId>>) -> ThreadId {
160        let id = THREAD_INDEX
161            .try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
162            .ok()
163            .and_then(|n| std::num::NonZeroU16::new(n + 1))
164            .unwrap_or_else(|| {
165                log::error!(target: LOG_TARGET, "Thread indexes are exhausted, {} runtime-owning threads per process", u16::MAX);
166                std::process::abort()
167            });
168        let id = ThreadId(id);
169        slot.set(Some(id));
170        id
171    }
172
173    THREAD_ID.with(|slot| slot.get().unwrap_or_else(|| initialize(slot)))
174}
175
176/// Returns the index of the current thread without assigning one.
177#[cfg(not(ntex_loom))]
178#[inline]
179pub(crate) fn try_current_thread_id() -> Option<ThreadId> {
180    THREAD_ID.with(Cell::get)
181}
182
183/// Sets the last issued thread index, to test exhaustion.
184#[cfg(all(test, not(ntex_loom)))]
185pub(crate) fn set_thread_index(last: u16) {
186    THREAD_INDEX.store(last, Ordering::Relaxed);
187}
188
189/// Returns the current logical Loom thread's identity.
190#[cfg(ntex_loom)]
191pub(crate) fn current_thread_id() -> ThreadId {
192    loom::thread::current().id()
193}
194
195/// Returns the current logical Loom thread's identity.
196#[cfg(ntex_loom)]
197pub(crate) fn try_current_thread_id() -> Option<ThreadId> {
198    Some(loom::thread::current().id())
199}
200
201#[derive(Debug)]
202/// The native single-threaded task scheduler.
203///
204/// This is a thread-local runtime and cannot be sent to other threads, use
205/// [`Handle`] to spawn tasks from other threads.
206/// It is available even when the crate-level APIs select Tokio or Compio.
207/// A [`Driver`] supplies I/O and drives scheduled tasks through
208/// [`block_on`](Self::block_on).
209///
210/// Dropping the runtime cancels its tasks. If cleanup panics, shutdown finishes
211/// before the panic is resumed. A second cleanup panic, or a cleanup panic
212/// while the runtime is dropped during an existing unwind, aborts the process.
213///
214/// A process can create at most 65,535 runtimes, and at most 65,535 threads can
215/// create one. Neither is reused, and the process aborts when either runs out.
216pub struct Runtime {
217    stop: Cell<bool>,
218    queue: Arc<RunnableQueue>,
219    // tasks are polled and dropped on the thread that created the runtime
220    _not_send: PhantomData<*const ()>,
221}
222
223impl Runtime {
224    /// Creates a runtime with default configuration.
225    ///
226    /// `handle` must wake the driver that will drive this runtime. Creating the
227    /// scheduler does not start an event loop or install it as the current runtime.
228    pub fn new(handle: Box<dyn Notify>) -> Self {
229        Self::builder().build(handle)
230    }
231
232    /// Creates a runtime builder.
233    pub fn builder() -> RuntimeBuilder {
234        RuntimeBuilder::new()
235    }
236
237    /// Creates the owner-thread queue and registers its remote wake endpoint.
238    #[allow(clippy::arc_with_non_send_sync)]
239    fn with_builder(builder: &RuntimeBuilder, handle: Box<dyn Notify>) -> Self {
240        let queue = Arc::new(RunnableQueue::new(builder, handle));
241        wake::register(&queue);
242        Self {
243            stop: Cell::new(false),
244            queue,
245            _not_send: PhantomData,
246        }
247    }
248
249    /// Calls `f` with a reference to the native runtime already active on this thread.
250    ///
251    /// # Panics
252    ///
253    /// Panics if no runtime is active on the current thread.
254    pub fn with_current<T, F: FnOnce(&Self) -> T>(f: F) -> T {
255        /// Reports an operation that requires an active runtime.
256        #[cold]
257        fn not_in_neon_runtime() -> ! {
258            panic!("not in a neon runtime")
259        }
260
261        if CURRENT_RUNTIME.is_set() {
262            CURRENT_RUNTIME.with(f)
263        } else {
264            not_in_neon_runtime()
265        }
266    }
267
268    /// Returns [`Runtime::now`] of the runtime active on the current thread,
269    /// or [`Instant::now()`] if no runtime is active.
270    pub(crate) fn current_now() -> Instant {
271        if CURRENT_RUNTIME.is_set() {
272            CURRENT_RUNTIME.with(Runtime::now)
273        } else {
274            Instant::now()
275        }
276    }
277
278    #[inline]
279    /// Returns a handle to this runtime.
280    pub fn handle(&self) -> Handle {
281        Handle {
282            queue: self.queue.clone(),
283        }
284    }
285
286    /// Spawns a new asynchronous task, returning a [`JoinHandle`] for it.
287    ///
288    /// Spawning a task enables the task to execute concurrently to other tasks.
289    /// There is no guarantee that a spawned task will execute to completion.
290    /// The future and output need not be `Send`. Unlike [`crate::rt::spawn()`],
291    /// this low-level method does not apply registered task callbacks.
292    #[track_caller]
293    pub fn spawn<F: Future + 'static>(&self, future: F) -> JoinHandle<F::Output> {
294        // SAFETY: `Runtime` is thread-confined, and the future owns all captured data.
295        unsafe { self.spawn_at(future, Location::caller()) }
296    }
297
298    /// Spawns a task whose future may borrow non-`'static` data.
299    ///
300    /// Like [`spawn`](Self::spawn), this returns a local [`JoinHandle`] and
301    /// does not apply registered task callbacks.
302    ///
303    /// # Safety
304    ///
305    /// All data borrowed by the future must remain valid until the future is
306    /// completed or destroyed, including on unwind. Any borrowed data in the
307    /// output must remain valid until that output is destroyed, even if its join
308    /// handle outlives this runtime. Requesting cancellation, including through
309    /// [`JoinHandle::cancel_on_drop`], does not wait for destruction and is not
310    /// sufficient to end these obligations. Forgetting a join handle does not
311    /// request cancellation.
312    #[track_caller]
313    pub unsafe fn spawn_unchecked<F: Future>(&self, future: F) -> JoinHandle<F::Output> {
314        // SAFETY: The caller guarantees that borrowed future and output data outlive their use.
315        unsafe { self.spawn_at(future, Location::caller()) }
316    }
317
318    /// Spawns a task, `location` is reported by [`Handle::current_task`].
319    ///
320    /// # Safety
321    ///
322    /// The caller should ensure the captured lifetime is long enough.
323    pub(crate) unsafe fn spawn_at<F: Future>(
324        &self,
325        future: F,
326        location: SpawnLocation,
327    ) -> JoinHandle<F::Output> {
328        // SAFETY: `Runtime` is thread-confined, and the caller guarantees the captured lifetime.
329        unsafe { self.queue.spawn(future, location) }
330    }
331
332    /// Spawns a new asynchronous task without a [`JoinHandle`].
333    ///
334    /// The future and output need not be `Send`. The output is dropped on the
335    /// runtime thread when the task completes. This low-level method does not
336    /// apply registered task callbacks.
337    #[track_caller]
338    pub fn spawn_detached<F: Future + 'static>(&self, future: F) {
339        // SAFETY: `Runtime` is thread-confined, and the future owns all captured data.
340        unsafe { self.spawn_detached_at(future, Location::caller()) }
341    }
342
343    /// Spawns a detached task, `location` is reported by
344    /// [`Handle::current_task`].
345    ///
346    /// # Safety
347    ///
348    /// The caller should ensure the captured lifetime is long enough.
349    pub(crate) unsafe fn spawn_detached_at<F: Future>(&self, future: F, location: SpawnLocation) {
350        // SAFETY: `Runtime` is thread-confined, and the caller guarantees the captured lifetime.
351        unsafe { self.queue.spawn_detached::<_, true>(future, location) }
352    }
353
354    /// Marks the runtime as awake.
355    ///
356    /// Drivers call this after returning from a blocking wait, before handling
357    /// events that wake tasks. Tasks scheduled from the runtime thread do not
358    /// notify the driver until [`poll`](Self::poll) finds no more tasks to run,
359    /// the driver must call `poll` before blocking again.
360    ///
361    /// Starts a busy period, see [`busy_duration`](Self::busy_duration).
362    #[inline]
363    pub fn awake(&self) {
364        if self.queue.idle.get() {
365            self.queue.start_busy();
366        }
367    }
368
369    /// Polls the runtime and runs scheduled tasks.
370    ///
371    /// Runs bounded batches of ready tasks and remote submissions. Returns
372    /// [`PollResult::PollAgain`] if work remains, [`PollResult::Pending`] if the
373    /// driver may wait for events, or [`PollResult::Ready`] after the future
374    /// supplied to [`block_on`](Self::block_on) completes.
375    ///
376    /// This does not install the runtime as current; [`block_on`](Self::block_on)
377    /// establishes that context before invoking the driver.
378    pub fn poll(&self) -> PollResult {
379        let start = Instant::now();
380        // tasks scheduled from other threads do not end the idle state
381        if self.queue.idle.get() {
382            self.queue.busy.start(start);
383        }
384
385        let result = if self.stop.get() {
386            PollResult::Ready
387        } else if self.queue.run() {
388            self.queue.add_poll(true);
389            PollResult::PollAgain
390        } else {
391            self.queue.add_poll(false);
392            PollResult::Pending
393        };
394
395        // a runtime that never idles stays visible, its busy period is read
396        // from its start
397        let now = Instant::now();
398        if result != PollResult::Ready {
399            self.queue
400                .poll_histogram
401                .record(now.saturating_duration_since(start));
402        }
403        if result == PollResult::PollAgain {
404            self.queue.set_poll_start(now);
405            self.queue.busy.next_turn(now);
406        } else {
407            self.queue.idle.set(true);
408            self.queue.busy.stop(now);
409        }
410        result
411    }
412
413    /// Returns the start of the current runtime turn.
414    ///
415    /// While the runtime is busy, returns the time the driver woke up or the
416    /// previous [`poll`](Self::poll) finished, tasks polled in the same turn
417    /// observe the same instant. Returns [`Instant::now()`] while the runtime
418    /// is idle.
419    #[inline]
420    pub fn now(&self) -> Instant {
421        if self.queue.idle.get() {
422            Instant::now()
423        } else {
424            self.queue.poll_start.get()
425        }
426    }
427
428    /// Returns the total time the runtime has been busy.
429    ///
430    /// The runtime is busy from [`awake`](Self::awake) until [`poll`](Self::poll)
431    /// finds no more tasks to run. This includes running tasks and handling
432    /// driver events, and excludes time the driver is blocked waiting for events.
433    /// The value is wall-clock time, not CPU time, and includes the current
434    /// busy period, so it can be read from other threads while a task runs.
435    ///
436    /// Utilization over an interval is the busy duration delta divided by the
437    /// elapsed time of the interval.
438    pub fn busy_duration(&self) -> Duration {
439        self.queue.busy.busy_duration()
440    }
441
442    /// Returns how long the current runtime turn has been running, `None`
443    /// while the runtime is idle.
444    ///
445    /// A turn ends when [`poll`](Self::poll) returns, a long turn means a task
446    /// or a driver event handler keeps the runtime from making progress.
447    pub fn current_turn(&self) -> Option<Duration> {
448        self.queue.busy.current_turn()
449    }
450
451    /// Returns the number of scheduler polls, including polls with no ready tasks.
452    ///
453    /// Calls that immediately return [`PollResult::Ready`] are not counted.
454    pub fn poll_count(&self) -> u64 {
455        self.queue.polls.load(Ordering::Relaxed)
456    }
457
458    /// Returns the number of times [`poll`](Self::poll) returned
459    /// [`PollResult::PollAgain`].
460    ///
461    /// `poll` runs a limited number of tasks, and returns `PollAgain` if
462    /// scheduled tasks remain. The `poll_again_count` delta divided by the
463    /// [`poll_count`](Self::poll_count) delta over an interval is the share of
464    /// polls that left a backlog; a value close to 1 means tasks are scheduled
465    /// faster than the runtime runs them.
466    pub fn poll_again_count(&self) -> u64 {
467        self.queue.polls_again.load(Ordering::Relaxed)
468    }
469
470    /// Returns the number of times a task woke itself while it was polled.
471    ///
472    /// A task that wakes itself, for example with `wake_by_ref()` or a yield,
473    /// is scheduled again without waiting for an event. A steadily growing
474    /// count points to tasks that poll in a loop, see
475    /// [`RuntimeBuilder::self_wake_threshold`].
476    pub fn self_wake_count(&self) -> u64 {
477        self.queue.self_wakes.load(Ordering::Relaxed)
478    }
479
480    /// Returns the histogram of [`poll`](Self::poll) durations.
481    ///
482    /// Measures time spent inside `poll`, excluding driver-event processing
483    /// before the call. Calls returning [`PollResult::Ready`] are not recorded.
484    /// Long polls can delay driver events and increase scheduling latency.
485    pub fn poll_histogram(&self) -> Histogram {
486        self.queue.poll_histogram.snapshot()
487    }
488
489    /// Runs the provided future.
490    ///
491    /// Blocks the current thread until the future completes.
492    /// The future may borrow local data. Other tasks remain scheduled after
493    /// this call and may be driven by a later call; dropping the runtime cancels
494    /// its unfinished tasks. The supplied future is dropped before returning,
495    /// including if the driver fails or panics.
496    ///
497    /// # Panics
498    ///
499    /// Panics if the driver fails to complete the provided future, or if a runtime
500    /// is already active on the current thread. Nested calls would block the
501    /// running task and its runtime until the inner future completes.
502    #[track_caller]
503    pub fn block_on<F: Future>(&self, future: F, driver: &dyn Driver) -> F::Output {
504        /// Rejects blocking from within an already active runtime.
505        #[cold]
506        #[track_caller]
507        fn nested_block_on() -> ! {
508            panic!("Cannot start a runtime from within a runtime")
509        }
510
511        if CURRENT_RUNTIME.is_set() {
512            nested_block_on()
513        }
514
515        let location = Location::caller();
516        self.stop.set(false);
517        self.queue.set_poll_start(Instant::now());
518
519        CURRENT_RUNTIME.set(self, || {
520            let mut result = None;
521
522            // the task outlives this call if the driver fails or panics, it
523            // reaches the borrowing future only through the slot, which the
524            // guard empties before the borrows end
525            let slot = BlockOnSlot(Rc::new(RefCell::new(Some(Box::pin(async {
526                result = Some(future.await);
527                self.stop.set(true);
528                self.queue.notify();
529            })))));
530            let task = slot.0.clone();
531            // SAFETY: `slot` removes the borrowing future before this scope ends, including on unwind.
532            unsafe {
533                self.spawn_detached_at(
534                    poll_fn(move |cx| {
535                        let mut fut = task.borrow_mut();
536                        if let Some(f) = fut.as_mut()
537                            && f.as_mut().poll(cx).is_pending()
538                        {
539                            return Poll::Pending;
540                        }
541                        *fut = None;
542                        Poll::Ready(())
543                    }),
544                    location,
545                );
546            }
547
548            ntex_error::set_backtrace_start_alt("src/rt/task.rs", 0);
549            let res = driver.run(self);
550            drop(slot);
551            res.expect("Driver failed");
552            result.expect("Driver failed to poll")
553        })
554    }
555}
556
557/// Drops the [`Runtime::block_on`] future when the call returns or unwinds.
558struct BlockOnSlot<F>(Rc<RefCell<Option<Pin<Box<F>>>>>);
559
560impl<F> Drop for BlockOnSlot<F> {
561    /// Removes the borrowing future before the `block_on` scope ends.
562    fn drop(&mut self) {
563        let fut = self.0.borrow_mut().take();
564        drop(fut);
565    }
566}
567
568impl Drop for Runtime {
569    /// Cancels outstanding tasks with this runtime active during cleanup.
570    fn drop(&mut self) {
571        CURRENT_RUNTIME.set(self, || {
572            self.queue.shutdown();
573        });
574    }
575}
576
577#[derive(Debug)]
578/// A thread-safe handle used to schedule work on a runtime.
579pub struct Handle {
580    queue: Arc<RunnableQueue>,
581}
582
583impl Handle {
584    /// Returns a handle to the runtime active on the current thread.
585    ///
586    /// # Panics
587    ///
588    /// Panics if no runtime is active on the current thread.
589    pub fn current() -> Handle {
590        Runtime::with_current(Runtime::handle)
591    }
592
593    /// Wakes the runtime's driver.
594    ///
595    /// Returns notification errors to the caller without retrying, unlike
596    /// internal scheduler notifications.
597    pub fn notify(&self) -> io::Result<()> {
598        self.queue.handle.notify()
599    }
600
601    /// Returns the total time the runtime has been busy.
602    ///
603    /// See [`Runtime::busy_duration`]. Always returns `Some`, the return type
604    /// matches the other runtime backends.
605    pub fn busy_duration(&self) -> Option<Duration> {
606        Some(self.queue.busy.busy_duration())
607    }
608
609    /// Returns how long the current runtime turn has been running, `None`
610    /// while the runtime is idle.
611    ///
612    /// See [`Runtime::current_turn`].
613    pub fn current_turn(&self) -> Option<Duration> {
614        self.queue.busy.current_turn()
615    }
616
617    /// Returns the number of scheduler polls, including polls with no ready tasks.
618    ///
619    /// See [`Runtime::poll_count`]. Always returns `Some`.
620    pub fn poll_count(&self) -> Option<u64> {
621        Some(self.queue.polls.load(Ordering::Relaxed))
622    }
623
624    /// Returns the number of runtime polls that left scheduled tasks.
625    ///
626    /// See [`Runtime::poll_again_count`]. Always returns `Some`.
627    pub fn poll_again_count(&self) -> Option<u64> {
628        Some(self.queue.polls_again.load(Ordering::Relaxed))
629    }
630
631    /// Returns the number of times a task woke itself while it was polled.
632    ///
633    /// See [`Runtime::self_wake_count`]. Always returns `Some`.
634    pub fn self_wake_count(&self) -> Option<u64> {
635        Some(self.queue.self_wakes.load(Ordering::Relaxed))
636    }
637
638    /// Returns the spawn location of the task the runtime is polling.
639    ///
640    /// Returns `None` while the runtime is idle, handles driver events or
641    /// between tasks. Can be read from other threads, for example to name the
642    /// task that blocks a stalled runtime.
643    pub fn current_task(&self) -> Option<&'static Location<'static>> {
644        let task = self.queue.current.load(Ordering::Relaxed);
645        // SAFETY: The owner only stores null or a pointer to a `&'static Location`.
646        unsafe { task.as_ref() }
647    }
648
649    /// Returns the histogram of runtime poll durations.
650    ///
651    /// See [`Runtime::poll_histogram`]. Always returns `Some`.
652    pub fn poll_histogram(&self) -> Option<Histogram> {
653        Some(self.queue.poll_histogram.snapshot())
654    }
655
656    /// Spawns a task on the handle's runtime and returns a [`RemoteJoinHandle`].
657    ///
658    /// Spawning a task enables the task to execute concurrently to other tasks.
659    /// There is no guarantee that a spawned task will execute to completion.
660    ///
661    /// Both the future and output must be `Send`, including submissions from the
662    /// runtime's own thread, which use the local fast path. Accepted futures
663    /// are polled and dropped on the runtime thread; the output is transferred
664    /// to the caller through the join handle.
665    ///
666    /// The returned join handle is neither `Send` nor `Sync`; dropping it
667    /// detaches the task. Submissions rejected after shutdown are never polled
668    /// and their futures may be dropped on the submitting thread. This low-level
669    /// method does not apply registered task callbacks.
670    ///
671    /// ```no_run
672    /// # async fn check(hnd: ntex_rt::rt::Handle) {
673    /// let task = hnd.spawn(async { 42 });
674    /// assert_eq!(task.await.unwrap(), 42);
675    /// # }
676    /// ```
677    #[track_caller]
678    pub fn spawn<F>(&self, future: F) -> RemoteJoinHandle<F::Output>
679    where
680        F: Future + Send + 'static,
681        F::Output: Send + 'static,
682    {
683        let location = Location::caller();
684        if Some(self.queue.id) == try_current_thread_id() {
685            // SAFETY: The identity check establishes owner locality, and the future is `'static`.
686            RemoteJoinHandle::local(unsafe { self.queue.spawn(future, location) })
687        } else {
688            let job = Job::new(future, true);
689            let join = RemoteJoin::new(job.clone());
690            // a rejected submission closes the job on this thread
691            // SAFETY: `Runner` contains a `Send`, `'static` future and output, permitting remote submission.
692            unsafe {
693                self.queue.spawn_detached::<_, false>(Runner(job), location);
694            }
695            RemoteJoinHandle::remote(join)
696        }
697    }
698
699    /// Spawns a new asynchronous task without a join handle.
700    ///
701    /// The output is dropped on the runtime thread when the task completes,
702    /// so it does not have to be `Send`.
703    /// The future must be `Send`, even when submitted on the owner thread.
704    /// Rejected submissions are never polled and their futures may be dropped
705    /// on the submitting thread. Registered task callbacks are not applied.
706    #[track_caller]
707    pub fn spawn_detached<F>(&self, future: F)
708    where
709        F: Future + Send + 'static,
710    {
711        // SAFETY: The future is `Send` and `'static`, permitting either local or remote submission.
712        unsafe {
713            self.queue
714                .spawn_detached::<_, false>(future, Location::caller());
715        }
716    }
717}
718
719impl Clone for Handle {
720    /// Shares the runtime's queue without creating another runtime.
721    fn clone(&self) -> Self {
722        Self {
723            queue: self.queue.clone(),
724        }
725    }
726}
727
728/// Builder for [`Runtime`].
729#[derive(Debug, Clone)]
730pub struct RuntimeBuilder {
731    event_interval: usize,
732    self_wake_limit: u32,
733    self_wake_time: Duration,
734}
735
736impl Default for RuntimeBuilder {
737    /// Uses the default scheduler budgets and self-wake thresholds.
738    fn default() -> Self {
739        Self::new()
740    }
741}
742
743impl RuntimeBuilder {
744    /// Creates a builder with the default scheduler budgets and warning thresholds.
745    pub fn new() -> Self {
746        Self {
747            event_interval: 61,
748            self_wake_limit: 10_000,
749            self_wake_time: Duration::from_secs(1),
750        }
751    }
752
753    /// Sets the local task-poll budget for one [`Runtime::poll`] call.
754    ///
755    /// The driver can process external events between calls. Remote work is
756    /// serviced in separate batches, so this is not a strict limit on all work
757    /// done in one call. The default is 61; zero is treated as one.
758    pub fn event_interval(&mut self, val: usize) -> &mut Self {
759        self.event_interval = val.max(1);
760        self
761    }
762
763    /// Sets the self-wake streak that is reported as a possible busy loop.
764    ///
765    /// A task that wakes itself on every poll, for example a loop around
766    /// `wake_by_ref()` or a yield, never waits for an event. The runtime logs
767    /// a warning with the task spawn location once the task wakes itself
768    /// `count` times in a row and the streak lasts at least `duration`. Each
769    /// streak is reported once. A count of 0 disables the warning and per-task
770    /// streak tracking, but preserves [`Runtime::self_wake_count`].
771    ///
772    /// By default, 10 000 self-wakes over at least 1 second.
773    pub fn self_wake_threshold(&mut self, count: u32, duration: Duration) -> &mut Self {
774        self.self_wake_limit = count.min(!REPORTED);
775        self.self_wake_time = duration;
776        self
777    }
778
779    /// Creates a native runtime using this configuration and driver notifier.
780    ///
781    /// Does not start an event loop. The notifier must wake the driver used to
782    /// run this runtime.
783    pub fn build(&self, handle: Box<dyn Notify>) -> Runtime {
784        Runtime::with_builder(self, handle)
785    }
786}
787
788#[cfg(test)]
789#[path = "../../tests/rt/task_tests.rs"]
790mod task_tests;
791
792#[cfg(all(test, ntex_loom))]
793#[path = "../../tests/rt/task_loom.rs"]
794mod task_loom;
795
796#[cfg(test)]
797#[path = "../../tests/rt/tests.rs"]
798mod tests;