Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions chart/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand Down
9 changes: 9 additions & 0 deletions chart/templates/deployment.yaml
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions chart/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
58 changes: 51 additions & 7 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand All @@ -36,6 +39,18 @@ Every flag has an environment-variable equivalent.
Endpoints: `/healthz`, `/readyz`, `/metrics` (see [Metrics](./metrics.md)).


## Periodic refresh
Comment thread
rolandjitsu marked this conversation as resolved.
Resolved

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.
Expand Down
6 changes: 6 additions & 0 deletions docs/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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).
Expand Down
68 changes: 67 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -310,11 +339,48 @@ pub struct Config {

fn parse_upstream_timeout(value: &str) -> Result<u64, String> {
let seconds = value.parse::<u64>().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<RefreshConfig> {
(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::*;
Expand Down
Loading
Loading