Skip to main content

egui_pop_api/about/
journal.rs

1//! The journal a problem report attaches: a time window of what the
2//! application did, redacted, and the bundle `help.report` shows before
3//! anything leaves the machine.
4//!
5//! A [`Recorder`] follows the journal (`AppHandle::events_since`) once a
6//! pass and keeps the entries of the last few minutes
7//! ([`RecorderConfig::window`], 5 by default): commands and their
8//! outcomes, refusals, facts, the application's summary events. It keeps
9//! its own copy rather than reading the shared journal at report time:
10//! that journal is a ring of a fixed count, where a burst of frequent
11//! entries pushes the rare ones out; a time window keeps a rare entry as
12//! long as it is recent. Kinds that come at every pass or at a high rate
13//! are skipped ([`RecorderConfig::skip`], patterns as the journal reads
14//! them: `pop.pointer.*`, `*`).
15//!
16//! Each entry is redacted as it is kept ([`Redactor`]): a private
17//! command's arguments, result and error read `<private>`
18//! (`host::redact_private`); every string has the home folder written
19//! `~`, every other absolute path reduced to its root and its extension
20//! (`/…/*.raw`), and any secret of the environment blanked.
21//!
22//! ```
23//! use std::time::Duration;
24//! use egui_pop_api::about::journal::{Recorder, RecorderConfig, Redactor};
25//! use egui_pop_api::host::Event;
26//! use serde_json::json;
27//! use web_time::Instant;
28//!
29//! let redactor = Redactor::new(Some("/home/ann"), &[]);
30//! let mut rec = Recorder::new(RecorderConfig::default().skip("view.frame"));
31//! let t0 = Instant::now();
32//! let event = |seq, name: &str, data| Event {
33//!     seq, source: "user".into(), cause: None, name: name.into(), data,
34//! };
35//! rec.record(t0, &[
36//!     event(1, "command.dispatched", json!({ "command": "file.open", "args": { "path": "/home/ann/Photos/a.raw" } })),
37//!     event(2, "view.frame", json!(null)),
38//! ], &redactor);
39//! let kept = rec.window(t0 + Duration::from_secs(1));
40//! assert_eq!(kept.len(), 1);
41//! assert_eq!(kept[0].data["args"]["path"], "~/….raw");
42//! // Past the window, it goes.
43//! assert!(rec.window(t0 + Duration::from_secs(301)).is_empty());
44//! ```
45
46use std::collections::VecDeque;
47use std::time::Duration;
48
49use serde::Serialize;
50use serde_json::Value as Json;
51use web_time::Instant;
52
53use crate::host::{Event, Seq, redact_private};
54
55/// How long a report's journal reaches back by default.
56pub const WINDOW: Duration = Duration::from_secs(5 * 60);
57
58/// The most entries a recorder keeps, whatever their age: a bound on its
59/// memory, far above what a few minutes of skipped-free use give.
60pub const CAP: usize = 20_000;
61
62/// What stands for a secret in a report.
63pub const SECRET: &str = "[redacted]";
64
65/// What a recorder keeps and for how long.
66#[derive(Clone, Debug, PartialEq)]
67pub struct RecorderConfig {
68    /// How far back the window reaches.
69    pub window: Duration,
70    /// Kinds never kept: per-render or high-rate ones (journal patterns:
71    /// an id, a prefix ending `.*`, or `*`).
72    pub skip: Vec<String>,
73    /// The most entries kept ([`CAP`]).
74    pub cap: usize,
75}
76
77impl Default for RecorderConfig {
78    fn default() -> Self {
79        Self {
80            window: WINDOW,
81            skip: Vec::new(),
82            cap: CAP,
83        }
84    }
85}
86
87impl RecorderConfig {
88    /// How far back the window reaches (at least a second).
89    #[must_use]
90    pub fn window(mut self, window: Duration) -> Self {
91        self.window = window.max(Duration::from_secs(1));
92        self
93    }
94
95    /// A kind, or a pattern of kinds, never kept.
96    #[must_use]
97    pub fn skip(mut self, pattern: &str) -> Self {
98        self.skip.push(pattern.into());
99        self
100    }
101
102    /// The most entries kept (at least one).
103    #[must_use]
104    pub fn cap(mut self, cap: usize) -> Self {
105        self.cap = cap.max(1);
106        self
107    }
108
109    /// Whether entries of `kind` are skipped.
110    pub fn skips(&self, kind: &str) -> bool {
111        self.skip
112            .iter()
113            .any(|p| crate::bus::bus_contract_journal::kind_matches(p, kind))
114    }
115}
116
117/// An entry of a report's journal: a journal event, redacted, with its
118/// age when the report was made.
119#[derive(Clone, Debug, PartialEq, Serialize)]
120pub struct Recorded {
121    pub seq: Seq,
122    /// Milliseconds before the report.
123    pub ago_ms: u64,
124    pub source: String,
125    pub cause: Option<Seq>,
126    pub name: String,
127    pub data: Json,
128}
129
130/// The journal's recent entries, kept by time.
131#[derive(Debug)]
132pub struct Recorder {
133    config: RecorderConfig,
134    entries: VecDeque<(Instant, Event)>,
135    /// The last sequence number seen.
136    last: Seq,
137    /// Entries the recorder never saw: the journal dropped them between
138    /// two reads.
139    missed: u64,
140    /// Entries let go for the cap, not for their age.
141    capped: u64,
142}
143
144impl Recorder {
145    pub fn new(config: RecorderConfig) -> Self {
146        Self {
147            config,
148            entries: VecDeque::new(),
149            last: 0,
150            missed: 0,
151            capped: 0,
152        }
153    }
154
155    pub fn config(&self) -> &RecorderConfig {
156        &self.config
157    }
158
159    /// The last sequence number seen: the next read starts after it.
160    pub fn last(&self) -> Seq {
161        self.last
162    }
163
164    /// Entries the recorder never saw (the journal had dropped them
165    /// before it read) and entries let go for the cap.
166    pub fn lost(&self) -> (u64, u64) {
167        (self.missed, self.capped)
168    }
169
170    /// Keeps the events read at `now` (oldest first) that are not
171    /// skipped, redacted, and lets go of those past the window.
172    pub fn record(&mut self, now: Instant, events: &[Event], redactor: &Redactor) {
173        for e in events {
174            if e.seq <= self.last {
175                continue;
176            }
177            // The first read takes what the journal still has; after it,
178            // a hole in the numbers is entries dropped before this read.
179            if self.last > 0 && e.seq > self.last + 1 {
180                self.missed += e.seq - self.last - 1;
181            }
182            self.last = e.seq;
183            if self.config.skips(&e.name) {
184                continue;
185            }
186            if self.entries.len() >= self.config.cap {
187                self.entries.pop_front();
188                self.capped += 1;
189            }
190            self.entries.push_back((now, redactor.event(e)));
191        }
192        self.prune(now);
193    }
194
195    /// Lets go of the entries past the window.
196    pub fn prune(&mut self, now: Instant) {
197        let window = self.config.window;
198        while let Some((at, _)) = self.entries.front() {
199            if now.saturating_duration_since(*at) > window {
200                self.entries.pop_front();
201            } else {
202                break;
203            }
204        }
205    }
206
207    /// The entries of the window at `now`, oldest first.
208    pub fn window(&self, now: Instant) -> Vec<Recorded> {
209        let window = self.config.window;
210        self.entries
211            .iter()
212            .filter(|(at, _)| now.saturating_duration_since(*at) <= window)
213            .map(|(at, e)| Recorded {
214                seq: e.seq,
215                ago_ms: u64::try_from(now.saturating_duration_since(*at).as_millis())
216                    .unwrap_or(u64::MAX),
217                source: e.source.clone(),
218                cause: e.cause,
219                name: e.name.clone(),
220                data: e.data.clone(),
221            })
222            .collect()
223    }
224}
225
226/// Hides what a report must not carry: private commands' data, the home
227/// folder's name, absolute paths, the environment's secrets.
228#[derive(Clone, Debug, Default, PartialEq)]
229pub struct Redactor {
230    /// Written `~`.
231    home: Option<String>,
232    /// Values never written, wherever they appear.
233    secrets: Vec<String>,
234}
235
236impl Redactor {
237    /// A redactor writing `home` as `~` and blanking `secrets` (values
238    /// shorter than 8 characters are too common to blank and are left).
239    pub fn new(home: Option<&str>, secrets: &[&str]) -> Self {
240        let home = home
241            .map(|h| h.trim_end_matches(['/', '\\']).to_string())
242            .filter(|h| !h.is_empty());
243        let mut secrets: Vec<String> = secrets
244            .iter()
245            .map(|s| s.trim().to_string())
246            .filter(|s| s.len() >= 8)
247            .collect();
248        // The longest first, so one inside another is blanked whole.
249        secrets.sort_by_key(|s| std::cmp::Reverse(s.len()));
250        Self { home, secrets }
251    }
252
253    /// From an environment: its home folder, and the values of its
254    /// variables named like a secret (a token, a key, a password, a
255    /// client id or secret, a credential).
256    pub fn from_env(vars: &[(String, String)], home: Option<&str>) -> Self {
257        let secrets: Vec<&str> = vars
258            .iter()
259            .filter(|(n, _)| secret_name(n))
260            .map(|(_, v)| v.as_str())
261            .collect();
262        Self::new(home, &secrets)
263    }
264
265    /// This process's environment (no home and no variables on the web).
266    pub fn current() -> Self {
267        #[cfg(not(target_arch = "wasm32"))]
268        {
269            let vars: Vec<(String, String)> = std::env::vars().collect();
270            let home = std::env::home_dir();
271            Self::from_env(&vars, home.as_deref().and_then(|h| h.to_str()))
272        }
273        #[cfg(target_arch = "wasm32")]
274        {
275            Self::default()
276        }
277    }
278
279    /// A journal event, redacted: a private command's data hidden, then
280    /// every string of its data and its source scrubbed.
281    pub fn event(&self, e: &Event) -> Event {
282        let mut v = serde_json::json!({ "seq": e.seq, "name": e.name, "data": e.data });
283        redact_private(&mut v);
284        let mut data = v.get_mut("data").map(Json::take).unwrap_or(Json::Null);
285        self.json(&mut data);
286        Event {
287            seq: e.seq,
288            source: self.text(&e.source),
289            cause: e.cause,
290            name: e.name.clone(),
291            data,
292        }
293    }
294
295    /// Scrubs every string of `v`, keys included.
296    pub fn json(&self, v: &mut Json) {
297        match v {
298            Json::String(s) => *s = self.value(s),
299            Json::Array(items) => items.iter_mut().for_each(|x| self.json(x)),
300            Json::Object(o) => {
301                let taken = std::mem::take(o);
302                for (k, mut x) in taken {
303                    self.json(&mut x);
304                    o.insert(self.text(&k), x);
305                }
306            }
307            _ => {}
308        }
309    }
310
311    /// A string value: reduced whole when it is one path alone (spaces
312    /// in its names do not end it), else as [`Redactor::text`].
313    pub fn value(&self, value: &str) -> String {
314        let v = value.trim();
315        let b = v.as_bytes();
316        let drive = b.len() > 3
317            && b[0].is_ascii_alphabetic()
318            && b[1] == b':'
319            && (b[2] == b'\\' || b[2] == b'/');
320        let rooted = v.starts_with("file:")
321            || v.starts_with("~/")
322            || v.starts_with("~\\")
323            || (v.starts_with('/') && v.len() > 1)
324            || drive;
325        if rooted && !v.contains(['\n', '"']) && !v.contains(": ") {
326            let masked = self.unsecret(v).replace(' ', "\u{1}");
327            return scrub_paths(&masked).replace('\u{1}', " ");
328        }
329        self.text(value)
330    }
331
332    /// `text` with no secret and the home folder written `~`.
333    fn unsecret(&self, text: &str) -> String {
334        let mut out = text.to_string();
335        for s in &self.secrets {
336            if out.contains(s.as_str()) {
337                out = out.replace(s.as_str(), SECRET);
338            }
339        }
340        match &self.home {
341            Some(home) => home_to_tilde(&out, home),
342            None => out,
343        }
344    }
345
346    /// `text` with no secret, the home folder written `~` and every
347    /// absolute path reduced to its root and its extension.
348    pub fn text(&self, text: &str) -> String {
349        scrub_paths(&self.unsecret(text))
350    }
351}
352
353/// A variable whose value is a secret, or close enough to one never to be
354/// copied.
355fn secret_name(name: &str) -> bool {
356    let n = name.to_ascii_uppercase();
357    [
358        "TOKEN",
359        "SECRET",
360        "CLIENT_ID",
361        "PASSWORD",
362        "PASSWD",
363        "KEY",
364        "CREDENTIAL",
365        "AUTH",
366    ]
367    .iter()
368    .any(|s| n.contains(s))
369}
370
371/// `home` written `~`, only as a whole folder (`/home/ann` in
372/// `/home/ann/x`, not in `/home/anna`).
373fn home_to_tilde(text: &str, home: &str) -> String {
374    let mut out = String::with_capacity(text.len());
375    let mut rest = text;
376    while let Some(at) = rest.find(home) {
377        let after = &rest[at + home.len()..];
378        out.push_str(&rest[..at]);
379        if after.is_empty()
380            || after.starts_with(['/', '\\', ' ', '"', '\'', ')', ',', ':', ';', '\n'])
381        {
382            out.push('~');
383        } else {
384            out.push_str(home);
385        }
386        rest = after;
387    }
388    out.push_str(rest);
389    out
390}
391
392/// Where a path may start: the text's start or after one of these.
393fn boundary(c: Option<char>) -> bool {
394    c.is_none_or(|c| c.is_whitespace() || matches!(c, '"' | '\'' | '(' | '[' | '=' | '<' | ','))
395}
396
397/// Where a path ends: whitespace, a quote, a closing bracket, a comma, or
398/// a colon or a semicolon before whitespace or the end.
399fn path_end(s: &str) -> usize {
400    let mut chars = s.char_indices().peekable();
401    while let Some((i, c)) = chars.next() {
402        let next = chars.peek().map(|(_, c)| *c);
403        let stop = c.is_whitespace()
404            || matches!(c, '"' | '\'' | ')' | ']' | '>' | ',')
405            || (matches!(c, ':' | ';') && next.is_none_or(char::is_whitespace));
406        if stop {
407            return i;
408        }
409    }
410    s.len()
411}
412
413/// A path reduced to its root and its file's extension: `~/….raw`,
414/// `/…`, `C:/…​.jpg`.
415fn reduced(root: &str, path: &str) -> String {
416    let file = path.rsplit(['/', '\\']).next().unwrap_or("");
417    let ext = file
418        .rsplit_once('.')
419        .filter(|(stem, ext)| !stem.is_empty() && !ext.is_empty() && ext.len() <= 5)
420        .map(|(_, ext)| format!(".{ext}"))
421        .unwrap_or_default();
422    format!("{root}/…{ext}")
423}
424
425/// Every absolute path of `text` reduced ([`reduced`]): `/…`, `~/…`,
426/// `file:` URLs, Windows drives (`C:\…`); a bare `/` or `~` is left.
427fn scrub_paths(text: &str) -> String {
428    let mut out = String::with_capacity(text.len());
429    let mut prev: Option<char> = None;
430    let mut i = 0;
431    while i < text.len() {
432        let rest = &text[i..];
433        let c = rest.chars().next().unwrap_or(' ');
434        if boundary(prev) {
435            // `file:` URLs, then the path they hold.
436            let (prefix, body) = match rest.strip_prefix("file://") {
437                Some(b) => ("file://", b),
438                None => match rest.strip_prefix("file:") {
439                    Some(b) => ("file:", b),
440                    None => ("", rest),
441                },
442            };
443            let root = if body.starts_with("~/") || body.starts_with("~\\") {
444                Some(("~", 1))
445            } else if body.starts_with('/')
446                && body[1..].chars().next().is_some_and(|c| !c.is_whitespace())
447            {
448                Some(("", 0))
449            } else {
450                let b = body.as_bytes();
451                (b.len() > 3
452                    && b[0].is_ascii_alphabetic()
453                    && b[1] == b':'
454                    && (b[2] == b'\\' || b[2] == b'/'))
455                    .then(|| (&body[..2], 2))
456            };
457            if let Some((root, skip)) = root {
458                let end = path_end(body);
459                if end > skip + 1 {
460                    out.push_str(prefix);
461                    out.push_str(&reduced(root, &body[..end]));
462                    i += prefix.len() + end;
463                    prev = Some('…');
464                    continue;
465                }
466            }
467        }
468        out.push(c);
469        prev = Some(c);
470        i += c.len_utf8();
471    }
472    out
473}
474
475/// Says whether a token (a run of letters and digits) is an id to alias.
476pub type AliasFn = dyn Fn(&str) -> bool;
477
478/// Ids replaced by aliases numbered in order of appearance (`photo-1`,
479/// `photo-2`…): the same id gets the same alias across a report, so
480/// entries still tie together, and an id that is a fingerprint (a
481/// content hash, an account id) never leaves the machine.
482pub struct Aliases<'a> {
483    prefix: &'a str,
484    matches: &'a AliasFn,
485    seen: std::collections::HashMap<String, usize>,
486}
487
488impl std::fmt::Debug for Aliases<'_> {
489    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
490        f.debug_struct("Aliases")
491            .field("prefix", &self.prefix)
492            .field("seen", &self.seen.len())
493            .finish_non_exhaustive()
494    }
495}
496
497impl<'a> Aliases<'a> {
498    pub fn new(prefix: &'a str, matches: &'a AliasFn) -> Self {
499        Self {
500            prefix,
501            matches,
502            seen: std::collections::HashMap::new(),
503        }
504    }
505
506    /// How many ids were aliased.
507    pub fn len(&self) -> usize {
508        self.seen.len()
509    }
510
511    pub fn is_empty(&self) -> bool {
512        self.seen.is_empty()
513    }
514
515    /// `text` with each matching token replaced by its alias.
516    pub fn text(&mut self, text: &str) -> String {
517        let mut out = String::with_capacity(text.len());
518        let mut token = String::new();
519        let flush = |token: &mut String, out: &mut String, me: &mut Self| {
520            if token.is_empty() {
521                return;
522            }
523            if (me.matches)(token) {
524                let n = me.seen.len() + 1;
525                let n = *me.seen.entry(std::mem::take(token)).or_insert(n);
526                out.push_str(&format!("{}-{n}", me.prefix));
527            } else {
528                out.push_str(token);
529                token.clear();
530            }
531        };
532        for c in text.chars() {
533            if c.is_ascii_alphanumeric() {
534                token.push(c);
535            } else {
536                flush(&mut token, &mut out, self);
537                out.push(c);
538            }
539        }
540        flush(&mut token, &mut out, self);
541        out
542    }
543
544    /// Every string of `v`, keys included, aliased.
545    pub fn json(&mut self, v: &mut Json) {
546        match v {
547            Json::String(s) => *s = self.text(s),
548            Json::Array(items) => items.iter_mut().for_each(|x| self.json(x)),
549            Json::Object(o) => {
550                let taken = std::mem::take(o);
551                for (k, mut x) in taken {
552                    let k = self.text(&k);
553                    self.json(&mut x);
554                    o.insert(k, x);
555                }
556            }
557            _ => {}
558        }
559    }
560}
561
562/// What a problem report attaches: shown to the user before anything
563/// leaves the machine ([`Bundle::text`]).
564#[derive(Clone, Debug, PartialEq, Serialize)]
565pub struct Bundle {
566    /// The version info, without its platform line.
567    pub version: String,
568    pub platform: String,
569    /// The page or view shown, when the application says.
570    pub page: Option<String>,
571    /// How far back the journal reaches, in seconds.
572    pub window_s: u64,
573    /// Entries the recorder never saw (dropped by the journal between
574    /// two reads) and entries let go for its cap: a report with either
575    /// may lack the cause.
576    pub missed: u64,
577    pub capped: u64,
578    /// The journal's window, oldest first, redacted.
579    pub journal: Vec<Recorded>,
580    /// The application's context, by name, redacted.
581    pub context: std::collections::BTreeMap<String, Json>,
582    /// The bus's points and their listeners' order.
583    pub bus: Json,
584}
585
586impl Bundle {
587    /// The report as the user reads and pastes it: a fenced JSON block.
588    pub fn text(&self) -> String {
589        let json = serde_json::to_string_pretty(self).unwrap_or_default();
590        format!(
591            "<details><summary>Diagnostic report</summary>\n\n```json\n{json}\n```\n</details>\n"
592        )
593    }
594}
595
596/// The bus's points and the order of each one's listeners, for a report
597/// (ids only: no input and no value).
598pub fn bus_description(bus: &dyn bus_contract::Bus) -> Json {
599    let mut points: Vec<_> = bus.points();
600    points.sort_by_key(|p| p.id);
601    let mut out = serde_json::Map::new();
602    for p in points {
603        let listeners: Vec<String> = bus
604            .listeners(p.id)
605            .unwrap_or_default()
606            .into_iter()
607            .map(|l| l.id)
608            .collect();
609        out.insert(
610            p.id.to_string(),
611            serde_json::json!({ "kind": format!("{:?}", p.kind), "listeners": listeners }),
612        );
613    }
614    Json::Object(out)
615}
616
617#[cfg(test)]
618mod tests {
619    use super::*;
620    use serde_json::json;
621
622    fn ann() -> Redactor {
623        Redactor::new(Some("/home/ann"), &["tok-56789012"])
624    }
625
626    fn ev(seq: Seq, name: &str, data: Json) -> Event {
627        Event {
628            seq,
629            source: "user".into(),
630            cause: None,
631            name: name.into(),
632            data,
633        }
634    }
635
636    #[test]
637    fn paths_keep_their_root_and_extension_only() {
638        let r = ann();
639        // In free text a space ends a path; a value that is one path is
640        // reduced whole.
641        assert_eq!(
642            r.text("/home/ann/Photos/Jane wedding.raw"),
643            "~/… wedding.raw"
644        );
645        assert_eq!(r.value("/home/ann/Photos/Jane wedding.raw"), "~/….raw");
646        assert_eq!(r.value("not a path: /home/ann/x y"), "not a path: ~/… y");
647        assert_eq!(
648            r.text("/home/ann/Photos/a.raw: unreadable"),
649            "~/….raw: unreadable"
650        );
651        assert_eq!(r.text("/home/anna/b.jpg"), "/….jpg");
652        assert_eq!(r.text("file:/home/ann/x"), "file:~/…");
653        assert_eq!(r.text("file:///mnt/card/DCIM"), "file:///…");
654        assert_eq!(r.text("C:\\Users\\Ann\\c.NEF"), "C:/….NEF");
655        assert_eq!(
656            r.text("open \"/run/media/ann/CARD\" now"),
657            "open \"/…\" now"
658        );
659        // Not paths: a URL's slashes, a ratio, a lone slash, a relative path.
660        assert_eq!(r.text("https://github.com/o/r"), "https://github.com/o/r");
661        assert_eq!(r.text("1/2 and a / b"), "1/2 and a / b");
662        assert_eq!(r.text("photos/2024"), "photos/2024");
663        assert_eq!(r.text("~"), "~");
664    }
665
666    #[test]
667    fn secrets_are_blanked_and_short_values_left() {
668        let r = Redactor::from_env(
669            &[
670                ("SOME_TOKEN".into(), "tok-56789012".into()),
671                ("API_KEY".into(), "short".into()),
672                ("LANG".into(), "fr_FR.UTF-8".into()),
673            ],
674            None,
675        );
676        assert_eq!(r.text("sent tok-56789012 to x"), "sent [redacted] to x");
677        assert_eq!(r.text("short fr_FR.UTF-8"), "short fr_FR.UTF-8");
678    }
679
680    #[test]
681    fn a_private_command_reads_private_and_strings_are_scrubbed() {
682        let r = ann();
683        let e = r.event(&ev(
684            4,
685            "command.done",
686            json!({ "command": "accounts.connect", "result": "ann@example.org", "private": true }),
687        ));
688        assert_eq!(e.data["result"], crate::host::REDACTED);
689        let e = r.event(&ev(
690            5,
691            "image.refused",
692            json!({ "why": "locked: /home/ann/a.raw", "/home/ann/k": [ "/srv/x.tif" ] }),
693        ));
694        assert_eq!(e.data["why"], "locked: ~/….raw");
695        assert_eq!(e.data["~/…"][0], "/….tif");
696    }
697
698    #[test]
699    fn the_window_is_by_time_and_skipped_kinds_never_enter() {
700        let mut rec = Recorder::new(
701            RecorderConfig::default()
702                .window(Duration::from_secs(60))
703                .skip("view.*"),
704        );
705        let t0 = Instant::now();
706        let r = Redactor::default();
707        rec.record(t0, &[ev(1, "engine.gpu_lost", json!(null))], &r);
708        // A burst of frequent kinds does not push the rare one out.
709        let burst: Vec<Event> = (2..3000).map(|n| ev(n, "view.frame", json!(n))).collect();
710        rec.record(t0 + Duration::from_secs(10), &burst, &r);
711        let w = rec.window(t0 + Duration::from_secs(30));
712        assert_eq!(w.len(), 1);
713        assert_eq!(w[0].name, "engine.gpu_lost");
714        assert_eq!(w[0].ago_ms, 30_000);
715        assert_eq!(rec.last(), 2999);
716        // Past the window.
717        rec.prune(t0 + Duration::from_secs(61));
718        assert!(rec.window(t0 + Duration::from_secs(61)).is_empty());
719    }
720
721    #[test]
722    fn ids_get_one_alias_each_in_order_of_appearance() {
723        let hex = |t: &str| t.len() == 8 && t.chars().all(|c| c.is_ascii_hexdigit());
724        let mut a = Aliases::new("photo", &hex);
725        let mut v = json!([
726            { "image": "deadbeef" },
727            { "image": "0badf00d", "text": "after deadbeef, cafe" },
728            { "deadbeef": 1 },
729        ]);
730        a.json(&mut v);
731        assert_eq!(v[0]["image"], "photo-1");
732        assert_eq!(v[1]["image"], "photo-2");
733        assert_eq!(v[1]["text"], "after photo-1, cafe");
734        assert_eq!(v[2]["photo-1"], 1);
735        assert_eq!(a.len(), 2);
736    }
737
738    #[test]
739    fn entries_dropped_between_reads_are_counted() {
740        let mut rec = Recorder::new(RecorderConfig::default().cap(2));
741        let t = Instant::now();
742        let r = Redactor::default();
743        rec.record(t, &[ev(10, "a", json!(1))], &r);
744        rec.record(t, &[ev(14, "b", json!(1)), ev(15, "c", json!(1))], &r);
745        assert_eq!(rec.lost(), (3, 1));
746        let names: Vec<_> = rec.window(t).into_iter().map(|e| e.name).collect();
747        assert_eq!(names, ["b", "c"]);
748    }
749}