feat: add configurable GFS retention per orbit

This commit is contained in:
2026-11-10 11:16:03 +07:00
parent 749c4cc828
commit 30a1a9b8f0
14 changed files with 665 additions and 86 deletions

View File

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