use serde::{Deserialize, Serialize}; use crate::hash; /// One resolved upstream VCS source (DESIGN.md §3). The commit SHA alone is /// sufficient: a git commit transitively commits to its tree, and a gitlink in /// that tree commits to any submodule's commit. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct UpstreamPin { pub index: usize, pub url: String, /// The ref we asked for: `HEAD`, a tag, or an explicit commit. pub ref_: String, pub branch: Option, /// The pin. pub commit: String, } /// A row of the Stage B cache (§5.2): the version resolution produced, with the /// pins it was computed from. This lives with the schema because the table does — /// the persistence layer must not name a type from the module that owns VCS /// probing (§6 M-6). #[derive(Debug, Clone)] pub struct StageBCacheRow { pub epoch: String, pub pkgver: String, pub pkgrel: String, pub pins: Vec, } impl StageBCacheRow { pub fn version(&self) -> String { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } } /// A source entry with the digest *we* computed, regardless of what the /// PKGBUILD declares (§5.3). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SourceDigest { pub index: usize, pub url: String, /// `static` | `vcs` | `local` pub kind: String, /// sha256, or the resolved VCS commit for vcs sources. pub digest: String, pub size: u64, /// True when the PKGBUILD gave us no checksum to trust — `SKIP`, a malformed /// digest, or nothing at all. It means that and nothing else (m-19): a `-git` /// source has no checksum by design because the *pin* is the integrity. Ask /// [`SourceDigest::is_vcs`] which mechanism protects an entry. pub skip_declared: bool, } impl SourceDigest { /// True when this entry's integrity comes from a resolved commit rather than a /// content hash. pub fn is_vcs(&self) -> bool { matches!(self.kind.as_str(), "vcs" | "git" | "svn" | "hg" | "bzr") } } /// A member of a world snapshot: one of *our* packages the build ran against. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct WorldMember { pub pkgbase: String, pub version: String, } /// The identity tuple of a candidate (§3). Every element is part of the key. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Identity { pub aur_commit: String, pub epoch: String, pub pkgver: String, pub pkgrel: String, pub upstream_pins: Vec, pub source_digests: Vec, } impl Identity { /// The hash that makes I3 a fact: two byte-identical inputs never produce two /// candidates, and any change to what becomes a byte in the artifact produces a /// new one. This is the value an approval must echo; a value that cannot be /// serialized is an error rather than a digest, because a shared fallback /// digest would be the one way two identities could collide by accident. pub fn hash(&self) -> crate::error::Result { Ok(format!("sha256:{}", hash::hex(hash::canonical_json(self)?.as_bytes()))) } } /// The review state machine (§7.1). A decision must never be overwritten by /// accident — an approval that silently replaced a rejection 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 { /// The only state a reviewer can act on. PendingReview, Approved, Rejected, /// 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::ALL.iter().copied().find(|c| c.as_str() == s) } pub fn is_open(&self) -> bool { *self == CandidateState::PendingReview } /// Re-writing the state a row 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 { pub const NEW_VERSION: &str = "new_version"; pub const FIRST_INTRODUCTION: &str = "first_introduction"; } /// The release state machine (§9). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ReleaseState { 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::ALL.iter().copied().find(|r| r.as_str() == s) } /// Withdrawal is the only move a release makes on its own. 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, so `db::state_col` can fail an unknown state /// 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; 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 { <$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). 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 { 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 — a spelling the reaper, dispatcher and UI /// all speak. 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", } } /// An unrecognised state is `None`, and the row boundary turns that into an /// error: a state we cannot name is one we must not act on. pub fn parse(s: &str) -> Option { BuildState::ALL.iter().copied().find(|b| b.as_str() == s) } /// Nothing happens to a finished build by itself; only an explicit human /// requeue or resume moves it again. pub fn is_terminal(&self) -> bool { matches!( self, BuildState::Succeeded | BuildState::Failed | BuildState::Cancelled ) } /// Writing the state a row already has is always allowed: the step loop /// re-asserts `Running` at every step boundary (§8.3). 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. 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 ` runs one // in the foreground without a lease. 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 (§8.4). Failed => matches!(to, Queued | Running), 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() } 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()) } } /// The step checkpoint state machine (§8.3, I5). The checkpoint row is what a /// resumed build reads to decide what not to redo, so a completed checkpoint is /// frozen. #[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::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. 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 { pub const PIN_DRIFT: &str = "pin_drift"; pub const RECIPE_DRIFT: &str = "recipe_drift"; pub const DIGEST_DRIFT: &str = "digest_drift"; pub const INTEGRITY_ALERT: &str = "integrity_alert"; pub const UNPINABLE_PKGVER: &str = "unpinable_pkgver"; pub const ORPHANED: &str = "orphaned"; pub const DELETED: &str = "deleted"; pub const RENAMED: &str = "renamed"; pub const DOWNGRADE: &str = "downgrade"; } /// 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::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 /// in this list without a `succeeded` row. pub const BUILD_STEPS: &[&str] = &[ "materialize", "plan", "chroot", "sources", "pkgver", "build", "collect", "verify", "ingest", "publish", ]; /// A `source=()` entry after parsing. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SourceEntry { pub index: usize, /// The URL as written, minus the filename fragment. pub url: String, /// Explicit filename (`::name` / `::` prefix handling). pub filename: Option, pub commit: Option, pub tag: Option, pub branch: Option, /// Set when the url is prefixed `git+`, `svn+`, `hg+`, `bzr+`. pub vcs: Option, /// True for files shipped inside the AUR repo (no scheme). pub local: bool, } impl SourceEntry { pub fn is_vcs(&self) -> bool { self.vcs.is_some() } } /// A parsed recipe: what `.SRCINFO` / `PKGBUILD` tell us. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Recipe { pub pkgbase: String, pub pkgver: String, pub pkgrel: String, pub epoch: String, pub pkgdesc: String, pub url: String, pub arch: Vec, pub license: Vec, pub groups: Vec, pub depends: Vec, pub makedepends: Vec, pub checkdepends: Vec, pub optdepends: Vec, pub provides: Vec, pub conflicts: Vec, pub source: Vec, pub sha256sums: Vec, pub b2sums: Vec, pub validpgpkeys: Vec, pub options: Vec, pub backup: Vec, pub install: Option, /// Names of the binary packages this pkgbase emits (split pkgbases have N). pub pkgnames: Vec, pub pkg_depends: Vec<(String, Vec)>, /// Raw PKGBUILD text, for display and diffing. pub pkgbuild: String, pub srcinfo: Option, /// True if `--skippgpcheck` appears in the PKGBUILD. pub skipgpcheck: bool, /// Derived from `source`, so not serialized. #[serde(skip, default)] pub source_entries: Vec, } impl Recipe { pub fn full_version(&self) -> String { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } } /// A source row as stored on a candidate/release. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ReleaseRow { pub id: i64, pub pkgbase_id: i64, pub candidate_id: Option, pub approval_id: Option, pub aur_commit: String, pub recipe_hash: String, pub upstream_pins_json: String, pub source_digests_json: String, pub epoch: String, pub pkgver: String, pub pkgrel: String, pub world_snapshot_id: Option, pub state: ReleaseState, pub published_at: Option, } impl ReleaseRow { pub fn version(&self) -> String { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } pub fn pins(&self) -> Vec { serde_json::from_str(&self.upstream_pins_json).unwrap_or_default() } pub fn digests(&self) -> Vec { serde_json::from_str(&self.source_digests_json).unwrap_or_default() } } #[derive(Debug, Clone, Serialize)] pub struct CandidateRow { pub id: i64, pub pkgbase_id: i64, pub base_release_id: Option, pub kind: String, pub snapshot_id: i64, pub epoch: String, pub pkgver: String, pub pkgrel: String, pub upstream_pins_json: String, pub source_digests_json: String, pub identity_hash: String, pub diff_digest: String, pub revision: i64, pub viewed_at: Option, pub risk_level: String, pub risk_signals_json: String, pub missing_deps_json: String, pub state: CandidateState, pub detected_at: String, pub resolved_at: Option, pub pkgbase: String, } impl CandidateRow { pub fn version(&self) -> String { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } pub fn pins(&self) -> Vec { serde_json::from_str(&self.upstream_pins_json).unwrap_or_default() } pub fn digests(&self) -> Vec { serde_json::from_str(&self.source_digests_json).unwrap_or_default() } pub fn risk_signals(&self) -> Vec { serde_json::from_str(&self.risk_signals_json).unwrap_or_default() } pub fn missing_deps(&self) -> Vec { serde_json::from_str(&self.missing_deps_json).unwrap_or_default() } } /// Parse a JSON column with a fallback, so one bad row never takes down a page. pub fn json_or(s: &str, fallback: T) -> T { serde_json::from_str(s).unwrap_or(fallback) }