Skip to main content

gatel_core/
runtime.rs

1//! Runtime abstraction layer for gatel.
2//!
3//! Provides a common interface over different async runtimes. The default
4//! implementation uses Tokio. When the `monoio` feature is enabled, a
5//! monoio-based implementation is available for Linux systems with io_uring
6//! support.
7//!
8//! # Architecture
9//!
10//! The abstraction is intentionally thin — it wraps the most commonly used
11//! runtime operations (spawning tasks, sleeping, TCP operations) behind
12//! feature-gated implementations. Business logic uses these wrappers
13//! instead of calling tokio/monoio directly, making it possible to switch
14//! runtimes at compile time.
15//!
16//! # Usage
17//!
18//! ```rust,ignore
19//! use gatel_core::runtime;
20//!
21//! // Spawn a background task
22//! runtime::spawn(async { /* ... */ });
23//!
24//! // Sleep
25//! runtime::sleep(Duration::from_secs(1)).await;
26//! ```
27
28use std::future::Future;
29use std::time::Duration;
30
31/// Spawn a new async task on the current runtime.
32///
33/// On tokio: delegates to `tokio::spawn`.
34/// On monoio: delegates to `monoio::spawn` (task is !Send, pinned to current thread).
35#[cfg(not(feature = "runtime-monoio"))]
36pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<F::Output>
37where
38    F: Future + Send + 'static,
39    F::Output: Send + 'static,
40{
41    tokio::spawn(future)
42}
43
44#[cfg(feature = "runtime-monoio")]
45pub fn spawn<F>(future: F)
46where
47    F: Future + 'static,
48    F::Output: 'static,
49{
50    monoio::spawn(future);
51}
52
53/// Sleep for the given duration.
54#[cfg(not(feature = "runtime-monoio"))]
55pub async fn sleep(duration: Duration) {
56    tokio::time::sleep(duration).await;
57}
58
59#[cfg(feature = "runtime-monoio")]
60pub async fn sleep(duration: Duration) {
61    monoio::time::sleep(duration).await;
62}
63
64/// Create a periodic interval timer.
65#[cfg(not(feature = "runtime-monoio"))]
66pub fn interval(period: Duration) -> tokio::time::Interval {
67    tokio::time::interval(period)
68}
69
70/// Runtime information and capabilities.
71pub struct RuntimeInfo {
72    /// Name of the active runtime.
73    pub name: &'static str,
74    /// Whether io_uring is available (Linux only).
75    pub io_uring: bool,
76    /// Whether tasks are Send (tokio=true, monoio=false).
77    pub send_tasks: bool,
78}
79
80/// Get information about the active runtime.
81pub fn info() -> RuntimeInfo {
82    #[cfg(not(feature = "runtime-monoio"))]
83    {
84        RuntimeInfo {
85            name: "tokio",
86            io_uring: false,
87            send_tasks: true,
88        }
89    }
90    #[cfg(feature = "runtime-monoio")]
91    {
92        RuntimeInfo {
93            name: "monoio",
94            io_uring: cfg!(target_os = "linux"),
95            send_tasks: false,
96        }
97    }
98}