diff --git a/docs/architecture.md b/docs/architecture.md index c730d94..03540a5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -185,7 +185,9 @@ fleet pays the WAN cost, the rest are served locally. The upstream LFS transfer in-process over HTTPS (reqwest + rustls, no OpenSSL), so the binary stays statically linked. Cached objects share the `--cache-max-mb` budget and LRU eviction with the git mirrors. No configuration is needed: LFS is served on the same endpoints the git -client already routes through the proxy. +client already routes through the proxy. With `--lfs-batch-cache-fallback`, a batch +whose upstream call fails transiently is answered from the cache when every +object in it is cached (see [Auth model](./security.md#auth-model) for where that is allowed). ### Cache management diff --git a/docs/configuration.md b/docs/configuration.md index ac1911c..daafef4 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -19,6 +19,7 @@ Every flag has an environment-variable equivalent. | `--auth-ttl-seconds` | `GITCACHEPROXY_AUTH_TTL_SECONDS` | `0` | Reuse a validation verdict per `(credential, repo)` for this many seconds, so the requests of one clone, or repeated submodule fetches, validate once (`0` = validate every request) | | `--auth-max-concurrent` | `GITCACHEPROXY_AUTH_MAX_CONCURRENT` | `32` | Max token-validation requests in flight; a check waits up to `--auth-timeout-seconds` for a slot, then fails with 503 (`0` = unlimited) | | `--auth-allow-http` | `GITCACHEPROXY_AUTH_ALLOW_HTTP` | `false` | Provider modes: accept a plain `http://` validation endpoint, which sends client credentials in cleartext | +| `--lfs-batch-cache-fallback` | `GITCACHEPROXY_LFS_BATCH_CACHE_FALLBACK` | `false` | When the upstream LFS batch fails transiently (no response or a 5xx), answer a download batch whose objects are all cached. Requires `--upstream-credential static` and `--auth-provider none` or `shared` (see [Auth model](./security.md#auth-model)) | | `--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 | diff --git a/docs/metrics.md b/docs/metrics.md index 3c6d35a..410ca8c 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -28,7 +28,9 @@ Label values: `serve_duration_seconds`: `info_refs` (the buffered ref advertisement) or `upload_pack` (the packfile stream, timed to EOF). - `result` on `requests_total`: `ok`, `error`, `upstream_error`, `unauthorized`, - `rejected`. On `upstream_ops_total`: `ok` or `error`. On `lfs_objects_total`: + `rejected`, `cache_fallback` (an `lfs_batch` answered from the cache after a + transient upstream failure, see `--lfs-batch-cache-fallback`). On + `upstream_ops_total`: `ok` or `error`. On `lfs_objects_total`: `hit` (served from disk), `miss` (fetched from upstream, then cached), `error`. On `auth_validations_total`: `allow`, `deny`, `unavailable` (the endpoint failed, throttled, or answered something else), `saturated` (no call made: no diff --git a/docs/security.md b/docs/security.md index ad026db..9b0977c 100644 --- a/docs/security.md +++ b/docs/security.md @@ -82,6 +82,12 @@ cannot fetch another repo's object from the shared object cache. Every replica behind one address must share `--auth-signing-key`, or a grant issued by one is refused by the others; the caches themselves stay independent. +That repo binding relies on the upstream batch to confirm an object belongs to +the repo, which is why `--lfs-batch-cache-fallback` (answering a batch from the +cache while upstream is down) is refused at startup with a provider mode or +`--upstream-credential client`. With `none` or `shared` auth any client can +already GET any cached object, so the fallback grants nothing new. + ### Fetch upstream with the client's credential (`--upstream-credential client`) In the default `static` mode the proxy clones and fetches upstream with the one diff --git a/src/config.rs b/src/config.rs index 5338f10..b712086 100644 --- a/src/config.rs +++ b/src/config.rs @@ -97,6 +97,30 @@ pub fn validate_upstream_credential( Ok(()) } +/// Reject a `--lfs-batch-cache-fallback` that would bypass an authorization +/// check. In `client` upstream-credential mode the upstream batch runs on the +/// client's own credential, so it is what authorizes the client. Under a +/// `github`/`gitlab`/`custom` provider a batch grant binds an object to the +/// validated repo, and only the upstream batch confirms the object belongs to +/// that repo; the cache is shared across repos, so a fallback would let a +/// client reach another repo's cached object by its oid. +pub fn validate_lfs_batch_cache_fallback( + enabled: bool, + mode: UpstreamCredential, + provider: AuthProvider, +) -> Result<()> { + if !enabled { + return Ok(()); + } + if mode != UpstreamCredential::Static { + bail!("--lfs-batch-cache-fallback requires --upstream-credential static"); + } + if !matches!(provider, AuthProvider::None | AuthProvider::Shared) { + bail!("--lfs-batch-cache-fallback requires --auth-provider none or shared, not {provider}"); + } + Ok(()) +} + #[derive(Parser, Debug, Clone)] #[command( name = "git-cache-proxy", @@ -214,6 +238,13 @@ pub struct Config { #[arg(long, env = "GITCACHEPROXY_AUTH_TTL_SECONDS", default_value_t = 0)] pub auth_ttl_seconds: u64, + /// Answer an LFS download batch from the cache when the upstream batch fails + /// transiently (no response, or a 5xx). Requires `--upstream-credential static` + /// and `--auth-provider none` or `shared`, where the upstream batch authorizes + /// nothing the client could not already reach. + #[arg(long, env = "GITCACHEPROXY_LFS_BATCH_CACHE_FALLBACK")] + pub lfs_batch_cache_fallback: bool, + /// Total seconds per upstream clone, full-ref fetch or SHA backfill, /// including all attempts and retry delays. Must be positive. #[arg(long, env = "GITCACHEPROXY_UPSTREAM_TIMEOUT_SECONDS", default_value = "3600", @@ -429,6 +460,46 @@ mod tests { } } + #[test] + fn lfs_batch_cache_fallback_needs_static_mode_and_no_per_repo_auth() { + let all = [ + AuthProvider::None, + AuthProvider::Shared, + AuthProvider::Github, + AuthProvider::Gitlab, + AuthProvider::Custom, + ]; + for provider in all { + for mode in [UpstreamCredential::Static, UpstreamCredential::Client] { + assert!(validate_lfs_batch_cache_fallback(false, mode, provider).is_ok()); + } + } + for provider in [AuthProvider::None, AuthProvider::Shared] { + assert!( + validate_lfs_batch_cache_fallback(true, UpstreamCredential::Static, provider) + .is_ok() + ); + } + let err = validate_lfs_batch_cache_fallback( + true, + UpstreamCredential::Client, + AuthProvider::Github, + ) + .unwrap_err() + .to_string(); + assert!(err.contains("--upstream-credential static"), "{err}"); + for provider in [ + AuthProvider::Github, + AuthProvider::Gitlab, + AuthProvider::Custom, + ] { + let err = validate_lfs_batch_cache_fallback(true, UpstreamCredential::Static, provider) + .unwrap_err() + .to_string(); + assert!(err.contains("--auth-provider"), "{err}"); + } + } + #[test] fn client_mode_rejects_a_static_auth_header() { let err = diff --git a/src/lfs.rs b/src/lfs.rs index ce9c5b6..754892f 100644 --- a/src/lfs.rs +++ b/src/lfs.rs @@ -11,7 +11,9 @@ //! Flow: //! POST /info/lfs/objects/batch //! -> forward to upstream, then rewrite every download href to point back here -//! (`/info/lfs/objects/`) so the object fetch is cached. +//! (`/info/lfs/objects/`) so the object fetch is cached. With +//! `--lfs-batch-cache-fallback`, a transient upstream failure is answered +//! locally when every requested object is cached (see `Lfs::cached_batch`). //! GET /info/lfs/objects/ //! -> serve from the on-disk cache (content-addressed by oid), or on a miss fetch //! it once (re-batch for a fresh authorized URL, download, verify sha256 == @@ -85,6 +87,8 @@ pub struct Lfs { /// Names the per-download temp file the object is streamed to before its atomic /// rename into the content-addressed cache path. tmp_counter: AtomicU64, + /// Whether a transiently failed download batch may be answered from the cache. + batch_cache_fallback: bool, } impl Lfs { @@ -102,9 +106,18 @@ impl Lfs { index, slots: Mutex::new(HashMap::new()), tmp_counter: AtomicU64::new(0), + batch_cache_fallback: false, } } + /// Allow `cached_batch` to answer a download batch whose upstream call failed + /// transiently. Startup validation (`validate_lfs_batch_cache_fallback`) only + /// allows it where the upstream batch authorizes nothing. + pub fn with_batch_cache_fallback(mut self, enabled: bool) -> Self { + self.batch_cache_fallback = enabled; + self + } + /// Proxy a client batch request to upstream and rewrite the download hrefs so the /// objects are fetched back through this proxy (and thus cached). `advertise_base` /// is the proxy's own `scheme://host` as the client reached it, and `grant` @@ -128,6 +141,59 @@ impl Lfs { serde_json::to_vec(&json).context("serialize lfs batch response") } + /// Answer a download batch from the cache alone after the upstream batch failed + /// with `err`. Each object gets the same download action `batch` would produce, + /// so its GET is a plain cache hit. Objects are content-addressed and + /// hash-verified on store, so a cached one is never stale. `None`, leaving the + /// caller to fail the batch, when the fallback is off, `err` is not transient, + /// the request is not a well-formed basic-transfer download batch, or any + /// requested object is not cached: the client would need upstream for it anyway. + pub async fn cached_batch( + &self, + err: &anyhow::Error, + repo: &str, + body: &[u8], + advertise_base: &str, + grant: impl Fn(&str, u64) -> Option, + ) -> Option> { + if !self.batch_cache_fallback || !is_transient_batch_error(err) { + return None; + } + let req: Value = serde_json::from_slice(body).ok()?; + if req.get("operation")?.as_str()? != "download" { + return None; + } + // An omitted list means basic; otherwise the client must offer it. + if let Some(transfers) = req.get("transfers") + && !transfers.as_array()?.iter().any(|t| t == "basic") + { + return None; + } + let mut objects = Vec::new(); + for obj in req.get("objects")?.as_array()? { + let oid = obj.get("oid")?.as_str()?; + let size = obj.get("size")?.as_u64()?; + if !repo::valid_lfs_oid(oid) + || !self + .cached(&repo::lfs_object_path(&self.cfg.cache_root, oid)) + .await + { + return None; + } + // `authenticated`: the href carries its own credential, so git-lfs + // would otherwise prompt for one on the proxy href. + objects.push(serde_json::json!({ + "oid": oid, + "size": size, + "authenticated": true, + "actions": { "download": { "href": "" } }, + })); + } + let mut json = serde_json::json!({ "transfer": "basic", "objects": objects }); + rewrite_download_hrefs(&mut json, advertise_base, repo, grant); + serde_json::to_vec(&json).ok() + } + /// Ensure the object identified by `oid` is on disk and return its path plus /// whether it was a cache hit. On a miss `size` is required (the upstream batch /// API needs it); it is not needed for a hit. @@ -247,13 +313,22 @@ impl Lfs { { req = req.header(name, value); } + // URLs are dropped from errors: they are logged, and an upstream base may + // carry userinfo. let resp = req .send() .await + .map_err(reqwest::Error::without_url) .context("send lfs batch")? .error_for_status() + .map_err(reqwest::Error::without_url) .context("lfs batch http status")?; - Ok(resp.bytes().await.context("read lfs batch body")?.to_vec()) + Ok(resp + .bytes() + .await + .map_err(reqwest::Error::without_url) + .context("read lfs batch body")? + .to_vec()) } /// Stream an object href to `out`, sending the batch-supplied `headers`. reqwest @@ -304,11 +379,24 @@ impl Lfs { } } +/// Whether an upstream batch failure is transient: a connect or send failure, a +/// body cut short, or a 5xx. A 4xx is upstream's answer about the +/// repo or credential and must not be papered over, nor a malformed 2xx body. +fn is_transient_batch_error(err: &anyhow::Error) -> bool { + err.chain() + .find_map(|e| e.downcast_ref::()) + .is_some_and(|e| match e.status() { + Some(status) => status.is_server_error(), + None => !e.is_builder() && !e.is_redirect(), + }) +} + /// Rewrite each object's `download` href to point back at this proxy so the fetch is /// cached, and set the object GET's credential from `grant` (or drop it when the /// proxy serves anonymously) - the client authenticates to the proxy, not upstream. /// Objects carrying an `error`, or an `upload` action, are left untouched, so a -/// grant is only ever issued for an object upstream listed for `repo`. +/// grant is only ever issued for an object upstream listed for `repo`, or, with +/// `--lfs-batch-cache-fallback` (only under `none`/`shared` auth), one already cached. /// Malformed entries are skipped rather than failing the batch. fn rewrite_download_hrefs( json: &mut Value, diff --git a/src/main.rs b/src/main.rs index 227a9ed..919e71a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,8 @@ use clap::Parser; use tracing_subscriber::EnvFilter; use git_cache_proxy::config::{ - Config, LogFormat, UpstreamCredential, validate_upstream_credential, + Config, LogFormat, UpstreamCredential, validate_lfs_batch_cache_fallback, + validate_upstream_credential, }; use git_cache_proxy::{auth, evict, git, lfs, metrics, repo, server}; @@ -48,6 +49,11 @@ async fn main() -> Result<()> { cfg.auth_provider, upstream_auth_header.is_some(), )?; + validate_lfs_batch_cache_fallback( + cfg.lfs_batch_cache_fallback, + cfg.upstream_credential, + cfg.auth_provider, + )?; match cfg.upstream_credential { UpstreamCredential::Client => tracing::info!( "upstream credential: forwarding each request's client credential; \ @@ -127,14 +133,17 @@ async fn main() -> Result<()> { ) .await; - let lfs = Arc::new(lfs::Lfs::new( - lfs::LfsConfig { - upstream_base: upstream_base.clone(), - cache_root: cfg.cache_root.clone(), - upstream_auth_header, - }, - index.clone(), - )); + let lfs = Arc::new( + lfs::Lfs::new( + lfs::LfsConfig { + upstream_base: upstream_base.clone(), + cache_root: cfg.cache_root.clone(), + upstream_auth_header, + }, + index.clone(), + ) + .with_batch_cache_fallback(cfg.lfs_batch_cache_fallback), + ); let state = server::AppState { cache: cache.clone(), diff --git a/src/metrics.rs b/src/metrics.rs index 6bdcdc5..dc76626 100644 --- a/src/metrics.rs +++ b/src/metrics.rs @@ -43,6 +43,8 @@ pub enum Status { UpstreamError, Unauthorized, Rejected, + /// An LFS batch upstream failed transiently, answered from the cache. + CacheFallback, } /// The `op` label on `upstream_ops_total` / `upstream_duration_seconds`. @@ -115,6 +117,7 @@ impl Status { Self::UpstreamError => "upstream_error", Self::Unauthorized => "unauthorized", Self::Rejected => "rejected", + Self::CacheFallback => "cache_fallback", } } } @@ -163,8 +166,8 @@ pub struct Metrics { pub registry: Registry, /// `requests_total{kind, result, repo}` - kind = info_refs | upload_pack | /// auth | receive_pack | lfs_batch | lfs_object; result = ok | error | - /// upstream_error | unauthorized | rejected; repo = the served repo path when - /// result = ok, else `-`. + /// upstream_error | unauthorized | rejected | cache_fallback; repo = the served + /// repo path when result = ok, else `-`. requests: IntCounterVec, /// `upstream_ops_total{op, result, repo}` - op = clone | fetch | want_fetch; /// result = ok | error; repo = the repo path when result = ok, else `-`. diff --git a/src/server.rs b/src/server.rs index 7707f91..6ff53d6 100644 --- a/src/server.rs +++ b/src/server.rs @@ -333,7 +333,8 @@ async fn handle_git( /// Proxy an LFS batch request to upstream, rewriting each object's download URL back /// to this proxy so the object fetch is cached here. An `upload` batch is refused: -/// the proxy is read-only, like `git-receive-pack`. +/// the proxy is read-only, like `git-receive-pack`. With the cache fallback on, a +/// transient upstream failure is answered from the cache. async fn lfs_batch( st: AppState, name: &str, @@ -353,23 +354,35 @@ async fn lfs_batch( // In `client` mode the grant seals `cred` so the object GET can re-batch with // it; in `static` mode `cred` is `None` and the grant carries no credential. let grant = |oid: &str, size| st.auth.lfs_grant(name, oid, size, cred); - match st.lfs.batch(name, &body, &advertise, grant, cred).await { + let json = match st.lfs.batch(name, &body, &advertise, grant, cred).await { Ok(json) => { st.metrics .record_request(RequestKind::LfsBatch, Status::Ok, name); - Response::builder() - .header(header::CONTENT_TYPE, LFS_CONTENT_TYPE) - .header(header::CACHE_CONTROL, "no-cache") - .body(Body::from(json)) - .expect("valid response") + json } Err(e) => { + tracing::warn!(repo = %name, error = %format_args!("{e:#}"), "lfs batch failed"); + let Some(json) = st + .lfs + .cached_batch(&e, name, &body, &advertise, grant) + .await + else { + st.metrics + .record_request(RequestKind::LfsBatch, Status::UpstreamError, "-"); + return err(StatusCode::BAD_GATEWAY, "upstream lfs batch failed"); + }; + // `-`, not the repo: upstream did not confirm the repo exists. st.metrics - .record_request(RequestKind::LfsBatch, Status::UpstreamError, "-"); - tracing::warn!(repo = %name, error = %e, "lfs batch failed"); - err(StatusCode::BAD_GATEWAY, "upstream lfs batch failed") + .record_request(RequestKind::LfsBatch, Status::CacheFallback, "-"); + tracing::info!(repo = %name, "lfs batch served from cache"); + json } - } + }; + Response::builder() + .header(header::CONTENT_TYPE, LFS_CONTENT_TYPE) + .header(header::CACHE_CONTROL, "no-cache") + .body(Body::from(json)) + .expect("valid response") } /// Serve a cached LFS object, fetching and caching it from upstream on a miss. The diff --git a/tests/lfs.rs b/tests/lfs.rs index f84d5c4..cc5db5e 100644 --- a/tests/lfs.rs +++ b/tests/lfs.rs @@ -2,8 +2,8 @@ //! End-to-end git-LFS tests: a mock upstream LFS server (batch API + object storage) //! on a live socket, with the proxy driven in-process reaching it over real HTTP. //! Verifies batch href rewriting, a cache miss (fetch + sha256 verify + store), a -//! cache hit served from disk without touching upstream, and rejection of a -//! corrupted object. +//! cache hit served from disk without touching upstream, rejection of a +//! corrupted object, and the batch cache fallback on a transient upstream failure. use std::net::SocketAddr; use std::sync::Arc; @@ -292,6 +292,133 @@ async fn batch_upstream_failure_returns_bad_gateway() { )); } +/// A transient upstream batch failure (504) with every object cached is +/// answered locally, and the object GET is a plain cache hit. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fallback_serves_a_fully_cached_batch_on_upstream_5xx() { + let (addr, batches) = spawn_upstream(Mode::BatchStatus(StatusCode::GATEWAY_TIMEOUT)).await; + let cache = tempfile::tempdir().unwrap(); + let metrics = Arc::new(Metrics::new()); + let state = proxy_state_with(addr, cache.path(), metrics.clone(), true); + let oid = seed(cache.path(), PAYLOAD).await; + + let resp = batch(state.clone(), &[(&oid, PAYLOAD.len())]).await; + assert_eq!(resp.status(), StatusCode::OK); + let json: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap(); + let obj = &json["objects"][0]; + assert_eq!(obj["oid"], oid.as_str()); + assert_eq!(obj["size"], PAYLOAD.len()); + let href = obj["actions"]["download"]["href"].as_str().unwrap(); + assert_eq!( + href, + format!( + "http://proxy.test:8080/{REPO}/info/lfs/objects/{oid}?size={}", + PAYLOAD.len() + ) + ); + assert_eq!(batches.load(Ordering::SeqCst), 1); + + let path = href.strip_prefix("http://proxy.test:8080").unwrap(); + let resp = object_get(state, path, None).await; + assert_eq!(resp.status(), StatusCode::OK); + assert_eq!(body_bytes(resp).await, PAYLOAD); + assert_eq!( + batches.load(Ordering::SeqCst), + 1, + "a fallback-served object GET must not re-batch upstream" + ); + + let scraped = metrics.gather(); + assert!(scraped.contains( + r#"gitcacheproxy_requests_total{kind="lfs_batch",repo="-",result="cache_fallback"} 1"# + )); + assert!(scraped.contains(r#"gitcacheproxy_lfs_objects_total{result="hit"} 1"#)); +} + +/// One uncached object fails the whole batch: the client needs upstream for it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fallback_needs_every_object_cached() { + let (addr, _batches) = spawn_upstream(Mode::BatchStatus(StatusCode::BAD_GATEWAY)).await; + let cache = tempfile::tempdir().unwrap(); + let state = proxy_state_with(addr, cache.path(), Arc::new(Metrics::new()), true); + let cached = seed(cache.path(), PAYLOAD).await; + let resp = batch(state, &[(&cached, PAYLOAD.len()), (&oid_of(b"absent"), 6)]).await; + assert_eq!(resp.status(), StatusCode::BAD_GATEWAY); +} + +/// A connection failure is as transient as a 5xx. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fallback_covers_an_unreachable_upstream() { + let cache = tempfile::tempdir().unwrap(); + let dead: SocketAddr = "127.0.0.1:1".parse().unwrap(); + let state = proxy_state_with(dead, cache.path(), Arc::new(Metrics::new()), true); + let oid = seed(cache.path(), PAYLOAD).await; + let resp = batch(state, &[(&oid, PAYLOAD.len())]).await; + assert_eq!(resp.status(), StatusCode::OK); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fallback_with_nothing_cached_still_fails() { + let (addr, _batches) = spawn_upstream(Mode::BatchStatus(StatusCode::GATEWAY_TIMEOUT)).await; + let cache = tempfile::tempdir().unwrap(); + let metrics = Arc::new(Metrics::new()); + let state = proxy_state_with(addr, cache.path(), metrics.clone(), true); + let resp = batch(state, &[(&oid_of(PAYLOAD), PAYLOAD.len())]).await; + assert_eq!(resp.status(), StatusCode::BAD_GATEWAY); + assert!(metrics.gather().contains( + r#"gitcacheproxy_requests_total{kind="lfs_batch",repo="-",result="upstream_error"} 1"# + )); +} + +/// A 4xx is upstream's answer about the repo or credential, so it stands even +/// when the object is cached. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fallback_never_bypasses_an_upstream_4xx() { + for status in [ + StatusCode::UNAUTHORIZED, + StatusCode::FORBIDDEN, + StatusCode::NOT_FOUND, + StatusCode::UNPROCESSABLE_ENTITY, + ] { + let (addr, _batches) = spawn_upstream(Mode::BatchStatus(status)).await; + let cache = tempfile::tempdir().unwrap(); + let state = proxy_state_with(addr, cache.path(), Arc::new(Metrics::new()), true); + let oid = seed(cache.path(), PAYLOAD).await; + let resp = batch(state, &[(&oid, PAYLOAD.len())]).await; + assert_eq!(resp.status(), StatusCode::BAD_GATEWAY, "{status}"); + } +} + +/// The fallback answers only a well-formed basic-transfer download batch; anything +/// else keeps the upstream failure. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fallback_refuses_a_malformed_batch() { + let (addr, _batches) = spawn_upstream(Mode::BatchStatus(StatusCode::GATEWAY_TIMEOUT)).await; + let cache = tempfile::tempdir().unwrap(); + let state = proxy_state_with(addr, cache.path(), Arc::new(Metrics::new()), true); + let oid = seed(cache.path(), PAYLOAD).await; + let cached = serde_json::json!({ "oid": oid, "size": PAYLOAD.len() }); + for body in [ + serde_json::json!({ "operation": "download", "objects": [cached, { "size": 1 }] }), + serde_json::json!({ "operation": "download", "objects": [cached, { "oid": oid }] }), + serde_json::json!({ "operation": "download", "transfers": ["custom"], "objects": [cached] }), + serde_json::json!({ "objects": [cached] }), + ] { + let resp = post_batch(state.clone(), body.clone()).await; + assert_eq!(resp.status(), StatusCode::BAD_GATEWAY, "{body}"); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn fallback_is_off_by_default() { + let (addr, _batches) = spawn_upstream(Mode::BatchStatus(StatusCode::GATEWAY_TIMEOUT)).await; + let cache = tempfile::tempdir().unwrap(); + let state = proxy_state(addr, cache.path(), Arc::new(Metrics::new())); + let oid = seed(cache.path(), PAYLOAD).await; + let resp = batch(state, &[(&oid, PAYLOAD.len())]).await; + assert_eq!(resp.status(), StatusCode::BAD_GATEWAY); +} + // --- test helpers -------------------------------------------------------- const REPO: &str = "group/repo.git"; @@ -307,6 +434,8 @@ enum Mode { Ok, Corrupt, Missing, + /// The batch endpoint itself fails with this status. + BatchStatus(StatusCode), } /// Shared state of the mock upstream: how many batch calls it has served (so a test @@ -338,6 +467,9 @@ async fn upstream_handler(State(up): State, req: Request) -> Res if parts.method == Method::POST && path.ends_with("/info/lfs/objects/batch") { up.batches.fetch_add(1, Ordering::SeqCst); + if let Mode::BatchStatus(status) = up.mode { + return (status, "mock: batch failed").into_response(); + } let repo = path .trim_start_matches('/') .strip_suffix("/info/lfs/objects/batch") @@ -382,7 +514,7 @@ async fn upstream_handler(State(up): State, req: Request) -> Res return match up.mode { Mode::Ok => (StatusCode::OK, PAYLOAD.to_vec()).into_response(), Mode::Corrupt => (StatusCode::OK, b"tampered".to_vec()).into_response(), - Mode::Missing => (StatusCode::NOT_FOUND, "gone").into_response(), + Mode::Missing | Mode::BatchStatus(_) => (StatusCode::NOT_FOUND, "gone").into_response(), }; } @@ -411,6 +543,16 @@ async fn spawn_upstream(mode: Mode) -> (SocketAddr, Arc) { /// A proxy `AppState` whose LFS upstream is the mock at `addr`, cached under `cache`. fn proxy_state(addr: SocketAddr, cache: &std::path::Path, metrics: Arc) -> AppState { + proxy_state_with(addr, cache, metrics, false) +} + +/// `proxy_state`, with the batch cache fallback on when `batch_cache_fallback`. +fn proxy_state_with( + addr: SocketAddr, + cache: &std::path::Path, + metrics: Arc, + batch_cache_fallback: bool, +) -> AppState { let upstream = format!("http://{addr}"); let idx = CacheIndex::new(cache.to_path_buf(), u64::MAX, metrics.clone()); let cfg = GitConfig { @@ -419,14 +561,17 @@ fn proxy_state(addr: SocketAddr, cache: &std::path::Path, metrics: Arc) }; AppState { cache: Arc::new(GitCache::new(cfg, metrics.clone(), Some(idx.clone()))), - lfs: Arc::new(Lfs::new( - LfsConfig { - upstream_base: upstream.clone(), - cache_root: cache.to_path_buf(), - upstream_auth_header: None, - }, - Some(idx), - )), + lfs: Arc::new( + Lfs::new( + LfsConfig { + upstream_base: upstream.clone(), + cache_root: cache.to_path_buf(), + upstream_auth_header: None, + }, + Some(idx), + ) + .with_batch_cache_fallback(batch_cache_fallback), + ), upstream_base: upstream, cache_root: cache.to_path_buf(), auth: Arc::new(Auth::anonymous()), @@ -437,6 +582,49 @@ fn proxy_state(addr: SocketAddr, cache: &std::path::Path, metrics: Arc) } } +/// Store `bytes` in the LFS cache as a previous download would have; returns its oid. +async fn seed(cache: &std::path::Path, bytes: &[u8]) -> String { + let oid = oid_of(bytes); + let path = git_cache_proxy::repo::lfs_object_path(cache, &oid); + tokio::fs::create_dir_all(path.parent().unwrap()) + .await + .unwrap(); + tokio::fs::write(&path, bytes).await.unwrap(); + oid +} + +/// POST a download batch for `objects` (`(oid, size)` pairs) to the proxy. +async fn batch(state: AppState, objects: &[(&str, usize)]) -> Response { + let objects: Vec<_> = objects + .iter() + .map(|(oid, size)| serde_json::json!({ "oid": oid, "size": size })) + .collect(); + post_batch( + state, + serde_json::json!({ + "operation": "download", + "transfers": ["basic"], + "objects": objects, + }), + ) + .await +} + +/// POST `body` to the proxy's batch endpoint. +async fn post_batch(state: AppState, body: serde_json::Value) -> Response { + let body = serde_json::to_vec(&body).unwrap(); + router(state) + .oneshot( + Request::post(format!("/{REPO}/info/lfs/objects/batch")) + .header(header::HOST, "proxy.test:8080") + .header(header::CONTENT_TYPE, "application/vnd.git-lfs+json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap() +} + fn batch_body(oid: &str, size: usize) -> Vec { serde_json::to_vec(&serde_json::json!({ "operation": "download",