use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt;
use std::panic::Location;
use std::rc::Rc;
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
use crate::config::{HangAfter, RealClock, SystemClock};
use crate::runtime::{SharedBook, lock};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct HangReport {
pub(crate) call: &'static str,
pub(crate) test: String,
pub(crate) step: Option<String>,
pub(crate) last_message: Option<String>,
pub(crate) pending: Vec<String>,
pub(crate) elapsed: Duration,
}
impl fmt::Display for HangReport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "harness aborted: app call did not return")?;
writeln!(f, " test: {}", self.test)?;
writeln!(
f,
" step: {}",
self.step
.as_deref()
.unwrap_or("boot, before the first step")
)?;
writeln!(
f,
" app call: {} (running for {:.1}s)",
self.call,
self.elapsed.as_secs_f64()
)?;
writeln!(
f,
" last message: {}",
self.last_message.as_deref().unwrap_or("none")
)?;
if self.pending.is_empty() {
writeln!(f, " pending tasks: none")?;
} else {
writeln!(f, " pending tasks:")?;
for task in &self.pending {
writeln!(f, " {task}")?;
}
}
write!(
f,
" Set ICEDWRIGHT_WATCHDOG to a longer duration, or to off in a debugger session."
)
}
}
type PendingTasks = Arc<dyn Fn() -> Vec<String> + Send + Sync>;
struct Running {
started: Instant,
budget: Duration,
call: &'static str,
test: String,
step: Option<String>,
last_message: Option<String>,
pending: PendingTasks,
}
impl Running {
fn deadline(&self) -> Instant {
self.started + self.budget
}
fn report(&self, now: Instant) -> HangReport {
HangReport {
call: self.call,
test: self.test.clone(),
step: self.step.clone(),
last_message: self.last_message.clone(),
pending: (self.pending)(),
elapsed: now.saturating_duration_since(self.started),
}
}
}
#[derive(Default)]
struct Calls {
next: u64,
running: BTreeMap<u64, Running>,
reported: bool,
}
#[derive(Debug, PartialEq, Eq)]
enum Next {
Idle,
Wait(Duration),
Abort(HangReport),
}
impl Calls {
fn next(&self, now: Instant) -> Next {
let Some(earliest) = self.running.values().min_by_key(|call| call.deadline()) else {
return Next::Idle;
};
match earliest.deadline().checked_duration_since(now) {
Some(left) if !left.is_zero() => Next::Wait(left),
_ => Next::Abort(earliest.report(now)),
}
}
}
pub(crate) type AbortHook = Box<dyn Fn(&HangReport) + Send + Sync>;
pub(crate) struct Watchdog {
clock: Arc<dyn RealClock>,
abort: AbortHook,
calls: Mutex<Calls>,
changed: Condvar,
}
impl fmt::Debug for Watchdog {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Watchdog")
.field("running", &lock(&self.calls).running.len())
.finish_non_exhaustive()
}
}
impl Watchdog {
pub(crate) fn new(clock: Arc<dyn RealClock>, abort: AbortHook) -> Self {
Self {
clock,
abort,
calls: Mutex::default(),
changed: Condvar::new(),
}
}
pub(crate) fn global() -> Option<&'static Arc<Watchdog>> {
static GLOBAL: OnceLock<Option<Arc<Watchdog>>> = OnceLock::new();
GLOBAL
.get_or_init(|| {
let watchdog = Arc::new(Watchdog::new(
Arc::new(SystemClock),
Box::new(|report| {
eprintln!("{report}");
std::process::abort();
}),
));
let watching = Arc::clone(&watchdog);
std::thread::Builder::new()
.name("icedwright-watchdog".to_owned())
.spawn(move || watching.watch())
.ok()
.map(|_| watchdog)
})
.as_ref()
}
fn start(&self, budget: Duration, call: &'static str, context: &Context) -> u64 {
let mut calls = lock(&self.calls);
let id = calls.next;
calls.next += 1;
calls.running.insert(
id,
Running {
started: self.clock.now(),
budget,
call,
test: context.test.clone(),
step: context.step.borrow().clone(),
last_message: context.last_message.borrow().clone(),
pending: Arc::clone(&context.pending),
},
);
drop(calls);
self.changed.notify_all();
id
}
fn end(&self, id: u64) {
lock(&self.calls).running.remove(&id);
self.changed.notify_all();
}
pub(crate) fn poll(&self) -> bool {
let mut calls = lock(&self.calls);
if calls.reported {
return false;
}
let Next::Abort(report) = calls.next(self.clock.now()) else {
return false;
};
calls.reported = true;
drop(calls);
(self.abort)(&report);
true
}
fn watch(&self) {
let mut calls = lock(&self.calls);
loop {
calls = match calls.next(self.clock.now()) {
Next::Idle => self
.changed
.wait(calls)
.unwrap_or_else(std::sync::PoisonError::into_inner),
Next::Wait(left) => {
self.changed
.wait_timeout(calls, left)
.unwrap_or_else(std::sync::PoisonError::into_inner)
.0
}
Next::Abort(_) => {
drop(calls);
self.poll();
lock(&self.calls)
}
};
}
}
}
pub(crate) struct Context {
watchdog: Option<Arc<Watchdog>>,
budget: Duration,
test: String,
step: RefCell<Option<String>>,
last_message: RefCell<Option<String>>,
pending: PendingTasks,
}
impl fmt::Debug for Context {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Context")
.field("watched", &self.watchdog.is_some())
.field("budget", &self.budget)
.finish_non_exhaustive()
}
}
pub(crate) fn budget(env: Option<HangAfter>, config: HangAfter) -> Option<Duration> {
if config == HangAfter::Off {
return None;
}
match env.unwrap_or_default() {
HangAfter::After(budget) => Some(budget),
HangAfter::Off => None,
}
}
pub(crate) fn pending_tasks(book: SharedBook) -> PendingTasks {
Arc::new(move || {
let Ok(book) = book.try_lock() else {
return vec!["(the task list is locked by the stuck call)".to_owned()];
};
book.tasks
.iter()
.filter(|(_, record)| record.state.is_live())
.map(|(id, record)| format!("{id}: {:?}, {:?}", record.spawn, record.state))
.collect()
})
}
impl Context {
pub(crate) fn new(
watchdog: Option<Arc<Watchdog>>,
budget: Option<Duration>,
pending: PendingTasks,
) -> Self {
let thread = std::thread::current();
Self {
watchdog: budget.and(watchdog),
budget: budget.unwrap_or_default(),
test: thread.name().unwrap_or("main").to_owned(),
step: RefCell::new(None),
last_message: RefCell::new(None),
pending,
}
}
pub(crate) fn set_step(&self, location: &Location<'_>) {
*self.step.borrow_mut() = Some(format!(
"{}:{}:{}",
location.file(),
location.line(),
location.column()
));
}
pub(crate) fn set_message(&self, debug: &str) {
*self.last_message.borrow_mut() = Some(debug.to_owned());
}
fn run<T>(&self, call: &'static str, f: impl FnOnce() -> T) -> T {
let Some(watchdog) = &self.watchdog else {
return f();
};
let id = watchdog.start(self.budget, call, self);
let _end = End { watchdog, id };
f()
}
}
struct End<'w> {
watchdog: &'w Watchdog,
id: u64,
}
impl Drop for End<'_> {
fn drop(&mut self) {
self.watchdog.end(self.id);
}
}
thread_local! {
static CURRENT: RefCell<Option<Rc<Context>>> = const { RefCell::new(None) };
}
#[derive(Debug)]
pub(crate) struct ContextGuard {
context: Rc<Context>,
previous: Option<Rc<Context>>,
}
impl ContextGuard {
pub(crate) fn install(context: Context) -> Self {
let context = Rc::new(context);
let previous = CURRENT.with(|current| current.replace(Some(Rc::clone(&context))));
Self { context, previous }
}
pub(crate) fn context(&self) -> &Context {
&self.context
}
}
impl Drop for ContextGuard {
fn drop(&mut self) {
let previous = self.previous.take();
CURRENT.with(|current| current.replace(previous));
}
}
pub(crate) fn app_call<T>(call: &'static str, f: impl FnOnce() -> T) -> T {
let context = CURRENT.with(|current| current.borrow().clone());
match context {
Some(context) => context.run(call, f),
None => f(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicU64, Ordering};
struct HandClock {
start: Instant,
offset_ms: AtomicU64,
}
impl HandClock {
fn new() -> Arc<Self> {
Arc::new(Self {
start: SystemClock.now(),
offset_ms: AtomicU64::new(0),
})
}
fn advance(&self, by: Duration) {
let ms = u64::try_from(by.as_millis()).unwrap();
self.offset_ms.fetch_add(ms, Ordering::SeqCst);
}
}
impl RealClock for HandClock {
fn now(&self) -> Instant {
self.start + Duration::from_millis(self.offset_ms.load(Ordering::SeqCst))
}
}
fn watchdog(clock: &Arc<HandClock>) -> (Arc<Watchdog>, Arc<Mutex<Vec<HangReport>>>) {
let reports = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&reports);
let watchdog = Watchdog::new(
Arc::clone(clock) as Arc<dyn RealClock>,
Box::new(move |report| sink.lock().unwrap().push(report.clone())),
);
(Arc::new(watchdog), reports)
}
fn context(watchdog: &Arc<Watchdog>, budget: Duration) -> Context {
Context::new(
Some(Arc::clone(watchdog)),
Some(budget),
Arc::new(|| vec!["#1: Boot, Pending".to_owned()]),
)
}
#[test]
fn a_call_past_its_budget_is_reported_with_its_context() {
let clock = HandClock::new();
let (watchdog, reports) = watchdog(&clock);
let context = context(&watchdog, Duration::from_secs(1));
context.set_step(Location::caller());
context.set_message("Block");
let ran = context.run("update", || {
assert!(!watchdog.poll());
clock.advance(Duration::from_millis(999));
assert!(!watchdog.poll());
clock.advance(Duration::from_millis(1));
assert!(watchdog.poll());
7
});
assert_eq!(ran, 7);
let reports = reports.lock().unwrap();
let [report] = reports.as_slice() else {
panic!("expected one report, got {reports:?}");
};
assert_eq!(report.call, "update");
assert_eq!(report.last_message.as_deref(), Some("Block"));
assert_eq!(report.pending, vec!["#1: Boot, Pending".to_owned()]);
assert_eq!(report.elapsed, Duration::from_secs(1));
let step = report.step.as_deref().unwrap();
assert!(step.contains("watchdog.rs"), "{step}");
let text = report.to_string();
assert!(
text.starts_with("harness aborted: app call did not return"),
"{text}"
);
for part in [
"app call: update",
"last message: Block",
"#1: Boot, Pending",
] {
assert!(text.contains(part), "{text}");
}
}
#[test]
fn a_call_that_returns_in_time_is_forgotten() {
let clock = HandClock::new();
let (watchdog, reports) = watchdog(&clock);
let context = context(&watchdog, Duration::from_secs(1));
context.run("view", || clock.advance(Duration::from_millis(500)));
clock.advance(Duration::from_secs(600));
assert!(!watchdog.poll());
assert!(reports.lock().unwrap().is_empty());
assert_eq!(lock(&watchdog.calls).next(clock.now()), Next::Idle);
}
#[test]
fn a_call_that_unwinds_is_forgotten_too() {
let clock = HandClock::new();
let (watchdog, _) = watchdog(&clock);
let context = context(&watchdog, Duration::from_secs(1));
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
context.run("update", || panic!("app bug"));
}));
assert!(unwound.is_err());
assert!(lock(&watchdog.calls).running.is_empty());
}
#[test]
fn the_thread_waits_for_the_earliest_deadline_and_reports_once() {
let clock = HandClock::new();
let (watchdog, reports) = watchdog(&clock);
let slow = context(&watchdog, Duration::from_secs(10));
let quick = context(&watchdog, Duration::from_secs(2));
slow.run("view", || {
quick.run("update", || {
assert_eq!(
lock(&watchdog.calls).next(clock.now()),
Next::Wait(Duration::from_secs(2))
);
clock.advance(Duration::from_secs(3));
assert!(watchdog.poll());
assert!(!watchdog.poll());
});
});
let reports = reports.lock().unwrap();
assert_eq!(reports.len(), 1);
assert_eq!(reports.first().map(|r| r.call), Some("update"));
}
#[test]
fn an_unwatched_context_runs_calls_without_registering_them() {
let clock = HandClock::new();
let (watchdog, _) = watchdog(&clock);
let context = Context::new(Some(Arc::clone(&watchdog)), None, Arc::new(Vec::new));
context.run("update", || {
assert!(lock(&watchdog.calls).running.is_empty());
});
}
#[test]
fn app_calls_report_to_the_innermost_installed_harness() {
let clock = HandClock::new();
let (watchdog, _) = watchdog(&clock);
assert_eq!(app_call("view", || 1), 1);
let outer = ContextGuard::install(context(&watchdog, Duration::from_secs(5)));
{
let _inner = ContextGuard::install(context(&watchdog, Duration::from_secs(1)));
app_call("view", || {
let calls = lock(&watchdog.calls);
let budgets: Vec<Duration> = calls.running.values().map(|r| r.budget).collect();
assert_eq!(budgets, vec![Duration::from_secs(1)]);
});
}
app_call("view", || {
let calls = lock(&watchdog.calls);
let budgets: Vec<Duration> = calls.running.values().map(|r| r.budget).collect();
assert_eq!(budgets, vec![Duration::from_secs(5)]);
});
assert_eq!(outer.context().budget, Duration::from_secs(5));
}
#[test]
fn the_budget_comes_from_the_environment_and_off_wins() {
let second = HangAfter::After(Duration::from_secs(1));
assert_eq!(
budget(None, second),
Some(Duration::from_secs(120)),
"a harness's own hang window does not shorten the watchdog"
);
assert_eq!(
budget(Some(second), HangAfter::default()),
Some(Duration::from_secs(1))
);
assert_eq!(budget(Some(HangAfter::Off), HangAfter::default()), None);
assert_eq!(budget(Some(second), HangAfter::Off), None);
}
}