diff options
Diffstat (limited to 'src/db')
| -rw-r--r-- | src/db/builds.rs | 122 | ||||
| -rw-r--r-- | src/db/model.rs | 132 | ||||
| -rw-r--r-- | src/db/queries.rs | 14 |
3 files changed, 207 insertions, 61 deletions
diff --git a/src/db/builds.rs b/src/db/builds.rs index 5c4d1d4..a41308e 100644 --- a/src/db/builds.rs +++ b/src/db/builds.rs @@ -2,8 +2,8 @@ use rusqlite::{params, Connection, OptionalExtension}; -use crate::db::Db; -use crate::error::Result; +use crate::db::{BuildState, Db}; +use crate::error::{Error, Result}; use crate::time; #[derive(Debug, Clone)] @@ -15,7 +15,7 @@ pub struct BuildRow { pub kind: String, pub world_snapshot_id: Option<i64>, pub build_profile: String, - pub state: String, + pub state: BuildState, pub blocked_on_json: String, pub current_step: Option<String>, pub lease_owner: Option<String>, @@ -30,7 +30,18 @@ const BUILD_COLS: &str = "id, pkgbase_id, candidate_id, release_id, kind, world_ 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<BuildRow> { +pub(crate) fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result<BuildRow> { + let state_text: String = r.get(7)?; + let state = BuildState::parse(&state_text).ok_or_else(|| { + rusqlite::Error::FromSqlConversionFailure( + 7, + rusqlite::types::Type::Text, + Box::new(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("build has a state outside the state machine: {state_text:?}"), + )), + ) + })?; Ok(BuildRow { id: r.get(0)?, pkgbase_id: r.get(1)?, @@ -39,7 +50,7 @@ fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result<BuildRow> { kind: r.get(4)?, world_snapshot_id: r.get(5)?, build_profile: r.get(6)?, - state: r.get(7)?, + state, blocked_on_json: r.get(8)?, current_step: r.get(9)?, lease_owner: r.get(10)?, @@ -95,8 +106,8 @@ pub fn get(db: &Db, id: &str) -> Result<Option<BuildRow>> { }) } -pub fn list(db: &Db, states: &[&str], limit: i64) -> Result<Vec<BuildRow>> { - let states = states.iter().map(|s| s.to_string()).collect::<Vec<_>>(); +pub fn list(db: &Db, states: &[BuildState], limit: i64) -> Result<Vec<BuildRow>> { + let states = states.iter().map(|s| s.as_str().to_string()).collect::<Vec<_>>(); db.read(move |c| { let placeholders = states.iter().map(|_| "?").collect::<Vec<_>>().join(","); let sql = format!( @@ -192,30 +203,57 @@ pub fn reap_expired(db: &Db) -> Result<usize> { }) } -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()); +/// The one way a build changes state, usable inside a transaction. +/// +/// The write is a compare-and-swap: only a row currently in one of `to`'s legal +/// predecessor states is updated, so two workers cannot both land a terminal +/// state, and a zombie worker whose lease was reaped gets an error instead of +/// silently rewriting a build that has since been handed to somebody else. +fn transition_in_tx( + tx: &mut rusqlite::Transaction<'_>, + id: &str, + to: BuildState, + error: Option<&str>, +) -> Result<()> { + let froms = BuildState::predecessors(to); + let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); + let sql = format!( + "UPDATE build SET state=?1, error=?2, updated_at=?3, lease_owner=NULL, + lease_expires_at=NULL WHERE id=?4 AND state IN ({placeholders})" + ); 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(()) - }) + let state = to.as_str(); + let mut args: Vec<&dyn rusqlite::ToSql> = vec![&state, &error, &at, &id]; + for f in &froms { + args.push(f); + } + let n = tx.execute(&sql, rusqlite::params_from_iter(args))?; + if n == 0 { + let was: Option<String> = tx + .query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)) + .optional()?; + return Err(match was { + Some(s) => Error::invalid(format!("illegal build transition {s} → {to} for build {id}")), + None => Error::invalid(format!("no build {id} to move to {to}")), + }); + } + Ok(()) +} + +/// Move a build to `to`, refusing any transition [`BuildState`] forbids. +pub fn set_state(db: &Db, id: &str, to: BuildState, error: Option<&str>) -> Result<()> { + let id = id.to_string(); + let error = error.map(|e| e.to_string()); + db.writer + .tx(move |tx| transition_in_tx(tx, &id, to, error.as_deref())) } 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], - )?; + transition_in_tx(tx, &id, BuildState::BlockedMissingDep, None)?; + tx.execute("UPDATE build SET blocked_on_json=?1 WHERE id=?2", params![json, id])?; Ok(()) }) } @@ -455,10 +493,16 @@ pub fn set_blocked_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { }) } -pub fn current_state(c: &Connection, id: &str) -> Result<String> { - Ok(c.query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)) - .optional()? - .unwrap_or_default()) +pub fn current_state(c: &Connection, id: &str) -> Result<Option<BuildState>> { + let s: Option<String> = c + .query_row("SELECT state FROM build WHERE id=?1", params![id], |r| r.get(0)) + .optional()?; + match s { + None => Ok(None), + Some(text) => BuildState::parse(&text) + .map(Some) + .ok_or_else(|| Error::invalid(format!("build {id} has a state outside the state machine: {text:?}"))), + } } /// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and @@ -512,15 +556,8 @@ pub fn cancel_superseded(db: &Db) -> Result<usize> { /// 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(()) - }) + db.writer + .tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None)) } /// Explicitly retry a failed build (§8.4). This is a human decision, not a @@ -528,18 +565,17 @@ pub fn requeue_transient(db: &Db, id: &str) -> Result<()> { /// 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], - )?; + // The move itself goes through the machine, so requeueing a build that + // already published is refused with a reason instead of silently + // re-queueing a row whose every step is checkpointed as done. + transition_in_tx(tx, &id, BuildState::Queued, None)?; + tx.execute("UPDATE build SET cancel_requested=0 WHERE id=?1", params![id])?; Ok(()) }) } diff --git a/src/db/model.rs b/src/db/model.rs index dfc1f8b..bf3e017 100644 --- a/src/db/model.rs +++ b/src/db/model.rs @@ -112,14 +112,130 @@ pub mod release_state { pub const FAILED_UNBUILT: &str = "failed_unbuilt"; } -pub mod build_state { - pub const QUEUED: &str = "queued"; - pub const LEASED: &str = "leased"; - pub const RUNNING: &str = "running"; - pub const BLOCKED_MISSING_DEP: &str = "blocked_missing_dep"; - pub const SUCCEEDED: &str = "succeeded"; - pub const FAILED: &str = "failed"; - pub const CANCELLED: &str = "cancelled"; +/// The build state machine (§7.1, §8.2). +/// +/// This used to be seven `&str` constants and a `set_state(&str)` that wrote any +/// string a caller invented, so the machine existed only as `WHERE state IN +/// (...)` clauses scattered across six modules — nothing could tell you that +/// `succeeded → running` is nonsense. The enum is the machine: a state is one +/// of these seven, it is parsed where a row is read, and `can_transition` is +/// the only way a write happens. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub enum BuildState { + /// Approved and waiting for a worker. + Queued, + /// Claimed by a worker with a lease (§8.2). + Leased, + /// A step is executing. + Running, + /// Waiting for packages another build must publish first (§10.4). + BlockedMissingDep, + Succeeded, + Failed, + Cancelled, +} + +impl BuildState { + pub const ALL: &'static [BuildState] = &[ + BuildState::Queued, + BuildState::Leased, + BuildState::Running, + BuildState::BlockedMissingDep, + BuildState::Succeeded, + BuildState::Failed, + BuildState::Cancelled, + ]; + + /// The text in the `state` column. The spelling is part of the schema: the + /// reaper, the dispatcher and the UI all speak it. + pub fn as_str(&self) -> &'static str { + match self { + BuildState::Queued => "queued", + BuildState::Leased => "leased", + BuildState::Running => "running", + BuildState::BlockedMissingDep => "blocked_missing_dep", + BuildState::Succeeded => "succeeded", + BuildState::Failed => "failed", + BuildState::Cancelled => "cancelled", + } + } + + /// The only way in from the database text. An unrecognised state is `None`, + /// and the row boundary turns that into an error rather than a silent + /// fallback: a state we cannot name is a state we must not act on. + pub fn parse(s: &str) -> Option<BuildState> { + BuildState::ALL.iter().copied().find(|b| b.as_str() == s) + } + + /// Nothing happens to a finished build by itself. `Succeeded` is final — + /// the release is published and the row is history (§15). `Failed` and + /// `Cancelled` end a worker's involvement, and only an explicit human + /// requeue or resume moves them again ([`BuildState::can_transition`]). + pub fn is_terminal(&self) -> bool { + matches!( + self, + BuildState::Succeeded | BuildState::Failed | BuildState::Cancelled + ) + } + + /// May a row in this state be written to `to`? + /// + /// Writing the state a row already has is always allowed: it is a no-op, not + /// a move. The step loop re-asserts `Running` at every step boundary (§8.3), + /// and re-running a finished build must stay harmless rather than turn into + /// an error. + /// + /// Everything else is refused by [`crate::db::builds::set_state`], and the + /// refusals are the point: nothing revives a `Succeeded` build, and a build + /// reaped back to `Queued` cannot be completed by the zombie worker that + /// lost its lease — that refusal is the alarm. + pub fn can_transition(&self, to: BuildState) -> bool { + use BuildState::*; + if *self == to { + return true; + } + match self { + // The dispatcher claims queued builds; `aur-build run <id>` runs one + // in the foreground without a lease, so `Running` is legal from here + // too. A dependency can be discovered before a worker ever starts. + Queued => matches!(to, Leased | Running | BlockedMissingDep | Cancelled), + Leased => matches!(to, Running | Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), + Running => matches!(to, Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), + BlockedMissingDep => matches!(to, Queued | Cancelled), + // A failed build is resumed on the same row — that is I5 (the step + // checkpoints say where to continue) and §8.4's human requeue. + Failed => matches!(to, Queued | Running), + // §8.4: requeue is a human decision, not a policy. + Cancelled => to == Queued, + Succeeded => false, + } + } + + /// Every state that may legally move to `to` — the `WHERE state IN (...)` + /// that makes a state write a compare-and-swap. + pub fn predecessors(to: BuildState) -> Vec<&'static str> { + BuildState::ALL + .iter() + .filter(|from| from.can_transition(to)) + .map(|from| from.as_str()) + .collect() + } + + /// The states the queue considers "in flight" for metrics and the index. + pub fn active() -> &'static [BuildState] { + &[ + BuildState::Queued, + BuildState::Running, + BuildState::Leased, + BuildState::BlockedMissingDep, + ] + } +} + +impl std::fmt::Display for BuildState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } } pub mod step_state { diff --git a/src/db/queries.rs b/src/db/queries.rs index b768f83..e1f25b7 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -661,16 +661,10 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr priority, cancel_requested, error FROM build WHERE pkgbase_id=?1 ORDER BY rowid DESC LIMIT ?2", )?; - let rows = st.query_map(params![pkgbase_id, limit], |r| { - Ok(crate::db::builds::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)?, - }) - })?; - Ok(rows.filter_map(|r| r.ok()).collect()) + let rows = st.query_map(params![pkgbase_id, limit], crate::db::builds::row_to_build)?; + // A row we cannot read is an error, not a build that quietly disappears + // from the package page. + rows.collect::<::rusqlite::Result<Vec<_>>>().map_err(Into::into) }) } |
