diff --git a/crates/grove-core/src/busy.rs b/crates/grove-core/src/busy.rs new file mode 100644 index 0000000..58f399f --- /dev/null +++ b/crates/grove-core/src/busy.rs @@ -0,0 +1,88 @@ +//! The "busy" marker: `/.grove-busy` exists while grove restructures a repo (`grove add`, +//! clone/import, init). The daemon treats such a repo as not ready and leaves it alone until the +//! marker is gone, so it never fetches, materializes or snapshots a half-built layout. +//! +//! The marker holds ` `. A marker whose process is gone is *stale*: the +//! operation was interrupted, the repo may be half-migrated, and nothing removes the marker +//! automatically. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +pub const BUSY: &str = ".grove-busy"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BusyState { + Free, + /// The marker's process is still running. + Active, + /// The marker's process is gone: an interrupted operation. + Stale, +} + +/// Holds the marker; removes it on drop, so also on error paths and rollback. +#[derive(Debug)] +pub struct BusyGuard(PathBuf); + +impl BusyGuard { + /// Creates `/.grove-busy` (and `dir` if needed). Fails if the marker already exists. + pub fn acquire(dir: &Path) -> io::Result { + fs::create_dir_all(dir)?; + let path = dir.join(BUSY); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let mut f = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&path)?; + io::Write::write_all(&mut f, format!("{} {now}\n", std::process::id()).as_bytes())?; + Ok(BusyGuard(path)) + } +} + +impl Drop for BusyGuard { + fn drop(&mut self) { + let _ = fs::remove_file(&self.0); + } +} + +/// State of the marker in `dir`. +pub fn busy_state(dir: &Path) -> BusyState { + let Ok(text) = fs::read_to_string(dir.join(BUSY)) else { + return if dir.join(BUSY).exists() { + BusyState::Stale + } else { + BusyState::Free + }; + }; + match text + .split_whitespace() + .next() + .and_then(|p| p.parse::().ok()) + { + Some(pid) if Path::new(&format!("/proc/{pid}")).exists() => BusyState::Active, + _ => BusyState::Stale, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn marker_lifecycle() { + let d = std::env::temp_dir().join(format!("grove-busy-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + assert_eq!(busy_state(&d), BusyState::Free); + let g = BusyGuard::acquire(&d).unwrap(); + assert_eq!(busy_state(&d), BusyState::Active); + assert!(BusyGuard::acquire(&d).is_err()); + drop(g); + assert_eq!(busy_state(&d), BusyState::Free); + fs::write(d.join(BUSY), "999999999 1\n").unwrap(); + assert_eq!(busy_state(&d), BusyState::Stale); + fs::remove_dir_all(&d).unwrap(); + } +} diff --git a/crates/grove-core/src/lib.rs b/crates/grove-core/src/lib.rs index 8f68d35..59e8c8e 100644 --- a/crates/grove-core/src/lib.rs +++ b/crates/grove-core/src/lib.rs @@ -1,5 +1,6 @@ //! Sync engine core: git plumbing wrapper, config, snapshots and state classification. +pub mod busy; pub mod config; pub mod git; pub mod inspect; diff --git a/crates/grove-core/src/migrate.rs b/crates/grove-core/src/migrate.rs index 8cf143e..2c95eec 100644 --- a/crates/grove-core/src/migrate.rs +++ b/crates/grove-core/src/migrate.rs @@ -19,6 +19,7 @@ use std::process::Command; const BARE: &str = ".bare"; const STAGE: &str = ".grove-stage"; +const BUSY: &str = crate::busy::BUSY; #[derive(Debug)] pub enum MigrateError { @@ -477,7 +478,9 @@ fn migrate_inner( let (backup_tar, backup_ref, linked_backups) = backup(&root, &git, machine, backup_dir, stamp, &linked)?; - let dir = dir_name(&branch, &[BARE, STAGE]); + let dir = dir_name(&branch, &[BARE, STAGE, BUSY]); + // From here on the daemon must leave the repo alone; dropped last, also after a rollback. + let _busy = crate::busy::BusyGuard::acquire(&root)?; let mut p = Progress { orig_ids: list_ids(&root.join(".git")), ..Progress::default() @@ -573,7 +576,7 @@ fn run_steps( // 1. Move everything except .git into a staging dir. fs::create_dir(&stage).map_err(s)?; p.staged = true; - move_entries(root, &stage, &[".git", STAGE]).map_err(s)?; + move_entries(root, &stage, &[".git", STAGE, BUSY]).map_err(s)?; hook(inject, Step::Staged)?; // 2. .git -> .bare, make it bare. diff --git a/crates/grove-core/src/registry.rs b/crates/grove-core/src/registry.rs index d6fd454..7ffa970 100644 --- a/crates/grove-core/src/registry.rs +++ b/crates/grove-core/src/registry.rs @@ -5,7 +5,6 @@ use crate::git::{Git, GitError}; use crate::layout::dir_name; use crate::receive::{ensure_fetch_refspec, materialize}; use serde::{Deserialize, Serialize}; -use std::fs; use std::path::{Path, PathBuf}; #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)] @@ -53,7 +52,8 @@ pub fn clone_bare_layout( dir: &Path, envs: &[(String, String)], ) -> Result, GitError> { - fs::create_dir_all(dir)?; + // Released last: until then the daemon ignores the half-built repo. + let _busy = crate::busy::BusyGuard::acquire(dir)?; let bare = dir.join(".bare"); let mut g = Git::new(dir); for (k, v) in envs { @@ -85,7 +85,7 @@ pub fn clone_bare_layout( /// Creates a brand new local repo in the bare layout with an initial empty commit on `main`, /// pointing at `url`. Nothing is pushed here. pub fn init_bare_layout(dir: &Path, url: &str) -> Result { - fs::create_dir_all(dir)?; + let _busy = crate::busy::BusyGuard::acquire(dir)?; let bare = dir.join(".bare"); let g = Git::new(dir); g.run(&[ diff --git a/crates/grove-core/tests/migrate.rs b/crates/grove-core/tests/migrate.rs index 8be8960..1071f73 100644 --- a/crates/grove-core/tests/migrate.rs +++ b/crates/grove-core/tests/migrate.rs @@ -422,3 +422,34 @@ fn rollback_restores_linked_worktrees_at_every_step() { migrate(&repo, "m", &base.join("bk"), "2").unwrap(); } } + +#[test] +fn busy_marker_is_gone_after_success_and_after_rollback() { + let base = tmpdir("busy"); + let repo = base.join("ok"); + messy_repo(&repo); + migrate(&repo, "m", &base.join("bk"), "1").unwrap(); + assert!(!repo.join(".grove-busy").exists()); + + let repo = base.join("failing"); + messy_repo(&repo); + let err = migrate_failing_after(&repo, "m", &base.join("bk"), "2", Step::Filled).unwrap_err(); + assert!(matches!( + err, + MigrateError::Failed { + rolled_back: true, + .. + } + )); + assert!(!repo.join(".grove-busy").exists()); +} + +#[test] +fn migrate_refuses_while_another_operation_holds_the_marker() { + let base = tmpdir("busy2"); + let repo = base.join("proj"); + messy_repo(&repo); + let _held = grove_core::busy::BusyGuard::acquire(&repo.canonicalize().unwrap()).unwrap(); + assert!(migrate(&repo, "m", &base.join("bk"), "1").is_err()); + assert!(repo.join(".git").is_dir()); +} diff --git a/crates/grove-daemon/src/daemon.rs b/crates/grove-daemon/src/daemon.rs index dc97d9b..9febdba 100644 --- a/crates/grove-daemon/src/daemon.rs +++ b/crates/grove-daemon/src/daemon.rs @@ -3,14 +3,14 @@ //! so passes never overlap. use crate::activity::{Activity, now_secs}; -use crate::discover::{discover, group_of}; +use crate::discover::{discover, group_of, is_ready, subdirs}; use crate::ipc; use crate::visibility::{RealForge, Visibility, snapshot_gate}; use grove_core::config::Config; use grove_core::receive::Received; use grove_core::sync::{Options, sync_repo}; use notify::{EventKind, RecursiveMode, Watcher}; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; @@ -19,6 +19,9 @@ use std::thread::JoinHandle; use std::time::{Duration, Instant}; const MAX_BACKOFF: Duration = Duration::from_secs(300); +/// Quiet time after the first layout event before rediscovery runs (`grove add` does several +/// renames in a row). +const RESCAN_DEBOUNCE: Duration = Duration::from_millis(500); #[derive(Debug, Clone)] pub struct Settings { @@ -87,6 +90,8 @@ pub struct Shared { pub enum Msg { Changed(PathBuf), + /// The layout under a group directory may have changed: rediscover (debounced). + Rescan, /// Sync one repo (or all) as soon as possible. SyncNow(Option), Shutdown, @@ -171,6 +176,7 @@ pub fn ignored(rel: &Path, extra: &[String]) -> bool { let n = c.as_os_str().to_string_lossy(); n == ".git" || n == ".bare" + || n == ".grove-busy" || n == ".grove-stage" || extra.iter().any(|p| pattern_matches(p, &n)) }) @@ -180,13 +186,56 @@ fn repo_of<'a>(path: &Path, repos: &'a [PathBuf]) -> Option<&'a PathBuf> { repos.iter().find(|r| path.starts_with(r)) } +/// True for events that may change what is managed: a child directory of a configured group +/// appearing, disappearing or being renamed, a group directory itself doing so under the root, or +/// `.bare` / `.git` appearing or disappearing inside such a child. +pub fn triggers_rediscovery(path: &Path, root: &Path, groups: &[String]) -> bool { + let Ok(rel) = path.strip_prefix(root) else { + return false; + }; + let parts: Vec = rel + .components() + .map(|c| c.as_os_str().to_string_lossy().into_owned()) + .collect(); + let in_group = |n: &String| groups.contains(n); + match parts.as_slice() { + [g] => in_group(g), + [g, _] => in_group(g), + [g, _, f] => { + in_group(g) + && matches!( + f.as_str(), + ".bare" | ".git" | ".grove-busy" | ".grove-stage" + ) + } + _ => false, + } +} + struct Watch { watcher: Option, repos: Arc>>, - watched: Vec, + /// Watched paths: whether the watch is recursive, and the (device, inode) of the directory it + /// was set on, so a directory deleted and recreated under the same name is watched anew. + watched: HashMap)>, + /// Paths whose watch failed and was already reported (reported once until it succeeds). + watch_failed: HashSet, + /// Stalled repos already warned about. + warned_stalled: HashSet, } -fn make_watch(tx: Sender, extra: Vec, ctx: &Ctx) -> Watch { +fn dir_id(p: &Path) -> Option<(u64, u64)> { + use std::os::unix::fs::MetadataExt; + std::fs::metadata(p).ok().map(|m| (m.dev(), m.ino())) +} + +fn make_watch( + tx: Sender, + extra: Vec, + root: PathBuf, + groups: Vec, + ctx: &Ctx, +) -> Watch { let repos: Arc>> = Arc::default(); let cb_repos = repos.clone(); let handler = move |res: notify::Result| { @@ -196,6 +245,9 @@ fn make_watch(tx: Sender, extra: Vec, ctx: &Ctx) -> Watch { } let repos = cb_repos.lock().unwrap(); for p in &ev.paths { + if triggers_rediscovery(p, &root, &groups) { + let _ = tx.send(Msg::Rescan); + } if let Some(r) = repo_of(p, &repos) && let Ok(rel) = p.strip_prefix(r) && !ignored(rel, &extra) @@ -218,45 +270,132 @@ fn make_watch(tx: Sender, extra: Vec, ctx: &Ctx) -> Watch { Watch { watcher, repos, - watched: Vec::new(), + watched: HashMap::new(), + watch_failed: HashSet::new(), + warned_stalled: HashSet::new(), } } impl Watch { - fn add(&mut self, repo: &Path, ctx: &Ctx) { - if self.watched.iter().any(|w| w == repo) { - return; + /// Adds the watches in `wanted` that are missing, and replaces watches whose directory was + /// deleted and recreated. With `prune`, also removes watches that are no longer wanted or + /// whose mode changed. Nothing in the watched directories is touched. + fn sync(&mut self, wanted: &HashMap, prune: bool, ctx: &Ctx) { + let stale: Vec = self + .watched + .iter() + .filter(|(p, (rec, id))| *id != dir_id(p) || (prune && wanted.get(*p) != Some(rec))) + .map(|(p, _)| p.clone()) + .collect(); + for p in stale { + self.watched.remove(&p); + if let Some(w) = &mut self.watcher { + let _ = w.unwatch(&p); + } } - self.watched.push(repo.to_path_buf()); - self.repos.lock().unwrap().push(repo.to_path_buf()); - if let Some(w) = &mut self.watcher - && let Err(e) = w.watch(repo, RecursiveMode::Recursive) - { - ctx.activity.log( - "watch_error", - Some(&repo.display().to_string()), - format!( - "cannot watch (raise fs.inotify.max_user_watches?): {e}; relying on periodic passes" - ), - ); + for (p, rec) in wanted { + if self.watched.contains_key(p) { + continue; + } + let Some(id) = dir_id(p) else { continue }; + let mode = if *rec { + RecursiveMode::Recursive + } else { + RecursiveMode::NonRecursive + }; + let Some(w) = &mut self.watcher else { continue }; + match w.watch(p, mode) { + Ok(()) => { + self.watched.insert(p.clone(), (*rec, Some(id))); + self.watch_failed.remove(p); + } + // Not recorded as watched, so the next rescan retries. + Err(e) => { + if self.watch_failed.insert(p.clone()) { + ctx.activity.log( + "watch_error", + Some(&p.display().to_string()), + format!( + "cannot watch (raise fs.inotify.max_user_watches?): {e}; relying on periodic passes" + ), + ); + } + } + } } } } -fn rescan(root: &Path, groups: &[String], watch: &mut Watch, ctx: &Ctx) -> Vec { +/// Re-runs discovery and makes the shared status, the watches and the repo list match it. +/// Returns the managed repos found now and the ones that were not managed before. +fn rescan( + root: &Path, + groups: &[String], + watch: &mut Watch, + ctx: &Ctx, +) -> (Vec, Vec) { + // Shallow watches first, then discover: a `.bare` created in a child between the two steps + // is then still seen as an event. + let mut wanted: HashMap = HashMap::new(); + wanted.insert(root.to_path_buf(), false); + for g in groups { + let gdir = root.join(g); + wanted.insert(gdir.clone(), false); + for child in subdirs(&gdir) { + // Children that are not managed yet are watched shallowly so `.bare` appearing + // inside them (`grove add`, `grove import`) is noticed. + wanted.insert(child, false); + } + } + watch.sync(&wanted, false, ctx); let d = discover(root, groups); let found = d.managed; - let mut shared = ctx.shared.lock().unwrap(); - shared.not_migrated = d.not_migrated; - shared.repos.retain(|p, _| found.contains(p)); - for r in &found { - shared.repos.entry(r.clone()).or_default(); + for r in &d.stalled { + if watch.warned_stalled.insert(r.clone()) { + ctx.activity.log( + "repo_stalled", + Some(&r.display().to_string()), + "WARNING: left alone: an interrupted `grove add`/clone left `.grove-busy` or `.grove-stage` behind; check the repo and restore from the backups, then remove the marker by hand", + ); + } } - drop(shared); - for r in &found { - watch.add(r, ctx); + watch.warned_stalled.retain(|p| d.stalled.contains(p)); + let mut added = Vec::new(); + let mut removed = Vec::new(); + { + let mut shared = ctx.shared.lock().unwrap(); + shared.not_migrated = d.not_migrated; + shared.repos.retain(|p, _| { + let keep = found.contains(p); + if !keep { + removed.push(p.clone()); + } + keep + }); + for r in &found { + if !shared.repos.contains_key(r) { + shared.repos.insert(r.clone(), RepoStatus::default()); + added.push(r.clone()); + } + } } - found + for r in &added { + ctx.activity + .log("repo_added", Some(&r.display().to_string()), "now managed"); + } + for r in &removed { + ctx.activity.log( + "repo_removed", + Some(&r.display().to_string()), + "no longer managed (directory gone or no longer a bare layout); files untouched", + ); + } + for r in &found { + wanted.insert(r.clone(), true); + } + *watch.repos.lock().unwrap() = found.clone(); + watch.sync(&wanted, true, ctx); + (found, added) } fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { @@ -265,7 +404,13 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { let root = cfg.root_path(); let groups: Vec = cfg.groups.iter().map(|g| g.name.clone()).collect(); let mut visibility = Visibility::load(st.visibility_cache.clone()); - let mut watch = make_watch(ctx.tx.clone(), cfg.sync.ignore_extra.clone(), &ctx); + let mut watch = make_watch( + ctx.tx.clone(), + cfg.sync.ignore_extra.clone(), + root.clone(), + groups.clone(), + &ctx, + ); rescan(&root, &groups, &mut watch, &ctx); // due_at: when a repo should next be synced; backoff_until: earliest retry after failures. @@ -276,6 +421,8 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { let mut first_at: HashMap = HashMap::new(); let max_wait = (debounce * 10).max(Duration::from_secs(5)); let mut next_full = Instant::now(); + // When a debounced rediscovery is due (set by the first event of a burst, never pushed back). + let mut rescan_at: Option = None; loop { let now = Instant::now(); @@ -283,6 +430,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { .values() .copied() .chain([next_full]) + .chain(rescan_at) .min() .unwrap_or(next_full); let mut timeout = wake @@ -306,6 +454,9 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { s.phase = "pending"; } } + Ok(Msg::Rescan) => { + rescan_at.get_or_insert(Instant::now() + RESCAN_DEBOUNCE); + } Ok(Msg::SyncNow(Some(r))) => { backoff_until.remove(&r); due_at.insert(r, Instant::now()); @@ -317,13 +468,23 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { Ok(Msg::Shutdown) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} } + // Discovery also runs while paused so the status stays current; only syncing stops. + if rescan_at.is_some_and(|t| t <= Instant::now()) { + rescan_at = None; + let (found, added) = rescan(&root, &groups, &mut watch, &ctx); + forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until); + for r in added { + due_at.insert(r, Instant::now()); + } + } if ctx.shared.lock().unwrap().paused { continue; } let now = Instant::now(); if now >= next_full { - let found = rescan(&root, &groups, &mut watch, &ctx); - due_at.retain(|r, _| found.contains(r)); + // Safety net for events the watcher missed (one `read_dir` per group). + let (found, _) = rescan(&root, &groups, &mut watch, &ctx); + forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until); for r in found { due_at.insert(r, now); } @@ -342,10 +503,22 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { } due_at.remove(&r); first_at.remove(&r); + if !is_ready(&r) { + // Removed or migrated away since the last discovery: drop it, no error. + let (found, _) = rescan(&root, &groups, &mut watch, &ctx); + forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until); + continue; + } // While backing off after a failure, still snapshot local work (no network needed); // the network is retried at the first pass after the backoff expires. let offline = backoff_until.get(&r).is_some_and(|u| *u > now); let failures = pass(&r, &cfg, &st, &mut visibility, offline, &ctx); + if !is_ready(&r) { + // It vanished mid-pass: whatever the pass reported is moot. + let (found, _) = rescan(&root, &groups, &mut watch, &ctx); + forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until); + continue; + } if offline { continue; } @@ -364,6 +537,18 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { ctx.activity.log("stop", None, "daemon stopped"); } +/// Drops scheduling state of repos that are no longer managed. +fn forget_removed( + found: &[PathBuf], + due_at: &mut HashMap, + first_at: &mut HashMap, + backoff_until: &mut HashMap, +) { + due_at.retain(|r, _| found.contains(r)); + first_at.retain(|r, _| found.contains(r)); + backoff_until.retain(|r, _| found.contains(r)); +} + /// One sync pass for `repo`; returns the number of consecutive failures (0 = success). fn pass( repo: &Path, @@ -374,6 +559,10 @@ fn pass( ctx: &Ctx, ) -> u32 { let name = repo.display().to_string(); + if !is_ready(repo) { + // Being migrated/cloned (or gone): leave it alone, the rediscovery sorts it out. + return 0; + } set_phase(ctx, repo, "syncing"); let group = group_of(repo).unwrap_or_default(); // `auto_materialize` is per group; a repo whose group is gone from the config keeps the default. @@ -409,7 +598,10 @@ fn pass( }; let result = sync_repo(repo, &opts); let mut shared = ctx.shared.lock().unwrap(); - let status = shared.repos.entry(repo.to_path_buf()).or_default(); + // The repo may have been dropped by a rediscovery while the pass ran. + let Some(status) = shared.repos.get_mut(repo) else { + return 0; + }; let mut errors: Vec = Vec::new(); match result { Err(e) => errors.push(e.to_string()), @@ -494,7 +686,9 @@ fn pass( /// Records why snapshots are withheld (or that they are pushed again), logging only changes. fn note_snapshot_gate(ctx: &Ctx, repo: &Path, name: &str, withheld: Option) { let mut shared = ctx.shared.lock().unwrap(); - let status = shared.repos.entry(repo.to_path_buf()).or_default(); + let Some(status) = shared.repos.get_mut(repo) else { + return; + }; status.gate_allowed = Some(withheld.is_none()); if status.snapshots_withheld == withheld { return; @@ -556,4 +750,22 @@ mod tests { assert!(ignored(Path::new("main/src/.a.rs.swp"), &extra)); assert!(!ignored(Path::new("main/src/a.rs"), &extra)); } + + #[test] + fn layout_events_trigger_rediscovery() { + let root = Path::new("/r"); + let g = vec!["g".to_string()]; + let t = |p: &str| triggers_rediscovery(Path::new(p), root, &g); + assert!(t("/r/g")); + assert!(t("/r/g/repo")); + assert!(t("/r/g/repo/.bare")); + assert!(t("/r/g/repo/.git")); + assert!(t("/r/g/repo/.grove-busy")); + assert!(t("/r/g/repo/.grove-stage")); + assert!(!t("/r/g/repo/main")); + assert!(!t("/r/g/repo/main/.bare")); + assert!(!t("/r/other")); + assert!(!t("/r/other/x/.bare")); + assert!(!t("/elsewhere/g/x")); + } } diff --git a/crates/grove-daemon/src/discover.rs b/crates/grove-daemon/src/discover.rs index 1515c32..94b33b3 100644 --- a/crates/grove-daemon/src/discover.rs +++ b/crates/grove-daemon/src/discover.rs @@ -2,14 +2,24 @@ //! groups, where the repo is in the bare + worktrees layout (has a `.bare` directory). Plain //! clones are never managed (they were not migrated with `grove add`); they are only reported. +use grove_core::busy::{BusyState, busy_state}; use std::path::{Path, PathBuf}; -fn is_bare_layout(p: &Path) -> bool { +pub fn is_bare_layout(p: &Path) -> bool { p.join(".bare").is_dir() } /// A linked worktree (`.git` file pointing into `/.git/worktrees/`) belongs to the repo /// it was added from; treating it as a repo of its own would sync the same worktrees twice. +/// A repo the daemon may touch: complete bare layout (`.bare/HEAD`), no migration/clone in +/// progress (`.grove-busy`) and no interrupted migration (`.grove-stage`). +pub fn is_ready(p: &Path) -> bool { + is_bare_layout(p) + && p.join(".bare/HEAD").exists() + && !p.join(".grove-stage").exists() + && busy_state(p) == BusyState::Free +} + fn is_linked_worktree(p: &Path) -> bool { std::fs::read_to_string(p.join(".git")).is_ok_and(|s| { s.trim() @@ -22,7 +32,7 @@ fn is_plain_clone(p: &Path) -> bool { !is_bare_layout(p) && p.join(".git").exists() && !is_linked_worktree(p) } -fn subdirs(p: &Path) -> Vec { +pub fn subdirs(p: &Path) -> Vec { let mut v: Vec = std::fs::read_dir(p) .into_iter() .flatten() @@ -42,6 +52,9 @@ pub struct Discovery { pub managed: Vec, /// Plain clones in configured groups: ignored, reported as "not migrated". pub not_migrated: Vec, + /// Bare-layout repos left alone because an interrupted `grove add`/clone left a stale + /// `.grove-busy` or a `.grove-stage` behind. + pub stalled: Vec, } /// Looks only at `root//` for each name in `groups` (cheap: one `read_dir` per @@ -53,8 +66,12 @@ pub fn discover(root: &Path, groups: &[String]) -> Discovery { groups.dedup(); for g in groups { for repo in subdirs(&root.join(g)) { - if is_bare_layout(&repo) { + if is_ready(&repo) { d.managed.push(repo); + } else if is_bare_layout(&repo) { + if busy_state(&repo) == BusyState::Stale || repo.join(".grove-stage").exists() { + d.stalled.push(repo); + } } else if is_plain_clone(&repo) { d.not_migrated.push(repo); } @@ -78,6 +95,10 @@ mod tests { let _ = std::fs::remove_dir_all(&base); for d in [ "grp/migrated/.bare", + "grp/halfway/.bare", + "grp/busy/.bare", + "grp/staged/.bare", + "grp/staged/.grove-stage", "grp/plain/.git", "grp/.hidden/.bare", "grp/notarepo/x", @@ -91,6 +112,19 @@ mod tests { ] { std::fs::create_dir_all(base.join(d)).unwrap(); } + for r in ["migrated", "busy", "staged"] { + std::fs::write( + base.join("grp").join(r).join(".bare/HEAD"), + "ref: refs/heads/main\n", + ) + .unwrap(); + } + // An active marker (this process) hides the repo; a stale one also gets it reported. + std::fs::write( + base.join("grp/busy/.grove-busy"), + format!("{} 1\n", std::process::id()), + ) + .unwrap(); // A linked worktree sitting next to its repo is neither managed nor "not migrated". std::fs::create_dir_all(base.join("grp/migrated-feature")).unwrap(); std::fs::write( @@ -103,6 +137,7 @@ mod tests { &["grp".to_string(), "grp2".to_string(), "absent".into()], ); assert_eq!(found.managed, vec![base.join("grp/migrated")]); + assert_eq!(found.stalled, vec![base.join("grp/staged")]); assert_eq!(found.not_migrated, vec![base.join("grp/plain")]); assert_eq!(group_of(&base.join("grp/migrated")).as_deref(), Some("grp")); std::fs::remove_dir_all(&base).unwrap(); diff --git a/crates/grove-daemon/tests/daemon.rs b/crates/grove-daemon/tests/daemon.rs index a82c797..8aabbde 100644 --- a/crates/grove-daemon/tests/daemon.rs +++ b/crates/grove-daemon/tests/daemon.rs @@ -527,3 +527,220 @@ fn snapshots_already_pushed_are_deleted_when_they_become_withheld() { let log = fs::read_to_string(w.base.join("pca.jsonl")).unwrap(); assert!(log.contains("snapshots_purged"), "{log}"); } + +/// A daemon whose periodic pass is far away, so only events (not the safety net) can notice changes. +fn start_event_only(w: &World, machine: &str) -> (Daemon, PathBuf) { + let st = settings(w, machine); + let sock = st.socket.clone(); + ( + Daemon::start(config(w, machine, 200, 3600), st).unwrap(), + sock, + ) +} + +fn repo_paths(sock: &Path) -> Vec { + let mut v: Vec = status(sock)["repos"] + .as_array() + .unwrap() + .iter() + .map(|r| r["path"].as_str().unwrap().to_string()) + .collect(); + v.sort(); + v +} + +#[test] +fn repo_migrated_after_start_is_picked_up_and_synced() { + let w = world("rd-migrate", &["pca"]); + let root = w.base.join("pca"); + let plain = root.join("g/plain"); + git( + &root.join("g"), + &["clone", "-q", w.remote.to_str().unwrap(), "plain"], + ); + let (d, sock) = start_event_only(&w, "pca"); + wait_until("plain clone reported", 10, || { + status(&sock)["not_migrated"] == json!([plain.display().to_string()]) + }); + + // Migrate in place, as `grove add` does: the clone goes away, the bare layout takes its place. + fs::remove_dir_all(&plain).unwrap(); + bare_layout(&plain, &w.remote); + wait_until("migrated repo managed", 10, || { + repo_paths(&sock).contains(&plain.display().to_string()) + && status(&sock)["not_migrated"] == json!([]) + }); + fs::write(plain.join("main/wip.txt"), "wip\n").unwrap(); + wait_until("snapshot of the new repo on the remote", 30, || { + git(&w.remote, &["for-each-ref", "refs/sync/pca/"]).contains("refs/sync/pca/main") + }); + d.shutdown(); +} + +#[test] +fn repo_cloned_with_bare_layout_after_start_is_picked_up() { + let w = world("rd-clone", &["pca"]); + let root = w.base.join("pca"); + let (d, sock) = start_event_only(&w, "pca"); + wait_until("initial repo listed", 10, || repo_paths(&sock).len() == 1); + + // Like `grove import`: the directory appears first, `.bare` a moment later. + let new = root.join("g/imported"); + fs::create_dir_all(&new).unwrap(); + std::thread::sleep(Duration::from_millis(800)); + assert_eq!(repo_paths(&sock).len(), 1); + bare_layout(&new, &w.remote); + wait_until("imported repo managed", 10, || { + repo_paths(&sock).contains(&new.display().to_string()) + }); + fs::write(new.join("main/wip.txt"), "wip\n").unwrap(); + wait_until("snapshot of the imported repo", 30, || { + git(&w.remote, &["for-each-ref", "refs/sync/pca/"]).contains("refs/sync/pca/main") + }); + d.shutdown(); +} + +#[test] +fn managed_repo_removed_after_start_disappears_without_crash() { + let w = world("rd-remove", &["pca"]); + let root = w.base.join("pca"); + bare_layout(&root.join("g/second"), &w.remote); + let (d, sock) = start_event_only(&w, "pca"); + wait_until("both repos listed", 10, || repo_paths(&sock).len() == 2); + + // Keep the first repo busy so a pass may be running when the other one vanishes. + fs::write(root.join("g/repo/main/busy.txt"), "x\n").unwrap(); + fs::remove_dir_all(root.join("g/second")).unwrap(); + wait_until("removed repo dropped", 10, || { + repo_paths(&sock) == vec![root.join("g/repo").display().to_string()] + }); + // The daemon is alive, the other repo still syncs, and the removal was not logged as an error. + assert_eq!( + ipc::request(&sock, &json!({"v":1,"cmd":"ping"})).unwrap()["data"], + "pong" + ); + wait_until("remaining repo still synced", 30, || { + git(&w.remote, &["for-each-ref", "refs/sync/pca/"]).contains("refs/sync/pca/main") + }); + let log = ipc::request(&sock, &json!({"v":1,"cmd":"log","limit":500})).unwrap(); + let errors: Vec<_> = log["data"] + .as_array() + .unwrap() + .iter() + .filter(|e| e["kind"] == "error") + .collect(); + assert!(errors.is_empty(), "{errors:?}"); + d.shutdown(); +} + +#[test] +fn not_migrated_list_follows_clones_added_and_removed() { + let w = world("rd-notmig", &["pca"]); + let root = w.base.join("pca"); + let (d, sock) = start_event_only(&w, "pca"); + wait_until("initial repo listed", 10, || repo_paths(&sock).len() == 1); + assert_eq!(status(&sock)["not_migrated"], json!([])); + + let plain = root.join("g/plain"); + git( + &root.join("g"), + &["clone", "-q", w.remote.to_str().unwrap(), "plain"], + ); + wait_until("new clone reported", 10, || { + status(&sock)["not_migrated"] == json!([plain.display().to_string()]) + }); + // Deleted (e.g. moved to the trash): it must leave the list again. + fs::remove_dir_all(&plain).unwrap(); + wait_until("deleted clone dropped", 10, || { + status(&sock)["not_migrated"] == json!([]) + }); + d.shutdown(); +} + +fn events(sock: &Path, kind: &str) -> Vec { + let log = ipc::request(sock, &json!({"v":1,"cmd":"log","limit":500})).unwrap(); + log["data"] + .as_array() + .unwrap() + .iter() + .filter(|e| e["kind"] == kind) + .cloned() + .collect() +} + +#[test] +fn repo_with_busy_marker_is_ignored_until_the_marker_is_removed() { + let w = world("rd-busy", &["pca"]); + let root = w.base.join("pca"); + let (d, sock) = start_event_only(&w, "pca"); + wait_until("initial repo listed", 10, || repo_paths(&sock).len() == 1); + + let new = root.join("g/halfway"); + fs::create_dir_all(&new).unwrap(); + fs::write( + new.join(".grove-busy"), + format!("{} 1\n", std::process::id()), + ) + .unwrap(); + bare_layout(&new, &w.remote); + std::thread::sleep(Duration::from_millis(1500)); + assert_eq!(repo_paths(&sock).len(), 1, "busy repo must not be managed"); + assert!(git(&w.remote, &["for-each-ref", "refs/sync/"]).is_empty()); + + fs::remove_file(new.join(".grove-busy")).unwrap(); + wait_until("repo managed once the marker is gone", 10, || { + repo_paths(&sock).contains(&new.display().to_string()) + }); + d.shutdown(); +} + +#[test] +fn stale_busy_marker_keeps_the_repo_out_and_warns_once() { + let w = world("rd-stale", &["pca"]); + let root = w.base.join("pca"); + let stale = root.join("g/crashed"); + fs::create_dir_all(&stale).unwrap(); + bare_layout(&stale, &w.remote); + fs::write(stale.join(".grove-busy"), "999999999 1\n").unwrap(); + let (d, sock) = start_event_only(&w, "pca"); + wait_until("warning logged", 10, || { + !events(&sock, "repo_stalled").is_empty() + }); + // Another rescan must not repeat the warning, and the marker is never deleted. + fs::create_dir_all(root.join("g/other")).unwrap(); + std::thread::sleep(Duration::from_millis(1500)); + assert_eq!(events(&sock, "repo_stalled").len(), 1); + assert_eq!(repo_paths(&sock).len(), 1); + assert!(stale.join(".grove-busy").exists()); + d.shutdown(); +} + +#[test] +fn clone_appears_only_when_complete() { + let w = world("rd-clonecomplete", &["pca"]); + let root = w.base.join("pca"); + let (d, sock) = start_event_only(&w, "pca"); + wait_until("initial repo listed", 10, || repo_paths(&sock).len() == 1); + + let new = root.join("g/cloned"); + let url = w.remote.display().to_string(); + let target = new.clone(); + let h = std::thread::spawn(move || { + grove_core::registry::clone_bare_layout(&url, &target, &[]).unwrap() + }); + let mut seen = false; + let end = Instant::now() + Duration::from_secs(30); + while Instant::now() < end && !seen { + if repo_paths(&sock).contains(&new.display().to_string()) { + // Listed: the clone must be finished, never in the middle. + assert!(!new.join(".grove-busy").exists()); + assert!(new.join(".bare/HEAD").exists()); + assert!(new.join("main").is_dir()); + seen = true; + } + std::thread::sleep(Duration::from_millis(20)); + } + h.join().unwrap(); + assert!(seen, "cloned repo never managed"); + d.shutdown(); +} diff --git a/docs/phase2.md b/docs/phase2.md index aaa58b0..219696b 100644 --- a/docs/phase2.md +++ b/docs/phase2.md @@ -59,7 +59,7 @@ socket is refused; a stale socket file left by a crash is replaced. JSON lines in `/activity.jsonl` (rotated at 5 MiB to `.jsonl.1`), the last 500 events in memory, and live via `subscribe`. Kinds: `start`, `stop`, `snapshot`, `fast_forward`, `applied`, -`declined`, `snapshots_withheld`, `snapshots_enabled`, `snapshots_purged`, `state` (worktree state changed), `materialized`, `archived`, `error`, `watch_error`, +`declined`, `snapshots_withheld`, `snapshots_enabled`, `snapshots_purged`, `state` (worktree state changed), `materialized`, `archived`, `repo_added`, `repo_removed`, `repo_stalled`, `error`, `watch_error`, `pause`, `resume`. ## CLI @@ -99,6 +99,6 @@ discard the staged version). - Peer-credential check on the socket: access control is the 0700 directory only. - GUI/tray (Phase 3), providers and wizards (Phase 4). - Remote-change notifications (webhooks); only polling at `fetch_interval_s`. -- Config reload: restart the daemon after editing `config.toml`. +- Config reload: restart the daemon after editing `config.toml`. (Repos added, migrated or removed under the configured groups are picked up at runtime; see `docs/phase6.md`.) - Watching skips no heavy ignored directories (`node_modules`, `target`) at watch time; add them to `sync.ignore_extra` to avoid triggering passes, and raise the inotify limit if needed. diff --git a/docs/phase6.md b/docs/phase6.md index 5f5a3e6..7257ed3 100644 --- a/docs/phase6.md +++ b/docs/phase6.md @@ -74,6 +74,42 @@ groups, repos directly under the root. Ignored plain clones inside a configured "not migrated (run grove add)" by `grove daemon status` and `grove doctor`. Discovery reads one directory per configured group, so it stays cheap. +### Rediscovery at runtime + +Discovery is not startup-only. The daemon watches (non-recursively) the root, each configured group +directory and every child directory that is not managed yet; managed repos keep their recursive +watch. A child directory created, deleted or renamed, or `.bare` / `.git` appearing or disappearing +inside one (`grove add` migrating a clone, `grove import` cloning into `//.bare`, +a clone moved to the trash) triggers a debounced (500 ms) rediscovery and diff: + +- New bare-layout repos are managed at once: watches set up, a pass scheduled, activity event + `repo_added`. +- Repos that are gone (or no longer bare layout) are dropped with their watches and state, one + `repo_removed` event, no error; their files are never touched. A repo whose directory vanishes + while a pass runs is dropped the same way. +- The "not migrated" list is refreshed. + +A repo is only picked up when it is **ready**: `.bare/HEAD` exists, there is no `.grove-busy` and no +`.grove-stage`. `grove add`, clone/import and init hold `/.grove-busy` (pid + start time) from +before their first change until their very last step, also on rollback, so the daemon never +fetches, materializes or snapshots a half-built layout (e.g. a `--no-checkout` worktree whose files +are still in `.grove-stage`). Creating or removing `.grove-busy` / `.grove-stage` triggers a +rediscovery, so the repo is picked up as soon as the marker goes. A marker whose process is gone +(or a leftover `.grove-stage`) means an interrupted operation: the repo stays unmanaged, the daemon +logs one `repo_stalled` warning to check it and restore from the backups, and never deletes the +marker. `pass` re-checks readiness and skips unready repos. Clones are not built in a temp dir and +renamed, because worktree link files hold absolute paths. + +Managed repos are watched recursively, including `node_modules` / `target`; notify cannot exclude +subtrees, so raise `fs.inotify.max_user_watches` on machines with many large repos. + +As a safety net every full pass (every `fetch_interval_s`) re-runs discovery too, so missed +inotify events delay detection by at most that interval. `grove daemon status` reflects the new set +right after rediscovery, also while paused (discovery runs while paused, syncing does not). + +Config reload is still out of scope: restart the daemon after editing `config.toml` (new or removed +groups are only picked up then). + **Breaking change:** group names must now be plain directory names (non-empty, no `/`, no leading `.`); a config with other names no longer loads.