hyperlane-plugin-shutdown 23.3.2

A graceful shutdown coordinator plugin for the Hyperlane framework providing OS signal arming (SIGINT/SIGTERM), lock-free in-flight request draining, bounded drain timeouts, LIFO async shutdown callbacks, and ServerControlHook integration.
Documentation
use super::*;

/// Default construction for [`ShutdownConfig`].
impl Default for ShutdownConfig {
    /// Constructs a default [`ShutdownConfig`] with 30 s drain timeout and `SIGINT`/`SIGTERM` enabled.
    fn default() -> Self {
        Self {
            drain_timeout_ms: DEFAULT_SHUTDOWN_DRAIN_TIMEOUT_MS,
            callback_timeout_ms: DEFAULT_SHUTDOWN_CALLBACK_TIMEOUT_MS,
            handle_sigint: true,
            handle_sigterm: true,
        }
    }
}

/// Inherent builders for [`ShutdownConfig`].
impl ShutdownConfig {
    /// Sets the maximum in-flight drain timeout in milliseconds.
    ///
    /// # Arguments
    ///
    /// - `u64` - Drain timeout in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: u64) -> Self {
        self.set_drain_timeout_ms(drain_timeout_ms);
        self
    }

    /// Sets the maximum timeout for each [`ShutdownCallback`] in milliseconds.
    ///
    /// # Arguments
    ///
    /// - `u64` - Per-callback timeout in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_callback_timeout_ms(mut self, callback_timeout_ms: u64) -> Self {
        self.set_callback_timeout_ms(callback_timeout_ms);
        self
    }
}

/// Drop implementation for [`ShutdownGuard`].
impl Drop for ShutdownGuard {
    /// Decrements the owning shard's lock-free in-flight counter and wakes drain waiters upon reaching zero.
    #[inline]
    fn drop(&mut self) {
        let Self { shard } = self;
        let prev: usize = shard.state.fetch_sub(1, Ordering::Release);
        if prev == (SHUTDOWN_BIT | 1) {
            fence(Ordering::SeqCst);
            shard.core.drained_notify.notify_waiters();
        }
    }
}

/// Default construction for [`ShutdownCoordinator`].
impl Default for ShutdownCoordinator {
    /// Constructs a default [`ShutdownCoordinator`].
    fn default() -> Self {
        Self::new(ShutdownConfig::default())
    }
}

/// Inherent implementation of [`ShutdownCoordinator`].
impl ShutdownCoordinator {
    /// Creates a new [`ShutdownCoordinator`] governed by `config`.
    ///
    /// # Arguments
    ///
    /// - `ShutdownConfig` - Drain timeout and signal handling settings.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready shutdown coordinator.
    pub fn new(config: ShutdownConfig) -> Self {
        let core: Arc<ShutdownCore> = Arc::new(ShutdownCore {
            config,
            triggered: AtomicBool::new(false),
            shards_armed: AtomicBool::new(false),
            shutdown_notify: Notify::new(),
            drained_notify: Notify::new(),
            callbacks: Vec::new(),
        });
        let shards: Box<[Arc<ShutdownShard>; SHUTDOWN_SHARD_COUNT]> =
            Box::new(from_fn(|_: usize| {
                Arc::new(ShutdownShard {
                    state: AtomicUsize::new(0),
                    core: Arc::clone(&core),
                })
            }));
        Self {
            inner: Arc::new(ShutdownCoordinatorInner { core, shards }),
        }
    }

