fix: report verified orbit capture outcomes

This commit is contained in:
2026-11-09 22:01:14 +07:00
parent e95d1553ff
commit 2129e80c38
6 changed files with 128 additions and 32 deletions

24
Cargo.lock generated
View File

@@ -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]]

View File

@@ -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<Option<Uuid>> {
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<Option<Uuid>> {
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)
}

View File

@@ -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<chrono::Utc>,
orbit_name: String,
size_bytes: u64,
@@ -147,6 +148,7 @@ async fn list_snapshots(State(state): State<HubState>) -> Result<Json<Vec<Snapsh
.into_iter()
.map(|s| SnapshotSummary {
id: s.id,
orbit_id: s.manifest.orbit_id,
taken_at: s.taken_at,
orbit_name: s.manifest.orbit_name,
size_bytes: s.size_bytes,
@@ -186,15 +188,24 @@ async fn create_orbit(
Ok(Json(row))
}
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204)))]
#[utoipa::path(post, path = "/api/v1/orbits/{id}/run", params(("id" = Uuid, Path, description = "orbit id")), responses((status = 204, headers(("X-Tessera-Snapshot-Id" = Uuid, description = "New retained snapshot ID when a capture writes to the vault")))))]
async fn trigger_orbit(
State(state): State<HubState>,
Path(id): Path<Uuid>,
) -> Result<StatusCode, StatusCode> {
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,22 +241,15 @@ 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) {
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 = {
let vault = state_bg.vault.read().await;

View File

@@ -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<RwLock<Vault>>,
pub pairing_codes: Arc<RwLock<Vec<PairingEntry>>>,
pub reconstitute_sessions: Arc<RwLock<HashMap<Uuid, ReconstituteSession>>>,
pub active_orbits: Arc<Mutex<HashSet<Uuid>>>,
}
#[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())),
})
}

View File

@@ -202,10 +202,25 @@ impl Vault {
}
pub fn prune_with_decay(&mut self, preset: &str) -> Result<Vec<Uuid>> {
let policy = DecayPolicy::from_preset(preset);
let snaps = self.list_snapshots()?;
let refs: Vec<SnapshotRef> = snaps
.iter()
self.prune_snapshots(preset, snaps.into_iter())
}
pub fn prune_orbit_with_decay(&mut self, orbit_id: Uuid, preset: &str) -> Result<Vec<Uuid>> {
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<Item = StoredSnapshot>,
) -> Result<Vec<Uuid>> {
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));
}
}

View File

@@ -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.
---