ulo 0.1.0-alpha.3

Fast and modular web framework for scalable applications
Documentation
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::panic::Location;

use crate::redact::{Redacted, SecretRegistry, redact, redact_as};
use crate::timer::BoxError;
use crate::type_name::TypeName;

/// Every failure the servers' `prepare` calls reported, one entry per failure, collected across
/// every server before any of them binds (transports DESIGN ยง2.7, X6). `StartupError::Configure`
/// carries it, as `StartupError::Wiring` carries `WiringErrors`.
///
/// A server's `prepare` answers one error listing its own failures; the core stores it as one
/// entry, redacted. `Display` writes every entry, and `Debug` writes the same text, so `main`
/// returning `Box<dyn Error>` prints the report.
///
/// The report applies the wiring report's naming rule across every server: each entry's
/// transport and the types a [`PrepareError`] names enter one check, and two different types
/// printing alike anywhere in the report, `a::User` from one transport and `b::User` from
/// another, or two transports whose markers share a last segment, print with their full paths in
/// every entry. Each entry's text, `source` and transport included, is written against the whole
/// report's names when the report is built, before it is redacted.
pub struct ConfigureErrors {
    errors: Vec<ConfigureError>,
}

/// One server's configuration failure: route-table construction, a duplicate route, TLS loading,
/// CORS validation, endpoint parsing, an inherited socket that does not exist, or a backend limit.
/// `Display` writes the entry as its report does.
#[non_exhaustive]
#[derive(Debug)]
pub struct ConfigureError {
    /// The transport's marker type, as `StartupError::Bind` names it.
    pub transport: TypeName,
    pub source: Redacted,
    /// Whether the report writes `transport` with its full path, which `Display` follows.
    transport_full: bool,
}

impl ConfigureErrors {
    /// The report of every `prepare` that failed, as `(transport, error)`. The transports and
    /// the names of every [`PrepareError`] enter one check, and each `PrepareError` and transport
    /// is written against it; any other error keeps its own text.
    pub(crate) fn collect(refused: Vec<(TypeName, BoxError)>, secrets: &SecretRegistry) -> Self {
        let named = refused.iter().filter_map(|(_, error)| error.downcast_ref::<PrepareError>());
        let transports = refused.iter().map(|(transport, _)| *transport);
        let full = TypeName::colliding(transports.chain(named.flat_map(|error| error.names.iter().copied())));
        let errors = refused
            .into_iter()
            .map(|(transport, error)| {
                let text = error.downcast_ref::<PrepareError>().map(|prepared| prepared.text(&full));
                let source = match text {
                    Some(text) => redact_as(secrets, error, text),
                    None => redact(secrets, error),
                };
                ConfigureError { transport, source, transport_full: full.contains(&transport) }
            })
            .collect();
        ConfigureErrors { errors }
    }

    pub fn iter(&self) -> std::slice::Iter<'_, ConfigureError> {
        self.errors.iter()
    }

    pub fn len(&self) -> usize {
        self.errors.len()
    }

    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }
}

impl<'a> IntoIterator for &'a ConfigureErrors {
    type Item = &'a ConfigureError;
    type IntoIter = std::slice::Iter<'a, ConfigureError>;

    fn into_iter(self) -> Self::IntoIter {
        self.errors.iter()
    }
}

impl fmt::Display for ConfigureErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let count = self.errors.len();
        let noun = if count == 1 { "error" } else { "errors" };
        write!(f, "error: configuration failed with {count} {noun}")?;
        for error in &self.errors {
            write!(f, "\n\n  ร— {error}")?;
        }
        Ok(())
    }
}

impl fmt::Debug for ConfigureErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl Error for ConfigureErrors {}

impl fmt::Display for ConfigureError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.transport_full {
            write!(f, "transport `{:#}`: {}", self.transport, self.source)
        } else {
            write!(f, "transport `{}`: {}", self.transport, self.source)
        }
    }
}

impl Error for ConfigureError {}

/// A `prepare` error whose text names types: what a server answers, boxed, so the startup report
/// decides how each name prints. The report runs [`TypeName::colliding`] over the names of every
/// server's `PrepareError` and every failing transport, and calls `text` with the result, so a
/// type that prints alike with a different type another server names, or with a transport, is
/// written with its full path.
///
/// `text` writes each name in `names` with `{:#}` when the set it receives holds it, and with
/// `{}` otherwise. `Display` on a `PrepareError` alone collides its own names.
///
/// ```
/// use ulo::{PrepareError, TypeName};
///
/// struct User;
/// let user = TypeName::of::<User>();
/// let error = PrepareError::new([user], move |full| {
///     let user = if full.contains(&user) { format!("{user:#}") } else { user.to_string() };
///     format!("`{user}` is read and nothing supplies it")
/// });
/// assert_eq!(error.to_string(), "`User` is read and nothing supplies it");
/// ```
pub struct PrepareError {
    names: Vec<TypeName>,
    entries: Vec<PrepareEntry>,
    text: Box<dyn Fn(&HashSet<TypeName>) -> String + Send + Sync>,
    permanent: bool,
}

