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:
693
crates/tessera-hub/src/db/jobs.rs
Normal file
693
crates/tessera-hub/src/db/jobs.rs
Normal file
@@ -0,0 +1,693 @@
|
||||
use super::*;
|
||||
use rusqlite::{types::Type, Row, TransactionBehavior};
|
||||
use tessera_core::job::{
|
||||
CaptureEvent, CaptureJob, CaptureLease, CaptureProfile, CaptureProgress, CaptureReport,
|
||||
CAPTURE_LEASE_SECONDS,
|
||||
};
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS capture_profiles (
|
||||
application_id TEXT PRIMARY KEY,
|
||||
orbit_id TEXT NOT NULL UNIQUE,
|
||||
outpost_id TEXT NOT NULL,
|
||||
profile TEXT NOT NULL,
|
||||
registered_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS capture_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
application_id TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
phase TEXT NOT NULL DEFAULT 'queued',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
lease_id TEXT,
|
||||
lease_until INTEGER,
|
||||
snapshot_id TEXT,
|
||||
schedule_slot INTEGER,
|
||||
offsite_status TEXT,
|
||||
offsite_attempt_at INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS capture_jobs_queue
|
||||
ON capture_jobs(application_id, status, created_at);
|
||||
CREATE INDEX IF NOT EXISTS capture_jobs_history
|
||||
ON capture_jobs(application_id, created_at);
|
||||
CREATE TABLE IF NOT EXISTS capture_events (
|
||||
id INTEGER PRIMARY KEY, job_id TEXT NOT NULL, at INTEGER NOT NULL, phase TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS capture_events_job ON capture_events(job_id, id);
|
||||
CREATE TRIGGER IF NOT EXISTS capture_events_queued AFTER INSERT ON capture_jobs
|
||||
BEGIN
|
||||
INSERT INTO capture_events(job_id, at, phase) VALUES (NEW.id, NEW.updated_at, NEW.phase);
|
||||
END;
|
||||
CREATE TRIGGER IF NOT EXISTS capture_events_progress AFTER UPDATE OF phase ON capture_jobs
|
||||
WHEN OLD.phase <> NEW.phase OR OLD.lease_id IS NOT NEW.lease_id
|
||||
BEGIN
|
||||
INSERT INTO capture_events(job_id, at, phase) VALUES (NEW.id, NEW.updated_at, NEW.phase);
|
||||
DELETE FROM capture_events WHERE job_id = NEW.id AND id < COALESCE((
|
||||
SELECT id FROM capture_events WHERE job_id = NEW.id ORDER BY id DESC LIMIT 1 OFFSET 63
|
||||
), 0);
|
||||
END;",
|
||||
)?;
|
||||
ensure_column(
|
||||
conn,
|
||||
"capture_profiles",
|
||||
"registered_at",
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
ensure_column(conn, "capture_jobs", "schedule_slot", "INTEGER")?;
|
||||
ensure_column(conn, "capture_jobs", "offsite_status", "TEXT")?;
|
||||
ensure_column(
|
||||
conn,
|
||||
"capture_jobs",
|
||||
"offsite_attempt_at",
|
||||
"INTEGER NOT NULL DEFAULT 0",
|
||||
)?;
|
||||
conn.execute(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS capture_jobs_slot ON capture_jobs(application_id, schedule_slot)",
|
||||
[],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const JOB_VIEW: &str = "SELECT j.id, p.profile, j.actor, j.status, j.phase, j.created_at,
|
||||
j.updated_at, j.snapshot_id, j.offsite_status FROM capture_jobs j JOIN capture_profiles p USING(application_id)";
|
||||
|
||||
pub(super) fn invalid_column(
|
||||
index: usize,
|
||||
error: impl std::error::Error + Send + Sync + 'static,
|
||||
) -> rusqlite::Error {
|
||||
rusqlite::Error::FromSqlConversionFailure(index, Type::Text, Box::new(error))
|
||||
}
|
||||
|
||||
fn parse_profile(row: &Row<'_>, index: usize) -> rusqlite::Result<CaptureProfile> {
|
||||
serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
|
||||
}
|
||||
|
||||
fn read_job(row: &Row<'_>) -> rusqlite::Result<CaptureJob> {
|
||||
Ok(CaptureJob {
|
||||
id: Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))?,
|
||||
profile: parse_profile(row, 1)?,
|
||||
actor: row.get(2)?,
|
||||
status: row.get(3)?,
|
||||
phase: row.get(4)?,
|
||||
created_at: row.get(5)?,
|
||||
updated_at: row.get(6)?,
|
||||
snapshot_id: row
|
||||
.get::<_, Option<String>>(7)?
|
||||
.map(|value| Uuid::parse_str(&value))
|
||||
.transpose()
|
||||
.map_err(|err| invalid_column(7, err))?,
|
||||
offsite_status: row.get(8)?,
|
||||
})
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn register_capture_profile(&self, profile: &CaptureProfile, now: i64) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let changed = conn.execute(
|
||||
"INSERT INTO capture_profiles (application_id, orbit_id, outpost_id, profile, registered_at)
|
||||
SELECT ?1, ?2, ?3, ?4, ?5
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM orbits WHERE id = ?2 AND provider = 'wormhole' AND dry_run = 0
|
||||
AND COALESCE(json_extract(provider_config, '$.source'), ?6) = ?6
|
||||
)
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active')
|
||||
ON CONFLICT DO NOTHING",
|
||||
params![profile.application_id.to_string(), profile.orbit_id.to_string(),
|
||||
profile.outpost_id.to_string(), serde_json::to_string(profile)?, now,
|
||||
if profile.format.engine().is_some() { "database" } else { "filesystem" }],
|
||||
)?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
|
||||
pub fn capture_profiles(&self) -> Result<Vec<CaptureProfile>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT profile FROM capture_profiles ORDER BY application_id")?;
|
||||
let rows = stmt.query_map([], |row| parse_profile(row, 0))?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn capture_schedule_cursors(&self) -> Result<Vec<(CaptureProfile, i64)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT p.profile, COALESCE(MAX(j.schedule_slot), p.registered_at)
|
||||
FROM capture_profiles p LEFT JOIN capture_jobs j USING(application_id)
|
||||
GROUP BY p.application_id",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| Ok((parse_profile(row, 0)?, row.get(1)?)))?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn enqueue_scheduled_capture(&self, application: Uuid, slot: i64, now: i64) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute(
|
||||
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at, schedule_slot)
|
||||
SELECT ?1, application_id, 'scheduler', ?4, ?4, ?3 FROM capture_profiles p
|
||||
WHERE application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = p.outpost_id AND state = 'active')
|
||||
ON CONFLICT(application_id, schedule_slot) DO NOTHING",
|
||||
params![Uuid::new_v4().to_string(), application.to_string(), slot, now],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn enqueue_capture(
|
||||
&self,
|
||||
application_id: Uuid,
|
||||
actor: &str,
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureJob>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let id = Uuid::new_v4();
|
||||
conn.execute(
|
||||
"INSERT INTO capture_jobs (id, application_id, actor, created_at, updated_at)
|
||||
SELECT ?1, application_id, ?3, ?4, ?4 FROM capture_profiles p
|
||||
WHERE application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = p.outpost_id AND state = 'active')",
|
||||
params![id.to_string(), application_id.to_string(), actor, now],
|
||||
)?;
|
||||
capture_job(&conn, id)
|
||||
}
|
||||
|
||||
pub fn capture_jobs(
|
||||
&self,
|
||||
application: Option<Uuid>,
|
||||
status: Option<&str>,
|
||||
limit: u16,
|
||||
) -> Result<Vec<CaptureJob>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"{JOB_VIEW} WHERE (?1 IS NULL OR j.application_id = ?1) AND (?2 IS NULL OR j.status = ?2)
|
||||
ORDER BY j.created_at DESC, j.rowid DESC LIMIT ?3"
|
||||
))?;
|
||||
let rows = stmt.query_map(
|
||||
params![application.map(|id| id.to_string()), status, limit],
|
||||
read_job,
|
||||
)?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn capture_events(&self, job: Uuid) -> Result<Vec<CaptureEvent>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT at, phase FROM capture_events WHERE job_id = ?1 ORDER BY id")?;
|
||||
let rows = stmt.query_map([job.to_string()], |row| {
|
||||
Ok(CaptureEvent {
|
||||
at: row.get(0)?,
|
||||
phase: row.get(1)?,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn capture_job(&self, id: Uuid) -> Result<Option<CaptureJob>> {
|
||||
capture_job(&self.conn.lock().unwrap(), id)
|
||||
}
|
||||
|
||||
pub fn capture_profile_for_orbit(&self, orbit: Uuid) -> Result<Option<CaptureProfile>> {
|
||||
Ok(self
|
||||
.conn
|
||||
.lock()
|
||||
.unwrap()
|
||||
.query_row(
|
||||
"SELECT profile FROM capture_profiles WHERE orbit_id = ?1",
|
||||
[orbit.to_string()],
|
||||
|row| parse_profile(row, 0),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn managed_orbit(&self, orbit_id: Uuid) -> Result<bool> {
|
||||
Ok(self.conn.lock().unwrap().query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM capture_profiles WHERE orbit_id = ?1)",
|
||||
[orbit_id.to_string()],
|
||||
|row| row.get(0),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn pending_offsite(&self) -> Result<Vec<Uuid>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id FROM capture_jobs WHERE offsite_status IN ('pending', 'failed')
|
||||
ORDER BY offsite_attempt_at, rowid LIMIT 10",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn set_offsite_result(&self, job: Uuid, success: bool) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute(
|
||||
"UPDATE capture_jobs SET offsite_status = ?2, offsite_attempt_at = ?3 WHERE id = ?1",
|
||||
params![
|
||||
job.to_string(),
|
||||
if success { "copied" } else { "failed" },
|
||||
chrono::Utc::now().timestamp()
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn offsite_pending(&self, id: Uuid) -> Result<bool> {
|
||||
Ok(self.conn.lock().unwrap().query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM capture_jobs WHERE snapshot_id = ?1 AND offsite_status IN ('pending', 'failed'))",
|
||||
[id.to_string()], |row| row.get(0),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn restic_required(&self, orbit: Uuid) -> Result<bool> {
|
||||
Ok(self.conn.lock().unwrap().query_row(
|
||||
"SELECT json_extract(provider_config, '$.source') IS NOT NULL FROM orbits WHERE id = ?1",
|
||||
[orbit.to_string()], |row| row.get(0),
|
||||
).optional()?.unwrap_or(false))
|
||||
}
|
||||
|
||||
pub fn capture_upload(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
lease: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureJob>> {
|
||||
capture_upload(&self.conn.lock().unwrap(), outpost, id, lease, now)
|
||||
}
|
||||
|
||||
pub fn publish_capture(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
lease: Uuid,
|
||||
offsite_enabled: bool,
|
||||
publish: impl FnOnce(&CaptureJob) -> Result<()>,
|
||||
) -> Result<Option<(Uuid, bool)>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let Some(job) = capture_upload(&tx, outpost, id, lease, now)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
if let Some(snapshot_id) = job.snapshot_id {
|
||||
return Ok(Some((snapshot_id, false)));
|
||||
}
|
||||
publish(&job)?;
|
||||
tx.execute(
|
||||
"UPDATE capture_jobs SET status = 'completed', phase = 'completed', snapshot_id = ?1, updated_at = ?2, offsite_status = ?3
|
||||
WHERE id = ?1",
|
||||
params![id.to_string(), now, offsite_enabled.then_some("pending")],
|
||||
)?;
|
||||
tx.execute(
|
||||
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), 'capture.completed', ?1)",
|
||||
[format!("actor={} job={id} snapshot={id}", job.actor)],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(Some((id, true)))
|
||||
}
|
||||
|
||||
pub fn incomplete_publications(&self) -> Result<Vec<Uuid>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT id FROM capture_jobs WHERE status IN ('running', 'failed')")?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Uuid::parse_str(&row.get::<_, String>(0)?).map_err(|err| invalid_column(0, err))
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn reconcile_capture(
|
||||
&self,
|
||||
snapshot: Uuid,
|
||||
orbit: Uuid,
|
||||
offsite_enabled: bool,
|
||||
) -> Result<()> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction()?;
|
||||
let changed = tx.execute(
|
||||
"UPDATE capture_jobs SET status = 'completed', phase = 'completed',
|
||||
snapshot_id = id, updated_at = ?3, offsite_status = ?4
|
||||
WHERE id = ?1 AND status <> 'completed' AND application_id IN (
|
||||
SELECT application_id FROM capture_profiles WHERE orbit_id = ?2
|
||||
)",
|
||||
params![
|
||||
snapshot.to_string(),
|
||||
orbit.to_string(),
|
||||
chrono::Utc::now().timestamp(),
|
||||
offsite_enabled.then_some("pending")
|
||||
],
|
||||
)?;
|
||||
if changed == 1 {
|
||||
tx.execute(
|
||||
"INSERT INTO audit_log (at, event, detail) VALUES (datetime('now'), 'capture.reconciled', ?1)",
|
||||
[format!("snapshot={snapshot}")],
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn claim_capture(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
application: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureLease>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let candidate = tx.query_row(
|
||||
"SELECT j.id, p.profile, json_extract(o.provider_config, '$.source') IS NOT NULL
|
||||
FROM capture_jobs j JOIN capture_profiles p USING(application_id) JOIN orbits o ON o.id = p.orbit_id
|
||||
WHERE p.outpost_id = ?1 AND p.application_id = ?2
|
||||
AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3))
|
||||
AND NOT EXISTS (SELECT 1 FROM capture_jobs active WHERE active.application_id = j.application_id
|
||||
AND active.status = 'running' AND active.lease_until > ?3)
|
||||
AND NOT EXISTS (SELECT 1 FROM restore_jobs r JOIN restore_targets t ON t.id = r.target_id
|
||||
WHERE t.application_id = j.application_id AND
|
||||
(r.status IN ('applying','recovery_required') OR (r.status = 'running' AND r.lease_until > ?3)))
|
||||
ORDER BY j.created_at, j.rowid LIMIT 1",
|
||||
params![outpost.to_string(), application.to_string(), now],
|
||||
|row| Ok((row.get::<_, String>(0)?, parse_profile(row, 1)?, row.get::<_, bool>(2)?)),
|
||||
).optional()?;
|
||||
let Some((id, profile, restic)) = candidate else {
|
||||
return Ok(None);
|
||||
};
|
||||
let job_id = Uuid::parse_str(&id)?;
|
||||
let lease_id = Uuid::new_v4();
|
||||
tx.execute(
|
||||
"UPDATE capture_jobs SET status = 'running', phase = 'claimed',
|
||||
lease_id = ?2, lease_until = ?3, updated_at = ?4 WHERE id = ?1",
|
||||
params![id, lease_id.to_string(), now + CAPTURE_LEASE_SECONDS, now],
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(Some(CaptureLease {
|
||||
job_id,
|
||||
profile,
|
||||
lease_id,
|
||||
restic,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn report_capture(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
job: Uuid,
|
||||
report: CaptureReport,
|
||||
now: i64,
|
||||
) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let (phase, prior, status) = match report.progress {
|
||||
CaptureProgress::Heartbeat => (None, None, "running"),
|
||||
CaptureProgress::Dumping => (Some("dumping"), Some("claimed"), "running"),
|
||||
CaptureProgress::Uploading => (Some("uploading"), Some("dumping"), "running"),
|
||||
CaptureProgress::DumpFailed => (Some("dump_failed"), Some("dumping"), "failed"),
|
||||
CaptureProgress::UploadFailed => (Some("upload_failed"), Some("uploading"), "failed"),
|
||||
};
|
||||
let changed = conn.execute(
|
||||
"UPDATE capture_jobs SET status = ?6, phase = COALESCE(?5, phase), updated_at = ?4, lease_until = ?7
|
||||
WHERE id = ?1 AND lease_id = ?2 AND status = 'running' AND lease_until > ?4
|
||||
AND (?8 IS NULL OR phase = ?8 OR phase = ?5)
|
||||
AND application_id IN (SELECT application_id FROM capture_profiles WHERE outpost_id = ?3)",
|
||||
params![job.to_string(), report.lease_id.to_string(), outpost.to_string(), now,
|
||||
phase, status, now + CAPTURE_LEASE_SECONDS, prior],
|
||||
)?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
}
|
||||
|
||||
fn capture_upload(
|
||||
conn: &Connection,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
lease: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<CaptureJob>> {
|
||||
Ok(conn.query_row(
|
||||
&format!("{JOB_VIEW} WHERE j.id = ?1 AND p.outpost_id = ?2 AND j.lease_id = ?3
|
||||
AND (j.status = 'completed' OR (j.status = 'running' AND j.phase = 'uploading' AND j.lease_until > ?4))"),
|
||||
params![id.to_string(), outpost.to_string(), lease.to_string(), now],
|
||||
read_job,
|
||||
).optional()?)
|
||||
}
|
||||
|
||||
fn capture_job(conn: &Connection, id: Uuid) -> Result<Option<CaptureJob>> {
|
||||
Ok(conn
|
||||
.query_row(
|
||||
&format!("{JOB_VIEW} WHERE j.id = ?1"),
|
||||
[id.to_string()],
|
||||
read_job,
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tessera_core::job::CaptureFormat;
|
||||
|
||||
async fn profile(db: &Db, outpost_id: Uuid) -> CaptureProfile {
|
||||
let orbit_id = Uuid::new_v4();
|
||||
db.upsert_orbit(&OrbitRow {
|
||||
id: orbit_id,
|
||||
name: "fixture".into(),
|
||||
provider: "wormhole".into(),
|
||||
provider_config: "{}".into(),
|
||||
schedule: None,
|
||||
decay_preset: "week-of-dailies".into(),
|
||||
retention: None,
|
||||
dry_run: false,
|
||||
last_status: "idle".into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
CaptureProfile {
|
||||
application_id: Uuid::new_v4(),
|
||||
orbit_id,
|
||||
outpost_id,
|
||||
format: CaptureFormat::PostgresCustom,
|
||||
schedule: None,
|
||||
retention: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn queue_survives_restart_and_fences_competing_agents() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("old.db");
|
||||
Connection::open(&path).unwrap().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);
|
||||
INSERT INTO orbits VALUES ('20200000-0000-0000-0000-000000000000', 'old', 'postgres',
|
||||
'{\"connection_url\":\"synthetic-secret\"}', NULL, 'week-of-dailies', 0, 'idle');"
|
||||
).unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
let other = Uuid::new_v4();
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let a = profile(&db, outpost).await;
|
||||
let b = profile(&db, outpost).await;
|
||||
let app = a.application_id;
|
||||
assert!(!db.register_capture_profile(&a, 100).unwrap());
|
||||
assert!(db.enqueue_capture(app, "fixture", 100).unwrap().is_none());
|
||||
for (id, token) in [(outpost, "token-a"), (other, "token-b")] {
|
||||
db.insert_wormhole_token(token, &id.to_string(), token, "9999")
|
||||
.unwrap();
|
||||
db.claim_wormhole_code(token, "agent", "2026")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
}
|
||||
assert!(db.register_capture_profile(&a, 100).unwrap());
|
||||
assert!(db.register_capture_profile(&b, 100).unwrap());
|
||||
let queued = db.enqueue_capture(app, "fixture", 100).unwrap().unwrap();
|
||||
db.enqueue_capture(app, "fixture", 100).unwrap().unwrap();
|
||||
db.enqueue_capture(b.application_id, "fixture", 100)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
drop(db);
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
assert!(
|
||||
db.list_orbits()
|
||||
.await
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|orbit| orbit.name == "old"
|
||||
&& orbit.provider_config.contains("synthetic-secret"))
|
||||
);
|
||||
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().status, "queued");
|
||||
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().actor, "fixture");
|
||||
assert!(db.claim_capture(other, app, 100).unwrap().is_none());
|
||||
let second = Db::connect(&path).await.unwrap();
|
||||
let race = std::thread::scope(|scope| {
|
||||
let first = scope.spawn(|| db.claim_capture(outpost, app, 100).unwrap());
|
||||
let second = scope.spawn(|| second.claim_capture(outpost, app, 100).unwrap());
|
||||
[first.join().unwrap(), second.join().unwrap()]
|
||||
});
|
||||
assert_eq!(race.iter().flatten().count(), 1);
|
||||
let lease = race.into_iter().flatten().next().unwrap();
|
||||
assert_eq!(lease.job_id, queued.id);
|
||||
assert!(db
|
||||
.claim_capture(outpost, b.application_id, 101)
|
||||
.unwrap()
|
||||
.is_some());
|
||||
let report = |lease_id, progress| CaptureReport { lease_id, progress };
|
||||
assert!(!db
|
||||
.report_capture(
|
||||
other,
|
||||
queued.id,
|
||||
report(lease.lease_id, CaptureProgress::Dumping),
|
||||
101
|
||||
)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_capture(
|
||||
outpost,
|
||||
queued.id,
|
||||
report(lease.lease_id, CaptureProgress::Dumping),
|
||||
101
|
||||
)
|
||||
.unwrap());
|
||||
drop(db);
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
let retry = db.claim_capture(outpost, app, 191).unwrap().unwrap();
|
||||
assert_eq!(retry.job_id, queued.id);
|
||||
assert_ne!(retry.lease_id, lease.lease_id);
|
||||
assert!(!db
|
||||
.report_capture(
|
||||
outpost,
|
||||
queued.id,
|
||||
report(lease.lease_id, CaptureProgress::Heartbeat),
|
||||
192
|
||||
)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_capture(
|
||||
outpost,
|
||||
queued.id,
|
||||
report(retry.lease_id, CaptureProgress::Dumping),
|
||||
192
|
||||
)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_capture(
|
||||
outpost,
|
||||
queued.id,
|
||||
report(retry.lease_id, CaptureProgress::DumpFailed),
|
||||
193
|
||||
)
|
||||
.unwrap());
|
||||
assert_eq!(db.capture_job(queued.id).unwrap().unwrap().status, "failed");
|
||||
assert!(db.claim_capture(outpost, app, 194).unwrap().is_some());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_orbit_uses_latest_job_even_after_a_success() {
|
||||
let db = Db::connect(std::path::Path::new(":memory:")).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
db.insert_wormhole_token("token", &outpost.to_string(), "code", "9999").unwrap();
|
||||
db.claim_wormhole_code("code", "agent", "2026").unwrap().unwrap();
|
||||
let profile = profile(&db, outpost).await;
|
||||
let app = profile.application_id;
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
assert!(db.register_capture_profile(&profile, now).unwrap());
|
||||
for (progress, expected) in [
|
||||
(CaptureProgress::Uploading, "completed"),
|
||||
(CaptureProgress::DumpFailed, "failed"),
|
||||
] {
|
||||
let job = db.enqueue_capture(app, "fixture", now).unwrap().unwrap();
|
||||
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "queued");
|
||||
let lease = db.claim_capture(outpost, app, now).unwrap().unwrap();
|
||||
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, "running");
|
||||
for progress in [CaptureProgress::Dumping, progress] {
|
||||
assert!(db.report_capture(outpost, job.id, CaptureReport {
|
||||
lease_id: lease.lease_id, progress,
|
||||
}, now).unwrap());
|
||||
}
|
||||
if expected == "completed" {
|
||||
assert!(db.publish_capture(outpost, job.id, lease.lease_id, false, |_| Ok(())).unwrap().is_some());
|
||||
}
|
||||
assert_eq!(db.list_orbits().await.unwrap()[0].last_status, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daily_slots_are_caught_up_once_and_offline_jobs_are_visible() {
|
||||
use chrono::{TimeZone, Utc};
|
||||
use tessera_core::job::CaptureSchedule;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let path = temp.path().join("jobs.db");
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
db.insert_wormhole_token("test", &outpost.to_string(), "code", "9999")
|
||||
.unwrap();
|
||||
db.claim_wormhole_code("code", "fixture", "2026")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let mut a = profile(&db, outpost).await;
|
||||
let mut b = profile(&db, outpost).await;
|
||||
a.schedule = Some(CaptureSchedule {
|
||||
hour: 2,
|
||||
minute: 0,
|
||||
timezone: "Asia/Jakarta".into(),
|
||||
});
|
||||
b.schedule = a.schedule.clone();
|
||||
let registered = Utc.with_ymd_and_hms(2026, 11, 7, 18, 0, 0).unwrap();
|
||||
for p in [&a, &b] {
|
||||
assert!(db
|
||||
.register_capture_profile(p, registered.timestamp())
|
||||
.unwrap());
|
||||
}
|
||||
let tick = crate::scheduler::tick_capture_schedules;
|
||||
tick(&db, registered).unwrap();
|
||||
assert!(db.capture_jobs(None, None, 100).unwrap().is_empty());
|
||||
let now = Utc.with_ymd_and_hms(2026, 11, 8, 19, 5, 0).unwrap();
|
||||
tick(&db, now).unwrap();
|
||||
drop(db);
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
tick(&db, now).unwrap();
|
||||
let all = db.capture_jobs(None, Some("queued"), 100).unwrap();
|
||||
assert_eq!(all.len(), 4);
|
||||
let history = db
|
||||
.capture_jobs(Some(a.application_id), Some("queued"), 100)
|
||||
.unwrap();
|
||||
assert_eq!(history.len(), 2);
|
||||
assert!(history.iter().all(|job| job.actor == "scheduler"));
|
||||
let first = db
|
||||
.claim_capture(outpost, a.application_id, now.timestamp())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
for (progress, offset) in [
|
||||
(CaptureProgress::Dumping, 1),
|
||||
(CaptureProgress::Heartbeat, 2),
|
||||
(CaptureProgress::DumpFailed, 3),
|
||||
] {
|
||||
assert!(db
|
||||
.report_capture(
|
||||
outpost,
|
||||
first.job_id,
|
||||
CaptureReport {
|
||||
lease_id: first.lease_id,
|
||||
progress
|
||||
},
|
||||
now.timestamp() + offset
|
||||
)
|
||||
.unwrap());
|
||||
}
|
||||
let failed = db
|
||||
.capture_jobs(Some(a.application_id), Some("failed"), 100)
|
||||
.unwrap();
|
||||
assert_eq!(failed.len(), 1);
|
||||
let events = db.capture_events(first.job_id).unwrap();
|
||||
assert_eq!(
|
||||
events
|
||||
.iter()
|
||||
.map(|event| event.phase.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["queued", "claimed", "dumping", "dump_failed"]
|
||||
);
|
||||
}
|
||||
}
|
||||
560
crates/tessera-hub/src/db/restore.rs
Normal file
560
crates/tessera-hub/src/db/restore.rs
Normal file
@@ -0,0 +1,560 @@
|
||||
use super::{jobs::invalid_column, *};
|
||||
use rusqlite::{Row, Transaction, TransactionBehavior};
|
||||
use tessera_core::{
|
||||
job::CAPTURE_LEASE_SECONDS,
|
||||
restore::{RestoreArtifact, RestoreJob, RestoreLease, RestoreProgress, RestoreTarget},
|
||||
};
|
||||
|
||||
pub(super) fn migrate(conn: &Connection) -> Result<()> {
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS restore_targets (
|
||||
id TEXT PRIMARY KEY,
|
||||
application_id TEXT NOT NULL,
|
||||
outpost_id TEXT NOT NULL,
|
||||
identity TEXT NOT NULL UNIQUE,
|
||||
profile TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS restore_jobs (
|
||||
id TEXT PRIMARY KEY,
|
||||
snapshot_id TEXT NOT NULL,
|
||||
target_id TEXT NOT NULL,
|
||||
actor TEXT NOT NULL,
|
||||
artifact TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'queued',
|
||||
phase TEXT NOT NULL DEFAULT 'queued',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
lease_token TEXT,
|
||||
lease_until INTEGER,
|
||||
attempt_safety_id TEXT,
|
||||
safety_id TEXT
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS restore_jobs_target ON restore_jobs(target_id, status);
|
||||
CREATE INDEX IF NOT EXISTS restore_jobs_snapshot ON restore_jobs(snapshot_id, safety_id, status);",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const VIEW: &str =
|
||||
"SELECT j.id, j.snapshot_id, t.profile, j.actor, j.status, j.phase, j.safety_id, j.created_at,
|
||||
j.updated_at, j.artifact, j.attempt_safety_id
|
||||
FROM restore_jobs j JOIN restore_targets t ON t.id = j.target_id";
|
||||
|
||||
fn uuid(row: &Row<'_>, index: usize) -> rusqlite::Result<Uuid> {
|
||||
Uuid::parse_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
|
||||
}
|
||||
|
||||
fn json<T: serde::de::DeserializeOwned>(row: &Row<'_>, index: usize) -> rusqlite::Result<T> {
|
||||
serde_json::from_str(&row.get::<_, String>(index)?).map_err(|err| invalid_column(index, err))
|
||||
}
|
||||
|
||||
fn read_job(row: &Row<'_>) -> rusqlite::Result<RestoreJob> {
|
||||
Ok(RestoreJob {
|
||||
id: uuid(row, 0)?,
|
||||
snapshot_id: uuid(row, 1)?,
|
||||
target: json(row, 2)?,
|
||||
actor: row.get(3)?,
|
||||
status: row.get(4)?,
|
||||
phase: row.get(5)?,
|
||||
safety_snapshot_id: row
|
||||
.get::<_, Option<String>>(6)?
|
||||
.map(|id| Uuid::parse_str(&id))
|
||||
.transpose()
|
||||
.map_err(|err| invalid_column(6, err))?,
|
||||
created_at: row.get(7)?,
|
||||
updated_at: row.get(8)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn restore_target_mismatch(
|
||||
target: &RestoreTarget,
|
||||
artifact: &RestoreArtifact,
|
||||
) -> Option<&'static str> {
|
||||
if Some(target.engine) != artifact.format.engine() {
|
||||
Some("Database engine differs from the snapshot")
|
||||
} else if target.identity == artifact.identity {
|
||||
Some("Target is the source database")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn register_restore_target(&self, target: &RestoreTarget) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let changed = conn.execute(
|
||||
"INSERT INTO restore_targets(id, application_id, outpost_id, identity, profile)
|
||||
SELECT ?1, ?2, ?3, ?4, ?5
|
||||
WHERE EXISTS (SELECT 1 FROM capture_profiles WHERE application_id = ?2)
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = ?3 AND state = 'active')
|
||||
ON CONFLICT DO NOTHING",
|
||||
params![
|
||||
target.id.to_string(),
|
||||
target.application_id.to_string(),
|
||||
target.outpost_id.to_string(),
|
||||
serde_json::to_string(&(target.engine, &target.identity))?,
|
||||
serde_json::to_string(target)?,
|
||||
],
|
||||
)?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
|
||||
pub fn restore_targets(&self, application: Uuid) -> Result<Vec<RestoreTarget>> {
|
||||
Ok(self.restore_targets_with_activity(application)?
|
||||
.into_iter().map(|(target, _)| target).collect())
|
||||
}
|
||||
|
||||
pub fn restore_targets_with_activity(&self, application: Uuid) -> Result<Vec<(RestoreTarget, bool)>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT t.profile, EXISTS (SELECT 1 FROM wormhole_tokens
|
||||
WHERE outpost_id = t.outpost_id AND state = 'active')
|
||||
FROM restore_targets t WHERE t.application_id = ?1 ORDER BY t.id",
|
||||
)?;
|
||||
let rows = stmt.query_map([application.to_string()], |row| Ok((json(row, 0)?, row.get(1)?)))?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn enqueue_restore(
|
||||
&self,
|
||||
snapshot: Uuid,
|
||||
application: Uuid,
|
||||
target: Uuid,
|
||||
actor: &str,
|
||||
artifact: &RestoreArtifact,
|
||||
now: i64,
|
||||
) -> Result<Option<RestoreJob>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let registered: Option<RestoreTarget> = tx.query_row(
|
||||
"SELECT t.profile FROM restore_targets t WHERE t.id = ?1 AND t.application_id = ?2
|
||||
AND EXISTS (SELECT 1 FROM wormhole_tokens WHERE outpost_id = t.outpost_id AND state = 'active')",
|
||||
params![target.to_string(), application.to_string()],
|
||||
|row| json(row, 0),
|
||||
).optional()?;
|
||||
let Some(registered) = registered else {
|
||||
return Ok(None);
|
||||
};
|
||||
if restore_target_mismatch(®istered, artifact).is_some() {
|
||||
return Ok(None);
|
||||
}
|
||||
let id = Uuid::new_v4();
|
||||
tx.execute(
|
||||
"INSERT INTO restore_jobs(id, snapshot_id, target_id, actor, artifact, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6)",
|
||||
params![id.to_string(), snapshot.to_string(), target.to_string(), actor,
|
||||
serde_json::to_string(artifact)?, now],
|
||||
)?;
|
||||
audit(
|
||||
&tx,
|
||||
"restore.queued",
|
||||
&format!("actor={actor} job={id} snapshot={snapshot} target={target}"),
|
||||
)?;
|
||||
let job = tx.query_row(
|
||||
&format!("{VIEW} WHERE j.id = ?1"),
|
||||
[id.to_string()],
|
||||
read_job,
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(Some(job))
|
||||
}
|
||||
|
||||
pub fn restore_job(&self, id: Uuid, now: i64) -> Result<Option<RestoreJob>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
expire_destructive(&conn, now)?;
|
||||
Ok(conn
|
||||
.query_row(
|
||||
&format!("{VIEW} WHERE j.id = ?1"),
|
||||
[id.to_string()],
|
||||
read_job,
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn restore_history(&self, snapshot: Uuid, now: i64) -> Result<Vec<RestoreJob>> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
expire_destructive(&conn, now)?;
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"{VIEW} WHERE j.snapshot_id = ?1 ORDER BY j.rowid DESC LIMIT 25"
|
||||
))?;
|
||||
let rows = stmt.query_map([snapshot.to_string()], read_job)?;
|
||||
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||
}
|
||||
|
||||
pub fn snapshot_in_restore(&self, id: Uuid) -> Result<bool> {
|
||||
let conn = self.conn.lock().unwrap();
|
||||
Ok(conn.query_row(
|
||||
"SELECT EXISTS(SELECT 1 FROM restore_jobs WHERE (snapshot_id = ?1 OR safety_id = ?1 OR attempt_safety_id = ?1)
|
||||
AND status IN ('queued','running','applying','recovery_required'))",
|
||||
[id.to_string()], |row| row.get(0),
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn claim_restore(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
target: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<RestoreLease>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
expire_destructive(&tx, now)?;
|
||||
let selected = tx.query_row(
|
||||
&format!("{VIEW} WHERE t.id = ?1 AND t.outpost_id = ?2
|
||||
AND (j.status = 'queued' OR (j.status = 'running' AND j.lease_until <= ?3))
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM restore_jobs active JOIN restore_targets owner ON owner.id = active.target_id
|
||||
WHERE owner.application_id = t.application_id
|
||||
AND (active.status IN ('applying','recovery_required')
|
||||
OR (active.status = 'running' AND active.lease_until > ?3))
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM capture_jobs c WHERE c.application_id = t.application_id
|
||||
AND c.status = 'running' AND c.lease_until > ?3
|
||||
)
|
||||
ORDER BY j.created_at, j.rowid LIMIT 1"),
|
||||
params![target.to_string(), outpost.to_string(), now],
|
||||
|row| Ok((read_job(row)?, json(row, 9)?)),
|
||||
).optional()?;
|
||||
let Some((mut job, artifact)) = selected else {
|
||||
tx.commit()?;
|
||||
return Ok(None);
|
||||
};
|
||||
let token = Uuid::new_v4();
|
||||
tx.execute(
|
||||
"UPDATE restore_jobs SET status = 'running', phase = 'claimed', lease_token = ?2, lease_until = ?3,
|
||||
attempt_safety_id = ?4, safety_id = NULL, updated_at = ?5 WHERE id = ?1",
|
||||
params![job.id.to_string(), token.to_string(), now + CAPTURE_LEASE_SECONDS,
|
||||
Uuid::new_v4().to_string(), now],
|
||||
)?;
|
||||
job.status = "running".into();
|
||||
job.phase = "claimed".into();
|
||||
job.safety_snapshot_id = None;
|
||||
job.updated_at = now;
|
||||
tx.commit()?;
|
||||
Ok(Some(RestoreLease {
|
||||
job,
|
||||
token,
|
||||
artifact,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn restore_access(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
token: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
|
||||
restore_access(&self.conn.lock().unwrap(), outpost, id, token, now)
|
||||
}
|
||||
|
||||
pub fn record_safety(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
token: Uuid,
|
||||
now: i64,
|
||||
publish: impl FnOnce(Uuid) -> Result<()>,
|
||||
) -> Result<Option<Uuid>> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let Some((job, _, expected)) = restore_access(&tx, outpost, id, token, now)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
if job.status != "running" {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(safety) = job.safety_snapshot_id {
|
||||
return Ok(Some(safety));
|
||||
}
|
||||
if job.phase != "safety" {
|
||||
return Ok(None);
|
||||
}
|
||||
publish(expected)?;
|
||||
tx.execute("UPDATE restore_jobs SET phase = 'ready', safety_id = ?2, updated_at = ?3 WHERE id = ?1",
|
||||
params![id.to_string(), expected.to_string(), now])?;
|
||||
audit(
|
||||
&tx,
|
||||
"restore.safety_committed",
|
||||
&format!("job={id} snapshot={expected}"),
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(Some(expected))
|
||||
}
|
||||
|
||||
pub fn authorize_apply(&self, outpost: Uuid, id: Uuid, token: Uuid, now: i64) -> Result<bool> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
if job.status != "running" || job.phase != "ready" || job.safety_snapshot_id.is_none() {
|
||||
return Ok(false);
|
||||
}
|
||||
tx.execute("UPDATE restore_jobs SET status = 'applying', phase = 'applying', updated_at = ?2, lease_until = ?3 WHERE id = ?1",
|
||||
params![id.to_string(), now, now + CAPTURE_LEASE_SECONDS])?;
|
||||
audit(
|
||||
&tx,
|
||||
"restore.apply_authorized",
|
||||
&format!("job={id} target={}", job.target.id),
|
||||
)?;
|
||||
tx.commit()?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn report_restore(
|
||||
&self,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
token: Uuid,
|
||||
progress: RestoreProgress,
|
||||
now: i64,
|
||||
) -> Result<bool> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let Some((job, _, _)) = restore_access(&tx, outpost, id, token, now)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let (status, phase) = match progress {
|
||||
RestoreProgress::Heartbeat => (job.status.as_str(), job.phase.as_str()),
|
||||
RestoreProgress::Checking if job.phase == "claimed" => ("running", "checking"),
|
||||
RestoreProgress::Safety if job.phase == "checking" => ("running", "safety"),
|
||||
RestoreProgress::InvalidPayload if job.phase == "checking" => {
|
||||
("failed", "invalid_payload")
|
||||
}
|
||||
RestoreProgress::WrongTarget if job.phase == "checking" => ("failed", "wrong_target"),
|
||||
RestoreProgress::SafetyFailed if matches!(job.phase.as_str(), "safety" | "ready") => {
|
||||
("failed", "safety_failed")
|
||||
}
|
||||
RestoreProgress::Applied if job.status == "applying" => ("completed", "completed"),
|
||||
RestoreProgress::ApplyFailed if job.status == "applying" => {
|
||||
("recovery_required", "apply_failed")
|
||||
}
|
||||
_ => return Ok(false),
|
||||
};
|
||||
tx.execute("UPDATE restore_jobs SET status = ?2, phase = ?3, updated_at = ?4, lease_until = ?5 WHERE id = ?1",
|
||||
params![id.to_string(), status, phase, now, now + CAPTURE_LEASE_SECONDS])?;
|
||||
if !matches!(progress, RestoreProgress::Heartbeat) {
|
||||
audit(&tx, "restore.phase", &format!("job={id} phase={phase}"))?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn reconcile_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
expire_destructive(&tx, now)?;
|
||||
let changed = tx.execute(
|
||||
"UPDATE restore_jobs SET status = 'reconciled', phase = 'reconciled', updated_at = ?2
|
||||
WHERE id = ?1 AND status = 'recovery_required'",
|
||||
params![id.to_string(), now],
|
||||
)?;
|
||||
if changed == 1 {
|
||||
audit(
|
||||
&tx,
|
||||
"restore.reconciled",
|
||||
&format!("actor={actor} job={id}"),
|
||||
)?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
|
||||
pub fn cancel_restore(&self, id: Uuid, actor: &str, now: i64) -> Result<bool> {
|
||||
let mut conn = self.conn.lock().unwrap();
|
||||
let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
|
||||
let changed = tx.execute(
|
||||
"UPDATE restore_jobs SET status = 'cancelled', phase = 'cancelled', updated_at = ?2
|
||||
WHERE id = ?1 AND status IN ('queued','running')",
|
||||
params![id.to_string(), now],
|
||||
)?;
|
||||
if changed == 1 {
|
||||
audit(&tx, "restore.cancelled", &format!("actor={actor} job={id}"))?;
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(changed == 1)
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_access(
|
||||
conn: &Connection,
|
||||
outpost: Uuid,
|
||||
id: Uuid,
|
||||
token: Uuid,
|
||||
now: i64,
|
||||
) -> Result<Option<(RestoreJob, RestoreArtifact, Uuid)>> {
|
||||
Ok(conn
|
||||
.query_row(
|
||||
&format!(
|
||||
"{VIEW} WHERE j.id = ?1 AND t.outpost_id = ?2 AND j.lease_token = ?3
|
||||
AND j.lease_until > ?4 AND j.status IN ('running', 'applying')"
|
||||
),
|
||||
params![id.to_string(), outpost.to_string(), token.to_string(), now],
|
||||
|row| Ok((read_job(row)?, json(row, 9)?, uuid(row, 10)?)),
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
fn expire_destructive(conn: &Connection, now: i64) -> Result<()> {
|
||||
conn.execute(
|
||||
"UPDATE restore_jobs SET status = 'recovery_required', phase = 'lease_lost', updated_at = ?1
|
||||
WHERE status = 'applying' AND lease_until <= ?1",
|
||||
[now],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn audit(tx: &Transaction<'_>, event: &str, detail: &str) -> Result<()> {
|
||||
tx.execute(
|
||||
"INSERT INTO audit_log(at, event, detail) VALUES (datetime('now'), ?1, ?2)",
|
||||
params![event, detail],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tessera_core::{
|
||||
job::{CaptureFormat, CaptureProfile},
|
||||
restore::{DatabaseIdentity, Engine},
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn expired_apply_survives_restart_and_fences_the_target_until_reconciled() {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let path = root.path().join("restore.db");
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let outpost = Uuid::new_v4();
|
||||
db.insert_wormhole_token("synthetic-token", &outpost.to_string(), "code", "9999")
|
||||
.unwrap();
|
||||
db.claim_wormhole_code("code", "fixture", "2026")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let orbit = Uuid::new_v4();
|
||||
db.upsert_orbit(&OrbitRow {
|
||||
id: orbit,
|
||||
name: "fixture".into(),
|
||||
provider: "wormhole".into(),
|
||||
provider_config: "{}".into(),
|
||||
schedule: None,
|
||||
decay_preset: "week-of-dailies".into(),
|
||||
retention: None,
|
||||
dry_run: false,
|
||||
last_status: "idle".into(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let app = Uuid::new_v4();
|
||||
assert!(db
|
||||
.register_capture_profile(
|
||||
&CaptureProfile {
|
||||
application_id: app,
|
||||
orbit_id: orbit,
|
||||
outpost_id: outpost,
|
||||
format: CaptureFormat::PostgresCustom,
|
||||
schedule: None,
|
||||
retention: None,
|
||||
},
|
||||
100
|
||||
)
|
||||
.unwrap());
|
||||
let target = Uuid::new_v4();
|
||||
assert!(db
|
||||
.register_restore_target(&RestoreTarget {
|
||||
id: target,
|
||||
application_id: app,
|
||||
outpost_id: outpost,
|
||||
name: "target".into(),
|
||||
engine: Engine::Postgres,
|
||||
identity: DatabaseIdentity {
|
||||
instance: "123".into(),
|
||||
database: "target".into()
|
||||
},
|
||||
})
|
||||
.unwrap());
|
||||
let snapshot = Uuid::new_v4();
|
||||
let artifact = RestoreArtifact {
|
||||
format: CaptureFormat::PostgresCustom,
|
||||
sha256: "0".repeat(64),
|
||||
identity: DatabaseIdentity {
|
||||
instance: "123".into(),
|
||||
database: "source".into(),
|
||||
},
|
||||
};
|
||||
let registered = db.restore_targets_with_activity(app).unwrap().pop().unwrap();
|
||||
assert!(registered.1);
|
||||
let same_source = RestoreArtifact { identity: registered.0.identity.clone(), ..artifact.clone() };
|
||||
assert_eq!(restore_target_mismatch(®istered.0, &same_source), Some("Target is the source database"));
|
||||
assert!(db.enqueue_restore(snapshot, app, target, "fixture", &same_source, 100).unwrap().is_none());
|
||||
let job = db
|
||||
.enqueue_restore(snapshot, app, target, "fixture", &artifact, 100)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let next_snapshot = Uuid::new_v4();
|
||||
let next = db
|
||||
.enqueue_restore(next_snapshot, app, target, "fixture", &artifact, 101)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let lease = db.claim_restore(outpost, target, 102).unwrap().unwrap();
|
||||
assert_eq!(lease.job.id, job.id);
|
||||
assert!(db.claim_restore(outpost, target, 103).unwrap().is_none());
|
||||
assert!(db.snapshot_in_restore(snapshot).unwrap());
|
||||
assert!(!db
|
||||
.authorize_apply(outpost, job.id, lease.token, 104)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_restore(outpost, job.id, lease.token, RestoreProgress::Checking, 104)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.report_restore(outpost, job.id, lease.token, RestoreProgress::Safety, 105)
|
||||
.unwrap());
|
||||
assert!(db
|
||||
.record_safety(outpost, job.id, lease.token, 106, |_| anyhow::bail!(
|
||||
"synthetic write failure"
|
||||
))
|
||||
.is_err());
|
||||
assert!(!db
|
||||
.authorize_apply(outpost, job.id, lease.token, 107)
|
||||
.unwrap());
|
||||
let safety = db
|
||||
.record_safety(outpost, job.id, lease.token, 108, |_| Ok(()))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(db
|
||||
.authorize_apply(outpost, job.id, lease.token, 109)
|
||||
.unwrap());
|
||||
assert!(!db
|
||||
.authorize_apply(outpost, job.id, lease.token, 110)
|
||||
.unwrap());
|
||||
drop(db);
|
||||
let db = Db::connect(&path).await.unwrap();
|
||||
db.migrate().await.unwrap();
|
||||
let late = 109 + CAPTURE_LEASE_SECONDS;
|
||||
assert!(db.claim_restore(outpost, target, late).unwrap().is_none());
|
||||
assert!(db
|
||||
.restore_access(outpost, job.id, lease.token, late)
|
||||
.unwrap()
|
||||
.is_none());
|
||||
assert!(!db
|
||||
.authorize_apply(outpost, job.id, lease.token, late)
|
||||
.unwrap());
|
||||
let interrupted = db.restore_job(job.id, late).unwrap().unwrap();
|
||||
assert_eq!(interrupted.status, "recovery_required");
|
||||
assert_eq!(interrupted.safety_snapshot_id, Some(safety));
|
||||
assert!(db.snapshot_in_restore(snapshot).unwrap());
|
||||
assert!(db.snapshot_in_restore(safety).unwrap());
|
||||
assert!(db.reconcile_restore(job.id, "fixture", late + 1).unwrap());
|
||||
assert!(!db.snapshot_in_restore(snapshot).unwrap());
|
||||
assert!(!db.snapshot_in_restore(safety).unwrap());
|
||||
let retry = db
|
||||
.claim_restore(outpost, target, late + 2)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(retry.job.id, next.id);
|
||||
assert_ne!(retry.token, lease.token);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user