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

@@ -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"]
);
}
}