use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};
use serde::Serialize;
#[derive(Default, Clone)]
struct Entry {
status: String,
total: i64,
completed: i64,
}
static STATE: LazyLock<Mutex<HashMap<String, Entry>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
#[derive(Serialize, Default)]
pub struct Snapshot {
pub status: String,
pub total: i64,
pub completed: i64,
}
pub fn reset(key: &str, status: &str) {
if key.is_empty() {
return;
}
STATE.lock().unwrap().insert(
key.to_string(),
Entry {
status: status.to_string(),
..Default::default()
},
);
}
pub fn set_status(key: &str, status: &str) {
if key.is_empty() {
return;
}
STATE
.lock()
.unwrap()
.entry(key.to_string())
.or_default()
.status = status.to_string();
}
pub fn add_total(key: &str, delta: i64) {
if key.is_empty() || delta == 0 {
return;
}
STATE
.lock()
.unwrap()
.entry(key.to_string())
.or_default()
.total += delta;
}
pub fn add_completed(key: &str, delta: i64) {
if key.is_empty() || delta <= 0 {
return;
}
STATE
.lock()
.unwrap()
.entry(key.to_string())
.or_default()
.completed += delta;
}
pub fn done(key: &str) {
if key.is_empty() {
return;
}
STATE.lock().unwrap().remove(key);
}
pub fn poll(key: &str) -> Snapshot {
let state = STATE.lock().unwrap();
match state.get(key) {
Some(e) => Snapshot {
status: e.status.clone(),
total: e.total,
completed: e.completed,
},
None => Snapshot::default(),
}
}
pub struct DoneGuard<'a>(pub &'a str);
impl Drop for DoneGuard<'_> {
fn drop(&mut self) {
done(self.0);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reset_then_poll_round_trips() {
let key = "test::reset_then_poll_round_trips";
reset(key, "pulling");
add_total(key, 100);
add_completed(key, 40);
let snap = poll(key);
assert_eq!(snap.status, "pulling");
assert_eq!(snap.total, 100);
assert_eq!(snap.completed, 40);
done(key);
}
#[test]
fn poll_of_untracked_key_is_zero_value() {
let snap = poll("test::never-tracked-key");
assert_eq!(snap.status, "");
assert_eq!(snap.total, 0);
assert_eq!(snap.completed, 0);
}
#[test]
fn empty_key_is_a_no_op_everywhere() {
reset("", "x");
add_total("", 10);
add_completed("", 10);
set_status("", "y");
assert_eq!(poll("").total, 0);
done("");
}
#[test]
fn done_guard_cleans_up_on_drop() {
let key = "test::done_guard_cleans_up_on_drop";
reset(key, "pulling");
{
let _guard = DoneGuard(key);
add_total(key, 10);
}
assert_eq!(
poll(key).total,
0,
"entry must be gone once the guard drops"
);
}
}