    /// Registers an async [`ShutdownCallback`] executed in LIFO order during shutdown.
    ///
    /// # Arguments
    ///
    /// - `C` - Concrete [`ShutdownCallback`] implementation.
    ///
    /// # Returns
    ///
    /// - `Self` - New coordinator handle including the registered callback.
    pub fn with_callback<C>(self, callback: C) -> Self
    where
        C: ShutdownCallback,
    {
        let in_flight_count: usize = self.in_flight();
        let Self { inner } = self;
        let mut callbacks: Vec<Arc<dyn ShutdownCallback>> = inner.core.callbacks.clone();
        callbacks.push(Arc::new(callback));
        let already_triggered: bool = inner.core.triggered.load(Ordering::Acquire);
        let core: Arc<ShutdownCore> = Arc::new(ShutdownCore {
            config: inner.core.config.clone(),
            triggered: AtomicBool::new(already_triggered),
            shards_armed: AtomicBool::new(already_triggered),
            shutdown_notify: Notify::new(),
            drained_notify: Notify::new(),
            callbacks,
        });
        let base_bits: usize = if already_triggered { SHUTDOWN_BIT } else { 0 };
        let shards: Box<[Arc<ShutdownShard>; SHUTDOWN_SHARD_COUNT]> =
            Box::new(from_fn(|idx: usize| {
                let initial: usize = if idx == 0 {
                    base_bits | in_flight_count
                } else {
                    base_bits
                };
                Arc::new(ShutdownShard {
                    state: AtomicUsize::new(initial),
                    core: Arc::clone(&core),
                })
            }));
        Self {
            inner: Arc::new(ShutdownCoordinatorInner { core, shards }),
        }
    }

    /// Returns the active [`ShutdownConfig`].
    ///
    /// # Returns
    ///
    /// - `&ShutdownConfig` - Active configuration.
    #[inline]
    pub fn get_config(&self) -> &ShutdownConfig {
        let Self { inner } = self;
        &inner.core.config
    }

    /// Reports whether shutdown has been triggered.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` once shutdown has started.
    #[inline]
    pub fn is_shutting_down(&self) -> bool {
        let Self { inner } = self;
        inner.core.shards_armed.load(Ordering::Acquire)
    }

    /// Returns the current number of active [`ShutdownGuard`] instances across all shards.
    ///
    /// # Returns
    ///
    /// - `usize` - In-flight guard count.
    #[inline]
    pub fn in_flight(&self) -> usize {
        let Self { inner } = self;
        let mut total: usize = 0;
        for shard in inner.shards.iter() {
            total = total.saturating_add(shard.state.load(Ordering::Acquire) & IN_FLIGHT_MASK);
        }
        total
    }

    /// Acquires a lock-free RAII [`ShutdownGuard`] on the caller's thread-affine shard if shutdown has not yet started.
    ///
    /// # Returns
    ///
    /// - `Option<ShutdownGuard>` - Active guard, or `None` once shutdown has been triggered.
    #[inline]
    pub fn enter(&self) -> Option<ShutdownGuard> {
        let Self { inner } = self;
        let shard: &Arc<ShutdownShard> = &inner.shards[shutdown_shard_index()];
        if (shard.state.load(Ordering::Relaxed) & SHUTDOWN_BIT) != 0 {
            return None;
        }
        let prev: usize = shard.state.fetch_add(1, Ordering::Acquire);
        if (prev & SHUTDOWN_BIT) != 0 {
            let undo: usize = shard.state.fetch_sub(1, Ordering::Release);
            if undo == (SHUTDOWN_BIT | 1) {
                fence(Ordering::SeqCst);
                shard.core.drained_notify.notify_waiters();
            }
            return None;
        }
        Some(ShutdownGuard {
            shard: Arc::clone(shard),
        })
    }

    /// Triggers shutdown immediately across all shards and wakes all tasks awaiting [`ShutdownCoordinator::wait_triggered`].
    pub fn trigger(&self) {
        let Self { inner } = self;
        if inner.core.shards_armed.load(Ordering::Acquire) {
            return;
        }
        let mut total_in_flight: usize = 0;
        for shard in inner.shards.iter() {
            let prev: usize = shard.state.fetch_or(SHUTDOWN_BIT, Ordering::AcqRel);
            total_in_flight = total_in_flight.saturating_add(prev & IN_FLIGHT_MASK);
        }
        inner.core.shards_armed.store(true, Ordering::Release);
        if !inner.core.triggered.swap(true, Ordering::AcqRel) {
            inner.core.shutdown_notify.notify_waiters();
        }
        if total_in_flight == 0 {
            inner.core.drained_notify.notify_waiters();
        }
    }

    /// Waits asynchronously until [`ShutdownCoordinator::trigger`] is invoked.
    pub async fn wait_triggered(&self) {
        let Self { inner } = self;
        if inner.core.triggered.load(Ordering::Acquire) {
            return;
        }
        let mut notified: Pin<&mut Notified<'_>> = pin!(inner.core.shutdown_notify.notified());
        notified.as_mut().enable();
        if inner.core.triggered.load(Ordering::Acquire) {
            return;
        }
        notified.await;
    }

