//! The build pipeline (§8). //! //! Ten steps, each idempotent and checkpointed in `build_step`. A worker can die //! at any instant and the pipeline resumes at the next incomplete step with no //! duplicate side effects (I5). Only the last step is externally visible, and it //! is serialized per repo (I4). pub mod publish; pub mod dispatch; mod steps; use std::path::PathBuf; use crate::config::Config; use crate::db::{self, builds, Db, Pkgbase}; use crate::db::model::*; use crate::error::{Error, Result}; /// The approved source identity a build must reproduce. /// /// For a new version it comes from the candidate; for a manual rebuild it comes /// from the accepted release, which is what makes I6 true: a rebuild reuses the /// approved source identity and never needs a new approval. #[derive(Debug, Clone)] pub struct SourceIdentity { 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 identity_hash: String, } impl SourceIdentity { pub fn from_candidate(c: &CandidateRow) -> Self { Self { aur_commit: String::new(), recipe_hash: String::new(), upstream_pins_json: c.upstream_pins_json.clone(), source_digests_json: c.source_digests_json.clone(), epoch: c.epoch.clone(), pkgver: c.pkgver.clone(), pkgrel: c.pkgrel.clone(), identity_hash: c.identity_hash.clone(), } } pub fn from_release(r: &ReleaseRow) -> Self { Self { aur_commit: r.aur_commit.clone(), recipe_hash: r.recipe_hash.clone(), upstream_pins_json: r.upstream_pins_json.clone(), source_digests_json: r.source_digests_json.clone(), epoch: r.epoch.clone(), pkgver: r.pkgver.clone(), pkgrel: r.pkgrel.clone(), identity_hash: String::new(), } } pub fn version(&self) -> String { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } } /// One package produced by the build, as recorded by `collect` and `ingest`. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CollectedPkg { pub name: String, pub version: String, pub arch: String, /// Where the artifact lives: staging until `ingest`, the store afterwards. pub path: String, pub digest: String, pub size: u64, pub signature_path: Option, pub depends: Vec, pub makedepends: Vec, pub provides: Vec, pub conflicts: Vec, /// The full installed set from `.BUILDINFO`, unfiltered (§10.1). pub installed: Vec<(String, String)>, } #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct Collect { pub packages: Vec, } impl Collect { pub fn load(path: &std::path::Path) -> Result { if !path.exists() { return Ok(Self::default()); } Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?) } pub fn save(&self, path: &std::path::Path) -> Result<()> { std::fs::write(path, serde_json::to_string_pretty(self)?)?; Ok(()) } } /// Everything a step needs. Built once per build run, cheap to clone handles. pub struct Ctx { pub cfg: Config, pub db: Db, pub build: builds::BuildRow, pub pb: Pkgbase, pub src: SourceIdentity, pub staging: PathBuf, pub srcdir: PathBuf, pub collect_path: PathBuf, pub log: PathBuf, pub profile: String, pub attempt: i64, } impl Ctx { pub fn new(cfg: &Config, db: &Db, build_id: &str) -> Result { let build = builds::get(db, build_id)? .ok_or_else(|| Error::not_found(format!("build {build_id}")))?; let pb = db::get_pkgbase_by_id(db, build.pkgbase_id)? .ok_or_else(|| Error::not_found("pkgbase for build"))?; let src = match build.candidate_id { Some(cid) => { let c = crate::review::candidates::candidate_by_id(db, cid)? .ok_or_else(|| Error::not_found("candidate for build"))?; let mut si = SourceIdentity::from_candidate(&c); if let Some(s) = db::snapshot_by_id(db, c.snapshot_id)? { si.aur_commit = s.aur_commit; si.recipe_hash = s.recipe_hash; } si } None => { let rid = build .release_id .ok_or_else(|| Error::invalid("build has neither candidate nor release"))?; let r = db::release_by_id(db, rid)? .ok_or_else(|| Error::not_found("release for rebuild"))?; SourceIdentity::from_release(&r) } }; let attempt = build.attempt; let profile = build.build_profile.clone(); let staging = cfg.staging_build_dir(build_id); let srcdir = staging.join("src"); let collect_path = staging.join("collect.json"); Ok(Self { cfg: cfg.clone(), db: db.clone(), build, pb, src, staging, srcdir, collect_path, log: cfg.build_log_path(build_id), profile, attempt, }) } /// Append to the build log; the SSE tail reads this file (§12). pub fn log_line(&self, line: &str) { use std::io::Write; if let Some(parent) = self.log.parent() { let _ = std::fs::create_dir_all(parent); } if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&self.log) { let _ = writeln!(f, "{line}"); } } } /// What a full run produced. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Outcome { Succeeded { release_id: i64 }, Failed { step: String, error: String, transient: bool }, Blocked { on: Vec }, Cancelled, } /// Run a build to completion, resuming at the first incomplete step (I5). pub fn run(cfg: &Config, db: &Db, build_id: &str) -> Result { let ctx = Ctx::new(cfg, db, build_id)?; db::audit_system( &db.writer, "build.start", "build", build_id, serde_json::json!({"pkgbase": ctx.pb.name, "version": ctx.src.version(), "attempt": ctx.attempt}), )?; run_with(&ctx) } pub fn run_with(ctx: &Ctx) -> Result { std::fs::create_dir_all(&ctx.staging)?; for step in crate::db::model::BUILD_STEPS { if crate::db::builds::cancel_requested(&ctx.db, &ctx.build.id)? { builds::set_state(&ctx.db, &ctx.build.id, build_state::CANCELLED, Some("cancelled"))?; 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) { continue; // checkpoint says we already did this } builds::begin_step(&ctx.db, &ctx.build.id, step, ctx.attempt)?; builds::set_state(&ctx.db, &ctx.build.id, build_state::RUNNING, None)?; 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::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)?; } Ok(StepResult::Blocked(on)) => { builds::finish_step(&ctx.db, &ctx.build.id, step, step_state::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::set_state( &ctx.db, &ctx.build.id, build_state::FAILED, Some(&format!("{step}: {e}")), )?; ctx.log_line(&format!("!! {step} failed: {e}")); // A failed build must not leave the old version looking healthy: // the release stays approved_but_unbuilt and the UI says so. if let Some(cid) = ctx.build.candidate_id { if ctx.build.release_id.is_none() { mark_approved_but_unbuilt(&ctx.db, cid)?; } } return Ok(Outcome::Failed { step: step.to_string(), error: e.to_string(), transient }); } } } let release_id = ctx .release_id() .ok_or_else(|| Error::other("publish produced no release"))?; builds::set_state(&ctx.db, &ctx.build.id, build_state::SUCCEEDED, None)?; db::audit_system( &ctx.db.writer, "build.succeeded", "build", &ctx.build.id, serde_json::json!({"release": release_id}), )?; Ok(Outcome::Succeeded { release_id }) } impl Ctx { fn release_id(&self) -> Option { builds::get(&self.db, &self.build.id).ok().flatten().and_then(|b| b.release_id) } } /// A failed build must not make the old version look healthy (§8.4). The /// candidate stays `approved`; what the UI renders is the *absence* of a /// published release behind it: "v2 approved, build failed, index still /// serving v1". Nothing here mutates the accepted pointer. fn mark_approved_but_unbuilt(_db: &Db, _candidate_id: i64) -> Result<()> { Ok(()) } /// Enqueue the build an approval implies. Deterministic id, so calling this /// twice is a no-op (§8.2). pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result { let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)? .ok_or_else(|| Error::not_found("pkgbase"))?; let world = publish::index_world(db)?; let world_hash = crate::hash::canonical_json(&world)?; let id = builds::build_id(&pb.name, &c.identity_hash, &world_hash, &cfg.build_profile); let world_id = db::put_world_snapshot(&db.writer, &world)?; builds::enqueue(db, &id, pb.id, Some(c.id), "new_version", Some(world_id), &cfg.build_profile, 0)?; Ok(id) } /// Manual rebuild of the current accepted version (I6): same source identity, /// no new approval, same version. pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result { let pb = db::get_pkgbase(db, pkgbase)? .ok_or_else(|| Error::not_found(format!("pkgbase {pkgbase}")))?; let rel = db::accepted_release(db, pkgbase)? .ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?; let identity = crate::hash::hex_str(&format!( "{}|{}|manual", rel.aur_commit, rel.recipe_hash )); let world = publish::index_world(db)?; let world_hash = crate::hash::canonical_json(&world)?; let id = builds::build_id(pkgbase, &identity, &world_hash, &cfg.build_profile); let world_id = db::put_world_snapshot(&db.writer, &world)?; builds::enqueue(db, &id, pb.id, None, "manual_rebuild", Some(world_id), &cfg.build_profile, 1)?; let id_for_tx = id.clone(); let rid = rel.id; db.writer.tx(move |tx| { tx.execute( "UPDATE build SET release_id=?1 WHERE id=?2", rusqlite::params![rid, id_for_tx], )?; Ok(()) })?; Ok(id) } /// What one step produced. pub enum StepResult { Done(Option), Skipped(String), /// A dependency we publish is not in the index yet (§10.4). Blocked(Vec), }