nmbrs_runtime/readouts/snapshot.rs
1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Snapshot capture for readout renders. See SRD-63 §6.
5//!
6//! Each event fire captures the rendered output (both
7//! styled and ANSI-stripped) and persists to the session
8//! db's `readout_snapshots` table. The latest render per
9//! `(slot, subject_kind, subject_id, readout_name, lod)`
10//! tuple wins — insert-or-replace upsert keeps the row
11//! count bounded by the scenario tree size.
12//!
13//! Push 6 ships:
14//!
15//! - [`strip_ansi`] — utility that turns the styled byte
16//! stream into the plain-text fallback column.
17//! - [`capture`] — takes one rendered body (e.g. a
18//! [`StringSink`](super::StringSink)'s output), derives
19//! the plain-text column from it, and hands the
20//! `(ansi_bytes, plain_text)` pair to the sqlite writer
21//! behind a [`SnapshotWriter`].
22//! - The
23//! [`SqliteReporter::upsert_readout_snapshot`](nmbrs_metrics::reporters::sqlite::SqliteReporter::upsert_readout_snapshot)
24//! surface in `nmbrs-metrics::reporters::sqlite` is the
25//! actual store.
26//!
27//! Wiring the capture into `nmbrs-runtime::activity`'s
28//! per-event fire sites is intentionally out of scope here
29//! — the activity-side glue lives next to the existing
30//! binder.fire() call sites and threads through whatever
31//! `SqliteReporter` the session already holds.
32
33/// Handle the activity holds for snapshot writes.
34///
35/// The shape — `Arc<Mutex<Option<SqliteReporter>>>` — is
36/// load-bearing because the runner shares the same handle
37/// for non-readout sqlite work (cadence flushes, shutdown
38/// finalisers); the inner `Option` reflects "sqlite init
39/// failed; degrade gracefully," the Mutex serialises
40/// writes (sqlite isn't Send), and the Arc shares across
41/// the activity / observer / readout-fire threads.
42///
43/// Snapshot capture goes through [`capture`] rather than
44/// locking and matching by hand — the helper hides the
45/// three-layer unwrap and treats lock-poisoning /
46/// writer-absent as silent no-ops (best-effort).
47pub type SnapshotWriter =
48 std::sync::Arc<std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>>;
49
50/// LOD → string serialised for the storage column.
51pub fn lod_str(lod: super::Lod) -> &'static str {
52 match lod {
53 super::Lod::Compact => "compact",
54 super::Lod::Labeled => "labeled",
55 super::Lod::Expanded => "expanded",
56 }
57}
58
59/// Capture a rendered body to the snapshot store. Best-
60/// effort: a `None` writer (snapshots disabled), lock
61/// poisoning, or "sqlite init failed" (inner `Option` is
62/// `None`) all collapse to silent no-ops — snapshot
63/// capture must never block or corrupt the readout-fire
64/// path.
65///
66/// The row is keyed by `event`'s slot and subject kind and by `ctx`'s
67/// execution id and subject id. The subject id comes from
68/// [`ReadoutContext::subject_id`](super::ReadoutContext::subject_id):
69/// the trait default folds `subject_name` + `subject_labels` into the
70/// conventional `name@labels` shape, and session-scoped contexts
71/// override it to a literal `"session"`.
72pub fn capture<C: super::ReadoutContext + ?Sized>(
73 writer: Option<&SnapshotWriter>,
74 event: crate::lifecycle::EventType,
75 ctx: &C,
76 readout_name: &str,
77 lod: super::Lod,
78 rendered: &str,
79) {
80 let Some(writer) = writer else {
81 return;
82 };
83 let slot = event.slot_name();
84 let exec_id = ctx.subject_exec_id();
85 let subject_kind = event.subject_kind();
86 let subject_kind = subject_kind.as_str();
87 let subject_id = ctx.subject_id();
88 let subject_id = subject_id.as_str();
89 let lod = lod_str(lod);
90 let plain = strip_ansi(rendered);
91 let now_nanos = std::time::SystemTime::now()
92 .duration_since(std::time::UNIX_EPOCH)
93 .map(|d| d.as_nanos() as i64)
94 .unwrap_or(0);
95 let body_ansi = if rendered != plain {
96 Some(rendered.as_bytes())
97 } else {
98 None
99 };
100 let mut guard = match writer.lock() {
101 Ok(g) => g,
102 Err(_) => return,
103 };
104 if let Some(reporter) = guard.as_mut() {
105 reporter.upsert_readout_snapshot(
106 slot,
107 exec_id,
108 subject_kind,
109 subject_id,
110 readout_name,
111 lod,
112 now_nanos,
113 body_ansi,
114 &plain,
115 );
116 }
117}
118
119/// Strip ANSI SGR escape sequences (`\x1b[...m`) from a
120/// rendered string, leaving the plain text. Used to
121/// derive the `body_plain` column from the styled
122/// `body_ansi` blob.
123///
124/// This is the same algorithm as
125/// `nmbrs-runtime::activity::truncate_to_width` uses to
126/// skip escapes when measuring visible width — kept here
127/// so snapshot capture has no surface dependency on the
128/// activity module.
129pub fn strip_ansi(s: &str) -> String {
130 let mut out = String::with_capacity(s.len());
131 let mut chars = s.char_indices();
132 while let Some((_, c)) = chars.next() {
133 if c == '\x1b' {
134 // Walk past `[` / `(` / etc. and the
135 // terminating letter (m / K / J / …). Skips
136 // CSI parameters and intermediate bytes
137 // without trying to interpret them — we just
138 // want to drop the whole escape from the
139 // visible stream.
140 for (_, ch) in chars.by_ref() {
141 if ch.is_ascii_alphabetic() {
142 break;
143 }
144 }
145 continue;
146 }
147 out.push(c);
148 }
149 out
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 #[test]
157 fn strip_ansi_removes_sgr_runs() {
158 assert_eq!(
159 strip_ansi("\x1b[34m[setup]\x1b[0m 100% \x1b[32m\u{2713}\x1b[0m"),
160 "[setup] 100% \u{2713}",
161 );
162 }
163
164 #[test]
165 fn strip_ansi_handles_no_escapes() {
166 assert_eq!(strip_ansi("plain text"), "plain text");
167 }
168
169 #[test]
170 fn strip_ansi_preserves_non_escape_unicode() {
171 assert_eq!(strip_ansi("(profile=alpha) ✓"), "(profile=alpha) ✓");
172 }
173
174 #[test]
175 fn strip_ansi_handles_carriage_return_and_clear() {
176 // The inline-status thread emits `\r\x1b[K`; the
177 // strip helper drops only the SGR-shaped escape.
178 // The `\r` is preserved as-is — that's a control
179 // character but not an SGR escape. Snapshot store
180 // captures the rendered body, not the carriage
181 // return preamble.
182 assert_eq!(strip_ansi("\x1b[Khello"), "hello",);
183 }
184}