Files
tessera/crates/tessera-hub/src/api/orbit.rs
Adnan Zahir 6320b6f244 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>
2026-11-10 23:26:49 +07:00

156 lines
5.3 KiB
Rust

use crate::db::OrbitRow;
use crate::state::HubState;
use anyhow::{Context, Result};
use tessera_core::manifest::SnapshotManifest;
use tessera_providers::{FilesystemConfig, MysqlSource, PostgresProvider, PostgresSource};
use uuid::Uuid;
#[derive(serde::Deserialize)]
#[serde(tag = "engine", rename_all = "snake_case")]
pub(super) enum DatabaseSource {
Postgres(PostgresSource),
Mysql(MysqlSource),
}
impl DatabaseSource {
pub(super) fn valid_endpoint(&self) -> bool {
let (host, port, database, user, password_file) = match self {
Self::Postgres(source) if source.bastion.is_none() => (
&source.host,
source.port,
&source.database,
&source.user,
&source.password_file,
),
Self::Mysql(MysqlSource::Direct {
host,
port,
database,
user,
password_file,
..
}) => (host, *port, database, user, password_file),
_ => return false,
};
port != 0
&& password_file.is_absolute()
&& [host, database, user]
.iter()
.all(|value| !value.trim().is_empty() && !value.chars().any(char::is_control))
}
}
pub async fn run_orbit_internal(state: HubState, orbit: OrbitRow) -> Result<Option<Uuid>> {
anyhow::ensure!(
orbit.provider != "wormhole",
"Wormhole backups are started by the outpost agent"
);
let orbit_id = orbit.id;
anyhow::ensure!(
state.active_orbits.lock().await.insert(orbit_id),
"orbit already running"
);
// Keep capture and its status update together if the requesting client disconnects.
tokio::spawn(async move {
let result = run_orbit_row(&state, orbit).await;
if result.is_err() {
if let Err(error) = state.db.set_orbit_status(orbit_id, "failed").await {
tracing::error!(%orbit_id, %error, "could not record failed capture");
}
}
state.active_orbits.lock().await.remove(&orbit_id);
result
})
.await?
}
async fn run_orbit_row(state: &HubState, orbit: OrbitRow) -> Result<Option<Uuid>> {
state.db.set_orbit_status(orbit.id, "running").await?;
let config: serde_json::Value = serde_json::from_str(&orbit.provider_config)?;
let mut manifest = SnapshotManifest {
snapshot_id: Uuid::new_v4(),
orbit_id: orbit.id,
orbit_name: orbit.name.clone(),
labels: vec![orbit.provider.clone()],
provider: orbit.provider.clone(),
paths: vec![],
restore_hints: serde_json::Value::Null,
};
let (payload, max_file_bytes) = match orbit.provider.as_str() {
"filesystem" => {
let config: FilesystemConfig = serde_json::from_value(config)?;
manifest.paths = config.paths;
(None, config.max_file_bytes)
}
"database" => {
let source = serde_json::from_value::<DatabaseSource>(config)?;
let file = tempfile::tempfile()?;
let (engine, format) = match source {
DatabaseSource::Postgres(source) => {
source.dump_to(file.try_clone()?, "plain").await?;
("postgres", "plain")
}
DatabaseSource::Mysql(source) => {
source.dump_to(file.try_clone()?).await?;
("mysql", "plain")
}
};
manifest.provider = engine.into();
manifest.restore_hints = serde_json::json!({"engine": engine, "format": format});
(Some(file), None)
}
"postgres" => {
let provider = PostgresProvider::from_config(&config)?;
let file = tempfile::tempfile()?;
manifest.restore_hints = provider.dump_to(file.try_clone()?).await?;
(Some(file), None)
}
"wormhole" => anyhow::bail!("Wormhole backups are started by the outpost agent"),
"command" => {
anyhow::bail!("command provider is outside this release; use filesystem or postgres")
}
other => anyhow::bail!("unknown provider '{other}'"),
};
let vault = state.vault.clone().read_owned().await;
let snap = tokio::task::spawn_blocking(move || {
match payload {
Some(file) => vault.snapshot_payload(manifest, file, orbit.dry_run),
None => vault.snapshot_files(manifest, max_file_bytes, orbit.dry_run),
}
.context("vault snapshot")
})
.await??;
let snap_id = snap.id;
let retained_snapshot = if orbit.dry_run {
None
} else {
let pruned = state.prune_orbit(orbit.id).await?;
state
.db
.audit("decay.pruned", &format!("orbit={}", orbit.name))
.await?;
(!pruned.contains(&snap_id)).then_some(snap_id)
};
let status = if orbit.dry_run {
"rehearsed"
} else {
"completed"
};
state.db.set_orbit_status(orbit.id, status).await?;
state
.db
.audit(
if orbit.dry_run {
"orbit.rehearsed"
} else {
"orbit.completed"
},
&format!("snapshot={snap_id}"),
)
.await?;
Ok(retained_snapshot)
}