use std::time::{Duration, Instant};
use backon::{BackoffBuilder as _, ExponentialBackoff, ExponentialBuilder};
use super::{Exit, ExitWait, OsProcess, WaitFor};
use crate::error::Error;
use crate::wait::remaining;
fn enter() -> Result<(), Error> {
#[cfg(test)]
if crate::wait::fault::take_force_watch_error() {
return Err(crate::wait::fault::forced_watch_error());
}
Ok(())
}
pub(crate) fn exited_held(p: &dyn OsProcess, timeout: Option<Duration>) -> Result<bool, Error> {
exited_until(p, absolute(timeout))
}
pub(crate) fn exited_until(p: &dyn OsProcess, deadline: Option<Instant>) -> Result<bool, Error> {
enter()?;
let mut wait = exit_wait(p, remaining(deadline))?;
Ok(matches!(run(&mut *wait, deadline)?, RunOutcome::Done(())))
}
pub(crate) fn exit_wait(p: &dyn OsProcess, left: Option<Duration>) -> Result<ExitWait<'_>, Error> {
if left == Some(Duration::ZERO) {
return Ok(Box::new(ProcessExit(p)));
}
p.exit_wait()
}
pub(crate) fn absolute(timeout: Option<Duration>) -> Option<Instant> {
timeout.and_then(crate::wait::deadline_from)
}
pub(crate) trait Waitable {
type Output;
fn look(&mut self) -> Result<Step<'_, Self::Output>, Error>;
fn block_failed(&mut self, e: Error) -> Result<(), Error> {
Err(e)
}
}
pub(crate) enum Step<'a, T> {
Done(T),
Wait(WaitFor<'a>),
Recheck,
}
#[derive(Debug)]
pub(crate) enum RunOutcome<T> {
Done(T),
DeadlinePassed,
}
pub(crate) fn pause_end(now: Instant, step: Duration, deadline: Option<Instant>) -> Option<Instant> {
if crate::wait::remaining_at(deadline, now) == Some(Duration::ZERO) {
return None;
}
Some(deadline.map_or(now + step, |deadline| deadline.min(now + step)))
}
fn backoff() -> ExponentialBackoff {
ExponentialBuilder::new()
.with_min_delay(Duration::from_millis(1))
.with_factor(2.0)
.with_max_delay(Duration::from_millis(50))
.without_max_times()
.build()
}
impl<T> Step<'_, T> {
pub(crate) fn looked(&self) -> Looked {
match self {
Step::Done(_) => Looked::Done,
Step::Wait(_) => Looked::Wait,
Step::Recheck => Looked::Recheck,
}
}
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Looked {
Done,
Wait,
Recheck,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Next {
Done,
DeadlinePassed,
Wait,
Pause(Duration),
Look,
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Ended {
NotReleased,
Released,
}
pub(crate) fn wait_ended<W: Waitable + ?Sized>(w: &mut W, waited: Result<bool, Error>) -> Result<Ended, Error> {
Ok(match waited {
Ok(true) => Ended::NotReleased,
Ok(false) => Ended::Released,
Err(e) => {
w.block_failed(e)?;
Ended::NotReleased
}
})
}
pub(crate) struct Control {
steps: ExponentialBackoff,
released: bool,
final_look: bool,
}
impl Control {
pub(crate) fn new() -> Self {
Self {
steps: backoff(),
released: false,
final_look: false,
}
}
pub(crate) fn before_look(&mut self, left: Option<Duration>) {
self.final_look = self.released || left == Some(Duration::ZERO);
}
pub(crate) fn after_look(&mut self, looked: Looked, left: Option<Duration>) -> Next {
match looked {
Looked::Done => Next::Done,
Looked::Wait | Looked::Recheck if self.final_look => Next::DeadlinePassed,
_ if left == Some(Duration::ZERO) => Next::Look,
Looked::Wait => Next::Wait,
Looked::Recheck => Next::Pause(self.steps.next().expect("a backoff without a cap never ends")),
}
}
pub(crate) fn waited(&mut self, ended: Ended) {
self.steps = backoff();
self.released = matches!(ended, Ended::Released);
}
}
pub(crate) fn run<W: Waitable + ?Sized>(w: &mut W, deadline: Option<Instant>) -> Result<RunOutcome<W::Output>, Error> {
run_with(w, deadline, pause)
}
fn run_with<W: Waitable + ?Sized>(
w: &mut W,
deadline: Option<Instant>,
mut pause: impl FnMut(Duration),
) -> Result<RunOutcome<W::Output>, Error> {
let mut control = Control::new();
loop {
control.before_look(remaining(deadline));
let step = w.look()?;
let next = control.after_look(step.looked(), remaining(deadline));
match (next, step) {
(Next::Done, Step::Done(out)) => return Ok(RunOutcome::Done(out)),
(Next::DeadlinePassed, _) => return Ok(RunOutcome::DeadlinePassed),
(Next::Look, _) => {}
(Next::Pause(step), _) => {
let now = crate::wait::now();
if let Some(end) = pause_end(now, step, deadline) {
pause(end - now);
}
}
(Next::Wait, Step::Wait(wait_for)) => {
let waited = block(&wait_for, deadline);
control.waited(wait_ended(w, waited)?);
}
(next, _) => unreachable!("{next:?} answers a look that found something else"),
}
}
}
fn pause(d: Duration) {
#[cfg(test)]
crate::wait::block_probe::record_pause(d);
#[cfg(test)]
let started = Instant::now();
std::thread::sleep(d);
#[cfg(test)]
crate::wait::test_clock::advance_by_elapsed_if_frozen(started.elapsed());
}
pub(crate) struct ProcessExit<'a, P: OsProcess + ?Sized>(pub(crate) &'a P);
impl<P: OsProcess + ?Sized> Waitable for ProcessExit<'_, P> {
type Output = ();
fn look(&mut self) -> Result<Step<'_, ()>, Error> {
Ok(match self.0.exited()? {
Exit::Exited => Step::Done(()),
Exit::Running(wait_for) => Step::Wait(wait_for),
Exit::Recheck => Step::Recheck,
})
}
}
fn block(wait_for: &WaitFor<'_>, deadline: Option<Instant>) -> Result<bool, Error> {
match wait_for {
#[cfg(unix)]
WaitFor::Readable(fd) => crate::os_process::poll::poll_readable(*fd, deadline).map_err(Error::Io),
#[cfg(windows)]
WaitFor::Signalled(process) => {
use std::os::windows::io::AsRawHandle;
use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows::Win32::System::Threading::WaitForSingleObject;
let handle = HANDLE(process.as_raw_handle());
let waited = crate::wait::wait_until(deadline, |ms| {
#[cfg(test)]
crate::wait::block_probe::blocking(
(ms != u32::MAX).then(|| Duration::from_millis(ms.into())),
crate::wait::block_probe::WaitObject::Handles,
);
unsafe { WaitForSingleObject(handle, ms) }
});
if waited != WAIT_OBJECT_0 && waited != WAIT_TIMEOUT {
let e = std::io::Error::last_os_error();
debug_assert!(
false,
"WaitForSingleObject on a process handle returned {waited:?}: {e}"
);
return Err(Error::Io(e));
}
Ok(waited == WAIT_OBJECT_0)
}
}
}
#[cfg(test)]
#[path = "drive_tests.rs"]
pub(crate) mod drive_tests;