use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use chrono::{DateTime, Utc};
use second_brain_core::keys::{moved_aside_dirs, remove_expired_asides};
use second_brain_core::sqlite_store::encrypt_migration::remove_plaintext_copies;
use tokio::task::JoinHandle;
use tokio::time::MissedTickBehavior;
use crate::health::Health;
const SWEEP_INTERVAL: Duration = Duration::from_secs(24 * 3600);
pub fn spawn(data_dir: PathBuf, health: Arc<Health>) -> JoinHandle<()> {
tokio::spawn(async move {
let mut interval = tokio::time::interval(SWEEP_INTERVAL);
interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
loop {
interval.tick().await;
let (dir, health) = (data_dir.clone(), health.clone());
let swept = tokio::task::spawn_blocking(move || sweep(&dir, &health, Utc::now())).await;
if let Err(e) = swept {
tracing::warn!("sweeping moved-aside data dirs panicked: {e}");
}
}
})
}
pub fn sweep(data_dir: &Path, health: &Health, now: DateTime<Utc>) {
match remove_expired_asides(data_dir, now.timestamp_micros()) {
Ok(removed) => {
for path in removed {
tracing::info!("deleted {}, moved aside over 90 days ago", path.display());
}
}
Err(e) => tracing::warn!("sweeping moved-aside data dirs failed: {e:#}"),
}
match moved_aside_dirs(data_dir) {
Ok(asides) => {
for aside in &asides {
match remove_plaintext_copies(&aside.path, None) {
Ok(0) => {}
Ok(n) => tracing::info!(
"removed {n} plaintext store copies from {}",
aside.path.display()
),
Err(e) => tracing::warn!(
"cannot remove plaintext store copies from {}: {e:#}",
aside.path.display()
),
}
}
health.moved_aside_listed(asides, now);
}
Err(e) => tracing::warn!("listing moved-aside data dirs failed: {e:#}"),
}
}