//! Row types and small value objects that appear in JSON columns. use serde::{Deserialize, Serialize}; use crate::hash; /// One resolved upstream VCS source (DESIGN.md §3, "Three things to pin"). /// /// 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 { /// Index into the PKGBUILD `source=()` array. pub index: usize, pub url: String, /// The ref we asked for: `HEAD`, a tag, or an explicit commit. pub ref_: String, /// Branch the ref resolved to, when known. pub branch: Option, /// Resolved commit SHA. This is the pin. pub commit: String, } /// A row of the Stage B cache (§5.2): the version that resolution produced, /// with the pins it was computed from. /// /// This lives with the schema because the table lives here — the persistence /// layer must not name a type from the module that owns VCS probing, which is /// the dependency pointing the wrong way (§6 M-6). `watch::upstream::StageB` /// is this plus `cached`, and that extra field is the reason the two are not /// the same type: "was this answer a cache hit?" is a fact about the resolution /// that just happened, not a column. #[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 declared `SKIP` (or nothing) for this source. pub skip_declared: bool, } /// 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. /// /// A digest of the canonical JSON of the identity tuple. This is the value /// an approval must echo: two candidates share an `identity_hash` only if /// every pin, digest and version in them is identical. A value that cannot /// be serialized is an error rather than a digest — 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()))) } } /// 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"; } pub mod candidate_kind { pub const NEW_VERSION: &str = "new_version"; 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 build state machine (§7.1, §8.2). /// /// This used to be seven `&str` constants and a `set_state(&str)` that wrote any /// string a caller invented, so the machine existed only as `WHERE state IN /// (...)` clauses scattered across six modules — nothing could tell you that /// `succeeded → running` is nonsense. The enum is the machine: a state is one /// of these seven, it is parsed where a row is read, and `can_transition` is /// the only way a write happens. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum BuildState { /// Approved and waiting for a worker. Queued, /// Claimed by a worker with a lease (§8.2). Leased, /// A step is executing. Running, /// Waiting for packages another build must publish first (§10.4). BlockedMissingDep, Succeeded, Failed, Cancelled, } impl BuildState { pub const ALL: &'static [BuildState] = &[ BuildState::Queued, BuildState::Leased, BuildState::Running, BuildState::BlockedMissingDep, BuildState::Succeeded, BuildState::Failed, BuildState::Cancelled, ]; /// The text in the `state` column. The spelling is part of the schema: the /// reaper, the dispatcher and the UI all speak it. pub fn as_str(&self) -> &'static str { match self { BuildState::Queued => "queued", BuildState::Leased => "leased", BuildState::Running => "running", BuildState::BlockedMissingDep => "blocked_missing_dep", BuildState::Succeeded => "succeeded", BuildState::Failed => "failed", BuildState::Cancelled => "cancelled", } } /// The only way in from the database text. An unrecognised state is `None`, /// and the row boundary turns that into an error rather than a silent /// fallback: a state we cannot name is a state we must not act on. pub fn parse(s: &str) -> Option { BuildState::ALL.iter().copied().find(|b| b.as_str() == s) } /// Nothing happens to a finished build by itself. `Succeeded` is final — /// the release is published and the row is history (§15). `Failed` and /// `Cancelled` end a worker's involvement, and only an explicit human /// requeue or resume moves them again ([`BuildState::can_transition`]). pub fn is_terminal(&self) -> bool { matches!( self, BuildState::Succeeded | BuildState::Failed | BuildState::Cancelled ) } /// May a row in this state be written to `to`? /// /// Writing the state a row already has is always allowed: it is a no-op, not /// a move. The step loop re-asserts `Running` at every step boundary (§8.3), /// and re-running a finished build must stay harmless rather than turn into /// an error. /// /// Everything else is refused by [`crate::db::builds::set_state`], and the /// refusals are the point: nothing revives a `Succeeded` build, and a build /// reaped back to `Queued` cannot be completed by the zombie worker that /// lost its lease — that refusal is the alarm. pub fn can_transition(&self, to: BuildState) -> bool { use BuildState::*; if *self == to { return true; } match self { // The dispatcher claims queued builds; `aur-build run ` runs one // in the foreground without a lease, so `Running` is legal from here // too. A dependency can be discovered before a worker ever starts. Queued => matches!(to, Leased | Running | BlockedMissingDep | Cancelled), Leased => matches!(to, Running | Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), Running => matches!(to, Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), BlockedMissingDep => matches!(to, Queued | Cancelled), // A failed build is resumed on the same row — that is I5 (the step // checkpoints say where to continue) and §8.4's human requeue. Failed => matches!(to, Queued | Running), // §8.4: requeue is a human decision, not a policy. Cancelled => to == Queued, Succeeded => false, } } /// Every state that may legally move to `to` — the `WHERE state IN (...)` /// that makes a state write a compare-and-swap. pub fn predecessors(to: BuildState) -> Vec<&'static str> { BuildState::ALL .iter() .filter(|from| from.can_transition(to)) .map(|from| from.as_str()) .collect() } /// The states the queue considers "in flight" for metrics and the index. pub fn active() -> &'static [BuildState] { &[ BuildState::Queued, BuildState::Running, BuildState::Leased, BuildState::BlockedMissingDep, ] } } impl std::fmt::Display for BuildState { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.as_str()) } } pub mod step_state { 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"; } 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"; } pub mod subscription_state { pub const ACTIVE: &str = "active"; pub const PAUSED: &str = "paused"; pub const ORPHANED: &str = "orphaned"; pub const REMOVED: &str = "removed"; } /// 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, /// `#commit=` fragment. pub commit: Option, /// `#tag=` fragment. pub tag: Option, /// `#branch=` fragment. pub branch: Option, /// VCS kind if 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, /// Per-package depends, for split pkgbases. pub pkg_depends: Vec<(String, Vec)>, /// Raw PKGBUILD text, for display and diffing. pub pkgbuild: String, /// Raw .SRCINFO text when it was present. pub srcinfo: Option, /// True if `--skippgpcheck` appears in the PKGBUILD. pub skipgpcheck: bool, /// Parsed `source=()` entries. Derived from `source`, so not serialized. #[serde(skip, default)] pub source_entries: Vec, } impl Recipe { /// `epoch:pkgver-pkgrel` as displayed to consumers. 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: String, 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: String, 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) }