use std::time::Duration;
use crate::error::Error;
pub(crate) fn tokio_now() -> std::time::Instant {
#[cfg(all(test, unix))]
if let Some(now) = now_override::get() {
return now;
}
::tokio::time::Instant::now().into_std()
}
pub(crate) fn deadline_from(duration: Duration) -> Option<std::time::Instant> {
crate::wait::deadline_at(tokio_now(), duration)
}
#[cfg(any(windows, test))]
pub(crate) fn to_real_clock_at(
deadline: Option<std::time::Instant>,
tokio_now: std::time::Instant,
real_now: std::time::Instant,
) -> Option<std::time::Instant> {
deadline.and_then(|at| crate::wait::deadline_at(real_now, at.saturating_duration_since(tokio_now)))
}
#[cfg(windows)]
pub(crate) fn to_real_clock(deadline: Option<std::time::Instant>) -> Option<std::time::Instant> {
to_real_clock_at(deadline, tokio_now(), crate::wait::now())
}
#[cfg(unix)]
pub(crate) async fn arm_at<F: std::future::Future>(at: std::time::Instant, fut: F) -> Option<F::Output> {
let holds = crate::wait::clears_tokio_timer_margin(at);
debug_assert!(
holds,
"deadline_from's contract should prevent a deadline inside tokio's timer margin"
);
if !holds {
#[cfg(test)]
armed_deadline_seam::notify(armed_deadline_seam::Armed::Unbounded);
return Some(fut.await);
}
#[cfg(test)]
armed_deadline_seam::notify(armed_deadline_seam::Armed::At(at));
#[expect(clippy::disallowed_methods, reason = "the one sanctioned timeout_at call")]
let armed = ::tokio::time::timeout_at(::tokio::time::Instant::from_std(at), fut);
armed.await.ok()
}
pub(crate) enum Unjoined {
NotRun(Error),
Unknown(Error),
}
pub(crate) struct Hop {
what: &'static str,
}
impl Hop {
pub(crate) fn enter(what: &'static str) -> Result<Hop, Unjoined> {
if ::tokio::runtime::Handle::try_current().is_err() {
return Err(Unjoined::NotRun(Error::Io(std::io::Error::other(format!(
"{what} must be called from within a Tokio runtime"
)))));
}
Ok(Hop { what })
}
pub(crate) async fn run<T: Send + 'static>(self, work: impl FnOnce() -> T + Send + 'static) -> Result<T, Unjoined> {
let what = self.what;
#[cfg(test)]
let relay = crate::relayed_probe::capture();
let (tx, rx) = ::tokio::sync::oneshot::channel();
let mut landing = Landing { rx };
let joined = ::tokio::task::spawn_blocking(move || {
#[cfg(test)]
let _relay = relay.reinstall();
_ = tx.send(work());
})
.await;
match joined {
Ok(()) => {}
Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
Err(e) if e.is_cancelled() => {
return Err(Unjoined::NotRun(Error::Io(std::io::Error::other(format!(
"{what} cancelled (runtime shutting down)"
)))))
}
Err(e) => {
debug_assert!(false, "unknown JoinError variant: {e:?}");
return Err(Unjoined::Unknown(Error::Io(std::io::Error::other(format!(
"{what}: nothing is known of what the task did: {e}"
)))));
}
}
Ok(landing
.rx
.try_recv()
.expect("a blocking task that ended without panicking sent its value"))
}
}
pub(crate) async fn on_blocking_pool<T: Send + 'static>(
what: &'static str,
work: impl FnOnce() -> T + Send + 'static,
) -> Result<T, Unjoined> {
Hop::enter(what)?.run(work).await
}
struct Landing<T: Send + 'static> {
rx: ::tokio::sync::oneshot::Receiver<T>,
}
impl<T: Send + 'static> Drop for Landing<T> {
fn drop(&mut self) {
self.rx.close();
let Ok(value) = self.rx.try_recv() else { return };
match ::tokio::runtime::Handle::try_current() {
Ok(runtime) => drop(runtime.spawn_blocking(move || drop(value))),
Err(_) => drop(value),
}
}
}
#[cfg(target_os = "linux")]
pub(crate) async fn watch_pidfd<F: std::os::fd::AsRawFd>(pidfd: F) -> Result<(), Error> {
use ::tokio::io::unix::AsyncFd;
use ::tokio::io::Interest;
let afd = AsyncFd::with_interest(pidfd, Interest::READABLE | Interest::ERROR).map_err(Error::Io)?;
loop {
let mut guard = afd
.ready(Interest::READABLE | Interest::ERROR)
.await
.map_err(Error::Io)?;
match classify_pidfd_ready(guard.ready()) {
Some(verdict) => return verdict,
None => guard.clear_ready(), }
}
}
#[cfg(target_os = "linux")]
pub(crate) fn classify_pidfd_ready(ready: ::tokio::io::Ready) -> Option<Result<(), Error>> {
if ready.is_error() {
return Some(Err(Error::Io(std::io::Error::other("pidfd poll returned POLLERR"))));
}
if ready.is_readable() || ready.is_read_closed() {
return Some(Ok(()));
}
None
}
#[cfg(target_os = "macos")]
pub(crate) async fn watch_readable<K, F>(afd: &::tokio::io::unix::AsyncFd<K>, mut drain: F) -> Result<(), Error>
where
K: std::os::fd::AsRawFd,
F: FnMut(&K) -> Result<Option<()>, Error>,
{
loop {
let mut guard = afd.readable().await.map_err(Error::Io)?;
match drain(afd.get_ref())? {
Some(()) => return Ok(()),
None => guard.clear_ready(), }
}
}
#[cfg(all(test, unix))]
pub(crate) mod armed_deadline_seam {
use std::cell::RefCell;
use std::sync::mpsc::Sender;
use std::time::Instant;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Armed {
At(Instant),
Unbounded,
}
thread_local! {
static NOTIFY: RefCell<Option<Sender<Armed>>> = const { RefCell::new(None) };
}
#[must_use]
pub(crate) struct Installed(());
pub(crate) fn install(tx: Sender<Armed>) -> Installed {
NOTIFY.with(|n| *n.borrow_mut() = Some(tx));
Installed(())
}
impl Drop for Installed {
fn drop(&mut self) {
NOTIFY.with(|n| {
n.borrow_mut().take();
});
}
}
pub(crate) fn notify(armed: Armed) {
NOTIFY.with(|n| {
if let Some(tx) = n.borrow().as_ref() {
_ = tx.send(armed);
}
});
}
}
#[cfg(all(test, unix))]
pub(crate) mod now_override {
use std::cell::Cell;
use std::time::Instant;
thread_local! {
static NOW: Cell<Option<Instant>> = const { Cell::new(None) };
}
pub(crate) fn get() -> Option<Instant> {
NOW.with(Cell::get)
}
#[must_use]
pub(crate) struct Installed(());
pub(crate) fn install(now: Instant) -> Installed {
NOW.with(|n| {
debug_assert!(n.get().is_none(), "a now_override is already installed on this thread");
n.set(Some(now));
});
Installed(())
}
impl Drop for Installed {
fn drop(&mut self) {
NOW.with(|n| n.set(None));
}
}
}
#[cfg(test)]
#[path = "wait_tests.rs"]
mod wait_tests;