Skip to main content

isothrum_runner/
steps.rs

1//! The steps an operation goes through, said as `step` events ([`EventKind::Step`]): each format's
2//! own phases ([`Phase`]), with what a step is about (a machine, an image) and how far it is
3//! ([`StepCount`]). A driver says them from the calls it makes and from what its tool prints.
4//!
5//! A step is said when it starts, again when its count moves, and once when it ends. What is still
6//! open when the operation ends is closed then: done when the operation went through; else the step
7//! started last failed (unless a driver already said which one did), and the others were cut short
8//! (skipped).
9
10use std::sync::{Mutex, PoisonError};
11
12use serde::{Deserialize, Serialize};
13
14use crate::events::{EventKind, StepState};
15
16/// A step of an operation: its id in a `step` event.
17///
18/// | Format | Steps, in order |
19/// |---|---|
20/// | Compose | `images` (pulled and built), `create` (networks, volumes, containers), `start`, `health` (waited on until healthy) |
21/// | Vagrant | `boxes` (downloaded), then for each machine (the step's `label`): `up`, `provision` |
22/// | Terraform | `init`, `apply` (the resources changed so far of those planned), `ready` (the module's provisioners set its machines up) |
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum Phase {
26    /// Compose: the images the services run, pulled and built (counted by image).
27    Images,
28    /// Compose: the project's networks, volumes and containers made (counted by container).
29    Create,
30    /// Compose: the containers started (counted by container).
31    Start,
32    /// Compose: the services waited on until they run healthy, or a one-shot one exited (counted
33    /// by container).
34    Health,
35    /// Vagrant: the boxes the machines boot from, downloaded (counted by box).
36    Boxes,
37    /// Vagrant: a machine (the label) made and booted.
38    Up,
39    /// Vagrant: a machine (the label) set up by its provisioners.
40    Provision,
41    /// Terraform: the module's providers and modules installed, its state's backend readied.
42    Init,
43    /// Terraform: the module's resources made, changed or removed (counted by resource).
44    Apply,
45    /// Terraform: the module's provisioners setting its machines up.
46    Ready,
47}
48
49impl Phase {
50    /// Every step, in the order a format goes through its own.
51    pub const ALL: [Phase; 10] = [
52        Phase::Images,
53        Phase::Create,
54        Phase::Start,
55        Phase::Health,
56        Phase::Boxes,
57        Phase::Up,
58        Phase::Provision,
59        Phase::Init,
60        Phase::Apply,
61        Phase::Ready,
62    ];
63
64    /// Its id in a `step` event.
65    #[must_use]
66    pub fn id(self) -> &'static str {
67        match self {
68            Phase::Images => "images",
69            Phase::Create => "create",
70            Phase::Start => "start",
71            Phase::Health => "health",
72            Phase::Boxes => "boxes",
73            Phase::Up => "up",
74            Phase::Provision => "provision",
75            Phase::Init => "init",
76            Phase::Apply => "apply",
77            Phase::Ready => "ready",
78        }
79    }
80
81    /// The step whose id is `id`, if it is one.
82    #[must_use]
83    pub fn of(id: &str) -> Option<Phase> {
84        Phase::ALL.into_iter().find(|p| p.id() == id)
85    }
86}
87
88/// How far a step is: `done` of its `total` items, when the total is known.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
90#[non_exhaustive]
91pub struct StepCount {
92    /// The items done so far.
93    pub done: u32,
94    /// How many there are, once the tool says.
95    #[serde(default, skip_serializing_if = "Option::is_none")]
96    pub total: Option<u32>,
97}
98
99impl StepCount {
100    /// `done` of `total`.
101    #[must_use]
102    pub fn new(done: u32, total: Option<u32>) -> StepCount {
103        StepCount { done, total }
104    }
105}
106
107/// One step open now.
108struct Open {
109    phase: Phase,
110    label: Option<String>,
111    count: Option<StepCount>,
112}
113
114/// The steps open now, in the order they started, and whether one was said failed.
115#[derive(Default)]
116struct Opened {
117    steps: Vec<Open>,
118    failed: bool,
119}
120
121impl Opened {
122    fn find(&self, phase: Phase, label: Option<&str>) -> Option<usize> {
123        self.steps.iter().position(|s| s.phase == phase && s.label.as_deref() == label)
124    }
125
126    fn get_mut(&mut self, phase: Phase, label: Option<&str>) -> Option<&mut Open> {
127        self.steps.iter_mut().find(|s| s.phase == phase && s.label.as_deref() == label)
128    }
129}
130
131/// The steps of one operation, said through `say` as they move.
132pub(crate) struct Steps<'a> {
133    say: &'a (dyn Fn(EventKind) + Send + Sync),
134    opened: Mutex<Opened>,
135}
136
137/// Says nothing: the steps of a context that says none (a read, a console, a test's).
138fn unsaid(_: EventKind) {}
139
140impl<'a> Steps<'a> {
141    /// Steps said through `say`.
142    pub(crate) fn new(say: &'a (dyn Fn(EventKind) + Send + Sync)) -> Steps<'a> {
143        Steps {
144            say,
145            opened: Mutex::new(Opened::default()),
146        }
147    }
148
149    /// Steps said nowhere.
150    pub(crate) fn silent() -> Steps<'static> {
151        Steps::new(&unsaid)
152    }
153
154    fn opened(&self) -> std::sync::MutexGuard<'_, Opened> {
155        self.opened.lock().unwrap_or_else(PoisonError::into_inner)
156    }
157
158    /// Starts step `phase` of `label`: said once, while it isn't open.
159    pub(crate) fn start(&self, phase: Phase, label: Option<&str>) {
160        let mut opened = self.opened();
161        if opened.find(phase, label).is_none() {
162            opened.steps.push(Open {
163                phase,
164                label: label.map(str::to_owned),
165                count: None,
166            });
167            self.said(phase, label, StepState::Started, None);
168        }
169    }
170
171    /// Step `phase` of `label` is `count` along: said when the count moved (the step started
172    /// first when it isn't open).
173    pub(crate) fn count(&self, phase: Phase, label: Option<&str>, count: StepCount) {
174        let mut opened = self.opened();
175        match opened.get_mut(phase, label) {
176            Some(open) if open.count == Some(count) => return,
177            Some(open) => open.count = Some(count),
178            None => opened.steps.push(Open {
179                phase,
180                label: label.map(str::to_owned),
181                count: Some(count),
182            }),
183        }
184        self.said(phase, label, StepState::Started, Some(count));
185    }
186
187    /// How far open step `phase` of `label` is, when it said a count.
188    pub(crate) fn count_of(&self, phase: Phase, label: Option<&str>) -> Option<StepCount> {
189        self.opened().get_mut(phase, label).and_then(|open| open.count)
190    }
191
192    /// Whether step `phase` of `label` is open.
193    pub(crate) fn is_open(&self, phase: Phase, label: Option<&str>) -> bool {
194        self.opened().find(phase, label).is_some()
195    }
196
197    /// Ends step `phase` of `label` as done, when it is open.
198    pub(crate) fn done(&self, phase: Phase, label: Option<&str>) {
199        self.close(phase, label, StepState::Done);
200    }
201
202    /// Ends step `phase` of `label` as failed, when it is open: the operation's failure is its.
203    pub(crate) fn failed(&self, phase: Phase, label: Option<&str>) {
204        self.close(phase, label, StepState::Failed);
205    }
206
207    fn close(&self, phase: Phase, label: Option<&str>, state: StepState) {
208        let mut opened = self.opened();
209        if let Some(at) = opened.find(phase, label) {
210            let step = opened.steps.remove(at);
211            opened.failed |= state == StepState::Failed;
212            self.said(step.phase, label, state, step.count);
213        }
214    }
215
216    /// Ends every open step: done when `ok`; else the one started last failed (unless one was
217    /// already said failed), the others cut short.
218    pub(crate) fn end(&self, ok: bool) {
219        let mut opened = self.opened();
220        let steps = std::mem::take(&mut opened.steps);
221        let blamed = if ok || opened.failed { None } else { steps.len().checked_sub(1) };
222        opened.failed |= blamed.is_some();
223        for (at, step) in steps.into_iter().enumerate() {
224            let state = if ok {
225                StepState::Done
226            } else if Some(at) == blamed {
227                StepState::Failed
228            } else {
229                StepState::Skipped
230            };
231            self.said(step.phase, step.label.as_deref(), state, step.count);
232        }
233    }
234
235    fn said(&self, phase: Phase, label: Option<&str>, state: StepState, count: Option<StepCount>) {
236        (self.say)(EventKind::Step {
237            step: phase.id().to_owned(),
238            state,
239            label: label.map(str::to_owned),
240            count,
241        });
242    }
243}
244
245/// The steps said through a [`Steps`], kept, for tests.
246#[cfg(test)]
247pub(crate) mod said {
248    use std::sync::{Mutex, PoisonError};
249
250    use crate::events::{EventKind, StepState};
251
252    /// The step events said, kept in order.
253    #[derive(Default)]
254    pub(crate) struct Said(Mutex<Vec<EventKind>>);
255
256    impl Said {
257        /// Keeps `kind`.
258        pub(crate) fn keep(&self, kind: EventKind) {
259            self.0.lock().unwrap_or_else(PoisonError::into_inner).push(kind);
260        }
261
262        /// Each step said, as `step[:label] state[ done/total]`.
263        pub(crate) fn lines(&self) -> Vec<String> {
264            self.0
265                .lock()
266                .unwrap_or_else(PoisonError::into_inner)
267                .iter()
268                .filter_map(|kind| match kind {
269                    EventKind::Step { step, state, label, count } => {
270                        let state = match state {
271                            StepState::Started => "started",
272                            StepState::Done => "done",
273                            StepState::Failed => "failed",
274                            StepState::Skipped => "skipped",
275                        };
276                        let label = label.as_deref().map(|l| format!(":{l}")).unwrap_or_default();
277                        let count = count
278                            .map(|c| format!(" {}/{}", c.done, c.total.map_or_else(|| "?".to_owned(), |t| t.to_string())))
279                            .unwrap_or_default();
280                        Some(format!("{step}{label} {state}{count}"))
281                    }
282                    _ => None,
283                })
284                .collect()
285        }
286    }
287
288    /// The steps said while `run` works through a [`super::Steps`], as [`Said::lines`] writes them.
289    pub(crate) fn said_by(run: impl FnOnce(&super::Steps<'_>)) -> Vec<String> {
290        let said = Said::default();
291        let say = |kind: EventKind| said.keep(kind);
292        run(&super::Steps::new(&say));
293        said.lines()
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::said::{Said, said_by};
300    use super::*;
301
302    #[test]
303    fn each_id_reads_back_as_its_step() {
304        for phase in Phase::ALL {
305            assert_eq!(Phase::of(phase.id()), Some(phase));
306        }
307        assert_eq!(Phase::of("pull-up"), None);
308    }
309
310    #[test]
311    fn a_step_is_said_when_it_starts_moves_and_ends_once() {
312        let said = Said::default();
313        let say = |kind: EventKind| said.keep(kind);
314        let s = Steps::new(&say);
315        s.start(Phase::Images, None);
316        s.start(Phase::Images, None);
317        s.count(Phase::Images, None, StepCount::new(1, Some(2)));
318        s.count(Phase::Images, None, StepCount::new(1, Some(2)));
319        s.count(Phase::Images, None, StepCount::new(2, Some(2)));
320        s.done(Phase::Images, None);
321        s.done(Phase::Images, None);
322        s.count(Phase::Create, None, StepCount::new(0, None));
323        s.end(true);
324        assert_eq!(
325            said.lines(),
326            [
327                "images started",
328                "images started 1/2",
329                "images started 2/2",
330                "images done 2/2",
331                "create started 0/?",
332                "create done 0/?",
333            ]
334        );
335    }
336
337    #[test]
338    fn a_failed_operation_fails_the_step_started_last_and_cuts_the_others_short() {
339        let said = said_by(|s| {
340            s.start(Phase::Up, Some("dc01"));
341            s.start(Phase::Up, Some("ws01"));
342            s.end(false);
343        });
344        assert_eq!(said, ["up:dc01 started", "up:ws01 started", "up:dc01 skipped", "up:ws01 failed"]);
345    }
346
347    #[test]
348    fn a_step_said_failed_is_the_failure_and_the_others_are_cut_short() {
349        let said = said_by(|s| {
350            s.start(Phase::Up, Some("dc01"));
351            s.start(Phase::Up, Some("ws01"));
352            s.failed(Phase::Up, Some("dc01"));
353            s.end(false);
354            s.end(false);
355        });
356        assert_eq!(said, ["up:dc01 started", "up:ws01 started", "up:dc01 failed", "up:ws01 skipped"]);
357    }
358}