use std::time::Instant;
use crate::containment::TreeDrain;
use crate::error::Error;
pub(crate) enum DrainEdge<'a> {
#[cfg(target_os = "linux")]
Cgroup(&'a crate::containment::cgroup::CgroupLeaf),
#[cfg(windows)]
Job(&'a crate::containment::windows::JobHandle),
#[cfg(target_os = "macos")]
Marker(&'a crate::containment::fdmarker::Marker),
}
impl DrainEdge<'_> {
pub(crate) fn wait(&self, deadline: Option<Instant>) -> Result<TreeDrain, Error> {
match self {
#[cfg(target_os = "linux")]
DrainEdge::Cgroup(leaf) => leaf.wait_drained(deadline),
#[cfg(windows)]
DrainEdge::Job(job) => job.wait_drained(deadline),
#[cfg(target_os = "macos")]
DrainEdge::Marker(m) => m.wait_drained(deadline),
}
}
#[cfg(feature = "tokio")]
pub(crate) async fn wait_async(&self, deadline: Option<Instant>) -> Result<TreeDrain, Error> {
match self {
#[cfg(target_os = "linux")]
DrainEdge::Cgroup(leaf) => cgroup_wait_tree_drained(leaf, deadline).await,
#[cfg(windows)]
DrainEdge::Job(job) => job_wait_tree_drained(job, deadline).await,
#[cfg(target_os = "macos")]
DrainEdge::Marker(m) => {
m.check_read_end_still_valid()?;
debug_assert_ne!(
crate::containment::marker_eof::write_end_check(m.read_end()),
crate::containment::marker_eof::WriteEndCheck::HeldByUs,
"the supervisor still holds a copy of the marker write end - the tree-drain edge can never fire"
);
wait_tree_deadline(m.read_end(), deadline).await
}
}
}
}
#[cfg(all(feature = "tokio", target_os = "macos"))]
pub(crate) async fn wait_tree_drained(read_end: std::os::fd::BorrowedFd<'_>) -> Result<(), Error> {
wait_tree_drained_watched(read_end, None).await
}
#[cfg(all(feature = "tokio", target_os = "macos"))]
pub(crate) async fn wait_tree_deadline(
read_end: std::os::fd::BorrowedFd<'_>,
deadline: Option<Instant>,
) -> Result<TreeDrain, Error> {
use crate::tokio::wait::{arm_at, tokio_now};
match deadline {
None => {
wait_tree_drained(read_end).await?;
Ok(TreeDrain::AllMarkersClosed)
}
Some(at) => {
if crate::wait::remaining_at(deadline, tokio_now()) == Some(std::time::Duration::ZERO) {
return crate::containment::marker_eof::probe(read_end);
}
match arm_at(at, wait_tree_drained_inner(read_end, false, None)).await {
Some(res) => res.map(|()| TreeDrain::AllMarkersClosed),
None => crate::containment::marker_eof::probe(read_end),
}
}
}
}
#[cfg(all(test, feature = "tokio", target_os = "macos"))]
pub(crate) mod declined_hook {
use std::cell::RefCell;
use ::tokio::sync::mpsc::UnboundedSender;
thread_local! {
static DECLINED: RefCell<Option<UnboundedSender<()>>> = const { RefCell::new(None) };
}
pub(crate) fn notify() {
DECLINED.with(|d| {
if let Some(tx) = d.borrow().as_ref() {
let sent = tx.send(());
debug_assert!(sent.is_ok(), "declined_hook receiver dropped before the hook fired");
}
});
}
#[must_use]
pub(crate) struct DeclinedGuard {
_private: (),
}
impl DeclinedGuard {
pub(crate) fn install(tx: UnboundedSender<()>) -> Self {
DECLINED.with(|d| {
let mut slot = d.borrow_mut();
debug_assert!(slot.is_none(), "a declined_hook is already installed on this thread");
*slot = Some(tx);
});
Self { _private: () }
}
}
impl Drop for DeclinedGuard {
fn drop(&mut self) {
DECLINED.with(|d| {
let prev = d.borrow_mut().take();
debug_assert!(
prev.is_some(),
"declined_hook slot was cleared before its guard dropped"
);
});
}
}
}
#[cfg(all(test, feature = "tokio", target_os = "macos"))]
pub(crate) async fn wait_tree_drained_for_test(
read_end: std::os::fd::BorrowedFd<'_>,
armed: std::sync::mpsc::Sender<std::os::fd::RawFd>,
) -> Result<(), Error> {
wait_tree_drained_watched(read_end, Some(armed)).await
}
#[cfg(all(feature = "tokio", target_os = "macos"))]
async fn wait_tree_drained_watched(
read_end: std::os::fd::BorrowedFd<'_>,
armed: Option<std::sync::mpsc::Sender<std::os::fd::RawFd>>,
) -> Result<(), Error> {
wait_tree_drained_inner(read_end, true, armed).await
}
#[cfg(all(feature = "tokio", target_os = "macos"))]
async fn wait_tree_drained_inner(
read_end: std::os::fd::BorrowedFd<'_>,
unbounded_wait: bool,
armed: Option<std::sync::mpsc::Sender<std::os::fd::RawFd>>,
) -> Result<(), Error> {
use std::os::fd::AsRawFd;
use crate::containment::marker_eof::DrainOutcome;
use crate::tokio::wait::watch_readable;
use ::tokio::io::unix::AsyncFd;
use ::tokio::io::Interest;
let kq = crate::containment::marker_eof::arm(read_end, unbounded_wait)?;
if let Some(tx) = armed {
let sent = tx.send(kq.as_raw_fd());
debug_assert!(
sent.is_ok(),
"the `armed` receiver was dropped before the kqueue was armed"
);
}
let afd = AsyncFd::with_interest(kq, Interest::READABLE).map_err(Error::Io)?;
watch_readable(&afd, move |kq| {
match crate::containment::marker_eof::drain_kqueue(kq, read_end, unbounded_wait)? {
DrainOutcome::Drained(_) => Ok(Some(())),
DrainOutcome::Declined => {
#[cfg(test)]
declined_hook::notify();
Ok(None)
}
DrainOutcome::Spurious => Ok(None),
}
})
.await
}
#[cfg(all(feature = "tokio", target_os = "linux"))]
pub(crate) async fn cgroup_wait_tree_drained(
leaf: &crate::containment::cgroup::CgroupLeaf,
deadline: Option<Instant>,
) -> Result<TreeDrain, Error> {
use crate::containment::cgroup::DrainStep;
use crate::tokio::wait::{arm_at, tokio_now};
loop {
match leaf.drain_step_on(deadline, tokio_now)? {
DrainStep::Done(drain) => return Ok(drain),
DrainStep::Block {
listener,
deadline: None,
} => {
#[cfg(test)]
crate::tokio::wait::armed_deadline_seam::notify(
crate::tokio::wait::armed_deadline_seam::Armed::Unbounded,
);
listener.await
}
DrainStep::Block {
listener,
deadline: Some(at),
} => {
let _ = arm_at(at, listener).await;
}
}
}
}
#[cfg(all(feature = "tokio", windows))]
async fn job_wait_tree_drained(
job: &crate::containment::windows::JobHandle,
deadline: Option<Instant>,
) -> Result<TreeDrain, Error> {
use crate::containment::windows::{Ended, Round};
use crate::os_process::windows::registered_wait::{wait_any, Woke};
let deadline = crate::tokio::wait::to_real_clock(deadline);
loop {
let last_round = deadline.is_some_and(|at| crate::wait::now() >= at);
let watch = match job.drain_round(last_round)? {
Round::Answer(drain) => return Ok(drain),
Round::List => {
::tokio::task::yield_now().await;
continue;
}
Round::Watch(watch) => watch,
};
let ended = if last_round {
watch.poll()?
} else {
match wait_any(watch.handles(), deadline).await.map_err(Error::Io)? {
Woke::Signalled => Ended::Signalled,
Woke::TimedOut => watch.poll()?,
}
};
match ended {
Ended::Deadline => return Ok(TreeDrain::MembersRemain),
Ended::Signalled => {
if let Some(drain) = job.after_signalled(&watch)? {
return Ok(drain);
}
::tokio::task::yield_now().await;
}
}
}
}