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::{PanicMessage, Redacted};
use crate::signal::Signal;
use crate::timer::BoxError;
use crate::type_name::{TypeName, short_type_name};
pub use configure::{ConfigureError, ConfigureErrors, PrepareEntry, 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 struct PreparePanicked {
pub message: Redacted,
}
impl fmt::Display for PreparePanicked {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "`prepare` panicked: {}", self.message)
}
}
impl Error for PreparePanicked {}
#[non_exhaustive]
#[derive(Debug)]
pub enum ConnectError {
Construct { key: KeyName, module: ModuleName, reason: FailureReason },
Readiness { key: KeyName, module: ModuleName, 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, module, attempts, reason } => {
let noun = if *attempts == 1 { "attempt" } else { "attempts" };
write!(f, "readiness check of `{key}` in {module} 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 },
Dropped,
Serve { transport: TypeName, end: ServeEnd },
}
#[non_exhaustive]
#[derive(Debug)]
pub enum ServeEnd {
Errored(Redacted),
Panicked(Redacted),
Returned,
}
impl ShutdownFailure {
fn type_names(&self) -> Vec<TypeName> {
match self {
ShutdownFailure::Hook { key, .. } => key.key().type_names().collect(),
ShutdownFailure::Close { transport, .. } => vec![*transport],
ShutdownFailure::Dropped => Vec::new(),
ShutdownFailure::Serve { 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))
}
ShutdownFailure::Dropped => "the app was dropped before its shutdown closed its servers: they were released \
without their `close`, and no shutdown hook runs after the drop"
.to_owned(),
ShutdownFailure::Serve { transport, end: ServeEnd::Errored(reason) } => {
format!("transport `{}` failed while serving: {reason}", transport.written(full))
}
ShutdownFailure::Serve { transport, end: ServeEnd::Panicked(message) } => {
format!("transport `{}` panicked while serving: {message}", transport.written(full))
}
ShutdownFailure::Serve { transport, end: ServeEnd::Returned } => {
format!("transport `{}` stopped serving while the app was running", 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 },
ExecutionEnded { 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::ExecutionEnded { key } => write!(f, "`{key}` was read through an execution that has ended"),
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 {}
#[non_exhaustive]
pub struct Permanent(BoxError);
impl Permanent {
pub fn new(error: impl Into<BoxError>) -> Permanent {
Permanent(error.into())
}
}
impl fmt::Debug for Permanent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Permanent").field(&self.0).finish()
}
}
impl fmt::Display for Permanent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl Error for Permanent {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&*self.0)
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct UndeclaredRead {
reader: TypeName,
read: UndeclaredWhat,
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum UndeclaredWhat {
Key(KeyName),
Extension(TypeName),
Execution,
}
impl UndeclaredRead {
pub(crate) fn new(reader: TypeName, read: UndeclaredWhat) -> Self {
UndeclaredRead { reader, read }
}
pub fn reader(&self) -> TypeName {
self.reader
}
pub fn key(&self) -> Option<KeyName> {
match self.read {
UndeclaredWhat::Key(key) => Some(key),
_ => None,
}
}
pub fn extension(&self) -> Option<TypeName> {
match self.read {
UndeclaredWhat::Extension(ext) => Some(ext),
_ => None,
}
}
}
impl fmt::Display for UndeclaredRead {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let reader = self.reader;
match self.read {
UndeclaredWhat::Key(key) => write!(
f,
"`{reader}` reads `{key}` in `construct` but its `dependencies` does not declare it; \
add it there (`d.field::<..>(..)` or `d.param::<..>(..)`) so wiring can check it, \
or read it through a `ModuleRef` after construction"
),
UndeclaredWhat::Extension(ext) => write!(
f,
"`{reader}` reads the execution extension `{ext}` in `construct` but its `dependencies` does not declare it; \
add `d.field::<Ext<{ext}>>(..)` so wiring knows it needs an execution"
),
UndeclaredWhat::Execution => write!(
f,
"`{reader}` reads the execution in `construct` but its `dependencies` does not declare it; \
add `d.field::<ExecutionRef>(..)` so wiring knows it needs an execution"
),
}
}
}
impl Error for UndeclaredRead {}
pub fn is_permanent(error: &StartupError) -> bool {
startup_permanent(error, 0)
}
fn startup_permanent(error: &StartupError, depth: usize) -> bool {
match error {
StartupError::Wiring(_) => true,
StartupError::Connect(connect) => connect_permanent(connect, depth),
StartupError::Configure(errors) => errors.iter().any(|e| redacted_permanent(&e.source, depth + 1)),
StartupError::Bind { source, .. } => {
source.downcast_ref::<RuntimeMissing>().is_some() || redacted_permanent(source, depth + 1)
}
}
}
pub(crate) fn construct_permanent(error: &ConstructError) -> bool {
match error {
ConstructError::Failed(inner) => permanent_in(&**inner, 1),
ConstructError::Dependency(lookup) => lookup_permanent(lookup, 1),
}
}
fn permanent_in(error: &(dyn Error + 'static), depth: usize) -> bool {
if depth >= MAX_DEPTH {
return false;
}
if error.downcast_ref::<Permanent>().is_some() {
return true;
}
if let Some(redacted) = error.downcast_ref::<Redacted>() {
return redacted_permanent(redacted, depth + 1);
}
if let Some(found) = recognized_permanent(error, depth) {
return found;
}
error.source().is_some_and(|cause| permanent_in(cause, depth + 1))
}
fn redacted_permanent(redacted: &Redacted, depth: usize) -> bool {
depth < MAX_DEPTH && permanent_in(redacted.original(), depth)
}
fn recognized_permanent(error: &(dyn Error + 'static), depth: usize) -> Option<bool> {
if let Some(lookup) = error.downcast_ref::<LookupError>() {
return Some(lookup_permanent(lookup, depth));
}
if let Some(construct) = error.downcast_ref::<ConstructError>() {
return Some(match construct {
ConstructError::Dependency(lookup) => lookup_permanent(lookup, depth),
ConstructError::Failed(inner) => permanent_in(&**inner, depth + 1),
});
}
if let Some(connect) = error.downcast_ref::<ConnectError>() {
return Some(connect_permanent(connect, depth));
}
if let Some(load) = error.downcast_ref::<LoadError>() {
return Some(matches!(load, LoadError::Connect(connect) if connect_permanent(connect, depth)));
}
if let Some(startup) = error.downcast_ref::<StartupError>() {
return Some(startup_permanent(startup, depth));
}
if error.downcast_ref::<PrepareError>().is_some_and(PrepareError::is_permanent) {
return Some(true);
}
None
}
fn lookup_permanent(error: &LookupError, depth: usize) -> bool {
match error {
LookupError::Construct { reason, .. } => reason_permanent(reason, depth),
_ => false,
}
}
fn connect_permanent(error: &ConnectError, depth: usize) -> bool {
match error {
ConnectError::Construct { reason, .. }
| ConnectError::Readiness { reason, .. }
| ConnectError::Hook { reason, .. } => reason_permanent(reason, depth),
}
}
fn reason_permanent(reason: &FailureReason, depth: usize) -> bool {
match reason {
FailureReason::Errored(redacted) => redacted_permanent(redacted, depth + 1),
FailureReason::Panicked(_) | FailureReason::TimedOut { .. } | FailureReason::Skipped => false,
}
}
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() || error.get::<PreparePanicked>().is_some() || error.get::<PanicMessage>().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(match startup {
StartupError::Connect(connect) => connect_panicked(connect, depth),
StartupError::Configure(errors) => configure_panicked(errors, depth),
StartupError::Wiring(_) | StartupError::Bind { .. } => false,
});
}
if let Some(errors) = error.get::<ConfigureErrors>() {
return Some(configure_panicked(errors, depth));
}
if let Some(redacted) = error.get::<Redacted>() {
return Some(redacted_panicked(redacted, depth + 1));
}
if let Some(shutdown) = error.get::<ShutdownError>() {
return Some(shutdown.failures.iter().any(|failure| shutdown_failure_panicked(failure, depth)));
}
None
}
fn shutdown_failure_panicked(failure: &ShutdownFailure, depth: usize) -> bool {
match failure {
ShutdownFailure::Hook { reason, .. } | ShutdownFailure::Close { reason, .. } => reason_panicked(reason, depth),
ShutdownFailure::Serve { end, .. } => match end {
ServeEnd::Panicked(_) => true,
ServeEnd::Errored(redacted) => redacted_panicked(redacted, depth + 1),
ServeEnd::Returned => false,
},
ShutdownFailure::Dropped => false,
}
}
fn configure_panicked(errors: &ConfigureErrors, depth: usize) -> bool {
errors.iter().any(|entry| redacted_panicked(&entry.source, depth + 1))
}
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>()
}
}
#[cfg(test)]
mod shutdown_panics {
use super::*;
fn errored_with_a_panic() -> Redacted {
let panic = PanicRecovered { stage: DispatchStage::Handler, message: Redacted::from_parts(Box::new(fmt::Error), "boom".into()) };
Redacted::from_parts(Box::new(panic), "wrapped".into())
}
fn holds_a_panic(failure: ShutdownFailure) -> bool {
let error = ShutdownError {
report: Shutdown { signal: Signal::new("test"), abandoned: 0, terminal_skipped: 0 },
failures: Arc::from(vec![failure]),
};
crate::is_panic(&(Box::new(error) as BoxError))
}
#[test]
fn a_serve_end_and_a_close_whose_error_holds_a_panic_answer_alike() {
let close = ShutdownFailure::Close { transport: TypeName::of::<()>(), reason: FailureReason::Errored(errored_with_a_panic()) };
let serve = ShutdownFailure::Serve { transport: TypeName::of::<()>(), end: ServeEnd::Errored(errored_with_a_panic()) };
assert_eq!((holds_a_panic(close), holds_a_panic(serve)), (true, true));
}
}
#[cfg(test)]
mod task_panics {
use super::*;
use crate::redact::{SecretRegistry, redact_panic};
#[derive(Debug)]
struct Kept(Redacted);
impl fmt::Display for Kept {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("the connect ended")
}
}
impl Error for Kept {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&self.0)
}
}
#[test]
fn a_task_s_panic_kept_as_a_source_is_a_panic() {
let panicked = redact_panic(&SecretRegistry::default(), Box::new("boom"));
let errored = Redacted::from_parts(Box::new(fmt::Error), "boom".into());
let held = |redacted| crate::is_panic(&(Box::new(Kept(redacted)) as BoxError));
assert_eq!((held(panicked), held(errored)), (true, false));
}
}