use std::future::Future;
use parking_lot::Mutex;
use tokio::sync::Notify;
use tokio::sync::OnceCell;
use crate::shutdown_deadline::ShutdownDeadline;
use crate::shutdown_report::ShutdownReport;
#[derive(Debug)]
pub(super) struct ShutdownTimeout;
#[derive(Debug)]
pub(super) struct ShutdownCoordinator {
deadline: Mutex<Option<ShutdownDeadline>>,
changed: Notify,
pub(super) report: OnceCell<ShutdownReport>,
pub(super) report_ready: Notify,
}
impl ShutdownCoordinator {
pub(super) fn new() -> Self {
Self {
deadline: Mutex::new(None),
changed: Notify::new(),
report: OnceCell::new(),
report_ready: Notify::new(),
}
}
pub(super) fn deadline(&self) -> Option<ShutdownDeadline> {
*self.deadline.lock()
}
pub(super) async fn wait_report(&self) -> &ShutdownReport {
loop {
let ready = self.report_ready.notified();
if let Some(report) = self.report.get() {
return report;
}
ready.await;
}
}
pub(super) fn tighten(&self, deadline: ShutdownDeadline) -> ShutdownDeadline {
let (installed, changed) = {
let mut current = self.deadline.lock();
let installed = current.map_or(deadline, |existing| existing.earliest(deadline));
let changed = current.is_none_or(|existing| installed.instant() < existing.instant());
*current = Some(installed);
(installed, changed)
};
if changed {
self.changed.notify_waiters();
}
installed
}
pub(super) async fn run_until<F>(&self, future: F) -> Result<F::Output, ShutdownTimeout>
where
F: Future,
{
tokio::pin!(future);
loop {
let changed = self.changed.notified();
let Some(deadline) = self.deadline() else {
return Ok(future.await);
};
let deadline_elapsed = tokio::time::sleep(deadline.remaining());
tokio::pin!(changed);
tokio::pin!(deadline_elapsed);
tokio::select! {
biased;
output = &mut future => return Ok(output),
() = &mut changed => {}
() = &mut deadline_elapsed => return Err(ShutdownTimeout),
}
}
}
}