feat: add configurable GFS retention per orbit
This commit is contained in:
@@ -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?
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user