    /// Executes full graceful drain, runs registered callbacks in LIFO order, and optionally stops `control`.
    ///
    /// # Arguments
    ///
    /// - `Option<ServerControlHook>` - Optional Hyperlane server control hook to shut down cleanly.
    ///
    /// # Returns
    ///
    /// - `ShutdownReport` - Detailed drain and callback outcome summary.
    pub async fn execute_shutdown(&self, control: Option<ServerControlHook>) -> ShutdownReport {
        let Self { inner } = self;
        let started: Instant = Instant::now();
        self.trigger();
        let drain_budget: Duration =
            Duration::from_millis(inner.core.config.get_drain_timeout_ms());
        let drained_cleanly: bool = if self.in_flight() == 0 {
            true
        } else {
            timeout(drain_budget, async {
                loop {
                    let mut notified: Pin<&mut Notified<'_>> =
                        pin!(inner.core.drained_notify.notified());
                    notified.as_mut().enable();
                    fence(Ordering::SeqCst);
                    if self.in_flight() == 0 {
                        break;
                    }
                    notified.await;
                }
            })
            .await
            .is_ok()
        };
        let remaining_in_flight: usize = self.in_flight();
        let cb_budget: Duration =
            Duration::from_millis(inner.core.config.get_callback_timeout_ms().max(1));
        let mut completed_callbacks: Vec<String> = Vec::with_capacity(inner.core.callbacks.len());
        let mut timed_out_callbacks: Vec<String> = Vec::new();
        for callback in inner.core.callbacks.iter().rev() {
            let name: String = callback.name().to_owned();
            if timeout(cb_budget, callback.on_shutdown()).await.is_ok() {
                completed_callbacks.push(name);
            } else {
                timed_out_callbacks.push(name);
            }
        }
        if let Some(hook) = control {
            hook.shutdown().await;
        }
        ShutdownReport {
            drained_cleanly,
            remaining_in_flight,
            completed_callbacks,
            timed_out_callbacks,
            elapsed_ms: started.elapsed().as_millis() as u64,
        }
    }

    /// Arms a background Tokio task waiting for OS signals or manual [`ShutdownCoordinator::trigger`] to stop `control`.
    ///
    /// # Arguments
    ///
    /// - `ServerControlHook` - Hyperlane server control hook returned by `Server::run`.
    ///
    /// # Returns
    ///
    /// - `JoinHandle<ShutdownReport>` - Join handle resolving to the [`ShutdownReport`] once shutdown completes.
    pub fn arm_signals(&self, control: ServerControlHook) -> JoinHandle<ShutdownReport> {
        let coordinator: Self = self.clone();
        spawn(async move {
            let handle_sigint: bool = coordinator.get_config().get_handle_sigint();
            let handle_sigterm: bool = coordinator.get_config().get_handle_sigterm();
            select! {
                _ = coordinator.wait_triggered() => {}
                _ = async {
                    if handle_sigint {
                        let _: io::Result<()> = ctrl_c().await;
                    } else {
                        pending::<()>().await;
                    }
                } => {}
                _ = wait_sigterm(handle_sigterm) => {}
            }
            coordinator.execute_shutdown(Some(control)).await
        })
    }
}

/// Inherent implementation of [`ShutdownPlugin`].
impl ShutdownPlugin {
    /// Initializes the global [`ShutdownPlugin`] once with `coordinator`.
    ///
    /// # Arguments
    ///
    /// - `ShutdownCoordinator` - Configured graceful shutdown coordinator.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the initialized global plugin.
    pub fn init(coordinator: ShutdownCoordinator) -> &'static Self {
        SHUTDOWN_PLUGIN.get_or_init(|| Self { coordinator })
    }

    /// Returns the initialized global [`ShutdownPlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    pub fn get() -> Option<&'static Self> {
        SHUTDOWN_PLUGIN.get()
    }

    /// Returns the shared [`ShutdownCoordinator`].
    ///
    /// # Returns
    ///
    /// - `&ShutdownCoordinator` - Active shutdown coordinator.
    pub fn get_coordinator(&self) -> &ShutdownCoordinator {
        &self.coordinator
    }
}