use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
use super::TierHandler;
use crate::graph::{update_frontier_bounded, TenantRegistry};
use crate::types::{Freshness, Tier};
pub struct OverlayRefresh {
registry: Arc<RwLock<TenantRegistry>>,
tenant: String,
root: PathBuf,
hops: u32,
freshness: Arc<Mutex<HashMap<String, Freshness>>>,
}
impl OverlayRefresh {
#[must_use]
pub fn new(
registry: Arc<RwLock<TenantRegistry>>,
tenant: impl Into<String>,
root: PathBuf,
hops: u32,
) -> Self {
Self {
registry,
tenant: tenant.into(),
root,
hops,
freshness: Arc::new(Mutex::new(HashMap::new())),
}
}
#[must_use]
pub fn freshness_handle(&self) -> Arc<Mutex<HashMap<String, Freshness>>> {
Arc::clone(&self.freshness)
}
#[must_use]
pub fn freshness_of(&self, rel: &str) -> Option<Freshness> {
self.freshness.lock().ok()?.get(rel).copied()
}
fn rel_of(&self, path: &Path) -> String {
path.strip_prefix(&self.root)
.unwrap_or(path)
.display()
.to_string()
}
fn set_freshness(&self, rel: &str, f: Freshness) {
if let Ok(mut map) = self.freshness.lock() {
map.insert(rel.to_string(), f);
}
}
}
impl TierHandler for OverlayRefresh {
fn tree_sitter(&mut self, paths: &[PathBuf]) {
for path in paths {
let rel = self.rel_of(path);
match std::fs::read_to_string(path) {
Ok(source) => {
if let Ok(mut reg) = self.registry.write() {
reg.touch(&self.tenant, &rel, &source);
}
self.set_freshness(&rel, Freshness::Recomputing);
tracing::info!(
tenant = %self.tenant, file = %rel, tier = Tier::TreeSitter.as_str(),
"overlay touched (tree-sitter); frontier recomputing"
);
}
Err(_) => {
if let Ok(mut reg) = self.registry.write() {
reg.touch(&self.tenant, &rel, "");
}
self.set_freshness(&rel, Freshness::Recomputing);
}
}
}
}
fn heavy(&mut self, paths: &[PathBuf]) {
let Ok(reg) = self.registry.read() else {
return;
};
let view = reg.view(&self.tenant);
let rels: Vec<String> = paths.iter().map(|p| self.rel_of(p)).collect();
let mut seed_names: Vec<String> = Vec::new();
for rel in &rels {
for s in view.file_symbols(rel) {
seed_names.push(s.name);
}
}
let seeds: Vec<&str> = seed_names.iter().map(String::as_str).collect();
let threshold = reg.tenancy().high_fanin_threshold;
let frontier = update_frontier_bounded(&view, &seeds, self.hops, threshold);
tracing::info!(
tenant = %self.tenant, changed = rels.len(), frontier = frontier.len(),
"frontier recomputed (heavy tier)"
);
for rel in &rels {
self.set_freshness(rel, Freshness::Fresh);
}
}
}
#[cfg(test)]
#[path = "overlay_refresh_test.rs"]
mod overlay_refresh_test;