//! The background loop: watch → settle → save → sync, for one vault. use crate::config::VaultConfig; use crate::remote; use crate::state::{self, SyncState}; use crate::vault::{SyncReport, Vault}; use anyhow::{Result, bail}; use notify::{EventKind, RecursiveMode, Watcher}; use std::collections::{HashMap, HashSet}; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc; use std::time::{Duration, Instant}; /// Timing for bursts of edits (S2). #[derive(Debug, Clone, Copy)] pub struct Timing { /// A burst ends after this much quiet... pub quiet: Duration, /// ...or at the latest this long after it started. pub cap: Duration, /// When a burst is cut at the cap, files changed more recently than this wait for the next one. pub settle: Duration, } impl Default for Timing { fn default() -> Self { Timing { quiet: Duration::from_secs(5), cap: Duration::from_secs(60), settle: Duration::from_secs(2) } } } /// Tracks the current burst of edits. #[derive(Debug, Default)] pub struct Burst { started: Option, last: Option, touched: HashMap, } impl Burst { pub fn touch(&mut self, path: String, now: Instant) { self.started.get_or_insert(now); self.last = Some(now); self.touched.insert(path, now); } pub fn is_idle(&self) -> bool { self.started.is_none() } pub fn due(&self, now: Instant, t: &Timing) -> bool { match (self.started, self.last) { (Some(s), Some(l)) => now - l >= t.quiet || now - s >= t.cap, _ => false, } } /// Ends the burst. Returns files still changing, which must not be saved yet; they start the next burst. pub fn take(&mut self, now: Instant, t: &Timing) -> HashSet { let unsettled: HashMap = self.touched.drain().filter(|(_, at)| now - *at < t.settle).collect(); let skip = unsettled.keys().cloned().collect(); *self = Burst::default(); if !unsettled.is_empty() { self.started = Some(now); self.last = unsettled.values().max().copied(); self.touched = unsettled; } skip } } pub type Log<'a> = &'a (dyn Fn(&str, &str) + Sync); /// Set to stop every runner in this process (the desktop app uninstalling); each lets go of its vault. pub static STOP: AtomicBool = AtomicBool::new(false); /// Runs forever for one vault. `log(vault, message)` prints progress. pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log: Log) -> Result<()> { let vault = Vault::open(cfg, label)?; let Some(_running) = state::try_run_lock(&vault.git_dir)? else { bail!("{} is already being synced by another lunesync run", cfg.name); }; let (tx, rx) = mpsc::channel(); let mut watcher = notify::recommended_watcher(move |ev| { let _ = tx.send(ev); })?; watcher.watch(&vault.root, RecursiveMode::Recursive)?; let say = |m: &str| log(&vault.name, m); say(&format!("watching {} as {}", vault.root.display(), label)); let mut burst = Burst::default(); let mut rescan_at = Instant::now(); // pick up anything changed while we weren't running let mut sync_at = Instant::now(); let mut backoff = poll; let mut was_waiting = false; let mut was_holding = false; let mut was_read_only = false; let mut announced: HashSet = HashSet::new(); // Set when notes changed here (this device's burst was saved, or others' arrived): GBrain vaults refresh. let mut brain_due = false; let leaving = state::lune_dir(&vault.git_dir).join("leaving"); let nudge = state::lune_dir(&vault.git_dir).join("nudge"); loop { if leaving.exists() { say("access to this vault ended — stopped syncing it"); return Ok(()); } if STOP.load(Ordering::Relaxed) { return Ok(()); } if nudge.exists() { // Nudged from the canvas: save what has settled and share right away. let _ = std::fs::remove_file(&nudge); rescan_at = Instant::now(); sync_at = Instant::now(); } let first = rx.recv_timeout(Duration::from_millis(250)); for ev in first.into_iter().chain(rx.try_iter()) { match ev { Ok(ev) if !matches!(ev.kind, EventKind::Access(_)) => { for p in ev.paths { if let Some(rel) = relevant(&vault, &p) { burst.touch(rel, Instant::now()); } } } Ok(_) => {} Err(e) => say(&format!("file watcher hiccup: {e}")), } } let now = Instant::now(); let rescan = now >= rescan_at && burst.is_idle(); if rescan || burst.due(now, &timing) { let skip = burst.take(now, &timing); rescan_at = now + Duration::from_secs(60); let _op = state::op_lock(&vault.git_dir)?; match vault.save_changes(None, &skip) { Ok(Some(saved)) => { say(&format!("saved: {}", saved.message)); brain_due = true; if let Some(d) = saved.held { say(&format!( "HELD: this change removes or rewrites {} of {} notes, so it stays on this device. \ `lunesync held share` to send it anyway, `lunesync held undo` to bring everything back", d.removed + d.rewritten, d.total )); } sync_at = now; } Ok(None) => {} Err(e) => say(&format!("couldn't save changes: {e:#}")), } match vault.secret_holds() { Ok(notes) => { let mut current = HashSet::new(); for n in notes { for h in n.hits { let key = format!("{}:{}", n.path, h.line_hash); if !announced.contains(&key) { say(&format!( "HELD: {} line {} has a possible {} ({}), so this note isn't shared. \ `lunesync held` to replace it with a pointer or mark it not a secret", n.path, h.line, h.rule, h.hint )); } current.insert(key); } } announced = current; } Err(e) => say(&format!("couldn't run the secret check: {e:#}")), } } if Instant::now() >= sync_at { let _op = state::op_lock(&vault.git_dir)?; let result = vault.sync(); let mut st = SyncState::load(&vault.git_dir); st.last_attempt = Some(chrono::Utc::now().timestamp()); match result { Ok(report) => { st.last_error = None; if !report.waiting_for_local_edits && !report.holding { st.last_synced = st.last_attempt; } if report.holding && !was_holding { say("not sharing anything from this device while a big change is held"); } was_holding = report.holding; if report.read_only && !was_read_only { say("your changes here aren't shared — you have read access to this vault"); } was_read_only = report.read_only; if report.waiting_for_local_edits && !was_waiting { say("new changes are waiting until your current edits settle"); } was_waiting = report.waiting_for_local_edits; brain_due |= !report.received.is_empty(); print_report(&report, &say); backoff = poll; sync_at = Instant::now() + poll; } Err(e) => { let msg = remote::describe_error(&e); if st.last_error.as_deref() != Some(msg.as_str()) { say(&format!("{msg} — will keep trying")); } st.last_error = Some(msg); backoff = (backoff * 2).min(Duration::from_secs(60)); sync_at = Instant::now() + backoff; } } if let Err(e) = st.save(&vault.git_dir) { say(&format!("couldn't record sync status: {e:#}")); } } if brain_due { brain_due = false; // The settings are read fresh: the hub can change a vault's kind, and the person can turn refreshing on, while we run. let current = crate::config::Config::load() .ok() .and_then(|c| c.vaults.into_iter().find(|v| v.path == cfg.path)) .unwrap_or_else(|| cfg.clone()); if crate::brain::after_changes(¤t) { say("refreshing GBrain in the background"); } } } } /// Vault-relative path for a watcher event, or None for our own files and ignored ones. fn relevant(vault: &Vault, p: &Path) -> Option { let rel = p.strip_prefix(&vault.root).ok()?; if rel.as_os_str().is_empty() || rel.starts_with(".git") { return None; } if vault.is_ignored(rel) { return None; } Some(crate::names::slash_path(rel)) } fn print_report(r: &SyncReport, say: &dyn Fn(&str)) { if !r.received.is_empty() { let from: Vec<&str> = r.from.iter().map(String::as_str).collect(); let who = if from.is_empty() { String::new() } else { format!(" from {}", from.join(", ")) }; say(&format!("received {}{who}", count_notes(&r.received))); } for (note, copy) in &r.kept_both { say(&format!("{note} was changed in two places — kept both, yours is in \"{copy}\"")); } for note in &r.joined { say(&format!("{note} was added to in two places — both kept, the other device's lines first")); } for note in &r.to_tidy { say(&format!("{note} was changed in two places — the other version stays, yours waits under Notes to tidy")); } for note in &r.held_to_tidy { say(&format!("{note} changed elsewhere while held here — your held version waits under Notes to tidy")); } for (note, copy) in &r.set_aside { say(&format!("{note} changed elsewhere while held here — your held version is now \"{copy}\"")); } for (old, new) in &r.case_renamed { say(&format!("{old} clashed with another name differing only by case — renamed to {new}")); } if r.shared > 0 { say(&format!("shared {} change{}", r.shared, if r.shared == 1 { "" } else { "s" })); } } fn count_notes(files: &[String]) -> String { match files { [one] => one.clone(), many => format!("{} notes", many.len()), } } #[cfg(test)] mod tests { use super::*; #[test] fn burst_ends_after_quiet_or_cap_and_holds_back_unsettled_files() { let t = Timing::default(); let t0 = Instant::now(); let s = Duration::from_secs; let mut b = Burst::default(); assert!(!b.due(t0, &t)); b.touch("a.md".into(), t0); b.touch("b.md".into(), t0 + s(3)); assert!(!b.due(t0 + s(7), &t)); assert!(b.due(t0 + s(8), &t)); assert!(b.take(t0 + s(8), &t).is_empty()); assert!(!b.due(t0 + s(100), &t)); // A file written every second never goes quiet: the cap ends the burst without it. let mut b = Burst::default(); b.touch("done.md".into(), t0); for i in 0..=60 { b.touch("log.md".into(), t0 + s(i)); } assert!(b.due(t0 + s(60), &t)); let skip = b.take(t0 + s(60), &t); assert_eq!(skip, HashSet::from(["log.md".to_string()])); assert!(b.due(t0 + s(65), &t), "the still-changing file starts the next burst"); } }