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