second_brain_api/
asides.rs1use std::path::{Path, PathBuf};
2use std::sync::Arc;
3use std::time::Duration;
4
5use chrono::{DateTime, Utc};
6use second_brain_core::keys::{moved_aside_dirs, remove_expired_asides};
7use second_brain_core::sqlite_store::encrypt_migration::remove_plaintext_copies;
8use tokio::task::JoinHandle;
9use tokio::time::MissedTickBehavior;
10
11use crate::health::Health;
12
13const SWEEP_INTERVAL: Duration = Duration::from_secs(24 * 3600);
14
15pub fn spawn(data_dir: PathBuf, health: Arc<Health>) -> JoinHandle<()> {
16 tokio::spawn(async move {
17 let mut interval = tokio::time::interval(SWEEP_INTERVAL);
18 interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
19 loop {
20 interval.tick().await;
21 let (dir, health) = (data_dir.clone(), health.clone());
22 let swept = tokio::task::spawn_blocking(move || sweep(&dir, &health, Utc::now())).await;
23 if let Err(e) = swept {
24 tracing::warn!("sweeping moved-aside data dirs panicked: {e}");
25 }
26 }
27 })
28}
29
30pub fn sweep(data_dir: &Path, health: &Health, now: DateTime<Utc>) {
35 match remove_expired_asides(data_dir, now.timestamp_micros()) {
36 Ok(removed) => {
37 for path in removed {
38 tracing::info!("deleted {}, moved aside over 90 days ago", path.display());
39 }
40 }
41 Err(e) => tracing::warn!("sweeping moved-aside data dirs failed: {e:#}"),
42 }
43 match moved_aside_dirs(data_dir) {
44 Ok(asides) => {
45 for aside in &asides {
46 match remove_plaintext_copies(&aside.path, None) {
47 Ok(0) => {}
48 Ok(n) => tracing::info!(
49 "removed {n} plaintext store copies from {}",
50 aside.path.display()
51 ),
52 Err(e) => tracing::warn!(
53 "cannot remove plaintext store copies from {}: {e:#}",
54 aside.path.display()
55 ),
56 }
57 }
58 health.moved_aside_listed(asides, now);
59 }
60 Err(e) => tracing::warn!("listing moved-aside data dirs failed: {e:#}"),
61 }
62}