/// One failure a [`PrepareError`] lists, as data a test or a tool reads without parsing the
/// report's text: the types it names, the source line that declared what failed, what failed, and
/// the route scopes involved, and, for what was refused as something that would never run, why.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PrepareEntry {
    names: Vec<TypeName>,
    location: Option<&'static Location<'static>>,
    subject: Option<String>,
    scopes: Vec<String>,
    reason: Option<Unreached>,
}

/// Why `prepare` refused something it was given as something that would never run, as
/// [`PrepareEntry::reason`] reads it. `Display` writes the clause the refusal's text ends with,
/// so the text follows from the reason.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Unreached {
    /// The scope matches no path a route of the table matches, once the entry's exclusions are
    /// taken out.
    NoRoute,
    /// The only service the server answers whose paths the scope matches is `service`, a health
    /// service, which runs no scoped entry (transports DESIGN ยง6.2). The transport names the
    /// service.
    HealthOnly { service: &'static str },
    /// A scoped entry names no route pattern.
    EmptyScope,
    /// A message handler is mounted on a gateway that reads every message raw, which no handler
    /// receives.
    RawGateway,
    /// A route, a scope, an exclusion or an upgrade path has a static segment holding a `\`, raw
    /// or as `%5C`, and a request path holding one is refused before routing, so it can never
    /// match.
    BackslashSegment,
}

impl fmt::Display for Unreached {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Unreached::NoRoute => f.write_str("matches no route's path"),
            Unreached::HealthOnly { service } => write!(
                f,
                "matches only `{service}`'s paths among those the server answers, and that health service runs no \
                 scoped entry, so the entry would never run"
            ),
            Unreached::EmptyScope => f.write_str("names no route pattern, so it covers no route"),
            Unreached::RawGateway => f.write_str("reads every message raw, so the handler would never run"),
            Unreached::BackslashSegment => {
                f.write_str("holds a `\\`, raw or as `%5C`, and a request path holding one is refused with 400 before routing")
            }
        }
    }
}

impl PrepareEntry {
    /// An entry naming `names` and nothing else; [`at`](Self::at), [`about`](Self::about),
    /// [`scoped`](Self::scoped) and [`because`](Self::because) add the rest.
    pub fn new(names: impl IntoIterator<Item = TypeName>) -> Self {
        PrepareEntry { names: names.into_iter().collect(), ..PrepareEntry::default() }
    }

    /// The source line that declared what failed.
    pub fn at(mut self, location: &'static Location<'static>) -> Self {
        self.location = Some(location);
        self
    }

    /// What failed, such as `"pre-dispatch entry"`.
    pub fn about(mut self, subject: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self
    }

    /// The route scopes the failure concerns, as written.
    pub fn scoped(mut self, scopes: impl IntoIterator<Item = String>) -> Self {
        self.scopes = scopes.into_iter().collect();
        self
    }

    /// Why what failed would never run: a scope in [`scopes`](Self::scopes) its entry would never
    /// run for, a scoped entry with no scope, a handler its gateway never calls, or a route, scope,
    /// exclusion or upgrade path no request reaching it can match.
    pub fn because(mut self, reason: Unreached) -> Self {
        self.reason = Some(reason);
        self
    }

    /// The types the failure names.
    pub fn names(&self) -> &[TypeName] {
        &self.names
    }

    pub fn location(&self) -> Option<&'static Location<'static>> {
        self.location
    }

    pub fn subject(&self) -> Option<&str> {
        self.subject.as_deref()
    }

    pub fn scopes(&self) -> &[String] {
        &self.scopes
    }

    pub fn reason(&self) -> Option<Unreached> {
        self.reason
    }
}

impl PrepareError {
    pub fn new(
        names: impl IntoIterator<Item = TypeName>,
        text: impl Fn(&HashSet<TypeName>) -> String + Send + Sync + 'static,
    ) -> Self {
        PrepareError { names: names.into_iter().collect(), entries: Vec::new(), text: Box::new(text), permanent: false }
    }

    /// Marks the failure as one retrying the start cannot mend, which
    /// [`is_permanent`](crate::is_permanent) reads: a server whose `prepare` found a
    /// [`Permanent`](crate::Permanent) error in a component it asked, a link's, answers one.
    pub fn with_permanent(mut self, permanent: bool) -> Self {
        self.permanent = permanent;
        self
    }

    /// Whether a failure it lists is one retrying the start cannot mend.
    pub fn is_permanent(&self) -> bool {
        self.permanent
    }

    /// Sets the failures [`entries`](Self::entries) lists, in the order found, each as data.
    pub fn with_entries(mut self, entries: Vec<PrepareEntry>) -> Self {
        self.entries = entries;
        self
    }

    pub fn names(&self) -> &[TypeName] {
        &self.names
    }

    /// The failures this error lists, one per failure the server found; empty for an error built
    /// by [`new`](Self::new) alone.
    pub fn entries(&self) -> &[PrepareEntry] {
        &self.entries
    }

    /// The text, each name in `full` written with its full path.
    pub fn text(&self, full: &HashSet<TypeName>) -> String {
        (self.text)(full)
    }
}

impl fmt::Display for PrepareError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.text(&TypeName::colliding(self.names.iter().copied())))
    }
}

impl fmt::Debug for PrepareError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl Error for PrepareError {}