mirror of
https://github.com/Dasemu/Grove.git
synced 2026-11-27 07:46:13 +00:00
Merge pull request #11 from Dasemu/feat/parallel-sync
feat(daemon): run sync passes on a worker pool
This commit is contained in:
7 files changed
+292
-102
No files matched your search
@@ -171,6 +171,10 @@ pub struct Sync {
|
|||||||
/// (`prune::default_protected`) and the default branch. See [`Sync::protected_branches`].
|
/// (`prune::default_protected`) and the default branch. See [`Sync::protected_branches`].
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub prune_protected: Vec<String>,
|
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 {
|
impl Sync {
|
||||||
@@ -194,6 +198,7 @@ impl Default for Sync {
|
|||||||
prune_merged: true,
|
prune_merged: true,
|
||||||
prune_disposable: default_disposable(),
|
prune_disposable: default_disposable(),
|
||||||
prune_protected: Vec::new(),
|
prune_protected: Vec::new(),
|
||||||
|
workers: default_workers(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -207,6 +212,9 @@ pub struct ConfigRepo {
|
|||||||
fn yes() -> bool {
|
fn yes() -> bool {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
fn default_workers() -> usize {
|
||||||
|
4
|
||||||
|
}
|
||||||
fn default_debounce() -> u64 {
|
fn default_debounce() -> u64 {
|
||||||
2000
|
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
|
if let Some(d) = self
|
||||||
.sync
|
.sync
|
||||||
.prune_disposable
|
.prune_disposable
|
||||||
|
|||||||
@@ -47,7 +47,10 @@ fn temp_index_path() -> PathBuf {
|
|||||||
.duration_since(UNIX_EPOCH)
|
.duration_since(UNIX_EPOCH)
|
||||||
.map(|d| d.as_nanos())
|
.map(|d| d.as_nanos())
|
||||||
.unwrap_or(0);
|
.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),
|
/// 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
|
//! 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,
|
//! the watcher missed, failures back off exponentially. The loop thread schedules; a pool of
|
||||||
//! so passes never overlap.
|
//! `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::activity::{Activity, now_secs};
|
||||||
use crate::discover::{discover, group_of, is_ready, subdirs};
|
use crate::discover::{discover, group_of, is_ready, subdirs};
|
||||||
@@ -99,9 +100,72 @@ pub enum Msg {
|
|||||||
Rescan,
|
Rescan,
|
||||||
/// Sync one repo (or all) as soon as possible.
|
/// Sync one repo (or all) as soon as possible.
|
||||||
SyncNow(Option<PathBuf>),
|
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,
|
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)]
|
#[derive(Clone)]
|
||||||
pub struct Ctx {
|
pub struct Ctx {
|
||||||
pub shared: Arc<Mutex<Shared>>,
|
pub shared: Arc<Mutex<Shared>>,
|
||||||
@@ -337,6 +401,7 @@ fn rescan(
|
|||||||
root: &Path,
|
root: &Path,
|
||||||
groups: &[String],
|
groups: &[String],
|
||||||
watch: &mut Watch,
|
watch: &mut Watch,
|
||||||
|
running: &HashSet<PathBuf>,
|
||||||
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
|
// 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);
|
watch.sync(&wanted, false, ctx);
|
||||||
let d = discover(root, groups);
|
let mut d = discover(root, groups);
|
||||||
let found = d.managed;
|
// 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 {
|
for r in &d.stalled {
|
||||||
if watch.warned_stalled.insert(r.clone()) {
|
if watch.warned_stalled.insert(r.clone()) {
|
||||||
ctx.activity.log(
|
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 fetch_every = Duration::from_secs(cfg.sync.fetch_interval_s.max(1));
|
||||||
let root = cfg.root_path();
|
let root = cfg.root_path();
|
||||||
let groups: Vec<String> = cfg.groups.iter().map(|g| g.name.clone()).collect();
|
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(
|
let mut watch = make_watch(
|
||||||
ctx.tx.clone(),
|
ctx.tx.clone(),
|
||||||
cfg.sync.ignore_extra.clone(),
|
cfg.sync.ignore_extra.clone(),
|
||||||
@@ -417,7 +509,7 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
groups.clone(),
|
groups.clone(),
|
||||||
&ctx,
|
&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.
|
// 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 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();
|
let mut next_full = Instant::now();
|
||||||
// When a debounced rediscovery is due (set by the first event of a burst, never pushed back).
|
// When a debounced rediscovery is due (set by the first event of a burst, never pushed back).
|
||||||
let mut rescan_at: Option<Instant> = None;
|
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();
|
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
|
let wake = due_at
|
||||||
.values()
|
.iter()
|
||||||
.copied()
|
.filter(|(r, _)| idle && !running.contains(*r))
|
||||||
|
.map(|(_, t)| *t)
|
||||||
.chain([next_full])
|
.chain([next_full])
|
||||||
.chain(rescan_at)
|
.chain(rescan_at)
|
||||||
.min()
|
.min()
|
||||||
@@ -467,19 +561,44 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
}
|
}
|
||||||
Ok(Msg::SyncNow(Some(r))) => {
|
Ok(Msg::SyncNow(Some(r))) => {
|
||||||
backoff_until.remove(&r);
|
backoff_until.remove(&r);
|
||||||
|
if running.contains(&r) {
|
||||||
|
sync_asked.insert(r.clone());
|
||||||
|
}
|
||||||
due_at.insert(r, Instant::now());
|
due_at.insert(r, Instant::now());
|
||||||
}
|
}
|
||||||
Ok(Msg::SyncNow(None)) => {
|
Ok(Msg::SyncNow(None)) => {
|
||||||
backoff_until.clear();
|
backoff_until.clear();
|
||||||
|
sync_asked.extend(running.iter().cloned());
|
||||||
next_full = Instant::now();
|
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,
|
Ok(Msg::Shutdown) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
|
||||||
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
|
Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
|
||||||
}
|
}
|
||||||
// Discovery also runs while paused so the status stays current; only syncing stops.
|
// Discovery also runs while paused so the status stays current; only syncing stops.
|
||||||
if rescan_at.is_some_and(|t| t <= Instant::now()) {
|
if rescan_at.is_some_and(|t| t <= Instant::now()) {
|
||||||
rescan_at = None;
|
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);
|
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
||||||
for r in added {
|
for r in added {
|
||||||
due_at.insert(r, Instant::now());
|
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();
|
let now = Instant::now();
|
||||||
if now >= next_full {
|
if now >= next_full {
|
||||||
// Safety net for events the watcher missed (one `read_dir` per group).
|
// 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);
|
forget_removed(&found, &mut due_at, &mut first_at, &mut backoff_until);
|
||||||
for r in found {
|
for r in found {
|
||||||
due_at.insert(r, now);
|
due_at.insert(r, now);
|
||||||
}
|
}
|
||||||
next_full = now + fetch_every;
|
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
|
let mut due: Vec<PathBuf> = due_at
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|(_, t)| **t <= now)
|
.filter(|(r, t)| **t <= now && !running.contains(*r))
|
||||||
.map(|(r, _)| r.clone())
|
.map(|(r, _)| r.clone())
|
||||||
.collect();
|
.collect();
|
||||||
due.sort();
|
due.sort();
|
||||||
for r in due {
|
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) {
|
if !ctx.shared.lock().unwrap().repos.contains_key(&r) {
|
||||||
due_at.remove(&r);
|
due_at.remove(&r);
|
||||||
continue;
|
continue;
|
||||||
@@ -513,35 +638,24 @@ fn run(cfg: Config, st: Settings, rx: Receiver<Msg>, ctx: Ctx) {
|
|||||||
first_at.remove(&r);
|
first_at.remove(&r);
|
||||||
if !is_ready(&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, &running, &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);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// While backing off after a failure, still snapshot local work (no network needed);
|
// 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.
|
// 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, &mut forge, &ctx);
|
running.insert(r.clone());
|
||||||
if !is_ready(&r) {
|
if jobs.send(Job { repo: r, offline }).is_err() {
|
||||||
// It vanished mid-pass: whatever the pass reported is moot.
|
break 'main;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// 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");
|
ctx.activity.log("stop", None, "daemon stopped");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -557,11 +671,12 @@ fn forget_removed(
|
|||||||
backoff_until.retain(|r, _| found.contains(r));
|
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)]
|
#[derive(Default)]
|
||||||
struct ForgeMemory {
|
struct ForgeMemory {
|
||||||
/// Repos whose forge first confirmed their deletion at this time (see `purge`).
|
/// 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 pull requests per repo (see `merged`).
|
||||||
merged: MergedCache,
|
merged: MergedCache,
|
||||||
}
|
}
|
||||||
@@ -571,9 +686,9 @@ fn pass(
|
|||||||
repo: &Path,
|
repo: &Path,
|
||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
st: &Settings,
|
st: &Settings,
|
||||||
visibility: &mut Visibility,
|
visibility: &Visibility,
|
||||||
offline: bool,
|
offline: bool,
|
||||||
forge: &mut ForgeMemory,
|
forge: &ForgeMemory,
|
||||||
ctx: &Ctx,
|
ctx: &Ctx,
|
||||||
) -> u32 {
|
) -> u32 {
|
||||||
let ForgeMemory { gone_since, merged } = forge;
|
let ForgeMemory { gone_since, merged } = forge;
|
||||||
@@ -766,7 +881,7 @@ fn purge_if_gone(
|
|||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
st: &Settings,
|
st: &Settings,
|
||||||
result: &Result<grove_core::sync::SyncReport, grove_core::git::GitError>,
|
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,
|
ctx: &Ctx,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
let name = repo.display().to_string();
|
let name = repo.display().to_string();
|
||||||
@@ -776,14 +891,14 @@ fn purge_if_gone(
|
|||||||
};
|
};
|
||||||
if !hint || cfg.sync.purged_dir.is_empty() {
|
if !hint || cfg.sync.purged_dir.is_empty() {
|
||||||
if matches!(result, Ok(rep) if rep.fetch_error.is_none()) {
|
if matches!(result, Ok(rep) if rep.fetch_error.is_none()) {
|
||||||
gone_since.remove(repo);
|
gone_since.lock().unwrap().remove(repo);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
match purge::confirmed_gone(cfg, repo, &st.remote, &RealForge) {
|
match purge::confirmed_gone(cfg, repo, &st.remote, &RealForge) {
|
||||||
Ok(true) => {}
|
Ok(true) => {}
|
||||||
Ok(false) => {
|
Ok(false) => {
|
||||||
gone_since.remove(repo);
|
gone_since.lock().unwrap().remove(repo);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// Cannot tell (network, token): keep whatever was confirmed before.
|
// Cannot tell (network, token): keep whatever was confirmed before.
|
||||||
@@ -791,13 +906,16 @@ fn purge_if_gone(
|
|||||||
}
|
}
|
||||||
let now = now_secs();
|
let now = now_secs();
|
||||||
let window = purge::CONFIRM_AFTER_SECS;
|
let window = purge::CONFIRM_AFTER_SECS;
|
||||||
let entry = gone_since.entry(repo.to_path_buf()).or_insert((now, now));
|
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 {
|
if now.saturating_sub(entry.1) > 2 * window {
|
||||||
// Stale: start over.
|
// Stale: start over.
|
||||||
*entry = (now, now);
|
*entry = (now, now);
|
||||||
}
|
}
|
||||||
entry.1 = now;
|
entry.1 = now;
|
||||||
let first = entry.0;
|
entry.0
|
||||||
|
};
|
||||||
if first == now {
|
if first == now {
|
||||||
ctx.activity.log(
|
ctx.activity.log(
|
||||||
"purge_pending",
|
"purge_pending",
|
||||||
@@ -816,8 +934,8 @@ fn purge_if_gone(
|
|||||||
else {
|
else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
let gone = |ctx: &Ctx, gone_since: &mut HashMap<PathBuf, (u64, u64)>| {
|
let gone = |ctx: &Ctx, gone_since: &Mutex<HashMap<PathBuf, (u64, u64)>>| {
|
||||||
gone_since.remove(repo);
|
gone_since.lock().unwrap().remove(repo);
|
||||||
ctx.shared.lock().unwrap().repos.remove(repo);
|
ctx.shared.lock().unwrap().repos.remove(repo);
|
||||||
};
|
};
|
||||||
match purge::move_repo(repo, &dest) {
|
match purge::move_repo(repo, &dest) {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ use grove_core::inspect::worktrees;
|
|||||||
use grove_core::prune::MergedHead;
|
use grove_core::prune::MergedHead;
|
||||||
use std::collections::{BTreeSet, HashMap};
|
use std::collections::{BTreeSet, HashMap};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Mutex;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
/// How long a forge answer is reused.
|
/// How long a forge answer is reused.
|
||||||
@@ -91,10 +92,11 @@ struct Entry {
|
|||||||
noted: BTreeSet<String>,
|
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)]
|
#[derive(Default)]
|
||||||
pub struct MergedCache {
|
pub struct MergedCache {
|
||||||
entries: HashMap<PathBuf, Entry>,
|
entries: Mutex<HashMap<PathBuf, Entry>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Result of [`MergedCache::heads`].
|
/// Result of [`MergedCache::heads`].
|
||||||
@@ -107,14 +109,16 @@ pub struct Heads {
|
|||||||
impl MergedCache {
|
impl MergedCache {
|
||||||
/// The merged heads of `repo`, asking `src` when the cached answer is older than [`TTL`].
|
/// The merged heads of `repo`, asking `src` when the cached answer is older than [`TTL`].
|
||||||
pub fn heads(
|
pub fn heads(
|
||||||
&mut self,
|
&self,
|
||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
repo: &Path,
|
repo: &Path,
|
||||||
remote: &str,
|
remote: &str,
|
||||||
src: &dyn PullSource,
|
src: &dyn PullSource,
|
||||||
now: Instant,
|
now: Instant,
|
||||||
) -> Heads {
|
) -> Heads {
|
||||||
let e = self.entries.entry(repo.to_path_buf()).or_default();
|
{
|
||||||
|
let mut entries = self.entries.lock().unwrap();
|
||||||
|
let e = entries.entry(repo.to_path_buf()).or_default();
|
||||||
if e.checked
|
if e.checked
|
||||||
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
|
.is_some_and(|t| now.saturating_duration_since(t) < TTL)
|
||||||
{
|
{
|
||||||
@@ -124,8 +128,12 @@ impl MergedCache {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
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;
|
let mut new_error = None;
|
||||||
match lookup(cfg, repo, remote, src) {
|
match answer {
|
||||||
Ok(h) => {
|
Ok(h) => {
|
||||||
e.heads = h;
|
e.heads = h;
|
||||||
e.error = None;
|
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
|
/// 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.
|
/// 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> {
|
pub fn new_notes(&self, repo: &Path, notes: Vec<String>) -> Vec<String> {
|
||||||
let e = self.entries.entry(repo.to_path_buf()).or_default();
|
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 now: BTreeSet<String> = notes.into_iter().collect();
|
||||||
let fresh = now.difference(&e.noted).cloned().collect();
|
let fresh = now.difference(&e.noted).cloned().collect();
|
||||||
e.noted = now;
|
e.noted = now;
|
||||||
@@ -156,6 +165,8 @@ impl MergedCache {
|
|||||||
/// The last answer for `repo`, without asking the forge (offline passes).
|
/// The last answer for `repo`, without asking the forge (offline passes).
|
||||||
pub fn cached(&self, repo: &Path) -> Vec<MergedHead> {
|
pub fn cached(&self, repo: &Path) -> Vec<MergedHead> {
|
||||||
self.entries
|
self.entries
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
.get(repo)
|
.get(repo)
|
||||||
.map(|e| e.heads.clone())
|
.map(|e| e.heads.clone())
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
@@ -217,7 +228,7 @@ mod tests {
|
|||||||
asked: RefCell::new(vec![]),
|
asked: RefCell::new(vec![]),
|
||||||
answer: RefCell::new(Ok(vec![head(1)])),
|
answer: RefCell::new(Ok(vec![head(1)])),
|
||||||
};
|
};
|
||||||
let mut c = MergedCache::default();
|
let c = MergedCache::default();
|
||||||
let t0 = Instant::now();
|
let t0 = Instant::now();
|
||||||
assert_eq!(c.heads(&cfg, &repo, "origin", &f, t0).heads, vec![head(1)]);
|
assert_eq!(c.heads(&cfg, &repo, "origin", &f, t0).heads, vec![head(1)]);
|
||||||
assert_eq!(f.asked.borrow().as_slice(), ["gitea:Org/r"]);
|
assert_eq!(f.asked.borrow().as_slice(), ["gitea:Org/r"]);
|
||||||
@@ -235,7 +246,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn notes_are_reported_once_while_they_hold() {
|
fn notes_are_reported_once_while_they_hold() {
|
||||||
let mut c = MergedCache::default();
|
let c = MergedCache::default();
|
||||||
let r = Path::new("/r");
|
let r = Path::new("/r");
|
||||||
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
|
assert_eq!(c.new_notes(r, vec!["a".into()]), vec!["a".to_string()]);
|
||||||
assert!(c.new_notes(r, vec!["a".into()]).is_empty());
|
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 serde::{Deserialize, Serialize};
|
||||||
use std::collections::{BTreeMap, HashMap};
|
use std::collections::{BTreeMap, HashMap};
|
||||||
use std::path::{Path, PathBuf};
|
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).
|
/// How long a "private" answer is trusted (a repo can be made public at any time).
|
||||||
pub const PRIVATE_TTL: u64 = 3600;
|
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)]
|
#[derive(Debug, Default)]
|
||||||
pub struct Visibility {
|
pub struct Visibility {
|
||||||
path: Option<PathBuf>,
|
path: Option<PathBuf>,
|
||||||
|
state: Mutex<Cache>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Cache {
|
||||||
entries: BTreeMap<String, Entry>,
|
entries: BTreeMap<String, Entry>,
|
||||||
failed: HashMap<String, (u64, String)>,
|
failed: HashMap<String, (u64, String)>,
|
||||||
logins: HashMap<String, String>,
|
logins: HashMap<String, String>,
|
||||||
@@ -242,12 +249,14 @@ impl Visibility {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
Visibility {
|
Visibility {
|
||||||
path,
|
path,
|
||||||
|
state: Mutex::new(Cache {
|
||||||
entries,
|
entries,
|
||||||
..Visibility::default()
|
..Cache::default()
|
||||||
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn save(&self) {
|
fn save(&self, entries: &BTreeMap<String, Entry>) {
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
use std::os::unix::fs::OpenOptionsExt;
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
let Some(path) = &self.path else { return };
|
let Some(path) = &self.path else { return };
|
||||||
@@ -256,7 +265,7 @@ impl Visibility {
|
|||||||
}
|
}
|
||||||
let tmp = path.with_extension("json.tmp");
|
let tmp = path.with_extension("json.tmp");
|
||||||
let _ = std::fs::remove_file(&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;
|
return;
|
||||||
};
|
};
|
||||||
let written = std::fs::OpenOptions::new()
|
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.
|
/// What the forge says about `owner/name` on provider `pid`, from the cache or the forge.
|
||||||
fn seen(
|
fn seen(
|
||||||
&mut self,
|
&self,
|
||||||
pid: &str,
|
pid: &str,
|
||||||
pc: &ProviderCfg,
|
pc: &ProviderCfg,
|
||||||
owner: &str,
|
owner: &str,
|
||||||
@@ -282,34 +291,39 @@ impl Visibility {
|
|||||||
) -> Result<Seen, String> {
|
) -> Result<Seen, String> {
|
||||||
let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/');
|
let url = pc.url.as_deref().unwrap_or_default().trim_end_matches('/');
|
||||||
let key = format!("{pid}|{url}|{owner}/{name}").to_ascii_lowercase();
|
let key = format!("{pid}|{url}|{owner}/{name}").to_ascii_lowercase();
|
||||||
if let Some(e) = self.entries.get(&key)
|
{
|
||||||
|
let c = self.state.lock().unwrap();
|
||||||
|
if let Some(e) = c.entries.get(&key)
|
||||||
&& e.fresh(now)
|
&& e.fresh(now)
|
||||||
{
|
{
|
||||||
return Ok(e.seen);
|
return Ok(e.seen);
|
||||||
}
|
}
|
||||||
if let Some((at, why)) = self.failed.get(&key)
|
if let Some((at, why)) = c.failed.get(&key)
|
||||||
&& at.saturating_sub(0) <= now
|
&& at.saturating_sub(0) <= now
|
||||||
&& now - at < RETRY
|
&& now - at < RETRY
|
||||||
{
|
{
|
||||||
return Err(why.clone());
|
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) => {
|
Ok(seen) => {
|
||||||
self.failed.remove(&key);
|
c.failed.remove(&key);
|
||||||
self.entries.insert(key, Entry { seen, checked: now });
|
c.entries.insert(key, Entry { seen, checked: now });
|
||||||
self.save();
|
self.save(&c.entries);
|
||||||
Ok(seen)
|
Ok(seen)
|
||||||
}
|
}
|
||||||
Err(why) => {
|
Err(why) => {
|
||||||
let why = format!("lookup on {pid:?} failed: {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)
|
Err(why)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Visibility of the repo behind one push URL.
|
/// 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 {
|
let Some(id) = parse_remote(url) else {
|
||||||
return Verdict::Unknown("push URL not understood".into());
|
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.
|
/// Mirror target `name` on provider `pid`: `Ok` when it is private or does not exist.
|
||||||
fn check_mirror(
|
fn check_mirror(
|
||||||
&mut self,
|
&self,
|
||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
group: &str,
|
group: &str,
|
||||||
pid: &str,
|
pid: &str,
|
||||||
@@ -346,16 +360,20 @@ impl Visibility {
|
|||||||
.and_then(|g| g.owner(pid))
|
.and_then(|g| g.owner(pid))
|
||||||
{
|
{
|
||||||
Some(o) => o.to_string(),
|
Some(o) => o.to_string(),
|
||||||
None => match self.logins.get(pid) {
|
None => {
|
||||||
Some(l) => l.clone(),
|
let known = self.state.lock().unwrap().logins.get(pid).cloned();
|
||||||
|
match known {
|
||||||
|
Some(l) => l,
|
||||||
None => {
|
None => {
|
||||||
let l = forge
|
let l = forge
|
||||||
.login(pid, pc)
|
.login(pid, pc)
|
||||||
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
|
.map_err(|e| format!("mirror on {pid:?}: cannot get login: {e}"))?;
|
||||||
self.logins.insert(pid.to_string(), l.clone());
|
let mut c = self.state.lock().unwrap();
|
||||||
|
c.logins.insert(pid.to_string(), l.clone());
|
||||||
l
|
l
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
match self.seen(pid, pc, &owner, name, now, forge) {
|
match self.seen(pid, pc, &owner, name, now, forge) {
|
||||||
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
|
Ok(Seen::NotPrivate) => Err(format!("mirror {pid}:{owner}/{name} is public")),
|
||||||
@@ -395,7 +413,7 @@ pub fn snapshot_gate(
|
|||||||
cfg: &Config,
|
cfg: &Config,
|
||||||
repo: &Path,
|
repo: &Path,
|
||||||
remote: &str,
|
remote: &str,
|
||||||
vis: &mut Visibility,
|
vis: &Visibility,
|
||||||
now: u64,
|
now: u64,
|
||||||
forge: &dyn Forge,
|
forge: &dyn Forge,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
@@ -559,7 +577,7 @@ owners = { github = "gh-org" }
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
|
let e = provider_for(&dup, &parse_remote("https://h.io/o/r").unwrap()).unwrap_err();
|
||||||
assert!(e.contains("several"));
|
assert!(e.contains("several"));
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let fake = Fake::default().with("o/r", Ok(Seen::Private));
|
let fake = Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
v.check_url(&dup, "https://h.io/o/r", 0, &fake),
|
v.check_url(&dup, "https://h.io/o/r", 0, &fake),
|
||||||
@@ -571,7 +589,7 @@ owners = { github = "gh-org" }
|
|||||||
#[test]
|
#[test]
|
||||||
fn unknown_visibility_is_public_and_withholds_snapshots() {
|
fn unknown_visibility_is_public_and_withholds_snapshots() {
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let boom = Fake::default();
|
let boom = Fake::default();
|
||||||
for url in [
|
for url in [
|
||||||
"https://gitlab.com/o/r.git",
|
"https://gitlab.com/o/r.git",
|
||||||
@@ -608,7 +626,7 @@ owners = { github = "gh-org" }
|
|||||||
#[test]
|
#[test]
|
||||||
fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
|
fn private_answers_expire_after_an_hour_and_failures_are_throttled() {
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
let url = "https://github.com/o/r";
|
let url = "https://github.com/o/r";
|
||||||
assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private);
|
assert_eq!(v.check_url(&c, url, 100, &f), Verdict::Private);
|
||||||
@@ -654,7 +672,7 @@ owners = { github = "gh-org" }
|
|||||||
#[test]
|
#[test]
|
||||||
fn cache_keys_include_provider_and_are_case_normalised() {
|
fn cache_keys_include_provider_and_are_case_normalised() {
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let f = Fake::default().with("o/r", Ok(Seen::Private));
|
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, "https://github.com/O/R.git", 0, &f);
|
||||||
v.check_url(&c, "git@github.com:o/r", 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 file = dir.join("visibility.json");
|
||||||
let c = cfg();
|
let c = cfg();
|
||||||
let f = Fake::default().with("o/r", Ok(Seen::NotPrivate));
|
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!(
|
assert_eq!(
|
||||||
v.check_url(&c, "https://github.com/o/r", 50, &f),
|
v.check_url(&c, "https://github.com/o/r", 50, &f),
|
||||||
Verdict::Public
|
Verdict::Public
|
||||||
@@ -684,7 +702,7 @@ owners = { github = "gh-org" }
|
|||||||
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
|
let mode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
|
||||||
assert_eq!(mode, 0o600);
|
assert_eq!(mode, 0o600);
|
||||||
let never = Fake::default();
|
let never = Fake::default();
|
||||||
let mut again = Visibility::load(Some(file));
|
let again = Visibility::load(Some(file));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
again.check_url(&c, "https://github.com/o/r", 60, &never),
|
again.check_url(&c, "https://github.com/o/r", 60, &never),
|
||||||
Verdict::Public
|
Verdict::Public
|
||||||
@@ -721,22 +739,16 @@ owners = { github = "gh-org" }
|
|||||||
let f = Fake::default()
|
let f = Fake::default()
|
||||||
.with("o/r", Ok(Seen::Private))
|
.with("o/r", Ok(Seen::Private))
|
||||||
.with("o/open", Ok(Seen::NotPrivate));
|
.with("o/open", Ok(Seen::NotPrivate));
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
let gate = |repo: &Path, v: &mut Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
|
let gate = |repo: &Path, v: &Visibility| snapshot_gate(&c, repo, "origin", v, 0, &f);
|
||||||
let ok = "https://git.example.com:3000/o/r.git";
|
let ok = "https://git.example.com:3000/o/r.git";
|
||||||
assert!(gate(&mk(&base, "priv", &[ok], &[]), &mut v).is_ok());
|
assert!(gate(&mk(&base, "priv", &[ok], &[]), &v).is_ok());
|
||||||
assert!(gate(&mk(&base, "off", &[ok], &[]), &mut v).is_err());
|
assert!(gate(&mk(&base, "off", &[ok], &[]), &v).is_err());
|
||||||
assert!(
|
assert!(gate(&mk(&base, "all", &["https://unknown.example/o/r"], &[]), &v).is_ok());
|
||||||
gate(
|
|
||||||
&mk(&base, "all", &["https://unknown.example/o/r"], &[]),
|
|
||||||
&mut v
|
|
||||||
)
|
|
||||||
.is_ok()
|
|
||||||
);
|
|
||||||
// Fetch URL private, but the push goes to a public repo (pushurl).
|
// Fetch URL private, but the push goes to a public repo (pushurl).
|
||||||
let e = gate(
|
let e = gate(
|
||||||
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
|
&mk(&base, "priv2", &[ok], &["https://github.com/o/open"]),
|
||||||
&mut v,
|
&v,
|
||||||
);
|
);
|
||||||
assert!(e.is_err());
|
assert!(e.is_err());
|
||||||
// Private-only without any remote: unknown, withheld.
|
// Private-only without any remote: unknown, withheld.
|
||||||
@@ -744,7 +756,7 @@ owners = { github = "gh-org" }
|
|||||||
std::fs::create_dir_all(&bare).unwrap();
|
std::fs::create_dir_all(&bare).unwrap();
|
||||||
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
|
Git::new(&bare).run(&["init", "-q", "--bare"]).unwrap();
|
||||||
assert!(
|
assert!(
|
||||||
gate(&base.join("priv/none"), &mut v)
|
gate(&base.join("priv/none"), &v)
|
||||||
.unwrap_err()
|
.unwrap_err()
|
||||||
.contains("unknown")
|
.contains("unknown")
|
||||||
);
|
);
|
||||||
@@ -760,24 +772,24 @@ owners = { github = "gh-org" }
|
|||||||
let f = Fake::default()
|
let f = Fake::default()
|
||||||
.with("o/r", Ok(Seen::Private))
|
.with("o/r", Ok(Seen::Private))
|
||||||
.with("o/open", Ok(Seen::NotPrivate));
|
.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 ok = "https://git.example.com:3000/o/r.git";
|
||||||
let open = "https://github.com/o/open";
|
let open = "https://github.com/o/open";
|
||||||
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
|
// Group "priv": private fetch URL + public pushurl => withheld; both private => allowed.
|
||||||
let both = mk(&base, "priv", &[ok], &[ok, "https://github.com/o/r"]);
|
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();
|
std::fs::remove_dir_all(base.join("priv")).unwrap();
|
||||||
let leaky = mk(&base, "priv", &[ok, open], &[]);
|
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}");
|
assert!(e.contains("public"), "{e}");
|
||||||
// pushInsteadOf rewrites the push URL to a public repo.
|
// pushInsteadOf rewrites the push URL to a public repo.
|
||||||
let g = Git::new(leaky.join(".bare"));
|
let g = Git::new(leaky.join(".bare"));
|
||||||
g.run(&["remote", "set-url", "--delete", "origin", open])
|
g.run(&["remote", "set-url", "--delete", "origin", open])
|
||||||
.unwrap();
|
.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])
|
g.run(&["config", &format!("url.{open}.pushInsteadOf"), ok])
|
||||||
.unwrap();
|
.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();
|
std::fs::remove_dir_all(&base).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -789,8 +801,8 @@ owners = { github = "gh-org" }
|
|||||||
let _ = std::fs::remove_dir_all(&base);
|
let _ = std::fs::remove_dir_all(&base);
|
||||||
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
|
let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]);
|
||||||
let gate = |f: &Fake| {
|
let gate = |f: &Fake| {
|
||||||
let mut v = Visibility::default();
|
let v = Visibility::default();
|
||||||
snapshot_gate(&c, &repo, "origin", &mut v, 0, f)
|
snapshot_gate(&c, &repo, "origin", &v, 0, f)
|
||||||
};
|
};
|
||||||
let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
|
let base_f = || Fake::default().with("o/r", Ok(Seen::Private));
|
||||||
// No mirror (404): fine. Mirror owner comes from `owners`.
|
// 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");
|
assert!(seen, "cloned repo never managed");
|
||||||
d.shutdown();
|
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.
|
cannot starve snapshots.
|
||||||
- **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply
|
- **Periodic pass**: every `fetch_interval_s` all repos get a full pass (fetch, receive, apply
|
||||||
snapshots, materialize/archive). Also what catches missed events.
|
snapshots, materialize/archive). Also what catches missed events.
|
||||||
- **One worker thread**: passes never overlap. Events that arrive during a pass queue another pass;
|
- **Worker pool**: the loop thread only schedules; `sync.workers` threads (default 4, 1 to 32) run
|
||||||
it finds nothing to do and ends the chain.
|
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
|
- **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
|
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.
|
are still snapshotted locally (an offline pass); only the network is retried after the backoff.
|
||||||
|
|||||||
Reference in new issue
Block a user