use std::sync::{Mutex, PoisonError};
use serde::{Deserialize, Serialize};
use crate::events::{EventKind, StepState};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Phase {
Images,
Create,
Start,
Health,
Boxes,
Up,
Provision,
Init,
Apply,
Ready,
}
impl Phase {
pub const ALL: [Phase; 10] = [
Phase::Images,
Phase::Create,
Phase::Start,
Phase::Health,
Phase::Boxes,
Phase::Up,
Phase::Provision,
Phase::Init,
Phase::Apply,
Phase::Ready,
];
#[must_use]
pub fn id(self) -> &'static str {
match self {
Phase::Images => "images",
Phase::Create => "create",
Phase::Start => "start",
Phase::Health => "health",
Phase::Boxes => "boxes",
Phase::Up => "up",
Phase::Provision => "provision",
Phase::Init => "init",
Phase::Apply => "apply",
Phase::Ready => "ready",
}
}
#[must_use]
pub fn of(id: &str) -> Option<Phase> {
Phase::ALL.into_iter().find(|p| p.id() == id)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[non_exhaustive]
pub struct StepCount {
pub done: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub total: Option<u32>,
}
impl StepCount {
#[must_use]
pub fn new(done: u32, total: Option<u32>) -> StepCount {
StepCount { done, total }
}
}
struct Open {
phase: Phase,
label: Option<String>,
count: Option<StepCount>,
}
#[derive(Default)]
struct Opened {
steps: Vec<Open>,
failed: bool,
}
impl Opened {
fn find(&self, phase: Phase, label: Option<&str>) -> Option<usize> {
self.steps.iter().position(|s| s.phase == phase && s.label.as_deref() == label)
}
fn get_mut(&mut self, phase: Phase, label: Option<&str>) -> Option<&mut Open> {
self.steps.iter_mut().find(|s| s.phase == phase && s.label.as_deref() == label)
}
}
pub(crate) struct Steps<'a> {
say: &'a (dyn Fn(EventKind) + Send + Sync),
opened: Mutex<Opened>,
}
fn unsaid(_: EventKind) {}
impl<'a> Steps<'a> {
pub(crate) fn new(say: &'a (dyn Fn(EventKind) + Send + Sync)) -> Steps<'a> {
Steps {
say,
opened: Mutex::new(Opened::default()),
}
}
pub(crate) fn silent() -> Steps<'static> {
Steps::new(&unsaid)
}
fn opened(&self) -> std::sync::MutexGuard<'_, Opened> {
self.opened.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn start(&self, phase: Phase, label: Option<&str>) {
let mut opened = self.opened();
if opened.find(phase, label).is_none() {
opened.steps.push(Open {
phase,
label: label.map(str::to_owned),
count: None,
});
self.said(phase, label, StepState::Started, None);
}
}
pub(crate) fn count(&self, phase: Phase, label: Option<&str>, count: StepCount) {
let mut opened = self.opened();
match opened.get_mut(phase, label) {
Some(open) if open.count == Some(count) => return,
Some(open) => open.count = Some(count),
None => opened.steps.push(Open {
phase,
label: label.map(str::to_owned),
count: Some(count),
}),
}
self.said(phase, label, StepState::Started, Some(count));
}
pub(crate) fn count_of(&self, phase: Phase, label: Option<&str>) -> Option<StepCount> {
self.opened().get_mut(phase, label).and_then(|open| open.count)
}
pub(crate) fn is_open(&self, phase: Phase, label: Option<&str>) -> bool {
self.opened().find(phase, label).is_some()
}
pub(crate) fn done(&self, phase: Phase, label: Option<&str>) {
self.close(phase, label, StepState::Done);
}
pub(crate) fn failed(&self, phase: Phase, label: Option<&str>) {
self.close(phase, label, StepState::Failed);
}
fn close(&self, phase: Phase, label: Option<&str>, state: StepState) {
let mut opened = self.opened();
if let Some(at) = opened.find(phase, label) {
let step = opened.steps.remove(at);
opened.failed |= state == StepState::Failed;
self.said(step.phase, label, state, step.count);
}
}
pub(crate) fn end(&self, ok: bool) {
let mut opened = self.opened();
let steps = std::mem::take(&mut opened.steps);
let blamed = if ok || opened.failed { None } else { steps.len().checked_sub(1) };
opened.failed |= blamed.is_some();
for (at, step) in steps.into_iter().enumerate() {
let state = if ok {
StepState::Done
} else if Some(at) == blamed {
StepState::Failed
} else {
StepState::Skipped
};
self.said(step.phase, step.label.as_deref(), state, step.count);
}
}
fn said(&self, phase: Phase, label: Option<&str>, state: StepState, count: Option<StepCount>) {
(self.say)(EventKind::Step {
step: phase.id().to_owned(),
state,
label: label.map(str::to_owned),
count,
});
}
}
#[cfg(test)]
pub(crate) mod said {
use std::sync::{Mutex, PoisonError};
use crate::events::{EventKind, StepState};
#[derive(Default)]
pub(crate) struct Said(Mutex<Vec<EventKind>>);
impl Said {
pub(crate) fn keep(&self, kind: EventKind) {
self.0.lock().unwrap_or_else(PoisonError::into_inner).push(kind);
}
pub(crate) fn lines(&self) -> Vec<String> {
self.0
.lock()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.filter_map(|kind| match kind {
EventKind::Step { step, state, label, count } => {
let state = match state {
StepState::Started => "started",
StepState::Done => "done",
StepState::Failed => "failed",
StepState::Skipped => "skipped",
};
let label = label.as_deref().map(|l| format!(":{l}")).unwrap_or_default();
let count = count
.map(|c| format!(" {}/{}", c.done, c.total.map_or_else(|| "?".to_owned(), |t| t.to_string())))
.unwrap_or_default();
Some(format!("{step}{label} {state}{count}"))
}
_ => None,
})
.collect()
}
}
pub(crate) fn said_by(run: impl FnOnce(&super::Steps<'_>)) -> Vec<String> {
let said = Said::default();
let say = |kind: EventKind| said.keep(kind);
run(&super::Steps::new(&say));
said.lines()
}
}
#[cfg(test)]
mod tests {
use super::said::{Said, said_by};
use super::*;
#[test]
fn each_id_reads_back_as_its_step() {
for phase in Phase::ALL {
assert_eq!(Phase::of(phase.id()), Some(phase));
}
assert_eq!(Phase::of("pull-up"), None);
}
#[test]
fn a_step_is_said_when_it_starts_moves_and_ends_once() {
let said = Said::default();
let say = |kind: EventKind| said.keep(kind);
let s = Steps::new(&say);
s.start(Phase::Images, None);
s.start(Phase::Images, None);
s.count(Phase::Images, None, StepCount::new(1, Some(2)));
s.count(Phase::Images, None, StepCount::new(1, Some(2)));
s.count(Phase::Images, None, StepCount::new(2, Some(2)));
s.done(Phase::Images, None);
s.done(Phase::Images, None);
s.count(Phase::Create, None, StepCount::new(0, None));
s.end(true);
assert_eq!(
said.lines(),
[
"images started",
"images started 1/2",
"images started 2/2",
"images done 2/2",
"create started 0/?",
"create done 0/?",
]
);
}
#[test]
fn a_failed_operation_fails_the_step_started_last_and_cuts_the_others_short() {
let said = said_by(|s| {
s.start(Phase::Up, Some("dc01"));
s.start(Phase::Up, Some("ws01"));
s.end(false);
});
assert_eq!(said, ["up:dc01 started", "up:ws01 started", "up:dc01 skipped", "up:ws01 failed"]);
}
#[test]
fn a_step_said_failed_is_the_failure_and_the_others_are_cut_short() {
let said = said_by(|s| {
s.start(Phase::Up, Some("dc01"));
s.start(Phase::Up, Some("ws01"));
s.failed(Phase::Up, Some("dc01"));
s.end(false);
s.end(false);
});
assert_eq!(said, ["up:dc01 started", "up:ws01 started", "up:dc01 failed", "up:ws01 skipped"]);
}
}