tokio/runtime/
handle.rs

1#[cfg(tokio_unstable)]
2use crate::runtime;
3use crate::runtime::{context, scheduler, RuntimeFlavor, RuntimeMetrics};
4
5/// Handle to the runtime.
6///
7/// The handle is internally reference-counted and can be freely cloned. A handle can be
8/// obtained using the [`Runtime::handle`] method.
9///
10/// [`Runtime::handle`]: crate::runtime::Runtime::handle()
11#[derive(Debug, Clone)]
12// When the `rt` feature is *not* enabled, this type is still defined, but not
13// included in the public API.
14pub struct Handle {
15    pub(crate) inner: scheduler::Handle,
16}
17
18use crate::runtime::task::JoinHandle;
19use crate::runtime::BOX_FUTURE_THRESHOLD;
20use crate::util::error::{CONTEXT_MISSING_ERROR, THREAD_LOCAL_DESTROYED_ERROR};
21use crate::util::trace::SpawnMeta;
22
23use std::future::Future;
24use std::marker::PhantomData;
25use std::{error, fmt, mem};
26
27/// Runtime context guard.
28///
29/// Returned by [`Runtime::enter`] and [`Handle::enter`], the context guard exits
30/// the runtime context on drop.
31///
32/// [`Runtime::enter`]: fn@crate::runtime::Runtime::enter
33#[derive(Debug)]
34#[must_use = "Creating and dropping a guard does nothing"]
35pub struct EnterGuard<'a> {
36    _guard: context::SetCurrentGuard,
37    _handle_lifetime: PhantomData<&'a Handle>,
38}
39
40impl Handle {
41    /// Enters the runtime context. This allows you to construct types that must
42    /// have an executor available on creation such as [`Sleep`] or
43    /// [`TcpStream`]. It will also allow you to call methods such as
44    /// [`tokio::spawn`] and [`Handle::current`] without panicking.
45    ///
46    /// # Panics
47    ///
48    /// When calling `Handle::enter` multiple times, the returned guards
49    /// **must** be dropped in the reverse order that they were acquired.
50    /// Failure to do so will result in a panic and possible memory leaks.
51    ///
52    /// # Examples
53    ///
54    /// ```
55    /// # #[cfg(not(target_family = "wasm"))]
56    /// # {
57    /// use tokio::runtime::Runtime;
58    ///
59    /// let rt = Runtime::new().unwrap();
60    ///
61    /// let _guard = rt.enter();
62    /// tokio::spawn(async {
63    ///     println!("Hello world!");
64    /// });
65    /// # }
66    /// ```
67    ///
68    /// Do **not** do the following, this shows a scenario that will result in a
69    /// panic and possible memory leak.
70    ///
71    /// ```should_panic,ignore-wasm
72    /// use tokio::runtime::Runtime;
73    ///
74    /// let rt1 = Runtime::new().unwrap();
75    /// let rt2 = Runtime::new().unwrap();
76    ///
77    /// let enter1 = rt1.enter();
78    /// let enter2 = rt2.enter();
79    ///
80    /// drop(enter1);
81    /// drop(enter2);
82    /// ```
83    ///
84    /// [`Sleep`]: struct@crate::time::Sleep
85    /// [`TcpStream`]: struct@crate::net::TcpStream
86    /// [`tokio::spawn`]: fn@crate::spawn
87    pub fn enter(&self) -> EnterGuard<'_> {
88        EnterGuard {
89            _guard: match context::try_set_current(&self.inner) {
90                Some(guard) => guard,
91                None => panic!("{}", crate::util::error::THREAD_LOCAL_DESTROYED_ERROR),
92            },
93            _handle_lifetime: PhantomData,
94        }
95    }
96
97    /// Returns a `Handle` view over the currently running `Runtime`.
98    ///
99    /// # Panics
100    ///
101    /// This will panic if called outside the context of a Tokio runtime. That means that you must
102    /// call this on one of the threads **being run by the runtime**, or from a thread with an active
103    /// `EnterGuard`. Calling this from within a thread created by `std::thread::spawn` (for example)
104    /// will cause a panic unless that thread has an active `EnterGuard`.
105    ///
106    /// # Examples
107    ///
108    /// This can be used to obtain the handle of the surrounding runtime from an async
109    /// block or function running on that runtime.
110    ///
111    /// ```
112    /// # #[cfg(not(target_family = "wasm"))]
113    /// # {
114    /// # use std::thread;
115    /// # use tokio::runtime::Runtime;
116    /// # fn dox() {
117    /// # let rt = Runtime::new().unwrap();
118    /// # rt.spawn(async {
119    /// use tokio::runtime::Handle;
120    ///
121    /// // Inside an async block or function.
122    /// let handle = Handle::current();
123    /// handle.spawn(async {
124    ///     println!("now running in the existing Runtime");
125    /// });
126    ///
127    /// # let handle =
128    /// thread::spawn(move || {
129    ///     // Notice that the handle is created outside of this thread and then moved in
130    ///     handle.spawn(async { /* ... */ });
131    ///     // This next line would cause a panic because we haven't entered the runtime
132    ///     // and created an EnterGuard
133    ///     // let handle2 = Handle::current(); // panic
134    ///     // So we create a guard here with Handle::enter();
135    ///     let _guard = handle.enter();
136    ///     // Now we can call Handle::current();
137    ///     let handle2 = Handle::current();
138    /// });
139    /// # handle.join().unwrap();
140    /// # });
141    /// # }
142    /// # }
143    /// ```
144    #[track_caller]
145    pub fn current() -> Self {
146        Handle {
147            inner: scheduler::Handle::current(),
148        }
149    }
150
151    /// Returns a Handle view over the currently running Runtime
152    ///
153    /// Returns an error if no Runtime has been started
154    ///
155    /// Contrary to `current`, this never panics
156    pub fn try_current() -> Result<Self, TryCurrentError> {
157        context::with_current(|inner| Handle {
158            inner: inner.clone(),
159        })
160    }
161
162    /// Spawns a future onto the Tokio runtime.
163    ///
164    /// This spawns the given future onto the runtime's executor, usually a
165    /// thread pool. The thread pool is then responsible for polling the future
166    /// until it completes.
167    ///
168    /// The provided future will start running in the background immediately
169    /// when `spawn` is called, even if you don't await the returned
170    /// `JoinHandle`.
171    ///
172    /// See [module level][mod] documentation for more details.
173    ///
174    /// [mod]: index.html
175    ///
176    /// # Examples
177    ///
178    /// ```
179    /// # #[cfg(not(target_family = "wasm"))]
180    /// # {
181    /// use tokio::runtime::Runtime;
182    ///
183    /// # fn dox() {
184    /// // Create the runtime
185    /// let rt = Runtime::new().unwrap();
186    /// // Get a handle from this runtime
187    /// let handle = rt.handle();
188    ///
189    /// // Spawn a future onto the runtime using the handle
190    /// handle.spawn(async {
191    ///     println!("now running on a worker thread");
192    /// });
193    /// # }
194    /// # }
195    /// ```
196    #[track_caller]
197    pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output>
198    where
199        F: Future + Send + 'static,
200        F::Output: Send + 'static,
201    {
202        let fut_size = mem::size_of::<F>();
203        if fut_size > BOX_FUTURE_THRESHOLD {
204            self.spawn_named(Box::pin(future), SpawnMeta::new_unnamed(fut_size))
205        } else {
206            self.spawn_named(future, SpawnMeta::new_unnamed(fut_size))
207        }
208    }
209
210    /// Runs the provided function on an executor dedicated to blocking
211    /// operations.
212    ///
213    /// # Examples
214    ///
215    /// ```
216    /// # #[cfg(not(target_family = "wasm"))]
217    /// # {
218    /// use tokio::runtime::Runtime;
219    ///
220    /// # fn dox() {
221    /// // Create the runtime
222    /// let rt = Runtime::new().unwrap();
223    /// // Get a handle from this runtime
224    /// let handle = rt.handle();
225    ///
226    /// // Spawn a blocking function onto the runtime using the handle
227    /// handle.spawn_blocking(|| {
228    ///     println!("now running on a worker thread");
229    /// });
230    /// # }
231    /// # }
232    /// ```
233    #[track_caller]
234    pub fn spawn_blocking<F, R>(&self, func: F) -> JoinHandle<R>
235    where
236        F: FnOnce() -> R + Send + 'static,
237        R: Send + 'static,
238    {
239        self.inner.blocking_spawner().spawn_blocking(self, func)
240    }
241
242    /// Runs a future to completion on this `Handle`'s associated `Runtime`.
243    ///
244    /// This runs the given future on the current thread, blocking until it is
245    /// complete, and yielding its resolved result. Any tasks or timers which
246    /// the future spawns internally will be executed on the runtime.
247    ///
248    /// When this is used on a `current_thread` runtime, only the
249    /// [`Runtime::block_on`] method can drive the IO and timer drivers, but the
250    /// `Handle::block_on` method cannot drive them. This means that, when using
251    /// this method on a `current_thread` runtime, anything that relies on IO or
252    /// timers will not work unless there is another thread currently calling
253    /// [`Runtime::block_on`] on the same runtime.
254    ///
255    /// # If the runtime has been shut down
256    ///
257    /// If the `Handle`'s associated `Runtime` has been shut down (through
258    /// [`Runtime::shutdown_background`], [`Runtime::shutdown_timeout`], or by
259    /// dropping it) and `Handle::block_on` is used it might return an error or
260    /// panic. Specifically IO resources will return an error and timers will
261    /// panic. Runtime independent futures will run as normal.
262    ///
263    /// # Panics
264    ///
265    /// This function will panic if any of the following conditions are met:
266    /// - The provided future panics.
267    /// - It is called from within an asynchronous context, such as inside
268    ///   [`Runtime::block_on`], `Handle::block_on`, or from a function annotated
269    ///   with [`tokio::main`].
270    /// - A timer future is executed on a runtime that has been shut down.
271    ///
272    /// # Examples
273    ///
274    /// ```
275    /// # #[cfg(not(target_family = "wasm"))]
276    /// # {
277    /// use tokio::runtime::Runtime;
278    ///
279    /// // Create the runtime
280    /// let rt  = Runtime::new().unwrap();
281    ///
282    /// // Get a handle from this runtime
283    /// let handle = rt.handle();
284    ///
285    /// // Execute the future, blocking the current thread until completion
286    /// handle.block_on(async {
287    ///     println!("hello");
288    /// });
289    /// # }
290    /// ```
291    ///
292    /// Or using `Handle::current`:
293    ///
294    /// ```
295    /// # #[cfg(not(target_family = "wasm"))]
296    /// # {
297    /// use tokio::runtime::Handle;
298    ///
299    /// #[tokio::main]
300    /// async fn main () {
301    ///     let handle = Handle::current();
302    ///     std::thread::spawn(move || {
303    ///         // Using Handle::block_on to run async code in the new thread.
304    ///         handle.block_on(async {
305    ///             println!("hello");
306    ///         });
307    ///     });
308    /// }
309    /// # }
310    /// ```
311    ///
312    /// `Handle::block_on` may be combined with [`task::block_in_place`] to
313    /// re-enter the async context of a multi-thread scheduler runtime:
314    /// ```
315    /// # #[cfg(not(target_family = "wasm"))]
316    /// # {
317    /// use tokio::task;
318    /// use tokio::runtime::Handle;
319    ///
320    /// # async fn docs() {
321    /// task::block_in_place(move || {
322    ///     Handle::current().block_on(async move {
323    ///         // do something async
324    ///     });
325    /// });
326    /// # }
327    /// # }
328    /// ```
329    ///
330    /// [`JoinError`]: struct@crate::task::JoinError
331    /// [`JoinHandle`]: struct@crate::task::JoinHandle
332    /// [`Runtime::block_on`]: fn@crate::runtime::Runtime::block_on
333    /// [`Runtime::shutdown_background`]: fn@crate::runtime::Runtime::shutdown_background
334    /// [`Runtime::shutdown_timeout`]: fn@crate::runtime::Runtime::shutdown_timeout
335    /// [`spawn_blocking`]: crate::task::spawn_blocking
336    /// [`tokio::fs`]: crate::fs
337    /// [`tokio::net`]: crate::net
338    /// [`tokio::time`]: crate::time
339    /// [`tokio::main`]: ../attr.main.html
340    /// [`task::block_in_place`]: crate::task::block_in_place
341    #[track_caller]
342    pub fn block_on<F: Future>(&self, future: F) -> F::Output {
343        let fut_size = mem::size_of::<F>();
344        if fut_size > BOX_FUTURE_THRESHOLD {
345            self.block_on_inner(Box::pin(future), SpawnMeta::new_unnamed(fut_size))
346        } else {
347            self.block_on_inner(future, SpawnMeta::new_unnamed(fut_size))
348        }
349    }
350
351    #[track_caller]
352    fn block_on_inner<F: Future>(&self, future: F, _meta: SpawnMeta<'_>) -> F::Output {
353        #[cfg(all(
354            tokio_unstable,
355            feature = "taskdump",
356            feature = "rt",
357            target_os = "linux",
358            any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")
359        ))]
360        let future = super::task::trace::Trace::root(future);
361
362        #[cfg(all(tokio_unstable, feature = "tracing"))]
363        let future =
364            crate::util::trace::task(future, "block_on", _meta, super::task::Id::next().as_u64());
365
366        // Enter the runtime context. This sets the current driver handles and
367        // prevents blocking an existing runtime.
368        context::enter_runtime(&self.inner, true, |blocking| {
369            blocking.block_on(future).expect("failed to park thread")
370        })
371    }
372
373    #[track_caller]
374    pub(crate) fn spawn_named<F>(&self, future: F, meta: SpawnMeta<'_>) -> JoinHandle<F::Output>
375    where
376        F: Future + Send + 'static,
377        F::Output: Send + 'static,
378    {
379        let id = crate::runtime::task::Id::next();
380        #[cfg(all(
381            tokio_unstable,
382            feature = "taskdump",
383            feature = "rt",
384            target_os = "linux",
385            any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")
386        ))]
387        let future = super::task::trace::Trace::root(future);
388        #[cfg(all(tokio_unstable, feature = "tracing"))]
389        let future = crate::util::trace::task(future, "task", meta, id.as_u64());
390        self.inner.spawn(future, id, meta.spawned_at)
391    }
392
393    #[track_caller]
394    #[allow(dead_code)]
395    pub(crate) unsafe fn spawn_local_named<F>(
396        &self,
397        future: F,
398        meta: SpawnMeta<'_>,
399    ) -> JoinHandle<F::Output>
400    where
401        F: Future + 'static,
402        F::Output: 'static,
403    {
404        let id = crate::runtime::task::Id::next();
405        #[cfg(all(
406            tokio_unstable,
407            feature = "taskdump",
408            feature = "rt",
409            target_os = "linux",
410            any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64")
411        ))]
412        let future = super::task::trace::Trace::root(future);
413        #[cfg(all(tokio_unstable, feature = "tracing"))]
414        let future = crate::util::trace::task(future, "task", meta, id.as_u64());
415        self.inner.spawn_local(future, id, meta.spawned_at)
416    }
417
418    /// Returns the flavor of the current `Runtime`.
419    ///
420    /// # Examples
421    ///
422    /// ```
423    /// use tokio::runtime::{Handle, RuntimeFlavor};
424    ///
425    /// #[tokio::main(flavor = "current_thread")]
426    /// async fn main() {
427    ///   assert_eq!(RuntimeFlavor::CurrentThread, Handle::current().runtime_flavor());
428    /// }
429    /// ```
430    ///
431    /// ```
432    /// # #[cfg(not(target_family = "wasm"))]
433    /// # {
434    /// use tokio::runtime::{Handle, RuntimeFlavor};
435    ///
436    /// #[tokio::main(flavor = "multi_thread", worker_threads = 4)]
437    /// async fn main() {
438    ///   assert_eq!(RuntimeFlavor::MultiThread, Handle::current().runtime_flavor());
439    /// }
440    /// # }
441    /// ```
442    pub fn runtime_flavor(&self) -> RuntimeFlavor {
443        match self.inner {
444            scheduler::Handle::CurrentThread(_) => RuntimeFlavor::CurrentThread,
445            #[cfg(feature = "rt-multi-thread")]
446            scheduler::Handle::MultiThread(_) => RuntimeFlavor::MultiThread,
447        }
448    }
449
450    cfg_unstable! {
451        /// Returns the [`Id`] of the current `Runtime`.
452        ///
453        /// # Examples
454        ///
455        /// ```
456        /// use tokio::runtime::Handle;
457        ///
458        /// #[tokio::main(flavor = "current_thread")]
459        /// async fn main() {
460        ///   println!("Current runtime id: {}", Handle::current().id());
461        /// }
462        /// ```
463        ///
464        /// **Note**: This is an [unstable API][unstable]. The public API of this type
465        /// may break in 1.x releases. See [the documentation on unstable
466        /// features][unstable] for details.
467        ///
468        /// [unstable]: crate#unstable-features
469        /// [`Id`]: struct@crate::runtime::Id
470        pub fn id(&self) -> runtime::Id {
471            let owned_id = match &self.inner {
472                scheduler::Handle::CurrentThread(handle) => handle.owned_id(),
473                #[cfg(feature = "rt-multi-thread")]
474                scheduler::Handle::MultiThread(handle) => handle.owned_id(),
475            };
476            owned_id.into()
477        }
478    }
479
480    /// Returns a view that lets you get information about how the runtime
481    /// is performing.
482    pub fn metrics(&self) -> RuntimeMetrics {
483        RuntimeMetrics::new(self.clone())
484    }
485}
486
487impl std::panic::UnwindSafe for Handle {}
488
489impl std::panic::RefUnwindSafe for Handle {}
490
491cfg_taskdump! {
492    impl Handle {
493        /// Captures a snapshot of the runtime's state.
494        ///
495        /// If you only want to capture a snapshot of a single future's state, you can use
496        /// [`Trace::capture`][crate::runtime::dump::Trace].
497        ///
498        /// This functionality is experimental, and comes with a number of
499        /// requirements and limitations.
500        ///
501        /// # Examples
502        ///
503        /// This can be used to get call traces of each task in the runtime.
504        /// Calls to `Handle::dump` should usually be enclosed in a
505        /// [timeout][crate::time::timeout], so that dumping does not escalate a
506        /// single blocked runtime thread into an entirely blocked runtime.
507        ///
508        /// ```
509        /// # use tokio::runtime::Runtime;
510        /// # fn dox() {
511        /// # let rt = Runtime::new().unwrap();
512        /// # rt.spawn(async {
513        /// use tokio::runtime::Handle;
514        /// use tokio::time::{timeout, Duration};
515        ///
516        /// // Inside an async block or function.
517        /// let handle = Handle::current();
518        /// if let Ok(dump) = timeout(Duration::from_secs(2), handle.dump()).await {
519        ///     for (i, task) in dump.tasks().iter().enumerate() {
520        ///         let trace = task.trace();
521        ///         println!("TASK {i}:");
522        ///         println!("{trace}\n");
523        ///     }
524        /// }
525        /// # });
526        /// # }
527        /// ```
528        ///
529        /// This produces highly detailed traces of tasks; e.g.:
530        ///
531        /// ```plain
532        /// TASK 0:
533        /// ╼ dump::main::{{closure}}::a::{{closure}} at /tokio/examples/dump.rs:18:20
534        /// └╼ dump::main::{{closure}}::b::{{closure}} at /tokio/examples/dump.rs:23:20
535        ///    └╼ dump::main::{{closure}}::c::{{closure}} at /tokio/examples/dump.rs:28:24
536        ///       └╼ tokio::sync::barrier::Barrier::wait::{{closure}} at /tokio/tokio/src/sync/barrier.rs:129:10
537        ///          └╼ <tokio::util::trace::InstrumentedAsyncOp<F> as core::future::future::Future>::poll at /tokio/tokio/src/util/trace.rs:77:46
538        ///             └╼ tokio::sync::barrier::Barrier::wait_internal::{{closure}} at /tokio/tokio/src/sync/barrier.rs:183:36
539        ///                └╼ tokio::sync::watch::Receiver<T>::changed::{{closure}} at /tokio/tokio/src/sync/watch.rs:604:55
540        ///                   └╼ tokio::sync::watch::changed_impl::{{closure}} at /tokio/tokio/src/sync/watch.rs:755:18
541        ///                      └╼ <tokio::sync::notify::Notified as core::future::future::Future>::poll at /tokio/tokio/src/sync/notify.rs:1103:9
542        ///                         └╼ tokio::sync::notify::Notified::poll_notified at /tokio/tokio/src/sync/notify.rs:996:32
543        /// ```
544        ///
545        /// # Requirements
546        ///
547        /// ## Debug Info Must Be Available
548        ///
549        /// To produce task traces, the application must **not** be compiled
550        /// with `split debuginfo`. On Linux, including `debuginfo` within the
551        /// application binary is the (correct) default. You can further ensure
552        /// this behavior with the following directive in your `Cargo.toml`:
553        ///
554        /// ```toml
555        /// [profile.*]
556        /// split-debuginfo = "off"
557        /// ```
558        ///
559        /// ## Unstable Features
560        ///
561        /// This functionality is **unstable**, and requires both the
562        /// `--cfg tokio_unstable` and cargo feature `taskdump` to be set.
563        ///
564        /// You can do this by setting the `RUSTFLAGS` environment variable
565        /// before invoking `cargo`; e.g.:
566        /// ```bash
567        /// RUSTFLAGS="--cfg tokio_unstable cargo run --example dump
568        /// ```
569        ///
570        /// Or by [configuring][cargo-config] `rustflags` in
571        /// `.cargo/config.toml`:
572        /// ```text
573        /// [build]
574        /// rustflags = ["--cfg", "tokio_unstable"]
575        /// ```
576        ///
577        /// [cargo-config]:
578        ///     https://doc.rust-lang.org/cargo/reference/config.html
579        ///
580        /// ## Platform Requirements
581        ///
582        /// Task dumps are supported on Linux atop `aarch64`, `x86` and `x86_64`.
583        ///
584        /// ## Current Thread Runtime Requirements
585        ///
586        /// On the `current_thread` runtime, task dumps may only be requested
587        /// from *within* the context of the runtime being dumped. Do not, for
588        /// example, await `Handle::dump()` on a different runtime.
589        ///
590        /// # Limitations
591        ///
592        /// ## Performance
593        ///
594        /// Although enabling the `taskdump` feature imposes virtually no
595        /// additional runtime overhead, actually calling `Handle::dump` is
596        /// expensive. The runtime must synchronize and pause its workers, then
597        /// re-poll every task in a special tracing mode. Avoid requesting dumps
598        /// often.
599        ///
600        /// ## Local Executors
601        ///
602        /// Tasks managed by local executors (e.g., `FuturesUnordered` and
603        /// [`LocalSet`][crate::task::LocalSet]) may not appear in task dumps.
604        ///
605        /// ## Non-Termination When Workers Are Blocked
606        ///
607        /// The future produced by `Handle::dump` may never produce `Ready` if
608        /// another runtime worker is blocked for more than 250ms. This may
609        /// occur if a dump is requested during shutdown, or if another runtime
610        /// worker is infinite looping or synchronously deadlocked. For these
611        /// reasons, task dumping should usually be paired with an explicit
612        /// [timeout][crate::time::timeout].
613        pub async fn dump(&self) -> crate::runtime::Dump {
614            match &self.inner {
615                scheduler::Handle::CurrentThread(handle) => handle.dump(),
616                #[cfg(all(feature = "rt-multi-thread", not(target_os = "wasi")))]
617                scheduler::Handle::MultiThread(handle) => {
618                    // perform the trace in a separate thread so that the
619                    // trace itself does not appear in the taskdump.
620                    let handle = handle.clone();
621                    spawn_thread(async {
622                        let handle = handle;
623                        handle.dump().await
624                    }).await
625                },
626            }
627        }
628
629        /// Produces `true` if the current task is being traced for a dump;
630        /// otherwise false. This function is only public for integration
631        /// testing purposes. Do not rely on it.
632        #[doc(hidden)]
633        pub fn is_tracing() -> bool {
634            super::task::trace::Context::is_tracing()
635        }
636    }
637
638    cfg_rt_multi_thread! {
639        /// Spawn a new thread and asynchronously await on its result.
640        async fn spawn_thread<F>(f: F) -> <F as Future>::Output
641        where
642            F: Future + Send + 'static,
643            <F as Future>::Output: Send + 'static
644        {
645            let (tx, rx) = crate::sync::oneshot::channel();
646            crate::loom::thread::spawn(|| {
647                let rt = crate::runtime::Builder::new_current_thread().build().unwrap();
648                rt.block_on(async {
649                    let _ = tx.send(f.await);
650                });
651            });
652            rx.await.unwrap()
653        }
654    }
655}
656
657/// Error returned by `try_current` when no Runtime has been started
658#[derive(Debug)]
659pub struct TryCurrentError {
660    kind: TryCurrentErrorKind,
661}
662
663impl TryCurrentError {
664    pub(crate) fn new_no_context() -> Self {
665        Self {
666            kind: TryCurrentErrorKind::NoContext,
667        }
668    }
669
670    pub(crate) fn new_thread_local_destroyed() -> Self {
671        Self {
672            kind: TryCurrentErrorKind::ThreadLocalDestroyed,
673        }
674    }
675
676    /// Returns true if the call failed because there is currently no runtime in
677    /// the Tokio context.
678    pub fn is_missing_context(&self) -> bool {
679        matches!(self.kind, TryCurrentErrorKind::NoContext)
680    }
681
682    /// Returns true if the call failed because the Tokio context thread-local
683    /// had been destroyed. This can usually only happen if in the destructor of
684    /// other thread-locals.
685    pub fn is_thread_local_destroyed(&self) -> bool {
686        matches!(self.kind, TryCurrentErrorKind::ThreadLocalDestroyed)
687    }
688}
689
690enum TryCurrentErrorKind {
691    NoContext,
692    ThreadLocalDestroyed,
693}
694
695impl fmt::Debug for TryCurrentErrorKind {
696    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
697        match self {
698            TryCurrentErrorKind::NoContext => f.write_str("NoContext"),
699            TryCurrentErrorKind::ThreadLocalDestroyed => f.write_str("ThreadLocalDestroyed"),
700        }
701    }
702}
703
704impl fmt::Display for TryCurrentError {
705    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
706        use TryCurrentErrorKind as E;
707        match self.kind {
708            E::NoContext => f.write_str(CONTEXT_MISSING_ERROR),
709            E::ThreadLocalDestroyed => f.write_str(THREAD_LOCAL_DESTROYED_ERROR),
710        }
711    }
712}
713
714impl error::Error for TryCurrentError {}