mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 07:16:11 +00:00
fix(daemon): address review findings
Idle paused loop no longer spins, local snapshots continue during network backoff, debounce has a maximum wait, sync accepts non-canonical paths, removed repos are dropped, socket dir mode is enforced. adopt_if_identical now skips worktrees with staged changes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3f5ef28503
commit
0e77dd26d9
6 files changed
+182
-18
No files matched your search
@@ -119,6 +119,10 @@ fn adopt_if_identical(
|
||||
stamp: &str,
|
||||
st: State,
|
||||
) -> Result<Received, GitError> {
|
||||
// Anything staged (partial `add -p`, intent-to-add) would be lost by the index reset: skip.
|
||||
if g.probe(&["diff", "--cached", "--quiet"])?.is_none() {
|
||||
return Ok(Received::Skipped(st));
|
||||
}
|
||||
let worktree_tree = crate::snapshot::worktree_tree(g.dir())?;
|
||||
let upstream_tree = g.run(&["rev-parse", "@{upstream}^{tree}"])?;
|
||||
if worktree_tree != upstream_tree {
|
||||
|
||||
@@ -131,3 +131,40 @@ fn unreachable_remote_is_reported_but_local_snapshot_still_taken() {
|
||||
assert!(!r.worktrees[0].errors.is_empty(), "push failure surfaced");
|
||||
assert_eq!(r.worktrees[0].state, State::Dirty);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_changes_block_adoption_so_the_index_is_never_reset() {
|
||||
let base = tmpdir("staged");
|
||||
let remote = base.join("r.git");
|
||||
Git::new(&base)
|
||||
.run(&[
|
||||
"init",
|
||||
"-q",
|
||||
"--bare",
|
||||
"-b",
|
||||
"main",
|
||||
remote.to_str().unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let seed = init(&base.join("seed"));
|
||||
seed.run(&["remote", "add", "origin", remote.to_str().unwrap()])
|
||||
.unwrap();
|
||||
commit(&seed, "a.txt", "1\n");
|
||||
seed.run(&["push", "-q", "-u", "origin", "main"]).unwrap();
|
||||
let (ga, da) = clone(&base, &remote, "A");
|
||||
let (_gb, db) = clone(&base, &remote, "B");
|
||||
fs::write(da.join("a.txt"), "1\nwork\n").unwrap();
|
||||
sync_repo(&da, &opts("A", "t1")).unwrap();
|
||||
sync_repo(&db, &opts("B", "t2")).unwrap();
|
||||
// B stages an intermediate version, then its worktree matches what A will commit.
|
||||
let gb = Git::new(&db);
|
||||
fs::write(db.join("a.txt"), "1\nstaged\n").unwrap();
|
||||
gb.run(&["add", "a.txt"]).unwrap();
|
||||
fs::write(db.join("a.txt"), "1\nwork\n").unwrap();
|
||||
ga.run(&["add", "-A"]).unwrap();
|
||||
ga.run(&["commit", "-qm", "work"]).unwrap();
|
||||
ga.run(&["push", "-q"]).unwrap();
|
||||
let r = sync_repo(&db, &opts("B", "t3")).unwrap();
|
||||
assert_eq!(r.worktrees[0].state, State::BehindDirty);
|
||||
assert_eq!(gb.run(&["show", ":a.txt"]).unwrap(), "1\nstaged");
|
||||
}
|
||||
@@ -233,6 +233,7 @@ impl Watch {
|
||||
fn rescan(root: &Path, watch: &mut Watch, ctx: &Ctx) -> Vec<PathBuf> {
|
||||
let found = discover(root);
|
||||
let mut shared = ctx.shared.lock().unwrap();
|
||||
shared.repos.retain(|p, _| found.contains(p));
|
||||
for r in &found {
|
||||
shared.repos.entry(r.clone()).or_default();
|
||||
}
|
||||
@@ -254,6 +255,10 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
// due_at: when a repo should next be synced; backoff_until: earliest retry after failures.
|
||||
let mut due_at: HashMap<PathBuf, Instant> = HashMap::new();
|
||||
let mut backoff_until: HashMap<PathBuf, Instant> = HashMap::new();
|
||||
// first_at: first unsynced event of a repo, so a constant stream of events cannot postpone
|
||||
// its snapshot beyond `max_wait`.
|
||||
let mut first_at: HashMap<PathBuf, Instant> = HashMap::new();
|
||||
let max_wait = (debounce * 10).max(Duration::from_secs(5));
|
||||
let mut next_full = Instant::now();
|
||||
|
||||
loop {
|
||||
@@ -264,12 +269,20 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
.chain([next_full])
|
||||
.min()
|
||||
.unwrap_or(next_full);
|
||||
let timeout = wake
|
||||
let mut timeout = wake
|
||||
.saturating_duration_since(now)
|
||||
.min(Duration::from_secs(1));
|
||||
if ctx.shared.lock().unwrap().paused {
|
||||
// Nothing is due while paused: only wait for commands, never spin on past deadlines.
|
||||
timeout = Duration::from_secs(1);
|
||||
}
|
||||
match rx.recv_timeout(timeout) {
|
||||
Ok(Msg::Changed(r)) => {
|
||||
let at = Instant::now() + debounce;
|
||||
let now = Instant::now();
|
||||
let first = *first_at.entry(r.clone()).or_insert(now);
|
||||
let at = (now + debounce).min(first + max_wait);
|
||||
// An earlier deadline (e.g. an immediate `sync`) is never pushed back.
|
||||
let at = due_at.get(&r).map_or(at, |old| at.min(*old));
|
||||
due_at.insert(r.clone(), at);
|
||||
if let Some(s) = ctx.shared.lock().unwrap().repos.get_mut(&r)
|
||||
&& s.phase == "idle"
|
||||
@@ -293,7 +306,9 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
}
|
||||
let now = Instant::now();
|
||||
if now >= next_full {
|
||||
for r in rescan(&root, &mut watch, &ctx) {
|
||||
let found = rescan(&root, &mut watch, &ctx);
|
||||
due_at.retain(|r, _| found.contains(r));
|
||||
for r in found {
|
||||
due_at.insert(r, now);
|
||||
}
|
||||
next_full = now + fetch_every;
|
||||
@@ -305,12 +320,19 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
.collect();
|
||||
due.sort();
|
||||
for r in due {
|
||||
if let Some(until) = backoff_until.get(&r).filter(|u| **u > now) {
|
||||
due_at.insert(r, *until);
|
||||
if !ctx.shared.lock().unwrap().repos.contains_key(&r) {
|
||||
due_at.remove(&r);
|
||||
continue;
|
||||
}
|
||||
due_at.remove(&r);
|
||||
let failures = pass(&r, &cfg, &st, materialize, &ctx);
|
||||
first_at.remove(&r);
|
||||
// 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, materialize, offline, &ctx);
|
||||
if offline {
|
||||
continue;
|
||||
}
|
||||
if failures == 0 {
|
||||
backoff_until.remove(&r);
|
||||
} else {
|
||||
@@ -327,14 +349,21 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
}
|
||||
|
||||
/// One sync pass for `repo`; returns the number of consecutive failures (0 = success).
|
||||
fn pass(repo: &Path, cfg: &Config, st: &Settings, materialize: bool, ctx: &Ctx) -> u32 {
|
||||
fn pass(
|
||||
repo: &Path,
|
||||
cfg: &Config,
|
||||
st: &Settings,
|
||||
materialize: bool,
|
||||
offline: bool,
|
||||
ctx: &Ctx,
|
||||
) -> u32 {
|
||||
let name = repo.display().to_string();
|
||||
set_phase(ctx, repo, "syncing");
|
||||
let opts = Options {
|
||||
machine: cfg.machine.name.clone(),
|
||||
stamp: stamp(),
|
||||
remote: st.remote.clone(),
|
||||
offline: false,
|
||||
offline,
|
||||
materialize,
|
||||
};
|
||||
let result = sync_repo(repo, &opts);
|
||||
@@ -394,7 +423,13 @@ fn pass(repo: &Path, cfg: &Config, st: &Settings, materialize: bool, ctx: &Ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
if errors.is_empty() {
|
||||
if offline {
|
||||
// A snapshot-only pass during backoff changes neither the failure count nor the phase.
|
||||
status.phase = if status.failures > 0 { "error" } else { "idle" };
|
||||
if !errors.is_empty() {
|
||||
ctx.activity.log("error", Some(&name), errors.join("; "));
|
||||
}
|
||||
} else if errors.is_empty() {
|
||||
status.phase = "idle";
|
||||
status.failures = 0;
|
||||
status.last_error = None;
|
||||
|
||||
@@ -49,6 +49,8 @@ pub fn serve(socket: &Path, ctx: Ctx, stop: Arc<AtomicBool>) -> std::io::Result<
|
||||
.recursive(true)
|
||||
.mode(0o700)
|
||||
.create(dir)?;
|
||||
// The mode above only applies to a directory we create: enforce it on an existing one.
|
||||
std::fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?;
|
||||
}
|
||||
if socket.exists() {
|
||||
if UnixStream::connect(socket).is_ok() {
|
||||
@@ -187,11 +189,21 @@ fn handle(req: &Request, ctx: &Ctx) -> Value {
|
||||
}
|
||||
"sync" => {
|
||||
let target = req.repo.as_ref().map(PathBuf::from);
|
||||
if let Some(t) = &target
|
||||
&& !ctx.shared.lock().unwrap().repos.contains_key(t)
|
||||
{
|
||||
return err("unknown repo");
|
||||
}
|
||||
// Match by canonical path so `.`, relative and symlinked paths work.
|
||||
let target = match target {
|
||||
None => None,
|
||||
Some(t) => {
|
||||
let want = std::fs::canonicalize(&t).unwrap_or(t);
|
||||
let shared = ctx.shared.lock().unwrap();
|
||||
let found = shared.repos.keys().find(|k| {
|
||||
std::fs::canonicalize(k).unwrap_or_else(|_| (*k).clone()) == want
|
||||
});
|
||||
match found {
|
||||
Some(k) => Some(k.clone()),
|
||||
None => return err("unknown repo"),
|
||||
}
|
||||
}
|
||||
};
|
||||
let _ = ctx.tx.send(Msg::SyncNow(target));
|
||||
ok(json!("queued"))
|
||||
}
|
||||
|
||||
@@ -307,3 +307,65 @@ fn work_in_progress_then_committed_on_a_leaves_b_clean() {
|
||||
a.shutdown();
|
||||
b.shutdown();
|
||||
}
|
||||
|
||||
fn cpu_ticks(pid: u32) -> u64 {
|
||||
let stat = fs::read_to_string(format!("/proc/{pid}/stat")).unwrap();
|
||||
let rest = stat.rsplit_once(')').unwrap().1;
|
||||
let f: Vec<&str> = rest.split_whitespace().collect();
|
||||
f[11].parse::<u64>().unwrap() + f[12].parse::<u64>().unwrap() // utime + stime
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paused_daemon_does_not_spin() {
|
||||
let w = world("spin", &["pca"]);
|
||||
let cfg_path = w.base.join("config.toml");
|
||||
fs::write(
|
||||
&cfg_path,
|
||||
format!(
|
||||
"[machine]\nname = \"pca\"\n[root]\npath = \"{}\"\n[sync]\nsnapshot_debounce_ms = 50\nfetch_interval_s = 1\n",
|
||||
w.base.join("pca").display()
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let runtime = w.base.join("run");
|
||||
fs::create_dir_all(&runtime).unwrap();
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_groved"))
|
||||
.arg("--config")
|
||||
.arg(&cfg_path)
|
||||
.env("XDG_RUNTIME_DIR", &runtime)
|
||||
.env("XDG_STATE_HOME", w.base.join("state"))
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let sock = runtime.join("grove/grove.sock");
|
||||
wait_until("daemon up", 10, || {
|
||||
ipc::request(&sock, &json!({"v":1,"cmd":"ping"})).is_ok()
|
||||
});
|
||||
ipc::request(&sock, &json!({"v":1,"cmd":"pause"})).unwrap();
|
||||
std::thread::sleep(Duration::from_millis(1500)); // let any in-flight pass finish
|
||||
let before = cpu_ticks(child.id());
|
||||
std::thread::sleep(Duration::from_secs(3)); // well past several fetch intervals
|
||||
let used = cpu_ticks(child.id()) - before;
|
||||
child.kill().unwrap();
|
||||
child.wait().unwrap();
|
||||
assert!(used < 30, "paused daemon burned {used} ticks of CPU in 3 s");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_accepts_a_non_canonical_repo_path_and_unknown_repos_are_rejected() {
|
||||
let w = world("path", &["pca"]);
|
||||
let st = settings(&w, "pca");
|
||||
let sock = st.socket.clone();
|
||||
let d = Daemon::start(config(&w, "pca", 200, 60), st).unwrap();
|
||||
let repo = w.base.join("pca/repo");
|
||||
wait_until("repo listed", 10, || {
|
||||
ipc::request(&sock, &json!({"v":1,"cmd":"status"})).unwrap()["data"]["repos"]
|
||||
.as_array()
|
||||
.is_some_and(|r| r.len() == 1)
|
||||
});
|
||||
let odd = format!("{}/../repo/.", repo.display());
|
||||
let ok = ipc::request(&sock, &json!({"v":1,"cmd":"sync","repo":odd})).unwrap();
|
||||
assert_eq!(ok["ok"], true, "{ok}");
|
||||
let bad = ipc::request(&sock, &json!({"v":1,"cmd":"sync","repo":"/nonexistent"})).unwrap();
|
||||
assert_eq!(bad["ok"], false);
|
||||
d.shutdown();
|
||||
}
|
||||
+18
-4
@@ -11,17 +11,21 @@ is `grove_core::sync::sync_repo`, the same code the CLI runs. The daemon only de
|
||||
`.grove-stage` and anything matching `sync.ignore_extra` (exact component name or `*suffix`) are
|
||||
ignored. If a watch cannot be set (typically `ENOSPC`, raise `fs.inotify.max_user_watches`) it is
|
||||
logged and the periodic pass still covers that repo.
|
||||
- **Debounce**: each event pushes the repo's next pass to `now + snapshot_debounce_ms`.
|
||||
- **Debounce**: each event pushes the repo's next pass to `now + snapshot_debounce_ms`, but never
|
||||
later than `max(10 x debounce, 5 s)` after the first unsynced event, so a constantly written file
|
||||
cannot starve snapshots.
|
||||
- **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply
|
||||
snapshots, materialize/archive). Also what catches missed events.
|
||||
- **One worker thread**: passes never overlap. Events that arrive during a pass queue another pass;
|
||||
it finds nothing to do and ends the chain.
|
||||
- **Failures** (network, auth, git errors) back off exponentially per repo: 10 s, 20 s, ... capped at
|
||||
5 min, and are logged as `error`. `sync` over IPC clears the backoff.
|
||||
5 min, and are logged as `error`. `sync` over IPC clears the backoff. While backing off, changes
|
||||
are still snapshotted locally (an offline pass); only the network is retried after the backoff.
|
||||
- **Locks**: grove never takes the user's index (snapshots use a temp index) so git's own locks are
|
||||
not contended; a git command that fails because the user holds a lock is just a failed pass that
|
||||
is retried.
|
||||
- **Pause**: `pause` stops all passes (events keep accumulating); `resume` runs a full pass.
|
||||
- **Pause**: `pause` stops all passes (events keep accumulating, the loop idles at 1 s ticks);
|
||||
`resume` runs a full pass.
|
||||
- **Crash safety**: nothing durable lives in the daemon. Killing it at any point leaves the working
|
||||
tree and index untouched; the next start rediscovers and resyncs (covered by a kill -9 test).
|
||||
There is no signal handler: SIGTERM ends the process, which is safe for the same reason.
|
||||
@@ -73,15 +77,25 @@ journalctl --user -u groved -f
|
||||
|
||||
Socket activation was considered and not done: the daemon must run anyway to watch files.
|
||||
|
||||
## Latency
|
||||
|
||||
Measured on the real Gitea with default settings (2 s debounce, 60 s fetch): an edit on A showed up on
|
||||
B after 58 s, and a commit pushed on A left B clean at the new commit after 60 s. Worst case is
|
||||
`debounce + fetch_interval_s + pass time`; lower `fetch_interval_s` for faster convergence.
|
||||
|
||||
## Found by the daemon tests
|
||||
|
||||
A worktree that had another machine's snapshot applied stayed `BehindDirty` forever once the author
|
||||
committed and pushed that work. `receive` now adopts the upstream commit with a mixed reset when the
|
||||
worktree's content is byte-identical to the upstream tree (`receive::adopt_if_identical`); any
|
||||
other dirty worktree is still left alone.
|
||||
other dirty worktree is still left alone, including one with staged changes (the reset would
|
||||
discard the staged version).
|
||||
|
||||
## Not done
|
||||
|
||||
- `Daemon::shutdown` finishes the queued passes first, and idle client connections are not joined.
|
||||
`groved` never calls it (no signal handler), so this only matters for tests and embedding.
|
||||
- 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`.
|
||||
|
||||
Reference in new issue
Block a user