use std::sync::Arc;
use crate::child::drop_teardown::Torn;
use crate::error::{ChildFate, Error, Failures};
use crate::Unreaped;
#[derive(Debug)]
pub(crate) enum SpawnFailure {
NotStarted(Error),
#[cfg_attr(
not(any(target_os = "linux", windows)),
allow(
dead_code,
reason = "only the Linux and Windows spawns hold a child they prove never ran"
)
)]
NotStartedWithChild {
cause: Error,
#[cfg_attr(
windows,
allow(dead_code, reason = "read by `map`, which no Windows spawn calls, and by tests")
)]
fate: ChildFate,
},
MayHaveStarted {
cause: Box<Error>,
fate: ChildFate,
wrapper_elevated: bool,
detail: Option<String>,
unreaped: Option<Box<Unreaped>>,
cleanup: Option<Failures>,
},
}
impl SpawnFailure {
pub(crate) fn started(cause: Error, fate: ChildFate, unreaped: Option<Unreaped>) -> SpawnFailure {
SpawnFailure::MayHaveStarted {
cause: Box::new(cause),
fate,
wrapper_elevated: false,
detail: None,
unreaped: unreaped.map(Box::new),
cleanup: None,
}
}
pub(crate) fn with_detail(self, detail: Option<String>) -> SpawnFailure {
let Some(detail) = detail else {
return self;
};
match self {
SpawnFailure::MayHaveStarted {
cause,
fate,
wrapper_elevated,
detail: earlier,
unreaped,
cleanup,
} => {
debug_assert!(
earlier.is_none(),
"a failure's detail is set once: {earlier:?}, then {detail:?}"
);
SpawnFailure::MayHaveStarted {
cause,
fate,
wrapper_elevated,
detail: Some(detail),
unreaped,
cleanup,
}
}
other => {
debug_assert!(
false,
"a spawn that did not start has no detail of its child: {other:?}"
);
other
}
}
}
pub(crate) fn with_cleanup(self, cleanup: Option<Failures>) -> SpawnFailure {
let Some(cleanup) = cleanup else {
return self;
};
match self {
SpawnFailure::MayHaveStarted {
cause,
fate,
wrapper_elevated,
detail,
unreaped,
cleanup: earlier,
} => SpawnFailure::MayHaveStarted {
cause,
fate,
wrapper_elevated,
detail,
unreaped,
cleanup: Failures::merged(earlier, Some(cleanup)),
},
other => {
debug_assert!(false, "a spawn that did not start has no cleanup: {other:?}");
other
}
}
}
#[cfg(any(test, unix))]
pub(crate) fn map(self, f: impl FnOnce(Error) -> Error) -> SpawnFailure {
match self {
SpawnFailure::NotStarted(e) => SpawnFailure::NotStarted(f(e)),
SpawnFailure::NotStartedWithChild { cause, fate } => {
SpawnFailure::NotStartedWithChild { cause: f(cause), fate }
}
SpawnFailure::MayHaveStarted {
cause,
fate,
wrapper_elevated,
detail,
unreaped,
cleanup,
} => SpawnFailure::MayHaveStarted {
cause: Box::new(f(*cause)),
fate,
wrapper_elevated,
detail,
unreaped,
cleanup,
},
}
}
pub(crate) fn behind_front(self) -> SpawnFailure {
match self {
SpawnFailure::MayHaveStarted {
cause,
fate,
detail,
unreaped,
cleanup,
..
} => SpawnFailure::MayHaveStarted {
cause,
fate,
wrapper_elevated: true,
detail,
unreaped,
cleanup,
},
not_started => not_started,
}
}
}
pub(crate) fn after_the_spawn(cause: Error, torn: Torn, behind_front: bool) -> Error {
Error::from(failed_after_the_spawn(cause, torn, behind_front))
}
pub(crate) fn failed_after_the_spawn(cause: Error, torn: Torn, behind_front: bool) -> SpawnFailure {
let Torn {
fate,
unreaped,
cleanup,
} = torn;
let failure = SpawnFailure::started(cause, fate, unreaped).with_cleanup(cleanup);
if behind_front {
failure.behind_front()
} else {
failure
}
}
pub(crate) fn failed_after_teardown(cause: Error, behind_front: bool, torn_down: Result<Torn, Error>) -> SpawnFailure {
let torn = torn_down.unwrap_or_else(|cancelled| Torn {
fate: ChildFate::Unknown,
unreaped: None,
cleanup: Failures::collect([Arc::new(cancelled)]),
});
failed_after_the_spawn(cause, torn, behind_front)
}
pub(crate) fn failed_attach(
not_started: bool,
cause: Error,
detail: Option<String>,
attach_cleanup: Option<Failures>,
torn: Torn,
) -> SpawnFailure {
let Torn {
fate,
unreaped,
cleanup,
} = torn;
if not_started {
debug_assert!(
unreaped.is_none() && detail.is_none() && attach_cleanup.is_none() && cleanup.is_none(),
"a child that never ran has nothing to hand back, detail or clean up after the attach, and \
its teardown's failures were said in the spawn's warn"
);
return SpawnFailure::NotStartedWithChild { cause, fate };
}
SpawnFailure::started(cause, fate, unreaped)
.with_detail(detail)
.with_cleanup(attach_cleanup)
.with_cleanup(cleanup)
}
#[cfg(all(test, unix))]
impl SpawnFailure {
#[track_caller]
pub(crate) fn expect_may_have_started_with(self) -> (Error, ChildFate) {
let (cause, fate, unreaped) = self.parts();
if let Some(unreaped) = unreaped {
unreaped.leak();
panic!("the spawn handed a child back ({fate:?}): {cause:?}");
}
(cause, fate)
}
#[track_caller]
pub(crate) fn parts(self) -> (Error, ChildFate, Option<Unreaped>) {
match self {
SpawnFailure::MayHaveStarted {
cause, fate, unreaped, ..
} => (*cause, fate, unreaped.map(|unreaped| *unreaped)),
SpawnFailure::NotStarted(e) => panic!("expected `may have started`, got `not started`: {e:?}"),
SpawnFailure::NotStartedWithChild { cause, .. } => {
panic!("expected `may have started`, got `not started`: {cause:?}")
}
}
}
#[cfg(target_os = "linux")]
#[track_caller]
pub(crate) fn expect_not_started_with_child(self) -> (Error, ChildFate) {
match self {
SpawnFailure::NotStartedWithChild { cause, fate } => (cause, fate),
other => panic!("expected `not started` with a child's fate, got {other:?}"),
}
}
#[cfg_attr(
not(target_os = "linux"),
allow(dead_code, reason = "only the Linux spawn's tests take a not-started failure apart")
)]
#[track_caller]
pub(crate) fn expect_not_started(self) -> Error {
match self {
SpawnFailure::NotStarted(e) => e,
SpawnFailure::NotStartedWithChild { cause, .. } => cause,
SpawnFailure::MayHaveStarted { cause, fate, .. } => {
panic!("expected `not started`, got `may have started` ({fate:?}): {cause:?}")
}
}
}
}
#[cfg(test)]
#[track_caller]
pub(crate) fn expect_may_have_started_with(error: Error) -> (Error, ChildFate) {
let (cause, fate, unreaped) = error_parts(error);
if let Some(unreaped) = unreaped {
unreaped.leak();
panic!("the spawn handed a child back ({fate:?}): {cause:?}");
}
(cause, fate)
}
#[cfg(test)]
#[track_caller]
pub(crate) fn error_parts(error: Error) -> (Error, ChildFate, Option<Unreaped>) {
match error {
Error::MayHaveStarted {
fate, source, unreaped, ..
} => (
std::sync::Arc::try_unwrap(source).expect("a spawn's cause has one owner"),
fate,
unreaped.map(|unreaped| *unreaped),
),
other => panic!("expected Error::MayHaveStarted, got {other:?}"),
}
}
#[cfg(all(test, windows))]
pub(crate) fn unsupported(error: &Error) -> bool {
matches!(error, Error::Unsupported { .. })
}
#[cfg(all(test, windows))]
pub(crate) fn invalid_input(error: &Error) -> bool {
matches!(error, Error::Io(e) if e.kind() == std::io::ErrorKind::InvalidInput)
}
#[cfg(test)]
#[track_caller]
pub(crate) fn expect_not_started(error: Error) -> Error {
assert!(
!matches!(error, Error::MayHaveStarted { .. }),
"expected an error that says the program did not start, got {error:?}"
);
error
}
impl From<SpawnFailure> for Error {
fn from(failure: SpawnFailure) -> Error {
match failure {
SpawnFailure::NotStarted(error) => {
debug_assert!(
!matches!(error, Error::MayHaveStarted { .. }),
"a spawn answered both `not started` and `may have started`: {}",
crate::error::Report(&error)
);
error
}
SpawnFailure::NotStartedWithChild { cause: error, .. } => {
debug_assert!(
!matches!(error, Error::MayHaveStarted { .. }),
"a spawn answered both `not started` and `may have started`: {}",
crate::error::Report(&error)
);
error
}
SpawnFailure::MayHaveStarted {
cause,
fate,
wrapper_elevated,
detail,
unreaped,
cleanup,
} => {
debug_assert!(
!matches!(*cause, Error::MayHaveStarted { .. }),
"a `may have started` failure's cause is itself `may have started`: {}",
crate::error::Report(&*cause)
);
debug_assert!(
unreaped.as_ref().is_none_or(|child| match fate {
ChildFate::Running { id } => id == child.id(),
ChildFate::Unknown | ChildFate::Killed => true,
_ => false,
}),
"a child handed back is `Running` with its identity, `Unknown` or `Killed`, got {fate:?}"
);
Error::MayHaveStarted {
fate,
wrapper_elevated,
detail,
source: std::sync::Arc::new(*cause),
unreaped,
cleanup,
}
}
}
}
}
pub(crate) trait PlainError: Into<Error> + sealed::Sealed {}
impl PlainError for Error {}
impl PlainError for std::io::Error {}
mod sealed {
pub trait Sealed {}
impl Sealed for crate::error::Error {}
impl Sealed for std::io::Error {}
}
pub(crate) trait Classify<T> {
fn not_started(self) -> Result<T, SpawnFailure>;
}
impl<T, E: PlainError> Classify<T> for Result<T, E> {
fn not_started(self) -> Result<T, SpawnFailure> {
self.map_err(|e| SpawnFailure::NotStarted(e.into()))
}
}
#[cfg(test)]
pub(crate) mod seams {
use std::cell::Cell;
use std::thread::LocalKey;
use crate::error::Error;
thread_local! {
static WAIT: Cell<bool> = const { Cell::new(false) };
static PUMP: Cell<bool> = const { Cell::new(false) };
}
pub(crate) const FAILURE: &str = "forced failure after the spawn (test seam)";
#[must_use = "the seam is cleared as soon as the guard is dropped"]
pub(crate) struct Armed(&'static LocalKey<Cell<bool>>);
impl Drop for Armed {
fn drop(&mut self) {
self.0.with(|f| f.set(false));
}
}
fn arm(flag: &'static LocalKey<Cell<bool>>) -> Armed {
flag.with(|f| f.set(true));
Armed(flag)
}
pub(crate) fn fail_the_next_wait() -> Armed {
arm(&WAIT)
}
pub(crate) fn fail_the_next_pump() -> Armed {
arm(&PUMP)
}
fn take(flag: &'static LocalKey<Cell<bool>>) -> Option<Error> {
flag.with(|f| f.replace(false))
.then(|| Error::Io(std::io::Error::other(FAILURE)))
}
pub(crate) fn take_wait_failure() -> Option<Error> {
take(&WAIT)
}
pub(crate) fn take_pump_failure() -> Option<Error> {
take(&PUMP)
}
}
#[cfg(test)]
#[path = "failure_tests.rs"]
mod failure_tests;