//! Build queue rows: deterministic ids, leases, step checkpoints (§8.1, §8.2). use rusqlite::{params, Connection, OptionalExtension}; use crate::db::Db; use crate::error::Result; use crate::time; #[derive(Debug, Clone)] pub struct BuildRow { pub id: String, pub pkgbase_id: i64, pub candidate_id: Option, pub release_id: Option, pub kind: String, pub world_snapshot_id: Option, pub build_profile: String, pub state: String, pub blocked_on_json: String, pub current_step: Option, pub lease_owner: Option, pub lease_expires_at: Option, pub attempt: i64, pub priority: i64, pub cancel_requested: bool, pub error: Option, } const BUILD_COLS: &str = "id, pkgbase_id, candidate_id, release_id, kind, world_snapshot_id, \ build_profile, state, blocked_on_json, current_step, lease_owner, lease_expires_at, \ attempt, priority, cancel_requested, error"; fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result { Ok(BuildRow { id: r.get(0)?, pkgbase_id: r.get(1)?, candidate_id: r.get(2)?, release_id: r.get(3)?, kind: r.get(4)?, world_snapshot_id: r.get(5)?, build_profile: r.get(6)?, state: r.get(7)?, blocked_on_json: r.get(8)?, current_step: r.get(9)?, lease_owner: r.get(10)?, lease_expires_at: r.get(11)?, attempt: r.get(12)?, priority: r.get(13)?, cancel_requested: r.get::<_, i64>(14)? != 0, error: r.get(15)?, }) } /// Deterministic build id (§8.2): re-submitting the same intent is a no-op, /// which is what makes manual rebuilds safe to enqueue carelessly. pub fn build_id(pkgbase: &str, identity_hash: &str, world_hash: &str, profile: &str) -> String { crate::hash::hex_str(&format!("{pkgbase}|{identity_hash}|{world_hash}|{profile}")) } /// Enqueue a build intent. `INSERT OR IGNORE` on the deterministic id. #[allow(clippy::too_many_arguments)] pub fn enqueue( db: &Db, id: &str, pkgbase_id: i64, candidate_id: Option, kind: &str, world_snapshot_id: Option, profile: &str, priority: i64, ) -> Result { let (id, kind, profile) = (id.to_string(), kind.to_string(), profile.to_string()); let at = time::now(); db.writer.tx(move |tx| { let n = tx.execute( "INSERT INTO build (id, pkgbase_id, candidate_id, kind, world_snapshot_id, build_profile, state, created_at, updated_at, priority) VALUES (?1,?2,?3,?4,?5,?6,'queued',?7,?7,?8) ON CONFLICT(id) DO NOTHING", params![id, pkgbase_id, candidate_id, kind, world_snapshot_id, profile, at, priority], )?; Ok(n == 1) }) } pub fn get(db: &Db, id: &str) -> Result> { let id = id.to_string(); db.read(move |c| { Ok(c.query_row( &format!("SELECT {BUILD_COLS} FROM build WHERE id=?1"), params![id], row_to_build, ) .optional()?) }) } pub fn list(db: &Db, states: &[&str], limit: i64) -> Result> { let states = states.iter().map(|s| s.to_string()).collect::>(); db.read(move |c| { let placeholders = states.iter().map(|_| "?").collect::>().join(","); let sql = format!( "SELECT {BUILD_COLS} FROM build WHERE state IN ({placeholders}) ORDER BY priority DESC, created_at LIMIT ?{}", states.len() + 1 ); let mut stmt = c.prepare(&sql)?; let rows = stmt.query_map( rusqlite::params_from_iter(states.iter().chain(std::iter::once(&limit.to_string())).map(|s| s as &dyn rusqlite::ToSql)), row_to_build, )?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } pub fn queued(db: &Db, limit: i64) -> Result> { db.read(|c| { let mut stmt = c.prepare( "SELECT id FROM build WHERE state='queued' ORDER BY priority DESC, created_at LIMIT ?1", )?; let rows = stmt.query_map(params![limit], |r| r.get::<_, String>(0))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } /// Claim a build for a worker: the lease is what makes a crash recoverable. pub fn claim(db: &Db, owner: &str, id: &str, lease_secs: i64) -> Result { let (owner, id) = (owner.to_string(), id.to_string()); let exp = time::secs_ahead(lease_secs); let at = time::now(); db.writer.tx(move |tx| { let n = tx.execute( "UPDATE build SET state='leased', lease_owner=?1, lease_expires_at=?2, attempt=attempt+1, updated_at=?3 WHERE id=?4 AND state IN ('queued','leased')", params![owner, exp, at, id], )?; Ok(n == 1) }) } pub fn extend_lease(db: &Db, id: &str, lease_secs: i64) -> Result<()> { let id = id.to_string(); let exp = time::secs_ahead(lease_secs); db.writer.tx(move |tx| { tx.execute( "UPDATE build SET lease_expires_at=?1 WHERE id=?2", params![exp, id], )?; Ok(()) }) } /// Reaper pass (§8.2): expired leases go back to the queue and their in-flight /// step is marked interrupted, so the checkpoint decides where it resumes. /// /// Both `leased` and `running` are reaped: a worker sets `running` as soon as it /// starts a step, so a process that dies mid-step leaves a `running` row, not a /// `leased` one. Reaping only `leased` would strand every real crash. pub fn reap_expired(db: &Db) -> Result { let now = time::now(); db.writer.tx(move |tx| { let ids: Vec = { let mut stmt = tx.prepare( "SELECT id FROM build WHERE state IN ('leased','running') AND lease_expires_at IS NOT NULL AND lease_expires_at < ?1", )?; let rows = stmt.query_map(params![now], |r| r.get::<_, String>(0))?; rows.filter_map(|r| r.ok()).collect() }; for id in &ids { tx.execute( "UPDATE build SET state='queued', lease_owner=NULL, lease_expires_at=NULL WHERE id=?1", params![id], )?; tx.execute( "UPDATE build_step SET status='interrupted', finished_at=?2 WHERE build_id=?1 AND status='running'", params![id, now], )?; } Ok(ids.len()) }) } pub fn set_state(db: &Db, id: &str, state: &str, error: Option<&str>) -> Result<()> { let (id, state) = (id.to_string(), state.to_string()); let error = error.map(|e| e.to_string()); let at = time::now(); db.writer.tx(move |tx| { tx.execute( "UPDATE build SET state=?1, error=?2, updated_at=?3, lease_owner=NULL, lease_expires_at=NULL WHERE id=?4", params![state, error, at, id], )?; Ok(()) }) } pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { let id = id.to_string(); let json = serde_json::to_string(blocked_on)?; let at = time::now(); db.writer.tx(move |tx| { tx.execute( "UPDATE build SET state='blocked_missing_dep', blocked_on_json=?1, updated_at=?2, lease_owner=NULL, lease_expires_at=NULL WHERE id=?3", params![json, at, id], )?; Ok(()) }) } /// Re-check blocked builds whenever a publish lands (§10.4). pub fn requeue_blocked(db: &Db) -> Result { db.writer.tx(|tx| { let n = tx.execute( "UPDATE build SET state='queued', updated_at=?1 WHERE state='blocked_missing_dep'", params![time::now()], )?; Ok(n) }) } pub fn request_cancel(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { tx.execute("UPDATE build SET cancel_requested=1 WHERE id=?1", params![id])?; Ok(()) }) } pub fn cancel_requested(db: &Db, id: &str) -> Result { let id = id.to_string(); db.read(move |c| { Ok(c.query_row("SELECT cancel_requested FROM build WHERE id=?1", params![id], |r| { Ok(r.get::<_, i64>(0)? != 0) }) .optional()? .unwrap_or(false)) }) } // ------------------------------------------------------------- step rows -- #[derive(Debug, Clone)] pub struct StepRow { pub step: String, pub status: String, pub attempt: i64, pub error: Option, } pub fn steps(db: &Db, id: &str) -> Result> { let id = id.to_string(); db.read(move |c| { let mut stmt = c.prepare( "SELECT step, status, attempt, error FROM build_step WHERE build_id=?1 ORDER BY rowid", )?; let rows = stmt.query_map(params![id], |r| { Ok(StepRow { step: r.get(0)?, status: r.get(1)?, attempt: r.get(2)?, error: r.get(3)? }) })?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } pub fn step_status(db: &Db, build_id: &str, step: &str) -> Result> { let (b, s) = (build_id.to_string(), step.to_string()); db.read(move |c| { Ok(c.query_row( "SELECT status FROM build_step WHERE build_id=?1 AND step=?2", params![b, s], |r| r.get(0), ) .optional()?) }) } pub fn begin_step(db: &Db, build_id: &str, step: &str, attempt: i64) -> Result<()> { let (b, s) = (build_id.to_string(), step.to_string()); let at = time::now(); db.writer.tx(move |tx| { tx.execute( "INSERT INTO build_step (build_id, step, status, attempt, started_at) VALUES (?1,?2,'running',?3,?4) ON CONFLICT(build_id, step) DO UPDATE SET status='running', attempt=?3, started_at=?4, error=NULL", params![b, s, attempt, at], )?; tx.execute("UPDATE build SET current_step=?1 WHERE id=?2", params![s, b])?; Ok(()) }) } pub fn finish_step(db: &Db, build_id: &str, step: &str, status: &str, output_digest: Option<&str>, error: Option<&str>) -> Result<()> { let (b, s, st) = (build_id.to_string(), step.to_string(), status.to_string()); let od = output_digest.map(|s| s.to_string()); let err = error.map(|s| s.to_string()); let at = time::now(); db.writer.tx(move |tx| { tx.execute( "UPDATE build_step SET status=?1, output_digest=?2, error=?3, finished_at=?4 WHERE build_id=?5 AND step=?6", params![st, od, err, at, b, s], )?; Ok(()) }) } /// Builds in flight (leased or running), for the backpressure calculation. pub fn in_flight(db: &Db) -> Result { db.read(|c| { Ok(c.query_row( "SELECT count(*) FROM build WHERE state IN ('leased','running')", [], |r| r.get::<_, i64>(0), )? as usize) }) } pub fn queue_depth(db: &Db) -> Result { db.read(|c| { Ok(c.query_row("SELECT count(*) FROM build WHERE state='queued'", [], |r| r.get::<_, i64>(0))? as usize) }) } pub fn blocked_builds(db: &Db) -> Result)>> { db.read(|c| { let mut stmt = c.prepare( "SELECT b.id, p.name, b.blocked_on_json FROM build b JOIN pkgbase p ON p.id = b.pkgbase_id WHERE b.state='blocked_missing_dep'", )?; let rows = stmt.query_map([], |r| { Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?)) })?; let mut out = Vec::new(); for r in rows { let (id, name, json) = r?; let blocked: Vec = serde_json::from_str(&json).unwrap_or_default(); out.push((id, name, blocked)); } Ok(out) }) } pub fn touch(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { tx.execute("UPDATE build SET updated_at=?1 WHERE id=?2", params![time::now(), id])?; Ok(()) }) } pub fn set_release(db: &Db, id: &str, release_id: i64) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", params![release_id, id])?; Ok(()) }) } pub fn set_world(db: &Db, id: &str, world_id: i64) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { tx.execute("UPDATE build SET world_snapshot_id=?1 WHERE id=?2", params![world_id, id])?; Ok(()) }) } pub fn set_candidate(db: &Db, id: &str, candidate_id: i64) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { tx.execute("UPDATE build SET candidate_id=?1 WHERE id=?2", params![candidate_id, id])?; Ok(()) }) } pub fn set_pkgbase(db: &Db, id: &str, pkgbase_id: i64) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { tx.execute("UPDATE build SET pkgbase_id=?1 WHERE id=?2", params![pkgbase_id, id])?; Ok(()) }) } pub fn set_profile(db: &Db, id: &str, profile: &str) -> Result<()> { let (id, p) = (id.to_string(), profile.to_string()); db.writer.tx(move |tx| { tx.execute("UPDATE build SET build_profile=?1 WHERE id=?2", params![p, id])?; Ok(()) }) } pub fn set_kind(db: &Db, id: &str, kind: &str) -> Result<()> { let (id, k) = (id.to_string(), kind.to_string()); db.writer.tx(move |tx| { tx.execute("UPDATE build SET kind=?1 WHERE id=?2", params![k, id])?; Ok(()) }) } pub fn set_blocked_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { let id = id.to_string(); let json = serde_json::to_string(blocked_on)?; db.writer.tx(move |tx| { tx.execute("UPDATE build SET blocked_on_json=?1 WHERE id=?2", params![json, id])?; Ok(()) }) } pub fn current_state(c: &Connection, id: &str) -> Result { Ok(c.query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)) .optional()? .unwrap_or_default()) } /// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and /// hand them to workers (§8.2). SQLite has no `SKIP LOCKED`, but with exactly one /// writer the claim cannot race: the SELECT and the UPDATE are the same /// transaction, so no other claimer can see a row in between. pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result> { if limit == 0 { return Ok(Vec::new()); } let owner = owner.to_string(); let exp = time::secs_ahead(lease_secs); let at = time::now(); db.writer.tx(move |tx| { let ids: Vec = { let mut stmt = tx.prepare( "SELECT id FROM build WHERE state='queued' ORDER BY priority DESC, created_at LIMIT ?1", )?; let rows = stmt.query_map(params![limit as i64], |r| r.get::<_, String>(0))?; rows.filter_map(|r| r.ok()).collect() }; for id in &ids { tx.execute( "UPDATE build SET state='leased', lease_owner=?1, lease_expires_at=?2, attempt=attempt+1, updated_at=?3 WHERE id=?4 AND state='queued'", params![owner, exp, at, id], )?; } Ok(ids) }) } /// A newer approved release for the same pkgbase makes an in-flight build /// pointless (§8.2 cancellation). Workers notice at the next step boundary and /// stop; nothing is killed mid-step, which is what keeps the checkpoints honest. pub fn cancel_superseded(db: &Db) -> Result { db.writer.tx(move |tx| { let n = tx.execute( "UPDATE build SET cancel_requested=1 WHERE state IN ('queued','leased','running') AND candidate_id IN (SELECT id FROM candidate WHERE state='superseded')", [], )?; Ok(n) }) } /// Put a build back on the queue after a transient failure, keeping the attempt /// count so the retry cap can bite (§8.4). pub fn requeue_transient(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); let at = time::now(); db.writer.tx(move |tx| { tx.execute( "UPDATE build SET state='queued', lease_owner=NULL, lease_expires_at=NULL, error=NULL, updated_at=?1 WHERE id=?2", params![at, id], )?; Ok(()) }) } /// Explicitly retry a failed build (§8.4). This is a human decision, not a /// policy: the failed step is put back to pending so it runs again, everything /// that succeeded stays checkpointed, and the attempt counter keeps counting. pub fn retry(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); let at = time::now(); db.writer.tx(move |tx| { tx.execute( "UPDATE build_step SET status='pending', error=NULL, started_at=NULL, finished_at=NULL WHERE build_id=?1 AND status IN ('failed','interrupted')", params![id], )?; tx.execute( "UPDATE build SET state='queued', error=NULL, cancel_requested=0, lease_owner=NULL, lease_expires_at=NULL, updated_at=?2 WHERE id=?1", params![id, at], )?; Ok(()) }) }