servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Ownership, observation, and cancellation of a started application.

use std::{net::SocketAddr, sync::Arc};

use tokio::task::JoinHandle;

use crate::{Error, Failure, FailureKind, Result};

use super::{Phase, Shared};

/// Read-only lifecycle information, available even before startup completes.
#[derive(Clone)]
pub struct LifecycleStatus {
    pub(crate) shared: Arc<Shared>,
}

impl LifecycleStatus {
    /// The coordinator's current phase.
    pub fn phase(&self) -> Phase {
        self.shared.phase()
    }

    /// Whether startup completed, cached readiness checks pass, and admission is open.
    pub fn is_ready(&self) -> bool {
        self.shared.ready()
    }

    /// Wait for coordinator completion.
    pub async fn stopped(&self) {
        self.shared.stopped().await;
    }
}

/// A cloneable request/observation handle; it does not own application lifetime.
#[derive(Clone)]
pub struct AppHandle {
    pub(crate) shared: Arc<Shared>,
    pub(crate) address: Option<SocketAddr>,
}

impl AppHandle {
    /// Obtain lifecycle information that can be shared without shutdown authority.
    pub fn status(&self) -> LifecycleStatus {
        LifecycleStatus {
            shared: self.shared.clone(),
        }
    }

    /// Close admission and request cooperative shutdown, idempotently.
    pub fn shutdown(&self) {
        self.shared.request_shutdown();
    }

    /// Current coordinator phase; readiness is withdrawn at shutdown request time.
    pub fn phase(&self) -> Phase {
        self.shared.phase()
    }

    /// Whether startup completed, all cached checks pass, and shutdown is absent.
    pub fn is_ready(&self) -> bool {
        self.shared.ready()
    }

    /// Bound HTTP address, or `None` for a worker-only application.
    pub fn local_addr(&self) -> Option<SocketAddr> {
        self.address
    }

    /// Bound administrative address, including an OS-assigned ephemeral port.
    pub fn admin_addr(&self) -> Option<SocketAddr> {
        *self
            .shared
            .admin_address
            .lock()
            .unwrap_or_else(|error| error.into_inner())
    }

    /// Observe coordinator completion; use `Running::wait` to obtain its result.
    pub async fn stopped(&self) {
        self.shared.stopped().await;
    }
}

/// Owns an application. Dropping it requests shutdown but does not await cleanup.
///
/// Cancelling `wait` also requests shutdown. The coordinator continues while its
/// Tokio runtime remains alive; only awaiting completion confirms its outcome.
#[must_use = "await wait() to observe shutdown and cleanup completion"]
pub struct Running {
    pub(crate) handle: AppHandle,
    pub(crate) coordinator: Option<JoinHandle<Result<()>>>,
}

impl Running {
    /// Clone the application's observation and shutdown-request handle.
    pub fn handle(&self) -> AppHandle {
        self.handle.clone()
    }

    /// Bound HTTP address, or `None` for a worker-only application.
    pub fn local_addr(&self) -> Option<SocketAddr> {
        self.handle.local_addr()
    }

    /// Wait for the final result, including worker, drain, and cleanup failures.
    pub async fn wait(mut self) -> Result<()> {
        let Some(coordinator) = self.coordinator.take() else {
            return Ok(());
        };
        coordinator.await.map_err(|_| {
            Error::Lifecycle(vec![Failure {
                component: "coordinator".into(),
                kind: FailureKind::Panicked,
            }])
        })?
    }
}

impl Drop for Running {
    fn drop(&mut self) {
        if self.handle.phase() != Phase::Stopped {
            self.handle.shutdown();
        }
    }
}