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`): the `event` tag, `step`/`log`/`result`, with the
3//! run, the operation, a sequence number, the time on every event, and the stream's version `v`.
4//!
5//! Rules: a secret's value never appears (masked before the event is built); `log` lines are
6//! decoded lossily; an operation ends with exactly one `result` or `error`.
7
8mod emitter;
9mod result_data;
10
11#[cfg(test)]
12use std::sync::{Mutex, PoisonError};
13
14use serde::{Deserialize, Serialize};
15
16pub(crate) use emitter::{Emitter, MASK, StoreLog};
17
18use crate::state::{Op, RunState};
19pub use result_data::{ResultData, ShownOutput, SweepFailure};
20
21/// The event stream's version.
22pub(crate) const EVENTS_VERSION: u32 = 1;
23
24/// Where a step stands.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
26#[serde(rename_all = "snake_case")]
27#[non_exhaustive]
28pub enum StepState {
29 /// Started, or moved on (said again with its new `count`).
30 Started,
31 /// Finished and succeeded.
32 Done,
33 /// Finished and failed: the operation's failure is this step's.
34 Failed,
35 /// Cut short or not run: another step failed.
36 Skipped,
37}
38
39/// Which output of a tool a line came from.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
41#[serde(rename_all = "snake_case")]
42#[non_exhaustive]
43pub enum Stream {
44 /// Its standard output.
45 Stdout,
46 /// Its standard error.
47 Stderr,
48}
49
50/// Where a journaled operation stands.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
52#[serde(rename_all = "snake_case")]
53#[non_exhaustive]
54pub enum OperationPhase {
55 /// Accepted and waiting in its run's queue.
56 Queued,
57 /// Begun.
58 Started,
59 /// Ended (its `outcome` says how).
60 Ended,
61}
62
63/// What happened.
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
65#[serde(tag = "event", rename_all = "snake_case")]
66#[non_exhaustive]
67pub enum EventKind {
68 /// The run moved from one state to another.
69 State {
70 /// Before.
71 from: RunState,
72 /// After.
73 to: RunState,
74 },
75 /// A step started, moved on, finished, failed or was skipped: one of the format's own
76 /// ([`crate::Phase`], whose `id` the step is).
77 Step {
78 /// The step's id ([`crate::Phase::id`]).
79 step: String,
80 /// Where it stands.
81 state: StepState,
82 /// What it is about, when it is one of several of its kind: a machine.
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 label: Option<String>,
85 /// How far it is, when it counts what it does (images, containers, resources).
86 #[serde(default, skip_serializing_if = "Option::is_none")]
87 count: Option<crate::StepCount>,
88 },
89 /// A line a step's tool printed.
90 Log {
91 /// The step's id.
92 step: String,
93 /// Which output.
94 stream: Stream,
95 /// The line, without its line break.
96 line: String,
97 },
98 /// An output's value, once the run is up.
99 Output {
100 /// The output's name.
101 name: String,
102 /// Its value (`***` when sensitive), or null when it can't be read.
103 value: Option<String>,
104 /// Whether the value is sensitive.
105 sensitive: bool,
106 },
107 /// Something the embedder may show, that didn't fail the operation.
108 Warning {
109 /// What kind.
110 code: WarningCode,
111 /// The text.
112 message: String,
113 },
114 /// The operation's outcome, when it ran to its end.
115 Result {
116 /// Whether it reached its goal (false: a check failed).
117 ok: bool,
118 /// What it found or produced, by operation.
119 data: ResultData,
120 },
121 /// A journaled operation was queued, started or ended: what a runner service says of the
122 /// operations it queues (the runner's own operation stream doesn't carry it: it still ends
123 /// with exactly one `result` or `error`).
124 Operation {
125 /// Where the operation stands.
126 phase: OperationPhase,
127 /// How it ended, when `phase` is `ended`.
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 outcome: Option<crate::store::Outcome>,
130 /// Its place in its run's queue (0: next), when `phase` is `queued`.
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 position: Option<u32>,
133 },
134 /// What the user wants of the run changed: an operation that moves it began (`up`, `resume`:
135 /// running; `park`: parked; `down`: gone).
136 Desired {
137 /// What is wanted now.
138 desired: crate::state::Desired,
139 },
140 /// A resource of the run moved in the home's write-ahead ledger: written `creating` before
141 /// the call that makes it, `created` with the tool's id after it, `destroying` before the call
142 /// that removes it, `gone` after.
143 Resource {
144 /// The resource's key in the run (`container:web-1`, a volume's name, a local thing's kind).
145 key: String,
146 /// What it is.
147 kind: crate::store::ResourceKind,
148 /// Where it stands now.
149 state: crate::store::ResourceState,
150 /// The tool's id for it, once it has one.
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 native_id: Option<String>,
153 },
154 /// Why the operation failed: its code, message, step, typed fields and whether the run was
155 /// touched ([`crate::ErrorReport`]).
156 Error(crate::ErrorReport),
157}
158
159/// A run's logged events ([`crate::Runner::events`]), and how many of the log's lines it
160/// couldn't read as one: a line another version of the runner wrote (an event kind or a code
161/// this one doesn't know), or one cut short.
162#[derive(Debug, Clone, Default, PartialEq)]
163#[non_exhaustive]
164pub struct EventLog {
165 /// The events, oldest first.
166 pub events: Vec<Event>,
167 /// The lines that aren't an event this runner reads.
168 pub unreadable: usize,
169}
170
171/// One event of the stream.
172///
173/// Every event of an operation has `run` and `op`. An event written outside one ([`Event::new`])
174/// has those its writer knows. The command line's own: a command line it refused has neither;
175/// `reap`'s closing `result` and `error` have neither; any other failure before an operation
176/// began has `op` when the command is an operation, and `run` when `--name` named it (a failure
177/// of `status`, `console`, `events` or `key` has no `op`).
178#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
179#[non_exhaustive]
180pub struct Event {
181 /// The stream's version (1).
182 pub v: u32,
183 /// Its place in the operation, from 1.
184 pub seq: u64,
185 /// When (`YYYY-MM-DDTHH:MM:SSZ`, UTC).
186 pub time: String,
187 /// The run's name: on every event of an operation; outside one, when its writer knows it
188 /// (see [`Event`]).
189 #[serde(default, skip_serializing_if = "Option::is_none")]
190 pub run: Option<String>,
191 /// The operation: on every event of an operation; outside one, when its writer knows it (see
192 /// [`Event`]).
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub op: Option<Op>,
195 /// The operation's id in the home's journal: on every event of a journaled operation.
196 #[serde(default, skip_serializing_if = "Option::is_none")]
197 pub operation: Option<crate::store::OperationId>,
198 /// What happened.
199 #[serde(flatten)]
200 pub kind: EventKind,
201}
202
203impl Event {
204 /// An event an embedder writes itself, timed now, with the `run` and `op` it knows: the runner
205 /// numbers and writes its own. For what no operation reports, such as a command that couldn't
206 /// start one (an `error` with code `usage`).
207 #[must_use]
208 pub fn new(seq: u64, run: Option<String>, op: Option<Op>, kind: EventKind) -> Event {
209 Event {
210 v: EVENTS_VERSION,
211 seq,
212 time: crate::clock::rfc3339(std::time::SystemTime::now()),
213 run,
214 op,
215 operation: None,
216 kind,
217 }
218 }
219}
220
221/// Where an operation's events go. Implemented for closures (`|e: &Event| …`).
222pub trait Events: Send + Sync {
223 /// Receives one event.
224 fn emit(&self, event: &Event);
225}
226
227impl<F: Fn(&Event) + Send + Sync> Events for F {
228 fn emit(&self, event: &Event) {
229 self(event);
230 }
231}
232
233/// What kind of warning a `warning` event is, the same in the Rust API and the event stream.
234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
235#[serde(rename_all = "snake_case")]
236#[non_exhaustive]
237pub enum WarningCode {
238 /// A step whose failure the manifest tolerates failed.
239 StepTolerated,
240 /// A check runner failed or ran out of time: its checks that didn't report fail.
241 CheckRunnerFailed,
242 /// A clean-up of the checks failed: a check runner's that ran out of time (`on_timeout`), or
243 /// the teardown after a setup that failed too (the check ends with the setup's error).
244 CheckCleanupFailed,
245 /// What an earlier run left is removed before a start.
246 LeftoversRemoved,
247 /// A VM (or its folder) an earlier run left was removed.
248 OrphanRemoved,
249 /// The run last ran on another Vagrant provider: that run is cleared first.
250 OtherProvider,
251 /// A VM's saved state was cut off: it boots fresh.
252 SavedStateDiscarded,
253 /// A start failed on stale state: cleared, then started again.
254 Recovering,
255 /// A step is tried again: an apply that failed, an `ssh.run` whose host doesn't answer yet, a
256 /// Vagrant command another Vagrant process's lock on a machine refused, a UTM `up` an Apple
257 /// event failed in passing (once), or a download the network cut (a connection reset, a
258 /// gateway's 502), up to three more times.
259 Retrying,
260 /// An operation that failed couldn't update the run's record either: the operation's own
261 /// error is the one it ends with.
262 RecordNotSaved,
263 /// An output's `format` couldn't be filled (it names a value the run doesn't have): the
264 /// output has no value.
265 OutputUnformatted,
266 /// A resource a destroy found already gone (its provider's error, which the manifest names) is
267 /// dropped from the run's state, and the destroy runs again.
268 AlreadyGone,
269 /// A clean-up the runner does on its own, best effort, failed (an earlier run's VM or its
270 /// folder, the hypervisor's list of them, the run on another Vagrant provider): what it would have removed may still be
271 /// there, and the start goes on.
272 CleanupFailed,
273 /// A Terraform module keeps its state in a backend of its own: every copy of it shares that
274 /// state.
275 SharedState,
276 /// A running machine's forwarded ports couldn't be read (its provider can't list them, and
277 /// its hypervisor didn't say): it has no published port, and runs on.
278 PortsUnknown,
279 /// A machine's published host port is another than the one the run kept from its first
280 /// start (a Vagrant provider's `auto_correct` re-picked it at a boot): its address moved.
281 PortsMoved,
282 /// A tool printed no version the runner reads: it is used, its minimum version unchecked.
283 VersionUnknown,
284 /// On Windows, the host adapter of a VMware private network has no address of its own and
285 /// couldn't be given one (the administrator's prompt declined, VMware's `vnetlib` failed):
286 /// this computer reaches the run's machines on their forwarded ports, not at their private
287 /// addresses.
288 HostAdapterUnaddressed,
289}
290
291/// Events kept in memory, for tests.
292#[cfg(test)]
293#[derive(Debug, Default)]
294pub(crate) struct Recorder(Mutex<Vec<Event>>);
295
296#[cfg(test)]
297impl Recorder {
298 /// An empty recorder.
299 #[must_use]
300 pub(crate) fn new() -> Recorder {
301 Recorder::default()
302 }
303
304 /// Every event so far, in order.
305 pub(crate) fn events(&self) -> Vec<Event> {
306 self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
307 }
308}
309
310#[cfg(test)]
311impl Events for Recorder {
312 fn emit(&self, event: &Event) {
313 self.0.lock().unwrap_or_else(PoisonError::into_inner).push(event.clone());
314 }
315}
316
317/// The JSON Schema of one event.
318#[must_use]
319pub fn events_schema() -> serde_json::Value {
320 titled_schema::<Event>(&format!("Isothrum runner event, version {EVENTS_VERSION}"))
321}
322
323/// `T`'s JSON Schema, titled `title`.
324pub(crate) fn titled_schema<T: schemars::JsonSchema>(title: &str) -> serde_json::Value {
325 let schema = schemars::schema_for!(T);
326 // Written out as schemars writes a schema (its leading keys first, at every level); should that
327 // ever fail, the schema's own value, the same keys in another order, rather than nothing.
328 let mut value = serde_json::to_value(&schema).unwrap_or_else(|_| schema.to_value());
329 if let Some(fields) = value.as_object_mut() {
330 fields.insert("title".to_owned(), serde_json::json!(title));
331 }
332 value
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338 use crate::error::{ErrorCode, TimedOut};
339
340 fn event(kind: EventKind) -> Event {
341 Event {
342 v: 1,
343 seq: 1,
344 time: "2026-10-15T12:00:00Z".into(),
345 run: Some("web-portal".into()),
346 op: Some(Op::Up),
347 operation: None,
348 kind,
349 }
350 }
351
352 /// The JSON an embedder reads: the common fields, then the kind's own, an optional field
353 /// left out when it has no value; and each reads back as itself.
354 #[test]
355 fn each_event_is_written_as_documented_and_reads_back() {
356 let common = serde_json::json!({"v": 1, "seq": 1, "time": "2026-10-15T12:00:00Z", "run": "web-portal", "op": "up"});
357 let cases = [
358 (
359 EventKind::Step {
360 step: "images".into(),
361 state: StepState::Started,
362 label: None,
363 count: Some(crate::StepCount::new(1, Some(3))),
364 },
365 serde_json::json!({"event": "step", "step": "images", "state": "started", "count": {"done": 1, "total": 3}}),
366 ),
367 (
368 EventKind::Step {
369 step: "provision".into(),
370 state: StepState::Failed,
371 label: Some("dc01".into()),
372 count: None,
373 },
374 serde_json::json!({"event": "step", "step": "provision", "state": "failed", "label": "dc01"}),
375 ),
376 (
377 EventKind::Error(crate::ErrorReport {
378 step: Some("up".into()),
379 detail: Some(crate::ErrorDetail {
380 v: 2,
381 data: crate::Detail::Timeout {
382 timed_out: TimedOut::NoProgress {
383 after_s: 30,
384 last_line: Some("pulling".into()),
385 },
386 },
387 }),
388 ..crate::ErrorReport::new(ErrorCode::Timeout, "m")
389 }),
390 serde_json::json!({
391 "event": "error", "code": "timeout", "message": "m", "step": "up", "changed": true,
392 "detail": {"v": 2, "kind": "timeout", "timed_out": {"kind": "no_progress", "after_s": 30, "last_line": "pulling"}}
393 }),
394 ),
395 (
396 EventKind::Error(crate::ErrorReport::new(ErrorCode::PortInUse, "m").unchanged()),
397 serde_json::json!({"event": "error", "code": "port_in_use", "message": "m", "changed": false}),
398 ),
399 ];
400 for (kind, own) in cases {
401 let e = event(kind);
402 let mut expected = common.clone();
403 expected.as_object_mut().unwrap().extend(own.as_object().unwrap().clone());
404 let json = serde_json::to_value(&e).unwrap();
405 assert_eq!(json, expected);
406 assert_eq!(serde_json::from_value::<Event>(json).unwrap(), e);
407 }
408 }
409
410 /// A kind is never removed or renamed within a version of the stream: the schema still names
411 /// each the stream has had (it may name more).
412 #[test]
413 fn the_schema_keeps_every_event_kind_the_stream_has_had() {
414 let schema = events_schema();
415 let kinds: Vec<&str> = schema["oneOf"]
416 .as_array()
417 .expect("one schema per kind")
418 .iter()
419 .filter_map(|kind| kind["properties"]["event"]["const"].as_str())
420 .collect();
421 for kind in [
422 "state",
423 "step",
424 "log",
425 "output",
426 "warning",
427 "result",
428 "operation",
429 "desired",
430 "resource",
431 "error",
432 ] {
433 assert!(kinds.contains(&kind), "{kind}: {kinds:?}");
434 }
435 }
436}