Skip to main content

saluki_core/runtime/
supervisable.rs

1//! The contract that a supervised process implements.
2//!
3//! A supervisor drives a [`Supervisable`]. The [`Supervisable`] names the process, tells how to shut it down, and
4//! builds the future of the process each time the process starts. This module also contains the types in its signature.
5
6use std::{future::Future, pin::Pin, time::Duration};
7
8use async_trait::async_trait;
9use saluki_common::sync::shutdown::ShutdownHandle;
10use saluki_error::GenericError;
11use snafu::Snafu;
12
13/// A `Future` that represents the execution of a supervised process.
14pub type SupervisorFuture = Pin<Box<dyn Future<Output = Result<(), GenericError>> + Send>>;
15
16/// Initialization errors.
17///
18/// Initialization errors are distinct from runtime errors: they indicate that a process couldn't be started at all
19/// (for example, failed to bind a port, missing configuration). These errors don't trigger restart logic; instead, they
20/// immediately propagate up and fail the supervisor.
21#[derive(Debug, Snafu)]
22#[snafu(context(suffix(false)))]
23pub enum InitializationError {
24    /// The process couldn't be initialized due to an error.
25    // The alternate format includes the full cause chain, such as the OS error behind a failed bind.
26    #[snafu(display("Process failed to initialize: {:#}", source))]
27    Failed {
28        /// The underlying error that caused initialization to fail.
29        source: GenericError,
30    },
31}
32
33impl From<GenericError> for InitializationError {
34    fn from(source: GenericError) -> Self {
35        Self::Failed { source }
36    }
37}
38
39/// Strategy for shutting down a process.
40#[derive(Clone, Copy, Debug)]
41pub enum ShutdownStrategy {
42    /// Signals the process, then halts it if it hasn't exited within the given duration.
43    ///
44    /// The duration also covers the children in the process's [scope][crate::runtime::scope], which are halted along
45    /// with it. A halt is reported as an unclean shutdown.
46    Graceful(Duration),
47
48    /// Halts the process and everything it owns immediately, without signalling it.
49    ///
50    /// For work with no terminal condition. Not reported as an unclean shutdown.
51    Brutal,
52}
53
54/// A supervisable process.
55#[async_trait]
56pub trait Supervisable: Send + Sync {
57    /// Returns the name of the process.
58    fn name(&self) -> &str;
59
60    /// Returns the shutdown strategy for the process.
61    fn shutdown_strategy(&self) -> ShutdownStrategy {
62        ShutdownStrategy::Graceful(Duration::from_secs(5))
63    }
64
65    /// Returns whether this process observes the shutdown signal it is given.
66    ///
67    /// The shutdown of a subtree is a _trigger_, not an enforcement. Many workers ignore the signal completely, and
68    /// stop only when they reach their own terminal condition, such as when an input channel closes. If this function
69    /// returns `false`, the supervisor gives the process a [`ShutdownHandle::noop`] instead. But the
70    /// [scope][crate::runtime::scope] of the process still observes the signal for the process, so that it can tell
71    /// whether an exit of one of its children was requested.
72    ///
73    /// It also decides whether a nested supervisor in that scope that
74    /// [stops with its owner][crate::runtime::NestedSupervisorBuilder::stops_with_owner] is told to stop together with
75    /// the process. If this function returns `false`, the nested supervisor stops only when the scope closes.
76    ///
77    /// This says nothing about _whether_ the supervisor waits for the process -- that's
78    /// [`shutdown_strategy`][Self::shutdown_strategy]. A process that ignores the signal is still waited for, up to its
79    /// shutdown timeout.
80    ///
81    /// Defaults to `true`.
82    fn wants_shutdown_signal(&self) -> bool {
83        true
84    }
85
86    /// Returns whether the process can be started again after it has started once.
87    ///
88    /// [`initialize`][Self::initialize] builds the future of the process each time the process starts. Most processes
89    /// can build it again, so their owner can restart them. A process that consumes something when it starts cannot
90    /// build its future a second time. Examples are a connection, or a value that the process received before it ran.
91    /// Such a process returns `false` here.
92    ///
93    /// The owner of a process that returns `false` never restarts it, whatever restart policy the process has. When the
94    /// process stops, its owner reaps it, or fails if it needs the process. See the
95    /// [runtime documentation][crate::runtime#restart-policy] for how this decides the restart policy.
96    ///
97    /// Defaults to `true`.
98    fn can_restart(&self) -> bool {
99        true
100    }
101
102    /// Initializes the process asynchronously.
103    ///
104    /// During initialization, any resources or configuration for the process can be created asynchronously, and the
105    /// same runtime that's used for running the process is used for initialization. The resulting future is expected to
106    /// complete as soon as reasonably possible after `shutdown` resolves.
107    ///
108    /// **Important:** The `process_shutdown` signal must be moved into the returned [`SupervisorFuture`] so the worker
109    /// can respond to supervisor-initiated shutdown. If `process_shutdown` is dropped during initialization, the worker
110    /// will be unable to shut down gracefully and will be halted after the shutdown timeout.
111    ///
112    /// # Errors
113    ///
114    /// If the process can't be initialized, an error is returned.
115    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError>;
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    /// The smallest possible implementation, existing only to be erased below.
123    struct Noop;
124
125    #[async_trait]
126    impl Supervisable for Noop {
127        fn name(&self) -> &str {
128            "noop"
129        }
130
131        async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
132            Ok(Box::pin(async move {
133                process_shutdown.await;
134                Ok(())
135            }))
136        }
137    }
138
139    #[test]
140    fn trait_is_object_safe() {
141        // Producers hand their background work over as `Vec<Box<dyn Supervisable>>`, so object safety is load-bearing
142        // here rather than incidental: a default method taking `self` by value, or a generic one, would break every
143        // one of those call sites.
144        let worker: Box<dyn Supervisable> = Box::new(Noop);
145
146        assert_eq!(worker.name(), "noop");
147        assert!(worker.wants_shutdown_signal());
148        assert!(worker.can_restart());
149        assert!(matches!(
150            worker.shutdown_strategy(),
151            ShutdownStrategy::Graceful(timeout) if timeout == Duration::from_secs(5)
152        ));
153    }
154}