From 1252765346b105f8c3a3d8404fb3fd1db24a97d9 Mon Sep 17 00:00:00 2001 From: tower <12181924+profiling@users.noreply.github.com> Date: Sun, 15 Nov 2026 23:39:31 +0800 Subject: [PATCH 1/3] feat(git): refresh recently used mirrors in the background Assisted-by: OpenAI:Codex Assisted-by: Claude:claude-sonnet-5-5 --- README.md | 7 +- chart/README.md | 3 + chart/templates/deployment.yaml | 9 + chart/values.yaml | 7 + docs/architecture.md | 58 +- docs/configuration.md | 15 + src/config.rs | 68 +- src/evict.rs | 176 +++- src/git.rs | 1322 ++++++++++++++++++++++++++++++- src/main.rs | 7 + tests/auth.rs | 1 + tests/e2e.rs | 12 + tests/http.rs | 3 + tests/lfs.rs | 1 + tests/refresh.rs | 123 +++ tests/retry.rs | 1 + tests/upstream_credential.rs | 1 + 17 files changed, 1792 insertions(+), 22 deletions(-) create mode 100644 tests/refresh.rs diff --git a/README.md b/README.md index 744bd28..e4464f9 100644 --- a/README.md +++ b/README.md @@ -124,10 +124,9 @@ Working and end-to-end tested on both Git wire protocol versions - **v2** clone, incremental fetch, and push rejection. **git-LFS** is cached too (batch API proxied; objects stored content-addressed and integrity-checked). -Not yet implemented: - -- A background/scheduled refresh (today every `info/refs` triggers an on-demand, - TTL-coalesced fetch). +Optional background refresh of recently used mirrors is available with +`--refresh-interval-seconds` (default `0`, disabled; minimum enabled value +`3600`). See [Configuration](docs/configuration.md#periodic-refresh). **Non-goal: a git-free image.** The `git` binary is a permanent runtime dependency: the proxy serves clients by running `git upload-pack`, and no diff --git a/chart/README.md b/chart/README.md index ef73c5d..0d58a67 100644 --- a/chart/README.md +++ b/chart/README.md @@ -114,6 +114,9 @@ pointing at the Service. | `clientAuth.signingKey.existingSecret` | `""` | Secret with the HMAC key signing LFS download grants; empty = a random key per pod | | `clientAuth.signingKey.key` | `signing-key` | Key in that Secret | | `config.upstreamTimeoutSeconds` | `3600` | Positive total seconds per upstream operation, including retries | +| `config.refreshIntervalSeconds` | `0` | Seconds between background refresh rounds for recently requested mirrors; `0` disables, otherwise at least `3600` | +| `config.refreshActiveWindowSeconds` | `604800` | Refresh only mirrors requested within this window (at least `1`) | +| `config.maxConcurrentRefreshes` | `4` | Max background fetches in flight (at least `1`) | | `config.fetchTtlSeconds` | `10` | Skip upstream fetch if refreshed within this window (`0` = always) | | `config.cacheMaxMb` | `0` | Cap on on-disk cache, MiB; evicts LRU idle mirrors (`0` = unlimited) | | `config.maxConcurrentRequests` | `64` | Max concurrent in-flight requests (`0` = unlimited) | diff --git a/chart/templates/deployment.yaml b/chart/templates/deployment.yaml index 1c9f87e..c2dc7e9 100644 --- a/chart/templates/deployment.yaml +++ b/chart/templates/deployment.yaml @@ -1,6 +1,9 @@ {{- if or (not (regexMatch "^[1-9][0-9]*$" (toString .Values.config.upstreamTimeoutSeconds))) (le (int64 .Values.config.upstreamTimeoutSeconds) 0) }} {{- fail "config.upstreamTimeoutSeconds must be a positive integer" }} {{- end }} +{{- if or (not (regexMatch "^[0-9]+$" (toString .Values.config.refreshIntervalSeconds))) (and (ne (int64 .Values.config.refreshIntervalSeconds) 0) (lt (int64 .Values.config.refreshIntervalSeconds) 3600)) }} +{{- fail "config.refreshIntervalSeconds must be 0 or an integer of at least 3600" }} +{{- end }} apiVersion: apps/v1 kind: Deployment metadata: @@ -68,6 +71,12 @@ spec: value: /var/cache/git-cache-proxy - name: GITCACHEPROXY_UPSTREAM_TIMEOUT_SECONDS value: {{ .Values.config.upstreamTimeoutSeconds | quote }} + - name: GITCACHEPROXY_REFRESH_INTERVAL_SECONDS + value: {{ .Values.config.refreshIntervalSeconds | quote }} + - name: GITCACHEPROXY_REFRESH_ACTIVE_WINDOW_SECONDS + value: {{ .Values.config.refreshActiveWindowSeconds | quote }} + - name: GITCACHEPROXY_MAX_CONCURRENT_REFRESHES + value: {{ .Values.config.maxConcurrentRefreshes | quote }} - name: GITCACHEPROXY_FETCH_TTL_SECONDS value: {{ .Values.config.fetchTtlSeconds | quote }} - name: GITCACHEPROXY_CACHE_MAX_MB diff --git a/chart/values.yaml b/chart/values.yaml index a9b896b..eca2f54 100644 --- a/chart/values.yaml +++ b/chart/values.yaml @@ -83,6 +83,13 @@ config: fetchTtlSeconds: 10 # Total upstream command budget, including retries (positive seconds). upstreamTimeoutSeconds: 3600 + # Background refresh of recently requested mirrors: seconds between rounds. + # 0 = disabled; otherwise at least 3600. + refreshIntervalSeconds: 0 + # Refresh only mirrors requested within this many seconds (at least 1). + refreshActiveWindowSeconds: 604800 + # Max background fetches in flight (at least 1). Used only when refresh is on. + maxConcurrentRefreshes: 4 # Cap on total on-disk mirror cache, in MiB; evicts least-recently-used idle # mirrors when exceeded. 0 = unlimited (no eviction). Set this whenever the # cache volume is bounded. diff --git a/docs/architecture.md b/docs/architecture.md index c1d5a84..c730d94 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,8 +13,9 @@ works internally, and a throughput benchmark. For usage see the replicating every repo, and it can lag the exact commit CI just pushed. This proxy is **lazy and pull-only**: it caches on first request, and on every -request runs an incremental `git fetch` before serving - so a client always gets -the ref it asked for, and nothing is ever pushed or replicated to the origin. +request checks freshness before serving, using a TTL-coalesced incremental +`git fetch`. Optional background refresh updates recently used existing mirrors; +it never discovers or clones repositories. Nothing is pushed to the origin. That pull-only property is what makes it viable against a sensitive origin. ## How it compares @@ -34,8 +35,9 @@ That pull-only property is what makes it viable against a sensitive origin. mirror can lag its refresh interval (`lag`); `--reference` is only as fresh as its local seed (`seed`). 4. Only new objects cross the WAN per request; the bulk history is served from the local mirror. -5. Never writes to or proactively replicates from the origin - it only ever pulls what a - client requested. +5. Never writes to the origin. With background refresh disabled (the default), + upstream pulls serve client requests only. Optional refresh pulls recently used + existing mirrors without discovering or cloning repositories. 6. Works against any unmodified Git smart-HTTP origin. GitLab Geo needs GitLab on both ends. ## How it works @@ -70,9 +72,10 @@ Retries stay inside the existing per-repository lock. Each failed clone's stagin directory is removed before another attempt; an existing fetch mirror is kept. Only success updates the freshness timestamp. After retries are exhausted the request still fails with 502; stale refs are not served as a fallback. The retry -budget limits attempts and adds at most seven seconds of backoff; it does not -impose a new transfer timeout on large repositories. LFS and local upload-pack -operations are outside this retry policy. +budget limits attempts and adds at most seven seconds of backoff. Each upstream +Git operation also has one `--upstream-timeout-seconds` budget (default `3600`) +across all attempts and backoff, including background refresh. LFS and local +upload-pack operations are outside this retry policy and operation budget. If a client `want`s a commit by SHA that the mirror never captured - typically a GitHub pull-request merge commit, which lives only under the unadvertised @@ -120,6 +123,47 @@ headers are sent terminate the response body. On Unix targets with remaining group members are stopped before the leader is reaped. Other targets wait for request completion and stdout EOF before observing exit. +### Background refresh + +Optional background refresh keeps recently used existing mirrors warm without +repository discovery or cold clones. See [Periodic refresh](./configuration.md#periodic-refresh) +for the flags and defaults. + +**Eligibility.** Usage is kept only in memory and reset on restart. A request +counts as use after successful cache preparation (`ensure_fresh` returning +`Ok`), including TTL hits, not after the full HTTP response or pack stream. +Failed, cancelled, and auth-rejected preparation leaves prior successful use +unchanged, and concurrent completions cannot move the timestamp backwards. +Refresh itself never records use, so periodic work cannot keep a mirror active +forever. When disabled, requests neither record usage nor lock refresh state. +Each round selects mirrors used within the active window, most recent first. + +**Scheduling.** Rounds start every interval, measured from the previous round's +start. At the round deadline no new repository starts and running fetches +finish; the next round waits until both that deadline and all previous fetches +have completed. A deadline skip is not a fetch failure. Refresh shares the +per-repository fetch lock and TTL with requests and eviction, so a request +arriving during refresh waits for that fetch. Shutdown instead cancels upstream +operations and reaps child processes; library users must await both request +owners and the refresh handle. + +**Eviction.** Background fetches do not promote the eviction LRU. A successful +fetch marks the tracked entry for deferred size measurement and capacity +enforcement by the existing evictor; a TTL hit does not. Entries already +selected for eviction are not recreated, and an eviction cancels a refresh +fetch running for that mirror instead of waiting for it. + +**Credentials and failures.** Refresh uses only the static upstream auth header, +or anonymous access when none is configured, so it never stores or reuses +client credentials. An upstream auth rejection blocks further refresh attempts +for that mirror until a fetch using the same server credential succeeds, or the +process restarts; a client credential success clears ordinary failure backoff +but preserves this mark. The first ordinary failure is eligible in the next +scheduled round. Repeated failures wait `interval * 2^(failures - 1)` after +failure completion, capped at 32 intervals. Any successful upstream fetch +clears ordinary failure and backoff state. Request serving ignores refresh +backoff. + ### git-LFS LFS objects use a different HTTP API from the git protocol, so they are cached diff --git a/docs/configuration.md b/docs/configuration.md index a10e5b5..ac1911c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -21,6 +21,9 @@ Every flag has an environment-variable equivalent. | `--auth-allow-http` | `GITCACHEPROXY_AUTH_ALLOW_HTTP` | `false` | Provider modes: accept a plain `http://` validation endpoint, which sends client credentials in cleartext | | `--upstream-timeout-seconds` | `GITCACHEPROXY_UPSTREAM_TIMEOUT_SECONDS` | `3600` | Total seconds per upstream clone, full-ref fetch or SHA backfill, including all attempts and retry delays (must be positive) | | `--fetch-ttl-seconds` | `GITCACHEPROXY_FETCH_TTL_SECONDS` | `10` | Skip upstream fetch if the last one started within this window (`0` = always fetch) | +| `--refresh-interval-seconds` | `GITCACHEPROXY_REFRESH_INTERVAL_SECONDS` | `0` | Background refresh round spacing; 0 disables it, otherwise at least 3600 | +| `--refresh-active-window-seconds` | `GITCACHEPROXY_REFRESH_ACTIVE_WINDOW_SECONDS` | `604800` | Only refresh mirrors requested within this window; at least 1 when enabled | +| `--max-concurrent-refreshes` | `GITCACHEPROXY_MAX_CONCURRENT_REFRESHES` | `4` | Maximum background fetches in flight; at least 1 when enabled | | `--max-concurrent-requests` | `GITCACHEPROXY_MAX_CONCURRENT_REQUESTS` | `64` | Max concurrent in-flight requests; excess queue (`0` = unlimited) | | `--max-concurrent-upload-packs` | `GITCACHEPROXY_MAX_CONCURRENT_UPLOAD_PACKS` | `0` | Max concurrent `git upload-pack` processes, held until each exits; bounds `pack-objects` memory. Clones waiting for a slot hold a `--max-concurrent-requests` slot (`0` = unlimited) | | `--max-decoded-body-mb` | `GITCACHEPROXY_MAX_DECODED_BODY_MB` | `512` | Cap on a decoded upload-pack request body, in MiB (bounds memory / gzip bombs) | @@ -36,6 +39,18 @@ Every flag has an environment-variable equivalent. Endpoints: `/healthz`, `/readyz`, `/metrics` (see [Metrics](./metrics.md)). +## Periodic refresh + +Refresh is disabled by default. Set `--refresh-interval-seconds` to at least +3600 to enable it: the first round starts after one interval and refreshes +mirrors requested within `--refresh-active-window-seconds`, at most +`--max-concurrent-refreshes` at a time. The window and concurrency settings +have no effect when disabled. The interval and its maximum backoff must fit in +a monotonic deadline. Refresh never clones a missing mirror, and request usage +is kept in memory only, so it resets on restart. See +[Background refresh](./architecture.md#background-refresh) for scheduling, +credential, and failure behavior. + ## Reusing a cache after changing upstream Mirrors are keyed by repo path under `--cache-root`, not by upstream URL. diff --git a/src/config.rs b/src/config.rs index 9df1a3f..5338f10 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,10 +3,15 @@ use std::fmt; use std::path::PathBuf; +use std::time::Duration; + +use tokio::time::Instant; use anyhow::{Result, bail}; use clap::{Parser, ValueEnum}; +use crate::git::RefreshConfig; + /// Log output format. #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] pub enum LogFormat { @@ -221,6 +226,30 @@ pub struct Config { #[arg(long, env = "GITCACHEPROXY_FETCH_TTL_SECONDS", default_value_t = 10)] pub fetch_ttl_seconds: u64, + /// Pause between refresh round starts; 0 disables background refresh. + #[arg( + long, + env = "GITCACHEPROXY_REFRESH_INTERVAL_SECONDS", + default_value_t = 0 + )] + pub refresh_interval_seconds: u64, + + /// Refresh only mirrors requested within this many seconds. + #[arg( + long, + env = "GITCACHEPROXY_REFRESH_ACTIVE_WINDOW_SECONDS", + default_value_t = 604800 + )] + pub refresh_active_window_seconds: u64, + + /// Maximum background fetches in flight when refresh is enabled. + #[arg( + long, + env = "GITCACHEPROXY_MAX_CONCURRENT_REFRESHES", + default_value_t = 4 + )] + pub max_concurrent_refreshes: usize, + /// Maximum number of requests handled concurrently, shared across all /// connections. Excess requests queue until a slot frees. This bounds the /// concurrent upstream clone/fetch work a burst can trigger (the slot is held @@ -310,11 +339,48 @@ pub struct Config { fn parse_upstream_timeout(value: &str) -> Result { let seconds = value.parse::().map_err(|e| e.to_string())?; - crate::git::validate_upstream_timeout(std::time::Duration::from_secs(seconds)) + crate::git::validate_upstream_timeout(Duration::from_secs(seconds)) .map_err(|e| e.to_string())?; Ok(seconds) } +impl Config { + /// Refresh settings, or `None` when `--refresh-interval-seconds` is 0. + pub fn refresh_config(&self) -> Option { + (self.refresh_interval_seconds != 0).then(|| RefreshConfig { + interval: Duration::from_secs(self.refresh_interval_seconds), + active_window: Duration::from_secs(self.refresh_active_window_seconds), + concurrency: self.max_concurrent_refreshes, + }) + } + + /// Validate refresh options before starting background work. + pub fn validate_refresh(&self) -> Result<()> { + if self.refresh_interval_seconds != 0 { + if self.refresh_interval_seconds < 3600 { + bail!("--refresh-interval-seconds must be 0 or at least 3600"); + } + let interval = Duration::from_secs(self.refresh_interval_seconds); + if interval + .checked_mul(32) + .and_then(|delay| Instant::now().checked_add(delay)) + .is_none() + { + bail!( + "--refresh-interval-seconds and its maximum backoff must fit in a monotonic deadline" + ); + } + if self.refresh_active_window_seconds == 0 { + bail!("--refresh-active-window-seconds must be at least 1 when refresh is enabled"); + } + if self.max_concurrent_refreshes == 0 { + bail!("--max-concurrent-refreshes must be at least 1"); + } + } + Ok(()) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/src/evict.rs b/src/evict.rs index 239de85..9ccec4f 100644 --- a/src/evict.rs +++ b/src/evict.rs @@ -5,7 +5,8 @@ //! mirror's size and access order in memory. The request path only ever does O(1) //! bookkeeping against it - never disk IO: //! - `touch` on every request (a served cache hit counts as use), -//! - `mark_changed` after a clone/fetch, flagging the mirror for (re)measurement. +//! - `mark_changed` after a request clone/fetch, promoting and remeasuring, +//! - `mark_dirty` after a background fetch, remeasuring without promotion. //! //! All disk work - measuring a changed mirror's size, and evicting mirrors - runs //! in the background [`run`] task, off the critical path, so a client's clone/fetch @@ -135,6 +136,19 @@ impl CacheIndex { self.work.notify_one(); } + /// Schedule deferred measurement without promoting or recreating an entry. + /// A refresh can finish after eviction has already removed its index entry. + pub fn mark_dirty(&self, name: &str) { + { + let mut inner = self.lock(); + if !inner.cache.contains(name) { + return; + } + inner.dirty.insert(name.to_string()); + } + self.work.notify_one(); + } + /// On-disk path of a tracked mirror. pub fn cache_dir(&self, name: &str) -> PathBuf { self.cache_root.join(name) @@ -461,6 +475,130 @@ mod tests { use crate::git::{GitCache, GitConfig}; + #[cfg(unix)] + #[tokio::test] + async fn refresh_growth_updates_totals_and_metrics_without_lru_promotion() { + let tmp = tempfile::tempdir().unwrap(); + let (cache, idx, repo) = refresh_growth_fixture( + tmp.path(), + u64::MAX, + "printf '%01024d' 0 > objects/pack.data\n", + ); + let handle = cache.start_refresh().unwrap(); + cache.ensure_fresh(&repo, false, b"", None).await.unwrap(); + idx.touch("b.git"); + let before = idx.totals().0; + cache + .refresh_repo( + &repo, + tokio::time::Instant::now() + Duration::from_secs(3600), + ) + .await; + tokio::time::timeout(Duration::from_secs(5), idx.work.notified()) + .await + .unwrap(); + assert_eq!(idx.lock().cache.peek_lru().unwrap().0, "a.git"); + maintain(&cache, &idx).await; + let actual = measure(&repo.cache_dir).0 + measure(&tmp.path().join("b.git")).0; + assert!(actual > before); + assert_eq!(idx.totals(), (actual, 2)); + assert!( + idx.metrics + .gather() + .contains(&format!("gitcacheproxy_cache_bytes {actual}\n")) + ); + assert_eq!(idx.lock().cache.peek_lru().unwrap().0, "a.git"); + cache.ensure_fresh(&repo, true, b"", None).await.unwrap(); + assert!( + idx.take_dirty().is_empty(), + "a TTL hit must not schedule measurement" + ); + cache.shutdown(); + handle.await.unwrap(); + } + + #[cfg(unix)] + #[tokio::test] + async fn refresh_only_growth_enforces_the_cap_and_evicts_the_same_lru() { + let tmp = tempfile::tempdir().unwrap(); + let (cache, idx, repo) = + refresh_growth_fixture(tmp.path(), 256, "printf '%01024d' 0 > objects/pack.data\n"); + let handle = cache.start_refresh().unwrap(); + cache.ensure_fresh(&repo, false, b"", None).await.unwrap(); + idx.touch("b.git"); + cache + .refresh_repo( + &repo, + tokio::time::Instant::now() + Duration::from_secs(3600), + ) + .await; + assert_eq!(idx.lock().cache.peek_lru().unwrap().0, "a.git"); + maintain(&cache, &idx).await; + assert!(!repo.cache_dir.exists()); + let remaining = measure(&tmp.path().join("b.git")).0; + assert_eq!(idx.totals(), (remaining, 1)); + let metrics = idx.metrics.gather(); + assert!(metrics.contains(&format!("gitcacheproxy_cache_bytes {remaining}\n"))); + assert!(metrics.contains("gitcacheproxy_evictions_total 1\n")); + assert!(remaining <= 256); + cache.shutdown(); + handle.await.unwrap(); + } + + #[cfg(unix)] + #[tokio::test] + async fn eviction_after_victim_selection_preempts_refresh_without_resurrecting_entry() { + use tokio::io::AsyncReadExt; + let tmp = tempfile::tempdir().unwrap(); + let (cache, idx, repo) = + refresh_growth_fixture(tmp.path(), 256, "printf x > started\nexec sleep 30\n"); + assert!( + std::process::Command::new("mkfifo") + .arg(repo.cache_dir.join("started")) + .status() + .unwrap() + .success() + ); + let handle = cache.start_refresh().unwrap(); + cache.ensure_fresh(&repo, false, b"", None).await.unwrap(); + idx.touch("b.git"); + let refresh = cache.refresh_repo( + &repo, + tokio::time::Instant::now() + Duration::from_secs(3600), + ); + tokio::pin!(refresh); + let select_victim = async { + tokio::fs::File::open(repo.cache_dir.join("started")) + .await + .unwrap() + .read_exact(&mut [0]) + .await + .unwrap(); + idx.set_size("a.git", 1024); + let victims = idx.take_victims(); + assert_eq!(victims[0].0, "a.git"); + // The eviction cancels the running refresh instead of waiting it out. + tokio::time::timeout( + Duration::from_secs(5), + cache.evict(&repo.name, &repo.cache_dir), + ) + .await + .unwrap() + .unwrap(); + }; + tokio::join!(refresh, select_victim); + assert!(!repo.cache_dir.exists()); + assert!(!idx.lock().cache.contains("a.git")); + assert!(idx.take_dirty().is_empty()); + let before = idx.totals(); + idx.set_size("a.git", 9999); + idx.mark_dirty("a.git"); + assert_eq!(idx.totals(), before); + assert!(idx.take_dirty().is_empty()); + cache.shutdown(); + handle.await.unwrap(); + } + #[test] fn size_accounting_tracks_the_total() { let tmp = tempfile::tempdir().unwrap(); @@ -720,6 +858,41 @@ mod tests { assert_eq!(idx.totals(), (0, 1)); } + #[cfg(unix)] + fn refresh_growth_fixture( + root: &Path, + cap: u64, + script: &str, + ) -> (GitCache, Arc, crate::repo::RepoRef) { + use std::os::unix::fs::PermissionsExt; + make_mirror(&root.join("a.git"), 10, None); + make_mirror(&root.join("b.git"), 10, None); + let binary = root.join("git-wrapper"); + // Avoid writable descriptors inherited by parallel tests' forked children. + assert!( + std::process::Command::new("sh") + .args(["-c", "printf '%s' \"$2\" > \"$1\"", "sh"]) + .arg(&binary) + .arg(format!("#!/bin/sh\n{script}")) + .status() + .unwrap() + .success() + ); + std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap(); + let metrics = Arc::new(Metrics::new()); + let idx = CacheIndex::new(root.to_path_buf(), cap, metrics.clone()); + let mut cfg = dummy_cfg(); + cfg.git_binary = binary.to_str().unwrap().into(); + cfg.refresh = Some(crate::git::RefreshConfig { + interval: Duration::from_secs(3600), + active_window: Duration::from_secs(604800), + concurrency: 1, + }); + let cache = GitCache::new(cfg, metrics, Some(idx.clone())); + let repo = crate::repo::resolve("a.git", "https://example.com", root).unwrap(); + (cache, idx, repo) + } + fn dummy_cfg() -> GitConfig { // Eviction never shells out to git, so the binary is irrelevant. GitConfig { @@ -731,6 +904,7 @@ mod tests { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, } } diff --git a/src/git.rs b/src/git.rs index 0a38d25..9ece74f 100644 --- a/src/git.rs +++ b/src/git.rs @@ -110,6 +110,20 @@ pub struct GitConfig { pub pack_threads: Option, /// git `pack.windowMemory` for upload-pack (`None` = git default). pub pack_window_memory: Option, + /// Background refresh of recently used mirrors (`None` = disabled). + pub refresh: Option, +} + +/// Settings for [`GitCache::start_refresh`]. Callers validate them with +/// `Config::validate_refresh` first. +#[derive(Clone, Copy)] +pub struct RefreshConfig { + /// Pause between round starts. + pub interval: Duration, + /// Only mirrors used within this window are refreshed. + pub active_window: Duration, + /// Maximum background fetches in flight. + pub concurrency: usize, } /// Per-repo serialization point. `fetch_lock` is a `Mutex`, not an `RwLock`, on @@ -120,6 +134,29 @@ pub struct GitConfig { /// would only add overhead and never grant a concurrent reader. struct RepoSlot { fetch_lock: Mutex>, + refresh: Mutex, + /// Bumped by `evict` before it waits for `fetch_lock`, so a background + /// refresh holding the lock can yield instead of fetching data that is + /// about to be deleted. + evict_requests: watch::Sender, +} + +#[derive(Default)] +struct RefreshState { + used: Option<(RepoRef, Instant)>, + failures: u32, + retry_after: Option, + auth_blocked: bool, +} + +impl RefreshState { + fn succeeded(&mut self, server_credential: bool) { + self.failures = 0; + self.retry_after = None; + if server_credential { + self.auth_blocked = false; + } + } } #[derive(Clone)] @@ -135,8 +172,7 @@ pub struct GitCache { /// short for reader/writer separation to pay off. slots: Arc>>>, /// Cache-size index for LRU eviction, or `None` when no cap is configured. - /// When present it is `touch`ed on every request and `record`ed after each - /// clone/fetch; when absent the eviction machinery is entirely inert. + /// Requests promote entries; background refresh only schedules remeasurement. index: Option>, /// `None` when `max_upload_packs` is `0` (unlimited). upload_packs: Option>, @@ -144,10 +180,18 @@ pub struct GitCache { impl GitCache { pub fn new( - cfg: GitConfig, + mut cfg: GitConfig, metrics: Arc, index: Option>, ) -> Self { + // Settings that cannot run a round count as disabled, so request use is + // never recorded for a refresh task that will not exist. + if let Some(refresh) = cfg.refresh + && (refresh.interval.is_zero() || refresh.concurrency == 0) + { + tracing::warn!("refresh interval and concurrency must be at least 1; refresh disabled"); + cfg.refresh = None; + } let upload_packs = (cfg.max_upload_packs > 0).then(|| Arc::new(Semaphore::new(cfg.max_upload_packs))); Self { @@ -176,7 +220,8 @@ impl GitCache { self.owners.close(); } - /// Wait for upstream owners to reap children and release repository locks. + /// Wait for request upstream owners to reap children and release repository locks. + /// Also await the handle returned by start_refresh to finish refresh cleanup. pub async fn wait_for_shutdown(&self) { self.owners.wait().await; } @@ -189,11 +234,174 @@ impl GitCache { .or_insert_with(|| { Arc::new(RepoSlot { fetch_lock: Mutex::new(None), + refresh: Mutex::new(RefreshState::default()), + evict_requests: watch::channel(0).0, }) }) .clone() } + async fn record_fetch_success(&self, repo: &RepoRef, cred: Option<&str>) { + if self.cfg.refresh.is_none() { + return; + } + self.slot(&repo.name) + .await + .refresh + .lock() + .await + .succeeded(cred.is_none() || cred == self.cfg.upstream_auth_header.as_deref()); + } + + async fn record_client_use(&self, repo: &RepoRef, finished: Instant) { + let slot = self.slot(&repo.name).await; + let mut state = slot.refresh.lock().await; + if !self.shutdown.is_cancelled() + && state + .used + .as_ref() + .is_none_or(|(_, previous)| *previous <= finished) + { + state.used = Some((repo.clone(), finished)); + } + } + + /// Start optional refresh work from `GitConfig::refresh`. Disabled refresh + /// creates no task. Callers should validate the settings with Config first. + pub fn start_refresh(&self) -> Option> { + let RefreshConfig { + interval, + concurrency, + .. + } = self.cfg.refresh?; + let cache = self.clone(); + Some(tokio::spawn(async move { + refresh_loop(interval, cache.shutdown.child_token(), |deadline| { + let cache = &cache; + async move { + let candidates = cache.refresh_candidates().await; + refresh_round( + candidates.into_iter().map(|(repo, _)| repo), + concurrency, + deadline, + cache.shutdown.child_token(), + |repo| { + let worker = cache.clone(); + async move { + worker.refresh_repo(&repo, deadline).await; + } + }, + ) + .await; + } + }) + .await; + })) + } + + async fn refresh_candidates(&self) -> Vec<(RepoRef, Instant)> { + let Some(RefreshConfig { active_window, .. }) = self.cfg.refresh else { + return Vec::new(); + }; + let mut candidates = Vec::new(); + for slot in self.slots.lock().await.values() { + let state = slot.refresh.lock().await; + if let Some((repo, used)) = &state.used + && used.elapsed() <= active_window + { + candidates.push((repo.clone(), *used)); + } + } + candidates.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.name.cmp(&b.0.name))); + candidates + } + + /// Refresh an existing mirror without recording client use or LRU access. + pub(crate) async fn refresh_repo(&self, repo: &RepoRef, deadline: Instant) { + let Some(RefreshConfig { + interval, + active_window, + .. + }) = self.cfg.refresh + else { + return; + }; + let slot = self.slot(&repo.name).await; + // Subscribe before taking the lock so an eviction queued behind us is seen. + let mut evict_requested = slot.evict_requests.subscribe(); + let mut last = tokio::select! { + biased; + _ = self.shutdown.cancelled() => return, + _ = tokio::time::sleep_until(deadline) => return, + guard = slot.fetch_lock.lock() => guard, + }; + { + let state = slot.refresh.lock().await; + if Instant::now() >= deadline + || self.shutdown.is_cancelled() + || state.auth_blocked + || state.retry_after.is_some_and(|t| t > Instant::now()) + || state + .used + .as_ref() + .is_none_or(|(_, used)| used.elapsed() > active_window) + || !repo.cache_dir.join("HEAD").exists() + || last.is_some_and(|t| { + !self.cfg.fetch_ttl.is_zero() && t.elapsed() < self.cfg.fetch_ttl + }) + { + return; + } + } + let started = Instant::now(); + let mut worker = self.clone(); + worker.shutdown = self.shutdown.child_token(); + let cancel = worker.shutdown.clone(); + let fetch = worker.fetch(repo, None); + tokio::pin!(fetch); + let mut preempted = false; + // Cancel rather than drop the fetch so its child is still killed and reaped. + let result = tokio::select! { + result = &mut fetch => result, + _ = evict_requested.changed() => { + preempted = true; + cancel.cancel(); + fetch.await + } + }; + if preempted { + return; + } + match result { + Ok(()) => { + *last = Some(started); + if let Some(index) = &self.index { + index.mark_dirty(&repo.name); + } + } + Err(error) => { + if self.shutdown.is_cancelled() { + return; + } + tracing::warn!(repo = %repo.name, error = %error, "background refresh failed"); + let mut state = slot.refresh.lock().await; + state.auth_blocked |= is_auth_failure(&error); + state.failures = state.failures.saturating_add(1); + let multiplier = 1u32 << state.failures.saturating_sub(1).min(5); + state.retry_after = if state.failures == 1 { + None + } else { + // Startup validation reserves space for the maximum backoff. + Some( + Instant::now() + .checked_add(interval.saturating_mul(multiplier)) + .expect("validated refresh interval fits maximum backoff"), + ) + }; + } + } + } + /// Flag a mirror as changed after a clone/fetch so the background evictor /// (re)measures it and rebalances the cache. O(1) bookkeeping only - the size /// walk and any eviction run off this request path. No-op when eviction is @@ -213,6 +421,7 @@ impl GitCache { /// its open file descriptors and drains cleanly (POSIX unlink semantics). pub async fn evict(&self, name: &str, cache_dir: &Path) -> Result<()> { let slot = self.slot(name).await; + slot.evict_requests.send_modify(|n| *n = n.wrapping_add(1)); let guard = slot.fetch_lock.lock().await; if !cache_dir.join("HEAD").exists() { return Ok(()); // already gone (raced a prior eviction or manual removal) @@ -237,6 +446,8 @@ impl GitCache { /// the same repo are serialized; the first does the work, the rest see it already /// fresh. `body` is the client's upload-pack request (empty for `info/refs`), /// scanned for want-by-SHA misses - see `ensure_wanted_oids`. + /// Refresh use is recorded after successful preparation, including TTL hits, + /// independently of later HTTP response or pack-stream success. pub async fn ensure_fresh( &self, repo: &RepoRef, @@ -244,20 +455,26 @@ impl GitCache { body: &[u8], cred: Option<&str>, ) -> Result { + let track_use = self.cfg.refresh.is_some(); let mut owner = self.clone(); owner.shutdown = self.shutdown.child_token(); let _cancel_on_drop = owner.shutdown.clone().drop_guard(); - let repo = repo.clone(); + let owner_repo = repo.clone(); let wants = parse_wants(body); let cred = cred.map(str::to_owned); - self.owners + let outcome = self + .owners .spawn(async move { owner - .ensure_fresh_owned(&repo, want_fetch, &wants, cred.as_deref()) + .ensure_fresh_owned(&owner_repo, want_fetch, &wants, cred.as_deref()) .await }) .await - .context("join upstream owner")? + .context("join upstream owner")??; + if track_use { + self.record_client_use(repo, Instant::now()).await; + } + Ok(outcome) } async fn ensure_fresh_owned( @@ -293,6 +510,7 @@ impl GitCache { } { self.fetch(repo, cred).await?; + self.mark_changed(repo); *last = Some(started); CacheOutcome::Fetched } else { @@ -480,6 +698,7 @@ impl GitCache { self.metrics .observe_upstream(UpstreamOp::Clone, &repo.name, elapsed); self.mark_changed(repo); + self.record_fetch_success(repo, cred).await; Ok(()) } @@ -518,7 +737,7 @@ impl GitCache { &repo.name, started.elapsed().as_secs_f64(), ); - self.mark_changed(repo); + self.record_fetch_success(repo, cred).await; Ok(()) } @@ -591,6 +810,7 @@ impl GitCache { started.elapsed().as_secs_f64(), ); self.mark_changed(repo); + self.record_fetch_success(repo, cred).await; // Best-effort: a failed prune is not worth failing the request over. if let Err(e) = self.prune_wants(repo).await { tracing::warn!(repo = %repo.name, error = %e, "pruning want-by-sha pins failed"); @@ -1332,9 +1552,1009 @@ fn parse_wants(body: &[u8]) -> HashSet { oids } +async fn refresh_loop(interval: Duration, shutdown: CancellationToken, round: F) +where + F: Fn(Instant) -> Fut, + Fut: std::future::Future, +{ + let Some(mut next) = Instant::now().checked_add(interval) else { + tracing::warn!("refresh interval exceeds the monotonic deadline range"); + return; + }; + loop { + tokio::select! { + biased; + _ = shutdown.cancelled() => break, + _ = tokio::time::sleep_until(next) => {} + } + let Some(deadline) = Instant::now().checked_add(interval) else { + tracing::warn!("refresh interval exceeds the monotonic deadline range"); + break; + }; + round(deadline).await; + next = deadline; + } +} + +async fn refresh_round( + candidates: impl IntoIterator, + concurrency: usize, + deadline: Instant, + shutdown: CancellationToken, + fetch: F, +) where + F: Fn(RepoRef) -> Fut, + Fut: std::future::Future + Send + 'static, +{ + let mut jobs = tokio::task::JoinSet::new(); + for repo in candidates { + if jobs.len() == concurrency + && let Some(Err(error)) = jobs.join_next().await + { + tracing::warn!(%error, "background refresh job failed"); + } + if Instant::now() >= deadline || shutdown.is_cancelled() { + break; + } + jobs.spawn(fetch(repo)); + } + while let Some(result) = jobs.join_next().await { + if let Err(error) = result { + tracing::warn!(%error, "background refresh job failed"); + } + } +} + #[cfg(test)] mod tests { use super::*; + use std::sync::Mutex as StdMutex; + + #[tokio::test(start_paused = true)] + async fn refresh_usage_tracks_success_and_ttl_hits_only() { + let root = tempfile::tempdir().unwrap(); + let repo = refresh_test_mirror(root.path(), "repo.git"); + let mut cfg = test_config(); + cfg.git_binary = "true".into(); + let mut cache = GitCache::new(cfg, Arc::new(Metrics::new()), None); + enable_refresh(&mut cache, 3600, 604800, 1); + let handle = cache.start_refresh().unwrap(); + let slot = cache.slot(&repo.name).await; + cache + .clone() + .ensure_fresh(&repo, false, b"", None) + .await + .unwrap(); + let first = slot.refresh.lock().await.used.as_ref().unwrap().1; + *slot.fetch_lock.lock().await = Some(Instant::now()); + tokio::time::advance(Duration::from_secs(2)).await; + assert!(matches!( + cache.ensure_fresh(&repo, true, b"", None).await.unwrap(), + CacheOutcome::Cached + )); + let latest = slot.refresh.lock().await.used.as_ref().unwrap().1; + assert!(latest > first); + cache + .refresh_repo_with( + &repo, + Duration::from_secs(3600), + Duration::from_secs(604800), + Instant::now() + Duration::from_secs(3600), + ) + .await; + assert_eq!(slot.refresh.lock().await.used.as_ref().unwrap().1, latest); + cache.shutdown(); + handle.await.unwrap(); + } + + #[tokio::test(start_paused = true)] + async fn refresh_failed_preparation_does_not_add_or_replace_usage() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = refresh_spawn_failure_fixture(root.path()).await; + let slot = cache.slot(&repo.name).await; + let previous = slot.refresh.lock().await.used.as_ref().unwrap().1; + tokio::time::advance(Duration::from_secs(2)).await; + assert!(cache.ensure_fresh(&repo, true, b"", None).await.is_err()); + assert_eq!(slot.refresh.lock().await.used.as_ref().unwrap().1, previous); + let unseen = refresh_test_mirror(root.path(), "unseen.git"); + assert!(cache.ensure_fresh(&unseen, true, b"", None).await.is_err()); + assert!( + cache + .slot(&unseen.name) + .await + .refresh + .lock() + .await + .used + .is_none() + ); + } + + #[cfg(unix)] + #[tokio::test] + async fn refresh_auth_failed_preparation_preserves_successful_usage() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = refresh_fixture( + root.path(), + "echo 'fatal: Authentication failed' >&2\nexit 1\n", + ) + .await; + let slot = cache.slot(&repo.name).await; + let previous = slot.refresh.lock().await.used.as_ref().unwrap().1; + let error = cache + .ensure_fresh(&repo, true, b"", None) + .await + .unwrap_err(); + assert!(is_auth_failure(&error)); + assert_eq!(slot.refresh.lock().await.used.as_ref().unwrap().1, previous); + let unseen = refresh_test_mirror(root.path(), "unseen.git"); + assert!(is_auth_failure( + &cache + .ensure_fresh(&unseen, true, b"", None) + .await + .unwrap_err() + )); + assert!( + cache + .slot(&unseen.name) + .await + .refresh + .lock() + .await + .used + .is_none() + ); + } + + #[tokio::test(start_paused = true)] + async fn refresh_cancelled_preparation_preserves_usage() { + for previously_used in [false, true] { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = refresh_spawn_failure_fixture(root.path()).await; + let slot = cache.slot(&repo.name).await; + if !previously_used { + slot.refresh.lock().await.used = None; + } + let previous = slot + .refresh + .lock() + .await + .used + .as_ref() + .map(|(_, used)| *used); + let guard = slot.fetch_lock.lock().await; + let worker = cache.clone(); + let mirror = repo.clone(); + let request = + tokio::spawn(async move { worker.ensure_fresh(&mirror, false, b"", None).await }); + tokio::time::sleep(Duration::from_millis(1)).await; + request.abort(); + assert!(request.await.unwrap_err().is_cancelled()); + cache.shutdown(); + drop(guard); + cache.wait_for_shutdown().await; + assert_eq!( + slot.refresh + .lock() + .await + .used + .as_ref() + .map(|(_, used)| *used), + previous + ); + } + } + + #[tokio::test(start_paused = true)] + async fn refresh_usage_cannot_move_backwards() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = refresh_spawn_failure_fixture(root.path()).await; + let older = Instant::now(); + tokio::time::advance(Duration::from_secs(2)).await; + let newer = Instant::now(); + tokio::join!( + cache.record_client_use(&repo, newer), + cache.record_client_use(&repo, older) + ); + assert_eq!( + cache + .slot(&repo.name) + .await + .refresh + .lock() + .await + .used + .as_ref() + .unwrap() + .1, + newer + ); + } + + #[tokio::test(start_paused = true)] + async fn refresh_loop_rejects_an_overflowing_deadline_without_panicking() { + let round = |_| async { panic!("test refresh round") }; + let valid_round = tokio::spawn(async move { + refresh_loop(Duration::from_secs(1), CancellationToken::new(), round).await; + }); + assert!(valid_round.await.unwrap_err().is_panic()); + let now = Instant::now(); + let (mut valid, mut invalid) = (0, u64::MAX); + while invalid - valid > 1 { + let seconds = valid + (invalid - valid) / 2; + if now.checked_add(Duration::from_secs(seconds)).is_some() { + valid = seconds; + } else { + invalid = seconds; + } + } + let interval = Duration::from_secs(invalid); + assert!(now.checked_add(Duration::from_secs(valid)).is_some()); + assert!(now.checked_add(interval).is_none()); + refresh_loop(interval, CancellationToken::new(), round).await; + let interval = Duration::from_secs(1); + let token = CancellationToken::new(); + let refresh = refresh_loop(interval, token.clone(), round); + tokio::pin!(refresh); + std::future::poll_fn(|cx| { + assert!(refresh.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + tokio::time::advance(Duration::from_secs(valid)).await; + assert!(Instant::now().checked_add(interval).is_none()); + refresh.await; + } + + #[tokio::test(start_paused = true)] + async fn start_refresh_attempts_request_recorded_repos_in_recency_order() { + let root = tempfile::tempdir().unwrap(); + let (mut cache, repo) = refresh_spawn_failure_fixture(root.path()).await; + let stale = refresh_test_mirror(root.path(), "stale.git"); + cache.ensure_fresh(&stale, false, b"", None).await.unwrap(); + let cold = refresh_test_mirror(root.path(), "cold.git"); + tokio::time::advance(Duration::from_secs(200)).await; + cache.ensure_fresh(&repo, false, b"", None).await.unwrap(); + tokio::time::advance(Duration::from_secs(1)).await; + let newest_z = refresh_test_mirror(root.path(), "z.git"); + let newest_a = refresh_test_mirror(root.path(), "a.git"); + for mirror in [&newest_z, &newest_a] { + cache.ensure_fresh(mirror, false, b"", None).await.unwrap(); + } + let output = RefreshLog::default(); + let writer = output.clone(); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_writer(move || writer.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + enable_refresh(&mut cache, 10, 100, 1); + let handle = cache.start_refresh().unwrap(); + tokio::time::sleep(Duration::from_millis(10001)).await; + cache.shutdown(); + handle.await.unwrap(); + let log = String::from_utf8(output.0.lock().unwrap().clone()).unwrap(); + let attempts: Vec<_> = log + .lines() + .filter(|line| line.contains("background refresh failed")) + .collect(); + assert_eq!(attempts.len(), 3, "{log}"); + for (line, name) in attempts.iter().zip(["a.git", "z.git", "repo.git"]) { + assert!(line.contains(&format!("repo={name} ")), "{line}"); + assert_eq!(cache.slot(name).await.refresh.lock().await.failures, 1); + } + assert_eq!( + cache.slot(&stale.name).await.refresh.lock().await.failures, + 0 + ); + assert!(!cache.slots.lock().await.contains_key(&cold.name)); + } + + #[tokio::test(start_paused = true)] + async fn refresh_job_panics_are_logged_and_other_jobs_finish() { + let root = tempfile::tempdir().unwrap(); + let output = RefreshLog::default(); + let writer = output.clone(); + let subscriber = tracing_subscriber::fmt() + .without_time() + .with_ansi(false) + .with_writer(move || writer.clone()) + .finish(); + let _guard = tracing::subscriber::set_default(subscriber); + for names in [["a.git", "b.git"], ["b.git", "a.git"]] { + let candidates = names.map(|name| refresh_test_mirror(root.path(), name)); + let completed = Arc::new(Mutex::new(Vec::new())); + refresh_round( + candidates, + 1, + Instant::now() + Duration::from_secs(10), + CancellationToken::new(), + |repo| { + let completed = completed.clone(); + async move { + if repo.name == "a.git" { + panic!("test refresh panic"); + } + completed.lock().await.push(repo.name); + } + }, + ) + .await; + assert_eq!(*completed.lock().await, ["b.git"]); + } + std::io::Write::flush(&mut output.clone()).unwrap(); + let log = String::from_utf8(output.0.lock().unwrap().clone()).unwrap(); + assert!(log.contains("WARN")); + assert_eq!(log.matches("background refresh job failed").count(), 2); + } + + #[tokio::test] + async fn refresh_without_config_has_no_candidates_and_skips_the_fetch() { + let cache = GitCache::new(test_config(), Arc::new(Metrics::new()), None); + let root = tempfile::tempdir().unwrap(); + let repo = crate::repo::resolve("repo.git", "https://example.com", root.path()).unwrap(); + cache.slot(&repo.name).await.refresh.lock().await.used = + Some((repo.clone(), Instant::now())); + assert!(cache.refresh_candidates().await.is_empty()); + cache + .refresh_repo(&repo, Instant::now() + Duration::from_secs(10)) + .await; + assert!(!repo.cache_dir.exists()); + } + + #[tokio::test(start_paused = true)] + async fn refresh_candidates_use_client_recency_and_window_boundary() { + let mut cache = GitCache::new(test_config(), Arc::new(Metrics::new()), None); + enable_refresh(&mut cache, 3600, 20, 1); + let root = tempfile::tempdir().unwrap(); + for name in ["old.git", "recent.git", "newest.git"] { + let repo = crate::repo::resolve(name, "https://example.com", root.path()).unwrap(); + cache.slot(name).await.refresh.lock().await.used = Some((repo, Instant::now())); + tokio::time::advance(Duration::from_secs(10)).await; + } + let candidates = cache.refresh_candidates().await; + assert_eq!( + candidates + .iter() + .map(|(repo, _)| repo.name.as_str()) + .collect::>(), + ["newest.git", "recent.git"] + ); + tokio::time::advance(Duration::from_secs(1)).await; + assert_eq!(cache.refresh_candidates().await.len(), 1); + } + + #[cfg(unix)] + #[tokio::test] + async fn refresh_want_fetch_success_clears_backoff_with_credential_rules() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = refresh_fixture(root.path(), + "if [ \"$1\" = cat-file ]; then while read -r oid; do printf '%s missing\\n' \"$oid\"; done; fi\n").await; + let slot = cache.slot(&repo.name).await; + for cred in [Some("Authorization: client"), None] { + { + let mut state = slot.refresh.lock().await; + state.failures = 3; + state.retry_after = Some(Instant::now() + Duration::from_secs(100)); + state.auth_blocked = true; + } + let body = pkt_line(&format!("want {}\n", "a".repeat(40))); + cache.ensure_fresh(&repo, false, &body, cred).await.unwrap(); + let state = slot.refresh.lock().await; + assert_eq!(state.failures, 0); + assert!(state.retry_after.is_none()); + assert_eq!(state.auth_blocked, cred.is_some()); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn refresh_shutdown_reaps_running_fetch_and_releases_lock() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = + refresh_fixture(root.path(), "printf x > started\nexec sleep 30\n").await; + assert!( + std::process::Command::new("mkfifo") + .arg(repo.cache_dir.join("started")) + .status() + .unwrap() + .success() + ); + let worker = cache.clone(); + let mirror = repo.clone(); + let job = tokio::spawn(async move { + worker + .refresh_repo_with( + &mirror, + Duration::from_secs(10), + Duration::from_secs(100), + Instant::now() + Duration::from_secs(30), + ) + .await; + }); + tokio::fs::File::open(repo.cache_dir.join("started")) + .await + .unwrap() + .read_exact(&mut [0]) + .await + .unwrap(); + cache.shutdown(); + tokio::time::timeout(Duration::from_secs(5), job) + .await + .unwrap() + .unwrap(); + let slot = cache.slot(&repo.name).await; + assert!(slot.fetch_lock.try_lock().is_ok()); + assert_eq!(slot.refresh.lock().await.failures, 0); + } + + #[cfg(unix)] + #[tokio::test] + async fn eviction_preempts_a_running_refresh_fetch() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = + refresh_fixture(root.path(), "printf x > started\nexec sleep 30\n").await; + assert!( + std::process::Command::new("mkfifo") + .arg(repo.cache_dir.join("started")) + .status() + .unwrap() + .success() + ); + let worker = cache.clone(); + let mirror = repo.clone(); + let job = tokio::spawn(async move { + worker + .refresh_repo_with( + &mirror, + Duration::from_secs(10), + Duration::from_secs(100), + Instant::now() + Duration::from_secs(30), + ) + .await; + }); + tokio::fs::File::open(repo.cache_dir.join("started")) + .await + .unwrap() + .read_exact(&mut [0]) + .await + .unwrap(); + tokio::time::timeout( + Duration::from_secs(5), + cache.evict(&repo.name, &repo.cache_dir), + ) + .await + .unwrap() + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), job) + .await + .unwrap() + .unwrap(); + assert!(!repo.cache_dir.join("HEAD").exists()); + let slot = cache.slot(&repo.name).await; + let state = slot.refresh.lock().await; + assert_eq!(state.failures, 0); + assert!(!state.auth_blocked); + } + + #[cfg(unix)] + #[tokio::test] + async fn refresh_uses_static_auth_and_client_waits_for_refresh() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = refresh_fixture(root.path(), + "printf '%s' \"$GIT_CONFIG_VALUE_2\" > auth\nprintf '%s\\n' \"$@\" > args\nprintf x >> fetches\nprintf x > started\ncat release >/dev/null\n").await; + for name in ["started", "release"] { + assert!( + std::process::Command::new("mkfifo") + .arg(repo.cache_dir.join(name)) + .status() + .unwrap() + .success() + ); + } + let worker = cache.clone(); + let mirror = repo.clone(); + let job = tokio::spawn(async move { + worker + .refresh_repo_with( + &mirror, + Duration::from_secs(10), + Duration::from_secs(100), + Instant::now() + Duration::from_secs(30), + ) + .await; + }); + let mut signal = tokio::fs::File::open(repo.cache_dir.join("started")) + .await + .unwrap(); + signal.read_exact(&mut [0]).await.unwrap(); + assert!(cache.slot(&repo.name).await.fetch_lock.try_lock().is_err()); + let request = cache.ensure_fresh(&repo, true, b"", Some("Authorization: client")); + tokio::pin!(request); + std::future::poll_fn(|cx| { + assert!(request.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + tokio::time::pause(); + tokio::time::sleep(Duration::from_millis(1)).await; + std::future::poll_fn(|cx| { + assert!(request.as_mut().poll(cx).is_pending()); + Poll::Ready(()) + }) + .await; + tokio::time::resume(); + assert_eq!( + tokio::fs::read(repo.cache_dir.join("fetches")) + .await + .unwrap(), + b"x" + ); + assert_eq!( + tokio::fs::read_to_string(repo.cache_dir.join("auth")) + .await + .unwrap(), + "Authorization: server" + ); + let args = tokio::fs::read_to_string(repo.cache_dir.join("args")) + .await + .unwrap(); + assert!(args.lines().any(|arg| arg == repo.upstream_url)); + assert!(!args.lines().any(|arg| arg == "origin")); + tokio::fs::write(repo.cache_dir.join("release"), b"done") + .await + .unwrap(); + job.await.unwrap(); + assert!(matches!(request.await.unwrap(), CacheOutcome::Cached)); + assert_eq!( + tokio::fs::read(repo.cache_dir.join("fetches")) + .await + .unwrap(), + b"x" + ); + } + + #[cfg(unix)] + #[tokio::test] + async fn refresh_failure_backoff_auth_rejection_and_request_recovery() { + let root = tempfile::tempdir().unwrap(); + let (mut cache, repo) = refresh_fixture(root.path(), "exit 1\n").await; + let interval = Duration::from_secs(10); + let slot = cache.slot(&repo.name).await; + for failures in 1..=8 { + slot.refresh.lock().await.retry_after = None; + let before = Instant::now(); + cache + .refresh_repo_with(&repo, interval, Duration::from_secs(100), before + interval) + .await; + let state = slot.refresh.lock().await; + assert_eq!(state.failures, failures); + let delay = interval * (1 << (failures - 1).min(5)); + if failures == 1 { + assert!(state.retry_after.is_none()); + } else { + let retry_after = state.retry_after.unwrap(); + assert!(retry_after >= before + delay); + if failures >= 6 { + assert!(retry_after <= Instant::now() + interval * 32); + } + } + assert!(!state.auth_blocked); + } + cache.cfg.git_binary = "true".into(); + cache + .ensure_fresh(&repo, true, b"", Some("Authorization: client")) + .await + .unwrap(); + assert_eq!(slot.refresh.lock().await.failures, 0); + cache.cfg.git_binary = root.path().join("git-wrapper").to_str().unwrap().into(); + write_test_script( + Path::new(&cache.cfg.git_binary), + "#!/bin/sh\necho 'fatal: Authentication failed' >&2\nexit 1\n", + ); + *slot.fetch_lock.lock().await = None; + cache + .refresh_repo_with( + &repo, + interval, + Duration::from_secs(100), + Instant::now() + interval, + ) + .await; + assert!(slot.refresh.lock().await.auth_blocked); + assert_eq!(slot.refresh.lock().await.failures, 1); + cache + .refresh_repo_with( + &repo, + interval, + Duration::from_secs(100), + Instant::now() + interval, + ) + .await; + assert_eq!(slot.refresh.lock().await.failures, 1); + cache.cfg.git_binary = "true".into(); + cache + .ensure_fresh(&repo, true, b"", Some("Authorization: client")) + .await + .unwrap(); + assert!(slot.refresh.lock().await.auth_blocked); + *slot.fetch_lock.lock().await = None; + cache.ensure_fresh(&repo, true, b"", None).await.unwrap(); + assert!(!slot.refresh.lock().await.auth_blocked); + } + + #[tokio::test(start_paused = true)] + async fn refresh_backoff_stops_at_thirty_two_intervals() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = refresh_spawn_failure_fixture(root.path()).await; + let slot = cache.slot(&repo.name).await; + let interval = Duration::from_secs(10); + for failures in 1..=8 { + slot.refresh.lock().await.retry_after = None; + cache + .refresh_repo_with( + &repo, + interval, + Duration::from_secs(100), + Instant::now() + interval, + ) + .await; + let state = slot.refresh.lock().await; + assert_eq!(state.failures, failures); + let expected = if failures == 1 { + None + } else { + Some(Instant::now() + interval * (1 << (failures - 1).min(5))) + }; + assert_eq!(state.retry_after, expected); + } + } + + #[tokio::test(start_paused = true)] + async fn refresh_first_failure_retries_in_the_next_round() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = refresh_spawn_failure_fixture(root.path()).await; + let interval = Duration::from_secs(10); + let token = CancellationToken::new(); + let slot = cache.slot(&repo.name).await; + let started = Instant::now(); + tokio::time::timeout( + Duration::from_secs(30), + refresh_loop(interval, token.clone(), |deadline| { + let (cache, repo, slot, token) = (&cache, &repo, &slot, &token); + async move { + tokio::time::sleep(Duration::from_secs(3)).await; + cache + .refresh_repo_with(repo, interval, Duration::from_secs(100), deadline) + .await; + if slot.refresh.lock().await.failures == 2 { + token.cancel(); + } + } + }), + ) + .await + .expect("first failure must retry in round two"); + assert_eq!(started.elapsed(), Duration::from_secs(23)); + assert_eq!(slot.refresh.lock().await.failures, 2); + } + + #[tokio::test(start_paused = true)] + async fn refresh_second_failure_waits_two_intervals() { + let root = tempfile::tempdir().unwrap(); + let (cache, repo) = refresh_spawn_failure_fixture(root.path()).await; + let interval = Duration::from_secs(10); + let slot = cache.slot(&repo.name).await; + for _ in 0..2 { + cache + .refresh_repo_with( + &repo, + interval, + Duration::from_secs(100), + Instant::now() + interval, + ) + .await; + } + let retry_after = slot.refresh.lock().await.retry_after.unwrap(); + assert_eq!(retry_after, Instant::now() + interval * 2); + tokio::time::advance(interval).await; + cache + .refresh_repo_with( + &repo, + interval, + Duration::from_secs(100), + Instant::now() + interval, + ) + .await; + assert_eq!(slot.refresh.lock().await.failures, 2); + tokio::time::advance(interval).await; + cache + .refresh_repo_with( + &repo, + interval, + Duration::from_secs(100), + Instant::now() + interval, + ) + .await; + assert_eq!(slot.refresh.lock().await.failures, 3); + } + + #[tokio::test(start_paused = true)] + async fn refresh_schedule_spaces_short_rounds_and_waits_for_overruns() { + for length in [3, 15] { + let token = CancellationToken::new(); + let starts = Mutex::new(Vec::new()); + let start = Instant::now(); + refresh_loop(Duration::from_secs(10), token.clone(), |_| async { + starts.lock().await.push(Instant::now()); + tokio::time::sleep(Duration::from_secs(length)).await; + if starts.lock().await.len() == 3 { + token.cancel(); + } + }) + .await; + let starts = starts.lock().await; + assert_eq!(starts[0] - start, Duration::from_secs(10)); + assert_eq!(starts[1] - starts[0], Duration::from_secs(length.max(10))); + assert_eq!(starts[2] - starts[1], Duration::from_secs(length.max(10))); + } + } + + #[tokio::test] + async fn refresh_disabled_creates_no_task_or_request_state_access() { + let root = tempfile::tempdir().unwrap(); + let repo = refresh_test_mirror(root.path(), "repo.git"); + let mut cfg = test_config(); + cfg.git_binary = "true".into(); + let cache = GitCache::new(cfg, Arc::new(Metrics::new()), None); + let slot = cache.slot(&repo.name).await; + let guard = slot.refresh.lock().await; + assert!(cache.start_refresh().is_none()); + tokio::time::timeout( + Duration::from_secs(1), + cache.ensure_fresh(&repo, true, b"", None), + ) + .await + .unwrap() + .unwrap(); + assert!(guard.used.is_none()); + assert_eq!(guard.failures, 0); + assert!(cache.owners.is_empty()); + } + + #[tokio::test] + async fn refresh_unusable_settings_count_as_disabled() { + for (interval, concurrency) in [(3600, 0), (0, 1)] { + let mut cfg = test_config(); + cfg.refresh = Some(RefreshConfig { + interval: Duration::from_secs(interval), + active_window: Duration::from_secs(1), + concurrency, + }); + let cache = GitCache::new(cfg, Arc::new(Metrics::new()), None); + assert!(cache.cfg.refresh.is_none()); + assert!(cache.start_refresh().is_none()); + } + } + + #[tokio::test(start_paused = true)] + async fn refresh_round_deadline_drains_running_jobs_without_starting_waiters() { + let root = tempfile::tempdir().unwrap(); + let candidates = ["new.git", "middle.git", "old.git"] + .map(|name| crate::repo::resolve(name, "https://example.com", root.path()).unwrap()); + let events = Arc::new(Mutex::new(Vec::new())); + let start = Instant::now(); + let token = CancellationToken::new(); + refresh_round( + candidates, + 2, + start + Duration::from_secs(10), + token.clone(), + |repo| { + let events = events.clone(); + async move { + events.lock().await.push((repo.name.clone(), false)); + tokio::time::sleep(Duration::from_secs(15)).await; + events.lock().await.push((repo.name, true)); + } + }, + ) + .await; + assert_eq!(start.elapsed(), Duration::from_secs(15)); + let events = events.lock().await; + assert_eq!( + &events[..2], + &[("new.git".into(), false), ("middle.git".into(), false)] + ); + let mut completed = events[2..].to_vec(); + completed.sort(); + assert_eq!( + completed, + [("middle.git".into(), true), ("new.git".into(), true)] + ); + } + + #[tokio::test(start_paused = true)] + async fn refresh_round_short_jobs_start_in_order_with_bounded_concurrency() { + let root = tempfile::tempdir().unwrap(); + let candidates = ["a.git", "b.git", "c.git"] + .map(|name| crate::repo::resolve(name, "https://example.com", root.path()).unwrap()); + let events = Arc::new(Mutex::new(Vec::new())); + let start = Instant::now(); + refresh_round( + candidates, + 1, + start + Duration::from_secs(10), + CancellationToken::new(), + |repo| { + let events = events.clone(); + async move { + events.lock().await.push((repo.name, Instant::now())); + tokio::time::sleep(Duration::from_secs(1)).await; + } + }, + ) + .await; + assert_eq!(start.elapsed(), Duration::from_secs(3)); + let events = events.lock().await; + for (i, (name, when)) in events.iter().enumerate() { + assert_eq!(name, &["a.git", "b.git", "c.git"][i]); + assert_eq!(*when - start, Duration::from_secs(i as u64)); + } + } + + #[tokio::test(start_paused = true)] + async fn refresh_lock_deadline_and_shutdown_leave_failure_state_unchanged() { + let cache = GitCache::new(test_config(), Arc::new(Metrics::new()), None); + let root = tempfile::tempdir().unwrap(); + let repo = crate::repo::resolve("repo.git", "https://example.com", root.path()).unwrap(); + let slot = cache.slot(&repo.name).await; + slot.refresh.lock().await.failures = 3; + let guard = slot.fetch_lock.lock().await; + let start = Instant::now(); + cache + .refresh_repo_with( + &repo, + Duration::from_secs(10), + Duration::from_secs(100), + start + Duration::from_secs(10), + ) + .await; + assert_eq!(start.elapsed(), Duration::from_secs(10)); + assert_eq!(slot.refresh.lock().await.failures, 3); + cache.shutdown(); + cache + .refresh_repo_with( + &repo, + Duration::from_secs(10), + Duration::from_secs(100), + Instant::now() + Duration::from_secs(10), + ) + .await; + assert_eq!(slot.refresh.lock().await.failures, 3); + drop(guard); + assert!(slot.fetch_lock.try_lock().is_ok()); + } + + #[tokio::test] + async fn refresh_success_shares_ttl_and_preserves_client_usage() { + let root = tempfile::tempdir().unwrap(); + let repo = crate::repo::resolve("repo.git", "https://example.com", root.path()).unwrap(); + std::fs::create_dir_all(&repo.cache_dir).unwrap(); + std::fs::write(repo.cache_dir.join("HEAD"), "ref: refs/heads/main").unwrap(); + let mut cfg = test_config(); + cfg.git_binary = "true".into(); + cfg.fetch_ttl = Duration::from_secs(60); + let mut cache = GitCache::new(cfg, Arc::new(Metrics::new()), None); + enable_refresh(&mut cache, 3600, 604800, 1); + let slot = cache.slot(&repo.name).await; + let used = Instant::now(); + slot.refresh.lock().await.used = Some((repo.clone(), used)); + slot.refresh.lock().await.failures = 3; + cache + .refresh_repo_with( + &repo, + Duration::from_secs(10), + Duration::from_secs(100), + Instant::now() + Duration::from_secs(10), + ) + .await; + assert!(slot.fetch_lock.lock().await.is_some()); + assert_eq!(slot.refresh.lock().await.used.as_ref().unwrap().1, used); + assert_eq!(slot.refresh.lock().await.failures, 0); + assert!(matches!( + cache.ensure_fresh(&repo, true, b"", None).await.unwrap(), + CacheOutcome::Cached + )); + } + + #[tokio::test(start_paused = true)] + async fn refresh_skips_inactive_missing_auth_blocked_and_backoff_repos() { + let cache = GitCache::new(test_config(), Arc::new(Metrics::new()), None); + let root = tempfile::tempdir().unwrap(); + let repo = crate::repo::resolve("repo.git", "https://example.com", root.path()).unwrap(); + let slot = cache.slot(&repo.name).await; + let used = Instant::now(); + slot.refresh.lock().await.used = Some((repo.clone(), used)); + tokio::time::advance(Duration::from_secs(11)).await; + cache + .refresh_repo_with( + &repo, + Duration::from_secs(10), + Duration::from_secs(10), + Instant::now() + Duration::from_secs(10), + ) + .await; + assert!(!repo.cache_dir.exists()); + assert_eq!(slot.refresh.lock().await.failures, 0); + slot.refresh.lock().await.used = Some((repo.clone(), Instant::now())); + cache + .refresh_repo_with( + &repo, + Duration::from_secs(10), + Duration::from_secs(10), + Instant::now() + Duration::from_secs(10), + ) + .await; + assert!(!repo.cache_dir.exists()); + std::fs::create_dir_all(&repo.cache_dir).unwrap(); + std::fs::write(repo.cache_dir.join("HEAD"), "ref: refs/heads/main").unwrap(); + slot.refresh.lock().await.auth_blocked = true; + cache + .refresh_repo_with( + &repo, + Duration::from_secs(10), + Duration::from_secs(10), + Instant::now() + Duration::from_secs(10), + ) + .await; + assert_eq!(slot.refresh.lock().await.failures, 0); + slot.refresh.lock().await.auth_blocked = false; + slot.refresh.lock().await.retry_after = Some(Instant::now() + Duration::from_secs(20)); + cache + .refresh_repo_with( + &repo, + Duration::from_secs(10), + Duration::from_secs(10), + Instant::now() + Duration::from_secs(10), + ) + .await; + assert_eq!(slot.refresh.lock().await.failures, 0); + } + + #[tokio::test] + async fn refresh_auth_mark_requires_server_credential_success() { + let mut cfg = test_config(); + cfg.upstream_auth_header = Some("Authorization: server".into()); + let mut cache = GitCache::new(cfg, Arc::new(Metrics::new()), None); + enable_refresh(&mut cache, 3600, 604800, 1); + let root = tempfile::tempdir().unwrap(); + let repo = crate::repo::resolve("repo.git", "https://example.com", root.path()).unwrap(); + let slot = cache.slot(&repo.name).await; + { + let mut state = slot.refresh.lock().await; + state.auth_blocked = true; + state.failures = 4; + state.retry_after = Some(Instant::now() + Duration::from_secs(100)); + } + cache + .record_fetch_success(&repo, Some("Authorization: client")) + .await; + { + let state = slot.refresh.lock().await; + assert!(state.auth_blocked); + assert_eq!(state.failures, 0); + assert!(state.retry_after.is_none()); + } + cache.record_fetch_success(&repo, None).await; + assert!(!slot.refresh.lock().await.auth_blocked); + slot.refresh.lock().await.auth_blocked = true; + cache + .record_fetch_success(&repo, Some("Authorization: server")) + .await; + assert!(!slot.refresh.lock().await.auth_blocked); + } #[tokio::test] async fn missing_oids_drains_more_than_a_pipe_buffer() { @@ -1355,6 +2575,7 @@ mod tests { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }, Arc::new(Metrics::new()), None, @@ -3007,6 +4228,7 @@ mod tests { max_upload_packs: 1, pack_threads: None, pack_window_memory: None, + refresh: None, } } @@ -3044,9 +4266,91 @@ mod tests { max_upload_packs: 1, pack_threads: None, pack_window_memory: None, + refresh: None, }, Arc::new(Metrics::new()), None, ) } + + impl GitCache { + /// `refresh_repo` with explicit settings, so a test can vary them per call. + /// The clone shares slots, metrics and the shutdown token with `self`; only + /// its private copy of the settings differs. + async fn refresh_repo_with( + &self, + repo: &RepoRef, + interval: Duration, + active_window: Duration, + deadline: Instant, + ) { + let mut cache = self.clone(); + cache.cfg.refresh = Some(RefreshConfig { + interval, + active_window, + concurrency: 1, + }); + cache.refresh_repo(repo, deadline).await; + } + } + + fn enable_refresh(cache: &mut GitCache, interval: u64, active_window: u64, concurrency: usize) { + cache.cfg.refresh = Some(RefreshConfig { + interval: Duration::from_secs(interval), + active_window: Duration::from_secs(active_window), + concurrency, + }); + } + + #[derive(Clone, Default)] + struct RefreshLog(Arc>>); + + impl std::io::Write for RefreshLog { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + fn refresh_test_mirror(root: &Path, name: &str) -> RepoRef { + let repo = crate::repo::resolve(name, "https://example.com", root).unwrap(); + std::fs::create_dir_all(&repo.cache_dir).unwrap(); + std::fs::write(repo.cache_dir.join("HEAD"), "ref: refs/heads/main").unwrap(); + repo + } + + async fn refresh_spawn_failure_fixture(root: &Path) -> (GitCache, RepoRef) { + let mut cfg = test_config(); + cfg.git_binary = root.join("missing-git").to_str().unwrap().into(); + let mut cache = GitCache::new(cfg, Arc::new(Metrics::new()), None); + let repo = crate::repo::resolve("repo.git", "https://example.com", root).unwrap(); + std::fs::create_dir_all(&repo.cache_dir).unwrap(); + std::fs::write(repo.cache_dir.join("HEAD"), "ref: refs/heads/main").unwrap(); + enable_refresh(&mut cache, 3600, 604800, 1); + cache.ensure_fresh(&repo, false, b"", None).await.unwrap(); + (cache, repo) + } + + #[cfg(unix)] + async fn refresh_fixture(root: &Path, script: &str) -> (GitCache, RepoRef) { + use std::os::unix::fs::PermissionsExt; + let binary = root.join("git-wrapper"); + write_test_script(&binary, &format!("#!/bin/sh\n{script}")); + std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755)).unwrap(); + let mut cfg = test_config(); + cfg.git_binary = binary.to_str().unwrap().into(); + cfg.upstream_auth_header = Some("Authorization: server".into()); + cfg.fetch_ttl = Duration::from_secs(60); + let mut cache = GitCache::new(cfg, Arc::new(Metrics::new()), None); + let repo = crate::repo::resolve("repo.git", "https://example.com", root).unwrap(); + std::fs::create_dir_all(&repo.cache_dir).unwrap(); + std::fs::write(repo.cache_dir.join("HEAD"), "ref: refs/heads/main").unwrap(); + enable_refresh(&mut cache, 3600, 604800, 1); + cache.ensure_fresh(&repo, false, b"", None).await.unwrap(); + (cache, repo) + } } diff --git a/src/main.rs b/src/main.rs index a762ff3..227a9ed 100644 --- a/src/main.rs +++ b/src/main.rs @@ -22,6 +22,7 @@ use git_cache_proxy::{auth, evict, git, lfs, metrics, repo, server}; #[tokio::main(flavor = "multi_thread")] async fn main() -> Result<()> { let cfg = Config::parse(); + cfg.validate_refresh()?; // Hold the non-blocking writer's guard for the whole process; its drop flushes // any buffered log lines on exit. let _log_guard = init_tracing(&cfg.log, cfg.log_format); @@ -69,6 +70,7 @@ async fn main() -> Result<()> { max_upload_packs: cfg.max_concurrent_upload_packs, pack_threads: cfg.pack_threads, pack_window_memory: cfg.pack_window_memory.clone(), + refresh: cfg.refresh_config(), }; let metrics = Arc::new(metrics::Metrics::new()); @@ -164,6 +166,8 @@ async fn main() -> Result<()> { cfg.cache_root.display(), ); + let refresher = cache.start_refresh(); + let shutdown_cache = cache.clone(); axum::serve(listener, server::router(state)) .with_graceful_shutdown(async move { @@ -174,6 +178,9 @@ async fn main() -> Result<()> { .context("http server")?; cache.wait_for_shutdown().await; + if let Some(handle) = refresher { + handle.await.context("join refresh task")?; + } // The server has drained; stop the evictor and wait for it to finish any // in-progress eviction before exiting. diff --git a/tests/auth.rs b/tests/auth.rs index 9efa51b..c63cc99 100644 --- a/tests/auth.rs +++ b/tests/auth.rs @@ -349,6 +349,7 @@ fn state(auth: Arc) -> AppState { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let lfs = Arc::new(Lfs::new( LfsConfig { diff --git a/tests/e2e.rs b/tests/e2e.rs index 695cd04..3984dd4 100644 --- a/tests/e2e.rs +++ b/tests/e2e.rs @@ -69,6 +69,7 @@ async fn reused_mirror_fetches_configured_upstream_for_refs_and_missing_sha() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }, metrics.clone(), None, @@ -167,6 +168,7 @@ async fn upload_pack_decodes_gzip_encoded_request() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let state = AppState { cache: Arc::new(GitCache::new(cfg, metrics.clone(), None)), @@ -296,6 +298,7 @@ async fn serves_want_by_sha_for_unadvertised_pull_ref() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let state = AppState { cache: Arc::new(GitCache::new(cfg, metrics.clone(), None)), @@ -433,6 +436,7 @@ async fn want_by_sha_fetch_failure_is_recorded_and_degrades_gracefully() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let state = AppState { cache: Arc::new(GitCache::new(cfg, metrics.clone(), None)), @@ -566,6 +570,7 @@ async fn want_by_sha_pins_are_capped_per_mirror() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let state = AppState { cache: Arc::new(GitCache::new(cfg, metrics.clone(), None)), @@ -711,6 +716,7 @@ async fn caps_want_by_sha_fetch_within_a_single_request() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let gitcache = GitCache::new(cfg, metrics, None); let upstream_base = format!("file://{}", up.path().display()); @@ -806,6 +812,7 @@ async fn want_by_sha_pins_are_unlimited_when_max_wants_is_zero() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let gitcache = GitCache::new(cfg, metrics, None); let upstream_base = format!("file://{}", up.path().display()); @@ -888,6 +895,7 @@ async fn want_by_sha_tolerates_object_check_failure() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let gitcache = GitCache::new(cfg, metrics, None); let upstream_base = format!("file://{}", up.path().display()); @@ -952,6 +960,7 @@ async fn clones_through_proxy_serves_all_refs_and_rejects_push() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; // Eviction enabled with an effectively unbounded cap: no mirror is ever // evicted, but the on-request index bookkeeping (touch on serve, mark-changed @@ -1533,6 +1542,7 @@ async fn upload_pack_cap_holds_a_slot_until_the_process_exits() { max_upload_packs: 1, pack_threads: None, pack_window_memory: None, + refresh: None, }, Arc::new(Metrics::new()), None, @@ -1604,6 +1614,7 @@ async fn upload_pack_runs_with_pack_options() { max_upload_packs: 0, pack_threads: Some(2), pack_window_memory: Some("64m".into()), + refresh: None, }, Arc::new(Metrics::new()), None, @@ -1727,6 +1738,7 @@ async fn start_proxy_with_auth( max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let state = AppState { cache: Arc::new(GitCache::new(cfg, metrics.clone(), None)), diff --git a/tests/http.rs b/tests/http.rs index 783da58..eceab51 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -193,6 +193,7 @@ async fn upstream_failure_returns_bad_gateway_and_records_error() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let lfs = Arc::new(Lfs::new( LfsConfig { @@ -252,6 +253,7 @@ async fn upload_pack_upstream_failure_returns_bad_gateway() { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let lfs = Arc::new(Lfs::new( LfsConfig { @@ -354,6 +356,7 @@ fn state(auth: Arc) -> AppState { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let lfs = Arc::new(Lfs::new( LfsConfig { diff --git a/tests/lfs.rs b/tests/lfs.rs index a03ec48..b097760 100644 --- a/tests/lfs.rs +++ b/tests/lfs.rs @@ -422,6 +422,7 @@ fn proxy_state(addr: SocketAddr, cache: &std::path::Path, metrics: Arc) max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; AppState { cache: Arc::new(GitCache::new(cfg, metrics.clone(), Some(idx.clone()))), diff --git a/tests/refresh.rs b/tests/refresh.rs new file mode 100644 index 0000000..6786d08 --- /dev/null +++ b/tests/refresh.rs @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: Apache-2.0 +//! Public refresh configuration and startup behavior. + +use std::sync::Arc; +use std::time::Duration; + +use clap::Parser; +use git_cache_proxy::config::Config; +use git_cache_proxy::git::{GitCache, GitConfig}; +use git_cache_proxy::metrics::Metrics; + +#[tokio::test(start_paused = true)] +async fn refresh_default_disabled_does_not_start_a_task() { + let cfg = Config::try_parse_from(["proxy", "--upstream", "https://example.com"]).unwrap(); + assert_eq!(cfg.refresh_interval_seconds, 0); + assert_eq!(cfg.refresh_active_window_seconds, 604800); + assert_eq!(cfg.max_concurrent_refreshes, 4); + cfg.validate_refresh().unwrap(); + let cache = GitCache::new( + GitConfig { + git_binary: "missing-git-must-not-run".into(), + upstream_auth_header: None, + big_file_threshold: "8m".into(), + fetch_ttl: Duration::from_secs(10), + max_wants: 100, + max_upload_packs: 0, + pack_threads: None, + pack_window_memory: None, + refresh: cfg.refresh_config(), + }, + Arc::new(Metrics::new()), + None, + ); + assert!(cache.start_refresh().is_none()); + tokio::time::advance(Duration::from_secs(604800)).await; + cache.shutdown(); + cache.wait_for_shutdown().await; +} + +#[test] +fn refresh_config_maps_the_enabled_options() { + let cfg = Config::try_parse_from([ + "proxy", + "--upstream=https://example.com", + "--refresh-interval-seconds=7200", + "--refresh-active-window-seconds=86400", + "--max-concurrent-refreshes=2", + ]) + .unwrap(); + let refresh = cfg.refresh_config().unwrap(); + assert_eq!(refresh.interval, Duration::from_secs(7200)); + assert_eq!(refresh.active_window, Duration::from_secs(86400)); + assert_eq!(refresh.concurrency, 2); +} + +#[test] +fn refresh_validation_ignores_inactive_options_when_disabled() { + let mut cfg = Config::try_parse_from([ + "proxy", + "--upstream", + "https://example.com", + "--max-concurrent-refreshes", + "0", + ]) + .unwrap(); + assert!(cfg.validate_refresh().is_ok()); + cfg.refresh_interval_seconds = 3599; + assert!(cfg.validate_refresh().is_err()); + cfg.refresh_interval_seconds = 3600; + assert!(cfg.validate_refresh().is_err()); + cfg.max_concurrent_refreshes = 1; + assert!(cfg.validate_refresh().is_ok()); +} + +#[test] +fn refresh_validation_rejects_overflow_and_zero_active_window() { + let mut cfg = Config::try_parse_from(["proxy", "--upstream", "https://example.com"]).unwrap(); + cfg.refresh_interval_seconds = u64::MAX; + assert!( + cfg.validate_refresh() + .unwrap_err() + .to_string() + .contains("monotonic deadline") + ); + cfg.refresh_interval_seconds = 3600; + cfg.refresh_active_window_seconds = 0; + assert!( + cfg.validate_refresh() + .unwrap_err() + .to_string() + .contains("--refresh-active-window-seconds") + ); + cfg.refresh_interval_seconds = 0; + assert!(cfg.validate_refresh().is_ok()); +} + +#[test] +fn refresh_invalid_settings_fail_before_creating_cache() { + for (interval, concurrency, diagnostic) in [ + ("3599", "4", "--refresh-interval-seconds"), + ("18446744073709551615", "4", "monotonic deadline"), + ("3600", "0", "--max-concurrent-refreshes"), + ] { + let root = tempfile::tempdir().unwrap(); + let cache = root.path().join("not-created"); + let output = std::process::Command::new(env!("CARGO_BIN_EXE_git-cache-proxy")) + .args([ + "--upstream", + "https://example.com", + "--refresh-interval-seconds", + interval, + "--max-concurrent-refreshes", + concurrency, + "--cache-root", + ]) + .arg(&cache) + .output() + .unwrap(); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains(diagnostic)); + assert!(!cache.exists()); + } +} diff --git a/tests/retry.rs b/tests/retry.rs index b04d57b..23c14c5 100644 --- a/tests/retry.rs +++ b/tests/retry.rs @@ -306,6 +306,7 @@ exec git "$@" max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }, Arc::new(Metrics::new()), None, diff --git a/tests/upstream_credential.rs b/tests/upstream_credential.rs index efeb0ce..5fb3793 100644 --- a/tests/upstream_credential.rs +++ b/tests/upstream_credential.rs @@ -273,6 +273,7 @@ async fn client_state(base: &str) -> AppState { max_upload_packs: 0, pack_threads: None, pack_window_memory: None, + refresh: None, }; let auth = Arc::new(Auth::build(helpers::github_auth_config(base, 0), metrics.clone()).unwrap()); From 4ba540ff684f3760cc14a6c6a43420f55477f288 Mon Sep 17 00:00:00 2001 From: tower <12181924+profiling@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:56:52 +0800 Subject: [PATCH 2/3] feat(metrics): count background refresh results Add refresh_total{result} (ok, error, auth_rejected, preempted, skipped) so the refresh success and failure rates are visible apart from client-triggered fetches. Shutdown is not counted. An eviction that cancels a refresh fetch no longer counts as an upstream fetch error. Assisted-by: Claude:claude-sonnet-5-5 --- docs/metrics.md | 6 ++ src/git.rs | 149 ++++++++++++++++++++++++++++++++++++++++++------ src/metrics.rs | 49 ++++++++++++++++ 3 files changed, 186 insertions(+), 18 deletions(-) diff --git a/docs/metrics.md b/docs/metrics.md index 5007cb2..3c6d35a 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -14,6 +14,7 @@ | `evictions_total` | counter | - | Idle mirrors evicted to keep the cache under `--cache-max-mb` | | `lfs_objects_total` | counter | `result` | Cached git-LFS object lookups | | `cache_outcome_total` | counter | `outcome` | info/refs operations by outcome: served locally vs. fetched from upstream | +| `refresh_total` | counter | `result` | Background refresh attempts per mirror, by result | | `auth_validations_total` | counter | `result` | Per-request token validation calls | | `auth_cache_hits_total` | counter | - | Token checks answered from the `--auth-ttl-seconds` verdict cache | | `upstream_duration_seconds` | histogram | `op`, `repo` | Wall-clock duration of successful upstream clones/fetches | @@ -32,6 +33,11 @@ Label values: On `auth_validations_total`: `allow`, `deny`, `unavailable` (the endpoint failed, throttled, or answered something else), `saturated` (no call made: no `--auth-max-concurrent` slot freed up in time). + On `refresh_total`: `ok`, `error`, `auth_rejected` (the upstream rejected the + server credential), `preempted` (an eviction cancelled the fetch), `skipped` + (not attempted: backoff, auth block, fetch TTL, inactive or missing mirror, + or the round deadline). Shutdown is not counted. Refresh fetches also appear + in `upstream_ops_total{op="fetch"}`. - `op`: `clone` (first mirror of a repo), `fetch` (refresh of an existing mirror), `want_fetch` (on-demand fetch of a bare SHA the mirror lacks, e.g. a PR merge commit). diff --git a/src/git.rs b/src/git.rs index 9ece74f..9654048 100644 --- a/src/git.rs +++ b/src/git.rs @@ -39,7 +39,7 @@ use tokio_util::io::ReaderStream; use tokio_util::sync::CancellationToken; use tokio_util::task::TaskTracker; -use crate::metrics::{Metrics, ServeKind, Status, UpstreamOp}; +use crate::metrics::{Metrics, RefreshResult, ServeKind, Status, UpstreamOp}; use crate::repo::RepoRef; /// Reserved ref namespace for objects fetched by bare SHA on a want-miss. @@ -280,7 +280,8 @@ impl GitCache { let cache = &cache; async move { let candidates = cache.refresh_candidates().await; - refresh_round( + let total = candidates.len(); + let started = refresh_round( candidates.into_iter().map(|(repo, _)| repo), concurrency, deadline, @@ -293,6 +294,13 @@ impl GitCache { }, ) .await; + // Candidates the round never reached would otherwise be invisible. + let unstarted = total - started; + if unstarted > 0 && !cache.shutdown.is_cancelled() { + cache + .metrics + .record_refresh(RefreshResult::Skipped, unstarted as u64); + } } }) .await; @@ -332,13 +340,15 @@ impl GitCache { let mut last = tokio::select! { biased; _ = self.shutdown.cancelled() => return, - _ = tokio::time::sleep_until(deadline) => return, + _ = tokio::time::sleep_until(deadline) => { + self.metrics.record_refresh(RefreshResult::Skipped, 1); + return; + } guard = slot.fetch_lock.lock() => guard, }; - { + let skip = { let state = slot.refresh.lock().await; - if Instant::now() >= deadline - || self.shutdown.is_cancelled() + Instant::now() >= deadline || state.auth_blocked || state.retry_after.is_some_and(|t| t > Instant::now()) || state @@ -349,31 +359,37 @@ impl GitCache { || last.is_some_and(|t| { !self.cfg.fetch_ttl.is_zero() && t.elapsed() < self.cfg.fetch_ttl }) - { - return; - } + }; + if self.shutdown.is_cancelled() { + return; + } + if skip { + self.metrics.record_refresh(RefreshResult::Skipped, 1); + return; } let started = Instant::now(); let mut worker = self.clone(); worker.shutdown = self.shutdown.child_token(); let cancel = worker.shutdown.clone(); - let fetch = worker.fetch(repo, None); + let preempt = CancellationToken::new(); + let fetch = worker.fetch_inner(repo, None, Some(&preempt)); tokio::pin!(fetch); - let mut preempted = false; // Cancel rather than drop the fetch so its child is still killed and reaped. let result = tokio::select! { result = &mut fetch => result, _ = evict_requested.changed() => { - preempted = true; + preempt.cancel(); cancel.cancel(); fetch.await } }; - if preempted { + if preempt.is_cancelled() { + self.metrics.record_refresh(RefreshResult::Preempted, 1); return; } match result { Ok(()) => { + self.metrics.record_refresh(RefreshResult::Ok, 1); *last = Some(started); if let Some(index) = &self.index { index.mark_dirty(&repo.name); @@ -384,8 +400,17 @@ impl GitCache { return; } tracing::warn!(repo = %repo.name, error = %error, "background refresh failed"); + let auth_rejected = is_auth_failure(&error); + self.metrics.record_refresh( + if auth_rejected { + RefreshResult::AuthRejected + } else { + RefreshResult::Error + }, + 1, + ); let mut state = slot.refresh.lock().await; - state.auth_blocked |= is_auth_failure(&error); + state.auth_blocked |= auth_rejected; state.failures = state.failures.saturating_add(1); let multiplier = 1u32 << state.failures.saturating_sub(1).min(5); state.retry_after = if state.failures == 1 { @@ -703,6 +728,17 @@ impl GitCache { } async fn fetch(&self, repo: &RepoRef, cred: Option<&str>) -> Result<()> { + self.fetch_inner(repo, cred, None).await + } + + /// `preempt` is cancelled when an eviction, not a failure, stops the fetch; that + /// cancellation must not inflate the upstream error count. + async fn fetch_inner( + &self, + repo: &RepoRef, + cred: Option<&str>, + preempt: Option<&CancellationToken>, + ) -> Result<()> { tracing::debug!(repo = %repo.name, "fetching updates from upstream"); // A reused mirror can still record an older upstream in origin. let started = Instant::now(); @@ -726,8 +762,10 @@ impl GitCache { ) .await { - self.metrics - .record_upstream(UpstreamOp::Fetch, Status::Error, "-"); + if !preempt.is_some_and(CancellationToken::is_cancelled) { + self.metrics + .record_upstream(UpstreamOp::Fetch, Status::Error, "-"); + } return Err(error); } self.metrics @@ -1582,10 +1620,12 @@ async fn refresh_round( deadline: Instant, shutdown: CancellationToken, fetch: F, -) where +) -> usize +where F: Fn(RepoRef) -> Fut, Fut: std::future::Future + Send + 'static, { + let mut started = 0; let mut jobs = tokio::task::JoinSet::new(); for repo in candidates { if jobs.len() == concurrency @@ -1597,12 +1637,14 @@ async fn refresh_round( break; } jobs.spawn(fetch(repo)); + started += 1; } while let Some(result) = jobs.join_next().await { if let Err(error) = result { tracing::warn!(%error, "background refresh job failed"); } } + started } #[cfg(test)] @@ -1900,6 +1942,7 @@ mod tests { cache .refresh_repo(&repo, Instant::now() + Duration::from_secs(10)) .await; + assert_eq!(refresh_count(&cache, "ok"), 0); assert!(!repo.cache_dir.exists()); } @@ -2036,6 +2079,14 @@ mod tests { let state = slot.refresh.lock().await; assert_eq!(state.failures, 0); assert!(!state.auth_blocked); + assert_eq!(refresh_count(&cache, "preempted"), 1); + assert!( + !cache + .metrics + .gather() + .contains(r#"upstream_ops_total{op="fetch",repo="-",result="error"}"#), + "an eviction must not count as an upstream error" + ); } #[cfg(unix)] @@ -2142,6 +2193,13 @@ mod tests { } assert!(!state.auth_blocked); } + assert_eq!(refresh_count(&cache, "error"), 8); + assert!( + cache + .metrics + .gather() + .contains(r#"upstream_ops_total{op="fetch",repo="-",result="error"} 8"#) + ); cache.cfg.git_binary = "true".into(); cache .ensure_fresh(&repo, true, b"", Some("Authorization: client")) @@ -2164,6 +2222,7 @@ mod tests { .await; assert!(slot.refresh.lock().await.auth_blocked); assert_eq!(slot.refresh.lock().await.failures, 1); + assert_eq!(refresh_count(&cache, "auth_rejected"), 1); cache .refresh_repo_with( &repo, @@ -2173,6 +2232,8 @@ mod tests { ) .await; assert_eq!(slot.refresh.lock().await.failures, 1); + assert_eq!(refresh_count(&cache, "skipped"), 1); + assert_eq!(refresh_count(&cache, "error"), 8); cache.cfg.git_binary = "true".into(); cache .ensure_fresh(&repo, true, b"", Some("Authorization: client")) @@ -2323,6 +2384,34 @@ mod tests { assert!(cache.owners.is_empty()); } + #[tokio::test(start_paused = true)] + async fn refresh_counts_candidates_the_round_deadline_never_started() { + let mut cache = GitCache::new(test_config(), Arc::new(Metrics::new()), None); + let root = tempfile::tempdir().unwrap(); + let older = crate::repo::resolve("older.git", "https://example.com", root.path()).unwrap(); + let newer = crate::repo::resolve("newer.git", "https://example.com", root.path()).unwrap(); + let older_slot = cache.slot(&older.name).await; + older_slot.refresh.lock().await.used = Some((older.clone(), Instant::now())); + tokio::time::advance(Duration::from_secs(1)).await; + let newer_slot = cache.slot(&newer.name).await; + newer_slot.refresh.lock().await.used = Some((newer.clone(), Instant::now())); + // The most recent candidate runs first and waits on its lock until the + // deadline; with one slot the other is never started. + let _held = newer_slot.fetch_lock.lock().await; + enable_refresh(&mut cache, 10, 1000, 1); + let handle = cache.start_refresh().unwrap(); + // Covers the first round only: the next one ends after this sleep. + tokio::time::sleep(Duration::from_secs(25)).await; + assert_eq!(refresh_count(&cache, "skipped"), 2); + cache.shutdown(); + handle.await.unwrap(); + assert_eq!( + refresh_count(&cache, "skipped"), + 2, + "shutdown is not counted" + ); + } + #[tokio::test] async fn refresh_unusable_settings_count_as_disabled() { for (interval, concurrency) in [(3600, 0), (0, 1)] { @@ -2346,7 +2435,7 @@ mod tests { let events = Arc::new(Mutex::new(Vec::new())); let start = Instant::now(); let token = CancellationToken::new(); - refresh_round( + let started = refresh_round( candidates, 2, start + Duration::from_secs(10), @@ -2361,6 +2450,7 @@ mod tests { }, ) .await; + assert_eq!(started, 2); assert_eq!(start.elapsed(), Duration::from_secs(15)); let events = events.lock().await; assert_eq!( @@ -2423,6 +2513,7 @@ mod tests { .await; assert_eq!(start.elapsed(), Duration::from_secs(10)); assert_eq!(slot.refresh.lock().await.failures, 3); + assert_eq!(refresh_count(&cache, "skipped"), 1); cache.shutdown(); cache .refresh_repo_with( @@ -2433,6 +2524,11 @@ mod tests { ) .await; assert_eq!(slot.refresh.lock().await.failures, 3); + assert_eq!( + refresh_count(&cache, "skipped"), + 1, + "shutdown is not counted" + ); drop(guard); assert!(slot.fetch_lock.try_lock().is_ok()); } @@ -2463,6 +2559,7 @@ mod tests { assert!(slot.fetch_lock.lock().await.is_some()); assert_eq!(slot.refresh.lock().await.used.as_ref().unwrap().1, used); assert_eq!(slot.refresh.lock().await.failures, 0); + assert_eq!(refresh_count(&cache, "ok"), 1); assert!(matches!( cache.ensure_fresh(&repo, true, b"", None).await.unwrap(), CacheOutcome::Cached @@ -2521,6 +2618,11 @@ mod tests { ) .await; assert_eq!(slot.refresh.lock().await.failures, 0); + assert_eq!(refresh_count(&cache, "skipped"), 4); + assert_eq!( + refresh_count(&cache, "ok") + refresh_count(&cache, "error"), + 0 + ); } #[tokio::test] @@ -4302,6 +4404,17 @@ mod tests { }); } + /// Value of `refresh_total{result}`; 0 when the series was never recorded. + fn refresh_count(cache: &GitCache, result: &str) -> u64 { + let prefix = format!(r#"gitcacheproxy_refresh_total{{result="{result}"}} "#); + cache + .metrics + .gather() + .lines() + .find_map(|line| line.strip_prefix(&prefix)) + .map_or(0, |value| value.parse().unwrap()) + } + #[derive(Clone, Default)] struct RefreshLog(Arc>>); diff --git a/src/metrics.rs b/src/metrics.rs index fbbdfd4..6bdcdc5 100644 --- a/src/metrics.rs +++ b/src/metrics.rs @@ -69,6 +69,20 @@ pub enum LfsResult { Error, } +/// The `result` label on `refresh_total`. +#[derive(Debug, Clone, Copy)] +pub enum RefreshResult { + Ok, + Error, + /// The upstream rejected the server credential; the mirror is blocked. + AuthRejected, + /// An eviction cancelled the fetch. + Preempted, + /// Not attempted: backoff, auth block, TTL, inactive, missing mirror, or the + /// round deadline. + Skipped, +} + /// The `result` label on `auth_validations_total`. #[derive(Debug, Clone, Copy)] pub enum ValidationResult { @@ -179,6 +193,13 @@ pub struct Metrics { /// from the local mirror, no upstream call). Recorded once per advertisement, /// so the local-hit ratio is `cached / sum without (outcome) (...)`. cache_outcome: IntCounterVec, + /// `refresh_total{result}` - background refresh attempts per mirror; + /// result = ok | error | auth_rejected | preempted (evicted mid-fetch) | + /// skipped (not attempted). Mutually exclusive, so the sum is the number of + /// scheduled attempts and the failure rate is + /// `(error + auth_rejected) / sum without (result) (...)`. Shutdown is not + /// counted. No `repo` label, like `cache_outcome_total`. + refresh: IntCounterVec, /// `auth_validations_total{result}` - per-request token validation calls; /// result = allow | deny | unavailable | saturated. No `repo` label: a flood /// of junk credentials names arbitrary repos. @@ -252,6 +273,14 @@ impl Metrics { &["outcome"], ) .expect("valid metric"); + let refresh = IntCounterVec::new( + Opts::new( + "gitcacheproxy_refresh_total", + "Background refresh attempts by result (ok/error/auth_rejected/preempted/skipped)", + ), + &["result"], + ) + .expect("valid metric"); let auth_validations = IntCounterVec::new( Opts::new( "gitcacheproxy_auth_validations_total", @@ -310,6 +339,9 @@ impl Metrics { registry .register(Box::new(cache_outcome.clone())) .expect("register cache_outcome"); + registry + .register(Box::new(refresh.clone())) + .expect("register refresh"); registry .register(Box::new(auth_validations.clone())) .expect("register auth_validations"); @@ -333,6 +365,7 @@ impl Metrics { evictions, lfs_objects, cache_outcome, + refresh, auth_validations, auth_cache_hits, upstream_duration, @@ -390,6 +423,18 @@ impl Metrics { self.cache_outcome.with_label_values(&[label]).inc(); } + /// Record `count` background refresh attempts that ended with `result`. + pub fn record_refresh(&self, result: RefreshResult, count: u64) { + let label = match result { + RefreshResult::Ok => "ok", + RefreshResult::Error => "error", + RefreshResult::AuthRejected => "auth_rejected", + RefreshResult::Preempted => "preempted", + RefreshResult::Skipped => "skipped", + }; + self.refresh.with_label_values(&[label]).inc_by(count); + } + /// Record one token validation call, or a check that found no slot for one. pub fn record_validation(&self, result: ValidationResult) { self.auth_validations @@ -453,6 +498,8 @@ mod tests { m.record_cache_outcome(CacheOutcome::Cached); m.record_cache_outcome(CacheOutcome::Fetched); m.record_cache_outcome(CacheOutcome::Cloned); + m.record_refresh(RefreshResult::Ok, 1); + m.record_refresh(RefreshResult::Skipped, 3); m.record_validation(ValidationResult::Deny); m.record_auth_cache_hit(); m.observe_upstream(UpstreamOp::Clone, "group/foo.git", 1.5); @@ -469,6 +516,8 @@ mod tests { assert!(out.contains(r#"gitcacheproxy_cache_outcome_total{outcome="cached"} 1"#)); assert!(out.contains(r#"gitcacheproxy_cache_outcome_total{outcome="fetched"} 1"#)); assert!(out.contains(r#"gitcacheproxy_cache_outcome_total{outcome="cloned"} 1"#)); + assert!(out.contains(r#"gitcacheproxy_refresh_total{result="ok"} 1"#)); + assert!(out.contains(r#"gitcacheproxy_refresh_total{result="skipped"} 3"#)); assert!(out.contains(r#"gitcacheproxy_auth_validations_total{result="deny"} 1"#)); assert!(out.contains("gitcacheproxy_auth_cache_hits_total 1")); assert!(out.contains( From 371a454ac39b8211d575db9eda9e13d0447c9a5e Mon Sep 17 00:00:00 2001 From: tower <12181924+profiling@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:34:30 +0800 Subject: [PATCH 3/3] test(refresh): cover scheduled refresh end to end Drive a real file:// upstream through the router, push a new commit, and assert the mirror advances with no further client request. The paused clock is held still while real git runs, which would otherwise auto-advance it into the upstream timeout. Assisted-by: Claude:claude-sonnet-5-5 --- tests/refresh.rs | 200 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 195 insertions(+), 5 deletions(-) diff --git a/tests/refresh.rs b/tests/refresh.rs index 6786d08..3f86cd7 100644 --- a/tests/refresh.rs +++ b/tests/refresh.rs @@ -1,13 +1,23 @@ // SPDX-License-Identifier: Apache-2.0 //! Public refresh configuration and startup behavior. -use std::sync::Arc; -use std::time::Duration; +use std::future::Future; +use std::path::Path; +use std::process::Command; +use std::sync::{Arc, mpsc}; +use std::time::{Duration, Instant}; +use axum::body::Body; +use axum::http::{Request, StatusCode}; use clap::Parser; -use git_cache_proxy::config::Config; -use git_cache_proxy::git::{GitCache, GitConfig}; +use git_cache_proxy::auth::Auth; +use git_cache_proxy::config::{Config, UpstreamCredential}; +use git_cache_proxy::git::{GitCache, GitConfig, RefreshConfig}; +use git_cache_proxy::lfs::{Lfs, LfsConfig}; use git_cache_proxy::metrics::Metrics; +use git_cache_proxy::repo::resolve; +use git_cache_proxy::server::{AppState, router}; +use tower::ServiceExt; #[tokio::test(start_paused = true)] async fn refresh_default_disabled_does_not_start_a_task() { @@ -103,7 +113,7 @@ fn refresh_invalid_settings_fail_before_creating_cache() { ] { let root = tempfile::tempdir().unwrap(); let cache = root.path().join("not-created"); - let output = std::process::Command::new(env!("CARGO_BIN_EXE_git-cache-proxy")) + let output = Command::new(env!("CARGO_BIN_EXE_git-cache-proxy")) .args([ "--upstream", "https://example.com", @@ -121,3 +131,183 @@ fn refresh_invalid_settings_fail_before_creating_cache() { assert!(!cache.exists()); } } + +#[tokio::test(start_paused = true)] +async fn background_refresh_pulls_new_upstream_commits_without_a_client_request() { + let up = tempfile::tempdir().unwrap(); + let work = tempfile::tempdir().unwrap(); + git(work.path(), &["init", "-q", "-b", "main", "."]); + git( + work.path(), + &["commit", "-q", "--allow-empty", "-m", "first"], + ); + let upstream_repo = up.path().join("repo.git"); + git( + work.path(), + &[ + "clone", + "-q", + "--bare", + ".", + upstream_repo.to_str().unwrap(), + ], + ); + + let cache_root = tempfile::tempdir().unwrap(); + let metrics = Arc::new(Metrics::new()); + // The smallest interval the CLI accepts. + let interval = Duration::from_secs(3600); + let cache = Arc::new(GitCache::new( + GitConfig { + git_binary: "git".into(), + upstream_auth_header: None, + big_file_threshold: "8m".into(), + fetch_ttl: Duration::ZERO, + max_wants: 100, + max_upload_packs: 0, + pack_threads: None, + pack_window_memory: None, + refresh: Some(RefreshConfig { + interval, + active_window: Duration::from_secs(86400), + concurrency: 1, + }), + }, + metrics.clone(), + None, + )); + let refresher = cache.start_refresh().unwrap(); + let app = router(app_state( + cache.clone(), + metrics.clone(), + up.path(), + cache_root.path(), + )); + + let response = without_auto_advance( + app.oneshot( + Request::get("/repo.git/info/refs?service=git-upload-pack") + .header("git-protocol", "version=2") + .body(Body::empty()) + .unwrap(), + ), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::OK); + + let mirror = resolve("repo.git", "unused", cache_root.path()) + .unwrap() + .cache_dir; + let first = git(work.path(), &["rev-parse", "HEAD"]); + assert_eq!(git(&mirror, &["rev-parse", "refs/heads/main"]), first); + + git( + work.path(), + &["commit", "-q", "--allow-empty", "-m", "second"], + ); + let second = git(work.path(), &["rev-parse", "HEAD"]); + git( + work.path(), + &["push", "-q", upstream_repo.to_str().unwrap(), "main"], + ); + + // Fire the first round. No further client request is made, so only the + // scheduled refresh can move the mirror. The ref moves before the fetch + // process exits, so also wait for the recorded result. + tokio::time::advance(interval).await; + wait_until(|| { + let moved = git(&mirror, &["rev-parse", "refs/heads/main"]) == second; + let recorded = metrics + .gather() + .contains(r#"gitcacheproxy_refresh_total{result="ok"}"#); + moved && recorded + }) + .await; + + let out = metrics.gather(); + assert!( + out.contains( + r#"gitcacheproxy_requests_total{kind="info_refs",repo="repo.git",result="ok"} 1"# + ), + "the mirror must have been refreshed without another client request" + ); + + cache.shutdown(); + refresher.await.unwrap(); + cache.wait_for_shutdown().await; +} + +/// Hold the paused clock still while `work` waits on real subprocesses. With no +/// blocking task outstanding, tokio auto-advances an idle paused clock to the +/// next timer, here the upstream timeout, and the clone would fail. +async fn without_auto_advance(work: impl Future) -> T { + let (release, hold) = mpsc::channel::<()>(); + let guard = tokio::task::spawn_blocking(move || { + let _ = hold.recv(); + }); + let out = work.await; + drop(release); + guard.await.unwrap(); + out +} + +/// Poll `ready` every 10ms of paused time. Each check spawns `git`, which keeps +/// the virtual clock from racing far ahead of the real work it waits for (and +/// into the upstream timeout); the deadline is real time for the same reason. +async fn wait_until(mut ready: impl FnMut() -> bool) { + let deadline = Instant::now() + Duration::from_secs(30); + while !ready() { + assert!( + Instant::now() < deadline, + "background refresh did not fetch the new upstream commit" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +fn app_state( + cache: Arc, + metrics: Arc, + upstream_root: &Path, + cache_root: &Path, +) -> AppState { + let upstream_base = format!("file://{}", upstream_root.display()); + AppState { + cache, + lfs: Arc::new(Lfs::new( + LfsConfig { + upstream_base: upstream_base.clone(), + cache_root: cache_root.to_path_buf(), + upstream_auth_header: None, + }, + None, + )), + upstream_base, + cache_root: cache_root.to_path_buf(), + auth: Arc::new(Auth::anonymous()), + upstream_credential: UpstreamCredential::Static, + max_decoded_body: 512 * 1024 * 1024, + max_concurrent: 8, + metrics, + } +} + +fn git(cwd: &Path, args: &[&str]) -> String { + let out = Command::new("git") + .current_dir(cwd) + .args(args) + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_AUTHOR_NAME", "t") + .env("GIT_AUTHOR_EMAIL", "t@example.com") + .env("GIT_COMMITTER_NAME", "t") + .env("GIT_COMMITTER_EMAIL", "t@example.com") + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8(out.stdout).unwrap().trim().to_string() +}