use parking_lot::Mutex;
use std::collections::HashSet;
use std::sync::OnceLock;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DigestDirtyKey {
pub tenant_id: String,
pub project_id: Option<String>,
pub role: String,
}
#[derive(Default)]
pub struct DigestDirtyTracker {
dirty: Mutex<HashSet<DigestDirtyKey>>,
}
impl DigestDirtyTracker {
fn new() -> Self {
Self::default()
}
pub fn mark_dirty(&self, key: DigestDirtyKey) {
self.dirty.lock().insert(key);
}
pub fn drain_dirty(&self) -> Vec<DigestDirtyKey> {
let mut guard = self.dirty.lock();
guard.drain().collect()
}
pub fn len(&self) -> usize {
self.dirty.lock().len()
}
pub fn is_empty(&self) -> bool {
self.dirty.lock().is_empty()
}
pub fn contains(&self, key: &DigestDirtyKey) -> bool {
self.dirty.lock().contains(key)
}
}
static GLOBAL_DIGEST_DIRTY_TRACKER: OnceLock<DigestDirtyTracker> = OnceLock::new();
pub fn global() -> &'static DigestDirtyTracker {
GLOBAL_DIGEST_DIRTY_TRACKER.get_or_init(DigestDirtyTracker::new)
}
pub fn mark_dirty(tenant_id: impl Into<String>, project_id: Option<String>, role: &str) {
global().mark_dirty(DigestDirtyKey {
tenant_id: tenant_id.into(),
project_id,
role: role.to_string(),
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mark_dirty_deduplicates_by_triple() {
let tracker = DigestDirtyTracker::new();
let k = DigestDirtyKey {
tenant_id: "t".to_string(),
project_id: Some("p".to_string()),
role: "evidence_library".to_string(),
};
tracker.mark_dirty(k.clone());
tracker.mark_dirty(k.clone());
tracker.mark_dirty(k.clone());
assert_eq!(tracker.len(), 1);
let k2 = DigestDirtyKey {
tenant_id: "t".to_string(),
project_id: Some("p".to_string()),
role: "failure_library".to_string(),
};
tracker.mark_dirty(k2);
assert_eq!(tracker.len(), 2);
}
#[test]
fn drain_dirty_returns_keys_and_leaves_tracker_empty() {
let tracker = DigestDirtyTracker::new();
tracker.mark_dirty(DigestDirtyKey {
tenant_id: "t1".to_string(),
project_id: None,
role: "project_brief".to_string(),
});
tracker.mark_dirty(DigestDirtyKey {
tenant_id: "t2".to_string(),
project_id: Some("p".to_string()),
role: "decision_library".to_string(),
});
let drained = tracker.drain_dirty();
assert_eq!(drained.len(), 2);
assert!(tracker.is_empty());
}
#[test]
fn module_global_is_a_real_singleton() {
let k = DigestDirtyKey {
tenant_id: "singleton".to_string(),
project_id: None,
role: "highlight_library".to_string(),
};
global().mark_dirty(k.clone());
assert!(global().contains(&k));
let _ = global().drain_dirty();
}
}