diff options
| -rw-r--r-- | src/db/builds.rs | 90 | ||||
| -rw-r--r-- | src/db/candidates.rs | 49 | ||||
| -rw-r--r-- | src/db/mod.rs | 19 | ||||
| -rw-r--r-- | src/db/model.rs | 311 | ||||
| -rw-r--r-- | src/db/queries.rs | 8 | ||||
| -rw-r--r-- | src/http/routes.rs | 30 | ||||
| -rw-r--r-- | src/main.rs | 4 | ||||
| -rw-r--r-- | src/pipeline/mod.rs | 10 | ||||
| -rw-r--r-- | src/pipeline/publish.rs | 4 | ||||
| -rw-r--r-- | src/review/approve.rs | 12 | ||||
| -rw-r--r-- | src/watch/detect.rs | 4 | ||||
| -rw-r--r-- | tests/approve.rs | 4 | ||||
| -rw-r--r-- | tests/crash.rs | 12 | ||||
| -rw-r--r-- | tests/detect.rs | 8 | ||||
| -rw-r--r-- | tests/dispatch.rs | 8 | ||||
| -rw-r--r-- | tests/invariants.rs | 2 | ||||
| -rw-r--r-- | tests/pipeline.rs | 4 | ||||
| -rw-r--r-- | tests/state_machine.rs | 117 |
18 files changed, 580 insertions, 116 deletions
diff --git a/src/db/builds.rs b/src/db/builds.rs index a41308e..c1d65db 100644 --- a/src/db/builds.rs +++ b/src/db/builds.rs @@ -2,7 +2,7 @@ use rusqlite::{params, Connection, OptionalExtension}; -use crate::db::{BuildState, Db}; +use crate::db::{BuildState, Db, StepState}; use crate::error::{Error, Result}; use crate::time; @@ -31,17 +31,7 @@ const BUILD_COLS: &str = "id, pkgbase_id, candidate_id, release_id, kind, world_ attempt, priority, cancel_requested, error"; 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:?}"), - )), - ) - })?; + let state = crate::db::state_col::<BuildState>(7, &r.get::<_, String>(7)?)?; Ok(BuildRow { id: r.get(0)?, pkgbase_id: r.get(1)?, @@ -324,7 +314,7 @@ pub fn cancel_requested(db: &Db, id: &str) -> Result<bool> { #[derive(Debug, Clone)] pub struct StepRow { pub step: String, - pub status: String, + pub status: StepState, pub attempt: i64, pub error: Option<String>, } @@ -336,7 +326,12 @@ pub fn steps(db: &Db, id: &str) -> Result<Vec<StepRow>> { "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)? }) + Ok(StepRow { + step: r.get(0)?, + status: crate::db::state_col::<StepState>(1, &r.get::<_, String>(1)?)?, + attempt: r.get(2)?, + error: r.get(3)?, + }) })?; let mut out = Vec::new(); for r in rows { @@ -346,15 +341,16 @@ pub fn steps(db: &Db, id: &str) -> Result<Vec<StepRow>> { }) } -pub fn step_status(db: &Db, build_id: &str, step: &str) -> Result<Option<String>> { +pub fn step_status(db: &Db, build_id: &str, step: &str) -> Result<Option<StepState>> { let (b, s) = (build_id.to_string(), step.to_string()); db.read(move |c| { - Ok(c.query_row( + c.query_row( "SELECT status FROM build_step WHERE build_id=?1 AND step=?2", params![b, s], - |r| r.get(0), + |r| crate::db::state_col::<StepState>(0, &r.get::<_, String>(0)?), ) - .optional()?) + .optional() + .map_err(Into::into) }) } @@ -362,29 +358,69 @@ 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( + // The `WHERE` is I5 with teeth: a step already checkpointed as done is + // frozen, so a resume that asks to re-run it cannot overwrite the record + // that told it to skip. The insert path is unaffected. + let n = 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", + error=NULL + WHERE build_step.status NOT IN ('succeeded','skipped')", params![b, s, attempt, at], )?; + if n == 0 { + return Err(Error::invalid(format!( + "step {s} of build {b} is already checkpointed as done and must not re-run (I5)" + ))); + } 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()); +/// Record what a step produced. Refuses a transition [`StepState`] forbids — +/// above all, writing over a checkpoint a resume is relying on. +pub fn finish_step( + db: &Db, + build_id: &str, + step: &str, + to: StepState, + output_digest: Option<&str>, + error: Option<&str>, +) -> Result<()> { + let (b, s) = (build_id.to_string(), step.to_string()); let od = output_digest.map(|s| s.to_string()); let err = error.map(|s| s.to_string()); let at = time::now(); + let froms = StepState::predecessors(to); + let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); + let sql = format!( + "UPDATE build_step SET status=?1, output_digest=?2, error=?3, finished_at=?4 + WHERE build_id=?5 AND step=?6 AND status IN ({placeholders})" + ); 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], - )?; + let status = to.as_str(); + let mut args: Vec<&dyn rusqlite::ToSql> = vec![&status, &od, &err, &at, &b, &s]; + 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 status FROM build_step WHERE build_id=?1 AND step=?2", + params![b, s], + |r| r.get(0), + ) + .optional()?; + return Err(match was { + Some(w) => Error::invalid(format!( + "illegal step transition {w} → {to} for step {s} of build {b}" + )), + None => Error::invalid(format!("no checkpoint for step {s} of build {b}")), + }); + } Ok(()) }) } diff --git a/src/db/candidates.rs b/src/db/candidates.rs index e41fb94..63c089f 100644 --- a/src/db/candidates.rs +++ b/src/db/candidates.rs @@ -10,7 +10,7 @@ use rusqlite::{params, OptionalExtension, Row, Transaction}; -use crate::db::{CandidateRow, Db}; +use crate::db::{CandidateRow, CandidateState, Db}; use crate::error::{Error, Result}; use crate::time; @@ -41,7 +41,7 @@ fn row_to_candidate(r: &Row<'_>) -> rusqlite::Result<CandidateRow> { risk_level: r.get(14)?, risk_signals_json: r.get(15)?, missing_deps_json: r.get(16)?, - state: r.get(17)?, + state: crate::db::state_col::<CandidateState>(17, &r.get::<_, String>(17)?)?, detected_at: r.get(18)?, resolved_at: r.get(19)?, pkgbase: r.get(20)?, @@ -92,7 +92,7 @@ impl OpenReview { pub struct ReviewSubject { pub id: i64, pub pkgbase_id: i64, - pub state: String, + pub state: CandidateState, pub identity_hash: String, pub diff_digest: String, /// The release this review was opened against (I2). @@ -115,7 +115,7 @@ pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Opti Ok(ReviewSubject { id: r.get(0)?, pkgbase_id: r.get(1)?, - state: r.get(2)?, + state: crate::db::state_col::<CandidateState>(2, &r.get::<_, String>(2)?)?, identity_hash: r.get(3)?, diff_digest: r.get(4)?, base_release_id: r.get(5)?, @@ -129,16 +129,42 @@ pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Opti } /// Take a candidate out of the open state: approved, rejected or superseded. -pub fn resolve_in(tx: &Transaction<'_>, id: i64, state: &str, at: &str) -> Result<()> { - tx.execute("UPDATE candidate SET state=?1, resolved_at=?2 WHERE id=?3", params![state, at, id])?; +/// +/// The write is a compare-and-swap on [`CandidateState`]: a decided review is +/// never re-decided, so an approval racing a rejection — or a stale worker +/// resolving a review that has since been superseded — fails instead of +/// silently overwriting what a human did. +pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -> Result<()> { + let froms = CandidateState::predecessors(to); + let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); + let sql = format!( + "UPDATE candidate SET state=?1, resolved_at=?2 WHERE id=?3 AND state IN ({placeholders})" + ); + let state = to.as_str(); + let mut args: Vec<&dyn rusqlite::ToSql> = vec![&state, &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 candidate WHERE id=?1", params![id], |r| r.get(0)) + .optional()?; + return Err(match was { + Some(w) => Error::conflict(format!("illegal candidate transition {w} → {to} for review {id}")), + None => Error::not_found(format!("no candidate {id} to resolve")), + }); + } Ok(()) } /// A candidate's state, read inside a transaction (the reject path needs it /// before it writes). -pub fn state_in(tx: &Transaction<'_>, id: i64) -> Result<Option<String>> { +pub fn state_in(tx: &Transaction<'_>, id: i64) -> Result<Option<CandidateState>> { Ok(tx - .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0)) + .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| { + crate::db::state_col::<CandidateState>(0, &r.get::<_, String>(0)?) + }) .optional()?) } @@ -202,11 +228,8 @@ pub fn collapse_in(tx: &mut Transaction<'_>, open: &OpenReview, nc: &NewCandidat /// Freeze a reviewed candidate as `superseded` so a fresh review can open. pub fn supersede_in(tx: &Transaction<'_>, id: i64) -> Result<()> { - tx.execute( - "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2", - params![time::now(), id], - )?; - Ok(()) + let at = time::now(); + resolve_in(tx, id, CandidateState::Superseded, &at) } /// Has this exact identity been rejected before? If so the watcher stays quiet diff --git a/src/db/mod.rs b/src/db/mod.rs index 2cf766b..403ced2 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -17,6 +17,25 @@ pub mod queries; pub use migrations::MIGRATIONS; pub use model::*; + +/// Parse a state column into one of the state enums. +/// +/// A value the code does not recognise fails the row instead of becoming a +/// default: a build in a state we cannot name must not be listed, claimed, or +/// rendered as if it were in one we could. +pub(crate) fn state_col<T: StateEnum>(col: usize, text: &str) -> rusqlite::Result<T> { + T::parse(text).ok_or_else(|| { + rusqlite::Error::FromSqlConversionFailure( + col, + rusqlite::types::Type::Text, + Box::new(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("{} has a state outside the state machine: {text:?}", T::KIND), + )), + ) + }) +} + pub use queries::*; use std::path::{Path, PathBuf}; diff --git a/src/db/model.rs b/src/db/model.rs index bf3e017..263db4e 100644 --- a/src/db/model.rs +++ b/src/db/model.rs @@ -92,13 +92,83 @@ impl Identity { } } -/// Candidate/review states (§7.1). -pub mod candidate_state { - pub const PENDING: &str = "pending_review"; - pub const APPROVED: &str = "approved"; - pub const REJECTED: &str = "rejected"; - pub const SUPERSEDED: &str = "superseded"; - pub const BLOCKED: &str = "blocked"; +/// The review state machine (§7.1). +/// +/// A candidate is what a human decides on, and the decision is the one thing in +/// this system that must never be overwritten by accident: an approval that +/// silently replaced a rejection, or a superseded review resurrected, would +/// break I2 and I3 without any symptom. So the states are an enum, and +/// [`crate::db::candidates::resolve_in`] refuses a move the machine forbids. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum CandidateState { + /// Open: nobody has decided yet. The only state a reviewer can act on. + PendingReview, + Approved, + Rejected, + /// Frozen: a newer review of the same pkgbase took its place (§7.1). + Superseded, + /// Not approved because something it needs is missing (§10.4). + Blocked, +} + +impl CandidateState { + pub const ALL: &'static [CandidateState] = &[ + CandidateState::PendingReview, + CandidateState::Approved, + CandidateState::Rejected, + CandidateState::Superseded, + CandidateState::Blocked, + ]; + + pub fn as_str(&self) -> &'static str { + match self { + CandidateState::PendingReview => "pending_review", + CandidateState::Approved => "approved", + CandidateState::Rejected => "rejected", + CandidateState::Superseded => "superseded", + CandidateState::Blocked => "blocked", + } + } + + pub fn parse(s: &str) -> Option<CandidateState> { + CandidateState::ALL.iter().copied().find(|c| c.as_str() == s) + } + + /// The state a reviewer can still act on. + pub fn is_open(&self) -> bool { + *self == CandidateState::PendingReview + } + + /// May a candidate in this state be written to `to`? Re-writing the state it + /// already has is a no-op, not a move. + pub fn can_transition(&self, to: CandidateState) -> bool { + use CandidateState::*; + if *self == to { + return true; + } + match self { + PendingReview => matches!(to, Approved | Rejected | Superseded | Blocked), + // A decided review is only ever frozen, never re-decided (§7.1). + Approved | Rejected => to == Superseded, + Blocked => matches!(to, PendingReview | Approved | Rejected), + Superseded => false, + } + } + + pub fn predecessors(to: CandidateState) -> Vec<&'static str> { + CandidateState::ALL + .iter() + .filter(|from| from.can_transition(to)) + .map(|from| from.as_str()) + .collect() + } +} + +impl std::fmt::Display for CandidateState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } } pub mod candidate_kind { @@ -106,12 +176,87 @@ pub mod candidate_kind { pub const FIRST_INTRODUCTION: &str = "first_introduction"; } -pub mod release_state { - pub const PUBLISHED: &str = "published"; - pub const WITHDRAWN: &str = "withdrawn"; - pub const FAILED_UNBUILT: &str = "failed_unbuilt"; +/// The release state machine (§9). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReleaseState { + /// In the served index. + Published, + /// Taken out of the index (§9 withdrawal); the row stays (§15). + Withdrawn, + /// Approved, but the build never produced it: the old version still serves. + FailedUnbuilt, +} + +impl ReleaseState { + pub const ALL: &'static [ReleaseState] = &[ + ReleaseState::Published, + ReleaseState::Withdrawn, + ReleaseState::FailedUnbuilt, + ]; + + pub fn as_str(&self) -> &'static str { + match self { + ReleaseState::Published => "published", + ReleaseState::Withdrawn => "withdrawn", + ReleaseState::FailedUnbuilt => "failed_unbuilt", + } + } + + pub fn parse(s: &str) -> Option<ReleaseState> { + ReleaseState::ALL.iter().copied().find(|r| r.as_str() == s) + } + + /// Withdrawal is the only move a release makes on its own; a failed-unbuilt + /// release is a record of an attempt, and a published one is live. + pub fn can_transition(&self, to: ReleaseState) -> bool { + use ReleaseState::*; + if *self == to { + return true; + } + match self { + Published => matches!(to, Withdrawn | FailedUnbuilt), + Withdrawn | FailedUnbuilt => false, + } + } +} + +impl std::fmt::Display for ReleaseState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } +} + +/// What the state enums below have in common: a closed set of column values, +/// parsed where a row is read. `db::state_col` uses this to fail a row whose +/// state the code does not know instead of defaulting it. +pub trait StateEnum: Copy + Sized { + /// The name of the machine, for the error message. + const KIND: &'static str; + fn parse(text: &str) -> Option<Self>; + fn as_str(&self) -> &'static str; +} + +macro_rules! impl_state_enum { + ($t:ty, $kind:literal) => { + impl StateEnum for $t { + const KIND: &'static str = $kind; + fn parse(text: &str) -> Option<Self> { + <$t>::parse(text) + } + fn as_str(&self) -> &'static str { + <$t>::as_str(self) + } + } + }; } +impl_state_enum!(BuildState, "build"); +impl_state_enum!(CandidateState, "candidate"); +impl_state_enum!(StepState, "build step"); +impl_state_enum!(ReleaseState, "release"); +impl_state_enum!(SubscriptionState, "subscription"); + /// The build state machine (§7.1, §8.2). /// /// This used to be seven `&str` constants and a `set_state(&str)` that wrote any @@ -238,13 +383,82 @@ impl std::fmt::Display for BuildState { } } -pub mod step_state { - pub const PENDING: &str = "pending"; - pub const RUNNING: &str = "running"; - pub const SUCCEEDED: &str = "succeeded"; - pub const FAILED: &str = "failed"; - pub const INTERRUPTED: &str = "interrupted"; - pub const SKIPPED: &str = "skipped"; +/// The step checkpoint state machine (§8.3, I5). +/// +/// The checkpoint row is what a resumed build reads to decide what not to redo, +/// so the rule that matters is that a completed checkpoint is frozen: a step +/// recorded `succeeded` or `skipped` is never re-run and never rewritten. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StepState { + Pending, + Running, + Succeeded, + Failed, + /// Killed mid-step; the reaper writes this so the resume re-runs it (§8.2). + Interrupted, + Skipped, +} + +impl StepState { + pub const ALL: &'static [StepState] = &[ + StepState::Pending, + StepState::Running, + StepState::Succeeded, + StepState::Failed, + StepState::Interrupted, + StepState::Skipped, + ]; + + pub fn as_str(&self) -> &'static str { + match self { + StepState::Pending => "pending", + StepState::Running => "running", + StepState::Succeeded => "succeeded", + StepState::Failed => "failed", + StepState::Interrupted => "interrupted", + StepState::Skipped => "skipped", + } + } + + pub fn parse(text: &str) -> Option<StepState> { + StepState::ALL.iter().copied().find(|st| st.as_str() == text) + } + + /// I5: the resume skips a step in one of these two states, so nothing may + /// move it again — a checkpoint that can be rewritten is not a checkpoint. + pub fn is_done(&self) -> bool { + matches!(self, StepState::Succeeded | StepState::Skipped) + } + + pub fn can_transition(&self, to: StepState) -> bool { + use StepState::*; + if *self == to { + return true; + } + match self { + Pending => matches!(to, Running | Succeeded | Failed | Interrupted | Skipped), + // `Running → Pending` is the blocked path: the step did not happen, + // so the checkpoint goes back to waiting. + Running => matches!(to, Pending | Succeeded | Failed | Interrupted | Skipped), + Failed | Interrupted => matches!(to, Pending | Running), + Succeeded | Skipped => false, + } + } + + pub fn predecessors(to: StepState) -> Vec<&'static str> { + StepState::ALL + .iter() + .filter(|from| from.can_transition(to)) + .map(|from| from.as_str()) + .collect() + } +} + +impl std::fmt::Display for StepState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } } pub mod notice_kind { @@ -259,11 +473,58 @@ pub mod notice_kind { pub const DOWNGRADE: &str = "downgrade"; } -pub mod subscription_state { - pub const ACTIVE: &str = "active"; - pub const PAUSED: &str = "paused"; - pub const ORPHANED: &str = "orphaned"; - pub const REMOVED: &str = "removed"; +/// Whether a pkgbase is being watched (§4.1, §12). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SubscriptionState { + Active, + Paused, + /// The pkgbase left AUR; the watcher stopped looking (§12). + Orphaned, + Removed, +} + +impl SubscriptionState { + pub const ALL: &'static [SubscriptionState] = &[ + SubscriptionState::Active, + SubscriptionState::Paused, + SubscriptionState::Orphaned, + SubscriptionState::Removed, + ]; + + pub fn as_str(&self) -> &'static str { + match self { + SubscriptionState::Active => "active", + SubscriptionState::Paused => "paused", + SubscriptionState::Orphaned => "orphaned", + SubscriptionState::Removed => "removed", + } + } + + pub fn parse(text: &str) -> Option<SubscriptionState> { + SubscriptionState::ALL.iter().copied().find(|st| st.as_str() == text) + } + + /// Pause and resume are the only moves the UI makes; orphaned and removed + /// are facts about the pkgbase, reported once. + pub fn can_transition(&self, to: SubscriptionState) -> bool { + use SubscriptionState::*; + if *self == to { + return true; + } + match self { + Active => matches!(to, Paused | Orphaned | Removed), + Paused => matches!(to, Active | Orphaned | Removed), + Orphaned => matches!(to, Active | Removed), + Removed => false, + } + } +} + +impl std::fmt::Display for SubscriptionState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(self.as_str()) + } } /// The pipeline steps (§8.1). Order matters: a build resumes at the first step @@ -369,7 +630,7 @@ pub struct ReleaseRow { pub pkgver: String, pub pkgrel: String, pub world_snapshot_id: Option<i64>, - pub state: String, + pub state: ReleaseState, pub published_at: Option<String>, } @@ -404,7 +665,7 @@ pub struct CandidateRow { pub risk_level: String, pub risk_signals_json: String, pub missing_deps_json: String, - pub state: String, + pub state: CandidateState, pub detected_at: String, pub resolved_at: Option<String>, pub pkgbase: String, diff --git a/src/db/queries.rs b/src/db/queries.rs index e1f25b7..18f91cd 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -143,7 +143,7 @@ pub struct Subscription { pub pkgbase: String, pub aur_url: String, pub maintainer: Option<String>, - pub state: String, + pub state: SubscriptionState, pub next_check_at: Option<String>, pub last_checked_at: Option<String>, pub last_error: Option<String>, @@ -156,7 +156,7 @@ fn row_to_sub(r: &Row<'_>) -> rusqlite::Result<Subscription> { pkgbase: r.get(1)?, aur_url: r.get(2)?, maintainer: r.get(3)?, - state: r.get(4)?, + state: crate::db::state_col::<SubscriptionState>(4, &r.get::<_, String>(4)?)?, next_check_at: r.get(5)?, last_checked_at: r.get(6)?, last_error: r.get(7)?, @@ -211,7 +211,7 @@ pub fn subscribe(writer: &Writer, repo_id: i64, pkgbase: &str, aur_url: &str) -> }) } -pub fn set_subscription_state(writer: &Writer, pkgbase: &str, state: &str) -> Result<()> { +pub fn set_subscription_state(writer: &Writer, pkgbase: &str, state: SubscriptionState) -> Result<()> { let (p, s) = (pkgbase.to_string(), state.to_string()); writer.tx(move |tx| { tx.execute( @@ -459,7 +459,7 @@ fn row_to_release(r: &Row<'_>) -> rusqlite::Result<ReleaseRow> { pkgver: r.get(9)?, pkgrel: r.get(10)?, world_snapshot_id: r.get(11)?, - state: r.get(12)?, + state: crate::db::state_col::<ReleaseState>(12, &r.get::<_, String>(12)?)?, published_at: r.get(13)?, }) } diff --git a/src/http/routes.rs b/src/http/routes.rs index 926d2a8..288f002 100644 --- a/src/http/routes.rs +++ b/src/http/routes.rs @@ -170,7 +170,7 @@ fn dashboard(state: &State, req: &Req) -> Res { Some(PublishRow { name: pb.name, version: r.version(), - published_at: r.published_at.unwrap_or_else(|| r.state.clone()), + published_at: r.published_at.unwrap_or_else(|| r.state.to_string()), aur_commit: r.aur_commit.clone(), aur_commit_short: short(&r.aur_commit), }) @@ -530,13 +530,13 @@ fn subscriptions(state: &State, req: &Req) -> Res { .map(|s| SubRow { pending: pending.iter().filter(|c| c.pkgbase == s.pkgbase).count() as i64, name: s.pkgbase.clone(), - state: s.state.clone(), + state: s.state.to_string(), maintainer: s.maintainer.unwrap_or_else(|| "unknown".into()), last_checked: s.last_checked_at.unwrap_or_else(|| "never".into()), next_check: s.next_check_at.unwrap_or_else(|| "soon".into()), last_error: s.last_error.clone().unwrap_or_default(), has_error: s.last_error.is_some(), - pause_label: if s.state == subscription_state::PAUSED { "resume" } else { "pause" }, + pause_label: if s.state == SubscriptionState::Paused { "resume" } else { "pause" }, }) .collect(); page_to_res(Subscriptions { page, rows }, 200) @@ -561,8 +561,16 @@ fn sub_add(state: &State, req: &Req) -> Res { fn sub_pause(state: &State, req: &Req) -> Res { let db = &state.db; let name = req.form_get("pkgbase").unwrap_or_default(); - let cur = db::get_subscription(db, &name).ok().flatten().map(|s| s.state).unwrap_or_default(); - let next = if cur == subscription_state::PAUSED { subscription_state::ACTIVE } else { subscription_state::PAUSED }; + let cur = db::get_subscription(db, &name).ok().flatten().map(|s| s.state); + // Pause and resume are the only moves this page makes. A subscription that + // is orphaned or removed is not the reviewer's to pause, and saying so beats + // quietly rewriting its state. + let next = match cur { + Some(SubscriptionState::Active) => SubscriptionState::Paused, + Some(SubscriptionState::Paused) => SubscriptionState::Active, + Some(other) => return flash_sub(state, req, &format!("{name} is {other}: nothing to pause"), true), + None => return flash_sub(state, req, &format!("no subscription for {name}"), true), + }; let _ = db::set_subscription_state(&db.writer, &name, next); flash_sub(state, req, &format!("{name}: {next}"), false) } @@ -570,7 +578,7 @@ fn sub_pause(state: &State, req: &Req) -> Res { fn sub_remove(state: &State, req: &Req) -> Res { let db = &state.db; let name = req.form_get("pkgbase").unwrap_or_default(); - let _ = db::set_subscription_state(&db.writer, &name, subscription_state::REMOVED); + let _ = db::set_subscription_state(&db.writer, &name, SubscriptionState::Removed); flash_sub(state, req, &format!("{name}: removed"), false) } @@ -583,13 +591,13 @@ fn flash_sub(state: &State, req: &Req, msg: &str, err: bool) -> Res { .map(|s| SubRow { pending: pending.iter().filter(|c| c.pkgbase == s.pkgbase).count() as i64, name: s.pkgbase.clone(), - state: s.state.clone(), + state: s.state.to_string(), maintainer: s.maintainer.unwrap_or_else(|| "unknown".into()), last_checked: s.last_checked_at.unwrap_or_else(|| "never".into()), next_check: s.next_check_at.unwrap_or_else(|| "soon".into()), last_error: s.last_error.clone().unwrap_or_default(), has_error: s.last_error.is_some(), - pause_label: if s.state == subscription_state::PAUSED { "resume" } else { "pause" }, + pause_label: if s.state == SubscriptionState::Paused { "resume" } else { "pause" }, }) .collect(); page_to_res(Subscriptions { page, rows }, 200) @@ -702,7 +710,7 @@ fn package_detail(state: &State, req: &Req, name: &str) -> Res { .into_iter() .map(|r| TimelineRow { version: r.version(), - state: r.state.clone(), + state: r.state.to_string(), aur_commit: r.aur_commit.clone(), aur_commit_short: short(&r.aur_commit), published_at: r.published_at.unwrap_or_else(|| "—".into()), @@ -906,10 +914,10 @@ fn build_detail(state: &State, req: &Req, id: &str) -> Res { .unwrap_or_default() .into_iter() .map(|s| { - let cls = if s.status == "failed" { "risk-high" } else { "mut" }.to_string(); + let cls = if s.status == StepState::Failed { "risk-high" } else { "mut" }.to_string(); StepRow { step: s.step, - status: s.status, + status: s.status.to_string(), attempt: s.attempt, digest: String::new(), cls, diff --git a/src/main.rs b/src/main.rs index 1aacfac..91c086b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -192,7 +192,7 @@ fn main() -> anyhow::Result<()> { Ok(()) } Cmd::Unsubscribe { pkgbase } => { - db::set_subscription_state(&ctx.db.writer, &pkgbase, subscription_state::REMOVED)?; + db::set_subscription_state(&ctx.db.writer, &pkgbase, SubscriptionState::Removed)?; println!("unsubscribed {pkgbase}"); Ok(()) } @@ -201,7 +201,7 @@ fn main() -> anyhow::Result<()> { Some(n) => vec![n], None => db::list_subscriptions(&ctx.db)? .into_iter() - .filter(|s| s.state == subscription_state::ACTIVE) + .filter(|s| s.state == SubscriptionState::Active) .map(|s| s.pkgbase) .collect(), }; diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index 01c9bc5..9ddfc65 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -203,7 +203,7 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> { return Ok(Outcome::Cancelled); } let status = builds::step_status(&ctx.db, &ctx.build.id, step)?; - if status.as_deref() == Some(step_state::SUCCEEDED) || status.as_deref() == Some(step_state::SKIPPED) { + if status.is_some_and(|s| s.is_done()) { continue; // checkpoint says we already did this } builds::begin_step(&ctx.db, &ctx.build.id, step, ctx.attempt)?; @@ -211,22 +211,22 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> { ctx.log_line(&format!("==> step {step} (attempt {})", ctx.attempt)); match steps::run_step(ctx, step) { Ok(StepResult::Done(digest)) => { - builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::SUCCEEDED, digest.as_deref(), None)?; + builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Succeeded, digest.as_deref(), None)?; builds::extend_lease(&ctx.db, &ctx.build.id, 90)?; } Ok(StepResult::Skipped(why)) => { ctx.log_line(&format!(" skipped: {why}")); - builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::SKIPPED, None, None)?; + builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Skipped, None, None)?; } Ok(StepResult::Blocked(on)) => { - builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::PENDING, None, Some("blocked"))?; + builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Pending, None, Some("blocked"))?; builds::block_on(&ctx.db, &ctx.build.id, &on)?; ctx.log_line(&format!(" blocked on: {}", on.join(", "))); return Ok(Outcome::Blocked { on }); } Err(e) => { let transient = e.is_transient(); - builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::FAILED, None, Some(&e.to_string()))?; + builds::finish_step(&ctx.db, &ctx.build.id, step, StepState::Failed, None, Some(&e.to_string()))?; builds::set_state( &ctx.db, &ctx.build.id, diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs index 877d8e1..4f21e72 100644 --- a/src/pipeline/publish.rs +++ b/src/pipeline/publish.rs @@ -12,7 +12,7 @@ use std::process::Command; use std::sync::Mutex; use crate::config::Config; -use crate::db::{self, builds, candidate_state, candidates, Db, WorldMember}; +use crate::db::{self, builds, candidates, CandidateState, Db, WorldMember}; use crate::error::{Error, Result}; use crate::pipeline::{Collect, Ctx}; use crate::time; @@ -247,7 +247,7 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { } builds::set_release_in(tx, &build_id, release_id)?; if let Some(cid) = candidate_id { - candidates::resolve_in(tx, cid, candidate_state::APPROVED, &at)?; + candidates::resolve_in(tx, cid, CandidateState::Approved, &at)?; } Ok(release_id) }) diff --git a/src/review/approve.rs b/src/review/approve.rs index a76eeac..208e8e2 100644 --- a/src/review/approve.rs +++ b/src/review/approve.rs @@ -5,7 +5,7 @@ //! rendered; if either has moved under the reviewer, the approval is refused //! with a conflict (HTTP 409) and a re-render, never silently retargeted. -use crate::db::{self, approvals, candidate_state, candidates, *}; +use crate::db::{self, approvals, candidates, CandidateState, *}; use crate::error::{Error, Result}; use crate::time; @@ -78,8 +78,8 @@ pub fn approve( let current_base = subject.current_base_release_id; // 1. still open - if subject.state != candidate_state::PENDING { - return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state }))); + if !subject.state.is_open() { + return Ok(Err(ApproveError::Stale(Stale::NotPending { state: subject.state.to_string() }))); } // 2. same candidate bytes if subject.identity_hash != ih { @@ -107,7 +107,7 @@ pub fn approve( note: note.as_deref(), }, )?; - candidates::resolve_in(tx, id, candidate_state::APPROVED, &at)?; + candidates::resolve_in(tx, id, CandidateState::Approved, &at)?; db::audit_in( tx, &db::AuditEntry { @@ -142,13 +142,13 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> db.writer.tx(move |tx| { let state = candidates::state_in(tx, candidate_id)? .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; - if state != candidate_state::PENDING { + if !state.is_open() { return Err(Error::conflict(format!("candidate is {state}, not pending"))); } let identity = candidates::identity_in(tx, candidate_id)? .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?; approvals::record_rejection_in(tx, candidate_id, &at, &identity, ¬e)?; - candidates::resolve_in(tx, candidate_id, candidate_state::REJECTED, &at)?; + candidates::resolve_in(tx, candidate_id, CandidateState::Rejected, &at)?; db::audit_in( tx, &db::AuditEntry { diff --git a/src/watch/detect.rs b/src/watch/detect.rs index deb0749..37bdc8a 100644 --- a/src/watch/detect.rs +++ b/src/watch/detect.rs @@ -54,7 +54,7 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { // must not keep polling AUR either. The pause lives on the subscription, so // that is what we consult. let paused = db::get_subscription(db, name)? - .map(|s| s.state == subscription_state::PAUSED) + .map(|s| s.state == SubscriptionState::Paused) .unwrap_or(false); if paused { return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Paused }); @@ -69,7 +69,7 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { "high", serde_json::json!({"aur_url": pb.aur_url, "note": "repository no longer exists"}), )?; - db::set_subscription_state(&db.writer, name, subscription_state::ORPHANED)?; + db::set_subscription_state(&db.writer, name, SubscriptionState::Orphaned)?; return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone }); } // The cheap poll saved us a fetch, but we still have to look: a source diff --git a/tests/approve.rs b/tests/approve.rs index 61e42c2..1f61182 100644 --- a/tests/approve.rs +++ b/tests/approve.rs @@ -125,7 +125,7 @@ fn a_broken_database_is_not_reported_as_a_stale_review() { // And the refusal is atomic: the half-written approval rolled back with it. assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); let after = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); - assert_eq!(after.state, "pending_review", "a failed approval must not resolve the review"); + assert_eq!(after.state, CandidateState::PendingReview, "a failed approval must not resolve the review"); } #[test] @@ -208,7 +208,7 @@ fn once_viewed_a_new_state_freezes_the_old_one_as_superseded() { assert_eq!(open.len(), 1); assert_ne!(open[0].id, c.id, "a fresh review was opened"); let frozen = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); - assert_eq!(frozen.state, candidate_state::SUPERSEDED); + assert_eq!(frozen.state, CandidateState::Superseded); // The frozen one can no longer be approved: approving it would build a // version nobody is looking at. let err = approve(&env.db, "tester", c.id, &frozen.identity_hash, &frozen.diff_digest, None).unwrap_err(); diff --git a/tests/crash.rs b/tests/crash.rs index 0510aab..66e6043 100644 --- a/tests/crash.rs +++ b/tests/crash.rs @@ -67,13 +67,13 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work b.state ); assert_eq!( - builds::step_status(&env.db, &id, "build").unwrap().as_deref(), - Some(step_state::RUNNING), + builds::step_status(&env.db, &id, "build").unwrap(), + Some(StepState::Running), "the step that was running should be recorded as running" ); assert_eq!( - builds::step_status(&env.db, &id, "chroot").unwrap().as_deref(), - Some(step_state::SUCCEEDED), + builds::step_status(&env.db, &id, "chroot").unwrap(), + Some(StepState::Succeeded), "the completed step before the crash must be checkpointed" ); assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none(), "nothing was published"); @@ -83,8 +83,8 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", ¶ms(vec![id.as_str()])); assert_eq!(builds::reap_expired(&env.db).unwrap(), 1); assert_eq!( - builds::step_status(&env.db, &id, "build").unwrap().as_deref(), - Some(step_state::INTERRUPTED) + builds::step_status(&env.db, &id, "build").unwrap(), + Some(StepState::Interrupted) ); // Resume. The completed steps are not repeated; only the interrupted one and diff --git a/tests/detect.rs b/tests/detect.rs index 939dce1..e674c8a 100644 --- a/tests/detect.rs +++ b/tests/detect.rs @@ -230,7 +230,11 @@ fn a_viewed_review_is_frozen_and_a_fresh_one_opened() { )?) }) .unwrap(); - assert_eq!(old_state, candidate_state::SUPERSEDED); + assert_eq!( + CandidateState::parse(&old_state), + Some(CandidateState::Superseded), + "the frozen review must be superseded in the column, not only in memory" + ); } #[test] @@ -326,7 +330,7 @@ fn a_deleted_upstream_marks_the_subscription_and_alerts() { let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); assert!(matches!(rep.outcome, Outcome::Gone), "{:?}", rep.outcome); let sub = db::get_subscription(&env.db, "foo").unwrap().unwrap(); - assert_eq!(sub.state, subscription_state::ORPHANED); + assert_eq!(sub.state, SubscriptionState::Orphaned); assert!(db::list_notices(&env.db, false) .unwrap() .iter() diff --git a/tests/dispatch.rs b/tests/dispatch.rs index 6721fc8..d0d4bd7 100644 --- a/tests/dispatch.rs +++ b/tests/dispatch.rs @@ -95,7 +95,7 @@ fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() { let id = queued_build(&env, "plain-make"); assert_eq!(pass(&env), vec![id.clone()]); builds::begin_step(&env.db, &id, "build", 1).unwrap(); - assert_eq!(builds::step_status(&env.db, &id, "build").unwrap().as_deref(), Some("running")); + assert_eq!(builds::step_status(&env.db, &id, "build").unwrap(), Some(StepState::Running)); // Time passes — the lease expires, as it would if the process were killed. env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z'", &[]); @@ -105,8 +105,8 @@ fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() { assert_eq!(reaped, 1, "the expired lease was not requeued"); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Queued); assert_eq!( - builds::step_status(&env.db, &id, "build").unwrap().as_deref(), - Some("interrupted"), + builds::step_status(&env.db, &id, "build").unwrap(), + Some(StepState::Interrupted), "the in-flight step was not marked interrupted" ); // And it is claimable again. @@ -230,7 +230,7 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { let steps = builds::steps(&env.db, &id).unwrap(); let done = steps .iter() - .filter(|s| s.status == step_state::SUCCEEDED || s.status == step_state::SKIPPED) + .filter(|s| s.status == StepState::Succeeded || s.status == StepState::Skipped) .count(); assert_eq!(done, BUILD_STEPS.len(), "not every step ended succeeded or skipped: {steps:?}"); assert_eq!( diff --git a/tests/invariants.rs b/tests/invariants.rs index ceaddc4..b7bfc0d 100644 --- a/tests/invariants.rs +++ b/tests/invariants.rs @@ -214,7 +214,7 @@ fn i7_the_schema_refuses_a_second_open_review() { upstream_pins_json, source_digests_json, identity_hash, diff_digest, state, detected_at) VALUES (?1,'new_version',?2,'0','9','1','[]','[]','other-hash','',?3,'now')", - rusqlite::params![pb, snap, candidate_state::PENDING], + rusqlite::params![pb, snap, CandidateState::PendingReview.as_str()], )?; Ok(()) }) diff --git a/tests/pipeline.rs b/tests/pipeline.rs index 01ae5f7..a8eb1d9 100644 --- a/tests/pipeline.rs +++ b/tests/pipeline.rs @@ -64,7 +64,7 @@ fn end_to_end_publishes_a_signed_index() { assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}"); let rel = db::accepted_release(&env.db, "plain-make").unwrap().unwrap(); - assert_eq!(rel.state, release_state::PUBLISHED); + assert_eq!(rel.state, ReleaseState::Published); assert_eq!(rel.pkgver, "1.0"); assert_eq!(rel.version(), "1.0-1"); @@ -278,7 +278,7 @@ fn a_failed_build_leaves_the_previous_version_serving() { assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); assert_eq!( candidates::candidate_by_id(&env.db, c2.id).unwrap().unwrap().state, - candidate_state::APPROVED + CandidateState::Approved ); assert_eq!( env.query_i64("SELECT count(*) FROM package WHERE state='in_index' AND version='1.0.1-1'", &[]), diff --git a/tests/state_machine.rs b/tests/state_machine.rs index c5203d7..1c05fff 100644 --- a/tests/state_machine.rs +++ b/tests/state_machine.rs @@ -6,12 +6,12 @@ mod common; -use aur_build::db::{builds, model::BuildState}; +use aur_build::db::{builds, model::{BuildState, CandidateState, StepState}}; use common::Env; fn build(env: &Env, id: &str) -> String { env.exec( - "INSERT INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')", + "INSERT OR IGNORE INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')", &[], ); let pb = env.query_i64("SELECT id FROM pkgbase WHERE name='x'", &[]).expect("pkgbase id"); @@ -168,3 +168,116 @@ fn a_failed_build_is_resumed_on_its_own_row() { assert_eq!(state(&env, &id), BuildState::Succeeded); } + +// ---------------------------------------------------------- the other machines -- + +/// A candidate row in `state`, inserted directly: these tests are about the +/// state column, not about how a candidate is discovered. +fn candidate(env: &Env, state: &str) -> i64 { + env.exec( + "INSERT OR IGNORE INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')", + &[], + ); + let pb = env.query_i64("SELECT id FROM pkgbase WHERE name='x'", &[]).unwrap(); + let snap = aur_build::db::put_snapshot(&env.db.writer, pb, "commit", "rh", "{}", "[]").unwrap(); + env.exec( + "INSERT INTO candidate (pkgbase_id, kind, snapshot_id, pkgver, pkgrel, identity_hash, state, detected_at) + VALUES (?1,'new_version',?2,'1.0','1','ih-1',?3,'2026-01-01T00:00:00Z')", + &[common::P::I(pb), common::P::I(snap), common::P::S(state.into())], + ); + env.query_i64("SELECT id FROM candidate WHERE identity_hash='ih-1'", &[]).unwrap() +} + +fn resolve(env: &Env, id: i64, to: CandidateState) -> aur_build::error::Result<()> { + env.db + .writer + .tx_for_tests(move |tx| aur_build::db::candidates::resolve_in(tx, id, to, "2026-01-01T00:00:00Z")) +} + +fn candidate_state(env: &Env, id: i64) -> CandidateState { + aur_build::db::candidates::by_id(&env.db, id) + .unwrap() + .expect("candidate") + .state +} + +#[test] +fn a_decided_review_is_never_re_decided() { + // The one write in this system that must never overwrite a human's decision. + let env = Env::new(); + let id = candidate(&env, "approved"); + let err = resolve(&env, id, CandidateState::Rejected).unwrap_err(); + assert!(err.to_string().contains("illegal candidate transition approved"), "{err}"); + assert_eq!(candidate_state(&env, id), CandidateState::Approved); + + // Superseding a decided review is the one move it makes (§7.1), and a + // superseded review is history. + resolve(&env, id, CandidateState::Superseded).unwrap(); + assert_eq!(candidate_state(&env, id), CandidateState::Superseded); + assert!(resolve(&env, id, CandidateState::Approved).is_err()); +} + +#[test] +fn only_an_open_review_can_be_approved() { + let env = Env::new(); + let id = candidate(&env, "rejected"); + assert!(resolve(&env, id, CandidateState::Approved).is_err(), "a rejection was re-decided"); + assert_eq!(candidate_state(&env, id), CandidateState::Rejected); + // Re-writing the state it already has is a no-op, not a re-decision. + resolve(&env, id, CandidateState::Rejected).unwrap(); +} + +#[test] +fn a_completed_step_checkpoint_is_frozen() { + // I5: a resumed build reads these rows to decide what not to redo. A + // checkpoint that can be rewritten is not a checkpoint. + let env = Env::new(); + let id = build(&env, "b1"); + builds::begin_step(&env.db, &id, "build", 1).unwrap(); + builds::finish_step(&env.db, &id, "build", StepState::Succeeded, None, None).unwrap(); + + let err = builds::begin_step(&env.db, &id, "build", 2).unwrap_err(); + assert!(err.to_string().contains("checkpointed as done"), "{err}"); + assert!(builds::finish_step(&env.db, &id, "build", StepState::Failed, None, Some("x")).is_err()); + assert_eq!(builds::step_status(&env.db, &id, "build").unwrap(), Some(StepState::Succeeded)); +} + +#[test] +fn an_interrupted_step_resumes_and_a_blocked_step_waits() { + let env = Env::new(); + let id = build(&env, "b1"); + builds::begin_step(&env.db, &id, "build", 1).unwrap(); + // The reaper's write, then the resume's re-begin. + env.exec( + "UPDATE build_step SET status='interrupted' WHERE build_id=?1 AND step='build'", + &[common::P::S(id.clone())], + ); + assert_eq!(builds::step_status(&env.db, &id, "build").unwrap(), Some(StepState::Interrupted)); + builds::begin_step(&env.db, &id, "build", 2).unwrap(); + // The blocked path puts the checkpoint back to waiting rather than failing it. + builds::finish_step(&env.db, &id, "build", StepState::Pending, None, Some("blocked")).unwrap(); + assert_eq!(builds::step_status(&env.db, &id, "build").unwrap(), Some(StepState::Pending)); +} + +#[test] +fn an_unnamed_state_in_any_row_is_an_error() { + // Every state column is parsed through `db::state_col`, so a value the code + // does not know stops the read instead of rendering as some other state. + let env = Env::new(); + let cid = candidate(&env, "approved"); + env.exec( + "UPDATE candidate SET state='reconsidered' WHERE id=?1", + &[common::P::I(cid)], + ); + let err = aur_build::db::candidates::by_id(&env.db, cid).unwrap_err(); + assert!(err.to_string().contains("candidate has a state outside"), "{err}"); + + let id = build(&env, "b1"); + builds::begin_step(&env.db, &id, "build", 1).unwrap(); + env.exec( + "UPDATE build_step SET status='maybe' WHERE build_id=?1 AND step='build'", + &[common::P::S(id.clone())], + ); + let err = builds::step_status(&env.db, &id, "build").unwrap_err(); + assert!(err.to_string().contains("build step has a state outside"), "{err}"); +} |
