use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum RecoveryAction {
#[default]
None,
Restart,
Stop,
#[serde(rename = "command")]
Command(String),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RecoveryConfig {
#[serde(default)]
pub action: RecoveryAction,
#[serde(default = "default_max_attempts")]
pub max_attempts: u32,
#[serde(default = "default_cooldown")]
pub cooldown: u64,
}
impl RecoveryConfig {
pub const fn cooldown_duration(&self) -> std::time::Duration {
std::time::Duration::from_secs(self.cooldown)
}
pub fn should_attempt(&self, last_attempt: Option<std::time::Instant>) -> bool {
match last_attempt {
Some(t) => t.elapsed() >= self.cooldown_duration(),
None => true,
}
}
}
const fn default_max_attempts() -> u32 {
3
}
const fn default_cooldown() -> u64 {
60
}
impl Default for RecoveryConfig {
fn default() -> Self {
Self {
action: RecoveryAction::None,
max_attempts: default_max_attempts(),
cooldown: default_cooldown(),
}
}
}
#[cfg(test)]
impl RecoveryConfig {
pub fn restart() -> Self {
Self {
action: RecoveryAction::Restart,
..Default::default()
}
}
pub fn stop() -> Self {
Self {
action: RecoveryAction::Stop,
..Default::default()
}
}
pub fn command(cmd: &str) -> Self {
Self {
action: RecoveryAction::Command(cmd.to_string()),
..Default::default()
}
}
pub fn with_max_attempts(mut self, attempts: u32) -> Self {
self.max_attempts = attempts;
self
}
pub fn with_cooldown(mut self, cooldown: u64) -> Self {
self.cooldown = cooldown;
self
}
}
#[cfg(test)]
mod tests;