agentmux_srv/server/streamed_browser/screen/
pace.rs1use std::sync::atomic::{AtomicU64, Ordering};
8use std::sync::{Arc, OnceLock};
9use std::time::{Duration, Instant};
10
11pub const BURST_WINDOW: Duration = Duration::from_millis(300);
13pub const BURST_GAP: Duration = Duration::from_millis(16);
15
16pub fn gap(since_input: Option<Duration>, steady: Duration) -> Duration {
18 match since_input {
19 Some(d) if d < BURST_WINDOW => BURST_GAP.min(steady),
20 _ => steady,
21 }
22}
23
24fn base() -> Instant {
25 static BASE: OnceLock<Instant> = OnceLock::new();
26 *BASE.get_or_init(Instant::now)
27}
28
29#[derive(Clone, Default)]
31pub struct Activity(Arc<AtomicU64>);
32
33impl Activity {
34 pub fn touch(&self) {
36 self.0.store(base().elapsed().as_millis() as u64 + 1, Ordering::Relaxed);
38 }
39
40 pub fn since(&self) -> Option<Duration> {
42 match self.0.load(Ordering::Relaxed) {
43 0 => None,
44 at => Some(base().elapsed().saturating_sub(Duration::from_millis(at - 1))),
45 }
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn frames_come_quickly_only_for_a_short_while_after_input() {
55 let steady = Duration::from_millis(66);
56 assert_eq!(gap(None, steady), steady, "no input yet");
57 assert_eq!(gap(Some(Duration::from_millis(0)), steady), BURST_GAP);
58 assert_eq!(gap(Some(Duration::from_millis(299)), steady), BURST_GAP);
59 assert_eq!(gap(Some(Duration::from_millis(300)), steady), steady, "the window is over");
60 assert_eq!(gap(Some(Duration::from_secs(10)), steady), steady);
61 }
62
63 #[test]
64 fn the_burst_never_slows_a_steady_rate_that_is_already_faster() {
65 assert_eq!(gap(Some(Duration::ZERO), Duration::from_millis(5)), Duration::from_millis(5));
66 }
67
68 #[test]
69 fn activity_says_never_then_how_long_ago() {
70 let a = Activity::default();
71 assert_eq!(a.since(), None);
72 a.touch();
73 let seen = a.since().expect("touched");
74 assert!(seen < Duration::from_secs(1), "{seen:?}");
75 let other = a.clone();
76 std::thread::sleep(Duration::from_millis(20));
77 assert!(other.since().unwrap() >= Duration::from_millis(15), "a clone shares the time");
78 }
79}