1use std::sync::{Mutex, PoisonError};
11
12use serde::{Deserialize, Serialize};
13
14use crate::events::{EventKind, StepState};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum Phase {
26 Images,
28 Create,
30 Start,
32 Health,
35 Boxes,
37 Up,
39 Provision,
41 Init,
43 Apply,
45 Ready,
47}
48
49impl Phase {
50 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 #[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 #[must_use]
83 pub fn of(id: &str) -> Option<Phase> {
84 Phase::ALL.into_iter().find(|p| p.id() == id)
85 }
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
90#[non_exhaustive]
91pub struct StepCount {
92 pub done: u32,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub total: Option<u32>,
97}
98
99impl StepCount {
100 #[must_use]
102 pub fn new(done: u32, total: Option<u32>) -> StepCount {
103 StepCount { done, total }
104 }
105}
106
107struct Open {
109 phase: Phase,
110 label: Option<String>,
111 count: Option<StepCount>,
112}
113
114#[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
131pub(crate) struct Steps<'a> {
133 say: &'a (dyn Fn(EventKind) + Send + Sync),
134 opened: Mutex<Opened>,
135}
136
137fn unsaid(_: EventKind) {}
139
140impl<'a> Steps<'a> {
141 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 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 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 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 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 pub(crate) fn is_open(&self, phase: Phase, label: Option<&str>) -> bool {
194 self.opened().find(phase, label).is_some()
195 }
196
197 pub(crate) fn done(&self, phase: Phase, label: Option<&str>) {
199 self.close(phase, label, StepState::Done);
200 }
201
202 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 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#[cfg(test)]
247pub(crate) mod said {
248 use std::sync::{Mutex, PoisonError};
249
250 use crate::events::{EventKind, StepState};
251
252 #[derive(Default)]
254 pub(crate) struct Said(Mutex<Vec<EventKind>>);
255
256 impl Said {
257 pub(crate) fn keep(&self, kind: EventKind) {
259 self.0.lock().unwrap_or_else(PoisonError::into_inner).push(kind);
260 }
261
262 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 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}