Skip to main content

spawned_rt/tasks/
mod.rs

1//! Runtime wrapper to remove dependencies from code. Using this library will
2//! allow to set a tokio runtime or any other runtime, once implemented just by
3//! changing the enabled feature.
4//! May implement the `deterministic` version based on comonware.xyz's runtime:
5//! <https://github.com/commonwarexyz/monorepo/blob/main/runtime/src/deterministic.rs>
6//!
7//! Currently, only a very limited set of tokio functionality is reexported. We may want to
8//! extend this functionality as needed.
9
10mod tokio;
11
12#[cfg(feature = "backend-experiments")]
13mod dispatch_gate;
14
15#[cfg(feature = "backend-experiments")]
16#[doc(hidden)]
17pub mod experimental;
18
19use crate::tracing::init_tracing;
20
21pub mod affinity;
22
23pub use crate::tasks::tokio::mpsc;
24pub use crate::tasks::tokio::oneshot;
25pub use crate::tasks::tokio::sleep;
26pub use crate::tasks::tokio::timeout;
27pub use crate::tasks::tokio::watch;
28pub use crate::tasks::tokio::CancellationToken;
29pub use crate::tasks::tokio::{
30    block_in_place, spawn, spawn_blocking, task_id, unconstrained, Handle, JoinHandle, Runtime,
31    RuntimeFlavor,
32};
33pub use crate::tasks::tokio::{BroadcastStream, ReceiverStream};
34use std::future::Future;
35
36/// Build an explicitly sized async runtime. Runtime owners must destroy it
37/// outside an async executor thread.
38pub fn worker_runtime(name: &str, workers: usize) -> std::io::Result<Runtime> {
39    ::tokio::runtime::Builder::new_multi_thread()
40        .worker_threads(workers)
41        .thread_name(name)
42        .enable_all()
43        .build()
44}
45
46/// Build a single-thread control runtime, driven by its owning native thread.
47pub fn control_runtime() -> std::io::Result<Runtime> {
48    ::tokio::runtime::Builder::new_current_thread()
49        .enable_all()
50        .build()
51}
52
53/// Create a tokio runtime, initialize tracing, and block on the given future.
54pub fn run<F: Future>(future: F) -> F::Output {
55    init_tracing();
56
57    let rt = Runtime::new().unwrap();
58    rt.block_on(future)
59}
60
61/// Block on a future using the current tokio runtime handle.
62/// Panics if no tokio runtime is active.
63pub fn block_on<F: Future>(future: F) -> F::Output {
64    Handle::current().block_on(future)
65}
66
67pub use crate::tasks::tokio::ctrl_c;