use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HealthState {
#[default]
Idle,
Staged {
update_id: String,
},
Trial {
update_id: String,
boots: u8,
},
Committed {
update_id: String,
},
RolledBack {
update_id: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum BootChoice {
Current,
Candidate(String),
RollBack(String),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BootHealth {
pub state: HealthState,
pub max_failed_boots: u8,
}
impl Default for BootHealth {
fn default() -> Self {
Self { state: HealthState::Idle, max_failed_boots: 2 }
}
}
impl BootHealth {
pub fn stage(&mut self, update_id: &str) {
self.state = HealthState::Staged { update_id: update_id.to_owned() };
}
pub fn begin_boot(&mut self) -> BootChoice {
match std::mem::take(&mut self.state) {
HealthState::Staged { update_id } => {
self.state = HealthState::Trial { update_id: update_id.clone(), boots: 1 };
BootChoice::Candidate(update_id)
}
HealthState::Trial { update_id, boots } if boots >= self.max_failed_boots.max(1) => {
self.state = HealthState::RolledBack { update_id: update_id.clone() };
BootChoice::RollBack(update_id)
}
HealthState::Trial { update_id, boots } => {
self.state = HealthState::Trial { update_id: update_id.clone(), boots: boots + 1 };
BootChoice::Candidate(update_id)
}
other => {
self.state = other;
BootChoice::Current
}
}
}
pub fn mark_ready(&mut self) -> Option<String> {
if let HealthState::Trial { update_id, .. } = &self.state {
let id = update_id.clone();
self.state = HealthState::Committed { update_id: id.clone() };
return Some(id);
}
None
}
}