Skip to main content

vitrify_cli/run/
events.rs

1//! What happened to a run, one event at a time: the lines the run appends
2//! to `events.jsonl` as things happen, and the lines `vitrify run status
3//! --follow` prints. One shape serves both, so a follower can replay what
4//! the run wrote and then carry on with what it sees for itself.
5
6use std::fs::File;
7use std::io::Write;
8use std::path::Path;
9use std::sync::{Arc, Mutex};
10
11use vitrify_core::model::UtcTime;
12
13use crate::out::{J, diag};
14
15/// One thing that happened to a run or to one of its units. (Not `Event`:
16/// the scheduler has a private enum of that name for its own channel.)
17#[derive(Debug, Clone, PartialEq)]
18pub struct RunEvent {
19    pub at: UtcTime,
20    /// The kind: `dispatched`, `outcome`, `gate`, `run-ended`, …
21    pub kind: String,
22    pub unit: Option<String>,
23    pub claim_seq: Option<i64>,
24    /// Human-readable text, possibly empty.
25    pub detail: String,
26    /// The fields of this kind. Written in key order, whatever order they
27    /// were added in.
28    pub fields: Vec<(String, J)>,
29}
30
31/// The keys every event has; any other key is a field of its kind.
32const COMMON: [&str; 6] = ["at", "event", "unit", "claim_seq", "detail", "replay"];
33
34impl RunEvent {
35    pub fn new(
36        at: UtcTime,
37        kind: &str,
38        unit: Option<&str>,
39        claim_seq: Option<i64>,
40        detail: impl Into<String>,
41    ) -> RunEvent {
42        RunEvent {
43            at,
44            kind: kind.to_string(),
45            unit: unit.map(str::to_string),
46            claim_seq,
47            detail: detail.into(),
48            fields: Vec::new(),
49        }
50    }
51
52    /// The event with one more field of its kind.
53    pub fn with(mut self, key: &str, value: J) -> RunEvent {
54        self.fields.push((key.to_string(), value));
55        self
56    }
57
58    /// A field of this kind, if it has it.
59    pub fn field(&self, key: &str) -> Option<&J> {
60        self.fields.iter().find(|(k, _)| k == key).map(|(_, v)| v)
61    }
62
63    /// The event as one JSON object: the common keys first, then the
64    /// fields of its kind in key order. `replay` is for `run status` output
65    /// only (whether the line was read back from `events.jsonl`); the run's
66    /// own log is written with `None`.
67    pub fn to_json(&self, replay: Option<bool>) -> J {
68        let mut pairs = vec![
69            ("at".to_string(), J::s(self.at.format())),
70            ("event".to_string(), J::s(self.kind.clone())),
71            ("unit".to_string(), J::opt_str(self.unit.clone())),
72            (
73                "claim_seq".to_string(),
74                self.claim_seq.map(J::Int).unwrap_or(J::Null),
75            ),
76            ("detail".to_string(), J::s(self.detail.clone())),
77        ];
78        let mut fields = self.fields.clone();
79        fields.sort_by(|a, b| a.0.cmp(&b.0));
80        pairs.extend(fields);
81        if let Some(replay) = replay {
82            pairs.push(("replay".to_string(), J::Bool(replay)));
83        }
84        J::Obj(pairs)
85    }
86
87    /// An event read back from one line of `events.jsonl`. `None` for
88    /// anything that is not an event: a line cut short by a crash, or one
89    /// with no time or kind. A missing common key takes its default.
90    pub fn from_json(v: &serde_json::Value) -> Option<RunEvent> {
91        let obj = v.as_object()?;
92        let at = UtcTime::parse(obj.get("at")?.as_str()?)?;
93        let kind = obj.get("event")?.as_str()?.to_string();
94        let mut fields: Vec<(String, J)> = obj
95            .iter()
96            .filter(|(k, _)| !COMMON.contains(&k.as_str()))
97            .map(|(k, v)| (k.clone(), J::from_value(v)))
98            .collect();
99        fields.sort_by(|a, b| a.0.cmp(&b.0));
100        Some(RunEvent {
101            at,
102            kind,
103            unit: obj.get("unit").and_then(|u| u.as_str()).map(str::to_string),
104            claim_seq: obj.get("claim_seq").and_then(|c| c.as_i64()),
105            detail: obj
106                .get("detail")
107                .and_then(|d| d.as_str())
108                .unwrap_or_default()
109                .to_string(),
110            fields,
111        })
112    }
113}
114
115/// The run's event log, `<logs>/events.jsonl`: appended to as things
116/// happen, never rewritten. Shared by the scheduler and the integrator's
117/// gate board; each line goes out in one write under the lock, so lines
118/// from the two threads never interleave. Evidence for a reader, not state:
119/// nothing reads it back to decide anything, and a log that cannot be
120/// written does not stop the run.
121#[derive(Clone)]
122pub struct EventLog(Arc<Mutex<Option<File>>>);
123
124impl EventLog {
125    /// Create or append to `events.jsonl` in `logs_dir`. A log that cannot
126    /// be opened is said once and then disabled.
127    pub fn open(logs_dir: &Path) -> EventLog {
128        let path = logs_dir.join("events.jsonl");
129        match std::fs::OpenOptions::new()
130            .create(true)
131            .append(true)
132            .open(&path)
133        {
134            Ok(file) => EventLog(Arc::new(Mutex::new(Some(file)))),
135            Err(e) => {
136                diag(&format!("warning: events.jsonl not written: {e}"));
137                EventLog::off()
138            }
139        }
140    }
141
142    /// A log that writes nothing (tests, and integrators run outside `run`).
143    pub fn off() -> EventLog {
144        EventLog(Arc::new(Mutex::new(None)))
145    }
146
147    /// Append one event. Errors are ignored: the log is evidence, and a run
148    /// does not stop for want of it.
149    pub fn write(&self, e: &RunEvent) {
150        let line = format!("{}\n", e.to_json(None).dumps_default());
151        let mut file = self.0.lock().unwrap_or_else(|p| p.into_inner());
152        if let Some(f) = file.as_mut() {
153            let _ = f.write_all(line.as_bytes());
154        }
155    }
156}
157
158#[cfg(test)]
159mod tests {
160    use super::*;
161
162    fn sample() -> RunEvent {
163        RunEvent::new(
164            UtcTime::parse("2026-11-16T14:08:01Z").unwrap(),
165            "outcome",
166            Some("U-004"),
167            Some(1),
168            "rejected-gate — failing gate: `pytest -q`",
169        )
170        .with("outcome", J::s("rejected-gate"))
171        .with("duration_s", J::Int(660))
172    }
173
174    #[test]
175    fn fields_follow_the_common_keys_in_key_order() {
176        let line = sample().to_json(Some(false)).dumps_default();
177        assert_eq!(
178            line,
179            r#"{"at": "2026-11-16T14:08:01Z", "event": "outcome", "unit": "U-004", "claim_seq": 1, "detail": "rejected-gate \u2014 failing gate: `pytest -q`", "duration_s": 660, "outcome": "rejected-gate", "replay": false}"#
180        );
181        assert!(!sample().to_json(None).dumps_default().contains("replay"));
182    }
183
184    #[test]
185    fn an_event_survives_a_round_trip_field_order_included() {
186        let mut e = sample();
187        e.fields.sort_by(|a, b| a.0.cmp(&b.0));
188        let back: serde_json::Value =
189            serde_json::from_str(&e.to_json(None).dumps_default()).unwrap();
190        assert_eq!(RunEvent::from_json(&back), Some(e));
191
192        let run =
193            RunEvent::new(UtcTime(0), "run-ended", None, None, "").with("state", J::s("complete"));
194        let back: serde_json::Value =
195            serde_json::from_str(&run.to_json(Some(true)).dumps_default()).unwrap();
196        assert_eq!(RunEvent::from_json(&back), Some(run));
197    }
198
199    #[test]
200    fn a_line_that_is_not_an_event_is_skipped() {
201        for text in [
202            r#"{"event": "gate"}"#,
203            r#"{"at": "2026-11-16T14:08:01Z"}"#,
204            "[]",
205        ] {
206            let v: serde_json::Value = serde_json::from_str(text).unwrap();
207            assert_eq!(RunEvent::from_json(&v), None, "{text}");
208        }
209    }
210
211    #[test]
212    fn the_log_appends_one_line_per_event() {
213        let dir = tempfile::tempdir().unwrap();
214        let log = EventLog::open(dir.path());
215        log.write(&sample());
216        log.clone().write(&sample());
217        EventLog::off().write(&sample());
218        let text = std::fs::read_to_string(dir.path().join("events.jsonl")).unwrap();
219        assert_eq!(text.lines().count(), 2);
220        assert!(text.ends_with("}\n"));
221    }
222}