summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-18 16:49:40 +0000
committeraur-build <aur-build@localhost>2026-11-18 16:49:40 +0000
commit41fa1684de8eb13c5b76c3a3e174fece04ac5afa (patch)
tree491a2faf2dd2314f537300ccaf1e0150b54d1123 /src
parent101f077200e80c7869e4549db645ed94b01acb1b (diff)
downloadaur-build-41fa1684de8eb13c5b76c3a3e174fece04ac5afa.tar.gz
aur-build-41fa1684de8eb13c5b76c3a3e174fece04ac5afa.zip
db: the review, step, release and subscription states are enums too
M-8 named four more machines after `build_state`, and each had the same defect in miniature: `&str` constants, a writer that took any `&str`, and a rule that lived only in the caller's discipline. They are `CandidateState`, `StepState`, `ReleaseState` and `SubscriptionState` now, all parsed through one `db::state_col` at the row boundary — a column value the code cannot name fails the read rather than becoming a state it did not ask for. The one that mattered is the review machine. `resolve_in(tx, id, &str)` would move a candidate to any state from any state, so an approval racing a rejection, or a stale worker resolving a review that had already been superseded, silently overwrote what a human had decided — the direct route to breaking I2 and I3 with no symptom anywhere. It is a compare-and-swap on `CandidateState` now: a decided review is only ever frozen, never re-decided, and a refusal names both states. `supersede_in` goes through it, so the freeze cannot resurrect a superseded review either. `StepState` gives I5 teeth. `begin_step` upserted over any existing checkpoint, including one recorded `succeeded`, so a resume that asked to re-run a finished step could rewrite the very row that told it to skip; the upsert now refuses to touch a done checkpoint and `finish_step` is a CAS. The blocked path (`running → pending`) and the reaper's `running → interrupted` are unchanged, and both are in the table. Two behaviour changes, both for the better and both tested: the UI's pause button now says "orphaned: nothing to pause" instead of rewriting an orphaned subscription back to a pausable state, and a step checkpoint that is already done makes `begin_step` an error rather than a quiet overwrite. Five tests in `tests/state_machine.rs` cover the review CAS in both directions, the frozen checkpoint, the interrupted/blocked transitions, and the unknown value in a candidate and a step row.
Diffstat (limited to 'src')
-rw-r--r--src/db/builds.rs90
-rw-r--r--src/db/candidates.rs49
-rw-r--r--src/db/mod.rs19
-rw-r--r--src/db/model.rs311
-rw-r--r--src/db/queries.rs8
-rw-r--r--src/http/routes.rs30
-rw-r--r--src/main.rs4
-rw-r--r--src/pipeline/mod.rs10
-rw-r--r--src/pipeline/publish.rs4
-rw-r--r--src/review/approve.rs12
-rw-r--r--src/watch/detect.rs4
11 files changed, 444 insertions, 97 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, &note)?;
- 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