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 84f2132..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, is_bare_layout, subdirs}; +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}; @@ -176,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)) }) @@ -200,7 +201,13 @@ pub fn triggers_rediscovery(path: &Path, root: &Path, groups: &[String]) -> bool match parts.as_slice() { [g] => in_group(g), [g, _] => in_group(g), - [g, _, f] => in_group(g) && (f == ".bare" || f == ".git"), + [g, _, f] => { + in_group(g) + && matches!( + f.as_str(), + ".bare" | ".git" | ".grove-busy" | ".grove-stage" + ) + } _ => false, } } @@ -208,8 +215,18 @@ pub fn triggers_rediscovery(path: &Path, root: &Path, groups: &[String]) -> bool struct Watch { watcher: Option, repos: Arc>>, - /// Watched paths and whether the watch is recursive. - watched: HashMap, + /// 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 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( @@ -254,18 +271,20 @@ fn make_watch( watcher, repos, watched: HashMap::new(), + watch_failed: HashSet::new(), + warned_stalled: HashSet::new(), } } impl Watch { - /// Makes the set of watches match `wanted`. Watches are only ever added or removed here; - /// nothing in the watched directories is touched. - fn sync(&mut self, wanted: HashMap, ctx: &Ctx) { + /// 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() - // A deleted directory loses its inotify watch, so a recreated one needs a new one. - .filter(|(p, rec)| wanted.get(*p) != Some(*rec) || !p.exists()) + .filter(|(p, (rec, id))| *id != dir_id(p) || (prune && wanted.get(*p) != Some(rec))) .map(|(p, _)| p.clone()) .collect(); for p in stale { @@ -275,25 +294,33 @@ impl Watch { } } for (p, rec) in wanted { - if self.watched.contains_key(&p) || !p.exists() { + if self.watched.contains_key(p) { continue; } - self.watched.insert(p.clone(), rec); - let mode = if rec { + let Some(id) = dir_id(p) else { continue }; + let mode = if *rec { RecursiveMode::Recursive } else { RecursiveMode::NonRecursive }; - if let Some(w) = &mut self.watcher - && let Err(e) = w.watch(&p, mode) - { - ctx.activity.log( - "watch_error", - Some(&p.display().to_string()), - format!( - "cannot watch (raise fs.inotify.max_user_watches?): {e}; relying on periodic passes" - ), - ); + 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" + ), + ); + } + } } } } @@ -307,8 +334,32 @@ fn rescan( 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; + 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", + ); + } + } + watch.warned_stalled.retain(|p| d.stalled.contains(p)); let mut added = Vec::new(); let mut removed = Vec::new(); { @@ -339,24 +390,11 @@ fn rescan( "no longer managed (directory gone or no longer a bare layout); files untouched", ); } - let mut wanted: HashMap = HashMap::new(); - wanted.insert(root.to_path_buf(), false); - let mut names: Vec<&String> = groups.iter().collect(); - names.dedup(); - for g in names { - 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.entry(child).or_insert(false); - } - } for r in &found { wanted.insert(r.clone(), true); } *watch.repos.lock().unwrap() = found.clone(); - watch.sync(wanted, ctx); + watch.sync(&wanted, true, ctx); (found, added) } @@ -465,7 +503,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { } due_at.remove(&r); first_at.remove(&r); - if !is_bare_layout(&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); @@ -475,7 +513,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver, ctx: Ctx) { // 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_bare_layout(&r) { + 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); @@ -521,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. @@ -718,6 +760,8 @@ mod tests { 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")); diff --git a/crates/grove-daemon/src/discover.rs b/crates/grove-daemon/src/discover.rs index 8ee7d88..94b33b3 100644 --- a/crates/grove-daemon/src/discover.rs +++ b/crates/grove-daemon/src/discover.rs @@ -2,6 +2,7 @@ //! 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}; pub fn is_bare_layout(p: &Path) -> bool { @@ -10,6 +11,15 @@ pub fn is_bare_layout(p: &Path) -> bool { /// 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() @@ -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 8a284a7..8aabbde 100644 --- a/crates/grove-daemon/tests/daemon.rs +++ b/crates/grove-daemon/tests/daemon.rs @@ -656,3 +656,91 @@ fn not_migrated_list_follows_clones_added_and_removed() { }); 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(); +}