//! Snapshot downloads: what the file is, how it is compressed, and the limits around producing it. //! //! The export is first written to a private directory by the vault, then streamed to the client, //! compressed on the fly when it is not already a compressed format. The decision uses both the //! manifest hints and the first bytes of the real file; the bytes win, because hints are written by //! many producers and one of them (a legacy Restic commit) writes none. use crate::auth::{AuditAction, AuditOutcome, AuditResource, Principal}; use crate::db::Db; use axum::body::Bytes; use futures_core::Stream; use std::io; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use uuid::Uuid; pub const EXPORT_PREFIX: &str = "tessera-export-"; const DEFAULT_CONCURRENCY: usize = 2; const DEFAULT_MARGIN: u64 = 512 * 1024 * 1024; /// How a snapshot is delivered. #[derive(Debug, PartialEq, Eq)] pub struct Plan { /// File extension of the download, without the dot. pub extension: &'static str, /// Compress with gzip while streaming. Formats that are already compressed pass through unchanged. pub compress: bool, pub content_type: &'static str, } fn plan_of(extension: &'static str, compress: bool) -> Plan { let gz = extension.ends_with("gz"); Plan { extension, compress, content_type: if gz || compress { "application/gzip" } else { "application/octet-stream" } } } /// Decide the delivery from the manifest `restore_hints` and the first bytes of the exported file. pub fn plan(hints: &serde_json::Value, head: &[u8]) -> Plan { let format = hints.get("format").and_then(|f| f.as_str()).unwrap_or(""); let starts = |magic: &[u8]| head.starts_with(magic); // Already compressed or a self-compressing dump: send the bytes untouched. if starts(&[0x1f, 0x8b]) { let ext = match format { "tar" => "tar.gz", "plain" | "sql_gzip" => "sql.gz", _ => "gz", }; return plan_of(ext, false); } if starts(b"PGDMP") { return plan_of("dump", false); // pg_dump -Fc compresses its own data } if starts(&[0x28, 0xb5, 0x2f, 0xfd]) { return plan_of("zst", false); } if starts(&[0xfd, b'7', b'z', b'X', b'Z', 0x00]) { return plan_of("xz", false); } if starts(b"BZh") { return plan_of("bz2", false); } if starts(b"PK\x03\x04") { return plan_of("zip", false); } // Compressible content. if starts(b"SQLite format 3\0") || format == "sqlite" { return plan_of("sqlite.gz", true); } if head.len() > 262 && &head[257..262] == b"ustar" || format == "tar" { return plan_of("tar.gz", true); } match format { "plain" | "sql" => plan_of("sql.gz", true), "tessera-fs-v1" => plan_of("tessera-fs.gz", true), _ => plan_of("dump.gz", true), } } /// Limits on how many exports run at once and how much disk one may need. pub struct ExportGate { permits: Arc, /// Free space that must remain after the export has been written. min_free: u64, } pub enum Refused { /// Too many exports are already running. Busy, /// Not enough free disk for this snapshot. NoSpace, } impl ExportGate { pub fn new(concurrency: usize, min_free: u64) -> Self { Self { permits: Arc::new(Semaphore::new(concurrency)), min_free } } pub fn from_env() -> Self { let number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()); Self::new( number("TESSERA_EXPORT_CONCURRENCY").map_or(DEFAULT_CONCURRENCY, |n| n.clamp(1, 64) as usize), number("TESSERA_EXPORT_MIN_FREE_BYTES").unwrap_or(DEFAULT_MARGIN), ) } /// Admit one export of about `size` bytes into `dir`. The permit lives as long as the response body. pub fn admit(&self, dir: &std::path::Path, size: u64) -> Result { let permit = self.permits.clone().try_acquire_owned().map_err(|_| Refused::Busy)?; match free_bytes(dir) { // `size` is the snapshot's recorded size; when a producer did not record one it is 0 and the margin alone applies. Some(free) if free < size.saturating_add(self.min_free) => Err(Refused::NoSpace), _ => Ok(permit), } } } #[cfg(unix)] fn free_bytes(dir: &std::path::Path) -> Option { let stat = rustix::fs::statvfs(dir).ok()?; Some(stat.f_bavail.saturating_mul(stat.f_frsize)) } #[cfg(not(unix))] fn free_bytes(_dir: &std::path::Path) -> Option { None } /// Remove export directories a crash left behind. Only directories with our own prefix, only directly /// inside `data_dir`; run before the listener starts. Older `.tmp*` leftovers are deliberately not touched. pub fn sweep_stale(data_dir: &std::path::Path) -> usize { let Ok(entries) = std::fs::read_dir(data_dir) else { return 0 }; let mut removed = 0; for entry in entries.flatten() { let name = entry.file_name(); let is_ours = name.to_str().is_some_and(|n| n.starts_with(EXPORT_PREFIX)); let is_dir = entry.file_type().is_ok_and(|t| t.is_dir()); if is_ours && is_dir && std::fs::remove_dir_all(entry.path()).is_ok() { removed += 1; } } removed } /// Owns everything an in-flight download needs and reports how it ended. Dropping it (the stream ended, /// the client went away, or the response was discarded) releases the permit and deletes the export. pub struct Guarded { inner: Pin>, _permit: OwnedSemaphorePermit, _dir: tempfile::TempDir, db: Db, principal: Principal, snapshot: Uuid, request: Uuid, completed: bool, failed: bool, } impl Guarded { pub fn new(inner: S, permit: OwnedSemaphorePermit, dir: tempfile::TempDir, db: Db, principal: Principal, snapshot: Uuid, request: Uuid) -> Self { Self { inner: Box::pin(inner), _permit: permit, _dir: dir, db, principal, snapshot, request, completed: false, failed: false } } } impl>> Stream for Guarded { type Item = io::Result; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let polled = self.inner.as_mut().poll_next(cx); match &polled { Poll::Ready(None) => self.completed = true, Poll::Ready(Some(Err(_))) => self.failed = true, _ => {} } polled } } impl Drop for Guarded { fn drop(&mut self) { // "Finished" means the body was handed to the connection, not that a file reached a disk. let (action, outcome) = if self.completed && !self.failed { (AuditAction::ExportFinished, AuditOutcome::Succeeded) } else { (AuditAction::ExportDisconnected, AuditOutcome::Failed) }; if let Err(error) = self.db.audit_event(&self.principal, action, AuditResource::Snapshot(self.snapshot), outcome, self.request) { tracing::error!("could not audit the end of an export: {error:#}"); } } } #[cfg(test)] mod tests { use super::*; use serde_json::json; fn ustar() -> Vec { let mut block = vec![0u8; 512]; block[257..262].copy_from_slice(b"ustar"); block } #[test] fn every_producer_of_a_snapshot_gets_the_right_delivery() { let gz = [0x1f, 0x8b, 8, 0]; let cases: Vec<(&str, serde_json::Value, Vec, &str, bool)> = vec![ ("hub database orbit, postgres plain SQL", json!({"engine": "postgres", "format": "plain"}), b"-- PostgreSQL dump\n".to_vec(), "sql.gz", true), ("hub database orbit, mysql plain SQL", json!({"engine": "mysql", "format": "plain"}), b"-- MySQL dump\n".to_vec(), "sql.gz", true), ("agent capture, postgres custom", json!({"engine": "postgres", "format": "custom", "sha256": "x"}), b"PGDMP\x01\x0e\x00".to_vec(), "dump", false), ("hub postgres provider, custom", json!({"format": "custom", "restore_command_hint": "pg_restore"}), b"PGDMP\x01".to_vec(), "dump", false), ("restic filesystem, tar by hint", json!({"format": "tar"}), ustar(), "tar.gz", true), ("restic filesystem snapshot with no hint but a tar payload", serde_json::Value::Null, ustar(), "tar.gz", true), ("hub filesystem orbit archive", json!({"paths": [], "format": "tessera-fs-v1"}), b"a/b\0\x03\0\0\0\0\0\0\0xyz".to_vec(), "tessera-fs.gz", true), ("sqlite database", json!({"format": "sqlite"}), b"SQLite format 3\0....".to_vec(), "sqlite.gz", true), ("SQL that is already gzip", json!({"format": "sql_gzip"}), gz.to_vec(), "sql.gz", false), ("hint says plain SQL but the file is gzip: no double compression", json!({"format": "plain"}), gz.to_vec(), "sql.gz", false), ("a tar that is already gzip", json!({"format": "tar"}), gz.to_vec(), "tar.gz", false), ("zstd payload", serde_json::Value::Null, vec![0x28, 0xb5, 0x2f, 0xfd, 0], "zst", false), ("legacy wormhole commit with no hints", serde_json::Value::Null, b"opaque payload".to_vec(), "dump.gz", true), ("demo seed", json!({"demo": true}), b"demo".to_vec(), "dump.gz", true), ]; for (name, hints, head, extension, compress) in cases { let got = plan(&hints, &head); assert_eq!((got.extension, got.compress), (extension, compress), "{name}"); let ct = if extension.ends_with("gz") { "application/gzip" } else { "application/octet-stream" }; assert_eq!(got.content_type, ct, "{name}"); } } #[test] fn sweeping_removes_only_our_own_export_directories() { let dir = tempfile::tempdir().unwrap(); let make = |name: &str| std::fs::create_dir(dir.path().join(name)).unwrap(); make("tessera-export-aaaa"); make("tessera-export-bbbb"); make("vault"); make(".tmpXYZ"); std::fs::write(dir.path().join("tessera-export-file"), b"a file, not a directory").unwrap(); std::fs::create_dir_all(dir.path().join("vault/tessera-export-nested")).unwrap(); assert_eq!(sweep_stale(dir.path()), 2); for kept in ["vault", ".tmpXYZ", "tessera-export-file", "vault/tessera-export-nested"] { assert!(dir.path().join(kept).exists(), "{kept} must survive"); } assert!(!dir.path().join("tessera-export-aaaa").exists()); } #[test] fn admission_is_bounded_by_concurrency_and_by_free_disk() { let dir = tempfile::tempdir().unwrap(); let gate = ExportGate::new(1, 0); let held = gate.admit(dir.path(), 1).ok().expect("first export is admitted"); assert!(matches!(gate.admit(dir.path(), 1), Err(Refused::Busy)), "second export is refused at once"); drop(held); assert!(gate.admit(dir.path(), 1).is_ok(), "the permit comes back when the first ends"); let greedy = ExportGate::new(4, u64::MAX / 2); assert!(matches!(greedy.admit(dir.path(), 10), Err(Refused::NoSpace))); assert!(matches!(ExportGate::new(4, 0).admit(dir.path(), u64::MAX), Err(Refused::NoSpace)), "a snapshot bigger than the disk"); } }