//! Background orchestrator for scanning, watching, and telemetry polling. use crate::cache::CacheStore; use crate::config::Config; use crate::domain::{RelPath, ScanProgress}; use crate::macos::{SnapshotInventory, SnapshotProvider, VolumeStats, VolumeTelemetry}; use crate::scanner::{Scanner, current_time_ns, is_same_mount, metadata_dev}; use crate::watcher::{DirtyAction, DirtyCoalescer, FsWatcher, RawFsEvent}; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, RwLock}; use std::time::{Duration, Instant}; use tokio::sync::{broadcast, mpsc, watch}; use tracing::{error, info, warn}; const VOLUME_NUDGE_THRESHOLD_BYTES: u64 = 50 * 1024 * 1024; /// Current scan lifecycle state. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ScanState { Idle, Scanning, } /// Live status snapshot exposed by `/api/health`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct EngineStatus { pub scan_state: ScanState, pub progress: ScanProgress, pub fsevents_active: bool, pub last_full_scan_completed_ns: i64, } /// Typed events broadcast over SSE (`/api/events`). #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum EngineEvent { ScanProgress { scan_state: ScanState, progress: ScanProgress, }, DirUpdated { path: String, delta_physical_bytes: i64, delta_logical_bytes: i64, }, VolumeUpdated(VolumeStats), SnapshotsUpdated(SnapshotInventory), } /// Shared state held by [`Engine`] and read by the HTTP server. pub struct Engine { pub config: Arc, pub cache: Arc, pub scanner: Arc, pub volume_telemetry: Arc, pub snapshot_provider: Arc, pub watcher: Arc, pub events_tx: broadcast::Sender, status: RwLock, latest_volume: RwLock>, latest_snapshots: RwLock>, started_at: Instant, debounce: Duration, } impl std::fmt::Debug for Engine { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Engine") .field("home_root", &self.config.home_root) .finish_non_exhaustive() } } /// Handle controlling background tasks spawned by [`Engine::start`]. pub struct EngineHandle { shutdown_tx: watch::Sender, _watcher_guard: Box, } impl std::fmt::Debug for EngineHandle { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("EngineHandle").finish_non_exhaustive() } } impl EngineHandle { /// Signal all background engine tasks to stop. pub fn shutdown(&self) { let _ = self.shutdown_tx.send(true); } } impl Engine { /// Construct a new [`Engine`] with explicit seams. #[must_use] pub fn new( config: Arc, cache: Arc, scanner: Arc, volume_telemetry: Arc, snapshot_provider: Arc, watcher: Arc, ) -> Self { Self::with_debounce( config, cache, scanner, volume_telemetry, snapshot_provider, watcher, Duration::from_millis(1500), ) } /// Construct a new [`Engine`] with a custom `DirtyCoalescer` debounce window. #[must_use] pub fn with_debounce( config: Arc, cache: Arc, scanner: Arc, volume_telemetry: Arc, snapshot_provider: Arc, watcher: Arc, debounce: Duration, ) -> Self { let (events_tx, _) = broadcast::channel(256); let completed_ns = cache.meta().map_or(0, |m| m.last_full_scan_completed_ns); Self { config, cache, scanner, volume_telemetry, snapshot_provider, watcher, events_tx, status: RwLock::new(EngineStatus { scan_state: ScanState::Idle, progress: ScanProgress::default(), fsevents_active: false, last_full_scan_completed_ns: completed_ns, }), latest_volume: RwLock::new(None), latest_snapshots: RwLock::new(None), started_at: Instant::now(), debounce, } } /// Subscribe to live [`EngineEvent`]s. #[must_use] pub fn subscribe(&self) -> broadcast::Receiver { self.events_tx.subscribe() } /// Service uptime in seconds. #[must_use] pub fn uptime_secs(&self) -> u64 { self.started_at.elapsed().as_secs() } /// Current scan and watcher status. #[must_use] pub fn status(&self) -> EngineStatus { self.status .read() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone() } /// Latest cached [`VolumeStats`], querying synchronously if not yet populated. #[must_use] pub fn volume_stats(&self) -> Option { self.latest_volume .read() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone() } /// Latest cached [`SnapshotInventory`]. #[must_use] pub fn snapshot_inventory(&self) -> Option { self.latest_snapshots .read() .unwrap_or_else(std::sync::PoisonError::into_inner) .clone() } /// Refresh volume telemetry synchronously (intended for `spawn_blocking`). pub fn refresh_volume_sync(&self) -> Option { match self.volume_telemetry.read_volume(&self.config.home_root) { Ok(stats) => { *self .latest_volume .write() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(stats.clone()); let _ = self .events_tx .send(EngineEvent::VolumeUpdated(stats.clone())); Some(stats) } Err(err) => { warn!("volume telemetry refresh failed: {err}"); None } } } /// Refresh Time Machine snapshot inventory synchronously (intended for `spawn_blocking`). pub fn refresh_snapshots_sync(&self) -> Option { let mount = self .volume_stats() .map_or_else(|| "/System/Volumes/Data".to_string(), |v| v.mount_point); match self.snapshot_provider.read_snapshots(Path::new(&mount)) { Ok(inv) => { *self .latest_snapshots .write() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(inv.clone()); let _ = self .events_tx .send(EngineEvent::SnapshotsUpdated(inv.clone())); Some(inv) } Err(err) => { warn!("snapshot telemetry refresh failed: {err}"); None } } } /// Start the `FSEvents` watcher, background startup full scan, and periodic telemetry pollers. pub fn start(self: &Arc, run_initial_scan: bool) -> Result { let (shutdown_tx, shutdown_rx) = watch::channel(false); let (fs_tx, fs_rx) = mpsc::channel::(4096); let overflow = Arc::new(AtomicBool::new(false)); let watcher_guard = self.watcher .start(&self.config.home_root, fs_tx, Arc::clone(&overflow))?; { let mut st = self.status.write().unwrap_or_else(|p| { error!("Engine status RwLock poisoned"); p.into_inner() }); st.fsevents_active = true; if run_initial_scan { // Mark Scanning before spawning so watcher events buffer until replace_full_scan commits. st.scan_state = ScanState::Scanning; } } // Initial telemetry seed let engine_init = Arc::clone(self); tokio::task::spawn_blocking(move || { engine_init.refresh_volume_sync(); engine_init.refresh_snapshots_sync(); }); // Background full startup scan if run_initial_scan { let engine_scan = Arc::clone(self); tokio::task::spawn_blocking(move || { engine_scan.run_full_scan_sync(); }); } // FSEvents consumer + DirtyCoalescer loop let engine_watch = Arc::clone(self); let mut watch_shutdown = shutdown_rx.clone(); tokio::spawn(async move { engine_watch .run_watcher_loop(fs_rx, overflow, &mut watch_shutdown) .await; }); // Periodic volume + snapshot pollers let engine_poll = Arc::clone(self); let mut poll_shutdown = shutdown_rx; tokio::spawn(async move { engine_poll.run_telemetry_pollers(&mut poll_shutdown).await; }); Ok(EngineHandle { shutdown_tx, _watcher_guard: watcher_guard, }) } /// Execute a full scan of `home_root` synchronously and update the SQLite cache. pub fn run_full_scan_sync(&self) { let started_ns = current_time_ns(); { let mut st = self .status .write() .unwrap_or_else(std::sync::PoisonError::into_inner); st.scan_state = ScanState::Scanning; st.progress = ScanProgress::default(); } let _ = self.events_tx.send(EngineEvent::ScanProgress { scan_state: ScanState::Scanning, progress: ScanProgress::default(), }); let events_tx = self.events_tx.clone(); let res = self.scanner.scan_full(&self.config.home_root, &|prog| { if let Ok(mut st) = self.status.write() { st.progress = prog; } let _ = events_tx.send(EngineEvent::ScanProgress { scan_state: ScanState::Scanning, progress: prog, }); }); match res { Ok(scan) => { let completed_ns = current_time_ns(); if let Err(err) = self.cache.replace_full_scan( &scan, &self.config.home_root, started_ns, completed_ns, ) { warn!("failed to persist full scan: {err}"); } { let mut st = self .status .write() .unwrap_or_else(std::sync::PoisonError::into_inner); st.scan_state = ScanState::Idle; st.progress = scan.progress; st.last_full_scan_completed_ns = completed_ns; } let _ = self.events_tx.send(EngineEvent::ScanProgress { scan_state: ScanState::Idle, progress: scan.progress, }); info!( dirs = scan.progress.scanned_dirs, files = scan.progress.scanned_files, physical_bytes = scan.progress.scanned_physical_bytes, "full startup scan complete" ); } Err(err) => { warn!("full startup scan failed: {err}"); let mut st = self .status .write() .unwrap_or_else(std::sync::PoisonError::into_inner); st.scan_state = ScanState::Idle; } } } async fn run_watcher_loop( self: Arc, mut fs_rx: mpsc::Receiver, overflow: Arc, shutdown_rx: &mut watch::Receiver, ) { let cache_dir = self .config .cache_path .parent() .map_or_else(|| self.config.cache_path.clone(), Path::to_path_buf); let mut coalescer = DirtyCoalescer::with_excluded_dirs( self.config.home_root.clone(), vec![cache_dir, self.config.log_dir.clone()], self.debounce, ); let tick_ms = (self.debounce.as_millis() as u64 / 3).clamp(25, 250); let mut ticker = tokio::time::interval(Duration::from_millis(tick_ms)); let mut cumulative_abs_delta: u64 = 0; loop { tokio::select! { _ = shutdown_rx.changed() => { if *shutdown_rx.borrow() { break; } } maybe_ev = fs_rx.recv() => { match maybe_ev { Some(ev) => coalescer.ingest(&ev, Instant::now()), None => break, } } _ = ticker.tick() => { if overflow.swap(false, Ordering::AcqRel) { coalescer.ingest( &RawFsEvent { paths: vec![self.config.home_root.clone()], recursive_hint: true, is_dir_change: true, }, Instant::now(), ); } // Defer draining while a full startup scan is in flight so concurrent // edits are replayed after `replace_full_scan` commits. if self.status().scan_state == ScanState::Scanning { continue; } let actions = coalescer.drain_ready(Instant::now()); if actions.is_empty() { continue; } let engine_clone = Arc::clone(&self); let delta_sum = tokio::task::spawn_blocking(move || { engine_clone.apply_dirty_actions(actions) }).await.unwrap_or(0); cumulative_abs_delta = cumulative_abs_delta.saturating_add(delta_sum); if cumulative_abs_delta >= VOLUME_NUDGE_THRESHOLD_BYTES { cumulative_abs_delta = 0; let engine_vol = Arc::clone(&self); tokio::task::spawn_blocking(move || { engine_vol.refresh_volume_sync(); }); } } } } } fn apply_dirty_actions(&self, actions: Vec) -> u64 { let root_dev = std::fs::symlink_metadata(&self.config.home_root) .ok() .map(|m| metadata_dev(&m)); let is_valid_local_dir = |fs_path: &Path| -> bool { let Ok(meta) = std::fs::symlink_metadata(fs_path) else { return false; }; if meta.file_type().is_symlink() || !meta.file_type().is_dir() { return false; } root_dev.is_none_or(|rd| is_same_mount(fs_path, &meta, rd)) }; let mut abs_delta_sum = 0_u64; for action in actions { match action { DirtyAction::DirectDir(rel) => { let fs_path = rel.to_fs_path(&self.config.home_root); let summary = if is_valid_local_dir(&fs_path) { match self .scanner .scan_directory_direct(&self.config.home_root, &rel) { Ok(direct) => self.cache.apply_directory_delta(&rel, &direct), Err(err) => { warn!("direct rescan failed for {}: {err}", rel.as_str()); continue; } } } else { self.cache.remove_subtree(&rel) }; if let Ok(sum) = summary && (sum.delta_physical_bytes != 0 || sum.delta_logical_bytes != 0) { abs_delta_sum = abs_delta_sum.saturating_add(sum.delta_physical_bytes.unsigned_abs()); let _ = self.events_tx.send(EngineEvent::DirUpdated { path: sum.path, delta_physical_bytes: sum.delta_physical_bytes, delta_logical_bytes: sum.delta_logical_bytes, }); } } DirtyAction::Subtree(rel) => { let fs_path = rel.to_fs_path(&self.config.home_root); let summary = if is_valid_local_dir(&fs_path) { match self.scanner.scan_subtree(&self.config.home_root, &rel) { Ok(sub) => self.cache.upsert_subtree(&rel, &sub), Err(err) => { warn!("subtree rescan failed for {}: {err}", rel.as_str()); continue; } } } else { self.cache.remove_subtree(&rel) }; if let Ok(sum) = summary && (sum.delta_physical_bytes != 0 || sum.delta_logical_bytes != 0) { abs_delta_sum = abs_delta_sum.saturating_add(sum.delta_physical_bytes.unsigned_abs()); let _ = self.events_tx.send(EngineEvent::DirUpdated { path: sum.path, delta_physical_bytes: sum.delta_physical_bytes, delta_logical_bytes: sum.delta_logical_bytes, }); } } } } abs_delta_sum } async fn run_telemetry_pollers(self: Arc, shutdown_rx: &mut watch::Receiver) { let vol_secs = self.config.volume_poll_secs.max(5); let snap_secs = self.config.snapshot_poll_secs.max(10); let mut vol_tick = tokio::time::interval(Duration::from_secs(vol_secs)); let mut snap_tick = tokio::time::interval(Duration::from_secs(snap_secs)); vol_tick.tick().await; snap_tick.tick().await; loop { tokio::select! { _ = shutdown_rx.changed() => { if *shutdown_rx.borrow() { break; } } _ = vol_tick.tick() => { let eng = Arc::clone(&self); tokio::task::spawn_blocking(move || { eng.refresh_volume_sync(); }); } _ = snap_tick.tick() => { let eng = Arc::clone(&self); tokio::task::spawn_blocking(move || { eng.refresh_snapshots_sync(); }); } } } } } /// Helper to validate and parse a relative path string. pub fn parse_rel_path(raw: &str) -> Result { RelPath::parse(raw) } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; use crate::macos::{FakeSnapshotProvider, FakeVolumeTelemetry}; use crate::scanner::ApfsScanner; use crate::watcher::FakeWatcher; use std::fs; use tempfile::TempDir; #[tokio::test] async fn fake_watcher_file_changes_update_cache_and_emit_events() { let tmp = TempDir::new().unwrap(); let home = tmp.path().to_path_buf(); fs::create_dir_all(home.join("Projects")).unwrap(); fs::write(home.join("Projects/a.bin"), vec![b'x'; 4096]).unwrap(); let cfg = Arc::new(Config::load_from(&home, None, None).unwrap()); let cache = Arc::new(CacheStore::open_in_memory().unwrap()); let scanner = Arc::new(ApfsScanner::new()); let vol = Arc::new(FakeVolumeTelemetry::new(VolumeStats { volume_name: "Data".to_string(), mount_point: "/System/Volumes/Data".to_string(), device_identifier: "disk3s5".to_string(), container_ref: Some("disk3".to_string()), filesystem_type: Some("apfs".to_string()), total_bytes: 500_000_000_000, strictly_free_bytes: 100_000_000_000, purgeable_bytes: 20_000_000_000, important_available_bytes: 120_000_000_000, opportunistic_available_bytes: 110_000_000_000, sibling_volumes: Vec::new(), })); let snaps = Arc::new(FakeSnapshotProvider::new(SnapshotInventory::default())); let fake_watcher = Arc::new(FakeWatcher::new()); let engine = Arc::new(Engine::with_debounce( cfg, Arc::clone(&cache), scanner, vol, snaps, fake_watcher.clone(), Duration::from_millis(40), )); let mut rx = engine.subscribe(); engine.run_full_scan_sync(); let handle = engine.start(false).unwrap(); // Add a new file and inject FakeWatcher event let new_file = home.join("Projects/b.bin"); fs::write(&new_file, vec![b'y'; 8192]).unwrap(); fake_watcher.push_event(RawFsEvent { paths: vec![new_file], recursive_hint: false, is_dir_change: false, }); let mut saw_dir_updated = false; let deadline = tokio::time::Instant::now() + Duration::from_secs(2); while tokio::time::Instant::now() < deadline { if let Ok(Ok(EngineEvent::DirUpdated { path, delta_logical_bytes, .. })) = tokio::time::timeout(Duration::from_millis(200), rx.recv()).await && path == "Projects" && delta_logical_bytes == 8192 { saw_dir_updated = true; break; } } assert!(saw_dir_updated, "expected DirUpdated for Projects"); let root_rec = cache .get_directory_record(&RelPath::root()) .unwrap() .unwrap(); assert_eq!(root_rec.subtree_logical_bytes, 4096 + 8192); handle.shutdown(); } }