feat: add configurable GFS retention per orbit
This commit is contained in:
@@ -11,7 +11,18 @@ pub fn post_json(url: &str, body: &serde_json::Value) -> Result<String> {
|
||||
request("POST", url, Some(&payload), Some("application/json"))
|
||||
}
|
||||
|
||||
fn request(method: &str, url: &str, body: Option<&str>, content_type: Option<&str>) -> Result<String> {
|
||||
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<String> {
|
||||
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::<u16>()?;
|
||||
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)> {
|
||||
|
||||
@@ -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<String>,
|
||||
#[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<String>,
|
||||
#[command(flatten)]
|
||||
counts: RetentionArgs,
|
||||
},
|
||||
Snap {
|
||||
#[arg(long)]
|
||||
@@ -64,6 +75,45 @@ enum Commands {
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Args, Clone)]
|
||||
struct RetentionArgs {
|
||||
#[arg(long)]
|
||||
keep_daily: Option<u32>,
|
||||
#[arg(long)]
|
||||
keep_weekly: Option<u32>,
|
||||
#[arg(long)]
|
||||
keep_monthly: Option<u32>,
|
||||
#[arg(long)]
|
||||
keep_yearly: Option<u32>,
|
||||
}
|
||||
|
||||
impl RetentionArgs {
|
||||
fn policy(self) -> Result<Option<RetentionPolicy>> {
|
||||
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<String>,
|
||||
schedule: Option<String>,
|
||||
dry_run: bool,
|
||||
retention: Option<RetentionPolicy>,
|
||||
) -> 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)?;
|
||||
|
||||
@@ -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<Utc>,
|
||||
}
|
||||
|
||||
#[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<SnapshotRef>) -> Vec<Uuid> {
|
||||
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<K: PartialEq>(
|
||||
snapshots: &[SnapshotRef],
|
||||
keep: &mut HashSet<Uuid>,
|
||||
mut count: u32,
|
||||
period: impl Fn(DateTime<Utc>) -> 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<SnapshotRef>) -> Vec<Uuid> {
|
||||
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<SnapshotRef>) ->
|
||||
.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() {
|
||||
|
||||
@@ -74,11 +74,7 @@ async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>
|
||||
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))
|
||||
|
||||
@@ -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<String>,
|
||||
decay_preset: Option<String>,
|
||||
retention: Option<RetentionPolicy>,
|
||||
dry_run: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, utoipa::ToSchema)]
|
||||
struct RetentionUpdate {
|
||||
decay_preset: Option<String>,
|
||||
retention: Option<RetentionPolicy>,
|
||||
}
|
||||
|
||||
#[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<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(req): Json<CreateOrbitRequest>,
|
||||
) -> Result<Json<OrbitRow>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
) -> Result<Json<OrbitRow>, (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<String>,
|
||||
retention: Option<RetentionPolicy>,
|
||||
) -> Result<(String, Option<RetentionPolicy>), (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<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(req): Json<RetentionUpdate>,
|
||||
) -> Result<StatusCode, (StatusCode, &'static str)> {
|
||||
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<SocketAddr>,
|
||||
@@ -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
|
||||
|
||||
@@ -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<String>,
|
||||
pub decay_preset: String,
|
||||
#[serde(default)]
|
||||
pub retention: Option<RetentionPolicy>,
|
||||
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<Vec<OrbitRow>> {
|
||||
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<String>>(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::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
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<bool> {
|
||||
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<RetentionPolicy>)> {
|
||||
let row: Option<(String, Option<String>)> = 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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Vec<Uuid>> {
|
||||
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?
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Option<Uuid>> {
|
||||
) -> Result<Option<(Uuid, bool)>> {
|
||||
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<Vec<Uuid>> {
|
||||
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<Vec<Uuid>> {
|
||||
pub fn prune_orbit_with_decay(
|
||||
&mut self,
|
||||
orbit_id: Uuid,
|
||||
preset: &str,
|
||||
retention: Option<&RetentionPolicy>,
|
||||
) -> Result<Vec<Uuid>> {
|
||||
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<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,
|
||||
})
|
||||
.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
|
||||
|
||||
Reference in New Issue
Block a user