servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! Runtime failures and accumulated shutdown outcomes.

use std::{fmt, io};

use crate::ConfigError;

/// A runtime operation's result. Application services retain their own errors.
pub type Result<T> = std::result::Result<T, Error>;

/// A failure observed while supervising or stopping one named component.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Failure {
    /// Registered worker/cleanup name or runtime component identifier.
    pub component: String,
    /// The observed failure, without a success-shaped shutdown result.
    pub kind: FailureKind,
}

/// Reasons a coordinated lifecycle could not finish successfully.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FailureKind {
    /// A required worker returned successfully before shutdown was requested.
    UnexpectedExit,
    /// Application work returned an error at the runtime boundary.
    Error(String),
    /// Invalid startup configuration, retaining its typed constraint.
    Configuration(ConfigError),
    /// Invalid application registration or a panicking configuration override.
    Registration(String),
    /// An I/O failure with its operation, kind, and original OS code.
    Io {
        /// Runtime operation that failed.
        operation: &'static str,
        /// Portable I/O classification.
        kind: io::ErrorKind,
        /// Original platform error code, when available.
        raw_os_error: Option<i32>,
        /// Original I/O diagnostic.
        message: String,
    },
    /// A supervised future or its factory panicked under unwinding.
    Panicked,
    /// Setup or a worker did not complete its startup gate within the shared budget.
    StartupTimeout,
    /// Work was still active at the drain deadline and was cancelled.
    DrainTimeout,
    /// Cancellation completion was not observed before the absolute deadline.
    CancellationIncomplete,
    /// Cleanup did not complete, or could not start, before the shared deadline.
    CleanupTimeout,
    /// Startup was cancelled before the application could admit traffic.
    StartupCancelled,
}

/// Startup, configuration, process, and lifecycle failures.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
    /// Configuration did not satisfy the runtime's constraints.
    Config(ConfigError),
    /// An empty or duplicate component name was registered.
    Registration(String),
    /// The embedded path requires an existing Tokio executor.
    NoRuntime,
    /// A planned facility was configured before it is implemented.
    Unsupported(&'static str),
    /// A runtime I/O operation failed; the first value identifies the operation.
    Io(&'static str, io::Error),
    /// Process telemetry configuration or subscriber ownership failed.
    Telemetry(&'static str),
    /// All observed lifecycle failures, including startup and cleanup failures.
    Lifecycle(Vec<Failure>),
}

impl fmt::Display for Error {
    fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Config(error) => error.fmt(out),
            Self::Registration(message) => out.write_str(message),
            Self::NoRuntime => out.write_str("App::start requires a Tokio runtime"),
            Self::Telemetry(message) => out.write_str(message),
            Self::Unsupported(feature) => write!(out, "not implemented: {feature}"),
            Self::Io(operation, error) => write!(out, "{operation}: {error}"),
            Self::Lifecycle(failures) => write!(out, "application lifecycle failed: {failures:?}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Config(error) => Some(error),
            Self::Io(_, error) => Some(error),
            _ => None,
        }
    }
}

impl From<ConfigError> for Error {
    fn from(error: ConfigError) -> Self {
        Self::Config(error)
    }
}

impl From<io::Error> for Error {
    fn from(error: io::Error) -> Self {
        Self::Io("application I/O", error)
    }
}

impl Error {
    pub(crate) fn into_failures(self, component: &str) -> Vec<Failure> {
        let kind = match self {
            Self::Lifecycle(failures) => return failures,
            Self::Config(error) => FailureKind::Configuration(error),
            Self::Registration(message) => FailureKind::Registration(message),
            Self::Io(operation, error) => FailureKind::Io {
                operation,
                kind: error.kind(),
                raw_os_error: error.raw_os_error(),
                message: error.to_string(),
            },
            error => FailureKind::Error(error.to_string()),
        };
        vec![Failure {
            component: component.into(),
            kind,
        }]
    }
}