use std::collections::HashMap;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
use crate::namespace::Namespace;
const TTL: Duration = Duration::from_secs(60);
#[derive(Default)]
pub(super) struct Usage {
per_namespace: Mutex<HashMap<String, (Instant, u64, u64)>>,
}
impl Usage {
pub(super) async fn cached(&self, ns: &Namespace) -> Option<(u64, u64)> {
self.per_namespace
.lock()
.await
.get(&ns.to_string())
.filter(|(measured_at, _, _)| measured_at.elapsed() < TTL)
.map(|(_, objects, bytes)| (*objects, *bytes))
}
pub(super) async fn remember(&self, ns: &Namespace, objects: u64, bytes: u64) {
self.per_namespace
.lock()
.await
.insert(ns.to_string(), (Instant::now(), objects, bytes));
}
pub(super) async fn stored(&self, ns: &Namespace, bytes: u64) {
if let Some((_, objects, held)) = self.per_namespace.lock().await.get_mut(&ns.to_string()) {
*objects += 1;
*held += bytes;
}
}
pub(super) async fn forget(&self, ns: &Namespace) {
self.per_namespace.lock().await.remove(&ns.to_string());
}
}