From 30a1a9b8f03f0ee284db364713474f620e404d3e Mon Sep 17 00:00:00 2001 From: Adnan Zahir Date: Tue, 10 Nov 2026 11:16:03 +0700 Subject: [PATCH] feat: add configurable GFS retention per orbit --- README.md | 13 ++ crates/tessera-cli/src/http.rs | 28 +++- crates/tessera-cli/src/main.rs | 81 +++++++++- crates/tessera-core/src/decay.rs | 147 +++++++++++++++++- crates/tessera-hub/src/api/orbit.rs | 6 +- crates/tessera-hub/src/api/routes.rs | 109 ++++++++++--- crates/tessera-hub/src/db.rs | 124 ++++++++++++++- crates/tessera-hub/src/state.rs | 9 ++ crates/tessera-store/src/vault.rs | 33 ++-- web/src/App.tsx | 2 +- web/src/api.ts | 23 ++- web/src/components/decay/DecayView.tsx | 27 +++- web/src/components/orbits/OrbitsView.tsx | 69 +++++--- web/src/components/orbits/RetentionFields.tsx | 80 ++++++++++ 14 files changed, 665 insertions(+), 86 deletions(-) create mode 100644 web/src/components/orbits/RetentionFields.tsx diff --git a/README.md b/README.md index d05d619..a73411e 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,19 @@ Restore a new filesystem or Restic outpost snapshot to a file such as `restore.t Decay removes expired snapshots from Tessera's list. Run `tessera gc` periodically from the host or container with the same data directory and vault passphrase to let Restic reclaim their unreferenced chunks. Run it during a quiet period so Restic can acquire its repository locks. Legacy packs and Restic snapshots created outside Tessera's catalog require separate maintenance. +### Custom retention + +Choose **Custom (GFS)** in an orbit's retention settings. Each count selects the newest snapshot in each of the most recent occupied UTC days, ISO weeks (Monday to Sunday), months, or years. Empty periods do not use up a count. A snapshot can satisfy more than one tier. Set a tier to zero to skip it and keep at least one tier above zero. Existing presets keep their original behavior. + +To set 7 daily, 2 weekly, 6 monthly, and 3 yearly snapshots from the CLI: + +```bash +tessera orbit archive --path /srv/archive --keep-daily 7 --keep-weekly 2 --keep-monthly 6 --keep-yearly 3 +tessera retention --keep-daily 7 --keep-weekly 2 --keep-monthly 6 --keep-yearly 3 +``` + +The API accepts `{"retention":{"keep_daily":7,"keep_weekly":2,"keep_monthly":6,"keep_yearly":3}}` as part of `POST /api/v1/orbits` or as the body of `PUT /api/v1/orbits/{id}/retention`. Omitted tiers default to zero. To switch back to a preset, send `{"decay_preset":"week-of-dailies"}` to the same `PUT` endpoint or use `tessera retention --preset week-of-dailies`. Saving applies the policy after the next successful capture. The separate `tessera decay --preset` command still applies its selected preset across the vault. + ### Incremental Wormhole transfers Run [Rest Server](https://github.com/restic/rest-server#usage) with TLS, authentication, `--append-only`, and `--private-repos`. Point its storage at the hub's `vault/outposts` directory. Both processes need filesystem access to that directory. Give Rest Server access only to `outposts`, with a separate location for its TLS and authentication files. diff --git a/crates/tessera-cli/src/http.rs b/crates/tessera-cli/src/http.rs index d476966..eb9e7b4 100644 --- a/crates/tessera-cli/src/http.rs +++ b/crates/tessera-cli/src/http.rs @@ -11,7 +11,18 @@ pub fn post_json(url: &str, body: &serde_json::Value) -> Result { request("POST", url, Some(&payload), Some("application/json")) } -fn request(method: &str, url: &str, body: Option<&str>, content_type: Option<&str>) -> Result { +pub fn put_json(url: &str, body: &serde_json::Value) -> Result<()> { + let payload = serde_json::to_string(body)?; + request("PUT", url, Some(&payload), Some("application/json"))?; + Ok(()) +} + +fn request( + method: &str, + url: &str, + body: Option<&str>, + content_type: Option<&str>, +) -> Result { let (host, port, path) = parse_url(url)?; let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?; let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n"); @@ -28,8 +39,19 @@ fn request(method: &str, url: &str, body: Option<&str>, content_type: Option<&st stream.write_all(req.as_bytes())?; let mut buf = String::new(); stream.read_to_string(&mut buf)?; - let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0); - Ok(buf[body_start..].trim().to_string()) + let (headers, body) = buf.split_once("\r\n\r\n").context("invalid hub response")?; + let status = headers + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .context("missing hub response status")? + .parse::()?; + anyhow::ensure!( + (200..300).contains(&status), + "hub returned HTTP {status}: {}", + body.trim() + ); + Ok(body.trim().to_string()) } fn parse_url(url: &str) -> Result<(String, u16, String)> { diff --git a/crates/tessera-cli/src/main.rs b/crates/tessera-cli/src/main.rs index e71c660..27ce00f 100644 --- a/crates/tessera-cli/src/main.rs +++ b/crates/tessera-cli/src/main.rs @@ -1,7 +1,8 @@ mod http; use anyhow::{Context, Result}; -use clap::{Parser, Subcommand}; +use clap::{Args, Parser, Subcommand}; +use tessera_core::decay::RetentionPolicy; use tessera_store::Vault; use uuid::Uuid; @@ -33,6 +34,16 @@ enum Commands { schedule: Option, #[arg(long)] dry_run: bool, + #[command(flatten)] + retention: RetentionArgs, + }, + /// Change an orbit's retention for future captures. + Retention { + orbit_id: Uuid, + #[arg(long)] + preset: Option, + #[command(flatten)] + counts: RetentionArgs, }, Snap { #[arg(long)] @@ -64,6 +75,45 @@ enum Commands { }, } +#[derive(Args, Clone)] +struct RetentionArgs { + #[arg(long)] + keep_daily: Option, + #[arg(long)] + keep_weekly: Option, + #[arg(long)] + keep_monthly: Option, + #[arg(long)] + keep_yearly: Option, +} + +impl RetentionArgs { + fn policy(self) -> Result> { + if [ + self.keep_daily, + self.keep_weekly, + self.keep_monthly, + self.keep_yearly, + ] + .iter() + .all(Option::is_none) + { + return Ok(None); + } + let policy = RetentionPolicy { + keep_daily: self.keep_daily.unwrap_or(0), + keep_weekly: self.keep_weekly.unwrap_or(0), + keep_monthly: self.keep_monthly.unwrap_or(0), + keep_yearly: self.keep_yearly.unwrap_or(0), + }; + anyhow::ensure!( + policy.has_tiers(), + "set at least one retention count above zero" + ); + Ok(Some(policy)) + } +} + #[derive(Subcommand, Clone)] enum WormholeCmd { Pair { @@ -85,7 +135,32 @@ fn main() -> Result<()> { path, schedule, dry_run, - } => cmd_orbit(&cli, name, provider, path, schedule, dry_run)?, + retention, + } => cmd_orbit( + &cli, + name, + provider, + path, + schedule, + dry_run, + retention.policy()?, + )?, + Commands::Retention { + orbit_id, + preset, + counts, + } => { + let retention = counts.policy()?; + anyhow::ensure!( + preset.is_some() != retention.is_some(), + "choose --preset or custom --keep-* counts" + ); + http::put_json( + &format!("{}/api/v1/orbits/{orbit_id}/retention", cli.hub_url), + &serde_json::json!({ "decay_preset": preset, "retention": retention }), + )?; + println!("Retention saved for {orbit_id}."); + } Commands::Snap { orbit } => cmd_snap(&cli, orbit)?, Commands::List => cmd_list(&cli)?, Commands::Reconstitute { @@ -174,6 +249,7 @@ fn cmd_orbit( path: Option, schedule: Option, dry_run: bool, + retention: Option, ) -> Result<()> { let config = match provider.as_str() { "filesystem" => serde_json::json!({ "paths": [path.unwrap_or_else(|| ".".into())] }), @@ -193,6 +269,7 @@ fn cmd_orbit( "provider_config": config, "schedule": schedule, "dry_run": dry_run, + "retention": retention, }); let raw = http::post_json(&format!("{}/api/v1/orbits", cli.hub_url), &body)?; let orbit: serde_json::Value = serde_json::from_str(&raw)?; diff --git a/crates/tessera-core/src/decay.rs b/crates/tessera-core/src/decay.rs index a3625a6..554ff35 100644 --- a/crates/tessera-core/src/decay.rs +++ b/crates/tessera-core/src/decay.rs @@ -1,5 +1,6 @@ -use chrono::{DateTime, Utc}; +use chrono::{DateTime, Datelike, Utc}; use serde::{Deserialize, Serialize}; +use std::collections::HashSet; use uuid::Uuid; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -42,6 +43,64 @@ pub struct SnapshotRef { pub taken_at: DateTime, } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] +#[serde(default, deny_unknown_fields)] +pub struct RetentionPolicy { + pub keep_daily: u32, + pub keep_weekly: u32, + pub keep_monthly: u32, + pub keep_yearly: u32, +} + +impl RetentionPolicy { + pub fn has_tiers(&self) -> bool { + *self != Self::default() + } +} + +/// Keep the newest snapshot in each of the most recent occupied UTC periods. +pub fn evaluate_gfs(policy: &RetentionPolicy, mut snapshots: Vec) -> Vec { + if !policy.has_tiers() { + return Vec::new(); + } + snapshots.sort_unstable_by_key(|s| std::cmp::Reverse((s.taken_at, s.id))); + let mut keep = HashSet::new(); + keep_periods(&snapshots, &mut keep, policy.keep_daily, |at| { + at.date_naive() + }); + keep_periods(&snapshots, &mut keep, policy.keep_weekly, |at| { + at.iso_week() + }); + keep_periods(&snapshots, &mut keep, policy.keep_monthly, |at| { + (at.year(), at.month()) + }); + keep_periods(&snapshots, &mut keep, policy.keep_yearly, |at| at.year()); + snapshots + .into_iter() + .filter_map(|s| (!keep.contains(&s.id)).then_some(s.id)) + .collect() +} + +fn keep_periods( + snapshots: &[SnapshotRef], + keep: &mut HashSet, + mut count: u32, + period: impl Fn(DateTime) -> K, +) { + let mut last = None; + for s in snapshots { + if count == 0 { + break; + } + let key = period(s.taken_at); + if last.as_ref() != Some(&key) { + keep.insert(s.id); + count -= 1; + last = Some(key); + } + } +} + /// Returns snapshot IDs to forget (newest-first input). pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec) -> Vec { snapshots.sort_by(|a, b| b.taken_at.cmp(&a.taken_at)); @@ -96,12 +155,92 @@ pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec) -> .collect() } -use chrono::Datelike; - #[cfg(test)] mod tests { use super::*; - use chrono::Duration; + use chrono::{Duration, TimeZone, Timelike}; + + #[test] + fn gfs_keeps_the_newest_in_each_period_and_combines_tiers() { + let policy = RetentionPolicy { + keep_daily: 7, + keep_weekly: 2, + keep_monthly: 6, + keep_yearly: 3, + }; + let newest = Utc.with_ymd_and_hms(2026, 1, 17, 20, 0, 0).unwrap(); + let snapshots: Vec<_> = (0..1460) + .rev() + .flat_map(|day| { + [ + newest - Duration::days(day) - Duration::hours(12), + newest - Duration::days(day), + ] + .map(|taken_at| SnapshotRef { + id: Uuid::new_v4(), + taken_at, + }) + }) + .collect(); + let expired: std::collections::HashSet<_> = evaluate_gfs(&policy, snapshots.clone()) + .into_iter() + .collect(); + let kept: Vec<_> = snapshots + .iter() + .filter(|s| !expired.contains(&s.id)) + .collect(); + let dates: Vec<_> = kept + .iter() + .map(|s| s.taken_at.date_naive().to_string()) + .collect(); + assert_eq!( + dates, + [ + "2024-12-31", + "2025-08-31", + "2025-09-30", + "2025-10-31", + "2025-11-30", + "2025-12-31", + "2026-01-11", + "2026-01-12", + "2026-01-13", + "2026-01-14", + "2026-01-15", + "2026-01-16", + "2026-01-17" + ] + ); + assert!(kept.iter().all(|s| s.taken_at.hour() == 20)); + } + + #[test] + fn gfs_weeks_start_monday_and_skip_empty_weeks() { + let sunday = Utc.with_ymd_and_hms(2025, 1, 5, 23, 0, 0).unwrap(); + let snapshots: Vec<_> = [-49, -1, 0, 1] + .map(|hours| SnapshotRef { + id: Uuid::new_v4(), + taken_at: sunday + Duration::hours(hours), + }) + .into(); + let policy = RetentionPolicy { + keep_weekly: 2, + ..RetentionPolicy::default() + }; + assert_eq!( + evaluate_gfs(&policy, snapshots.clone()), + [snapshots[1].id, snapshots[0].id] + ); + let sparse = vec![ + snapshots[3].clone(), + SnapshotRef { + id: snapshots[0].id, + taken_at: sunday - Duration::weeks(3), + }, + ]; + assert!(evaluate_gfs(&policy, sparse).is_empty()); + assert!(evaluate_gfs(&RetentionPolicy::default(), snapshots).is_empty()); + } #[test] fn keeps_n_dailies() { diff --git a/crates/tessera-hub/src/api/orbit.rs b/crates/tessera-hub/src/api/orbit.rs index 789ce3c..eb4cbbd 100644 --- a/crates/tessera-hub/src/api/orbit.rs +++ b/crates/tessera-hub/src/api/orbit.rs @@ -74,11 +74,7 @@ async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result let retained_snapshot = if orbit.dry_run { None } else { - let pruned = state - .vault - .write() - .await - .prune_orbit_with_decay(orbit.id, &orbit.decay_preset)?; + let pruned = state.prune_orbit(orbit.id).await?; state .db .audit("decay.pruned", &format!("orbit={}", orbit.name)) diff --git a/crates/tessera-hub/src/api/routes.rs b/crates/tessera-hub/src/api/routes.rs index ef44488..ad48983 100644 --- a/crates/tessera-hub/src/api/routes.rs +++ b/crates/tessera-hub/src/api/routes.rs @@ -5,13 +5,14 @@ use axum::{ extract::{ConnectInfo, Path, State}, http::{header, HeaderMap, HeaderValue, StatusCode, Uri}, response::IntoResponse, - routing::{get, post}, + routing::{get, post, put}, Json, Router, }; use base64::Engine; use include_dir::{include_dir, Dir}; use std::fs::{File, OpenOptions}; use std::net::SocketAddr; +use tessera_core::decay::RetentionPolicy; use tessera_core::manifest::SnapshotManifest; use tessera_core::reconstitute::{ReconstituteSession, ReconstituteState, RECONSTITUTE_GRACE_SECS}; use tower_http::trace::TraceLayer; @@ -27,6 +28,7 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist"); list_snapshots, list_orbits, create_orbit, + update_orbit_retention, trigger_orbit, start_reconstitute, pairing_start, @@ -39,6 +41,8 @@ static WEB_DIST: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../../web/dist"); SnapshotSummary, OrbitRow, CreateOrbitRequest, + RetentionUpdate, + RetentionPolicy, ReconstituteRequest, ReconstituteSession, PairingResponse, @@ -69,9 +73,16 @@ struct CreateOrbitRequest { provider_config: serde_json::Value, schedule: Option, decay_preset: Option, + retention: Option, dry_run: Option, } +#[derive(serde::Deserialize, utoipa::ToSchema)] +struct RetentionUpdate { + decay_preset: Option, + retention: Option, +} + #[derive(serde::Deserialize, utoipa::ToSchema)] struct ReconstituteRequest { snapshot_id: Uuid, @@ -135,6 +146,7 @@ pub fn router(state: HubState) -> Router { .route("/health", get(health)) .route("/api/v1/snapshots", get(list_snapshots)) .route("/api/v1/orbits", get(list_orbits).post(create_orbit)) + .route("/api/v1/orbits/:id/retention", put(update_orbit_retention)) .route("/api/v1/orbits/:id/run", post(trigger_orbit)) .route("/api/v1/reconstitute", post(start_reconstitute)) .route( @@ -210,24 +222,81 @@ async fn create_orbit( State(state): State, headers: HeaderMap, Json(req): Json, -) -> Result, StatusCode> { - require_admin(&state, peer, &headers)?; +) -> Result, (StatusCode, &'static str)> { + require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?; + let (decay_preset, retention) = retention_settings(req.decay_preset, req.retention)?; let row = OrbitRow { id: Uuid::new_v4(), name: req.name, provider: req.provider, provider_config: serde_json::to_string(&req.provider_config).unwrap_or_else(|_| "{}".into()), schedule: req.schedule, - decay_preset: req - .decay_preset - .unwrap_or_else(|| "week-of-dailies".into()), + decay_preset, + retention, dry_run: req.dry_run.unwrap_or(false), last_status: "idle".into(), }; - state.db.upsert_orbit(&row).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + state + .db + .upsert_orbit(&row) + .await + .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "could not save orbit"))?; Ok(Json(row)) } +fn retention_settings( + preset: Option, + retention: Option, +) -> Result<(String, Option), (StatusCode, &'static str)> { + if preset.is_some() && retention.is_some() { + return Err(( + StatusCode::BAD_REQUEST, + "choose a preset or custom retention", + )); + } + if retention.is_some_and(|policy| !policy.has_tiers()) { + return Err(( + StatusCode::BAD_REQUEST, + "set at least one retention count above zero", + )); + } + Ok(( + preset.unwrap_or_else(|| "week-of-dailies".into()), + retention, + )) +} + +#[utoipa::path(put, path = "/api/v1/orbits/{id}/retention", params(("id" = Uuid, Path, description = "orbit id")), request_body = RetentionUpdate, responses((status = 204), (status = 400), (status = 404)))] +async fn update_orbit_retention( + ConnectInfo(peer): ConnectInfo, + State(state): State, + headers: HeaderMap, + Path(id): Path, + Json(req): Json, +) -> Result { + require_admin(&state, peer, &headers).map_err(|status| (status, "unauthorized"))?; + if req.decay_preset.is_none() && req.retention.is_none() { + return Err(( + StatusCode::BAD_REQUEST, + "choose a preset or custom retention", + )); + } + let (preset, retention) = retention_settings(req.decay_preset, req.retention)?; + let saved = state + .db + .set_orbit_retention(id, &preset, retention.as_ref()) + .map_err(|_| { + ( + StatusCode::INTERNAL_SERVER_ERROR, + "could not save retention", + ) + })?; + if !saved { + return Err((StatusCode::NOT_FOUND, "orbit not found")); + } + Ok(StatusCode::NO_CONTENT) +} + #[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( ConnectInfo(peer): ConnectInfo, @@ -584,7 +653,7 @@ async fn wormhole_restic_commit( .ok_or(StatusCode::NOT_FOUND)?; let orbit_id = orbit.id; let mut vault = state.vault.clone().write_owned().await; - let snapshot = tokio::task::spawn_blocking(move || { + let (snapshot, created) = tokio::task::spawn_blocking(move || { let manifest = SnapshotManifest { snapshot_id: Uuid::nil(), orbit_id, @@ -594,13 +663,7 @@ async fn wormhole_restic_commit( paths: vec![], restore_hints: serde_json::Value::Null, }; - let id = vault.register_outpost_snapshot(manifest, outpost_id, &body.snapshot_id)?; - if id.is_some() { - if let Err(error) = vault.prune_orbit_with_decay(orbit_id, &orbit.decay_preset) { - tracing::warn!(%orbit_id, %error, "could not apply Wormhole retention"); - } - } - Ok::<_, anyhow::Error>(id) + vault.register_outpost_snapshot(manifest, outpost_id, &body.snapshot_id) }) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? @@ -609,6 +672,11 @@ async fn wormhole_restic_commit( StatusCode::INTERNAL_SERVER_ERROR })? .ok_or(StatusCode::FORBIDDEN)?; + if created { + if let Err(error) = state.prune_orbit(orbit_id).await { + tracing::warn!(%orbit_id, %error, "could not apply Wormhole retention"); + } + } state .db .set_orbit_status(orbit_id, "completed") @@ -637,10 +705,6 @@ async fn seal_upload( .as_ref() .map(|orbit| orbit.name.clone()) .unwrap_or_else(|| orbit_id.to_string()); - let decay = orbit - .as_ref() - .map(|orbit| orbit.decay_preset.clone()) - .unwrap_or_else(|| "week-of-dailies".into()); let manifest = SnapshotManifest { snapshot_id: Uuid::new_v4(), orbit_id, @@ -666,12 +730,7 @@ async fn seal_upload( tracing::error!(%session_id, %error, "could not seal Wormhole snapshot"); StatusCode::INTERNAL_SERVER_ERROR })?; - if let Err(error) = state - .vault - .write() - .await - .prune_orbit_with_decay(orbit_id, &decay) - { + if let Err(error) = state.prune_orbit(orbit_id).await { tracing::warn!(%orbit_id, %error, "could not apply Wormhole retention"); } let _ = state diff --git a/crates/tessera-hub/src/db.rs b/crates/tessera-hub/src/db.rs index 392a4f6..240c8c2 100644 --- a/crates/tessera-hub/src/db.rs +++ b/crates/tessera-hub/src/db.rs @@ -2,6 +2,7 @@ use anyhow::Result; use rusqlite::{params, Connection, OptionalExtension}; use std::path::Path; use std::sync::{Arc, Mutex}; +use tessera_core::decay::RetentionPolicy; use uuid::Uuid; #[derive(Clone)] @@ -17,6 +18,8 @@ pub struct OrbitRow { pub provider_config: String, pub schedule: Option, pub decay_preset: String, + #[serde(default)] + pub retention: Option, pub dry_run: bool, pub last_status: String, } @@ -81,13 +84,19 @@ impl Db { ); "#, )?; - ensure_column(&conn, "upload_sessions", "sealed", "INTEGER NOT NULL DEFAULT 0")?; + ensure_column( + &conn, + "upload_sessions", + "sealed", + "INTEGER NOT NULL DEFAULT 0", + )?; + ensure_column(&conn, "orbits", "retention", "TEXT")?; Ok(()) } pub async fn list_orbits(&self) -> Result> { let conn = self.conn.lock().unwrap(); - let mut stmt = conn.prepare("SELECT id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status FROM orbits ORDER BY name")?; + let mut stmt = conn.prepare("SELECT id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status, retention FROM orbits ORDER BY name")?; let rows = stmt.query_map([], |r| { Ok(OrbitRow { id: Uuid::parse_str(&r.get::<_, String>(0)?).unwrap_or_else(|_| Uuid::new_v4()), @@ -96,21 +105,34 @@ impl Db { provider_config: r.get(3)?, schedule: r.get(4)?, decay_preset: r.get(5)?, + retention: r + .get::<_, Option>(8)? + .map(|json| { + serde_json::from_str(&json).map_err(|error| { + rusqlite::Error::FromSqlConversionFailure( + 8, + rusqlite::types::Type::Text, + Box::new(error), + ) + }) + }) + .transpose()?, dry_run: r.get::<_, i64>(6)? != 0, last_status: r.get(7)?, }) })?; - Ok(rows.filter_map(|r| r.ok()).collect()) + Ok(rows.collect::>>()?) } pub async fn upsert_orbit(&self, row: &OrbitRow) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( - r#"INSERT INTO orbits (id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8) + r#"INSERT INTO orbits (id, name, provider, provider_config, schedule, decay_preset, dry_run, last_status, retention) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9) ON CONFLICT(id) DO UPDATE SET name=excluded.name, provider=excluded.provider, provider_config=excluded.provider_config, - schedule=excluded.schedule, decay_preset=excluded.decay_preset, dry_run=excluded.dry_run"#, + schedule=excluded.schedule, decay_preset=excluded.decay_preset, dry_run=excluded.dry_run, + retention=excluded.retention"#, params![ row.id.to_string(), row.name, @@ -120,11 +142,44 @@ impl Db { row.decay_preset, row.dry_run as i64, row.last_status, + row.retention.as_ref().map(serde_json::to_string).transpose()?, ], )?; Ok(()) } + pub fn set_orbit_retention( + &self, + id: Uuid, + preset: &str, + policy: Option<&RetentionPolicy>, + ) -> Result { + let json = policy.map(serde_json::to_string).transpose()?; + let changed = self.conn.lock().unwrap().execute( + "UPDATE orbits SET decay_preset = ?1, retention = ?2 WHERE id = ?3", + params![preset, json, id.to_string()], + )?; + Ok(changed > 0) + } + + pub fn orbit_retention(&self, id: Uuid) -> Result<(String, Option)> { + let row: Option<(String, Option)> = self + .conn + .lock() + .unwrap() + .query_row( + "SELECT decay_preset, retention FROM orbits WHERE id = ?1", + [id.to_string()], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?; + let (preset, json) = row.unwrap_or_else(|| ("week-of-dailies".into(), None)); + Ok(( + preset, + json.as_deref().map(serde_json::from_str).transpose()?, + )) + } + pub async fn set_orbit_status(&self, id: Uuid, status: &str) -> Result<()> { let conn = self.conn.lock().unwrap(); conn.execute( @@ -308,3 +363,60 @@ fn ensure_column(conn: &Connection, table: &str, column: &str, decl: &str) -> Re conn.execute(&format!("ALTER TABLE {table} ADD COLUMN {column} {decl}"), [])?; Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn existing_orbit_can_switch_between_preset_and_custom_retention() { + let conn = Connection::open_in_memory().unwrap(); + let id = Uuid::new_v4(); + conn.execute_batch( + "CREATE TABLE orbits ( + id TEXT PRIMARY KEY, name TEXT, provider TEXT, provider_config TEXT, + schedule TEXT, decay_preset TEXT, dry_run INTEGER, last_status TEXT + )", + ) + .unwrap(); + conn.execute( + "INSERT INTO orbits VALUES (?1, 'archive', 'filesystem', '{}', NULL, + 'month-of-weeklies', 0, 'completed')", + [id.to_string()], + ) + .unwrap(); + let db = Db { + conn: Arc::new(Mutex::new(conn)), + }; + db.migrate().await.unwrap(); + assert_eq!( + db.orbit_retention(id).unwrap(), + ("month-of-weeklies".into(), None) + ); + + let policy = RetentionPolicy { + keep_daily: 7, + keep_weekly: 2, + keep_monthly: 6, + keep_yearly: 3, + }; + assert!(db + .set_orbit_retention(id, "week-of-dailies", Some(&policy)) + .unwrap()); + let orbit = db.list_orbits().await.unwrap().remove(0); + assert_eq!(orbit.retention, Some(policy)); + assert_eq!(orbit.last_status, "completed"); + assert_eq!(db.orbit_retention(id).unwrap().1, Some(policy)); + + assert!(db + .set_orbit_retention(id, "year-of-monthlies", None) + .unwrap()); + assert_eq!( + db.orbit_retention(id).unwrap(), + ("year-of-monthlies".into(), None) + ); + assert!(!db + .set_orbit_retention(Uuid::new_v4(), "year-of-monthlies", None) + .unwrap()); + } +} diff --git a/crates/tessera-hub/src/state.rs b/crates/tessera-hub/src/state.rs index 743f0d6..ee1d786 100644 --- a/crates/tessera-hub/src/state.rs +++ b/crates/tessera-hub/src/state.rs @@ -55,4 +55,13 @@ impl HubState { pub fn upload_token_valid(&self, token: &str) -> bool { self.db.upload_token_active(token).unwrap_or(false) } + + pub async fn prune_orbit(&self, orbit_id: Uuid) -> Result> { + let mut vault = self.vault.clone().write_owned().await; + let (preset, retention) = self.db.orbit_retention(orbit_id)?; + tokio::task::spawn_blocking(move || { + vault.prune_orbit_with_decay(orbit_id, &preset, retention.as_ref()) + }) + .await? + } } diff --git a/crates/tessera-store/src/vault.rs b/crates/tessera-store/src/vault.rs index 39a4b83..98d0c6b 100644 --- a/crates/tessera-store/src/vault.rs +++ b/crates/tessera-store/src/vault.rs @@ -8,7 +8,9 @@ use std::fs::{self, File}; use std::io::{Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; -use tessera_core::decay::{evaluate_decay, DecayPolicy, SnapshotRef}; +use tessera_core::decay::{ + evaluate_decay, evaluate_gfs, DecayPolicy, RetentionPolicy, SnapshotRef, +}; use tessera_core::manifest::SnapshotManifest; use uuid::Uuid; @@ -129,7 +131,7 @@ impl Vault { mut manifest: SnapshotManifest, outpost_id: Uuid, restic_id: &str, - ) -> Result> { + ) -> Result> { restic::validate_id(restic_id)?; if !self.outpost_repository_configured(manifest.orbit_id)? { return Ok(None); @@ -143,7 +145,7 @@ impl Vault { if dir.join(format!("{id}.json.enc")).try_exists()? || dir.join(format!("{id}.expired")).try_exists()? { - return Ok(Some(id)); + return Ok(Some((id, false))); } let repo = self.outpost_repository(manifest.orbit_id, config); let summary = repo.snapshot_summary(restic_id)?; @@ -161,7 +163,7 @@ impl Vault { }, false, )?; - Ok(Some(id)) + Ok(Some((id, true))) } pub fn snapshot_files( @@ -546,30 +548,41 @@ impl Vault { pub fn prune_with_decay(&mut self, preset: &str) -> Result> { let snaps = self.list_snapshots()?; - self.prune_snapshots(preset, snaps.into_iter()) + self.prune_snapshots(preset, None, snaps.into_iter()) } - pub fn prune_orbit_with_decay(&mut self, orbit_id: Uuid, preset: &str) -> Result> { + pub fn prune_orbit_with_decay( + &mut self, + orbit_id: Uuid, + preset: &str, + retention: Option<&RetentionPolicy>, + ) -> Result> { let snaps = self.list_snapshots()?; self.prune_snapshots( preset, - snaps.into_iter().filter(|s| s.manifest.orbit_id == orbit_id), + retention, + snaps + .into_iter() + .filter(|s| s.manifest.orbit_id == orbit_id), ) } fn prune_snapshots( &mut self, preset: &str, + retention: Option<&RetentionPolicy>, snapshots: impl Iterator, ) -> Result> { - let policy = DecayPolicy::from_preset(preset); let refs = snapshots .map(|s| SnapshotRef { id: s.id, taken_at: s.taken_at, }) .collect(); - let to_forget = evaluate_decay(&policy, refs); + let to_forget = match retention { + Some(policy) => evaluate_gfs(policy, refs), + None => evaluate_decay(&DecayPolicy::from_preset(preset), refs), + }; self.forget(&to_forget)?; Ok(to_forget) } @@ -736,7 +749,7 @@ mod tests { .unwrap(); } let pruned = vault - .prune_orbit_with_decay(orbit_id, "month-of-weeklies") + .prune_orbit_with_decay(orbit_id, "month-of-weeklies", None) .unwrap(); assert_eq!(pruned.len(), 1); assert!(vault diff --git a/web/src/App.tsx b/web/src/App.tsx index 8ecd3fd..6153635 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -247,7 +247,7 @@ export default function App() { )} {mode === "decay" && ( - orbit.decay_preset ?? "week-of-dailies")} /> + )} {mode === "snapshot" && ( diff --git a/web/src/api.ts b/web/src/api.ts index e3a99fa..44beffd 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -15,16 +15,25 @@ export type Orbit = { dry_run: boolean; schedule?: string | null; decay_preset?: string; + retention?: RetentionPolicy | null; }; +export type RetentionPolicy = { + keep_daily: number; + keep_weekly: number; + keep_monthly: number; + keep_yearly: number; +}; + +export type RetentionSettings = { decay_preset: string } | { retention: RetentionPolicy }; + export type CreateOrbitInput = { name: string; provider: "filesystem" | "postgres"; paths: string[]; schedule?: string; - decay_preset: string; dry_run: boolean; -}; +} & RetentionSettings; async function request(path: string, init?: RequestInit): Promise { const r = await fetch(path, init); @@ -64,12 +73,20 @@ export async function createOrbit(input: CreateOrbitInput): Promise { provider: input.provider, provider_config: { paths: input.paths }, schedule: input.schedule || null, - decay_preset: input.decay_preset, + ...("retention" in input ? { retention: input.retention } : { decay_preset: input.decay_preset }), dry_run: input.dry_run, }), }); } +export async function updateOrbitRetention(id: string, settings: RetentionSettings): Promise { + await api(`/api/v1/orbits/${id}/retention`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(settings), + }); +} + export async function startPairing(): Promise<{ code: string; expires_at: string }> { return api("/api/v1/wormhole/pairing", { method: "POST" }); } diff --git a/web/src/components/decay/DecayView.tsx b/web/src/components/decay/DecayView.tsx index 08c401b..35a03d4 100644 --- a/web/src/components/decay/DecayView.tsx +++ b/web/src/components/decay/DecayView.tsx @@ -1,21 +1,24 @@ +import type { Orbit } from "../../api"; import { DECAY_PRESETS } from "../../lib/format"; +import { describeRetention } from "../orbits/RetentionFields"; import { Hint } from "../ui/EmptyState"; import { TelemetryPanel } from "../ui/Telemetry"; -export function DecayView({ appliedPresets }: { appliedPresets: string[] }) { - const unique = [...new Set(appliedPresets)]; +export function DecayView({ orbits }: { orbits: Orbit[] }) { + const appliedPresets = new Set(orbits.filter((orbit) => !orbit.retention).map((orbit) => orbit.decay_preset ?? DECAY_PRESETS[0].id)); + const custom = orbits.filter((orbit) => orbit.retention); return (

Decay

- Old snapshots fade on purpose โ€” friendly presets, not retention spreadsheets. + Choose a preset or set daily, weekly, monthly and yearly counts for each orbit.

- Presets โ€” pick one when you create an orbit + Retention presets
    {DECAY_PRESETS.map((p) => { - const active = unique.includes(p.id); + const active = appliedPresets.has(p.id); return (
  • + {custom.length > 0 && ( +
    +

    Custom policies

    +
      + {custom.map((orbit) => ( +
    • +

      {orbit.name}

      +

      {describeRetention(orbit)}

      +
    • + ))} +
    +
    + )} + Decay runs after a successful capture โ€” rehearsed orbits never prune the vault. diff --git a/web/src/components/orbits/OrbitsView.tsx b/web/src/components/orbits/OrbitsView.tsx index 8d5bb5a..2bd9ed1 100644 --- a/web/src/components/orbits/OrbitsView.tsx +++ b/web/src/components/orbits/OrbitsView.tsx @@ -2,8 +2,9 @@ import { useState, type ReactNode } from "react"; import { AnimatePresence } from "motion/react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import type { Orbit } from "../../api"; -import { createOrbit } from "../../api"; -import { DECAY_PRESETS, orbitStatus, schedulePhrase } from "../../lib/format"; +import { createOrbit, updateOrbitRetention } from "../../api"; +import { orbitStatus, schedulePhrase } from "../../lib/format"; +import { describeRetention, retentionDraft, RetentionFields, retentionSettings } from "./RetentionFields"; import { Button } from "../ui/Button"; import { OrbitStatusDot } from "../ui/StatusDot"; import { TelemetryPanel } from "../ui/Telemetry"; @@ -22,20 +23,24 @@ export function OrbitsView({ const qc = useQueryClient(); const [name, setName] = useState("nightly-docs"); const [path, setPath] = useState("./docs"); - const [preset, setPreset] = useState(DECAY_PRESETS[0].id); + const [retention, setRetention] = useState(() => retentionDraft()); + const [editingRetention, setEditingRetention] = useState(null); const [rehearse, setRehearse] = useState(false); const [schedule, setSchedule] = useState("0 2 * * *"); const create = useMutation({ - mutationFn: () => - createOrbit({ + mutationFn: () => { + const settings = retentionSettings(retention); + if (!settings) throw new Error("Invalid retention policy"); + return createOrbit({ name, provider: "filesystem", paths: [path], schedule: schedule || undefined, - decay_preset: preset, + ...settings, dry_run: rehearse, - }), + }); + }, onSuccess: () => { qc.invalidateQueries({ queryKey: ["orbits"] }); setEditing(false); @@ -58,6 +63,7 @@ export function OrbitsView({

    {o.name}

    {orbitStatus(o.last_status).label}

    {schedulePhrase(o.schedule, o.dry_run)}

    +

    {describeRetention(o)}

    {o.dry_run && ( Rehearse mode @@ -74,7 +80,12 @@ export function OrbitsView({ > {o.dry_run ? "Rehearse" : "Capture now"} +
+ {editingRetention === o.id && setEditingRetention(null)} />} {JSON.stringify(o, null, 2)} @@ -112,20 +123,7 @@ export function OrbitsView({ onChange={(e) => setSchedule(e.target.value)} /> - +