use std::sync::Arc;
use std::time::{Duration, Instant};
use iced_core::window;
pub use icedwright_types::{VirtualDuration, VirtualInstant};
use crate::config::{HangAfter, RealClock};
use crate::effects::UntypedTaskId;
use crate::error::{HangCause, HarnessError};
pub(crate) const EPOCH_OFFSET: Duration = Duration::from_secs(24 * 60 * 60);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Clock {
Virtual(VirtualInstant),
Real,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WakeUp {
pub at: VirtualInstant,
pub kind: WakeKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WakeKind {
Frame,
WidgetTimer(window::Id),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RealDeadline {
pub redraws: u32,
pub tooltip_leaves: u32,
}
pub use icedwright_check::Waited;
#[derive(Debug, Clone, Copy)]
pub(crate) struct VirtualClock {
epoch: tokio::time::Instant,
}
impl VirtualClock {
pub(crate) fn new(epoch: tokio::time::Instant) -> Self {
Self { epoch }
}
pub(crate) fn epoch(&self) -> tokio::time::Instant {
self.epoch
}
pub(crate) fn of(&self, instant: tokio::time::Instant) -> VirtualInstant {
VirtualInstant::__from_offset(VirtualDuration::from(
instant.saturating_duration_since(self.epoch),
))
}
pub(crate) fn to_tokio(self, instant: VirtualInstant) -> tokio::time::Instant {
self.epoch + instant.since_boot().as_std()
}
pub(crate) fn to_iced(self, instant: VirtualInstant) -> Instant {
self.to_tokio(instant).into_std()
}
pub(crate) fn classify(&self, instant: Instant) -> Clock {
classify(self.epoch.into_std(), instant)
}
}
pub(crate) fn classify(epoch: Instant, instant: Instant) -> Clock {
match instant.checked_duration_since(epoch) {
Some(offset) => Clock::Virtual(VirtualInstant::__from_offset(offset.into())),
None => Clock::Real,
}
}
pub(crate) fn next_frame_boundary(
now: VirtualInstant,
interval: VirtualDuration,
) -> VirtualInstant {
let step = interval.as_std().as_nanos().max(1);
let elapsed = now.since_boot().as_std().as_nanos();
let next = (elapsed / step + 1).saturating_mul(step);
let nanos = u64::try_from(next).unwrap_or(u64::MAX);
VirtualInstant::__from_offset(VirtualDuration::from_nanos(nanos))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct WindowRedraw {
pub(crate) frame: bool,
pub(crate) timer: Option<VirtualInstant>,
pub(crate) input_timer: Option<VirtualInstant>,
pub(crate) real: bool,
}
impl WindowRedraw {
pub(crate) fn next_timer(&self) -> Option<VirtualInstant> {
match (self.timer, self.input_timer) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
pub(crate) fn before_redraw(self, now: VirtualInstant) -> Self {
Self {
input_timer: self.input_timer.filter(|t| *t > now),
..Self::default()
}
}
}
pub(crate) fn next_wake_up(
now: VirtualInstant,
interval: VirtualDuration,
windows: &[(window::Id, WindowRedraw)],
) -> Option<WakeUp> {
let frame = windows
.iter()
.any(|(_, redraw)| redraw.frame)
.then(|| WakeUp {
at: next_frame_boundary(now, interval),
kind: WakeKind::Frame,
});
let timer = windows
.iter()
.filter(|(_, redraw)| !redraw.frame)
.filter_map(|(id, redraw)| {
redraw.next_timer().map(|at| WakeUp {
at: at.max(now),
kind: WakeKind::WidgetTimer(*id),
})
})
.min_by_key(|wake| wake.at);
match (frame, timer) {
(Some(frame), Some(timer)) if timer.at < frame.at => Some(timer),
(Some(frame), _) => Some(frame),
(None, timer) => timer,
}
}
#[derive(Clone)]
pub(crate) struct HangDetector {
after: HangAfter,
clock: Arc<dyn RealClock>,
last_progress: Instant,
}
impl std::fmt::Debug for HangDetector {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HangDetector")
.field("after", &self.after)
.finish_non_exhaustive()
}
}
impl HangDetector {
pub(crate) fn new(after: HangAfter, clock: Arc<dyn RealClock>) -> Self {
let last_progress = clock.now();
Self {
after,
clock,
last_progress,
}
}
pub(crate) fn window(&self) -> Option<Duration> {
match self.after {
HangAfter::After(window) => Some(window),
HangAfter::Off => None,
}
}
pub(crate) fn now(&self) -> Instant {
self.clock.now()
}
pub(crate) fn progress(&mut self) {
self.last_progress = self.clock.now();
}
pub(crate) fn check(
&self,
step: &str,
cause: impl FnOnce() -> HangCause,
) -> Result<(), HarnessError> {
let Some(window) = self.window() else {
return Ok(());
};
let since = self
.clock
.now()
.saturating_duration_since(self.last_progress);
if since < window {
return Ok(());
}
Err(HarnessError::Hung {
step: step.to_owned(),
since_progress: since,
cause: cause(),
})
}
pub(crate) fn check_ceiling(
&self,
step: &str,
began: Instant,
sources: &[String],
) -> Result<(), HarnessError> {
let Some(window) = self.window() else {
return Ok(());
};
let since = self.clock.now().saturating_duration_since(began);
if since < window {
return Ok(());
}
Err(HarnessError::Hung {
step: step.to_owned(),
since_progress: since,
cause: HangCause::ExternalSources {
sources: sources.to_vec(),
},
})
}
}
pub(crate) fn busiest(polls: impl IntoIterator<Item = (UntypedTaskId, u64)>) -> Vec<UntypedTaskId> {
let mut all: Vec<(UntypedTaskId, u64)> = polls.into_iter().collect();
all.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
all.into_iter().take(3).map(|(id, _)| id).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::MockRealClock;
use std::sync::Mutex;
fn at(ms: u64) -> VirtualInstant {
VirtualInstant::__from_offset(VirtualDuration::from_millis(ms))
}
const FRAME: VirtualDuration = VirtualDuration::from_micros(16_667);
fn id() -> window::Id {
window::Id::unique()
}
#[test]
fn frame_boundaries_count_from_the_epoch() {
assert_eq!(
next_frame_boundary(at(0), FRAME),
VirtualInstant::__from_offset(FRAME)
);
assert_eq!(
next_frame_boundary(VirtualInstant::__from_offset(FRAME), FRAME),
VirtualInstant::__from_offset(FRAME * 2)
);
assert_eq!(
next_frame_boundary(at(20), FRAME),
VirtualInstant::__from_offset(FRAME * 2)
);
}
#[test]
fn next_frame_lands_on_the_next_boundary() {
let windows = [(
id(),
WindowRedraw {
frame: true,
..WindowRedraw::default()
},
)];
let wake = next_wake_up(at(5), FRAME, &windows);
assert_eq!(
wake,
Some(WakeUp {
at: VirtualInstant::__from_offset(FRAME),
kind: WakeKind::Frame
})
);
}
#[test]
fn a_virtual_timer_lands_at_its_instant() {
let window = id();
let windows = [(
window,
WindowRedraw {
timer: Some(at(500)),
..WindowRedraw::default()
},
)];
assert_eq!(
next_wake_up(at(5), FRAME, &windows),
Some(WakeUp {
at: at(500),
kind: WakeKind::WidgetTimer(window)
})
);
}
#[test]
fn a_real_clock_request_makes_no_wake_up_of_its_own() {
let windows = [(
id(),
WindowRedraw {
real: true,
..WindowRedraw::default()
},
)];
assert_eq!(next_wake_up(at(5), FRAME, &windows), None);
}
#[test]
fn wait_contributes_nothing_and_the_minimum_wins() {
let (a, b, c) = (id(), id(), id());
let windows = [
(a, WindowRedraw::default()),
(
b,
WindowRedraw {
frame: true,
..WindowRedraw::default()
},
),
(
c,
WindowRedraw {
timer: Some(at(3)),
input_timer: Some(at(4)),
..WindowRedraw::default()
},
),
];
assert_eq!(
next_wake_up(at(1), FRAME, &windows),
Some(WakeUp {
at: at(3),
kind: WakeKind::WidgetTimer(c)
})
);
assert_eq!(
next_wake_up(at(1), FRAME, &[(a, WindowRedraw::default())]),
None
);
}
#[test]
fn a_window_waiting_for_a_frame_gets_its_widget_timers_on_that_frame() {
let window = id();
let windows = [(
window,
WindowRedraw {
frame: true,
timer: Some(at(3)),
input_timer: Some(at(4)),
real: false,
},
)];
assert_eq!(
next_wake_up(at(1), FRAME, &windows),
Some(WakeUp {
at: VirtualInstant::__from_offset(FRAME),
kind: WakeKind::Frame
})
);
}
#[test]
fn a_redraw_drops_the_last_redraws_timer_and_keeps_input_timers_still_to_come() {
let pending = WindowRedraw {
frame: true,
timer: Some(at(400)),
input_timer: Some(at(300)),
real: true,
};
assert_eq!(pending.next_timer(), Some(at(300)));
assert_eq!(
pending.before_redraw(at(17)),
WindowRedraw {
input_timer: Some(at(300)),
..WindowRedraw::default()
}
);
assert_eq!(pending.before_redraw(at(300)), WindowRedraw::default());
}
#[test]
fn instants_before_the_epoch_are_real() {
let base = crate::config::SystemClock.now();
let epoch = base + EPOCH_OFFSET;
assert_eq!(classify(epoch, base), Clock::Real);
assert_eq!(
classify(epoch, epoch + Duration::from_millis(1250)),
Clock::Virtual(at(1250))
);
}
fn stepping_clock(step: Duration) -> Arc<dyn RealClock> {
let start = crate::config::SystemClock.now();
let ticks = Mutex::new(0u32);
let mut clock = MockRealClock::new();
clock.expect_now().returning(move || {
let mut ticks = ticks.lock().unwrap();
*ticks += 1;
start + step * *ticks
});
Arc::new(clock)
}
#[test]
fn steady_progress_for_600_seconds_never_hangs() {
let mut detector = HangDetector::new(
HangAfter::After(Duration::from_secs(120)),
stepping_clock(Duration::from_secs(10)),
);
for _ in 0..30 {
detector.progress();
assert!(
detector
.check("advance", || HangCause::AppCall { what: "update" })
.is_ok()
);
}
}
#[test]
fn no_progress_for_the_window_hangs() {
let detector = HangDetector::new(
HangAfter::After(Duration::from_secs(120)),
stepping_clock(Duration::from_secs(61)),
);
assert!(
detector
.check("settle", || HangCause::BlockingWork { job: None })
.is_ok()
);
let error = detector
.check("settle", || HangCause::BlockingWork { job: None })
.unwrap_err();
assert!(matches!(
error,
HarnessError::Hung {
cause: HangCause::BlockingWork { .. },
..
}
));
assert!(error.to_string().contains("spawn_blocking"));
}
#[test]
fn off_never_hangs() {
let detector = HangDetector::new(HangAfter::Off, stepping_clock(Duration::from_secs(1000)));
assert!(
detector
.check("settle", || HangCause::BlockingWork { job: None })
.is_ok()
);
}
#[test]
fn the_ceiling_counts_from_the_start_of_the_wait_whatever_progresses() {
let mut detector = HangDetector::new(
HangAfter::After(Duration::from_secs(5)),
stepping_clock(Duration::from_secs(1)),
);
let began = detector.now();
let sources = vec!["leaky::ticker".to_owned()];
let mut checks = 0;
let error = loop {
detector.progress();
checks += 1;
if let Err(error) = detector.check_ceiling("expect", began, &sources) {
break error;
}
};
assert_eq!(checks, 3);
let HarnessError::Hung {
since_progress,
cause,
..
} = error
else {
panic!("not a hang");
};
assert_eq!(since_progress, Duration::from_secs(6));
assert_eq!(cause, HangCause::ExternalSources { sources });
}
#[test]
fn busiest_sorts_by_polls() {
let ids: Vec<UntypedTaskId> = (1..=4).map(UntypedTaskId::new).collect();
let order = busiest([(ids[0], 3), (ids[1], 10), (ids[2], 3), (ids[3], 1)]);
assert_eq!(order, vec![ids[1], ids[0], ids[2]]);
}
}