use crate::agent::files;
use crate::agent::summary::{HourBucket, HourlyHistory};
use chrono::{DateTime, Duration, Timelike, Utc};
use serde::{Deserialize, Serialize};
use std::path::Path;
const MAX_HOURS: usize = 12;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct History {
hours: Vec<HourBucket>,
#[serde(default)]
last_requests: Option<u64>,
#[serde(default)]
last_earned: Option<f64>,
}
fn floor_to_hour(now: DateTime<Utc>) -> String {
now.with_minute(0)
.and_then(|t| t.with_second(0))
.and_then(|t| t.with_nanosecond(0))
.unwrap_or(now)
.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}
impl History {
pub fn record(&mut self, now: DateTime<Utc>, requests_5h: u64, earned_today: f64) {
let requests_delta = match self.last_requests {
Some(prev) => requests_5h.saturating_sub(prev),
None => 0,
};
let earned_delta = match self.last_earned {
Some(prev) if earned_today >= prev => earned_today - prev,
Some(_) => earned_today,
None => 0.0,
};
self.last_requests = Some(requests_5h);
self.last_earned = Some(earned_today);
let start = floor_to_hour(now);
match self.hours.last_mut() {
Some(b) if b.start == start => {
b.requests += requests_delta;
b.earned += earned_delta;
}
_ => self.hours.push(HourBucket {
start,
requests: requests_delta,
earned: earned_delta,
}),
}
self.trim();
}
fn trim(&mut self) {
if self.hours.len() > MAX_HOURS {
let excess = self.hours.len() - MAX_HOURS;
self.hours.drain(0..excess);
}
}
pub fn to_wire(&self) -> Option<HourlyHistory> {
if self.hours.is_empty() {
None
} else {
Some(HourlyHistory {
hours: self.hours.clone(),
})
}
}
pub fn load(path: &Path, now: DateTime<Utc>) -> Self {
let mut h: Self = if path.exists() {
files::load_json(path).unwrap_or_else(|| {
eprintln!(
" [AGENT] {} is unreadable; starting with an empty usage history",
path.display()
);
Self::default()
})
} else {
Self::default()
};
let cutoff = now - Duration::hours(MAX_HOURS as i64);
h.hours.retain(|b| {
DateTime::parse_from_rfc3339(&b.start)
.map(|t| t.with_timezone(&Utc) > cutoff)
.unwrap_or(false)
});
h.trim();
h
}
pub fn save(&self, path: &Path) -> std::io::Result<()> {
files::save_json(path, self)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn t(s: &str) -> DateTime<Utc> {
DateTime::parse_from_rfc3339(s).unwrap().with_timezone(&Utc)
}
#[test]
fn two_samples_in_one_hour_accumulate() {
let mut h = History::default();
h.record(t("2026-09-16T04:10:00Z"), 10, 1.0); h.record(t("2026-09-16T04:40:00Z"), 15, 1.5);
let hours = h.to_wire().unwrap().hours;
assert_eq!(hours.len(), 1);
assert_eq!(hours[0].start, "2026-09-16T04:00:00Z");
assert_eq!(hours[0].requests, 5);
assert!((hours[0].earned - 0.5).abs() < 1e-9);
}
#[test]
fn crossing_an_hour_boundary_opens_a_new_bucket() {
let mut h = History::default();
h.record(t("2026-09-16T04:50:00Z"), 10, 1.0);
h.record(t("2026-09-16T04:55:00Z"), 12, 1.2);
h.record(t("2026-09-16T05:05:00Z"), 20, 1.6);
let hours = h.to_wire().unwrap().hours;
assert_eq!(hours.len(), 2);
assert_eq!(hours[0].start, "2026-09-16T04:00:00Z");
assert_eq!(hours[0].requests, 2);
assert_eq!(hours[1].start, "2026-09-16T05:00:00Z");
assert_eq!(hours[1].requests, 8);
assert!((hours[1].earned - 0.4).abs() < 1e-9);
}
#[test]
fn a_decreasing_requests_gauge_contributes_zero() {
let mut h = History::default();
h.record(t("2026-09-16T04:00:00Z"), 30, 0.0);
h.record(t("2026-09-16T04:05:00Z"), 4, 0.0); let hours = h.to_wire().unwrap().hours;
assert_eq!(hours[0].requests, 0);
}
#[test]
fn a_decreasing_earnings_today_contributes_the_new_value() {
let mut h = History::default();
h.record(t("2026-09-16T04:00:00Z"), 0, 9.5);
h.record(t("2026-09-16T04:05:00Z"), 0, 0.4); let hours = h.to_wire().unwrap().hours;
assert!((hours[0].earned - 0.4).abs() < 1e-9);
}
#[test]
fn only_the_last_12_buckets_are_kept() {
let mut h = History::default();
for hour in 0..15 {
h.record(
t(&format!("2026-09-16T{hour:02}:00:00Z")),
(hour as u64) + 1,
0.0,
);
}
let hours = h.to_wire().unwrap().hours;
assert_eq!(hours.len(), 12);
assert_eq!(hours.first().unwrap().start, "2026-09-16T03:00:00Z");
assert_eq!(hours.last().unwrap().start, "2026-09-16T14:00:00Z");
}
#[test]
fn an_hour_with_no_samples_is_absent() {
let mut h = History::default();
h.record(t("2026-09-16T04:00:00Z"), 1, 0.0);
h.record(t("2026-09-16T06:00:00Z"), 3, 0.0); let hours = h.to_wire().unwrap().hours;
assert_eq!(hours.len(), 2);
assert_eq!(hours[0].start, "2026-09-16T04:00:00Z");
assert_eq!(hours[1].start, "2026-09-16T06:00:00Z");
}
#[test]
fn an_empty_series_has_no_wire_form() {
assert_eq!(History::default().to_wire(), None);
}
#[test]
fn round_trips_through_the_persisted_file() {
let dir = std::env::temp_dir().join(format!(
"zc-history-test-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("history.json");
let mut h = History::default();
h.record(t("2026-09-16T04:00:00Z"), 5, 0.4);
h.record(t("2026-09-16T05:00:00Z"), 12, 0.9);
h.save(&path).unwrap();
let reloaded = History::load(&path, t("2026-09-16T05:10:00Z"));
assert_eq!(reloaded, h);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn load_drops_stale_buckets_and_survives_a_bad_file() {
let dir = std::env::temp_dir().join(format!(
"zc-history-test-stale-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::create_dir_all(&dir).unwrap();
let missing = dir.join("missing.json");
assert_eq!(
History::load(&missing, t("2026-09-16T12:00:00Z")),
History::default()
);
let corrupt = dir.join("corrupt.json");
std::fs::write(&corrupt, b"not json").unwrap();
assert_eq!(
History::load(&corrupt, t("2026-09-16T12:00:00Z")),
History::default()
);
let mut h = History::default();
h.record(t("2026-09-15T10:00:00Z"), 1, 0.1); h.record(t("2026-09-16T11:00:00Z"), 2, 0.2); let stale = dir.join("stale.json");
h.save(&stale).unwrap();
let reloaded = History::load(&stale, t("2026-09-16T12:00:00Z"));
let hours = reloaded.to_wire().unwrap().hours;
assert_eq!(hours.len(), 1);
assert_eq!(hours[0].start, "2026-09-16T11:00:00Z");
std::fs::remove_dir_all(&dir).ok();
}
}