agentmux_srv_core/backend/
audit_live.rs1use std::sync::mpsc::{channel, Receiver, Sender};
13use std::sync::{Arc, OnceLock};
14use std::time::Duration;
15
16use super::mps::Broker;
17
18pub const WINDOW: Duration = Duration::from_millis(100);
20
21static POKE: OnceLock<Sender<()>> = OnceLock::new();
22
23pub fn install_broker(broker: Arc<Broker>) {
25 let publish = move || broker.publish_event::<super::mps_events::AuditChanged>(&(), vec![], 0);
26 if let Ok(tx) = spawn(publish, WINDOW) {
27 let _ = POKE.set(tx);
28 }
29}
30
31pub fn poke() {
33 if let Some(tx) = POKE.get() {
34 let _ = tx.send(());
35 }
36}
37
38fn spawn(publish: impl Fn() + Send + 'static, window: Duration) -> std::io::Result<Sender<()>> {
40 let (tx, rx) = channel::<()>();
41 std::thread::Builder::new().name("audit-live".into()).spawn(move || run(&rx, window, publish))?;
42 Ok(tx)
43}
44
45fn run(rx: &Receiver<()>, window: Duration, publish: impl Fn()) {
46 while rx.recv().is_ok() {
47 std::thread::sleep(window);
49 while rx.try_recv().is_ok() {}
50 publish();
51 }
52}
53
54#[cfg(test)]
55mod tests {
56 use super::*;
57 use std::sync::atomic::{AtomicUsize, Ordering};
58
59 #[test]
60 fn a_burst_of_pokes_is_one_event_and_a_later_poke_is_another() {
61 let events = Arc::new(AtomicUsize::new(0));
62 let seen = Arc::clone(&events);
63 let tx = spawn(move || { seen.fetch_add(1, Ordering::SeqCst); }, Duration::from_millis(40)).unwrap();
64
65 let settles_at = |n: usize| {
68 let deadline = std::time::Instant::now() + Duration::from_secs(10);
69 while events.load(Ordering::SeqCst) < n {
70 assert!(std::time::Instant::now() < deadline, "no event number {n}");
71 std::thread::sleep(Duration::from_millis(10));
72 }
73 std::thread::sleep(Duration::from_millis(200));
74 events.load(Ordering::SeqCst)
75 };
76
77 for _ in 0..25 {
78 tx.send(()).unwrap();
79 }
80 assert_eq!(settles_at(1), 1, "the burst is one event");
81
82 tx.send(()).unwrap();
83 assert_eq!(settles_at(2), 2, "a later poke is another");
84 }
85
86 #[test]
87 fn a_poke_before_the_broker_is_attached_does_nothing() {
88 poke();
89 }
90}