//! 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 std::sync::Arc; use std::time::Duration; use crate::config::Config; use crate::db::{self, builds, Db, Pkgbase}; use crate::db::model::*; use crate::db::SnapshotRow; use crate::error::{Error, Result}; use crate::sandbox::{Sandbox, SandboxBackend}; /// 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, } impl SourceIdentity { /// The identity of a build's source, complete on construction (n-1). /// /// This used to return a value with `aur_commit` and `recipe_hash` left /// empty, which `Ctx::new` filled in afterwards if it happened to find the /// snapshot row — so a `SourceIdentity` was a type whose empty strings could /// mean either "not filled in yet" or "genuinely unknown", and a new call /// site that forgot the second half produced a build that silently recorded /// an empty provenance. The snapshot is an argument now: you cannot build one /// without it. pub fn from_candidate(c: &CandidateRow, snapshot: &SnapshotRow) -> Self { Self { aur_commit: snapshot.aur_commit.clone(), recipe_hash: snapshot.recipe_hash.clone(), 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(), } } 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(), } } 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, /// Where build code runs. Defaults to the loopback backend (§8, sandbox /// seam); the pipeline itself never spawns a build subprocess directly. pub backend: Arc, } 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"))?; // A candidate without its snapshot is a broken row, not a // candidate with less provenance: say so rather than build // against an empty commit and hash. let snap = db::snapshot_by_id(db, c.snapshot_id)? .ok_or_else(|| Error::not_found("snapshot for candidate"))?; SourceIdentity::from_candidate(&c, &snap) } 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, backend: Arc::new(crate::sandbox::loopback::LoopbackBackend::new(cfg)), }) } /// Lease a sandbox for this build's profile. Today every step acquires and /// releases around itself; a remote backend will hold one sandbox across /// the sandbox-bearing steps of a build, and steps stay idempotent either /// way (I5). The TTL is the lease window: a sandbox that outlives it is /// assumed dead, which is exactly what the reaper already concludes about /// an expired build lease. pub fn sandbox(&self) -> Result> { let spec = crate::sandbox::SandboxSpec { profile: self.profile.clone(), task: self.build.id.clone(), ttl: Duration::from_secs(self.cfg.lease_secs.max(1) as u64), disk_mb: self.cfg.min_free_disk_mb, }; self.backend.acquire(&spec) } /// 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, BuildState::Cancelled, Some("cancelled"))?; return Ok(Outcome::Cancelled); } let status = builds::step_status(&ctx.db, &ctx.build.id, step)?; 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)?; builds::set_state(&ctx.db, &ctx.build.id, BuildState::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, StepState::Succeeded, digest.as_deref(), None)?; builds::extend_lease(&ctx.db, &ctx.build.id, ctx.cfg.lease_secs)?; } Ok(StepResult::Skipped(why)) => { ctx.log_line(&format!(" skipped: {why}")); 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, 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, StepState::Failed, None, Some(&e.to_string()))?; builds::set_state( &ctx.db, &ctx.build.id, BuildState::Failed, Some(&format!("{step}: {e}")), )?; ctx.log_line(&format!("!! {step} failed: {e}")); // A failed build must not leave the old version looking healthy. // Nothing has to *do* that: the accepted pointer was never moved, // so "approved, build failed, index still serving the old // version" is what the derived query reads back (§8.4). There is // deliberately no state to set here — see `approved_but_unbuilt`. 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, BuildState::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) } } /// 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")))?; // A manual rebuild is the accepted release asked for again, so its identity // is derived from what that release actually is — commit, recipe, pins, // digests — through the same canonical-JSON hash every other identity uses // (n-5). The old version was an ad-hoc `commit|hash|manual` string: a // different format for the same concept, with a delimiter that could appear // inside the values, and no pins or digests at all, so two releases with the // same recipe but different upstream commits... were distinguished only by // luck. `requested` is what keeps a rebuild a *distinct* build from the one // that produced the release, while staying deterministic (§8.2): clicking // rebuild twice is one build, not two. let identity = format!( "sha256:{}", crate::hash::hex(crate::hash::canonical_json(&serde_json::json!({ "aur_commit": rel.aur_commit, "recipe_hash": rel.recipe_hash, "upstream_pins": rel.pins(), "source_digests": rel.digests(), "requested": "manual_rebuild", }))?.as_bytes()) ); 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| builds::set_release_in(tx, &id_for_tx, rid))?; 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), }