Skip to main content

monocoque_core/rt/
compio.rs

1//! compio backend: native io_uring. Selected by `runtime-compio`.
2//!
3//! See [`super`](crate::rt) for the facade contract this implements.
4
5use std::future::Future;
6
7pub use compio::net::{TcpListener, TcpStream, ToSocketAddrsAsync as ToSocketAddrs};
8pub use compio::time::{sleep, timeout};
9
10/// Owned read half of a split TCP stream.
11pub type OwnedReadHalf = compio::net::OwnedReadHalf<TcpStream>;
12/// Owned write half of a split TCP stream.
13pub type OwnedWriteHalf = compio::net::OwnedWriteHalf<TcpStream>;
14
15#[cfg(unix)]
16pub use compio::net::{UnixListener, UnixStream};
17
18/// Handle to a spawned task. Kept alive keeps the task running; dropping it
19/// detaches under compio.
20pub type JoinHandle<T> = compio::runtime::Task<T>;
21
22/// Spawn a task on the current runtime and return its handle.
23#[inline]
24pub fn spawn<F>(fut: F) -> JoinHandle<F::Output>
25where
26    F: Future + 'static,
27{
28    compio::runtime::spawn(fut)
29}
30
31/// Spawn a task and let it run on its own, discarding the handle.
32#[inline]
33pub fn spawn_detached<F>(fut: F)
34where
35    F: Future + 'static,
36    F::Output: 'static,
37{
38    compio::runtime::spawn(fut).detach();
39}
40
41/// Run a blocking closure off the async executor and await its result.
42#[inline]
43pub async fn spawn_blocking<F, T>(f: F) -> T
44where
45    F: FnOnce() -> T + Send + Sync + 'static,
46    T: Send + 'static,
47{
48    compio::runtime::spawn_blocking(f).await
49}
50
51/// Await a spawned task and return its output.
52///
53/// Normalizes the difference between backends: compio's task awaits directly
54/// to the output, so this is just the await.
55#[inline]
56pub async fn join<T>(handle: JoinHandle<T>) -> T {
57    handle.await
58}
59
60/// A self-contained runtime owned by a single thread.
61///
62/// Used by worker threads that drive their own event loop independently of
63/// the caller's runtime (for example the publisher's fan-out workers).
64pub struct LocalRuntime {
65    inner: compio::runtime::Runtime,
66}
67
68impl LocalRuntime {
69    /// Build a new single-threaded runtime.
70    pub fn new() -> std::io::Result<Self> {
71        Ok(Self {
72            inner: compio::runtime::Runtime::new()?,
73        })
74    }
75
76    /// Run a future to completion on this runtime, blocking the thread.
77    pub fn block_on<F: Future>(&self, fut: F) -> F::Output {
78        self.inner.block_on(fut)
79    }
80}