pub(crate) mod configure;
pub(crate) mod wiring;
use std::collections::HashSet;
use std::error::Error;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use crate::construct::ConstructError;
use crate::hooks::HookKind;
use crate::key::{BindingKind, KeyName};
use crate::module::{ModuleName, colliding_names};
use crate::redact::Redacted;
use crate::signal::Signal;
use crate::timer::BoxError;
use crate::type_name::{TypeName, short_type_name};
pub use configure::{ConfigureError, ConfigureErrors, PrepareError};
pub use wiring::WiringErrors;
#[non_exhaustive]
pub enum StartupError {
Wiring(WiringErrors),
Connect(ConnectError),
Configure(ConfigureErrors),
Bind { transport: TypeName, source: Redacted },
}
impl fmt::Display for StartupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StartupError::Wiring(e) => fmt::Display::fmt(e, f),
StartupError::Connect(e) => fmt::Display::fmt(e, f),
StartupError::Configure(e) => fmt::Display::fmt(e, f),
StartupError::Bind { transport, source } => {
write!(f, "transport `{transport}` failed to bind: {source}")
}
}
}
}
impl fmt::Debug for StartupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl Error for StartupError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
StartupError::Wiring(e) => e.source(),
StartupError::Connect(e) => e.source(),
StartupError::Configure(e) => e.source(),
StartupError::Bind { .. } => None,
}
}
}
impl From<WiringErrors> for StartupError {
fn from(e: WiringErrors) -> Self {
StartupError::Wiring(e)
}
}
impl From<ConnectError> for StartupError {
fn from(e: ConnectError) -> Self {
StartupError::Connect(e)
}
}
impl From<ConfigureErrors> for StartupError {
fn from(e: ConfigureErrors) -> Self {
StartupError::Configure(e)
}
}
#[non_exhaustive]
#[derive(Debug)]
pub struct RuntimeMissing {
pub transport: TypeName,
}
impl fmt::Display for RuntimeMissing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"transport `{}` is bound on an app with no `Runtime`; set one with `.runtime(..)`, which sets the app's timer too",
self.transport
)
}
}
impl Error for RuntimeMissing {}
#[non_exhaustive]
#[derive(Debug)]
pub enum ConnectError {
Construct { key: KeyName, module: ModuleName, reason: FailureReason },
Readiness { key: KeyName, attempts: u32, reason: FailureReason },
Hook { hook: HookKind, key: KeyName, reason: FailureReason },
}
impl fmt::Display for ConnectError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConnectError::Construct { key, module, reason } => {
write!(f, "failed to construct `{key}` in {module}: {reason}")
}
ConnectError::Readiness { key, attempts, reason } => {
let noun = if *attempts == 1 { "attempt" } else { "attempts" };
write!(f, "readiness check of `{key}` failed after {attempts} {noun}: {reason}")
}
ConnectError::Hook { hook, key, reason } => write!(f, "`{hook}` hook of `{key}` failed: {reason}"),
}
}
}
impl Error for ConnectError {}
#[non_exhaustive]
#[derive(Debug)]
pub enum FailureReason {
Panicked(Redacted),
TimedOut { after: Duration, limit: Limit },
Skipped,
Errored(Redacted),
}
impl fmt::Display for FailureReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FailureReason::Panicked(message) => write!(f, "panicked: {message}"),
FailureReason::TimedOut { after, limit } => {
let which = match limit {
Limit::Item => "its own bound",
Limit::Attempt => "the attempt bound",
Limit::Default => "the app default",
Limit::ShutdownCap => "`shutdown_timeout`",
};
write!(f, "timed out after {after:?} ({which})")
}
FailureReason::Skipped => f.write_str("skipped: `shutdown_timeout` had expired"),
FailureReason::Errored(error) => fmt::Display::fmt(error, f),
}
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Limit {
Item,
Attempt,
Default,
ShutdownCap,
}
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Shutdown {
pub signal: Signal,
pub abandoned: usize,
pub terminal_skipped: usize,
}
#[non_exhaustive]
#[derive(Clone)]
pub struct ShutdownError {
pub report: Shutdown,
pub failures: Arc<[ShutdownFailure]>,
}
impl fmt::Display for ShutdownError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let count = self.failures.len();
let noun = if count == 1 { "failure" } else { "failures" };
write!(f, "shutdown on `{}` finished with {count} {noun}", self.report.signal)?;
let full = TypeName::colliding(self.failures.iter().flat_map(ShutdownFailure::type_names));
for failure in self.failures.iter() {
write!(f, "\n ร {}", failure.text(&full))?;
}
let abandoned = self.report.abandoned;
if abandoned > 0 {
let noun = if abandoned == 1 { "execution" } else { "executions" };
write!(f, "\n {abandoned} {noun} abandoned at the drain's end")?;
}
let skipped = self.report.terminal_skipped;
if skipped > 0 {
let noun = if skipped == 1 { "terminal execution" } else { "terminal executions" };
write!(f, "\n {skipped} {noun} refused or abandoned")?;
}
Ok(())
}
}
impl fmt::Debug for ShutdownError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl Error for ShutdownError {}
#[non_exhaustive]
#[derive(Debug)]
pub enum ShutdownFailure {
Hook { hook: HookKind, key: KeyName, reason: FailureReason },
Close { transport: TypeName, reason: FailureReason },
}
impl ShutdownFailure {
fn type_names(&self) -> Vec<TypeName> {
match self {
ShutdownFailure::Hook { key, .. } => key.key().type_names().collect(),
ShutdownFailure::Close { transport, .. } => vec![*transport],
}
}
fn text(&self, full: &HashSet<TypeName>) -> String {
match self {
ShutdownFailure::Hook { hook, key, reason } => format!("`{hook}` hook of `{}`: {reason}", key.text_in(full)),
ShutdownFailure::Close { transport, reason } => {
format!("transport `{}` failed to close: {reason}", transport.written(full))
}
}
}
}
impl fmt::Display for ShutdownFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text(&TypeName::colliding(self.type_names())))
}
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Closed;
impl Closed {
pub(crate) const fn new() -> Self {
Closed
}
}
impl fmt::Display for Closed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the application is shutting down")
}
}
impl Error for Closed {}
#[non_exhaustive]
pub enum LoadError {
Closed(Closed),
Wiring(WiringErrors),
Connect(ConnectError),
Refused(LoadRefusal),
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LoadError::Closed(closed) => write!(f, "cannot load a module: {closed}"),
LoadError::Wiring(e) => fmt::Display::fmt(e, f),
LoadError::Connect(e) => fmt::Display::fmt(e, f),
LoadError::Refused(refusal) => fmt::Display::fmt(refusal, f),
}
}
}
impl fmt::Debug for LoadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl Error for LoadError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
LoadError::Closed(_) | LoadError::Refused(_) => None,
LoadError::Wiring(e) => e.source(),
LoadError::Connect(e) => e.source(),
}
}
}
#[non_exhaustive]
#[derive(Debug)]
pub enum LoadRefusal {
Controllers { module: ModuleName },
Middleware { module: ModuleName },
Contribution { module: ModuleName, key: KeyName },
GlobalExport { module: ModuleName, key: KeyName },
Input { module: ModuleName, key: KeyName },
}
impl fmt::Display for LoadRefusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LoadRefusal::Controllers { module } => {
write!(f, "cannot load {module}: it declares controllers, and routes are already bound")
}
LoadRefusal::Middleware { module } => write!(
f,
"cannot load {module}: it writes module metadata such as middleware, which transports read when they bind"
),
LoadRefusal::Contribution { module, key } => write!(
f,
"cannot load {module}: it contributes to `{key}`, a collection it does not introduce, which bindings already read"
),
LoadRefusal::GlobalExport { module, key } => {
write!(f, "cannot load {module}: it exports `{key}` globally, and global exports are fixed at wiring")
}
LoadRefusal::Input { module, key } => write!(
f,
"cannot load {module}: it declares the execution input `{key}`; inputs belong to transports, and the per-handler input check ran at wiring"
),
}
}
}
#[non_exhaustive]
#[derive(Debug)]
pub enum LookupError {
NotFound { key: KeyName, kind: LookupKind },
NotReady { key: KeyName },
WrongType { key: KeyName, requested: &'static str },
WrongKind { key: KeyName, expected: BindingKind, found: BindingKind },
ExecutionRequired { key: KeyName },
Ambiguous { key: KeyName, sources: Vec<ModuleName> },
AmbiguousModule { module: &'static str, candidates: Vec<ModuleName> },
Construct { key: KeyName, reason: FailureReason },
Closed { key: KeyName },
}
impl fmt::Display for LookupError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LookupError::NotFound { key, kind } => match kind {
LookupKind::Binding => write!(f, "no binding for `{key}` is visible from this module"),
LookupKind::Extension => write!(f, "the extension `{key}` was not written in this execution"),
LookupKind::Input => write!(f, "the execution input `{key}` was not seeded in this execution"),
LookupKind::Module => write!(f, "no module `{key}` is registered"),
},
LookupError::NotReady { key } => write!(f, "`{key}` is a singleton the connect walk has not built yet"),
LookupError::WrongType { key, requested } => {
write!(f, "`{key}` does not hold a `{}`", short_type_name(*requested))
}
LookupError::WrongKind { key, expected, found } => {
write!(f, "`{key}` is {}, read as {}", kind_text(*found), kind_text(*expected))
}
LookupError::ExecutionRequired { key } => write!(f, "`{key}` needs an execution, and none is open here"),
LookupError::Ambiguous { key, sources } => {
write!(f, "`{key}` is ambiguous between ")?;
write_list(f, sources)
}
LookupError::AmbiguousModule { module, candidates } => {
write!(f, "`{}` is ambiguous between ", short_type_name(*module))?;
write_list(f, candidates)
}
LookupError::Construct { key, reason } => write!(f, "building `{key}` inside the call failed: {reason}"),
LookupError::Closed { key } => {
write!(f, "`{key}` is a singleton, and the application has begun destroying its singletons")
}
}
}
}
impl Error for LookupError {}
fn write_list(f: &mut fmt::Formatter<'_>, names: &[ModuleName]) -> fmt::Result {
let colliding = colliding_names(names);
for (i, name) in names.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
if colliding.contains(name) {
write!(f, "{name:#}")?;
} else {
write!(f, "{name}")?;
}
}
Ok(())
}
fn kind_text(kind: BindingKind) -> &'static str {
match kind {
BindingKind::Single => "a single binding",
BindingKind::Collection => "a collection",
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LookupKind {
Binding,
Extension,
Input,
Module,
}
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
pub struct GuardRejected {
pub guard: &'static str,
}
impl GuardRejected {
pub(crate) fn new(guard: &'static str) -> Self {
GuardRejected { guard }
}
}
impl fmt::Display for GuardRejected {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "guard `{}` refused the call", self.guard)
}
}
impl Error for GuardRejected {}
#[non_exhaustive]
#[derive(Debug)]
pub struct PanicRecovered {
pub stage: DispatchStage,
pub message: Redacted,
}
impl PanicRecovered {
pub(crate) fn new(stage: DispatchStage, message: Redacted) -> Self {
PanicRecovered { stage, message }
}
}
impl fmt::Display for PanicRecovered {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "the {} panicked: {}", self.stage, self.message)
}
}
impl Error for PanicRecovered {}
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DispatchStage {
Guard,
Interceptor,
Handler,
ErrorHandler,
PreDispatch,
}
impl fmt::Display for DispatchStage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
DispatchStage::Guard => "guard",
DispatchStage::Interceptor => "interceptor",
DispatchStage::Handler => "handler",
DispatchStage::ErrorHandler => "error handler",
DispatchStage::PreDispatch => "pre-dispatch stage",
})
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EndStream;
impl fmt::Display for EndStream {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the stream ends here")
}
}
impl Error for EndStream {}
pub fn is_panic(error: &BoxError) -> bool {
panic_in(&**error, 0)
}
const MAX_DEPTH: usize = 32;
fn panic_in(error: &(dyn Error + 'static), depth: usize) -> bool {
if depth >= MAX_DEPTH {
return false;
}
match recognized(error, depth) {
Some(found) => found,
None => error.source().is_some_and(|cause| panic_in(cause, depth + 1)),
}
}
fn redacted_panicked(redacted: &Redacted, depth: usize) -> bool {
depth < MAX_DEPTH && recognized(redacted, depth).unwrap_or(false)
}
fn recognized<'e>(error: impl ByType<'e>, depth: usize) -> Option<bool> {
if error.get::<PanicRecovered>().is_some() {
return Some(true);
}
if let Some(lookup) = error.get::<LookupError>() {
return Some(lookup_panicked(lookup, depth));
}
if let Some(construct) = error.get::<ConstructError>() {
return Some(match construct {
ConstructError::Dependency(lookup) => lookup_panicked(lookup, depth),
ConstructError::Failed(inner) => panic_in(&**inner, depth + 1),
});
}
if let Some(connect) = error.get::<ConnectError>() {
return Some(connect_panicked(connect, depth));
}
if let Some(load) = error.get::<LoadError>() {
return Some(matches!(load, LoadError::Connect(connect) if connect_panicked(connect, depth)));
}
if let Some(startup) = error.get::<StartupError>() {
return Some(matches!(startup, StartupError::Connect(connect) if connect_panicked(connect, depth)));
}
if let Some(redacted) = error.get::<Redacted>() {
return Some(redacted_panicked(redacted, depth + 1));
}
None
}
fn lookup_panicked(error: &LookupError, depth: usize) -> bool {
match error {
LookupError::Construct { reason, .. } => reason_panicked(reason, depth),
_ => false,
}
}
fn connect_panicked(error: &ConnectError, depth: usize) -> bool {
match error {
ConnectError::Construct { reason, .. }
| ConnectError::Readiness { reason, .. }
| ConnectError::Hook { reason, .. } => reason_panicked(reason, depth),
}
}
fn reason_panicked(reason: &FailureReason, depth: usize) -> bool {
match reason {
FailureReason::Panicked(_) => true,
FailureReason::Errored(redacted) => redacted_panicked(redacted, depth + 1),
FailureReason::TimedOut { .. } | FailureReason::Skipped => false,
}
}
trait ByType<'e> {
fn get<E: Error + 'static>(&self) -> Option<&'e E>;
}
impl<'e> ByType<'e> for &'e (dyn Error + 'static) {
fn get<E: Error + 'static>(&self) -> Option<&'e E> {
let error: &'e (dyn Error + 'static) = *self;
error.downcast_ref::<E>()
}
}
impl<'e> ByType<'e> for &'e Redacted {
fn get<E: Error + 'static>(&self) -> Option<&'e E> {
let redacted: &'e Redacted = *self;
redacted.downcast_ref::<E>()
}
}