rama_core/rt/
executor.rs

1use crate::graceful::ShutdownGuard;
2use tracing::instrument::Instrument;
3
4/// Future executor that utilises `tokio` threads.
5#[derive(Default, Debug, Clone)]
6pub struct Executor {
7    guard: Option<ShutdownGuard>,
8}
9
10impl Executor {
11    /// Create a new [`Executor`].
12    pub const fn new() -> Self {
13        Self { guard: None }
14    }
15
16    /// Create a new [`Executor`] with the given shutdown guard,
17    ///
18    /// This will spawn tasks that are awaited gracefully
19    /// in case the shutdown guard is triggered.
20    pub fn graceful(guard: ShutdownGuard) -> Self {
21        Self { guard: Some(guard) }
22    }
23
24    /// Spawn a future on the current executor,
25    /// this is spawned gracefully in case a shutdown guard has been registered.
26    pub fn spawn_task<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
27    where
28        F: Future<Output: Send + 'static> + Send + 'static,
29    {
30        match &self.guard {
31            Some(guard) => guard.spawn_task(future.in_current_span()),
32            None => tokio::spawn(future.in_current_span()),
33        }
34    }
35
36    /// Get a reference to the shutdown guard,
37    /// if and only if the executor was created with [`Self::graceful`].
38    pub fn guard(&self) -> Option<&ShutdownGuard> {
39        self.guard.as_ref()
40    }
41}