Skip to main content

ntex_rt/
rt_tokio.rs

1use std::task::{Context, Poll, ready};
2use std::time::{Duration, Instant};
3use std::{fmt, future::Future, marker::PhantomData, pin::Pin, rc::Rc, sync::Arc};
4
5use crate::arbiter::Arbiter;
6use crate::metrics::Histogram;
7use crate::remote::{Job, RemoteJoin, Spawner};
8
9/// Returns the current time.
10///
11/// Tokio does not expose the start of a runtime turn, so this is
12/// [`Instant::now()`].
13#[inline]
14pub fn now() -> Instant {
15    Instant::now()
16}
17
18#[inline]
19/// Spawns a future on the current Tokio local task set and returns its join handle.
20///
21/// The future and output need not be `Send`. The current system's
22/// [`TaskCallbacks`](crate::TaskCallbacks) are applied. Dropping the handle detaches the task unless
23/// [`cancel_on_drop`](JoinHandle::cancel_on_drop) is enabled. The local task set
24/// must keep being driven for it to make progress. An ntex system is not required,
25/// without one no task callbacks are applied.
26///
27/// # Panics
28///
29/// Panics outside a Tokio context that supports local spawning, such as a
30/// [`LocalSet`](tok_io::task::LocalSet).
31pub fn spawn<F>(f: F) -> JoinHandle<F::Output>
32where
33    F: Future + 'static,
34{
35    JoinHandle::new(tok_io::task::spawn_local(crate::task::wrap(f)))
36}
37
38#[inline]
39/// Spawns a future on the current thread without a join handle.
40///
41/// Like [`spawn()`], this applies registered task callbacks and supports
42/// non-`Send` futures and outputs. The output is discarded when the task
43/// completes. No ntex join handle is returned.
44///
45/// # Panics
46///
47/// Panics outside a Tokio context that supports local spawning, such as a
48/// [`LocalSet`](tok_io::task::LocalSet).
49pub fn spawn_detached<F>(f: F)
50where
51    F: Future + 'static,
52{
53    drop(tok_io::task::spawn_local(crate::task::wrap(f)));
54}
55
56/// Error returned when a Tokio-backed task ends without an output.
57///
58/// Cancellation and task panics are reported without preserving their cause.
59#[derive(Debug, Copy, Clone)]
60pub struct JoinError;
61
62impl fmt::Display for JoinError {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        write!(f, "JoinError")
65    }
66}
67
68impl std::error::Error for JoinError {}
69
70/// A local task handle. It is neither `Send` nor `Sync`.
71///
72/// Returned by [`spawn()`]. Dropping the handle detaches the task unless
73/// [`cancel_on_drop`](Self::cancel_on_drop) is enabled.
74/// Awaiting it returns the task output or [`JoinError`] on cancellation or panic.
75#[derive(Debug)]
76pub struct JoinHandle<T> {
77    task: Option<tok_io::task::JoinHandle<T>>,
78    cancel_on_drop: bool,
79    _local: PhantomData<Rc<()>>,
80}
81
82impl<T> JoinHandle<T> {
83    fn new(task: tok_io::task::JoinHandle<T>) -> Self {
84        Self {
85            task: Some(task),
86            cancel_on_drop: false,
87            _local: PhantomData,
88        }
89    }
90
91    /// Requests cancellation when this handle is dropped instead of detaching the task.
92    ///
93    /// Cancellation follows [`cancel`](Self::cancel) and does not wait for cleanup.
94    /// A running poll is not interrupted. The deprecated [`detach`](Self::detach)
95    /// method still overrides this setting.
96    #[must_use]
97    pub fn cancel_on_drop(mut self) -> Self {
98        self.cancel_on_drop = true;
99        self
100    }
101
102    /// Requests cancellation and discards the result without waiting for cleanup.
103    ///
104    /// A running poll is not interrupted; the local task set must make progress
105    /// for cancellation of a pending task to finish.
106    pub fn cancel(mut self) {
107        if let Some(t) = self.task.take() {
108            t.abort();
109        }
110    }
111
112    /// Detaches the task to let it keep running in the background.
113    ///
114    /// Overrides [`cancel_on_drop`](Self::cancel_on_drop) without requesting cancellation.
115    #[deprecated(
116        since = "4.5.0",
117        note = "Drop the handle instead if cancel_on_drop() is not enabled"
118    )]
119    pub fn detach(mut self) {
120        self.cancel_on_drop = false;
121    }
122
123    /// Returns `true` if the task completed, panicked, or finished cancellation.
124    pub fn is_finished(&self) -> bool {
125        match &self.task {
126            Some(t) => t.is_finished(),
127            None => true,
128        }
129    }
130}
131
132impl<T> Drop for JoinHandle<T> {
133    fn drop(&mut self) {
134        if self.cancel_on_drop
135            && let Some(t) = &self.task
136        {
137            t.abort();
138        }
139    }
140}
141
142impl<T> Future for JoinHandle<T> {
143    type Output = Result<T, JoinError>;
144
145    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
146        Poll::Ready(match self.task.as_mut() {
147            Some(t) => ready!(Pin::new(t).poll(cx)).map_err(|_| JoinError),
148            None => Err(JoinError),
149        })
150    }
151}
152
153/// A task handle returned by [`Handle::spawn()`].
154///
155/// It is neither `Send` nor `Sync` and stays on the calling thread.
156/// Submissions on the runtime thread retain the local spawn fast path.
157/// Dropping the handle detaches the task.
158/// Awaiting it returns the output or [`JoinError`] if the task ended without
159/// one, including when submission was rejected during shutdown.
160#[derive(Debug)]
161pub struct RemoteJoinHandle<T> {
162    inner: Inner<T>,
163}
164
165#[derive(Debug)]
166enum Inner<T> {
167    Local(JoinHandle<T>),
168    Remote(RemoteJoin<T>),
169}
170
171impl<T> RemoteJoinHandle<T> {
172    fn local(task: JoinHandle<T>) -> Self {
173        Self {
174            inner: Inner::Local(task),
175        }
176    }
177
178    fn remote(join: RemoteJoin<T>) -> Self {
179        Self {
180            inner: Inner::Remote(join),
181        }
182    }
183
184    /// Requests cancellation and discards the result without waiting for cleanup.
185    ///
186    /// Accepted futures are dropped on the runtime thread. A running poll is
187    /// not interrupted, and the runtime must make progress to finish cancellation.
188    pub fn cancel(self) {
189        match self.inner {
190            Inner::Local(t) => t.cancel(),
191            Inner::Remote(t) => t.cancel(),
192        }
193    }
194
195    /// Detaches the task to let it keep running in the background.
196    ///
197    /// This method does nothing beyond dropping the handle; dropping it already
198    /// detaches the task without canceling it.
199    #[deprecated(since = "4.5.0", note = "Use drop(handle) instead")]
200    pub fn detach(self) {}
201
202    /// Returns `true` if the task completed or ended without an output.
203    pub fn is_finished(&self) -> bool {
204        match &self.inner {
205            Inner::Local(t) => t.is_finished(),
206            Inner::Remote(t) => t.is_finished(),
207        }
208    }
209}
210
211impl<T> Future for RemoteJoinHandle<T> {
212    type Output = Result<T, JoinError>;
213
214    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
215        Poll::Ready(match &mut self.inner {
216            Inner::Local(t) => ready!(Pin::new(t).poll(cx)),
217            Inner::Remote(t) => ready!(t.poll_join(cx)).ok_or(JoinError),
218        })
219    }
220}
221
222#[derive(Clone, Debug)]
223/// A thread-safe handle for submitting work to a Tokio-backed arbiter.
224///
225/// Clones share the same target arbiter; they do not create another runtime.
226pub struct Handle {
227    spawner: Arc<Spawner>,
228    rt: Option<tok_io::runtime::Handle>,
229}
230
231impl Handle {
232    /// Must be called on the arbiter thread, inside its runtime.
233    pub(crate) fn new() -> Self {
234        // the arbiter runs on the single worker of a current-thread runtime
235        let rt = tok_io::runtime::Handle::try_current()
236            .ok()
237            .filter(|h| h.runtime_flavor() == tok_io::runtime::RuntimeFlavor::CurrentThread);
238        Self {
239            spawner: Spawner::start(),
240            rt,
241        }
242    }
243
244    /// Returns a handle to the current arbiter's runtime.
245    ///
246    /// # Panics
247    ///
248    /// Panics if no arbiter is installed on the current thread. A Tokio runtime
249    /// context alone is not sufficient.
250    pub fn current() -> Self {
251        Arbiter::current().handle().clone()
252    }
253
254    #[inline]
255    /// Compatibility hook that does nothing on the Tokio backend.
256    ///
257    /// Task submission and task wakers notify Tokio automatically.
258    pub fn notify(&self) {}
259
260    /// Returns the total time the runtime has been busy.
261    ///
262    /// Reports Tokio's `worker_total_busy_duration`, which excludes time spent
263    /// handling driver events. Returns `None` if the arbiter does not run on a
264    /// current-thread Tokio runtime.
265    pub fn busy_duration(&self) -> Option<Duration> {
266        self.rt
267            .as_ref()
268            .map(|h| h.metrics().worker_total_busy_duration(0))
269    }
270
271    /// Returns how long the current runtime turn has been running.
272    ///
273    /// Tokio does not expose runtime turns; always returns `None`.
274    pub fn current_turn(&self) -> Option<Duration> {
275        None
276    }
277
278    /// Returns the number of runtime polls, not available on Tokio.
279    ///
280    /// Always returns `None`, the method exists for compatibility with the
281    /// other runtime backends.
282    pub fn poll_count(&self) -> Option<u64> {
283        None
284    }
285
286    /// Returns the number of runtime polls that left scheduled tasks, not
287    /// available on Tokio.
288    ///
289    /// Always returns `None`, the method exists for compatibility with the
290    /// other runtime backends.
291    pub fn poll_again_count(&self) -> Option<u64> {
292        None
293    }
294
295    /// Returns the number of times a task woke itself while it was polled, not
296    /// available on Tokio.
297    ///
298    /// Always returns `None`, the method exists for compatibility with the
299    /// native runtime.
300    pub fn self_wake_count(&self) -> Option<u64> {
301        None
302    }
303
304    /// Returns the spawn location of the task the runtime is polling, not
305    /// available on Tokio.
306    ///
307    /// Always returns `None`, the method exists for compatibility with the
308    /// native runtime.
309    pub fn current_task(&self) -> Option<&'static std::panic::Location<'static>> {
310        None
311    }
312
313    /// Returns the histogram of runtime turn durations, not available on Tokio.
314    ///
315    /// Always returns `None`, the method exists for compatibility with the
316    /// other runtime backends.
317    pub fn poll_histogram(&self) -> Option<Histogram> {
318        None
319    }
320
321    /// Spawns a task on the handle's runtime and returns a [`RemoteJoinHandle`].
322    ///
323    /// There is no guarantee that a spawned task will execute to completion.
324    /// Both the future and output must be `Send`, even when submitted on the
325    /// runtime thread, which uses the local spawn fast path. Accepted futures
326    /// are polled and dropped on the runtime thread, with the output transferred
327    /// through the join handle. Rejected submissions are never polled and their
328    /// futures may be dropped on the submitting thread.
329    ///
330    /// The returned join handle is neither `Send` nor `Sync`; dropping it
331    /// detaches the task.
332    ///
333    /// # Panics
334    ///
335    /// Panics on the owner thread if there is no Tokio context supporting
336    /// local spawning. Submissions from other threads do not require one.
337    pub fn spawn<F>(&self, future: F) -> RemoteJoinHandle<F::Output>
338    where
339        F: Future + Send + 'static,
340        F::Output: Send + 'static,
341    {
342        if self.spawner.is_owner() {
343            RemoteJoinHandle::local(spawn(future))
344        } else {
345            let job = Job::new(future, true);
346            let join = RemoteJoin::new(job.clone());
347            self.spawner.submit(job);
348            RemoteJoinHandle::remote(join)
349        }
350    }
351
352    /// Spawns a new asynchronous task without a join handle.
353    ///
354    /// The output is dropped on the runtime thread when the task completes,
355    /// so it does not have to be `Send`.
356    /// The future must be `Send`, even on the owner thread. Rejected submissions
357    /// are never polled and their futures may be dropped on the submitting thread.
358    ///
359    /// # Panics
360    ///
361    /// Panics on the owner thread if there is no Tokio context supporting
362    /// local spawning. Submissions from other threads do not require one.
363    pub fn spawn_detached<F>(&self, future: F)
364    where
365        F: Future + Send + 'static,
366    {
367        if self.spawner.is_owner() {
368            spawn_detached(future);
369        } else {
370            self.spawner.submit(Job::new(
371                async move {
372                    future.await;
373                },
374                false,
375            ));
376        }
377    }
378}