diff --git a/Cargo.lock b/Cargo.lock index 7db124d..275b97d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1272,6 +1272,12 @@ dependencies = [ "serde", ] +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + [[package]] name = "sha2" version = "0.10.8" @@ -1431,6 +1437,7 @@ dependencies = [ "serde", "serde_json", "tessera-core", + "tessera-demo", "tessera-providers", "tessera-store", "uuid", @@ -1451,6 +1458,21 @@ dependencies = [ "uuid", ] +[[package]] +name = "tessera-demo" +version = "0.1.0" +dependencies = [ + "anyhow", + "chrono", + "rusqlite", + "serde", + "serde_json", + "tessera-core", + "tessera-store", + "tracing", + "uuid", +] + [[package]] name = "tessera-hub" version = "0.1.0" @@ -1468,6 +1490,7 @@ dependencies = [ "serde", "serde_json", "tessera-core", + "tessera-demo", "tessera-providers", "tessera-store", "tokio", @@ -1769,6 +1792,7 @@ checksum = "81dfa00651efa65069b0b6b651f4aaa31ba9e3c3ce0137aaad053604ee7e0314" dependencies = [ "getrandom 0.2.17", "serde", + "sha1_smol", ] [[package]] diff --git a/crates/tessera-hub/src/api/orbit.rs b/crates/tessera-hub/src/api/orbit.rs index 0bf63c4..b54a3c3 100644 --- a/crates/tessera-hub/src/api/orbit.rs +++ b/crates/tessera-hub/src/api/orbit.rs @@ -6,16 +6,32 @@ use tessera_core::manifest::SnapshotManifest; use tessera_providers::provider_from_config; use uuid::Uuid; -pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result<()> { +pub async fn run_orbit_internal(state: HubState, orbit_id: Uuid) -> Result> { let orbits = state.db.list_orbits().await?; let orbit = orbits .into_iter() .find(|o| o.id == orbit_id) .context("orbit not found")?; - run_orbit_row(state, orbit).await + anyhow::ensure!( + state.active_orbits.lock().await.insert(orbit_id), + "orbit already running" + ); + + // Keep capture and its status update together if the requesting client disconnects. + tokio::spawn(async move { + let result = run_orbit_row(&state, orbit).await; + if result.is_err() { + if let Err(error) = state.db.set_orbit_status(orbit_id, "failed").await { + tracing::error!(%orbit_id, %error, "could not record failed capture"); + } + } + state.active_orbits.lock().await.remove(&orbit_id); + result + }) + .await? } -pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> { +async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result> { state.db.set_orbit_status(orbit.id, "running").await?; let provider_kind = match orbit.provider.as_str() { @@ -42,13 +58,16 @@ pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> { .snapshot(manifest, &capture.payload, orbit.dry_run) .context("vault snapshot")?; - if !orbit.dry_run { - let _pruned = vault.prune_with_decay(&orbit.decay_preset)?; + let retained_snapshot = if orbit.dry_run { + None + } else { + let pruned = vault.prune_orbit_with_decay(orbit.id, &orbit.decay_preset)?; state .db .audit("decay.pruned", &format!("orbit={}", orbit.name)) .await?; - } + (!pruned.contains(&snap.id)).then_some(snap.id) + }; let status = if orbit.dry_run { "rehearsed" @@ -67,5 +86,5 @@ pub async fn run_orbit_row(state: HubState, orbit: OrbitRow) -> Result<()> { &format!("snapshot={}", snap.id), ) .await?; - Ok(()) + Ok(retained_snapshot) } diff --git a/crates/tessera-hub/src/api/routes.rs b/crates/tessera-hub/src/api/routes.rs index 9656dd9..9c1d1ce 100644 --- a/crates/tessera-hub/src/api/routes.rs +++ b/crates/tessera-hub/src/api/routes.rs @@ -2,9 +2,9 @@ use crate::db::OrbitRow; use crate::state::{HubState, PairingEntry}; use axum::{ extract::{Path, State}, - http::{header, StatusCode, Uri}, + http::{header, HeaderMap, HeaderValue, StatusCode, Uri}, response::IntoResponse, - routing::{delete, get, post}, + routing::{get, post}, Json, Router, }; use base64::Engine; @@ -49,6 +49,7 @@ struct ApiDoc; #[derive(serde::Serialize, utoipa::ToSchema)] struct SnapshotSummary { id: Uuid, + orbit_id: Uuid, taken_at: chrono::DateTime, orbit_name: String, size_bytes: u64, @@ -147,6 +148,7 @@ async fn list_snapshots(State(state): State) -> Result, Path(id): Path, -) -> Result { - crate::api::run_orbit_internal(state, id) +) -> Result<(StatusCode, HeaderMap), StatusCode> { + let snapshot_id = crate::api::run_orbit_internal(state, id) .await - .map(|_| StatusCode::NO_CONTENT) - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR) + .map_err(|error| { + tracing::warn!(orbit_id = %id, %error, "capture did not complete"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + let mut headers = HeaderMap::new(); + if let Some(snapshot_id) = snapshot_id { + let value = HeaderValue::from_str(&snapshot_id.to_string()) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + headers.insert("x-tessera-snapshot-id", value); + } + Ok((StatusCode::NO_CONTENT, headers)) } #[utoipa::path(post, path = "/api/v1/reconstitute", request_body = ReconstituteRequest, responses((status = 200, body = ReconstituteStartResponse)))] @@ -230,21 +241,14 @@ async fn start_reconstitute( } tokio::time::sleep(std::time::Duration::from_secs(1)).await; } - let aborted = { - let map = state_bg.reconstitute_sessions.read().await; - map.get(&session_id) - .map(|s| s.state == ReconstituteState::Aborted) - .unwrap_or(true) - }; - if aborted { - return; - } { let mut map = state_bg.reconstitute_sessions.write().await; - if let Some(s) = map.get_mut(&session_id) { - s.state = ReconstituteState::Restoring; - s.seconds_remaining = 0; + let Some(s) = map.get_mut(&session_id) else { return }; + if s.state == ReconstituteState::Aborted { + return; } + s.state = ReconstituteState::Restoring; + s.seconds_remaining = 0; } let dest = std::path::PathBuf::from(&target); let result = { diff --git a/crates/tessera-hub/src/state.rs b/crates/tessera-hub/src/state.rs index 11dac53..14501dc 100644 --- a/crates/tessera-hub/src/state.rs +++ b/crates/tessera-hub/src/state.rs @@ -1,12 +1,12 @@ use crate::db::Db; use anyhow::Result; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::sync::Arc; use tessera_core::reconstitute::ReconstituteSession; use tessera_core::wormhole::PairingState; use tessera_store::Vault; -use tokio::sync::RwLock; +use tokio::sync::{Mutex, RwLock}; use uuid::Uuid; #[derive(Clone)] @@ -17,6 +17,7 @@ pub struct HubState { pub vault: Arc>, pub pairing_codes: Arc>>, pub reconstitute_sessions: Arc>>, + pub active_orbits: Arc>>, } #[derive(Clone)] @@ -50,6 +51,7 @@ impl HubState { vault: Arc::new(RwLock::new(vault)), pairing_codes: Arc::new(RwLock::new(Vec::new())), reconstitute_sessions: Arc::new(RwLock::new(HashMap::new())), + active_orbits: Arc::new(Mutex::new(HashSet::new())), }) } diff --git a/crates/tessera-store/src/vault.rs b/crates/tessera-store/src/vault.rs index 21f1faf..17d00bd 100644 --- a/crates/tessera-store/src/vault.rs +++ b/crates/tessera-store/src/vault.rs @@ -202,10 +202,25 @@ impl Vault { } pub fn prune_with_decay(&mut self, preset: &str) -> Result> { - let policy = DecayPolicy::from_preset(preset); let snaps = self.list_snapshots()?; - let refs: Vec = snaps - .iter() + self.prune_snapshots(preset, snaps.into_iter()) + } + + pub fn prune_orbit_with_decay(&mut self, orbit_id: Uuid, preset: &str) -> Result> { + let snaps = self.list_snapshots()?; + self.prune_snapshots( + preset, + snaps.into_iter().filter(|s| s.manifest.orbit_id == orbit_id), + ) + } + + fn prune_snapshots( + &mut self, + preset: &str, + snapshots: impl Iterator, + ) -> Result> { + let policy = DecayPolicy::from_preset(preset); + let refs = snapshots .map(|s| SnapshotRef { id: s.id, taken_at: s.taken_at, @@ -268,4 +283,36 @@ mod tests { vault.snapshot(manifest, b"x", true).unwrap(); assert!(vault.list_snapshots().unwrap().is_empty()); } + + #[test] + fn orbit_decay_keeps_other_orbits_recoverable() { + let dir = tempdir().unwrap(); + let mut vault = Vault::init(dir.path(), "secret").unwrap(); + let orbit_id = Uuid::new_v4(); + let other_id = Uuid::new_v4(); + let now = DateTime::from_timestamp(1_730_000_000, 0).unwrap(); + for (index, id) in [orbit_id, orbit_id, other_id].into_iter().enumerate() { + let manifest = SnapshotManifest { + snapshot_id: Uuid::new_v4(), + orbit_id: id, + orbit_name: "same name".into(), + labels: vec![], + provider: "filesystem".into(), + paths: vec![], + restore_hints: serde_json::json!({}), + }; + vault + .snapshot_at(manifest, b"x", false, now - chrono::Duration::seconds(index as i64)) + .unwrap(); + } + let pruned = vault + .prune_orbit_with_decay(orbit_id, "month-of-weeklies") + .unwrap(); + assert_eq!(pruned.len(), 1); + assert!(vault + .list_snapshots() + .unwrap() + .iter() + .any(|s| s.manifest.orbit_id == other_id)); + } } diff --git a/docs/SPEC.md b/docs/SPEC.md index b24a13d..d841308 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -64,7 +64,7 @@ Tessera is a self-hosted backup vault. This document is the contract for metapho **Invariants** - Only one active capture per orbit per vault at a time (hub enforces lock). -- Decay runs only after a **successful** non-dry-run seal. +- Automatic decay runs only after a **successful** non-dry-run seal and applies to the captured orbit. - Dry-run (“rehearse”) never writes snapshot metadata to the vault store. ---