use std::path::Path;
use anyhow::{Context as _, Result};
use serde::{Deserialize, Serialize};
pub const MAX_FAILURES: usize = 5;
pub const WINDOW_MS: i64 = 15 * 60 * 1000;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct State {
#[serde(default)]
pub last_step: u64,
#[serde(default)]
pub failures: Vec<i64>,
}
impl State {
pub fn load(path: &Path) -> Result<Self> {
match std::fs::read(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
Ok(bytes) => serde_json::from_slice(&bytes).with_context(|| {
format!(
"reading {}: the gate's state does not parse; move it aside to start it again",
path.display()
)
}),
}
}
pub fn save(&self, path: &Path) -> Result<()> {
let mut text = serde_json::to_vec_pretty(self)?;
text.push(b'\n');
crate::home::write_private(path, &text)
}
pub fn prune(&mut self, now_ms: i64) {
self.failures
.retain(|t| now_ms - *t < WINDOW_MS && *t <= now_ms);
}
pub fn locked_until(&self, now_ms: i64) -> Option<i64> {
let recent: Vec<i64> = self
.failures
.iter()
.copied()
.filter(|t| now_ms - *t < WINDOW_MS && *t <= now_ms)
.collect();
if recent.len() < MAX_FAILURES {
return None;
}
let mut sorted = recent;
sorted.sort_unstable();
sorted
.get(sorted.len() - MAX_FAILURES)
.map(|t| t + WINDOW_MS)
}
pub fn failed(&mut self, now_ms: i64) {
self.prune(now_ms);
self.failures.push(now_ms);
}
pub fn passed(&mut self, step: u64) {
self.last_step = step;
self.failures.clear();
}
}