use super::Child;
use crate::child::owned::teardown::Disposition;
use crate::child::refused_commit;
use crate::child::spawn::failed_after_teardown;
use crate::child::suspended::could_not_resume;
use crate::error::Error;
use crate::identity::ProcessId;
use crate::tokio::wait::{on_blocking_pool, Hop, Unjoined};
const RESUME: &str = "cosca::tokio::SuspendedChild::resume";
use crate::tokio::Command;
#[cfg(windows)]
#[path = "suspended/windows.rs"]
mod platform;
#[cfg(not(windows))]
#[path = "suspended/unsupported.rs"]
mod platform;
#[derive(Debug)]
pub struct SuspendedChild {
child: Child,
wanted_kill_on_drop: bool,
}
impl Command {
pub async fn spawn_suspended(&mut self) -> Result<SuspendedChild, Error> {
platform::spawn(self).await
}
}
impl SuspendedChild {
pub fn id(&self) -> Option<ProcessId> {
self.child.id()
}
pub fn pid(&self) -> u32 {
self.child.pid()
}
pub async fn resume(self) -> Result<Child, Error> {
let SuspendedChild {
mut child,
wanted_kill_on_drop,
} = self;
let behind_front = child.inner.front().is_some();
if let Err(e) = platform::release(&child) {
let torn_down =
on_blocking_pool(RESUME, move || child.inner.tear_down_or_hand_back(Disposition::Leave)).await;
return Err(Error::from(failed_after_teardown(
could_not_resume(e),
behind_front,
torn_down.map_err(dropped_instead),
)));
}
child.inner.kill_on_drop = wanted_kill_on_drop;
let Err(refusal) = child.inner.try_commit_kill_on_drop() else {
return Ok(child);
};
let torn_down = match Hop::enter(RESUME) {
Err(_) => Ok(child.inner.tear_down_refused_commit()),
Ok(hop) => {
child.inner.kill_on_drop = true;
hop.run(move || child.inner.tear_down_refused_commit())
.await
.map_err(dropped_instead)
}
};
Err(Error::from(refused_commit(refusal, behind_front, torn_down)))
}
}
fn dropped_instead(unjoined: Unjoined) -> Error {
match unjoined {
Unjoined::NotRun(e) => Error::Io(crate::error::io_context(
"the teardown did not run, and the child was dropped as its handle's drop does",
e.into_io(),
)),
Unjoined::Unknown(e) => e,
}
}
#[cfg(test)]
#[path = "suspended_tests.rs"]
mod suspended_tests;