fix(daemon): leave repos alone while grove add or clone is still building them

Add a .grove-busy marker held by migrate and clone/init, treat a repo as
ready only with .bare/HEAD and no marker or .grove-stage, warn once on stale
markers. Also re-watch recreated dirs by inode, watch shallow dirs before
discovery, and retry failed watches with a rate-limited log.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-11-16 18:17:42 +01:00
1 parent 3784e1533b
commit e2abeed414
8 files changed
+335 -45

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
//! The "busy" marker: `<repo>/.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 `<pid> <start unix seconds>`. 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 `<dir>/.grove-busy` (and `dir` if needed). Fails if the marker already exists.
pub fn acquire(dir: &Path) -> io::Result<BusyGuard> {
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::<u32>().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();
}
}
+1
View File
@@ -1,5 +1,6 @@
//! Sync engine core: git plumbing wrapper, config, snapshots and state classification. //! Sync engine core: git plumbing wrapper, config, snapshots and state classification.
pub mod busy;
pub mod config; pub mod config;
pub mod git; pub mod git;
pub mod inspect; pub mod inspect;
+5 -2
View File
@@ -19,6 +19,7 @@ use std::process::Command;
const BARE: &str = ".bare"; const BARE: &str = ".bare";
const STAGE: &str = ".grove-stage"; const STAGE: &str = ".grove-stage";
const BUSY: &str = crate::busy::BUSY;
#[derive(Debug)] #[derive(Debug)]
pub enum MigrateError { pub enum MigrateError {
@@ -477,7 +478,9 @@ fn migrate_inner(
let (backup_tar, backup_ref, linked_backups) = let (backup_tar, backup_ref, linked_backups) =
backup(&root, &git, machine, backup_dir, stamp, &linked)?; 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 { let mut p = Progress {
orig_ids: list_ids(&root.join(".git")), orig_ids: list_ids(&root.join(".git")),
..Progress::default() ..Progress::default()
@@ -573,7 +576,7 @@ fn run_steps(
// 1. Move everything except .git into a staging dir. // 1. Move everything except .git into a staging dir.
fs::create_dir(&stage).map_err(s)?; fs::create_dir(&stage).map_err(s)?;
p.staged = true; 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)?; hook(inject, Step::Staged)?;
// 2. .git -> .bare, make it bare. // 2. .git -> .bare, make it bare.
+3 -3
View File
@@ -5,7 +5,6 @@ use crate::git::{Git, GitError};
use crate::layout::dir_name; use crate::layout::dir_name;
use crate::receive::{ensure_fetch_refspec, materialize}; use crate::receive::{ensure_fetch_refspec, materialize};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)] #[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize, Serialize)]
@@ -53,7 +52,8 @@ pub fn clone_bare_layout(
dir: &Path, dir: &Path,
envs: &[(String, String)], envs: &[(String, String)],
) -> Result<Vec<PathBuf>, GitError> { ) -> Result<Vec<PathBuf>, 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 bare = dir.join(".bare");
let mut g = Git::new(dir); let mut g = Git::new(dir);
for (k, v) in envs { 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`, /// Creates a brand new local repo in the bare layout with an initial empty commit on `main`,
/// pointing at `url`. Nothing is pushed here. /// pointing at `url`. Nothing is pushed here.
pub fn init_bare_layout(dir: &Path, url: &str) -> Result<PathBuf, GitError> { pub fn init_bare_layout(dir: &Path, url: &str) -> Result<PathBuf, GitError> {
fs::create_dir_all(dir)?; let _busy = crate::busy::BusyGuard::acquire(dir)?;
let bare = dir.join(".bare"); let bare = dir.join(".bare");
let g = Git::new(dir); let g = Git::new(dir);
g.run(&[ g.run(&[
+31
View File
@@ -422,3 +422,34 @@ fn rollback_restores_linked_worktrees_at_every_step() {
migrate(&repo, "m", &base.join("bk"), "2").unwrap(); 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());
}
+83 -39
View File
@@ -3,14 +3,14 @@
//! so passes never overlap. //! so passes never overlap.
use crate::activity::{Activity, now_secs}; 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::ipc;
use crate::visibility::{RealForge, Visibility, snapshot_gate}; use crate::visibility::{RealForge, Visibility, snapshot_gate};
use grove_core::config::Config; use grove_core::config::Config;
use grove_core::receive::Received; use grove_core::receive::Received;
use grove_core::sync::{Options, sync_repo}; use grove_core::sync::{Options, sync_repo};
use notify::{EventKind, RecursiveMode, Watcher}; use notify::{EventKind, RecursiveMode, Watcher};
use std::collections::{BTreeMap, HashMap}; use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel}; 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(); let n = c.as_os_str().to_string_lossy();
n == ".git" n == ".git"
|| n == ".bare" || n == ".bare"
|| n == ".grove-busy"
|| n == ".grove-stage" || n == ".grove-stage"
|| extra.iter().any(|p| pattern_matches(p, &n)) || 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() { match parts.as_slice() {
[g] => in_group(g), [g] => in_group(g),
[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, _ => false,
} }
} }
@@ -208,8 +215,18 @@ pub fn triggers_rediscovery(path: &Path, root: &Path, groups: &[String]) -> bool
struct Watch { struct Watch {
watcher: Option<notify::RecommendedWatcher>, watcher: Option<notify::RecommendedWatcher>,
repos: Arc<Mutex<Vec<PathBuf>>>, repos: Arc<Mutex<Vec<PathBuf>>>,
/// Watched paths and whether the watch is recursive. /// Watched paths: whether the watch is recursive, and the (device, inode) of the directory it
watched: HashMap<PathBuf, bool>, /// was set on, so a directory deleted and recreated under the same name is watched anew.
watched: HashMap<PathBuf, (bool, Option<(u64, u64)>)>,
/// Paths whose watch failed and was already reported (reported once until it succeeds).
watch_failed: HashSet<PathBuf>,
/// Stalled repos already warned about.
warned_stalled: HashSet<PathBuf>,
}
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( fn make_watch(
@@ -254,18 +271,20 @@ fn make_watch(
watcher, watcher,
repos, repos,
watched: HashMap::new(), watched: HashMap::new(),
watch_failed: HashSet::new(),
warned_stalled: HashSet::new(),
} }
} }
impl Watch { impl Watch {
/// Makes the set of watches match `wanted`. Watches are only ever added or removed here; /// Adds the watches in `wanted` that are missing, and replaces watches whose directory was
/// nothing in the watched directories is touched. /// deleted and recreated. With `prune`, also removes watches that are no longer wanted or
fn sync(&mut self, wanted: HashMap<PathBuf, bool>, ctx: &Ctx) { /// whose mode changed. Nothing in the watched directories is touched.
fn sync(&mut self, wanted: &HashMap<PathBuf, bool>, prune: bool, ctx: &Ctx) {
let stale: Vec<PathBuf> = self let stale: Vec<PathBuf> = self
.watched .watched
.iter() .iter()
// A deleted directory loses its inotify watch, so a recreated one needs a new one. .filter(|(p, (rec, id))| *id != dir_id(p) || (prune && wanted.get(*p) != Some(rec)))
.filter(|(p, rec)| wanted.get(*p) != Some(*rec) || !p.exists())
.map(|(p, _)| p.clone()) .map(|(p, _)| p.clone())
.collect(); .collect();
for p in stale { for p in stale {
@@ -275,25 +294,33 @@ impl Watch {
} }
} }
for (p, rec) in wanted { for (p, rec) in wanted {
if self.watched.contains_key(&p) || !p.exists() { if self.watched.contains_key(p) {
continue; continue;
} }
self.watched.insert(p.clone(), rec); let Some(id) = dir_id(p) else { continue };
let mode = if rec { let mode = if *rec {
RecursiveMode::Recursive RecursiveMode::Recursive
} else { } else {
RecursiveMode::NonRecursive RecursiveMode::NonRecursive
}; };
if let Some(w) = &mut self.watcher let Some(w) = &mut self.watcher else { continue };
&& let Err(e) = w.watch(&p, mode) match w.watch(p, mode) {
{ Ok(()) => {
ctx.activity.log( self.watched.insert(p.clone(), (*rec, Some(id)));
"watch_error", self.watch_failed.remove(p);
Some(&p.display().to_string()), }
format!( // Not recorded as watched, so the next rescan retries.
"cannot watch (raise fs.inotify.max_user_watches?): {e}; relying on periodic passes" 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, watch: &mut Watch,
ctx: &Ctx, ctx: &Ctx,
) -> (Vec<PathBuf>, Vec<PathBuf>) { ) -> (Vec<PathBuf>, Vec<PathBuf>) {
// 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<PathBuf, bool> = 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 d = discover(root, groups);
let found = d.managed; 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 added = Vec::new();
let mut removed = 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", "no longer managed (directory gone or no longer a bare layout); files untouched",
); );
} }
let mut wanted: HashMap<PathBuf, bool> = 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 { for r in &found {
wanted.insert(r.clone(), true); wanted.insert(r.clone(), true);
} }
*watch.repos.lock().unwrap() = found.clone(); *watch.repos.lock().unwrap() = found.clone();
watch.sync(wanted, ctx); watch.sync(&wanted, true, ctx);
(found, added) (found, added)
} }
@@ -465,7 +503,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
} }
due_at.remove(&r); due_at.remove(&r);
first_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. // Removed or migrated away since the last discovery: drop it, no error.
let (found, _) = rescan(&root, &groups, &mut watch, &ctx); let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until); forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
@@ -475,7 +513,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
// the network is retried at the first pass after the backoff expires. // 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 offline = backoff_until.get(&r).is_some_and(|u| *u > now);
let failures = pass(&r, &cfg, &st, &mut visibility, offline, &ctx); 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. // It vanished mid-pass: whatever the pass reported is moot.
let (found, _) = rescan(&root, &groups, &mut watch, &ctx); let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until); forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
@@ -521,6 +559,10 @@ fn pass(
ctx: &Ctx, ctx: &Ctx,
) -> u32 { ) -> u32 {
let name = repo.display().to_string(); 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"); set_phase(ctx, repo, "syncing");
let group = group_of(repo).unwrap_or_default(); 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. // `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"));
assert!(t("/r/g/repo/.bare")); assert!(t("/r/g/repo/.bare"));
assert!(t("/r/g/repo/.git")); 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"));
assert!(!t("/r/g/repo/main/.bare")); assert!(!t("/r/g/repo/main/.bare"));
assert!(!t("/r/other")); assert!(!t("/r/other"));
+36 -1
View File
@@ -2,6 +2,7 @@
//! groups, where the repo is in the bare + worktrees layout (has a `.bare` directory). Plain //! 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. //! 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}; use std::path::{Path, PathBuf};
pub fn is_bare_layout(p: &Path) -> bool { 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 `<repo>/.git/worktrees/<id>`) belongs to the repo /// A linked worktree (`.git` file pointing into `<repo>/.git/worktrees/<id>`) belongs to the repo
/// it was added from; treating it as a repo of its own would sync the same worktrees twice. /// 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 { fn is_linked_worktree(p: &Path) -> bool {
std::fs::read_to_string(p.join(".git")).is_ok_and(|s| { std::fs::read_to_string(p.join(".git")).is_ok_and(|s| {
s.trim() s.trim()
@@ -42,6 +52,9 @@ pub struct Discovery {
pub managed: Vec<PathBuf>, pub managed: Vec<PathBuf>,
/// Plain clones in configured groups: ignored, reported as "not migrated". /// Plain clones in configured groups: ignored, reported as "not migrated".
pub not_migrated: Vec<PathBuf>, pub not_migrated: Vec<PathBuf>,
/// Bare-layout repos left alone because an interrupted `grove add`/clone left a stale
/// `.grove-busy` or a `.grove-stage` behind.
pub stalled: Vec<PathBuf>,
} }
/// Looks only at `root/<group>/<repo>` for each name in `groups` (cheap: one `read_dir` per /// Looks only at `root/<group>/<repo>` for each name in `groups` (cheap: one `read_dir` per
@@ -53,8 +66,12 @@ pub fn discover(root: &Path, groups: &[String]) -> Discovery {
groups.dedup(); groups.dedup();
for g in groups { for g in groups {
for repo in subdirs(&root.join(g)) { for repo in subdirs(&root.join(g)) {
if is_bare_layout(&repo) { if is_ready(&repo) {
d.managed.push(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) { } else if is_plain_clone(&repo) {
d.not_migrated.push(repo); d.not_migrated.push(repo);
} }
@@ -78,6 +95,10 @@ mod tests {
let _ = std::fs::remove_dir_all(&base); let _ = std::fs::remove_dir_all(&base);
for d in [ for d in [
"grp/migrated/.bare", "grp/migrated/.bare",
"grp/halfway/.bare",
"grp/busy/.bare",
"grp/staged/.bare",
"grp/staged/.grove-stage",
"grp/plain/.git", "grp/plain/.git",
"grp/.hidden/.bare", "grp/.hidden/.bare",
"grp/notarepo/x", "grp/notarepo/x",
@@ -91,6 +112,19 @@ mod tests {
] { ] {
std::fs::create_dir_all(base.join(d)).unwrap(); 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". // 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::create_dir_all(base.join("grp/migrated-feature")).unwrap();
std::fs::write( std::fs::write(
@@ -103,6 +137,7 @@ mod tests {
&["grp".to_string(), "grp2".to_string(), "absent".into()], &["grp".to_string(), "grp2".to_string(), "absent".into()],
); );
assert_eq!(found.managed, vec![base.join("grp/migrated")]); 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!(found.not_migrated, vec![base.join("grp/plain")]);
assert_eq!(group_of(&base.join("grp/migrated")).as_deref(), Some("grp")); assert_eq!(group_of(&base.join("grp/migrated")).as_deref(), Some("grp"));
std::fs::remove_dir_all(&base).unwrap(); std::fs::remove_dir_all(&base).unwrap();
+88
View File
@@ -656,3 +656,91 @@ fn not_migrated_list_follows_clones_added_and_removed() {
}); });
d.shutdown(); d.shutdown();
} }
fn events(sock: &Path, kind: &str) -> Vec<serde_json::Value> {
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();
}