agentmux_srv_core/backend/audit_query/
ordered.rs1use std::collections::BinaryHeap;
9
10use crate::backend::rpc_types::AuditEntry;
11
12const SKEW_MS: u64 = 60_000;
14
15struct Held {
16 entry: AuditEntry,
17 end: u64,
19}
20
21impl Held {
22 fn key(&self) -> (u64, &str) {
23 (self.entry.ts_ms, self.entry.id.as_str())
24 }
25}
26
27impl PartialEq for Held {
28 fn eq(&self, other: &Self) -> bool {
29 self.key() == other.key()
30 }
31}
32impl Eq for Held {}
33impl PartialOrd for Held {
34 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
35 Some(self.cmp(other))
36 }
37}
38impl Ord for Held {
39 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
40 self.key().cmp(&other.key())
41 }
42}
43
44pub(super) struct Ordered<'a, T> {
46 lines: Box<dyn Iterator<Item = (u64, u64, T)> + 'a>,
47 stamp: Box<dyn Fn(&T) -> u64 + 'a>,
49 map: Box<dyn Fn(u64, &T) -> AuditEntry + 'a>,
50 keep: Box<dyn Fn(&AuditEntry) -> bool + 'a>,
51 since: u64,
53 after: Option<(u64, String)>,
55 held: BinaryHeap<Held>,
56 oldest_ms: u64,
58 oldest_start: Option<u64>,
59 done: bool,
60}
61
62impl<'a, T> Ordered<'a, T> {
63 pub fn new(
64 lines: impl Iterator<Item = (u64, u64, T)> + 'a,
65 stamp: impl Fn(&T) -> u64 + 'a,
66 map: impl Fn(u64, &T) -> AuditEntry + 'a,
67 keep: impl Fn(&AuditEntry) -> bool + 'a,
68 since: u64,
69 after: Option<(u64, String)>,
70 ) -> Self {
71 Self { lines: Box::new(lines), stamp: Box::new(stamp), map: Box::new(map), keep: Box::new(keep), since, after, held: BinaryHeap::new(), oldest_ms: u64::MAX, oldest_start: None, done: false }
72 }
73
74 fn fill(&mut self) {
76 loop {
77 if self.held.peek().is_some_and(|top| self.done || top.entry.ts_ms >= self.oldest_ms.saturating_add(SKEW_MS)) {
78 return;
79 }
80 if self.done {
81 return;
82 }
83 let Some((start, end, raw)) = self.lines.next() else {
84 self.done = true;
85 continue;
86 };
87 let at = (self.stamp)(&raw);
88 if at.saturating_add(SKEW_MS) < self.since {
89 self.done = true;
90 continue;
91 }
92 self.oldest_ms = self.oldest_ms.min(at);
93 self.oldest_start = Some(start);
94 let entry = (self.map)(start, &raw);
95 let fresh = self.after.as_ref().is_none_or(|(ts, id)| (entry.ts_ms, entry.id.as_str()) < (*ts, id.as_str()));
96 if fresh && (self.keep)(&entry) {
97 self.held.push(Held { entry, end });
98 }
99 }
100 }
101
102 pub fn peek(&mut self) -> Option<&AuditEntry> {
103 self.fill();
104 self.held.peek().map(|h| &h.entry)
105 }
106
107 pub fn pop(&mut self) -> Option<AuditEntry> {
108 self.fill();
109 self.held.pop().map(|h| h.entry)
110 }
111
112 pub fn resume(&self, from: Option<u64>) -> Option<u64> {
115 self.held.iter().map(|h| h.end).max().or(self.oldest_start).or(from)
116 }
117}