agentmux_srv_core/backend/transcript/
counting.rs1use std::collections::HashMap;
20use std::sync::{Arc, Condvar, Mutex};
21use std::time::Duration;
22
23use crate::backend::storage::filestore::FileStore;
24
25struct Flight {
27 done: Mutex<bool>,
28 ended: Condvar,
29}
30
31impl Flight {
32 fn wait(&self, wait: Duration) -> bool {
33 let guard = self.done.lock().unwrap();
34 let (guard, _) = self.ended.wait_timeout_while(guard, wait, |done| !*done).unwrap();
35 *guard
36 }
37}
38
39static FLIGHTS: Mutex<Option<HashMap<String, Arc<Flight>>>> = Mutex::new(None);
40
41pub fn flight_key(fs: &Arc<FileStore>, zone: &str) -> String {
43 format!("{:p}:{zone}", Arc::as_ptr(fs))
44}
45
46pub fn run_once(key: String, wait: Duration, work: impl FnOnce() + Send + 'static) -> bool {
49 let (flight, starts) = {
50 let mut flights = FLIGHTS.lock().unwrap();
51 let map = flights.get_or_insert_with(HashMap::new);
52 match map.get(&key) {
53 Some(f) => (f.clone(), false),
54 None => {
55 let f = Arc::new(Flight { done: Mutex::new(false), ended: Condvar::new() });
56 map.insert(key.clone(), f.clone());
57 (f, true)
58 }
59 }
60 };
61 if starts {
62 let ending = flight.clone();
63 let spawned = std::thread::Builder::new().name("transcript-count".into()).spawn(move || {
64 work();
65 if let Some(map) = FLIGHTS.lock().unwrap().as_mut() {
67 map.remove(&key);
68 }
69 *ending.done.lock().unwrap() = true;
70 ending.ended.notify_all();
71 });
72 if let Err(e) = spawned {
73 tracing::warn!(error = %e, "transcript count: couldn't start its thread");
74 return false;
75 }
76 }
77 flight.wait(wait)
78}
79
80fn counted(fs: &FileStore, zone: &str) -> bool {
82 matches!(fs.catch_up_line_counter(zone, "output"), Ok(Some(state)) if state.counted.is_some())
83}
84
85pub fn ensure_counted(fs: &Arc<FileStore>, zone: &str, wait: Duration) -> bool {
89 if counted(fs, zone) {
90 return true;
91 }
92 let (store, name) = (fs.clone(), zone.to_string());
93 let began = std::time::Instant::now();
94 run_once(flight_key(fs, zone), wait, move || match store.init_line_counter(&name, "output") {
95 Ok(Some(_)) => tracing::info!(zone = %name, ms = began.elapsed().as_millis() as u64, "transcript count: counted"),
96 Ok(None) => tracing::info!(zone = %name, "transcript count: the file moved under the scan; the next read counts it again"),
97 Err(e) => tracing::warn!(zone = %name, error = %e, "transcript count: failed"),
98 });
99 counted(fs, zone)
100}
101
102#[cfg(test)]
103#[path = "counting_tests.rs"]
104mod tests;