Skip to main content

agentmux_srv_core/backend/audit_query/
ordered.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A file's entries in time order (the jekt audit file's, or an activity day's). Several srvs append to the file, each stamping its entries when it
5//! queues them, so the file is in time order only to within a short skew. Read from its end, a line is given only
6//! once every line not yet read must be older: a window of the newest lines is held and sorted.
7
8use std::collections::BinaryHeap;
9
10use crate::backend::rpc_types::AuditEntry;
11
12/// How far out of time order two lines of the file may be.
13const SKEW_MS: u64 = 60_000;
14
15struct Held {
16    entry: AuditEntry,
17    /// Where the next line after this one starts.
18    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
44/// The lines of the file, newest first, mapped to entries and kept if `keep` says so.
45pub(super) struct Ordered<'a, T> {
46    lines: Box<dyn Iterator<Item = (u64, u64, T)> + 'a>,
47    /// The time of a line, to stop at the window's start.
48    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    /// Lines older than this need not be read.
52    since: u64,
53    /// Entries at or past this were given already (by the page before).
54    after: Option<(u64, String)>,
55    held: BinaryHeap<Held>,
56    /// The oldest time read so far, and where the oldest line read starts.
57    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    /// Reads until the newest held entry can be given: no line left unread can be newer.
75    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    /// Where reading starts again to meet every entry not given yet: after the last line held, or where the
113    /// oldest line read starts when none is held; `from` when nothing was read.
114    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}