agentmux_srv_core/backend/transcript/
origin_ledger.rs1use std::sync::atomic::{AtomicUsize, Ordering};
19use std::sync::OnceLock;
20use std::time::{Duration, Instant};
21
22use crate::backend::message_origin::RecordOrigin;
23
24pub const KEEP: Duration = Duration::from_secs(600);
27
28pub const PER_BLOCK: usize = 64;
30
31struct Expected {
32 block_id: String,
33 text: String,
34 record: RecordOrigin,
35 at: Instant,
36}
37
38static EXPECTED: OnceLock<parking_lot::Mutex<Vec<Expected>>> = OnceLock::new();
39static WAITING: AtomicUsize = AtomicUsize::new(0);
41
42fn expected() -> &'static parking_lot::Mutex<Vec<Expected>> {
43 EXPECTED.get_or_init(|| parking_lot::Mutex::new(Vec::new()))
44}
45
46fn prune(list: &mut Vec<Expected>, now: Instant) {
47 list.retain(|e| now.duration_since(e.at) < KEEP);
48 WAITING.store(list.len(), Ordering::Release);
49}
50
51pub fn expect(block_id: &str, text: &str, record: RecordOrigin) {
53 let mut list = expected().lock();
54 let now = Instant::now();
55 prune(&mut list, now);
56 if list.iter().filter(|e| e.block_id == block_id).count() >= PER_BLOCK {
57 if let Some(oldest) = list.iter().position(|e| e.block_id == block_id) {
58 list.remove(oldest);
59 }
60 }
61 list.push(Expected { block_id: block_id.to_string(), text: text.trim().to_string(), record, at: now });
62 WAITING.store(list.len(), Ordering::Release);
63}
64
65pub fn take(block_id: &str, text: &str) -> Option<RecordOrigin> {
68 if WAITING.load(Ordering::Acquire) == 0 {
69 return None;
70 }
71 let text = text.trim();
72 let mut list = expected().lock();
73 prune(&mut list, Instant::now());
74 let at = list.iter().position(|e| e.block_id == block_id && e.text == text)?;
75 let record = list.remove(at).record;
76 WAITING.store(list.len(), Ordering::Release);
77 Some(record)
78}
79
80#[cfg(test)]
81#[path = "origin_ledger_tests.rs"]
82mod tests;