servlet 1.1.0

A small application runtime with an explicit operational contract
Documentation
//! Admission closes atomically with the first shutdown request.

use std::sync::Arc;

use tokio::{sync::watch, time::Instant};
use tokio_util::sync::CancellationToken;

/// The coordinator's current lifecycle stage.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
    /// Listeners, typed state, and required workers are initializing; admission is closed.
    Starting,
    /// All startup gates passed and application traffic may be admitted.
    Running,
    /// Admission is closed and shutdown has been requested.
    Quiescing,
    /// Accepted work is being allowed to finish.
    Draining,
    /// Reverse-order cleanup is running within the remaining budget.
    Cleaning,
    /// The coordinator finished; await `Running::wait` for its outcome.
    Stopped,
}

#[derive(Clone, Copy)]
struct Status {
    phase: Phase,
    requested_at: Option<Instant>,
    admitting: bool,
}

pub(crate) struct Shared {
    pub name: String,
    status: watch::Sender<Status>,
    pub shutdown: CancellationToken,
    pub metrics: Arc<crate::telemetry::Metrics>,
    pub app_metrics: crate::metrics::Registry,
    pub health: crate::health::Health,
    pub admin_address: std::sync::Mutex<Option<std::net::SocketAddr>>,
}

impl Shared {
    #[cfg(test)]
    pub(crate) fn new(name: String) -> Arc<Self> {
        Self::with_metrics(name, crate::metrics::Registry::owned())
    }

    pub(crate) fn with_metrics(name: String, app_metrics: crate::metrics::Registry) -> Arc<Self> {
        let (status, _) = watch::channel(Status {
            phase: Phase::Starting,
            requested_at: None,
            admitting: false,
        });
        Arc::new(Self {
            name,
            app_metrics,
            status,
            shutdown: CancellationToken::new(),
            metrics: Arc::new(crate::telemetry::Metrics::new()),
            health: crate::health::Health::new(),
            admin_address: std::sync::Mutex::new(None),
        })
    }

    pub(crate) fn request_shutdown(&self) {
        self.status.send_modify(|status| {
            status.admitting = false;
            if status.requested_at.is_none() {
                status.requested_at = Some(Instant::now());
            }
        });
        self.shutdown.cancel();
    }

    pub(crate) fn begin_running(&self) -> bool {
        self.status.send_if_modified(|status| {
            if status.requested_at.is_some() {
                return false;
            }
            status.phase = Phase::Running;
            status.admitting = true;
            true
        })
    }

    pub(crate) fn phase(&self) -> Phase {
        self.status.borrow().phase
    }

    pub(crate) fn ready(&self) -> bool {
        self.admitting() && self.health.ready()
    }

    pub(crate) fn admitting(&self) -> bool {
        self.status.borrow().admitting
    }

    pub(crate) fn transition(&self, phase: Phase) {
        tracing::info!(phase = ?phase, "lifecycle transition");
        self.status.send_modify(|status| status.phase = phase);
    }

    pub(crate) fn requested_at(&self) -> Option<Instant> {
        self.status.borrow().requested_at
    }

    pub(crate) async fn stopped(&self) {
        let mut receiver = self.status.subscribe();
        let _ = receiver
            .wait_for(|status| status.phase == Phase::Stopped)
            .await;
    }
}

pub(super) struct CompletionGuard(pub Arc<Shared>);

impl Drop for CompletionGuard {
    fn drop(&mut self) {
        self.0.app_metrics.seal();
        self.0.request_shutdown();
        self.0.transition(Phase::Stopped);
    }
}