use chrono::{DateTime, Datelike, Utc}; use serde::{Deserialize, Serialize}; use std::collections::HashSet; use uuid::Uuid; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DecayPolicy { pub keep_daily: usize, pub keep_weekly: usize, pub keep_monthly: usize, } impl DecayPolicy { pub fn from_preset(name: &str) -> Self { match name { "week-of-dailies" => Self { keep_daily: 7, keep_weekly: 0, keep_monthly: 0, }, "month-of-weeklies" => Self { keep_daily: 0, keep_weekly: 4, keep_monthly: 0, }, "year-of-monthlies" => Self { keep_daily: 0, keep_weekly: 0, keep_monthly: 12, }, _ => Self { keep_daily: 7, keep_weekly: 4, keep_monthly: 12, }, } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SnapshotRef { pub id: Uuid, pub taken_at: DateTime, } #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, utoipa::ToSchema)] #[serde(default, deny_unknown_fields)] pub struct RetentionPolicy { pub keep_daily: u32, pub keep_weekly: u32, pub keep_monthly: u32, pub keep_yearly: u32, } impl RetentionPolicy { pub fn has_tiers(&self) -> bool { *self != Self::default() } } #[derive(Debug, Clone, Copy, Serialize, Deserialize)] #[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)] pub enum CaptureRetention { Age { days: u16, }, Count { #[serde(default = "fallback_count")] keep: u16, }, } fn fallback_count() -> u16 { 5 } impl Default for CaptureRetention { fn default() -> Self { Self::Age { days: 14 } } } impl CaptureRetention { pub fn is_valid(self) -> bool { match self { Self::Age { days } => days > 0, Self::Count { keep } => keep > 0, } } } pub fn evaluate_capture_retention( policy: CaptureRetention, mut snapshots: Vec, now: DateTime, ) -> Vec { snapshots.sort_unstable_by_key(|snapshot| std::cmp::Reverse((snapshot.taken_at, snapshot.id))); snapshots .into_iter() .enumerate() .skip(1) .filter_map(|(index, snapshot)| { let expired = match policy { CaptureRetention::Age { days } => { now.signed_duration_since(snapshot.taken_at).num_days() >= i64::from(days) } CaptureRetention::Count { keep } => index >= usize::from(keep), }; expired.then_some(snapshot.id) }) .collect() } /// A restore safety copy, for its own retention. #[derive(Debug, Clone)] pub struct SafetyRef { pub id: Uuid, pub taken_at: DateTime, pub target: String, } /// Safety copies kept per restore target regardless of age. pub const SAFETY_KEEP_PER_TARGET: usize = 3; /// Safety copies younger than this are always kept, however many there are. pub const SAFETY_KEEP_DAYS: i64 = 7; /// Which safety copies to forget. Each target keeps its newest few and everything from the last week, so the /// newest copy of a target is never forgotten here, and a burst of restores cannot erase the way back from /// the previous one. (A copy that a restore still depends on is protected separately, by the caller.) pub fn evaluate_safety_retention(snapshots: Vec, now: DateTime) -> Vec { let mut targets: std::collections::BTreeMap> = Default::default(); for snapshot in snapshots { targets .entry(snapshot.target.clone()) .or_default() .push(snapshot); } let mut forget = Vec::new(); for (_, mut copies) in targets { copies.sort_unstable_by_key(|s| std::cmp::Reverse((s.taken_at, s.id))); for (index, copy) in copies.into_iter().enumerate() { let recent = now.signed_duration_since(copy.taken_at).num_days() < SAFETY_KEEP_DAYS; if index >= SAFETY_KEEP_PER_TARGET && !recent { forget.push(copy.id); } } } forget } /// Keep the newest snapshot in each of the most recent occupied UTC periods. pub fn evaluate_gfs(policy: &RetentionPolicy, mut snapshots: Vec) -> Vec { if !policy.has_tiers() { return Vec::new(); } snapshots.sort_unstable_by_key(|s| std::cmp::Reverse((s.taken_at, s.id))); let mut keep = HashSet::new(); keep_periods(&snapshots, &mut keep, policy.keep_daily, |at| { at.date_naive() }); keep_periods(&snapshots, &mut keep, policy.keep_weekly, |at| { at.iso_week() }); keep_periods(&snapshots, &mut keep, policy.keep_monthly, |at| { (at.year(), at.month()) }); keep_periods(&snapshots, &mut keep, policy.keep_yearly, |at| at.year()); snapshots .into_iter() .filter_map(|s| (!keep.contains(&s.id)).then_some(s.id)) .collect() } fn keep_periods( snapshots: &[SnapshotRef], keep: &mut HashSet, mut count: u32, period: impl Fn(DateTime) -> K, ) { let mut last = None; for s in snapshots { if count == 0 { break; } let key = period(s.taken_at); if last.as_ref() != Some(&key) { keep.insert(s.id); count -= 1; last = Some(key); } } } /// Returns snapshot IDs to forget (newest-first input). pub fn evaluate_decay(policy: &DecayPolicy, mut snapshots: Vec) -> Vec { snapshots.sort_by(|a, b| b.taken_at.cmp(&a.taken_at)); let mut keep = std::collections::HashSet::new(); if policy.keep_daily > 0 { for s in snapshots.iter().take(policy.keep_daily) { keep.insert(s.id); } } if policy.keep_weekly > 0 { let mut weeks: Vec<(i64, SnapshotRef)> = Vec::new(); for s in &snapshots { let week = s.taken_at.timestamp() / (7 * 86400); if let Some(pos) = weeks.iter().position(|(w, _)| *w == week) { if s.taken_at > weeks[pos].1.taken_at { weeks[pos] = (week, s.clone()); } } else { weeks.push((week, s.clone())); } } weeks.sort_by(|a, b| b.1.taken_at.cmp(&a.1.taken_at)); for (_, s) in weeks.into_iter().take(policy.keep_weekly) { keep.insert(s.id); } } if policy.keep_monthly > 0 { let mut months: Vec<(i32, u32, SnapshotRef)> = Vec::new(); for s in &snapshots { let key = (s.taken_at.year(), s.taken_at.month()); if let Some(pos) = months .iter() .position(|(y, m, _)| *y == key.0 && *m == key.1) { if s.taken_at > months[pos].2.taken_at { months[pos] = (key.0, key.1, s.clone()); } } else { months.push((key.0, key.1, s.clone())); } } months.sort_by(|a, b| b.2.taken_at.cmp(&a.2.taken_at)); for (_, _, s) in months.into_iter().take(policy.keep_monthly) { keep.insert(s.id); } } snapshots .into_iter() .filter(|s| !keep.contains(&s.id)) .map(|s| s.id) .collect() } #[cfg(test)] mod tests { use super::*; use chrono::{Duration, TimeZone, Timelike}; #[test] fn capture_retention_keeps_one_old_archive_or_the_latest_five() { let now = Utc::now(); let snapshots: Vec<_> = (0..6) .map(|i| SnapshotRef { id: Uuid::new_v4(), taken_at: now - Duration::days(15 + i), }) .collect(); assert_eq!( evaluate_capture_retention(CaptureRetention::default(), snapshots.clone(), now), snapshots[1..] .iter() .map(|snap| snap.id) .collect::>() ); assert_eq!( evaluate_capture_retention(CaptureRetention::Count { keep: 5 }, snapshots.clone(), now), [snapshots[5].id] ); } #[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() { let policy = DecayPolicy::from_preset("week-of-dailies"); let now = Utc::now(); let snaps: Vec = (0..10) .map(|i| SnapshotRef { id: Uuid::new_v4(), taken_at: now - Duration::days(i), }) .collect(); let forget = evaluate_decay(&policy, snaps); assert_eq!(forget.len(), 3); } fn safety(day: u32, target: &str) -> SafetyRef { SafetyRef { id: Uuid::new_v4(), taken_at: Utc.with_ymd_and_hms(2026, 11, day, 4, 0, 0).unwrap(), target: target.into(), } } #[test] fn safety_snapshots_keep_the_newest_few_per_target_and_anything_recent() { let now = Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap(); let old: Vec<_> = (1..=6).map(|d| safety(d, "staging")).collect(); // all older than a week let recent = safety(28, "staging"); let mut all = old.clone(); all.push(recent.clone()); let forgotten = evaluate_safety_retention(all, now); // newest three overall (recent, day 6, day 5) stay; days 1..=4 go assert_eq!(forgotten.len(), 4); assert!(!forgotten.contains(&recent.id)); assert!(!forgotten.contains(&old[5].id) && !forgotten.contains(&old[4].id)); assert!(old[..4].iter().all(|s| forgotten.contains(&s.id))); } #[test] fn a_recent_safety_snapshot_is_never_forgotten_even_beyond_the_count() { let now = Utc.with_ymd_and_hms(2026, 11, 30, 12, 0, 0).unwrap(); let burst: Vec<_> = (24..=29).map(|d| safety(d, "staging")).collect(); // six in the last week assert!(evaluate_safety_retention(burst, now).is_empty()); } #[test] fn targets_are_counted_separately_and_each_keeps_at_least_its_newest() { let now = Utc.with_ymd_and_hms(2027, 6, 1, 0, 0, 0).unwrap(); // everything is very old let all = vec![safety(1, "staging"), safety(2, "staging"), safety(1, "dev")]; let forgotten = evaluate_safety_retention(all.clone(), now); assert!( forgotten.is_empty(), "three or fewer per target are always kept" ); let many: Vec<_> = (1..=5) .map(|d| safety(d, "staging")) .chain([safety(1, "dev")]) .collect(); let forgotten = evaluate_safety_retention(many.clone(), now); assert_eq!(forgotten.len(), 2); assert!( !forgotten.contains(&many[5].id), "the only snapshot of another target stays" ); } #[test] fn a_manifest_knows_whether_it_is_a_restore_safety_copy() { let mut manifest = crate::manifest::SnapshotManifest { snapshot_id: Uuid::nil(), orbit_id: Uuid::nil(), orbit_name: "x".into(), labels: vec!["postgres".into()], provider: "postgres".into(), paths: vec![], restore_hints: serde_json::json!({"job_id": "j"}), }; assert!(!manifest.is_restore_safety()); manifest.labels = vec!["restore-safety".into()]; assert!(manifest.is_restore_safety()); manifest.labels = vec![]; manifest.restore_hints = serde_json::json!({"safety_for": "job", "target_id": "t"}); assert!(manifest.is_restore_safety()); assert_eq!(manifest.safety_target().as_deref(), Some("t")); } }