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, Handle, JoinHandle, Runtime, RuntimeFlavor,
31};
32pub use crate::tasks::tokio::{BroadcastStream, ReceiverStream};
33use std::future::Future;
34
35/// Build an explicitly sized async runtime. Runtime owners must destroy it
36/// outside an async executor thread.
37pub fn worker_runtime(name: &str, workers: usize) -> std::io::Result<Runtime> {
38    ::tokio::runtime::Builder::new_multi_thread()
39        .worker_threads(workers)
40        .thread_name(name)
41        .enable_all()
42        .build()
43}
44
45/// Build a single-thread control runtime, driven by its owning native thread.
46pub fn control_runtime() -> std::io::Result<Runtime> {
47    ::tokio::runtime::Builder::new_current_thread()
48        .enable_all()
49        .build()
50}
51
52/// Create a tokio runtime, initialize tracing, and block on the given future.
53pub fn run<F: Future>(future: F) -> F::Output {
54    init_tracing();
55
56    let rt = Runtime::new().unwrap();
57    rt.block_on(future)
58}
59
60/// Block on a future using the current tokio runtime handle.
61/// Panics if no tokio runtime is active.
62pub fn block_on<F: Future>(future: F) -> F::Output {
63    Handle::current().block_on(future)
64}
65
66pub use crate::tasks::tokio::ctrl_c;