feat: add configurable GFS retention per orbit
This commit is contained in:
13
README.md
13
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 <orbit-id> --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 <orbit-id> --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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -247,7 +247,7 @@ export default function App() {
|
||||
<SpringPane key="wormhole"><WormholeView pairing={pairing} onPaired={setPairing} /></SpringPane>
|
||||
)}
|
||||
{mode === "decay" && (
|
||||
<SpringPane key="decay"><DecayView appliedPresets={sceneOrbits.map((orbit) => orbit.decay_preset ?? "week-of-dailies")} /></SpringPane>
|
||||
<SpringPane key="decay"><DecayView orbits={sceneOrbits} /></SpringPane>
|
||||
)}
|
||||
{mode === "snapshot" && (
|
||||
<SpringPane key="snapshot">
|
||||
|
||||
@@ -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<Response> {
|
||||
const r = await fetch(path, init);
|
||||
@@ -64,12 +73,20 @@ export async function createOrbit(input: CreateOrbitInput): Promise<Orbit> {
|
||||
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<void> {
|
||||
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" });
|
||||
}
|
||||
|
||||
@@ -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 (
|
||||
<div className="h-full overflow-y-auto px-4 py-4 pb-28">
|
||||
<h2 className="text-2xl font-semibold text-star-100">Decay</h2>
|
||||
<p className="text-sm text-star-300 mt-1 mb-6">
|
||||
Old snapshots fade on purpose — friendly presets, not retention spreadsheets.
|
||||
Choose a preset or set daily, weekly, monthly and yearly counts for each orbit.
|
||||
</p>
|
||||
|
||||
<span className="text-xs text-star-400">Presets — pick one when you create an orbit</span>
|
||||
<span className="text-xs text-star-400">Retention presets</span>
|
||||
<ul className="space-y-3 mt-3">
|
||||
{DECAY_PRESETS.map((p) => {
|
||||
const active = unique.includes(p.id);
|
||||
const active = appliedPresets.has(p.id);
|
||||
return (
|
||||
<li
|
||||
key={p.id}
|
||||
@@ -39,6 +42,20 @@ export function DecayView({ appliedPresets }: { appliedPresets: string[] }) {
|
||||
})}
|
||||
</ul>
|
||||
|
||||
{custom.length > 0 && (
|
||||
<div className="mt-4 space-y-2">
|
||||
<h3 className="text-sm font-medium text-star-100">Custom policies</h3>
|
||||
<ul className="space-y-2">
|
||||
{custom.map((orbit) => (
|
||||
<li key={orbit.id} className="rounded-2xl border border-space-700 bg-space-800/40 p-4">
|
||||
<p className="text-sm font-medium text-star-100">{orbit.name}</p>
|
||||
<p className="text-sm text-star-400">{describeRetention(orbit)}</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Hint>
|
||||
Decay runs after a successful capture — rehearsed orbits never prune the vault.
|
||||
</Hint>
|
||||
|
||||
@@ -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<string>(DECAY_PRESETS[0].id);
|
||||
const [retention, setRetention] = useState(() => retentionDraft());
|
||||
const [editingRetention, setEditingRetention] = useState<string | null>(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({
|
||||
<h3 className="font-semibold text-star-100 truncate">{o.name}</h3>
|
||||
<p className="text-sm text-star-300">{orbitStatus(o.last_status).label}</p>
|
||||
<p className="text-xs text-star-400 mt-0.5">{schedulePhrase(o.schedule, o.dry_run)}</p>
|
||||
<p className="text-xs text-star-400 mt-0.5">{describeRetention(o)}</p>
|
||||
{o.dry_run && (
|
||||
<span className="inline-block mt-2 text-[10px] uppercase tracking-wider text-orbit-amber border border-orbit-amber/30 rounded px-2 py-0.5">
|
||||
Rehearse mode
|
||||
@@ -74,7 +80,12 @@ export function OrbitsView({
|
||||
>
|
||||
{o.dry_run ? "Rehearse" : "Capture now"}
|
||||
</Button>
|
||||
<Button className="flex-1 text-xs py-2" onClick={() => setEditingRetention(o.id)}
|
||||
disabled={editingRetention === o.id}>
|
||||
Edit retention
|
||||
</Button>
|
||||
</div>
|
||||
{editingRetention === o.id && <OrbitRetentionEditor orbit={o} onClose={() => setEditingRetention(null)} />}
|
||||
<TelemetryPanel>
|
||||
{JSON.stringify(o, null, 2)}
|
||||
</TelemetryPanel>
|
||||
@@ -112,20 +123,7 @@ export function OrbitsView({
|
||||
onChange={(e) => setSchedule(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
<span className="text-star-400">Decay</span>
|
||||
<select
|
||||
className="mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2"
|
||||
value={preset}
|
||||
onChange={(e) => setPreset(e.target.value)}
|
||||
>
|
||||
{DECAY_PRESETS.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<RetentionFields draft={retention} onChange={setRetention} />
|
||||
<label className="flex items-center gap-2 text-sm text-star-300">
|
||||
<input type="checkbox" checked={rehearse} onChange={(e) => setRehearse(e.target.checked)} />
|
||||
Rehearse only (dry run)
|
||||
@@ -141,7 +139,7 @@ export function OrbitsView({
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex-1"
|
||||
disabled={create.isPending}
|
||||
disabled={create.isPending || !retentionSettings(retention)}
|
||||
onClick={() => create.mutate()}
|
||||
>
|
||||
Save orbit
|
||||
@@ -161,3 +159,30 @@ export function OrbitsView({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OrbitRetentionEditor({ orbit, onClose }: { orbit: Orbit; onClose: () => void }) {
|
||||
const [draft, setDraft] = useState(() => retentionDraft(orbit));
|
||||
const settings = retentionSettings(draft);
|
||||
const qc = useQueryClient();
|
||||
const save = useMutation({
|
||||
mutationFn: updateOrbitRetention.bind(null, orbit.id),
|
||||
onSuccess: async () => {
|
||||
await qc.invalidateQueries({ queryKey: ["orbits"] });
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
return (
|
||||
<form className="mt-4 space-y-3 border-t border-space-700 pt-3" onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (settings && !save.isPending) save.mutate(settings);
|
||||
}}>
|
||||
<RetentionFields draft={draft} onChange={setDraft} />
|
||||
<Hint>Changes apply after the next successful capture.</Hint>
|
||||
{save.isError && <p role="alert" className="text-sm text-orbit-red">Retention could not be saved.</p>}
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" className="flex-1" disabled={save.isPending} onClick={onClose}>Cancel</Button>
|
||||
<Button type="submit" variant="primary" className="flex-1" disabled={!settings || save.isPending}>Save retention</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
80
web/src/components/orbits/RetentionFields.tsx
Normal file
80
web/src/components/orbits/RetentionFields.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import type { Orbit, RetentionPolicy, RetentionSettings } from "../../api";
|
||||
import { DECAY_PRESETS } from "../../lib/format";
|
||||
|
||||
const tiers = [
|
||||
["keep_daily", "Daily"],
|
||||
["keep_weekly", "Weekly"],
|
||||
["keep_monthly", "Monthly"],
|
||||
["keep_yearly", "Yearly"],
|
||||
] as const;
|
||||
const maxCount = 4_294_967_295;
|
||||
const inputClass = "mt-1 w-full rounded-xl bg-space-950 border border-space-700 px-3 py-2";
|
||||
|
||||
type Draft = { preset: string; counts: Record<keyof RetentionPolicy, string> };
|
||||
|
||||
export function retentionDraft(orbit?: Orbit): Draft {
|
||||
return {
|
||||
preset: orbit?.retention ? "custom" : orbit?.decay_preset ?? DECAY_PRESETS[0].id,
|
||||
counts: {
|
||||
keep_daily: String(orbit?.retention?.keep_daily ?? 7),
|
||||
keep_weekly: String(orbit?.retention?.keep_weekly ?? 2),
|
||||
keep_monthly: String(orbit?.retention?.keep_monthly ?? 6),
|
||||
keep_yearly: String(orbit?.retention?.keep_yearly ?? 3),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function retentionSettings({ preset, counts }: Draft): RetentionSettings | undefined {
|
||||
if (preset !== "custom") return { decay_preset: preset };
|
||||
const retention: RetentionPolicy = { keep_daily: 0, keep_weekly: 0, keep_monthly: 0, keep_yearly: 0 };
|
||||
for (const [key] of tiers) {
|
||||
const count = Number(counts[key]);
|
||||
if (counts[key] === "" || !Number.isInteger(count) || count < 0 || count > maxCount) return;
|
||||
retention[key] = count;
|
||||
}
|
||||
if (Object.values(retention).some((count) => count > 0)) return { retention };
|
||||
}
|
||||
|
||||
export function describeRetention(orbit: Orbit): string {
|
||||
if (orbit.retention) {
|
||||
const policy = orbit.retention;
|
||||
return tiers.map(([key, label]) => `${policy[key]} ${label.toLowerCase()}`).join(" · ");
|
||||
}
|
||||
const preset = orbit.decay_preset ?? DECAY_PRESETS[0].id;
|
||||
return DECAY_PRESETS.find((item) => item.id === preset)?.title ?? preset;
|
||||
}
|
||||
|
||||
export function RetentionFields({ draft, onChange }: { draft: Draft; onChange: (draft: Draft) => void }) {
|
||||
const invalid = !retentionSettings(draft);
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<label className="block text-sm">
|
||||
<span className="text-star-400">Retention</span>
|
||||
<select className={inputClass} value={draft.preset} onChange={(e) => onChange({ ...draft, preset: e.target.value })}>
|
||||
{!DECAY_PRESETS.some((item) => item.id === draft.preset) && draft.preset !== "custom" && (
|
||||
<option value={draft.preset}>{draft.preset}</option>
|
||||
)}
|
||||
{DECAY_PRESETS.map((preset) => <option key={preset.id} value={preset.id}>{preset.title}</option>)}
|
||||
<option value="custom">Custom (GFS)</option>
|
||||
</select>
|
||||
</label>
|
||||
{draft.preset === "custom" && (
|
||||
<fieldset className="space-y-2">
|
||||
<legend className="text-sm text-star-400">Snapshots to keep</legend>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{tiers.map(([key, label]) => (
|
||||
<label key={key} className="block min-w-0 text-sm text-star-300">
|
||||
{label}
|
||||
<input className={inputClass} type="number" inputMode="numeric" min={0} max={maxCount} step={1}
|
||||
value={draft.counts[key]}
|
||||
onChange={(e) => onChange({ ...draft, counts: { ...draft.counts, [key]: e.target.value } })} />
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-xs text-star-400">Zero skips a tier. The newest snapshot in each UTC period can count toward several tiers.</p>
|
||||
{invalid && <p role="alert" className="text-xs text-orbit-red">Enter whole numbers from 0 to 4,294,967,295, with at least one above zero.</p>}
|
||||
</fieldset>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user