mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-26 07:16:11 +00:00
feat(daemon): run sync passes on a worker pool
The loop thread schedules and sync.workers threads (default 4) run passes, so a slow or hanging fetch no longer holds up every other repo. A repo never has two passes at once; passes go only to idle workers, so pause and backoff behave as before. Visibility and merged-PR caches are shared without holding locks across forge requests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6e5bee1a95
commit
f16438fa02
7 files changed
+317
-127
No files matched your search
@@ -171,6 +171,10 @@ pub struct Sync {
|
||||
/// (`prune::default_protected`) and the default branch. See [`Sync::protected_branches`].
|
||||
#[serde(default)]
|
||||
pub prune_protected: Vec<String>,
|
||||
/// How many repos the daemon syncs at the same time (1 to 32). A repo never has two
|
||||
/// passes at once.
|
||||
#[serde(default = "default_workers")]
|
||||
pub workers: usize,
|
||||
}
|
||||
|
||||
impl Sync {
|
||||
@@ -194,6 +198,7 @@ impl Default for Sync {
|
||||
prune_merged: true,
|
||||
prune_disposable: default_disposable(),
|
||||
prune_protected: Vec::new(),
|
||||
workers: default_workers(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,6 +212,9 @@ pub struct ConfigRepo {
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn default_workers() -> usize {
|
||||
4
|
||||
}
|
||||
fn default_debounce() -> u64 {
|
||||
2000
|
||||
}
|
||||
@@ -347,6 +355,12 @@ impl Config {
|
||||
));
|
||||
}
|
||||
}
|
||||
if !(1..=32).contains(&self.sync.workers) {
|
||||
return bad(format!(
|
||||
"sync.workers = {} must be between 1 and 32",
|
||||
self.sync.workers
|
||||
));
|
||||
}
|
||||
if let Some(d) = self
|
||||
.sync
|
||||
.prune_disposable
|
||||
|
||||
@@ -47,7 +47,10 @@ fn temp_index_path() -> PathBuf {
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
std::env::temp_dir().join(format!("grove-index-{}-{nanos}", std::process::id()))
|
||||
// A counter too: daemon workers snapshot several repos at once.
|
||||
static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
std::env::temp_dir().join(format!("grove-index-{}-{nanos}-{n}", std::process::id()))
|
||||
}
|
||||
|
||||
/// Tree of everything in the worktree (tracked changes and untracked files, not ignored ones),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Event loop: file events are debounced per repo, a periodic pass covers fetches and anything
|
||||
//! the watcher missed, failures back off exponentially. One worker thread runs the sync passes,
|
||||
//! so passes never overlap.
|
||||
//! the watcher missed, failures back off exponentially. The loop thread schedules; a pool of
|
||||
//! `sync.workers` threads runs the passes, several repos at once but never two passes of the
|
||||
//! same repo.
|
||||
|
||||
use crate::activity::{Activity, now_secs};
|
||||
use crate::discover::{discover, group_of, is_ready, subdirs};
|
||||
@@ -99,9 +100,72 @@ pub enum Msg {
|
||||
Rescan,
|
||||
/// Sync one repo (or all) as soon as possible.
|
||||
SyncNow(Option<PathBuf>),
|
||||
/// A worker finished a pass: consecutive failures (0 = success), and whether it was offline.
|
||||
Done {
|
||||
repo: PathBuf,
|
||||
failures: u32,
|
||||
offline: bool,
|
||||
},
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
/// One pass for a worker to run.
|
||||
struct Job {
|
||||
repo: PathBuf,
|
||||
offline: bool,
|
||||
}
|
||||
|
||||
/// Starts `n` threads that run passes from `jobs` and report each one as [`Msg::Done`].
|
||||
fn spawn_workers(
|
||||
n: usize,
|
||||
jobs: Receiver<Job>,
|
||||
cfg: &Arc<Config>,
|
||||
st: &Arc<Settings>,
|
||||
visibility: &Arc<Visibility>,
|
||||
forge: &Arc<ForgeMemory>,
|
||||
ctx: &Ctx,
|
||||
) -> Vec<JoinHandle<()>> {
|
||||
let jobs = Arc::new(Mutex::new(jobs));
|
||||
(0..n)
|
||||
.map(|_| {
|
||||
let (jobs, cfg, st, visibility, forge, ctx) = (
|
||||
jobs.clone(),
|
||||
cfg.clone(),
|
||||
st.clone(),
|
||||
visibility.clone(),
|
||||
forge.clone(),
|
||||
ctx.clone(),
|
||||
);
|
||||
std::thread::spawn(move || {
|
||||
loop {
|
||||
// The lock is held only while waiting for the next job.
|
||||
let job = jobs.lock().unwrap().recv();
|
||||
let Ok(Job { repo, offline }) = job else {
|
||||
break;
|
||||
};
|
||||
// A panicking pass must still report back, or its repo is never synced again.
|
||||
let failures = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
pass(&repo, &cfg, &st, &visibility, offline, &forge, &ctx)
|
||||
}))
|
||||
.unwrap_or_else(|_| {
|
||||
ctx.activity.log(
|
||||
"error",
|
||||
Some(&repo.display().to_string()),
|
||||
"sync pass panicked; retried with backoff",
|
||||
);
|
||||
1
|
||||
});
|
||||
let _ = ctx.tx.send(Msg::Done {
|
||||
repo,
|
||||
failures,
|
||||
offline,
|
||||
});
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Ctx {
|
||||
pub shared: Arc<Mutex<Shared>>,
|
||||
@@ -337,6 +401,7 @@ fn rescan(
|
||||
root: &Path,
|
||||
groups: &[String],
|
||||
watch: &mut Watch,
|
||||
running: &HashSet<PathBuf>,
|
||||
ctx: &Ctx,
|
||||
) -> (Vec<PathBuf>, Vec<PathBuf>) {
|
||||
// Shallow watches first, then discover: a `.bare` created in a child between the two steps
|
||||
@@ -353,8 +418,16 @@ fn rescan(
|
||||
}
|
||||
}
|
||||
watch.sync(&wanted, false, ctx);
|
||||
let d = discover(root, groups);
|
||||
let found = d.managed;
|
||||
let mut d = discover(root, groups);
|
||||
// A repo whose pass is running may hold `.grove-busy` (purge) for a moment: it is judged
|
||||
// when the pass reports back, not now.
|
||||
d.stalled.retain(|r| !running.contains(r));
|
||||
let mut found = d.managed;
|
||||
for r in running {
|
||||
if !found.contains(r) && r.is_dir() {
|
||||
found.push(r.clone());
|
||||
}
|
||||
}
|
||||
for r in &d.stalled {
|
||||
if watch.warned_stalled.insert(r.clone()) {
|
||||
ctx.activity.log(
|
||||
@@ -409,7 +482,26 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
let fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
|
||||
let root = cfg.root_path();
|
||||
let groups: Vec<String> = cfg.groups.iter().map(|g| g.name.clone()).collect();
|
||||
let mut visibility = Visibility::load(st.visibility_cache.clone());
|
||||
let cfg = Arc::new(cfg);
|
||||
let st = Arc::new(st);
|
||||
let visibility = Arc::new(Visibility::load(st.visibility_cache.clone()));
|
||||
// Deletions being confirmed and merged pull requests, per repo.
|
||||
let forge = Arc::new(ForgeMemory::default());
|
||||
let (jobs, job_rx) = channel::<Job>();
|
||||
let workers = spawn_workers(
|
||||
cfg.sync.workers.max(1),
|
||||
job_rx,
|
||||
&cfg,
|
||||
&st,
|
||||
&visibility,
|
||||
&forge,
|
||||
&ctx,
|
||||
);
|
||||
// Repos a worker is running a pass for: never scheduled twice.
|
||||
let mut running: HashSet<PathBuf> = HashSet::new();
|
||||
// Repos whose `sync` was requested while their pass ran: that pass's failure sets no backoff.
|
||||
let mut sync_asked: HashSet<PathBuf> = HashSet::new();
|
||||
let pool = cfg.sync.workers.max(1);
|
||||
let mut watch = make_watch(
|
||||
ctx.tx.clone(),
|
||||
cfg.sync.ignore_extra.clone(),
|
||||
@@ -417,7 +509,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
groups.clone(),
|
||||
&ctx,
|
||||
);
|
||||
rescan(&root, &groups, &mut watch, &ctx);
|
||||
rescan(&root, &groups, &mut watch, &running, &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();
|
||||
@@ -429,14 +521,16 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
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<Instant> = None;
|
||||
// Deletions being confirmed and merged pull requests, per repo.
|
||||
let mut forge = ForgeMemory::default();
|
||||
|
||||
loop {
|
||||
'main: loop {
|
||||
let now = Instant::now();
|
||||
// With every worker busy nothing can start before a `Done` arrives: due repos must not
|
||||
// shorten the wait (that would spin).
|
||||
let idle = running.len() < pool;
|
||||
let wake = due_at
|
||||
.values()
|
||||
.copied()
|
||||
.iter()
|
||||
.filter(|(r, _)| idle && !running.contains(*r))
|
||||
.map(|(_, t)| *t)
|
||||
.chain([next_full])
|
||||
.chain(rescan_at)
|
||||
.min()
|
||||
@@ -467,19 +561,44 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
}
|
||||
Ok(Msg::SyncNow(Some(r))) => {
|
||||
backoff_until.remove(&r);
|
||||
if running.contains(&r) {
|
||||
sync_asked.insert(r.clone());
|
||||
}
|
||||
due_at.insert(r, Instant::now());
|
||||
}
|
||||
Ok(Msg::SyncNow(None)) => {
|
||||
backoff_until.clear();
|
||||
sync_asked.extend(running.iter().cloned());
|
||||
next_full = Instant::now();
|
||||
}
|
||||
Ok(Msg::Done {
|
||||
repo,
|
||||
failures,
|
||||
offline,
|
||||
}) => {
|
||||
running.remove(&repo);
|
||||
let asked = sync_asked.remove(&repo);
|
||||
if !is_ready(&repo) {
|
||||
// It vanished mid-pass (or was purged): whatever the pass reported is moot.
|
||||
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
|
||||
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
||||
} else if !offline {
|
||||
if failures == 0 || asked {
|
||||
backoff_until.remove(&repo);
|
||||
} else {
|
||||
let wait = Duration::from_secs(5u64.saturating_mul(1 << failures.min(6)))
|
||||
.min(MAX_BACKOFF);
|
||||
backoff_until.insert(repo, Instant::now() + wait);
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
let (found, added) = rescan(&root, &groups, &mut watch, &running, &ctx);
|
||||
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
||||
for r in added {
|
||||
due_at.insert(r, Instant::now());
|
||||
@@ -491,20 +610,26 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
let now = Instant::now();
|
||||
if now >= next_full {
|
||||
// Safety net for events the watcher missed (one `read_dir` per group).
|
||||
let (found, _) = rescan(&root, &groups, &mut watch, &ctx);
|
||||
let (found, _) = rescan(&root, &groups, &mut watch, &running, &ctx);
|
||||
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
||||
for r in found {
|
||||
due_at.insert(r, now);
|
||||
}
|
||||
next_full = now + fetch_every;
|
||||
}
|
||||
// A repo whose pass is running stays due and is dispatched when that pass is done.
|
||||
let mut due: Vec<PathBuf> = due_at
|
||||
.iter()
|
||||
.filter(|(_, t)| **t <= now)
|
||||
.filter(|(r, t)| **t <= now && !running.contains(*r))
|
||||
.map(|(r, _)| r.clone())
|
||||
.collect();
|
||||
due.sort();
|
||||
for r in due {
|
||||
// Only as many passes as idle workers: the rest stay due, so pause stops them and
|
||||
// `offline` is decided when a pass really starts.
|
||||
if running.len() >= pool {
|
||||
break;
|
||||
}
|
||||
if !ctx.shared.lock().unwrap().repos.contains_key(&r) {
|
||||
due_at.remove(&r);
|
||||
continue;
|
||||
@@ -513,35 +638,24 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
||||
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);
|
||||
let (found, _) = rescan(&root, &groups, &mut watch, &running, &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, &mut forge, &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;
|
||||
}
|
||||
if failures == 0 {
|
||||
backoff_until.remove(&r);
|
||||
} else {
|
||||
let wait =
|
||||
Duration::from_secs(5u64.saturating_mul(1 << failures.min(6))).min(MAX_BACKOFF);
|
||||
backoff_until.insert(r, Instant::now() + wait);
|
||||
}
|
||||
if ctx.shared.lock().unwrap().paused {
|
||||
break;
|
||||
running.insert(r.clone());
|
||||
if jobs.send(Job { repo: r, offline }).is_err() {
|
||||
break 'main;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Workers finish the pass they are running; nothing is cut short.
|
||||
drop(jobs);
|
||||
for w in workers {
|
||||
let _ = w.join();
|
||||
}
|
||||
ctx.activity.log("stop", None, "daemon stopped");
|
||||
}
|
||||
|
||||
@@ -557,11 +671,12 @@ fn forget_removed(
|
||||
backoff_until.retain(|r, _| found.contains(r));
|
||||
}
|
||||
|
||||
/// What the daemon remembers between passes about each repo's forge (in memory only).
|
||||
/// What the daemon remembers between passes about each repo's forge (in memory only), shared
|
||||
/// by the workers.
|
||||
#[derive(Default)]
|
||||
struct ForgeMemory {
|
||||
/// Repos whose forge first confirmed their deletion at this time (see `purge`).
|
||||
gone_since: HashMap<PathBuf, (u64, u64)>,
|
||||
gone_since: Mutex<HashMap<PathBuf, (u64, u64)>>,
|
||||
/// Merged pull requests per repo (see `merged`).
|
||||
merged: MergedCache,
|
||||
}
|
||||
@@ -571,9 +686,9 @@ fn pass(
|
||||
repo: &Path,
|
||||
cfg: &Config,
|
||||
st: &Settings,
|
||||
visibility: &mut Visibility,
|
||||
visibility: &Visibility,
|
||||
offline: bool,
|
||||
forge: &mut ForgeMemory,
|
||||
forge: &ForgeMemory,
|
||||
ctx: &Ctx,
|
||||
) -> u32 {
|
||||
let ForgeMemory { gone_since, merged } = forge;
|
||||
@@ -766,7 +881,7 @@ fn purge_if_gone(
|
||||
cfg: &Config,
|
||||
st: &Settings,
|
||||
result: &Result<grove_core::sync::SyncReport, grove_core::git::GitError>,
|
||||
gone_since: &mut HashMap<PathBuf, (u64, u64)>,
|
||||
gone_since: &Mutex<HashMap<PathBuf, (u64, u64)>>,
|
||||
ctx: &Ctx,
|
||||
) -> bool {
|
||||
let name = repo.display().to_string();
|
||||
@@ -776,14 +891,14 @@ fn purge_if_gone(
|
||||
};
|
||||
if !hint || cfg.sync.purged_dir.is_empty() {
|
||||
if matches!(result, Ok(rep) if rep.fetch_error.is_none()) {
|
||||
gone_since.remove(repo);
|
||||
gone_since.lock().unwrap().remove(repo);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
match purge::confirmed_gone(cfg, repo, &st.remote, &RealForge) {
|
||||
Ok(true) => {}
|
||||
Ok(false) => {
|
||||
gone_since.remove(repo);
|
||||
gone_since.lock().unwrap().remove(repo);
|
||||
return false;
|
||||
}
|
||||
// Cannot tell (network, token): keep whatever was confirmed before.
|
||||
@@ -791,13 +906,16 @@ fn purge_if_gone(
|
||||
}
|
||||
let now = now_secs();
|
||||
let window = purge::CONFIRM_AFTER_SECS;
|
||||
let entry = gone_since.entry(repo.to_path_buf()).or_insert((now, now));
|
||||
if now.saturating_sub(entry.1) > 2 * window {
|
||||
// Stale: start over.
|
||||
*entry = (now, now);
|
||||
}
|
||||
entry.1 = now;
|
||||
let first = entry.0;
|
||||
let first = {
|
||||
let mut map = gone_since.lock().unwrap();
|
||||
let entry = map.entry(repo.to_path_buf()).or_insert((now, now));
|
||||
if now.saturating_sub(entry.1) > 2 * window {
|
||||
// Stale: start over.
|
||||
*entry = (now, now);
|
||||
}
|
||||
entry.1 = now;
|
||||
entry.0
|
||||
};
|
||||
if first == now {
|
||||
ctx.activity.log(
|
||||
"purge_pending",
|
||||
@@ -816,8 +934,8 @@ fn purge_if_gone(
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let gone = |ctx: &Ctx, gone_since: &mut HashMap<PathBuf, (u64, u64)>| {
|
||||
gone_since.remove(repo);
|
||||
let gone = |ctx: &Ctx, gone_since: &Mutex<HashMap<PathBuf, (u64, u64)>>| {
|
||||
gone_since.lock().unwrap().remove(repo);
|
||||
ctx.shared.lock().unwrap().repos.remove(repo);
|
||||
};
|
||||
match purge::move_repo(repo, &dest) {
|
||||
|
||||
@@ -12,6 +12,7 @@ use grove_core::inspect::worktrees;
|
||||
use grove_core::prune::MergedHead;
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// How long a forge answer is reused.
|
||||
@@ -91,10 +92,11 @@ struct Entry {
|
||||
noted: BTreeSet<String>,
|
||||
}
|
||||
|
||||
/// Per-repo forge answers and notes, held by the daemon loop (in memory only).
|
||||
/// Per-repo forge answers and notes (in memory only), shared by the daemon's sync workers. The
|
||||
/// lock is never held across a forge request.
|
||||
#[derive(Default)]
|
||||
pub struct MergedCache {
|
||||
entries: HashMap<PathBuf, Entry>,
|
||||
entries: Mutex<HashMap<PathBuf, Entry>>,
|
||||
}
|
||||
|
||||
/// Result of [`MergedCache::heads`].
|
||||
@@ -107,25 +109,31 @@ pub struct Heads {
|
||||
impl MergedCache {
|
||||
/// The merged heads of `repo`, asking `src` when the cached answer is older than [`TTL`].
|
||||
pub fn heads(
|
||||
&mut self,
|
||||
&self,
|
||||
cfg: &Config,
|
||||
repo: &Path,
|
||||
remote: &str,
|
||||
src: &dyn PullSource,
|
||||
now: Instant,
|
||||
) -> Heads {
|
||||
let e = self.entries.entry(repo.to_path_buf()).or_default();
|
||||
if e.checked
|
||||
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
|
||||
{
|
||||
return Heads {
|
||||
heads: e.heads.clone(),
|
||||
new_error: None,
|
||||
};
|
||||
let mut entries = self.entries.lock().unwrap();
|
||||
let e = entries.entry(repo.to_path_buf()).or_default();
|
||||
if e.checked
|
||||
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
|
||||
{
|
||||
return Heads {
|
||||
heads: e.heads.clone(),
|
||||
new_error: None,
|
||||
};
|
||||
}
|
||||
e.checked = Some(now);
|
||||
}
|
||||
e.checked = Some(now);
|
||||
let answer = lookup(cfg, repo, remote, src);
|
||||
let mut entries = self.entries.lock().unwrap();
|
||||
let e = entries.entry(repo.to_path_buf()).or_default();
|
||||
let mut new_error = None;
|
||||
match lookup(cfg, repo, remote, src) {
|
||||
match answer {
|
||||
Ok(h) => {
|
||||
e.heads = h;
|
||||
e.error = None;
|
||||
@@ -145,8 +153,9 @@ impl MergedCache {
|
||||
|
||||
/// Of the "kept" notes of this pass, those not logged yet for `repo`. Notes that no longer
|
||||
/// apply are forgotten, so they are logged again if they come back.
|
||||
pub fn new_notes(&mut self, repo: &Path, notes: Vec<String>) -> Vec<String> {
|
||||
let e = self.entries.entry(repo.to_path_buf()).or_default();
|
||||
pub fn new_notes(&self, repo: &Path, notes: Vec<String>) -> Vec<String> {
|
||||
let mut entries = self.entries.lock().unwrap();
|
||||
let e = entries.entry(repo.to_path_buf()).or_default();
|
||||
let now: BTreeSet<String> = notes.into_iter().collect();
|
||||
let fresh = now.difference(&e.noted).cloned().collect();
|
||||
e.noted = now;
|
||||
@@ -156,6 +165,8 @@ impl MergedCache {
|
||||
/// The last answer for `repo`, without asking the forge (offline passes).
|
||||
pub fn cached(&self, repo: &Path) -> Vec<MergedHead> {
|
||||
self.entries
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(repo)
|
||||
.map(|e| e.heads.clone())
|
||||
.unwrap_or_default()
|
||||
@@ -217,7 +228,7 @@ mod tests {
|
||||
asked: RefCell::new(vec![]),
|
||||
answer: RefCell::new(Ok(vec![head(1)])),
|
||||
};
|
||||
let mut c = MergedCache::default();
|
||||
let c = MergedCache::default();
|
||||
let t0 = Instant::now();
|
||||
assert_eq!(c.heads(&cfg, &repo, "origin", &f, t0).heads, vec![head(1)]);
|
||||
assert_eq!(f.asked.borrow().as_slice(), ["gitea:Org/r"]);
|
||||
@@ -235,7 +246,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn notes_are_reported_once_while_they_hold() {
|
||||
let mut c = MergedCache::default();
|
||||
let c = MergedCache::default();
|
||||
let r = Path::new("/r");
|
||||
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
|
||||
assert!(c.new_notes(r, vec!["a".into()]).is_empty());
|
||||
|
||||
@@ -15,6 +15,7 @@ use grove_core::sync::git_dir_for;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// How long a "private" answer is trusted (a repo can be made public at any time).
|
||||
pub const PRIVATE_TTL: u64 = 3600;
|
||||
@@ -223,10 +224,16 @@ impl Entry {
|
||||
}
|
||||
}
|
||||
|
||||
/// Visibility cache. Owned by the daemon's single worker thread.
|
||||
/// Visibility cache, shared by the daemon's sync workers. The lock is never held across a
|
||||
/// forge request, so lookups for different repos run in parallel.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Visibility {
|
||||
path: Option<PathBuf>,
|
||||
state: Mutex<Cache>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Cache {
|
||||
entries: BTreeMap<String, Entry>,
|
||||
failed: HashMap<String, (u64, String)>,
|
||||
logins: HashMap<String, String>,
|
||||
@@ -242,12 +249,14 @@ impl Visibility {
|
||||
.unwrap_or_default();
|
||||
Visibility {
|
||||
path,
|
||||
entries,
|
||||
..Visibility::default()
|
||||
state: Mutex::new(Cache {
|
||||
entries,
|
||||
..Cache::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self) {
|
||||
fn save(&self, entries: &BTreeMap<String, Entry>) {
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let Some(path) = &self.path else { return };
|
||||
@@ -256,7 +265,7 @@ impl Visibility {
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
let Ok(text) = serde_json::to_string_pretty(&self.entries) else {
|
||||
let Ok(text) = serde_json::to_string_pretty(entries) else {
|
||||
return;
|
||||
};
|
||||
let written = std::fs::OpenOptions::new()
|
||||
@@ -272,7 +281,7 @@ impl Visibility {
|
||||
|
||||
/// What the forge says about `owner/name` on provider `pid`, from the cache or the forge.
|
||||
fn seen(
|
||||
&mut self,
|
||||
&self,
|
||||
pid: &str,
|
||||
pc: &ProviderCfg,
|
||||
owner: &str,
|
||||
@@ -282,34 +291,39 @@ impl Visibility {
|
||||
) -> Result<Seen, String> {
|
||||
let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/');
|
||||
let key = format!("{pid}|{url}|{owner}/{name}").to_ascii_lowercase();
|
||||
if let Some(e) = self.entries.get(&key)
|
||||
&& e.fresh(now)
|
||||
{
|
||||
return Ok(e.seen);
|
||||
let c = self.state.lock().unwrap();
|
||||
if let Some(e) = c.entries.get(&key)
|
||||
&& e.fresh(now)
|
||||
{
|
||||
return Ok(e.seen);
|
||||
}
|
||||
if let Some((at, why)) = c.failed.get(&key)
|
||||
&& at.saturating_sub(0) <= now
|
||||
&& now - at < RETRY
|
||||
{
|
||||
return Err(why.clone());
|
||||
}
|
||||
}
|
||||
if let Some((at, why)) = self.failed.get(&key)
|
||||
&& at.saturating_sub(0) <= now
|
||||
&& now - at < RETRY
|
||||
{
|
||||
return Err(why.clone());
|
||||
}
|
||||
match forge.seen(pid, pc, owner, name) {
|
||||
let answer = forge.seen(pid, pc, owner, name);
|
||||
let mut c = self.state.lock().unwrap();
|
||||
match answer {
|
||||
Ok(seen) => {
|
||||
self.failed.remove(&key);
|
||||
self.entries.insert(key, Entry { seen, checked: now });
|
||||
self.save();
|
||||
c.failed.remove(&key);
|
||||
c.entries.insert(key, Entry { seen, checked: now });
|
||||
self.save(&c.entries);
|
||||
Ok(seen)
|
||||
}
|
||||
Err(why) => {
|
||||
let why = format!("lookup on {pid:?} failed: {why}");
|
||||
self.failed.insert(key, (now, why.clone()));
|
||||
c.failed.insert(key, (now, why.clone()));
|
||||
Err(why)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Visibility of the repo behind one push URL.
|
||||
pub fn check_url(&mut self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
|
||||
pub fn check_url(&self, cfg: &Config, url: &str, now: u64, forge: &dyn Forge) -> Verdict {
|
||||
let Some(id) = parse_remote(url) else {
|
||||
return Verdict::Unknown("push URL not understood".into());
|
||||
};
|
||||
@@ -327,7 +341,7 @@ impl Visibility {
|
||||
|
||||
/// Mirror target `name` on provider `pid`: `Ok` when it is private or does not exist.
|
||||
fn check_mirror(
|
||||
&mut self,
|
||||
&self,
|
||||
cfg: &Config,
|
||||
group: &str,
|
||||
pid: &str,
|
||||
@@ -346,16 +360,20 @@ impl Visibility {
|
||||
.and_then(|g| g.owner(pid))
|
||||
{
|
||||
Some(o) => o.to_string(),
|
||||
None => match self.logins.get(pid) {
|
||||
Some(l) => l.clone(),
|
||||
None => {
|
||||
let l = forge
|
||||
.login(pid, pc)
|
||||
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
|
||||
self.logins.insert(pid.to_string(), l.clone());
|
||||
l
|
||||
None => {
|
||||
let known = self.state.lock().unwrap().logins.get(pid).cloned();
|
||||
match known {
|
||||
Some(l) => l,
|
||||
None => {
|
||||
let l = forge
|
||||
.login(pid, pc)
|
||||
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
|
||||
let mut c = self.state.lock().unwrap();
|
||||
c.logins.insert(pid.to_string(), l.clone());
|
||||
l
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
};
|
||||
match self.seen(pid, pc, &owner, name, now, forge) {
|
||||
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
|
||||
@@ -395,7 +413,7 @@ pub fn snapshot_gate(
|
||||
cfg: &Config,
|
||||
repo: &Path,
|
||||
remote: &str,
|
||||
vis: &mut Visibility,
|
||||
vis: &Visibility,
|
||||
now: u64,
|
||||
forge: &dyn Forge,
|
||||
) -> Result<(), String> {
|
||||
@@ -559,7 +577,7 @@ owners = { github = "gh-org" }
|
||||
.unwrap();
|
||||
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
|
||||
assert!(e.contains("several"));
|
||||
let mut v = Visibility::default();
|
||||
let v = Visibility::default();
|
||||
let fake = Fake::default().with("o/r", Ok(Seen::Private));
|
||||
assert!(matches!(
|
||||
v.check_url(&dup, "https://h.io/o/r", 0, &fake),
|
||||
@@ -571,7 +589,7 @@ owners = { github = "gh-org" }
|
||||
#[test]
|
||||
fn unknown_visibility_is_public_and_withholds_snapshots() {
|
||||
let c = cfg();
|
||||
let mut v = Visibility::default();
|
||||
let v = Visibility::default();
|
||||
let boom = Fake::default();
|
||||
for url in [
|
||||
"https://gitlab.com/o/r.git",
|
||||
@@ -608,7 +626,7 @@ owners = { github = "gh-org" }
|
||||
#[test]
|
||||
fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
|
||||
let c = cfg();
|
||||
let mut v = Visibility::default();
|
||||
let v = Visibility::default();
|
||||
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
||||
let url = "https://github.com/o/r";
|
||||
assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private);
|
||||
@@ -654,7 +672,7 @@ owners = { github = "gh-org" }
|
||||
#[test]
|
||||
fn cache_keys_include_provider_and_are_case_normalised() {
|
||||
let c = cfg();
|
||||
let mut v = Visibility::default();
|
||||
let v = Visibility::default();
|
||||
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
||||
v.check_url(&c, "https://github.com/O/R.git", 0, &f);
|
||||
v.check_url(&c, "git@github.com:o/r", 0, &f);
|
||||
@@ -676,7 +694,7 @@ owners = { github = "gh-org" }
|
||||
let file = dir.join("visibility.json");
|
||||
let c = cfg();
|
||||
let f = Fake::default().with("o/r", Ok(Seen::NotPrivate));
|
||||
let mut v = Visibility::load(Some(file.clone()));
|
||||
let v = Visibility::load(Some(file.clone()));
|
||||
assert_eq!(
|
||||
v.check_url(&c, "https://github.com/o/r", 50, &f),
|
||||
Verdict::Public
|
||||
@@ -684,7 +702,7 @@ owners = { github = "gh-org" }
|
||||
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(mode, 0o600);
|
||||
let never = Fake::default();
|
||||
let mut again = Visibility::load(Some(file));
|
||||
let again = Visibility::load(Some(file));
|
||||
assert_eq!(
|
||||
again.check_url(&c, "https://github.com/o/r", 60, &never),
|
||||
Verdict::Public
|
||||
@@ -721,22 +739,16 @@ owners = { github = "gh-org" }
|
||||
let f = Fake::default()
|
||||
.with("o/r", Ok(Seen::Private))
|
||||
.with("o/open", Ok(Seen::NotPrivate));
|
||||
let mut v = Visibility::default();
|
||||
let gate = |repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
|
||||
let v = Visibility::default();
|
||||
let gate = |repo: &Path, v: &Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
|
||||
let ok = "https://git.example.com:3000/o/r.git";
|
||||
assert!(gate(&mk(&base, "priv", &[ok], &[]), &mut v).is_ok());
|
||||
assert!(gate(&mk(&base, "off", &[ok], &[]), &mut v).is_err());
|
||||
assert!(
|
||||
gate(
|
||||
&mk(&base, "all", &["https://unknown.example/o/r"], &[]),
|
||||
&mut v
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
assert!(gate(&mk(&base, "priv", &[ok], &[]), &v).is_ok());
|
||||
assert!(gate(&mk(&base, "off", &[ok], &[]), &v).is_err());
|
||||
assert!(gate(&mk(&base, "all", &["https://unknown.example/o/r"], &[]), &v).is_ok());
|
||||
// Fetch URL private, but the push goes to a public repo (pushurl).
|
||||
let e = gate(
|
||||
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
|
||||
&mut v,
|
||||
&v,
|
||||
);
|
||||
assert!(e.is_err());
|
||||
// Private-only without any remote: unknown, withheld.
|
||||
@@ -744,7 +756,7 @@ owners = { github = "gh-org" }
|
||||
std::fs::create_dir_all(&bare).unwrap();
|
||||
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
|
||||
assert!(
|
||||
gate(&base.join("priv/none"), &mut v)
|
||||
gate(&base.join("priv/none"), &v)
|
||||
.unwrap_err()
|
||||
.contains("unknown")
|
||||
);
|
||||
@@ -760,24 +772,24 @@ owners = { github = "gh-org" }
|
||||
let f = Fake::default()
|
||||
.with("o/r", Ok(Seen::Private))
|
||||
.with("o/open", Ok(Seen::NotPrivate));
|
||||
let mut v = Visibility::default();
|
||||
let v = Visibility::default();
|
||||
let ok = "https://git.example.com:3000/o/r.git";
|
||||
let open = "https://github.com/o/open";
|
||||
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
|
||||
let both = mk(&base, "priv", &[ok], &[ok, "https://github.com/o/r"]);
|
||||
assert!(snapshot_gate(&c, &both, "origin", &mut v, 0, &f).is_ok());
|
||||
assert!(snapshot_gate(&c, &both, "origin", &v, 0, &f).is_ok());
|
||||
std::fs::remove_dir_all(base.join("priv")).unwrap();
|
||||
let leaky = mk(&base, "priv", &[ok, open], &[]);
|
||||
let e = snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).unwrap_err();
|
||||
let e = snapshot_gate(&c, &leaky, "origin", &v, 0, &f).unwrap_err();
|
||||
assert!(e.contains("public"), "{e}");
|
||||
// pushInsteadOf rewrites the push URL to a public repo.
|
||||
let g = Git::new(leaky.join(".bare"));
|
||||
g.run(&["remote", "set-url", "--delete", "origin", open])
|
||||
.unwrap();
|
||||
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_ok());
|
||||
assert!(snapshot_gate(&c, &leaky, "origin", &v, 0, &f).is_ok());
|
||||
g.run(&["config", &format!("url.{open}.pushInsteadOf"), ok])
|
||||
.unwrap();
|
||||
assert!(snapshot_gate(&c, &leaky, "origin", &mut v, 0, &f).is_err());
|
||||
assert!(snapshot_gate(&c, &leaky, "origin", &v, 0, &f).is_err());
|
||||
std::fs::remove_dir_all(&base).unwrap();
|
||||
}
|
||||
|
||||
@@ -789,8 +801,8 @@ owners = { github = "gh-org" }
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
|
||||
let gate = |f: &Fake| {
|
||||
let mut v = Visibility::default();
|
||||
snapshot_gate(&c, &repo, "origin", &mut v, 0, f)
|
||||
let v = Visibility::default();
|
||||
snapshot_gate(&c, &repo, "origin", &v, 0, f)
|
||||
};
|
||||
let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
|
||||
// No mirror (404): fine. Mirror owner comes from `owners`.
|
||||
|
||||
@@ -768,3 +768,27 @@ fn clone_appears_only_when_complete() {
|
||||
assert!(seen, "cloned repo never managed");
|
||||
d.shutdown();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hanging_fetch_does_not_hold_up_other_repos() {
|
||||
let w = world("workers", &["pca"]);
|
||||
// `a-slow` sorts first, so its pass is dispatched first; its fetch hangs for 15 s.
|
||||
let slow = w.base.join("pca/g/a-slow");
|
||||
bare_layout(&slow, &w.remote);
|
||||
let bare = slow.join(".bare");
|
||||
git(
|
||||
&bare,
|
||||
&["remote", "set-url", "origin", "ssh://hang.invalid/x.git"],
|
||||
);
|
||||
git(&bare, &["config", "core.sshCommand", "sleep 15; false"]);
|
||||
let mut cfg = config(&w, "pca", 200, 60);
|
||||
cfg.sync.workers = 2;
|
||||
let started = Instant::now();
|
||||
let d = Daemon::start(cfg, settings(&w, "pca")).unwrap();
|
||||
fs::write(w.base.join("pca/g/repo/main/new.txt"), "x\n").unwrap();
|
||||
wait_until("snapshot of the other repo pushed", 10, || {
|
||||
!git(&w.remote, &["for-each-ref", "refs/sync/pca/"]).is_empty()
|
||||
});
|
||||
assert!(started.elapsed() < Duration::from_secs(12));
|
||||
d.shutdown();
|
||||
}
|
||||
+10
-2
@@ -17,8 +17,16 @@ is `grove_core::sync::sync_repo`, the same code the CLI runs. The daemon only de
|
||||
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.
|
||||
- **Worker pool**: the loop thread only schedules; `sync.workers` threads (default 4, 1 to 32) run
|
||||
the passes, so a slow or hanging fetch of one repo no longer holds up the others. A repo never
|
||||
has two passes at once: one that becomes due while its pass runs is dispatched when it ends.
|
||||
Events that arrive during a pass queue another pass; it finds nothing to do and ends the chain.
|
||||
Passes are handed out only to idle workers, so the rest stay due: pause stops them, and whether
|
||||
a pass runs offline (backoff) is decided when it starts. A `sync` request for a repo whose pass
|
||||
is running is not undone by that pass failing. A panicking pass is logged and counts as a
|
||||
failure. Rediscovery does not drop or flag (stalled) a repo while its pass runs.
|
||||
The visibility and merged-PR caches are shared and never locked across a forge request.
|
||||
Shutdown and pause let running passes finish. `workers = 1` is the old sequential behaviour.
|
||||
- **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. While backing off, changes
|
||||
are still snapshotted locally (an offline pass); only the network is retried after the backoff.
|
||||
|
||||
Reference in new issue
Block a user