diff --git a/.env.example b/.env.example index 6e3c1c71..91066ac0 100644 --- a/.env.example +++ b/.env.example @@ -208,6 +208,11 @@ TWIGPINE_P2P_BOOTSTRAP= # Maximum git smart-HTTP pack request size, in bytes. TWIGPINE_MAX_PACK_BYTES=2147483648 +# Maximum compressed Tigris repo archive size accepted on download, in bytes. +# Independent of the pack request cap because a repository accumulated over many +# pushes can exceed one push. Default 2147483648 (2 GiB). +TWIGPINE_MAX_TIGRIS_ARCHIVE_BYTES=2147483648 + # Max seconds a served git upload-pack / receive-pack (clone / push) may run # before it is aborted with a 504. Bounds a hung git that would otherwise pin a # worker and, on push, the repo write lock. Also bounds both info/refs diff --git a/README.md b/README.md index 272e2e0e..1aed9878 100644 --- a/README.md +++ b/README.md @@ -461,6 +461,7 @@ Important node settings: | `TWIGPINE_AUTO_SYNC` | Enable automatic sync from known peers. | | `TWIGPINE_RECONCILIATION_SWEEP` | Enable the hourly durability sweep that re-pins/backstops missing objects (default `true`; disabled when no IPFS/Pinata backend is configured). Public pin repair runs against any configured backend (IPFS, Pinata, or both). Encrypted recovery repair requires local IPFS (`TWIGPINE_IPFS_API`); Pinata-only nodes reconcile public pins only. | | `TWIGPINE_MAX_PACK_BYTES` | Max git pack body size for smart-HTTP routes. | +| `TWIGPINE_MAX_TIGRIS_ARCHIVE_BYTES` | Max compressed Tigris repo archive size accepted on download, independent of the per-push pack cap. Default 2147483648 (2 GiB). | | `TWIGPINE_MODEL_HOSTING_ENABLED` | Enable model hosting (signed releases, block storage, HF-compatible reads, independent fetch). Off by default; see [docs/MODEL-HOSTING.md](docs/MODEL-HOSTING.md) for the quota, block-store, and durability knobs. | | `TWIGPINE_GIT_SERVICE_TIMEOUT_SECS` | Max seconds a served git upload-pack, receive-pack, or `info/refs` advertisement may run before it is aborted (504). Default 600. Also bounds the withheld-blob classification walk (on both the upload-pack serve and receive-pack replication paths) and the push-side pin-candidate discovery (`rev-list` / `cat-file`), each reaped via process-group teardown at the deadline. On the path-scoped upload-pack path the classification walk and the pack serve share ONE deadline, so this value bounds their combined duration rather than granting each stage a full budget: a walk that consumes it leaves the serve nothing and the clone gets a 504. Serving large path-scoped repos may therefore need a higher value than they did when each stage was budgeted separately. Accepted range is 1 to 3153600000 (100 years), since the node derives deadlines from this value and a larger one cannot be represented. | | `TWIGPINE_GIT_ACQUIRE_TIMEOUT_SECS` | Max seconds the storage-acquisition phase (Tigris HEAD/GET, push advisory-lock) of a served git op may run before the request is shed with a 503, separate from the git-run timeout. The concurrency permit is released on expiry so a stalled backend cannot pin the pool. Default 30. | diff --git a/crates/twigpine-node/src/config.rs b/crates/twigpine-node/src/config.rs index a701e2d7..d2d48d99 100644 --- a/crates/twigpine-node/src/config.rs +++ b/crates/twigpine-node/src/config.rs @@ -303,6 +303,18 @@ pub struct Config { )] pub tigris_bucket: String, + /// Maximum compressed Tigris repo archive size accepted on download, in bytes. + /// Independent of the per-push pack ceiling: a repository accumulated over + /// many pushes can be larger than any one push. Default: 2 GiB. `global` so + /// admin subcommands accept it wherever they accept `--tigris-bucket`. + #[arg( + long, + env = "TWIGPINE_MAX_TIGRIS_ARCHIVE_BYTES", + default_value_t = crate::git::tigris::DEFAULT_MAX_ARCHIVE_BYTES, + global = true + )] + pub max_tigris_archive_bytes: u64, + /// Maximum pack body size for git-receive-pack and git-upload-pack, in bytes. /// Applies only to git smart-HTTP routes — all other API routes keep the 2 MB default. /// Default: 2 GB. Set lower on resource-constrained nodes. @@ -1563,6 +1575,30 @@ mod tests { defaults.validate().unwrap(); } + #[test] + fn tigris_archive_cap_defaults_and_parses() { + assert_eq!( + Config::parse_from(["twigpine-node"]).max_tigris_archive_bytes, + crate::git::tigris::DEFAULT_MAX_ARCHIVE_BYTES + ); + assert_eq!( + Config::parse_from(["twigpine-node", "--max-tigris-archive-bytes", "12345"]) + .max_tigris_archive_bytes, + 12_345 + ); + // The bucket is global for admin subcommands, so its archive ceiling is too. + assert_eq!( + Config::parse_from([ + "twigpine-node", + "purge-spam", + "--max-tigris-archive-bytes", + "12345", + ]) + .max_tigris_archive_bytes, + 12_345 + ); + } + #[test] fn upstream_mirror_worker_is_default_off_and_bounded() { let mut config = Config::parse_from(["twigpine-node"]); diff --git a/crates/twigpine-node/src/git/repo_store.rs b/crates/twigpine-node/src/git/repo_store.rs index 4eecb54e..115f4fd7 100644 --- a/crates/twigpine-node/src/git/repo_store.rs +++ b/crates/twigpine-node/src/git/repo_store.rs @@ -76,6 +76,9 @@ pub struct RepoStore { /// Tracks repos already confirmed to exist in Tigris — avoids redundant /// HEAD checks and background uploads for repos we've already migrated. migrated: Arc>>, + /// One lock per repo for the cold download in [`RepoStore::acquire`], so a + /// burst of readers of a repo that is not on disk shares one download. + cold_downloads: ColdDownloadLocks, /// Test-only seam: armed here, copied into every `RepoWriteGuard` this store /// hands out, so a test that only holds the `AppState` (not the guard) can /// still park `release` at its pre-unlock point. See @@ -88,6 +91,88 @@ pub struct RepoStore { upload_site_reached: Arc, } +/// Per-repo locks for the cold download in [`RepoStore::acquire`]. +/// +/// An entry lives only while someone holds or waits on its lock: a refcount kept +/// under the map lock counts both, every reference is taken under that lock, and +/// the entry is removed when the count reaches zero. A fresh entry therefore +/// only ever replaces one nobody references, so two holders of one repo can +/// never end up on different locks. Unlike `tigris::publish_lock`, nothing +/// accumulates per repo ever seen. +#[derive(Clone, Default)] +struct ColdDownloadLocks { + repos: ColdDownloadMap, +} + +type ColdDownloadMap = Arc>>; + +struct ColdDownloadSlot { + lock: Arc>, + refs: usize, +} + +/// One reference to a repo's entry. Live from the moment the reference is +/// taken, so a waiter cancelled while parked gives its reference back. +struct ColdDownloadRef { + repos: ColdDownloadMap, + key: String, +} + +impl Drop for ColdDownloadRef { + fn drop(&mut self) { + let mut map = self.repos.lock().expect("cold download lock map poisoned"); + if let Some(slot) = map.get_mut(&self.key) { + slot.refs -= 1; + if slot.refs == 0 { + map.remove(&self.key); + } + } + } +} + +/// A held cold-download lock for one repo. `Send + 'static`, so it can move +/// into the blocking extraction and be released only when that returns. +pub(crate) struct ColdDownloadGuard { + // Field order is drop order: the lock is released before the reference is + // given back, so the entry outlives its own holder. + _held: tokio::sync::OwnedMutexGuard<()>, + _ref: ColdDownloadRef, +} + +impl ColdDownloadLocks { + async fn lock(&self, key: &str) -> ColdDownloadGuard { + let (lock, reference) = { + let mut map = self.repos.lock().expect("cold download lock map poisoned"); + let slot = map + .entry(key.to_string()) + .or_insert_with(|| ColdDownloadSlot { + lock: Arc::new(Mutex::new(())), + refs: 0, + }); + slot.refs += 1; + ( + Arc::clone(&slot.lock), + ColdDownloadRef { + repos: Arc::clone(&self.repos), + key: key.to_string(), + }, + ) + }; + ColdDownloadGuard { + _held: lock.lock_owned().await, + _ref: reference, + } + } + + #[cfg(test)] + fn len(&self) -> usize { + self.repos + .lock() + .expect("cold download lock map poisoned") + .len() + } +} + impl RepoStore { #[cfg(any(test, feature = "test-harness"))] pub fn for_testing(repos_dir: PathBuf, lock_pool: PgPool) -> Self { @@ -155,6 +240,7 @@ impl RepoStore { lock_hold_timeout: LOCK_HOLD_TIMEOUT, lock_acquire_deadline: LOCK_ACQUIRE_DEADLINE, migrated: Arc::new(Mutex::new(HashSet::new())), + cold_downloads: ColdDownloadLocks::default(), #[cfg(test)] pre_unlock_gate: None, #[cfg(test)] @@ -166,6 +252,12 @@ impl RepoStore { /// If the repo exists locally but not yet in Tigris, a background upload is /// spawned to lazily migrate it (on-demand migration for pre-Tigris repos). /// Returns the local path to the bare repo. + /// + /// Concurrent cold reads of one repo share a single download: each caller + /// checks that the archive exists, then the first downloads under a per-repo + /// lock while the rest wait and read the tree it installs. A failed or + /// cancelled download is never handed to the waiters; the next one re-checks + /// and downloads for itself. pub async fn acquire(&self, owner_did: &str, repo_name: &str) -> Result { // Validate at the sink CodeQL watches (`rust/path-injection`), not only inside // `local_path()`, so `exists` and every later filesystem touch share one barrier. @@ -257,9 +349,41 @@ impl RepoStore { // Try downloading from Tigris if let Some(ref tigris) = self.tigris { if tigris.exists(&owner_slug, repo_name).await.unwrap_or(false) { + // One download per repo at a time: a burst of cold readers would + // otherwise each fetch and unpack the whole archive. The lock is + // taken only once the archive is known to exist, so a name with + // nothing stored never creates lock state. + let cold = self + .cold_downloads + .lock(&format!("{owner_slug}/{repo_name}")) + .await; + // Whoever held the lock before us may have installed the tree. + // Confirm it only when one is there. With no tree, confirm can + // only reach the store to resolve a marker left by a write, + // which has no timeout; skipping it keeps that call off this + // lock in the common case. A tree that does carry such a marker + // is still confirmed here, store call included, as on main. + if local_path.exists() { + let confirmed = self + .confirm_live_tree(&owner_slug, repo_name, local_path.clone()) + .await?; + if confirmed.exists() { + return Ok(confirmed.into_path_buf()); + } + } debug!(repo = %repo_name, "cache miss — downloading from tigris"); + // The lock rides into the extraction and is released when that + // returns, even if this caller's future is dropped first, so no + // second extraction of this repo can start beside it. tigris - .download(&owner_slug, repo_name, &local_path, None) + .download_to( + &owner_slug, + repo_name, + &local_path, + true, + None, + Some(Box::new(cold)), + ) .await .context("downloading repo from tigris")?; // Mark as migrated since we just downloaded it @@ -442,7 +566,7 @@ impl RepoStore { // in the ASYNC layer, armed for the whole download await and // disarmed only when `RepoSnapshot` takes ownership. let snapshot = tigris - .download_to(&owner_slug, repo_name, &local_path, false, None) + .download_to(&owner_slug, repo_name, &local_path, false, None, None) .await .map_err(|e| { anyhow::Error::new(RepoUnavailable).context(format!( @@ -5305,6 +5429,570 @@ pub(crate) mod tests { server.abort(); } + // ---- Cold-download lock map ---- + + #[tokio::test] + async fn a_cold_lock_entry_is_freed_when_its_holder_drops() { + let locks = ColdDownloadLocks::default(); + let guard = locks.lock("owner/repo").await; + assert_eq!(locks.len(), 1, "a held lock has an entry"); + drop(guard); + assert_eq!( + locks.len(), + 0, + "the entry must be freed once nobody holds or waits on it" + ); + } + + #[tokio::test] + async fn a_cancelled_cold_lock_waiter_does_not_strand_the_entry() { + let locks = ColdDownloadLocks::default(); + let guard = locks.lock("owner/repo").await; + let waiter = tokio::spawn({ + let locks = locks.clone(); + async move { locks.lock("owner/repo").await } + }); + tokio::time::sleep(Duration::from_millis(50)).await; + assert!( + !waiter.is_finished(), + "the waiter must park behind the holder" + ); + waiter.abort(); + let _ = waiter.await; + drop(guard); + assert_eq!( + locks.len(), + 0, + "a waiter cancelled while parked left its reference behind" + ); + } + + #[tokio::test] + async fn cold_locks_for_different_repos_do_not_wait_on_each_other() { + let locks = ColdDownloadLocks::default(); + let _a = locks.lock("owner/a").await; + let b = tokio::time::timeout(Duration::from_millis(500), locks.lock("owner/b")).await; + assert!( + b.is_ok(), + "a lock on one repo must not block a different repo" + ); + } + + #[tokio::test] + async fn one_repo_never_has_two_cold_lock_holders() { + let locks = ColdDownloadLocks::default(); + let guard = locks.lock("owner/repo").await; + let waiter = tokio::spawn({ + let locks = locks.clone(); + async move { locks.lock("owner/repo").await } + }); + tokio::time::sleep(Duration::from_millis(100)).await; + assert!( + !waiter.is_finished(), + "a second holder got the lock while the first still held it" + ); + assert_eq!(locks.len(), 1, "holder and waiter share one entry"); + drop(guard); + let second = tokio::time::timeout(Duration::from_secs(2), waiter) + .await + .expect("the waiter gets the lock once the holder drops") + .unwrap(); + assert_eq!(locks.len(), 1, "the waiter reuses the same entry"); + drop(second); + assert_eq!(locks.len(), 0); + } + + /// #487: concurrent cold reads of one repo must share a single archive + /// download. Without single-flight every caller runs its own GET, buffers the + /// whole archive and unpacks it, so N anonymous readers cost N archives. + #[sqlx::test] + async fn concurrent_cold_acquires_share_one_download(pool: PgPool) { + use axum::response::IntoResponse; + use std::sync::atomic::AtomicUsize; + + let mut archive_bytes = Vec::new(); + { + let dir = TempDir::new().unwrap(); + seed_bare_repo(dir.path()); + let encoder = zstd::stream::Encoder::new(&mut archive_bytes, 3).unwrap(); + let mut tar = tar::Builder::new(encoder); + tar.append_dir_all(".", dir.path()).unwrap(); + tar.into_inner().unwrap().finish().unwrap(); + } + let archive = Arc::new(archive_bytes); + let gets = Arc::new(AtomicUsize::new(0)); + + let app = axum::Router::new().route( + "/{*key}", + axum::routing::any({ + let gets = gets.clone(); + move |method: axum::http::Method| { + let archive = archive.clone(); + let gets = gets.clone(); + async move { + match method { + axum::http::Method::HEAD => axum::http::StatusCode::OK.into_response(), + axum::http::Method::GET => { + gets.fetch_add(1, Ordering::SeqCst); + // Hold the body long enough that every caller + // is in flight before the first one finishes. + tokio::time::sleep(Duration::from_millis(300)).await; + axum::body::Body::from(archive.as_ref().clone()).into_response() + } + _ => axum::http::StatusCode::METHOD_NOT_ALLOWED.into_response(), + } + } + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + + let opts = (*pool.connect_options()).clone(); + let repos = TempDir::new().unwrap(); + let store = Arc::new(RepoStore::for_testing_with_tigris( + repos.path().to_path_buf(), + no_reap_pool(&opts, 2).await, + TigrisClient::for_testing_with_endpoint("test-bucket", &endpoint), + )); + let owner = "did:key:z6MkColdFlightAAAAAAAAAAAAAAAAAAAAAAAAA"; + let repo = "cold-flight-repo"; + + const CALLERS: usize = 8; + let mut tasks = Vec::new(); + for _ in 0..CALLERS { + let store = store.clone(); + tasks.push(tokio::spawn( + async move { store.acquire(owner, repo).await }, + )); + } + for t in tasks { + let path = t.await.unwrap().expect("every cold reader gets the repo"); + assert!( + path.join("HEAD").exists(), + "the downloaded tree is installed" + ); + } + + assert_eq!( + gets.load(Ordering::SeqCst), + 1, + "{CALLERS} concurrent cold acquires of one repo must share one archive download" + ); + server.abort(); + } + + // ---- Single-flight cold download: failure, cancellation and bound paths ---- + + /// How one GET of the cold-download mock answers. + #[derive(Clone)] + enum ColdGet { + /// The whole archive after `delay`. + Whole(Duration), + /// HTTP 500. + Fail, + /// Half the archive, then no further progress. + HalfThenStall, + } + + /// An object-store mock for cold reads. GET number `i` answers per + /// `gets[i]` (the last plan repeats). Every HEAD answers 200, or 404 once + /// `hold_heads` is released when one is given. Counts both. + struct ColdMock { + endpoint: String, + heads: Arc, + gets: Arc, + server: tokio::task::JoinHandle<()>, + } + + impl ColdMock { + async fn start( + gets: Vec, + hold_heads: Option>, + ) -> Self { + use axum::response::IntoResponse; + let archive = { + let dir = TempDir::new().unwrap(); + seed_bare_repo(dir.path()); + Arc::new(crate::git::tigris::compress_repo(dir.path()).unwrap()) + }; + let heads = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let get_count = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let plans = Arc::new(gets); + let app = axum::Router::new().route( + "/{*key}", + axum::routing::any({ + let heads = heads.clone(); + let get_count = get_count.clone(); + move |method: axum::http::Method| { + let (archive, heads, get_count, plans, hold_heads) = ( + archive.clone(), + heads.clone(), + get_count.clone(), + plans.clone(), + hold_heads.clone(), + ); + async move { + if method == axum::http::Method::HEAD { + heads.fetch_add(1, Ordering::SeqCst); + return match hold_heads { + Some(release) => { + let _permit = release.acquire().await; + axum::http::StatusCode::NOT_FOUND.into_response() + } + None => axum::http::StatusCode::OK.into_response(), + }; + } + let n = get_count.fetch_add(1, Ordering::SeqCst); + let plan = plans[n.min(plans.len() - 1)].clone(); + let bytes = bytes::Bytes::from(archive.as_ref().clone()); + match plan { + ColdGet::Whole(delay) => { + tokio::time::sleep(delay).await; + axum::body::Body::from(bytes).into_response() + } + ColdGet::Fail => { + axum::http::StatusCode::INTERNAL_SERVER_ERROR.into_response() + } + ColdGet::HalfThenStall => { + let first = bytes.slice(..bytes.len() / 2); + let stream = futures::stream::unfold(0u8, move |step| { + let first = first.clone(); + async move { + if step == 0 { + Some((Ok::<_, std::io::Error>(first), 1)) + } else { + std::future::pending::<()>().await; + None + } + } + }); + axum::body::Body::from_stream(stream).into_response() + } + } + } + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + Self { + endpoint, + heads, + gets: get_count, + server, + } + } + + fn client(&self) -> TigrisClient { + TigrisClient::for_testing_with_endpoint("test-bucket", &self.endpoint) + } + + fn gets(&self) -> usize { + self.gets.load(Ordering::SeqCst) + } + + fn heads(&self) -> usize { + self.heads.load(Ordering::SeqCst) + } + } + + impl Drop for ColdMock { + fn drop(&mut self) { + self.server.abort(); + } + } + + async fn cold_store(pool: &PgPool, repos: &Path, client: TigrisClient) -> Arc { + let opts = (*pool.connect_options()).clone(); + Arc::new(RepoStore::for_testing_with_tigris( + repos.to_path_buf(), + no_reap_pool(&opts, 2).await, + client, + )) + } + + async fn wait_for(mut cond: impl FnMut() -> bool) -> bool { + for _ in 0..300 { + if cond() { + return true; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + false + } + + const COLD_OWNER: &str = "did:key:z6MkColdPathAAAAAAAAAAAAAAAAAAAAAAAAAA"; + + /// A leader cancelled while its GET body is still arriving releases the + /// repo: the next caller downloads on its own and gets the tree, and + /// nothing is left behind. + #[sqlx::test] + async fn a_leader_cancelled_mid_get_hands_the_repo_to_the_next_caller(pool: PgPool) { + let mock = ColdMock::start( + vec![ColdGet::HalfThenStall, ColdGet::Whole(Duration::ZERO)], + None, + ) + .await; + let repos = TempDir::new().unwrap(); + let store = cold_store(&pool, repos.path(), mock.client()).await; + let repo = "cancel-get"; + + let leader = tokio::spawn({ + let store = store.clone(); + async move { store.acquire(COLD_OWNER, repo).await } + }); + assert!( + wait_for(|| mock.gets() == 1).await, + "the leader never sent its GET" + ); + tokio::time::sleep(Duration::from_millis(100)).await; + leader.abort(); + let _ = leader.await; + + let path = tokio::time::timeout(Duration::from_secs(5), store.acquire(COLD_OWNER, repo)) + .await + .expect("the next caller must not stay blocked behind a cancelled leader") + .expect("the next caller downloads the repo itself"); + assert!(path.join("HEAD").exists()); + assert_eq!( + mock.gets(), + 2, + "one GET for the cancelled leader, one for the next caller" + ); + let parent = path.parent().unwrap(); + let spools = std::fs::read_dir(parent) + .unwrap() + .filter_map(|e| e.ok()) + .filter(|e| e.file_name().to_string_lossy().contains(".tmp-download.")) + .count(); + assert_eq!(spools, 0, "the cancelled leader left its spool behind"); + assert_eq!(store.cold_downloads.len(), 0, "the lock map kept an entry"); + } + + /// A leader cancelled while its extraction runs keeps the repo until that + /// extraction returns: a second caller does not start a second download + /// beside it, and gets the tree the first extraction installs. + #[sqlx::test] + async fn a_leader_cancelled_mid_extract_keeps_the_repo_until_the_extract_returns(pool: PgPool) { + let mock = ColdMock::start(vec![ColdGet::Whole(Duration::ZERO)], None).await; + let gate = Arc::new(crate::git::tigris::BlockingGate::shut()); + let repos = TempDir::new().unwrap(); + let store = cold_store( + &pool, + repos.path(), + mock.client().with_extract_gate(gate.clone()), + ) + .await; + let repo = "cancel-extract"; + + let leader = tokio::spawn({ + let store = store.clone(); + async move { store.acquire(COLD_OWNER, repo).await } + }); + assert!( + wait_for(|| mock.gets() == 1).await, + "the leader never sent its GET" + ); + // The body is tiny, so the leader is parked at the extraction gate well + // before this. + tokio::time::sleep(Duration::from_millis(300)).await; + leader.abort(); + let _ = leader.await; + + let second = tokio::spawn({ + let store = store.clone(); + async move { store.acquire(COLD_OWNER, repo).await } + }); + tokio::time::sleep(Duration::from_millis(300)).await; + let gets_while_extracting = mock.gets(); + gate.open(); + let path = tokio::time::timeout(Duration::from_secs(5), second) + .await + .expect("the second caller finishes once the extraction returns") + .unwrap() + .expect("the second caller gets the repo"); + assert_eq!( + gets_while_extracting, 1, + "a second download started while the cancelled leader's extraction still ran" + ); + assert!(path.join("HEAD").exists()); + assert_eq!( + mock.gets(), + 1, + "the installed tree must be reused, not downloaded again" + ); + } + + /// A failed download is the failing caller's alone: a caller waiting behind + /// it downloads for itself and succeeds. + #[sqlx::test] + async fn a_failed_leader_does_not_fail_the_waiting_caller(pool: PgPool) { + let mock = ColdMock::start(vec![ColdGet::Fail, ColdGet::Whole(Duration::ZERO)], None).await; + let repos = TempDir::new().unwrap(); + let store = cold_store(&pool, repos.path(), mock.client()).await; + let repo = "failed-leader"; + + let first = tokio::spawn({ + let store = store.clone(); + async move { store.acquire(COLD_OWNER, repo).await } + }); + let second = tokio::spawn({ + let store = store.clone(); + async move { store.acquire(COLD_OWNER, repo).await } + }); + let results = [first.await.unwrap(), second.await.unwrap()]; + let ok: Vec<_> = results.iter().filter_map(|r| r.as_ref().ok()).collect(); + assert_eq!( + ok.len(), + 1, + "exactly one caller hit the failing GET: {results:?}" + ); + assert!(ok[0].join("HEAD").exists(), "the other caller got the tree"); + assert_eq!(mock.gets(), 2); + } + + /// A leader with no timeout of its own whose GET stalls gives the repo up + /// after the stall bound, and reports an error rather than an absent repo; + /// a bounded caller behind it still gets the tree within its budget. + #[sqlx::test] + async fn a_stalled_leader_releases_the_repo_after_the_stall_bound(pool: PgPool) { + let mock = ColdMock::start( + vec![ColdGet::HalfThenStall, ColdGet::Whole(Duration::ZERO)], + None, + ) + .await; + let repos = TempDir::new().unwrap(); + let store = cold_store( + &pool, + repos.path(), + mock.client() + .with_get_stall_timeout(Duration::from_millis(300)), + ) + .await; + let repo = "stalled-leader"; + + let leader = tokio::spawn({ + let store = store.clone(); + async move { store.acquire(COLD_OWNER, repo).await } + }); + assert!( + wait_for(|| mock.gets() == 1).await, + "the leader never sent its GET" + ); + let second = tokio::time::timeout(Duration::from_secs(3), store.acquire(COLD_OWNER, repo)) + .await + .expect("a bounded caller behind a stalled leader must get the repo within its budget") + .expect("the bounded caller downloads the repo"); + assert!(second.join("HEAD").exists()); + let led = tokio::time::timeout(Duration::from_secs(3), leader) + .await + .expect("the stalled leader must give up") + .unwrap(); + assert!( + led.is_err(), + "a stalled download must surface as an error, not as an absent repo: {led:?}" + ); + } + + /// A name with no stored archive never creates lock state, even while its + /// existence check is still in flight. + #[sqlx::test] + async fn absent_names_create_no_cold_lock_state(pool: PgPool) { + let release = Arc::new(tokio::sync::Semaphore::new(0)); + let mock = ColdMock::start(vec![ColdGet::Fail], Some(release.clone())).await; + let repos = TempDir::new().unwrap(); + let store = cold_store(&pool, repos.path(), mock.client()).await; + + let mut calls = Vec::new(); + for i in 0..20 { + let store = store.clone(); + calls.push(tokio::spawn(async move { + store.acquire(COLD_OWNER, &format!("absent-{i}")).await + })); + } + assert!( + wait_for(|| mock.heads() == 20).await, + "every caller should be parked in its existence check" + ); + assert_eq!( + store.cold_downloads.len(), + 0, + "a caller took cold-download lock state before learning the repo exists" + ); + release.add_permits(64); + for call in calls { + let path = call + .await + .unwrap() + .expect("an absent repo resolves to its path"); + assert!(!path.exists(), "nothing is installed for an absent repo"); + } + assert_eq!(store.cold_downloads.len(), 0); + assert_eq!(mock.gets(), 0); + } + + /// Cold reads of two different repos run side by side. + #[sqlx::test] + async fn cold_reads_of_different_repos_do_not_serialize(pool: PgPool) { + let mock = ColdMock::start(vec![ColdGet::Whole(Duration::from_millis(400))], None).await; + let repos = TempDir::new().unwrap(); + let store = cold_store(&pool, repos.path(), mock.client()).await; + + let started = std::time::Instant::now(); + let a = tokio::spawn({ + let store = store.clone(); + async move { store.acquire(COLD_OWNER, "parallel-a").await } + }); + let b = tokio::spawn({ + let store = store.clone(); + async move { store.acquire(COLD_OWNER, "parallel-b").await } + }); + a.await.unwrap().expect("repo a"); + b.await.unwrap().expect("repo b"); + assert!( + started.elapsed() < Duration::from_millis(750), + "two repos' cold downloads ran one after the other ({:?})", + started.elapsed() + ); + } + + /// A tree left by an abandoned write (a marker naming no attempt) is + /// discarded and replaced by one shared download, and every caller is + /// served. + #[sqlx::test] + async fn an_abandoned_write_tree_is_replaced_by_one_shared_download(pool: PgPool) { + let mock = ColdMock::start(vec![ColdGet::Whole(Duration::from_millis(300))], None).await; + let repos = TempDir::new().unwrap(); + let store = cold_store(&pool, repos.path(), mock.client()).await; + let repo = "abandoned-write"; + let path = validated_repo_disk_path(repos.path(), COLD_OWNER, repo).unwrap(); + seed_bare_repo(&path); + quarantine_local_tree(&path, repo, None); + + let mut calls = Vec::new(); + for _ in 0..4 { + let store = store.clone(); + calls.push(tokio::spawn(async move { + store.acquire(COLD_OWNER, repo).await + })); + } + for call in calls { + call.await.unwrap().expect("every caller is served"); + } + assert_eq!( + mock.gets(), + 1, + "the replacement tree must be downloaded once" + ); + } + /// Build a store whose release-side upload lands on `mock` and gives up /// after 200ms, so a parked PUT reliably exceeds the bound. One lock-pool /// connection on purpose: with a single slot the backend pid is a direct diff --git a/crates/twigpine-node/src/git/tigris.rs b/crates/twigpine-node/src/git/tigris.rs index 20e4ba88..dd664925 100644 --- a/crates/twigpine-node/src/git/tigris.rs +++ b/crates/twigpine-node/src/git/tigris.rs @@ -70,11 +70,34 @@ fn classify_put_failure( } } +/// Default for [`TigrisClient::get_stall_timeout`]: equal to the default read +/// budget (`git_acquire_timeout_secs`), so a stalled archive GET is abandoned +/// within the time a bounded reader would wait for it anyway. +const GET_STALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + +/// Default compressed-archive byte ceiling, used when the operator does not set +/// one. Kept independent of the per-push pack ceiling: a repo accumulated over +/// many pushes can be larger than any one push. +pub const DEFAULT_MAX_ARCHIVE_BYTES: u64 = 2_147_483_648; + +/// The compressed archive exceeded the configured byte ceiling. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("compressed tigris archive exceeds the configured byte ceiling of {limit} bytes")] +pub struct ArchiveTooLarge { + /// The configured compressed-archive byte ceiling. + pub limit: u64, +} + /// Wrapper around the S3 client with the configured bucket. #[derive(Clone)] pub struct TigrisClient { s3: S3Client, bucket: String, + /// Compressed-archive byte ceiling enforced while a download is spooled. + max_archive_bytes: u64, + /// How long an archive GET may go without progress (no response yet, or no + /// new body chunk) before it is abandoned as stalled. + get_stall_timeout: std::time::Duration, /// Test-only seam: when set, the blocking compression inside `upload_tracked` /// parks on this barrier. That is the ONLY window in which a publish attempt /// can be cancelled with `PublishStage::PreparingArchive` still holding, and @@ -82,6 +105,11 @@ pub struct TigrisClient { /// test-sized repo finishes in microseconds. #[cfg(test)] compress_gate: Option>, + /// Test-only seam: when set, the blocking extraction inside `download_to` + /// parks here before unpacking, so a test can cancel a caller while its + /// extraction is still running. + #[cfg(test)] + extract_gate: Option>, } /// A gate a BLOCKING thread parks on until a test opens it. @@ -124,16 +152,20 @@ impl BlockingGate { impl TigrisClient { /// Create a new client. Uses AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and - /// AWS_ENDPOINT_URL_S3 env vars — all set automatically by Fly for Tigris buckets. - pub async fn new(bucket: &str) -> Result { + /// AWS_ENDPOINT_URL_S3 env vars, all set automatically by Fly for Tigris buckets. + pub async fn new(bucket: &str, max_archive_bytes: u64) -> Result { let config = aws_config::load_defaults(aws_config::BehaviorVersion::latest()).await; let s3 = S3Client::new(&config); info!(bucket = %bucket, "tigris storage client initialized"); Ok(Self { s3, bucket: bucket.to_string(), + max_archive_bytes, + get_stall_timeout: GET_STALL_TIMEOUT, #[cfg(test)] compress_gate: None, + #[cfg(test)] + extract_gate: None, }) } @@ -161,10 +193,36 @@ impl TigrisClient { Self { s3: S3Client::from_conf(config), bucket: bucket.to_string(), + max_archive_bytes: DEFAULT_MAX_ARCHIVE_BYTES, + get_stall_timeout: GET_STALL_TIMEOUT, compress_gate: None, + extract_gate: None, } } + /// Test-only: enforce `limit` as the compressed-archive byte ceiling. + #[cfg(test)] + pub fn with_max_archive_bytes(mut self, limit: u64) -> Self { + self.max_archive_bytes = limit; + self + } + + /// Test-only: park this client's blocking extraction on `gate` until the + /// holder opens it. + #[cfg(test)] + pub fn with_extract_gate(mut self, gate: Arc) -> Self { + self.extract_gate = Some(gate); + self + } + + /// Test-only: abandon an archive GET after `limit` without progress, so a + /// stall test does not wait out the production bound. + #[cfg(test)] + pub fn with_get_stall_timeout(mut self, limit: std::time::Duration) -> Self { + self.get_stall_timeout = limit; + self + } + /// Test-only: park this client's blocking compression on `gate` until the /// holder releases it, so a cancellation can be aimed at /// [`PublishStage::PreparingArchive`] rather than at the PUT. @@ -573,9 +631,16 @@ impl TigrisClient { local_path: &super::repo_store::ValidatedRepoDiskPath, swap_authority: Option>, ) -> Result<()> { - self.download_to(owner_slug, repo_name, local_path, true, swap_authority) - .await - .map(|_| ()) + self.download_to( + owner_slug, + repo_name, + local_path, + true, + swap_authority, + None, + ) + .await + .map(|_| ()) } /// Download a repo archive from Tigris and extract it, returning the @@ -586,6 +651,10 @@ impl TigrisClient { /// into a fresh temp directory under `target`'s parent (a non-mutating /// snapshot read; returns the temp dir, which the caller owns and cleans /// up). The snapshot form never touches the live repo path. + /// + /// `hold` is dropped only after the blocking extraction returns, even when + /// this future is dropped first. A caller passes a lock guard here to keep + /// it for exactly as long as the extraction it started. pub async fn download_to( &self, owner_slug: &str, @@ -593,25 +662,85 @@ impl TigrisClient { target: &super::repo_store::ValidatedRepoDiskPath, publish: bool, swap_authority: Option>, + hold: Option>, ) -> Result { + use tokio::io::AsyncWriteExt; + let key = Self::repo_key(owner_slug, repo_name); debug!(key = %key, path = %target.as_path().display(), "downloading repo from tigris"); + let stall = self.get_stall_timeout; - let resp = self - .s3 - .get_object() - .bucket(&self.bucket) - .key(&key) - .send() - .await - .context(format!("tigris GET {key}"))?; + let resp = tokio::time::timeout( + stall, + self.s3.get_object().bucket(&self.bucket).key(&key).send(), + ) + .await + .map_err(|_| anyhow::anyhow!("tigris GET {key}: no response within {stall:?}"))? + .context(format!("tigris GET {key}"))?; + + // A declared length over the ceiling fails before the spool exists. It + // is only an early-out, never proof of size: a chunked or misdeclared + // body is still bounded by the running count below. + if resp + .content_length() + .and_then(|len| u64::try_from(len).ok()) + .is_some_and(|len| len > self.max_archive_bytes) + { + return Err(ArchiveTooLarge { + limit: self.max_archive_bytes, + } + .into()); + } - let data = resp - .body - .collect() + // The body goes to a spool file beside the repo as it arrives, so memory + // does not grow with the archive. The guard owns the file from before it + // exists: a cancelled or failed download removes it here, and once it + // moves into the extraction below, the blocking task removes it. + let parent = target.parent().context("repo path has no parent")?; + std::fs::create_dir_all(parent).context("creating parent dir")?; + let file_name = target + .file_name() + .context("repo path has no file name")? + .to_string_lossy(); + let spool = SpoolFile { + path: parent.join(format!( + ".{file_name}.tmp-download.{}", + uuid::Uuid::new_v4() + )), + }; + let mut file = tokio::fs::File::create(&spool.path) .await - .context("reading tigris response body")? - .into_bytes(); + .context("creating download spool file")?; + let mut body = resp.body; + let mut received = 0u64; + loop { + // Bounded per wait, not in total: a slow archive that keeps arriving + // completes, a stalled one is abandoned. + let chunk = tokio::time::timeout(stall, body.try_next()) + .await + .map_err(|_| anyhow::anyhow!("tigris GET {key}: body stalled for {stall:?}"))? + .context("reading tigris response body")?; + match chunk { + Some(bytes) => { + let len = bytes.len() as u64; + if len > self.max_archive_bytes.saturating_sub(received) { + return Err(ArchiveTooLarge { + limit: self.max_archive_bytes, + } + .into()); + } + file.write_all(&bytes) + .await + .context("writing download spool file")?; + received += len; + } + None => break, + } + } + // A tokio write can return before its bytes reach the file; flush so the + // blocking reader below never sees a truncated archive. + file.flush().await.context("flushing download spool file")?; + drop(file); // The snapshot temp dir is decided HERE, in the async layer, before the // extraction runs. Cleanup ownership moves into the blocking task so a @@ -619,12 +748,6 @@ impl TigrisClient { let snapshot_tmp = if publish { None } else { - let parent = target.parent().context("snapshot path has no parent")?; - std::fs::create_dir_all(parent).context("creating parent dir")?; - let file_name = target - .file_name() - .context("snapshot path has no file name")? - .to_string_lossy(); Some(parent.join(format!( ".{file_name}.tmp-snapshot.{}", uuid::Uuid::new_v4() @@ -632,13 +755,22 @@ impl TigrisClient { }; // Extract tar.zst to a directory. + #[cfg(test)] + let extract_gate = self.extract_gate.clone(); let extracted = tokio::task::spawn_blocking({ let target = target.clone(); let snapshot_tmp = snapshot_tmp.clone(); move || -> Result { + #[cfg(test)] + if let Some(gate) = extract_gate { + gate.wait(); + } let result = (|| -> Result { + let data = std::io::BufReader::new( + std::fs::File::open(&spool.path).context("opening download spool file")?, + ); if publish { - decompress_repo(&data, &target, swap_authority.as_ref())?; + decompress_repo(data, &target, swap_authority.as_ref())?; return Ok(DownloadExtract::Published(())); } // Non-mutating snapshot: unpack into the temp dir decided above. @@ -646,7 +778,7 @@ impl TigrisClient { let tmp_dir = snapshot_tmp.expect("snapshot path was decided above"); std::fs::create_dir_all(&tmp_dir).context("creating temp extract dir")?; let unpack = (|| -> Result<()> { - let decoder = zstd::stream::Decoder::new(&data[..])?; + let decoder = zstd::stream::Decoder::new(data)?; let mut archive = tar::Archive::new(decoder); archive.unpack(&tmp_dir).context("unpacking tar.zst")?; Ok(()) @@ -657,6 +789,11 @@ impl TigrisClient { } Ok(DownloadExtract::Snapshot(TempSnapshotDir { path: tmp_dir })) })(); + // Released only now, after the extraction returned: the spool, + // then the caller's hold, which may be a lock that must outlive + // a caller whose future was dropped mid-extraction. + drop(spool); + drop(hold); result } }) @@ -724,6 +861,17 @@ impl Drop for TempSnapshotDir { } } +/// A download's on-disk copy of the archive body, removed when dropped. +struct SpoolFile { + path: PathBuf, +} + +impl Drop for SpoolFile { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } +} + /// What [`TigrisClient::download_to`] produced. pub enum DownloadExtract { /// Published into the validated live repo path. @@ -740,7 +888,7 @@ pub enum DownloadExtract { /// good existing copy at `local_path` — on failure we discard the temp dir and /// leave `local_path` exactly as it was. fn decompress_repo( - data: &[u8], + data: impl std::io::Read, local_path: &super::repo_store::ValidatedRepoDiskPath, swap_authority: Option<&Arc>, ) -> Result<()> { @@ -992,4 +1140,460 @@ mod tests { Err(payload) => std::panic::resume_unwind(payload), } } + + // ---- Streaming download: the archive body goes to a spool file, not RAM ---- + + use std::sync::atomic::Ordering; + use std::time::Duration; + + /// How a test GET serves the archive body. + #[derive(Clone)] + enum BodyPlan { + /// The whole archive at once. + Whole, + /// The first half, then nothing until `release` is notified, then the rest. + HalfThenGate(Arc), + /// The first half, then the body never makes progress again. + HalfThenStall, + /// The archive split into `chunks` pieces, one every `every`. + Drip { chunks: usize, every: Duration }, + } + + /// An in-process HTTP server answering every GET with `archive` per `plan`. + async fn serve_archive( + archive: Vec, + plan: BodyPlan, + ) -> (String, tokio::task::JoinHandle<()>) { + use axum::response::IntoResponse; + let archive = Arc::new(archive); + let app = axum::Router::new().route( + "/{*key}", + axum::routing::any(move |method: axum::http::Method| { + let archive = archive.clone(); + let plan = plan.clone(); + async move { + if method != axum::http::Method::GET { + return axum::http::StatusCode::OK.into_response(); + } + let bytes = bytes::Bytes::from(archive.as_ref().clone()); + let half = bytes.len() / 2; + let body = match plan { + BodyPlan::Whole => axum::body::Body::from(bytes), + BodyPlan::HalfThenGate(release) => { + let first = bytes.slice(..half); + let rest = bytes.slice(half..); + let stream = futures::stream::unfold(0u8, move |step| { + let (first, rest, release) = + (first.clone(), rest.clone(), release.clone()); + async move { + match step { + 0 => Some((Ok::<_, std::io::Error>(first), 1)), + 1 => { + release.notified().await; + Some((Ok(rest), 2)) + } + _ => None, + } + } + }); + axum::body::Body::from_stream(stream) + } + BodyPlan::HalfThenStall => { + let first = bytes.slice(..half); + let stream = futures::stream::unfold(0u8, move |step| { + let first = first.clone(); + async move { + if step == 0 { + Some((Ok::<_, std::io::Error>(first), 1)) + } else { + std::future::pending::<()>().await; + None + } + } + }); + axum::body::Body::from_stream(stream) + } + BodyPlan::Drip { chunks, every } => { + let size = bytes.len().div_ceil(chunks); + let stream = futures::stream::unfold(0usize, move |at| { + let bytes = bytes.clone(); + async move { + if at >= bytes.len() { + return None; + } + tokio::time::sleep(every).await; + let end = (at + size).min(bytes.len()); + Some((Ok::<_, std::io::Error>(bytes.slice(at..end)), end)) + } + }); + axum::body::Body::from_stream(stream) + } + }; + (axum::http::StatusCode::OK, body).into_response() + } + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + (endpoint, server) + } + + /// A bare-repo-shaped tree carrying `payload` bytes, compressed the way an + /// upload stores it. + fn archive_with_payload(payload: &[u8]) -> Vec { + let dir = tempfile::TempDir::new().unwrap(); + std::fs::create_dir_all(dir.path().join("objects/info")).unwrap(); + std::fs::create_dir_all(dir.path().join("refs/heads")).unwrap(); + std::fs::write(dir.path().join("HEAD"), "ref: refs/heads/main\n").unwrap(); + std::fs::write(dir.path().join("PAYLOAD"), payload).unwrap(); + compress_repo(dir.path()).unwrap() + } + + /// Bytes that do not compress, so the archive is about as large as `len`. + fn incompressible(len: usize) -> Vec { + let mut x: u64 = 0x9E37_79B9_7F4A_7C15; + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + x as u8 + }) + .collect() + } + + fn entries_named(dir: &Path, marker: &str) -> Vec { + std::fs::read_dir(dir) + .map(|rd| { + rd.filter_map(|e| e.ok().map(|e| e.path())) + .filter(|p| p.to_string_lossy().contains(marker)) + .collect() + }) + .unwrap_or_default() + } + + /// Poll until a nonempty spool file for the download exists under `dir`. + async fn wait_for_spool(dir: &Path) -> bool { + for _ in 0..200 { + let found = entries_named(dir, ".tmp-download.") + .into_iter() + .any(|p| std::fs::metadata(&p).map(|m| m.len() > 0).unwrap_or(false)); + if found { + return true; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + false + } + + fn snapshot_target(repos: &Path) -> super::super::repo_store::ValidatedRepoDiskPath { + super::super::repo_store::validated_repo_disk_path(repos, "did:key:z6MkSpool", "spool") + .expect("test repo path must validate") + } + + /// The body is written to disk as it arrives: while half of it has been sent + /// and the rest is held back, a nonempty spool file already exists beside + /// the repo. Buffering the body in memory leaves nothing on disk until the + /// whole of it has arrived. + #[tokio::test] + async fn download_spools_the_body_to_disk_as_it_arrives() { + let release = Arc::new(tokio::sync::Notify::new()); + let archive = archive_with_payload(&incompressible(256 * 1024)); + let (endpoint, server) = + serve_archive(archive, BodyPlan::HalfThenGate(release.clone())).await; + let repos = tempfile::TempDir::new().unwrap(); + let target = snapshot_target(repos.path()); + let parent = target.parent().unwrap().to_path_buf(); + let client = TigrisClient::for_testing_with_endpoint("b", &endpoint); + + let task = tokio::spawn(async move { + client + .download_to("owner", "spool", &target, false, None, None) + .await + }); + let spooled = wait_for_spool(&parent).await; + release.notify_one(); + let out = task + .await + .unwrap() + .expect("the download completes once released"); + drop(out); + server.abort(); + assert!( + spooled, + "half the body was sent and the rest held back, yet no nonempty spool file \ + existed: the body is being buffered in memory instead of streamed to disk" + ); + } + + /// A download whose future is dropped mid-body leaves no spool behind. + #[tokio::test] + async fn a_cancelled_download_leaves_no_spool_file() { + let release = Arc::new(tokio::sync::Notify::new()); + let archive = archive_with_payload(&incompressible(256 * 1024)); + let (endpoint, server) = + serve_archive(archive, BodyPlan::HalfThenGate(release.clone())).await; + let repos = tempfile::TempDir::new().unwrap(); + let target = snapshot_target(repos.path()); + let parent = target.parent().unwrap().to_path_buf(); + let client = TigrisClient::for_testing_with_endpoint("b", &endpoint); + + let task = tokio::spawn(async move { + client + .download_to("owner", "spool", &target, false, None, None) + .await + }); + assert!( + wait_for_spool(&parent).await, + "the spool never appeared, so cancellation cleanup cannot be observed" + ); + task.abort(); + let _ = task.await; + server.abort(); + assert!( + entries_named(&parent, ".tmp-download.").is_empty(), + "a download cancelled mid-body left its spool file on disk" + ); + } + + /// A chunked stream carries no dependable declared length, so the byte + /// ceiling is enforced by the running count as the body is spooled. The + /// exactly-at-cap control proves the boundary itself is inclusive. + #[tokio::test] + async fn an_oversized_archive_is_rejected_while_streaming_without_extraction() { + let payload = incompressible(256 * 1024); + let archive = archive_with_payload(&payload); + let archive_len = archive.len() as u64; + let (endpoint, server) = serve_archive( + archive, + BodyPlan::Drip { + chunks: 9, + every: Duration::from_millis(1), + }, + ) + .await; + let repos = tempfile::TempDir::new().unwrap(); + let target = snapshot_target(repos.path()); + let parent = target.parent().unwrap().to_path_buf(); + + let over_cap = archive_len - 1; + let client = TigrisClient::for_testing_with_endpoint("b", &endpoint) + .with_max_archive_bytes(over_cap); + let err = client + .download_to("owner", "spool", &target, true, None, None) + .await + .err() + .expect("an archive over the byte ceiling must be rejected before extraction"); + let typed = err + .downcast_ref::() + .expect("the rejection must be the typed archive-size error"); + assert_eq!(typed.limit, over_cap); + assert!( + err.to_string().contains(&over_cap.to_string()), + "the error must name the byte ceiling: {err}" + ); + assert!( + !target.exists(), + "an over-cap archive must not install a target tree" + ); + assert!( + entries_named(&parent, ".tmp-download.").is_empty(), + "an over-cap download left its partial spool file" + ); + assert!( + entries_named(&parent, ".tmp-extract.").is_empty(), + "an over-cap download reached extraction" + ); + + let exact = TigrisClient::for_testing_with_endpoint("b", &endpoint) + .with_max_archive_bytes(archive_len); + exact + .download_to("owner", "spool", &target, true, None, None) + .await + .expect("an archive exactly at the byte ceiling downloads and extracts"); + server.abort(); + assert_eq!(std::fs::read(target.join("PAYLOAD")).unwrap(), payload); + } + + /// A body that is not a valid archive fails the download and leaves neither + /// the spool nor a half-unpacked extract dir behind. + #[tokio::test] + async fn a_corrupt_archive_leaves_no_spool_or_extract_dir() { + let (endpoint, server) = + serve_archive(b"not a zstd archive".repeat(64), BodyPlan::Whole).await; + let repos = tempfile::TempDir::new().unwrap(); + let target = snapshot_target(repos.path()); + let parent = target.parent().unwrap().to_path_buf(); + let client = TigrisClient::for_testing_with_endpoint("b", &endpoint); + + let out = client.download("owner", "spool", &target, None).await; + server.abort(); + assert!(out.is_err(), "a corrupt archive must fail the download"); + assert!( + entries_named(&parent, ".tmp-download.").is_empty(), + "a failed extract left its spool file" + ); + assert!( + entries_named(&parent, ".tmp-extract.").is_empty(), + "a failed extract left its temp dir" + ); + assert!( + !target.exists(), + "a failed extract must not install anything" + ); + } + + /// A multi-megabyte archive survives the spool round trip byte for byte. + #[tokio::test] + async fn a_large_archive_round_trips_through_the_spool() { + let payload = incompressible(4 * 1024 * 1024); + let archive = archive_with_payload(&payload); + let (endpoint, server) = serve_archive(archive, BodyPlan::Whole).await; + let repos = tempfile::TempDir::new().unwrap(); + let target = snapshot_target(repos.path()); + let client = TigrisClient::for_testing_with_endpoint("b", &endpoint); + + client + .download("owner", "spool", &target, None) + .await + .expect("the archive downloads and installs"); + server.abort(); + assert_eq!( + std::fs::read(target.join("PAYLOAD")).unwrap(), + payload, + "the installed tree must match the archived bytes exactly" + ); + assert!(entries_named(target.parent().unwrap(), ".tmp-download.").is_empty()); + } + + /// A value handed to `download_to` as the hold is released only once the + /// blocking extraction has installed the tree, not when the async layer + /// hands off. That is what lets a caller's lock outlive the caller's future. + #[tokio::test] + async fn the_hold_is_released_only_after_extraction_installs_the_tree() { + struct Probe { + live: PathBuf, + installed_at_drop: Arc, + dropped: Arc, + } + impl Drop for Probe { + fn drop(&mut self) { + self.installed_at_drop + .store(self.live.join("HEAD").exists(), Ordering::SeqCst); + self.dropped.store(true, Ordering::SeqCst); + } + } + + let archive = archive_with_payload(b"hold"); + let (endpoint, server) = serve_archive(archive, BodyPlan::Whole).await; + let repos = tempfile::TempDir::new().unwrap(); + let target = snapshot_target(repos.path()); + let installed_at_drop = Arc::new(AtomicBool::new(false)); + let dropped = Arc::new(AtomicBool::new(false)); + let probe = Probe { + live: target.as_path().to_path_buf(), + installed_at_drop: installed_at_drop.clone(), + dropped: dropped.clone(), + }; + let client = TigrisClient::for_testing_with_endpoint("b", &endpoint); + + client + .download_to("owner", "spool", &target, true, None, Some(Box::new(probe))) + .await + .expect("the archive downloads and installs"); + server.abort(); + assert!( + dropped.load(Ordering::SeqCst), + "the hold was never released" + ); + assert!( + installed_at_drop.load(Ordering::SeqCst), + "the hold was released before extraction installed the tree" + ); + } + + /// A GET whose body stops making progress is abandoned after the stall bound, + /// and leaves no spool behind. + #[tokio::test] + async fn a_stalled_body_is_abandoned_after_the_stall_bound() { + let archive = archive_with_payload(&incompressible(256 * 1024)); + let (endpoint, server) = serve_archive(archive, BodyPlan::HalfThenStall).await; + let repos = tempfile::TempDir::new().unwrap(); + let target = snapshot_target(repos.path()); + let parent = target.parent().unwrap().to_path_buf(); + let client = TigrisClient::for_testing_with_endpoint("b", &endpoint) + .with_get_stall_timeout(Duration::from_millis(300)); + + let out = tokio::time::timeout( + Duration::from_secs(5), + client.download("owner", "spool", &target, None), + ) + .await; + server.abort(); + let out = out.expect("a stalled body must be abandoned well inside 5s"); + assert!(out.is_err(), "a stalled body must fail the download"); + assert!( + entries_named(&parent, ".tmp-download.").is_empty(), + "an abandoned download left its spool file" + ); + } + + /// A GET that never answers at all is abandoned after the stall bound too: + /// the wait for the response is bounded, not only the wait for each chunk. + #[tokio::test] + async fn a_get_that_never_answers_is_abandoned_after_the_stall_bound() { + use axum::response::IntoResponse; + let app = axum::Router::new().route( + "/{*key}", + axum::routing::any(|| async { + std::future::pending::<()>().await; + axum::http::StatusCode::OK.into_response() + }), + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port()); + let server = tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let repos = tempfile::TempDir::new().unwrap(); + let target = snapshot_target(repos.path()); + let client = TigrisClient::for_testing_with_endpoint("b", &endpoint) + .with_get_stall_timeout(Duration::from_millis(300)); + + let out = tokio::time::timeout( + Duration::from_secs(5), + client.download("owner", "spool", &target, None), + ) + .await; + server.abort(); + let out = out.expect("a GET that never answered must be given up on well inside 5s"); + assert!(out.is_err(), "an unanswered GET must fail the download"); + } + + /// The stall bound limits time WITHOUT PROGRESS, not total time: a body that + /// keeps arriving completes even though it takes several stall bounds. + #[tokio::test] + async fn a_slow_but_progressing_body_is_not_cut_off() { + let archive = archive_with_payload(&incompressible(64 * 1024)); + let (endpoint, server) = serve_archive( + archive, + BodyPlan::Drip { + chunks: 15, + every: Duration::from_millis(100), + }, + ) + .await; + let repos = tempfile::TempDir::new().unwrap(); + let target = snapshot_target(repos.path()); + let client = TigrisClient::for_testing_with_endpoint("b", &endpoint) + .with_get_stall_timeout(Duration::from_millis(300)); + + let out = client.download("owner", "spool", &target, None).await; + server.abort(); + out.expect("a body that keeps making progress must not be abandoned"); + assert!(target.join("HEAD").exists()); + } } diff --git a/crates/twigpine-node/src/lib.rs b/crates/twigpine-node/src/lib.rs index 9886400b..ef18650c 100644 --- a/crates/twigpine-node/src/lib.rs +++ b/crates/twigpine-node/src/lib.rs @@ -394,7 +394,9 @@ pub async fn run() -> Result<()> { // Initialize Tigris S3 client if bucket is configured let tigris = if !config.tigris_bucket.is_empty() { - match git::tigris::TigrisClient::new(&config.tigris_bucket).await { + match git::tigris::TigrisClient::new(&config.tigris_bucket, config.max_tigris_archive_bytes) + .await + { Ok(client) => { info!(bucket = %config.tigris_bucket, "tigris storage enabled"); Some(client) @@ -1079,7 +1081,12 @@ async fn run_admin_command(command: config::Command, config: &Config) -> Result< { None } else { - match git::tigris::TigrisClient::new(&config.tigris_bucket).await { + match git::tigris::TigrisClient::new( + &config.tigris_bucket, + config.max_tigris_archive_bytes, + ) + .await + { Ok(client) => Some(client), Err(e) => { // Fail closed: without the configured store we cannot