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:
428
crates/tessera-hub/src/api/jobs.rs
Normal file
428
crates/tessera-hub/src/api/jobs.rs
Normal file
@@ -0,0 +1,428 @@
|
||||
use super::routes::{require_admin, require_admin_mutation, upload_token};
|
||||
use crate::state::HubState;
|
||||
use axum::{
|
||||
body::{Body, HttpBody},
|
||||
extract::{rejection::JsonRejection, ConnectInfo, Path, Query, State},
|
||||
http::{header, HeaderMap, StatusCode},
|
||||
routing::{get, post},
|
||||
Json, Router,
|
||||
};
|
||||
use base64::Engine;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{net::SocketAddr, pin::Pin, time::Duration};
|
||||
use tessera_core::job::{
|
||||
CaptureEvent, CaptureFormat, CaptureJob, CaptureLease, CaptureProfile, CaptureReport, ResticCaptureCommit,
|
||||
};
|
||||
use tessera_core::{restore::DatabaseIdentity, SnapshotManifest};
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(super) fn routes() -> Router<HubState> {
|
||||
Router::new()
|
||||
.route(
|
||||
"/api/v1/capture-profiles",
|
||||
get(profiles).post(register_profile),
|
||||
)
|
||||
.route("/api/v1/capture-profiles/:id/jobs", post(enqueue))
|
||||
.route("/api/v1/capture-jobs", get(history))
|
||||
.route("/api/v1/capture-jobs/:id", get(job))
|
||||
.route("/api/v1/capture-jobs/:id/events", get(events))
|
||||
.route("/api/v1/wormhole/capture/:application/claim", post(claim))
|
||||
.route("/api/v1/wormhole/capture/:id/report", post(report))
|
||||
.route("/api/v1/wormhole/capture/:id/payload", post(upload))
|
||||
.route("/api/v1/wormhole/capture/:id/restic", post(commit_restic))
|
||||
}
|
||||
|
||||
async fn profiles(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<CaptureProfile>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state.db.capture_profiles().map(Json).map_err(internal)
|
||||
}
|
||||
|
||||
async fn register_profile(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Json(profile): Json<CaptureProfile>,
|
||||
) -> Result<(StatusCode, Json<CaptureProfile>), StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
if profile
|
||||
.retention
|
||||
.is_some_and(|retention| !retention.is_valid())
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
if let Some(schedule) = &profile.schedule {
|
||||
crate::scheduler::capture_schedule(schedule).ok_or(StatusCode::BAD_REQUEST)?;
|
||||
}
|
||||
let _vault = state.vault.write().await;
|
||||
if !state
|
||||
.db
|
||||
.register_capture_profile(&profile, now())
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
state
|
||||
.db
|
||||
.audit(
|
||||
"capture.profile_registered",
|
||||
&format!("actor={actor} application={}", profile.application_id),
|
||||
)
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
Ok((StatusCode::CREATED, Json(profile)))
|
||||
}
|
||||
|
||||
async fn enqueue(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<(StatusCode, Json<CaptureJob>), StatusCode> {
|
||||
let actor = require_admin_mutation(&state, peer, &headers)?;
|
||||
let job = state
|
||||
.db
|
||||
.enqueue_capture(id, &actor.name, now())
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
Ok((StatusCode::ACCEPTED, Json(job)))
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct JobFilter {
|
||||
application_id: Option<Uuid>,
|
||||
status: Option<String>,
|
||||
limit: Option<u16>,
|
||||
}
|
||||
|
||||
async fn history(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Query(filter): Query<JobFilter>,
|
||||
) -> Result<Json<Vec<CaptureJob>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
if filter
|
||||
.status
|
||||
.as_deref()
|
||||
.is_some_and(|status| !matches!(status, "queued" | "running" | "completed" | "failed"))
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
state
|
||||
.db
|
||||
.capture_jobs(
|
||||
filter.application_id,
|
||||
filter.status.as_deref(),
|
||||
filter.limit.unwrap_or(50).clamp(1, 200),
|
||||
)
|
||||
.map(Json)
|
||||
.map_err(internal)
|
||||
}
|
||||
|
||||
async fn events(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<Vec<CaptureEvent>>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
.db
|
||||
.capture_job(id)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
state.db.capture_events(id).map(Json).map_err(internal)
|
||||
}
|
||||
|
||||
async fn job(
|
||||
ConnectInfo(peer): ConnectInfo<SocketAddr>,
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> Result<Json<CaptureJob>, StatusCode> {
|
||||
require_admin(&state, peer, &headers)?;
|
||||
state
|
||||
.db
|
||||
.capture_job(id)
|
||||
.map_err(internal)?
|
||||
.map(Json)
|
||||
.ok_or(StatusCode::NOT_FOUND)
|
||||
}
|
||||
|
||||
async fn claim(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(application): Path<Uuid>,
|
||||
) -> Result<Json<Option<CaptureLease>>, StatusCode> {
|
||||
let outpost = outpost(&state, &headers)?;
|
||||
let mut lease = state.db.claim_capture(outpost, application, now()).map_err(internal)?;
|
||||
if let Some(lease) = &mut lease {
|
||||
lease.restic |= lease.profile.format == CaptureFormat::Filesystem
|
||||
|| state.vault.read().await.outpost_repository_configured(lease.profile.orbit_id).map_err(internal)?;
|
||||
}
|
||||
Ok(Json(lease))
|
||||
}
|
||||
|
||||
async fn report(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
body: Result<Json<CaptureReport>, JsonRejection>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let outpost = outpost(&state, &headers)?;
|
||||
let Json(body) = body.map_err(|_| StatusCode::UNPROCESSABLE_ENTITY)?;
|
||||
if !state
|
||||
.db
|
||||
.report_capture(outpost, id, body, now())
|
||||
.map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
async fn upload(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
body: Body,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let outpost = outpost(&state, &headers)?;
|
||||
let lease = Uuid::parse_str(header_value(&headers, "x-tessera-lease-id")?)
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let job = state
|
||||
.db
|
||||
.capture_upload(outpost, id, lease, now())
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::CONFLICT)?;
|
||||
if job.profile.format == CaptureFormat::Filesystem
|
||||
|| state.db.restic_required(job.profile.orbit_id).map_err(internal)?
|
||||
|| state.vault.read().await.outpost_repository_configured(job.profile.orbit_id).map_err(internal)?
|
||||
{
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
let identity = headers
|
||||
.get("x-tessera-source-identity")
|
||||
.map(|header| {
|
||||
let decoded = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
||||
.decode(header.as_bytes())
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
let identity: DatabaseIdentity =
|
||||
serde_json::from_slice(&decoded).map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if !job.profile.format.engine().is_some_and(|engine| identity.valid(engine)) {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
Ok(identity)
|
||||
})
|
||||
.transpose()?;
|
||||
let (file, expected) = receive_payload(&state, &headers, body, job.profile.format).await?;
|
||||
if let Some(snapshot) = job.snapshot_id {
|
||||
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
|
||||
}
|
||||
let orbit_id = job.profile.orbit_id;
|
||||
let manifest = capture_manifest(&state, &job, identity, Some(hex::encode(expected))).await?;
|
||||
let vault = state.vault.clone().read_owned().await;
|
||||
let db = state.db.clone();
|
||||
let offsite_enabled = state.offsite.is_some();
|
||||
let (snapshot, created) = tokio::task::spawn_blocking(move || {
|
||||
// SQLite fencing covers metadata publication. Restic work happens before the transaction.
|
||||
let prepared = if vault.has_published_snapshot(id)? {
|
||||
None
|
||||
} else {
|
||||
Some(vault.prepare_payload(manifest, file, false)?)
|
||||
};
|
||||
let mut wrote = false;
|
||||
let published = db.publish_capture(outpost, id, lease, offsite_enabled, |_| {
|
||||
if !vault.has_published_snapshot(id)? {
|
||||
vault.publish_prepared(
|
||||
prepared
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("prepared snapshot missing"))?,
|
||||
)?;
|
||||
wrote = true;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
// Preserve a prepared copy on an ambiguous commit error for reconciliation.
|
||||
if !wrote {
|
||||
if let Some(snap) = prepared.as_ref() {
|
||||
if let Err(error) = vault.discard_prepared(snap) {
|
||||
tracing::warn!(%id, %error, "could not discard unpublished capture");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok::<_, anyhow::Error>(published)
|
||||
})
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::CONFLICT)?;
|
||||
if created && state.prune_orbit(orbit_id).await.is_err() {
|
||||
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
|
||||
}
|
||||
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
|
||||
}
|
||||
|
||||
async fn commit_restic(
|
||||
State(state): State<HubState>,
|
||||
headers: HeaderMap,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(commit): Json<ResticCaptureCommit>,
|
||||
) -> Result<Json<serde_json::Value>, StatusCode> {
|
||||
let outpost = outpost(&state, &headers)?;
|
||||
let job = state.db.capture_upload(outpost, id, commit.lease_id, now())
|
||||
.map_err(internal)?.ok_or(StatusCode::CONFLICT)?;
|
||||
if let Some(snapshot) = job.snapshot_id {
|
||||
return Ok(Json(serde_json::json!({ "snapshot_id": snapshot })));
|
||||
}
|
||||
let engine = job.profile.format.engine();
|
||||
if commit.identity.as_ref().is_some_and(|identity| !engine.is_some_and(|engine| identity.valid(engine)))
|
||||
|| (engine.is_some() && !commit.sha256.as_ref().is_some_and(|hash| {
|
||||
hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit())
|
||||
}))
|
||||
|| (engine.is_none() && commit.sha256.is_some())
|
||||
{
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
let orbit_id = job.profile.orbit_id;
|
||||
let manifest = capture_manifest(&state, &job, commit.identity, commit.sha256).await?;
|
||||
let vault = state.vault.clone().read_owned().await;
|
||||
let db = state.db.clone();
|
||||
let offsite = state.offsite.is_some() && engine.is_some();
|
||||
let (snapshot, created) = tokio::task::spawn_blocking(move || {
|
||||
let prepared = vault.prepare_outpost_capture(manifest, outpost, &commit.snapshot_id)?;
|
||||
db.publish_capture(outpost, id, commit.lease_id, offsite, |_| {
|
||||
if !vault.has_published_snapshot(id)? {
|
||||
vault.publish_prepared(&prepared)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}).await.map_err(internal)?.map_err(internal)?.ok_or(StatusCode::CONFLICT)?;
|
||||
if created && state.prune_orbit(orbit_id).await.is_err() {
|
||||
tracing::warn!(%id, %orbit_id, "could not apply capture retention");
|
||||
}
|
||||
Ok(Json(serde_json::json!({ "snapshot_id": snapshot })))
|
||||
}
|
||||
|
||||
async fn capture_manifest(
|
||||
state: &HubState,
|
||||
job: &CaptureJob,
|
||||
identity: Option<DatabaseIdentity>,
|
||||
digest: Option<String>,
|
||||
) -> Result<SnapshotManifest, StatusCode> {
|
||||
let id = job.id;
|
||||
let orbit_id = job.profile.orbit_id;
|
||||
let orbit = state
|
||||
.db
|
||||
.list_orbits()
|
||||
.await
|
||||
.map_err(internal)?
|
||||
.into_iter()
|
||||
.find(|orbit| orbit.id == orbit_id)
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
let (engine, format) = match job.profile.format {
|
||||
CaptureFormat::PostgresCustom => ("postgres", "custom"),
|
||||
CaptureFormat::PostgresSql => ("postgres", "plain"),
|
||||
CaptureFormat::MysqlSql => ("mysql", "plain"),
|
||||
CaptureFormat::Filesystem => ("filesystem", "tar"),
|
||||
};
|
||||
Ok(SnapshotManifest {
|
||||
snapshot_id: id,
|
||||
orbit_id,
|
||||
orbit_name: orbit.name,
|
||||
labels: vec![engine.into()],
|
||||
provider: engine.into(),
|
||||
paths: vec![],
|
||||
restore_hints: serde_json::json!({
|
||||
"engine": engine, "format": format, "job_id": id, "outpost_id": job.profile.outpost_id,
|
||||
"application_id": job.profile.application_id, "sha256": digest,
|
||||
"queued_at": job.created_at, "uploaded_at": now(), "source_identity": identity
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn receive_payload(
|
||||
state: &HubState,
|
||||
headers: &HeaderMap,
|
||||
mut body: Body,
|
||||
format: CaptureFormat,
|
||||
) -> Result<(std::fs::File, [u8; 32]), StatusCode> {
|
||||
let length = header_value(headers, header::CONTENT_LENGTH.as_str())?
|
||||
.parse::<u64>()
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if length == 0 || length > 100 * 1024 * 1024 * 1024 {
|
||||
return Err(StatusCode::PAYLOAD_TOO_LARGE);
|
||||
}
|
||||
let mut expected = [0u8; 32];
|
||||
hex::decode_to_slice(header_value(headers, "x-tessera-sha256")?, &mut expected)
|
||||
.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
|
||||
let file = tempfile::tempfile_in(&state.data_dir).map_err(internal)?;
|
||||
let mut file = tokio::fs::File::from_std(file);
|
||||
let mut digest = Sha256::new();
|
||||
let mut bytes = 0;
|
||||
loop {
|
||||
let next = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx));
|
||||
let Some(frame) = tokio::time::timeout(Duration::from_secs(30), next)
|
||||
.await
|
||||
.map_err(|_| StatusCode::REQUEST_TIMEOUT)?
|
||||
else {
|
||||
break;
|
||||
};
|
||||
let frame = frame.map_err(|_| StatusCode::BAD_REQUEST)?;
|
||||
if let Ok(chunk) = frame.into_data() {
|
||||
bytes += chunk.len() as u64;
|
||||
if bytes > length {
|
||||
return Err(StatusCode::BAD_REQUEST);
|
||||
}
|
||||
digest.update(&chunk);
|
||||
file.write_all(&chunk).await.map_err(internal)?;
|
||||
}
|
||||
}
|
||||
if bytes != length || digest.finalize()[..] != expected {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
file.flush().await.map_err(internal)?;
|
||||
if format == CaptureFormat::PostgresCustom {
|
||||
let mut signature = [0; 5];
|
||||
file.seek(std::io::SeekFrom::Start(0))
|
||||
.await
|
||||
.map_err(internal)?;
|
||||
if file.read_exact(&mut signature).await.is_err() || &signature != b"PGDMP" {
|
||||
return Err(StatusCode::UNPROCESSABLE_ENTITY);
|
||||
}
|
||||
}
|
||||
Ok((file.into_std().await, expected))
|
||||
}
|
||||
|
||||
pub(super) fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Result<&'a str, StatusCode> {
|
||||
headers
|
||||
.get(name)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.ok_or(StatusCode::BAD_REQUEST)
|
||||
}
|
||||
|
||||
pub(super) fn outpost(state: &HubState, headers: &HeaderMap) -> Result<Uuid, StatusCode> {
|
||||
let token = upload_token(state, headers)?;
|
||||
let id = state
|
||||
.db
|
||||
.upload_token_outpost(token)
|
||||
.map_err(internal)?
|
||||
.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let id = Uuid::parse_str(&id).map_err(internal)?;
|
||||
state.db.touch_outpost(id).map_err(internal)?;
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub(super) fn now() -> i64 {
|
||||
chrono::Utc::now().timestamp()
|
||||
}
|
||||
|
||||
pub(super) fn internal(_: impl std::fmt::Display) -> StatusCode {
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
}
|
||||
Reference in New Issue
Block a user