Skip to main content

rust_supervisor/runtime/
supervisor.rs

1//! Runtime supervisor entry point.
2//!
3//! This module validates supervisor declarations, derives runtime options, and
4//! returns a [`crate::control::handle::SupervisorHandle`].
5
6use crate::control::handle::SupervisorHandle;
7use crate::error::types::SupervisorError;
8use crate::runtime::control_loop::{RuntimeControlState, run_control_loop};
9use crate::shutdown::stage::ShutdownPolicy;
10use crate::spec::supervisor::SupervisorSpec;
11use tokio::sync::{broadcast, mpsc};
12
13/// Supervisor runtime entry point.
14#[derive(Debug, Clone, Copy, Default)]
15pub struct Supervisor;
16
17impl Supervisor {
18    /// Starts a supervisor runtime from an owned specification value.
19    ///
20    /// # Arguments
21    ///
22    /// - `spec`: Supervisor specification owned by the caller.
23    ///
24    /// # Returns
25    ///
26    /// Returns a [`SupervisorHandle`] connected to the runtime control loop.
27    pub async fn start(spec: SupervisorSpec) -> Result<SupervisorHandle, SupervisorError> {
28        let shutdown_policy = shutdown_policy_from_spec(&spec);
29        Self::start_with_policy(spec, shutdown_policy).await
30    }
31
32    /// Starts a supervisor runtime with an explicit shutdown policy.
33    ///
34    /// # Arguments
35    ///
36    /// - `spec`: Supervisor specification owned by the caller.
37    /// - `shutdown_policy`: Policy used by the control loop.
38    ///
39    /// # Returns
40    ///
41    /// Returns a [`SupervisorHandle`] connected to the runtime control loop.
42    pub async fn start_with_policy(
43        spec: SupervisorSpec,
44        shutdown_policy: ShutdownPolicy,
45    ) -> Result<SupervisorHandle, SupervisorError> {
46        spec.validate()?;
47        let (command_sender, command_receiver) = mpsc::channel(spec.control_channel_capacity);
48        let (event_sender, _) = broadcast::channel(spec.event_channel_capacity);
49        let state = RuntimeControlState::new(spec, shutdown_policy, command_sender.clone())?;
50        tokio::spawn(run_control_loop(
51            state,
52            command_receiver,
53            event_sender.clone(),
54        ));
55        Ok(SupervisorHandle::new(command_sender, event_sender))
56    }
57}
58
59/// Builds the shutdown policy from supervisor defaults.
60///
61/// # Arguments
62///
63/// - `spec`: Supervisor declaration that owns default shutdown values.
64///
65/// # Returns
66///
67/// Returns a [`ShutdownPolicy`] for runtime shutdown coordination.
68fn shutdown_policy_from_spec(spec: &SupervisorSpec) -> ShutdownPolicy {
69    ShutdownPolicy::new(
70        spec.default_shutdown_policy.graceful_timeout,
71        spec.default_shutdown_policy.abort_wait,
72        true,
73    )
74}