feat: add managed database capture and operator restore

PostgreSQL and MySQL backups run through paired outposts, with operator sign-in, off-site copies, and legacy import. Retention stays on each orbit, so the unused retention console is removed.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-11-10 23:26:49 +07:00
parent 30a1a9b8f0
commit 6320b6f244
96 changed files with 11061 additions and 725 deletions

View File

@@ -58,6 +58,47 @@ impl RetentionPolicy {
}
}
#[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<SnapshotRef>,
now: DateTime<Utc>,
) -> Vec<Uuid> {
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()
}
/// 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() {
@@ -160,6 +201,19 @@ 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::<Vec<_>>());
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 {

View File

@@ -0,0 +1,89 @@
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CaptureFormat {
PostgresCustom,
PostgresSql,
MysqlSql,
Filesystem,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CaptureProfile {
pub application_id: Uuid,
pub orbit_id: Uuid,
pub outpost_id: Uuid,
pub format: CaptureFormat,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schedule: Option<CaptureSchedule>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub retention: Option<crate::decay::CaptureRetention>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct CaptureSchedule {
pub hour: u8,
#[serde(default)]
pub minute: u8,
pub timezone: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct CaptureJob {
pub id: Uuid,
pub profile: CaptureProfile,
pub actor: String,
pub status: String,
pub phase: String,
pub created_at: i64,
pub updated_at: i64,
pub snapshot_id: Option<Uuid>,
pub offsite_status: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureEvent {
pub at: i64,
pub phase: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureLease {
pub job_id: Uuid,
pub profile: CaptureProfile,
pub lease_id: Uuid,
#[serde(default)]
pub restic: bool,
}
pub const CAPTURE_LEASE_SECONDS: i64 = 90;
pub const CAPTURE_HEARTBEAT_SECONDS: u64 = 20;
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CaptureProgress {
Heartbeat,
Dumping,
Uploading,
DumpFailed,
UploadFailed,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CaptureReport {
pub lease_id: Uuid,
pub progress: CaptureProgress,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ResticCaptureCommit {
pub lease_id: Uuid,
pub snapshot_id: String,
pub identity: Option<crate::restore::DatabaseIdentity>,
pub sha256: Option<String>,
}

View File

@@ -1,9 +1,12 @@
pub mod config;
pub mod decay;
pub mod errors;
pub mod job;
pub mod manifest;
pub mod orbit;
pub mod reconstitute;
pub mod restore;
pub mod wormhole;
pub use config::*;

View File

@@ -0,0 +1,109 @@
use crate::job::CaptureFormat;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Engine {
Postgres,
Mysql,
}
impl CaptureFormat {
pub fn engine(self) -> Option<Engine> {
match self {
Self::PostgresCustom | Self::PostgresSql => Some(Engine::Postgres),
Self::MysqlSql => Some(Engine::Mysql),
Self::Filesystem => None,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DatabaseIdentity {
pub instance: String,
pub database: String,
}
impl DatabaseIdentity {
pub fn valid(&self, engine: Engine) -> bool {
let instance_valid = match engine {
Engine::Postgres => self
.instance
.parse::<u64>()
.is_ok_and(|id| id.to_string() == self.instance),
Engine::Mysql => {
Uuid::parse_str(&self.instance).is_ok_and(|id| id.to_string() == self.instance)
}
};
instance_valid
&& (1..=255).contains(&self.database.len())
&& !self.database.chars().any(char::is_control)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RestoreTarget {
pub id: Uuid,
pub application_id: Uuid,
pub outpost_id: Uuid,
pub name: String,
pub engine: Engine,
pub identity: DatabaseIdentity,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct RestoreRequest {
pub snapshot_id: Uuid,
pub target_id: Uuid,
pub confirmation: String,
}
impl RestoreRequest {
pub fn confirmation(snapshot: Uuid, target: Uuid) -> String {
format!("RESTORE {snapshot} TO {target}")
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RestoreJob {
pub id: Uuid,
pub snapshot_id: Uuid,
pub target: RestoreTarget,
pub actor: String,
pub status: String,
pub phase: String,
pub safety_snapshot_id: Option<Uuid>,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct RestoreArtifact {
pub format: CaptureFormat,
pub identity: DatabaseIdentity,
pub sha256: String,
}
#[derive(Deserialize, Serialize)]
pub struct RestoreLease {
pub job: RestoreJob,
pub token: Uuid,
pub artifact: RestoreArtifact,
}
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RestoreProgress {
Heartbeat,
Checking,
Safety,
InvalidPayload,
WrongTarget,
SafetyFailed,
Applied,
ApplyFailed,
}

View File

@@ -18,7 +18,15 @@ pub struct PairingCode {
pub hub_outpost_id: Option<Uuid>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[derive(Debug, Clone, Serialize)]
pub struct OutpostSummary {
pub id: Uuid,
pub name: Option<String>,
pub last_seen: Option<String>,
pub pairing_state: String,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct WormholeCredentials {
pub outpost_id: Uuid,
pub upload_token: String,