Skip to main content

icedwright_trace/
normalise.rs

1//! Rewrites of text that would otherwise differ between runs, and the limits on its size.
2
3use std::time::{Duration, Instant};
4
5use icedwright_types::VirtualDuration;
6
7/// The longest message `Debug` text kept, in bytes.
8pub(crate) const MESSAGE_LIMIT: usize = 4 * 1024;
9
10/// The largest state `Debug` text diffed, in bytes.
11pub(crate) const STATE_LIMIT: usize = 256 * 1024;
12
13/// The real instant the harness booted at, as the platform's `Instant` `Debug` text spells it,
14/// so instants printed inside message text can be rewritten as offsets from boot.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub struct BootInstant(Duration);
17
18impl BootInstant {
19    /// Reads `instant`'s `Debug` form, or `None` on a platform that prints it without
20    /// `tv_sec` and `tv_nsec`.
21    #[must_use]
22    pub fn from_std(instant: &Instant) -> Option<Self> {
23        Self::from_debug(&format!("{instant:?}"))
24    }
25
26    /// Reads an `Instant` `Debug` text such as `Instant { tv_sec: 5, tv_nsec: 20 }`.
27    #[must_use]
28    pub fn from_debug(text: &str) -> Option<Self> {
29        let body = text.trim().strip_prefix("Instant")?;
30        stamp(body).map(Self)
31    }
32}
33
34/// The `tv_sec` and `tv_nsec` fields anywhere in `body`, as a duration.
35fn stamp(body: &str) -> Option<Duration> {
36    let secs = field(body, "tv_sec:")?;
37    let nanos = field(body, "tv_nsec:")?;
38    Some(Duration::new(secs, u32::try_from(nanos).ok()?))
39}
40
41fn field(body: &str, name: &str) -> Option<u64> {
42    let start = body.find(name)? + name.len();
43    let rest = body.get(start..)?.trim_start();
44    let end = rest
45        .find(|c: char| !c.is_ascii_digit())
46        .unwrap_or(rest.len());
47    rest.get(..end)?.parse().ok()
48}
49
50/// Replaces every `Instant { .. }` that holds `tv_sec` and `tv_nsec` with `@+<offset>` from
51/// `boot`, or `@-<offset>` for one before it. Nested forms such as tokio's
52/// `Instant { std: Instant { .. } }` are replaced whole.
53pub(crate) fn rewrite_instants(text: &str, boot: BootInstant) -> String {
54    let mut out = String::with_capacity(text.len());
55    let mut rest = text;
56    while let Some(found) = rest.find("Instant") {
57        let (before, from) = rest.split_at(found);
58        out.push_str(before);
59        let follows_word = before
60            .chars()
61            .next_back()
62            .is_some_and(|c| c.is_alphanumeric() || c == '_');
63        let replaced = (!follows_word)
64            .then(|| braced(&from["Instant".len()..]))
65            .flatten()
66            .and_then(|(body, len)| stamp(body).map(|at| (at, len)));
67        let Some((at, len)) = replaced else {
68            out.push_str("Instant");
69            rest = &from["Instant".len()..];
70            continue;
71        };
72        match at.checked_sub(boot.0) {
73            Some(after) => out.push_str(&format!("@+{}", VirtualDuration::from(after))),
74            None => out.push_str(&format!("@-{}", VirtualDuration::from(boot.0 - at))),
75        }
76        rest = &from["Instant".len() + len..];
77    }
78    out.push_str(rest);
79    out
80}
81
82/// The balanced `{ .. }` at the start of `text` after optional spaces: its contents and the
83/// length consumed.
84fn braced(text: &str) -> Option<(&str, usize)> {
85    let open = text.len() - text.trim_start().len();
86    if !text.get(open..)?.starts_with('{') {
87        return None;
88    }
89    let mut depth = 0usize;
90    for (offset, c) in text.get(open..)?.char_indices() {
91        match c {
92            '{' => depth += 1,
93            '}' => {
94                depth -= 1;
95                if depth == 0 {
96                    let end = open + offset;
97                    return Some((text.get(open + 1..end)?, end + 1));
98                }
99            }
100            _ => {}
101        }
102    }
103    None
104}
105
106/// `text` cut to at most `limit` bytes on a character boundary, with the original length when
107/// it was cut.
108pub(crate) fn truncate(mut text: String, limit: usize) -> (String, Option<u64>) {
109    if text.len() <= limit {
110        return (text, None);
111    }
112    let full = u64::try_from(text.len()).unwrap_or(u64::MAX);
113    let mut end = limit;
114    while !text.is_char_boundary(end) {
115        end -= 1;
116    }
117    text.truncate(end);
118    (text, Some(full))
119}
120
121/// A unified line diff from `before` to `after`, `None` when they are equal, or a note when
122/// either is larger than [`STATE_LIMIT`].
123pub(crate) fn state_diff(before: &str, after: &str) -> Option<String> {
124    if before == after {
125        return None;
126    }
127    let largest = before.len().max(after.len());
128    if largest > STATE_LIMIT {
129        return Some(format!(
130            "state Debug output is {largest} bytes, over the {} KiB limit, so no diff is kept",
131            STATE_LIMIT / 1024
132        ));
133    }
134    Some(
135        similar::TextDiff::from_lines(before, after)
136            .unified_diff()
137            .context_radius(3)
138            .header("before", "after")
139            .to_string(),
140    )
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    fn boot() -> Option<BootInstant> {
148        BootInstant::from_debug("Instant { tv_sec: 100, tv_nsec: 500000000 }")
149    }
150
151    #[test]
152    fn boot_reads_the_debug_form() {
153        assert_eq!(boot(), Some(BootInstant(Duration::new(100, 500_000_000))));
154        assert_eq!(BootInstant::from_debug("Instant { t: 12 }"), None);
155        assert_eq!(
156            BootInstant::from_debug("Moment { tv_sec: 1, tv_nsec: 2 }"),
157            None
158        );
159    }
160
161    #[test]
162    fn instants_become_offsets_from_boot() {
163        let Some(boot) = boot() else {
164            panic!("boot did not parse");
165        };
166        let text = "Tick(Instant { tv_sec: 101, tv_nsec: 750000000 }, Instant { tv_sec: 100, tv_nsec: 500000000 })";
167        assert_eq!(rewrite_instants(text, boot), "Tick(@+1.250s, @+0.000s)");
168    }
169
170    #[test]
171    fn pretty_and_nested_instants_are_rewritten_whole() {
172        let Some(boot) = boot() else {
173            panic!("boot did not parse");
174        };
175        let pretty =
176            "Tick(\n    Instant {\n        tv_sec: 102,\n        tv_nsec: 500000000,\n    },\n)";
177        assert_eq!(rewrite_instants(pretty, boot), "Tick(\n    @+2.000s,\n)");
178        let tokio = "At(Instant { std: Instant { tv_sec: 100, tv_nsec: 600000000 } })";
179        assert_eq!(rewrite_instants(tokio, boot), "At(@+0.100s)");
180        let early = "Instant { tv_sec: 100, tv_nsec: 0 }";
181        assert_eq!(rewrite_instants(early, boot), "@-0.500s");
182    }
183
184    #[test]
185    fn other_text_is_left_alone() {
186        let Some(boot) = boot() else {
187            panic!("boot did not parse");
188        };
189        let cases = [
190            "Saved(\"Instant\")",
191            "LastInstant { tv_sec: 1, tv_nsec: 2 }",
192            "Instant { label: 3 }",
193            "Instant { tv_sec: 1",
194            "Id(3) and Instant",
195        ];
196        for text in cases {
197            assert_eq!(rewrite_instants(text, boot), text);
198        }
199    }
200
201    #[test]
202    fn truncation_respects_character_boundaries() {
203        assert_eq!(truncate("short".to_owned(), 8), ("short".to_owned(), None));
204        assert_eq!(
205            truncate("abcdef".to_owned(), 4),
206            ("abcd".to_owned(), Some(6))
207        );
208        assert_eq!(truncate("aƩ".to_owned(), 2), ("a".to_owned(), Some(3)));
209    }
210
211    #[test]
212    fn state_diffs_are_unified_and_limited() {
213        assert_eq!(state_diff("same", "same"), None);
214        let before = "State {\n    count: 1,\n    name: \"a\",\n}\n";
215        let after = "State {\n    count: 2,\n    name: \"a\",\n}\n";
216        assert_eq!(
217            state_diff(before, after).as_deref(),
218            Some(
219                "--- before\n+++ after\n@@ -1,4 +1,4 @@\n State {\n-    count: 1,\n+    count: 2,\n     name: \"a\",\n }\n"
220            )
221        );
222        let huge = "x".repeat(STATE_LIMIT + 1);
223        let note = state_diff("", &huge).unwrap_or_default();
224        assert!(note.contains("over the 256 KiB limit"), "{note}");
225    }
226}