isothrum_runner/events.rs
1//! The event stream: what an operation does, as JSON values an embedder shows or a command line
2//! prints one per line (`isothrum … --json`). It evolves from Isoloom's lifecycle events (the
3//! `event` tag, `step`/`log`/`check`/`result`), adding the run, the operation, a sequence number,
4//! the time on every event, and its own version `v`, independent of the manifest's.
5//!
6//! Rules: a secret's value never appears (masked before the event is built); `log` lines are
7//! decoded lossily; an operation ends with exactly one `result` or `error`.
8
9mod emitter;
10
11#[cfg(test)]
12use std::sync::{Mutex, PoisonError};
13
14use isoloom_manifest::OutputRole;
15use serde::{Deserialize, Serialize};
16
17pub(crate) use emitter::{Emitter, MASK};
18
19use crate::error::{ErrorCode, TimedOut};
20use crate::state::{Op, RunState};
21
22/// The event stream's version.
23pub(crate) const EVENTS_VERSION: u32 = 0;
24
25/// Where a step stands.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
27#[serde(rename_all = "snake_case")]
28#[non_exhaustive]
29pub enum StepState {
30 /// Started.
31 Running,
32 /// Finished and succeeded.
33 Done,
34 /// Finished and failed (an `error` follows unless the step's failure is tolerated).
35 Failed,
36 /// Not run: an earlier step failed.
37 Skipped,
38}
39
40/// Which output of a tool a line came from.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
42#[serde(rename_all = "snake_case")]
43#[non_exhaustive]
44pub enum Stream {
45 /// Its standard output.
46 Stdout,
47 /// Its standard error.
48 Stderr,
49}
50
51/// Where a ready condition stands.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
53#[serde(rename_all = "snake_case")]
54#[non_exhaustive]
55pub enum ReadyState {
56 /// Not yet; polled again.
57 Waiting,
58 /// It holds.
59 Ok,
60 /// It doesn't hold: the operation fails (`not_ready`).
61 Failed,
62}
63
64/// What happened.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
66#[serde(tag = "event", rename_all = "snake_case")]
67#[non_exhaustive]
68pub enum EventKind {
69 /// The run moved from one state to another.
70 State {
71 /// Before.
72 from: RunState,
73 /// After.
74 to: RunState,
75 },
76 /// A step started, finished, failed or was skipped.
77 Step {
78 /// The step's id.
79 step: String,
80 /// Where it stands.
81 state: StepState,
82 /// What it does, said when it starts: the manifest's line for a manifest step, the
83 /// runner's own for a step of its own (the tool probes, the boot, a guest delivery).
84 #[serde(default, skip_serializing_if = "Option::is_none")]
85 note: Option<String>,
86 },
87 /// A line a step's tool printed.
88 Log {
89 /// The step's id.
90 step: String,
91 /// Which output.
92 stream: Stream,
93 /// The line, without its line break.
94 line: String,
95 },
96 /// A ready condition was checked.
97 Ready {
98 /// The condition (`step_ok up`).
99 condition: String,
100 /// Where it stands.
101 state: ReadyState,
102 /// What was seen.
103 detail: String,
104 },
105 /// An output's value, once the run is up.
106 Output {
107 /// The output's name.
108 name: String,
109 /// What it is for.
110 role: OutputRole,
111 /// Its value (`***` when sensitive), or null when it can't be read.
112 value: Option<String>,
113 /// Whether the value is sensitive.
114 sensitive: bool,
115 },
116 /// One check's result.
117 Check {
118 /// The check runner's id.
119 runner: String,
120 /// Where it ran from.
121 from: String,
122 /// The check's name.
123 name: String,
124 /// Whether it passed.
125 ok: bool,
126 /// Why it failed (empty when it passed).
127 detail: String,
128 },
129 /// Something the embedder may show, that didn't fail the operation.
130 Warning {
131 /// What kind.
132 code: WarningCode,
133 /// The text.
134 message: String,
135 },
136 /// The operation's outcome, when it ran to its end.
137 Result {
138 /// Whether it reached its goal (false: a check failed).
139 ok: bool,
140 /// What it found or produced.
141 data: serde_json::Value,
142 },
143 /// Why the operation failed.
144 Error {
145 /// The stable code.
146 code: ErrorCode,
147 /// The message.
148 message: String,
149 /// The step that failed, when one did.
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 step: Option<String>,
152 /// Which limit the step ran into, when the code is `timeout`.
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 timeout: Option<TimedOut>,
155 },
156}
157
158/// A run's logged events ([`crate::Runner::events`]), and how many of the log's lines it
159/// couldn't read as one: a line another version of the runner wrote (an event kind or a code
160/// this one doesn't know), or one cut short.
161#[derive(Debug, Clone, Default, PartialEq)]
162#[non_exhaustive]
163pub struct EventLog {
164 /// The events, oldest first.
165 pub events: Vec<Event>,
166 /// The lines that aren't an event this runner reads.
167 pub unreadable: usize,
168}
169
170/// One event of the stream.
171///
172/// Every event of an operation has `run` and `op`. An event written outside one ([`Event::new`])
173/// has those its writer knows. The command line's own: a command line it refused has neither;
174/// `reap`'s closing `result` and `error` have neither; any other failure before an operation
175/// began has `op` when the command is an operation, and `run` when `--name` named it (a failure
176/// of `status`, `console`, `events` or `key` has no `op`).
177#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
178#[non_exhaustive]
179pub struct Event {
180 /// The stream's version (0).
181 pub v: u32,
182 /// Its place in the operation, from 1.
183 pub seq: u64,
184 /// When (`YYYY-MM-DDTHH:MM:SSZ`, UTC).
185 pub time: String,
186 /// The run's name: on every event of an operation; outside one, when its writer knows it
187 /// (see [`Event`]).
188 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub run: Option<String>,
190 /// The operation: on every event of an operation; outside one, when its writer knows it (see
191 /// [`Event`]).
192 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub op: Option<Op>,
194 /// What happened.
195 #[serde(flatten)]
196 pub kind: EventKind,
197}
198
199impl Event {
200 /// An event an embedder writes itself, timed now, with the `run` and `op` it knows: the runner
201 /// numbers and writes its own. For what no operation reports, such as a command that couldn't
202 /// start one (an `error` with code `usage`).
203 #[must_use]
204 pub fn new(seq: u64, run: Option<String>, op: Option<Op>, kind: EventKind) -> Event {
205 Event {
206 v: EVENTS_VERSION,
207 seq,
208 time: crate::clock::rfc3339(std::time::SystemTime::now()),
209 run,
210 op,
211 kind,
212 }
213 }
214}
215
216/// Where an operation's events go. Implemented for closures (`|e: &Event| …`).
217pub trait Events: Send + Sync {
218 /// Receives one event.
219 fn emit(&self, event: &Event);
220}
221
222impl<F: Fn(&Event) + Send + Sync> Events for F {
223 fn emit(&self, event: &Event) {
224 self(event);
225 }
226}
227
228/// What kind of warning a `warning` event is, the same in the Rust API and the event stream.
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
230#[serde(rename_all = "snake_case")]
231#[non_exhaustive]
232pub enum WarningCode {
233 /// A step whose failure the manifest tolerates failed.
234 StepTolerated,
235 /// A check runner failed or ran out of time: its checks that didn't report fail.
236 CheckRunnerFailed,
237 /// A clean-up of the checks failed: a check runner's that ran out of time (`on_timeout`), or
238 /// the teardown after a setup that failed too (the check ends with the setup's error).
239 CheckCleanupFailed,
240 /// What an earlier run left is removed before a start.
241 LeftoversRemoved,
242 /// A VM (or its folder) an earlier run left was removed.
243 OrphanRemoved,
244 /// The run last ran on another Vagrant provider: that run is cleared first.
245 OtherProvider,
246 /// A VM's saved state was cut off: it boots fresh.
247 SavedStateDiscarded,
248 /// A start failed on stale state: cleared, then started again.
249 Recovering,
250 /// A step is tried again: an apply that failed, an `ssh.run` whose host doesn't answer yet, a
251 /// Vagrant command another Vagrant process's lock on a machine refused, or a download the
252 /// network cut (a connection reset, a gateway's 502), up to three more times.
253 Retrying,
254 /// An operation that failed couldn't update the run's record either: the operation's own
255 /// error is the one it ends with.
256 RecordNotSaved,
257 /// An output's `format` couldn't be filled (it names a value the run doesn't have): the
258 /// output has no value.
259 OutputUnformatted,
260 /// A resource a destroy found already gone (its provider's error, which the manifest names) is
261 /// dropped from the run's state, and the destroy runs again.
262 AlreadyGone,
263 /// A clean-up the runner does on its own, best effort, failed (an earlier run's VM or its
264 /// folder, the hypervisor's list of them, the run on another Vagrant provider): what it would have removed may still be
265 /// there, and the start goes on.
266 CleanupFailed,
267}
268
269/// Events kept in memory, for tests.
270#[cfg(test)]
271#[derive(Debug, Default)]
272pub(crate) struct Recorder(Mutex<Vec<Event>>);
273
274#[cfg(test)]
275impl Recorder {
276 /// An empty recorder.
277 #[must_use]
278 pub(crate) fn new() -> Recorder {
279 Recorder::default()
280 }
281
282 /// Every event so far, in order.
283 pub(crate) fn events(&self) -> Vec<Event> {
284 self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
285 }
286}
287
288#[cfg(test)]
289impl Events for Recorder {
290 fn emit(&self, event: &Event) {
291 self.0.lock().unwrap_or_else(PoisonError::into_inner).push(event.clone());
292 }
293}
294
295/// The JSON Schema of one event.
296#[must_use]
297pub fn events_schema() -> serde_json::Value {
298 titled_schema::<Event>(&format!("Isothrum runner event, version {EVENTS_VERSION}"))
299}
300
301/// `T`'s JSON Schema, titled `title`.
302pub(crate) fn titled_schema<T: schemars::JsonSchema>(title: &str) -> serde_json::Value {
303 let schema = schemars::schema_for!(T);
304 // Written out as schemars writes a schema (its leading keys first, at every level); should that
305 // ever fail, the schema's own value, the same keys in another order, rather than nothing.
306 let mut value = serde_json::to_value(&schema).unwrap_or_else(|_| schema.to_value());
307 if let Some(fields) = value.as_object_mut() {
308 fields.insert("title".to_owned(), serde_json::json!(title));
309 }
310 value
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316
317 fn event(kind: EventKind) -> Event {
318 Event {
319 v: 0,
320 seq: 1,
321 time: "2026-10-15T12:00:00Z".into(),
322 run: Some("web-portal".into()),
323 op: Some(Op::Up),
324 kind,
325 }
326 }
327
328 #[test]
329 fn an_event_has_the_documented_shape() {
330 let e = event(EventKind::Step {
331 step: "up".into(),
332 state: StepState::Running,
333 note: Some("Starting…".into()),
334 });
335 assert_eq!(
336 serde_json::to_value(&e).unwrap(),
337 serde_json::json!({"v":0,"seq":1,"time":"2026-10-15T12:00:00Z","run":"web-portal","op":"up","event":"step","step":"up","state":"running","note":"Starting…"})
338 );
339 let error = event(EventKind::Error {
340 code: ErrorCode::PortInUse,
341 message: "m".into(),
342 step: None,
343 timeout: None,
344 });
345 let back: Event = serde_json::from_value(serde_json::to_value(&error).unwrap()).unwrap();
346 assert_eq!(back, error);
347 }
348
349 #[test]
350 fn the_schema_names_every_event_kind() {
351 let schema = events_schema().to_string();
352 for kind in ["state", "step", "log", "ready", "output", "check", "warning", "result", "error"] {
353 assert!(schema.contains(&format!("\"{kind}\"")), "{kind}");
354 }
355 }
356}