diff options
Diffstat (limited to 'src/pipeline')
| -rw-r--r-- | src/pipeline/mod.rs | 322 | ||||
| -rw-r--r-- | src/pipeline/publish.rs | 399 | ||||
| -rw-r--r-- | src/pipeline/steps.rs | 456 |
3 files changed, 1177 insertions, 0 deletions
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs new file mode 100644 index 0000000..37aae77 --- /dev/null +++ b/src/pipeline/mod.rs @@ -0,0 +1,322 @@ +//! 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; +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<String>, + pub depends: Vec<String>, + pub makedepends: Vec<String>, + pub provides: Vec<String>, + pub conflicts: Vec<String>, + /// 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<CollectedPkg>, +} + +impl Collect { + pub fn load(path: &std::path::Path) -> Result<Self> { + 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<Self> { + 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<String> }, + Cancelled, +} + +/// Run a build to completion, resuming at the first incomplete step (I5). +pub fn run(cfg: &Config, db: &Db, build_id: &str) -> Result<Outcome> { + 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<Outcome> { + 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<i64> { + 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<String> { + 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<String> { + 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<String>), + Skipped(String), + /// A dependency we publish is not in the index yet (§10.4). + Blocked(Vec<String>), +} diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs new file mode 100644 index 0000000..639d717 --- /dev/null +++ b/src/pipeline/publish.rs @@ -0,0 +1,399 @@ +//! Publishing and serving the index (§9). +//! +//! Publishing is the only externally visible step, and it is atomic and +//! serialized per repo (I4). The served database is a materialized view of the +//! DB: we render it to `.tmp`, fsync, commit the DB, then `rename` over the real +//! one. A crash anywhere in there leaves the *old* index intact, and +//! [`reconcile`] re-materializes from the DB on startup. + +use std::collections::BTreeSet; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Mutex; + +use rusqlite::OptionalExtension; + +use crate::config::Config; +use crate::db::{self, builds, Db, WorldMember}; +use crate::error::{Error, Result}; +use crate::pipeline::{Collect, Ctx}; +use crate::time; + +/// One publish per repo at a time. In one process a mutex is exactly the +/// single-writer guarantee the design asks for; the publisher thread in P3 keeps +/// the critical section tiny (db file rewrite only), never the build. +static REPO_LOCK: Mutex<()> = Mutex::new(()); + +/// The world a build is admitted against: every pkgbase's accepted version. +pub fn index_world(db: &Db) -> Result<Vec<WorldMember>> { + let rels = db::all_published_releases(db)?; + let mut out = Vec::new(); + for r in rels { + let pb = db::get_pkgbase_by_id(db, r.pkgbase_id)?; + if let Some(pb) = pb { + out.push(WorldMember { pkgbase: pb.name, version: r.version() }); + } + } + Ok(out) +} + +/// Package files that belong in the served index right now, plus the extra ones +/// being published (which are not in the DB yet when we render `.tmp`). +fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> { + let mut out: Vec<PathBuf> = Vec::new(); + for p in db::index_packages(db)? { + if let Some(aid) = p.artifact_id { + let path: Option<String> = db.read(|c| { + use rusqlite::OptionalExtension; + Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", rusqlite::params![aid], |r| r.get(0)) + .optional()?) + })?; + if let Some(p) = path.map(PathBuf::from).filter(|p| p.exists()) { + out.push(p); + } + } + } + out.extend(extra.iter().cloned()); + Ok(out) +} + +/// Publish the collected artifacts of a build. Returns the new release id. +pub fn publish(ctx: &Ctx) -> Result<i64> { + let collect = Collect::load(&ctx.collect_path)?; + if collect.packages.is_empty() { + return Err(Error::invalid("nothing to publish")); + } + let repo_row = repo_for(&ctx.db)?; + let arch_dir = ctx.cfg.repo_arch_dir(); + std::fs::create_dir_all(&arch_dir)?; + + // Artifacts are copied into the served tree under their real filenames. + let mut staged: Vec<(PathBuf, PathBuf)> = Vec::new(); + for p in &collect.packages { + let from = PathBuf::from(&p.path); + let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch); + let dest = arch_dir.join(&filename); + std::fs::copy(&from, &dest)?; + if let Some(sig) = &p.signature_path { + let s = PathBuf::from(sig); + if s.exists() { + std::fs::copy(&s, arch_dir.join(format!("{filename}.sig")))?; + } + } + staged.push((dest, from)); + } + + let _guard = REPO_LOCK + .lock() + .unwrap_or_else(|e| e.into_inner()); + + // 1. render the new database to .tmp and fsync it. The old one is untouched. + let db_name = ctx.cfg.repo_db_name(); + let final_db = arch_dir.join(format!("{db_name}.tar.gz")); + let tmp_db = arch_dir.join(format!("{db_name}.tar.gz.tmp")); + let mut pkgs = index_artifacts(&ctx.db, &staged.iter().map(|(d, _)| d.clone()).collect::<Vec<_>>())?; + // Deduplicate: the same package name must appear once, newest wins. + pkgs = dedupe_by_name(pkgs); + run_repo_add(&ctx.cfg, &tmp_db, &pkgs)?; + fsync_file(&tmp_db)?; + + // Fault injection so I4 can be tested for real: die between the tmp write + // and the rename, and the old index must still be what consumers get. + if ctx.cfg.publish_fault.as_deref() == Some("before-rename") { + return Err(Error::other("injected fault: before-rename")); + } + + // 2. commit the DB: release + package rows + the accepted pointer, in one + // transaction, with the pointer moved by compare-and-swap. + let release_id = commit_release(ctx, &collect)?; + + // 3. atomic swap: rename over the real database, then sign and swap the sig. + std::fs::rename(&tmp_db, &final_db)?; + fsync_dir(&arch_dir)?; + sign(&ctx.cfg, &final_db)?; + let sig = arch_dir.join(format!("{db_name}.tar.gz.sig")); + let tmp_sig = arch_dir.join(format!("{db_name}.tar.gz.sig.tmp")); + if tmp_sig.exists() { + std::fs::rename(&tmp_sig, &sig)?; + } + + // 4. a publish can unblock builds waiting on a dependency we just added. + let unblocked = builds::requeue_blocked(&ctx.db)?; + db::audit_system( + &ctx.db.writer, + "publish", + "repo", + &repo_row, + serde_json::json!({ + "release": release_id, + "packages": collect.packages.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>(), + "unblocked_builds": unblocked, + }), + )?; + if ctx.cfg.publish_fault.as_deref() == Some("after-rename") { + return Err(Error::other("injected fault: after-rename")); + } + Ok(release_id) +} + +fn repo_for(db: &Db) -> Result<String> { + let id = db::repo_id(db)?; + Ok(id.to_string()) +} + +/// Insert the release and its package rows, and move the accepted pointer. +fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { + let at = time::now(); + let pkgbase_id = ctx.pb.id; + let candidate_id = ctx.build.candidate_id; + let approval_id: Option<i64> = match candidate_id { + Some(cid) => crate::review::approve::approval_for(&ctx.db, cid)?.map(|(id, _)| id), + None => None, + }; + // I1: nothing publishes without an approval. A manual rebuild inherits the + // approval of the release it rebuilds. + let approval_id = match (approval_id, ctx.build.kind.as_str()) { + (Some(a), _) => Some(a), + (None, "manual_rebuild") => ctx + .build + .release_id + .and_then(|rid| db::release_by_id(&ctx.db, rid).ok().flatten()) + .and_then(|r| r.approval_id), + (None, other) => { + return Err(Error::fail_closed(format!( + "refusing to publish a {other} build with no approval behind it" + ))) + } + }; + let build_id = ctx.build.id.clone(); + let packages = collect.packages.clone(); + let names: Vec<String> = packages.iter().map(|p| p.name.clone()).collect(); + let src = ctx.src.clone(); + let world_id = builds::get(&ctx.db, &build_id) + .ok() + .flatten() + .and_then(|b| b.world_snapshot_id); + let repo_id = db::repo_id(&ctx.db)?; + // The compare-and-swap baseline is the release the *approval* was taken + // against, not whatever the pointer happens to say now. If they differ, + // someone accepted a newer version while we were building, and publishing + // this one would roll it back. + let expected_base: Option<i64> = match ctx.build.kind.as_str() { + "manual_rebuild" => ctx.build.release_id, + _ => ctx + .build + .candidate_id + .and_then(|cid| crate::review::candidates::candidate_by_id(&ctx.db, cid).ok().flatten()) + .and_then(|c| c.base_release_id), + }; + + ctx.db.writer.tx(move |tx| { + // Compare-and-swap on the accepted pointer, inside the write + // transaction: two publishes cannot both land (I4). + let actual_base: Option<i64> = tx.query_row( + "SELECT current_accepted_release_id FROM pkgbase WHERE id=?1", + rusqlite::params![pkgbase_id], + |r| r.get(0), + )?; + if actual_base != expected_base { + return Err(Error::conflict( + "accepted pointer moved while this build was running; refusing to publish", + )); + } + // Retire whatever the index held for these names *before* inserting the + // new rows: the index holds exactly the accepted pointer, nothing else. + if !names.is_empty() { + let ph = names.iter().map(|_| "?").collect::<Vec<_>>().join(","); + let sql = format!( + "UPDATE package SET state='removed' WHERE state='in_index' AND name IN ({ph})" + ); + let mut stmt = tx.prepare(&sql)?; + stmt.execute(rusqlite::params_from_iter(names.iter().map(|n| n as &dyn rusqlite::ToSql)))?; + } + tx.execute( + "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash, + upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel, + world_snapshot_id, state, build_id, published_at, created_at) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,'published',?12,?13,?13)", + rusqlite::params![ + pkgbase_id, candidate_id, approval_id, src.aur_commit, src.recipe_hash, + src.upstream_pins_json, src.source_digests_json, src.epoch, src.pkgver, src.pkgrel, + world_id, build_id, at + ], + )?; + let release_id = tx.last_insert_rowid(); + for p in &packages { + let artifact_id: Option<i64> = tx + .query_row( + "SELECT id FROM artifact WHERE digest=?1", + rusqlite::params![p.digest], + |r| r.get(0), + ) + .optional()?; + tx.execute( + "INSERT INTO package (repo_id, release_id, name, arch, version, artifact_id, state) + VALUES (?1,?2,?3,?4,?5,?6,'in_index')", + rusqlite::params![repo_id, release_id, p.name, p.arch, p.version, artifact_id], + )?; + } + let moved = tx.execute( + "UPDATE pkgbase SET current_accepted_release_id=?1 WHERE id=?2 AND current_accepted_release_id IS ?3", + rusqlite::params![release_id, pkgbase_id, expected_base], + )?; + if moved != 1 { + return Err(Error::conflict( + "accepted pointer moved while this build was running; refusing to publish", + )); + } + tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", rusqlite::params![release_id, build_id])?; + if let Some(cid) = candidate_id { + tx.execute("UPDATE candidate SET state='approved' WHERE id=?1", rusqlite::params![cid])?; + } + Ok(release_id) + }) +} + +/// `repo-add -s -p <key> -R <db> <pkgs...>` (§9: both packages and the database +/// are signed so consumers can run `SigLevel = Required`). +fn run_repo_add(cfg: &Config, db_path: &Path, pkgs: &[PathBuf]) -> Result<()> { + let mut cmd = Command::new(&cfg.repo_add_bin); + cmd.arg("-R"); + if !cfg.signing_key_id.is_empty() { + cmd.args(["-s", "-p", &cfg.signing_key_id]); + } + cmd.arg(db_path); + for p in pkgs { + cmd.arg(p); + } + cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: cfg.repo_add_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + Ok(()) +} + +fn sign(cfg: &Config, path: &Path) -> Result<()> { + if cfg.signing_key_id.is_empty() { + return Ok(()); + } + let mut cmd = Command::new(&cfg.gpg_bin); + cmd.args(["--batch", "--yes", "--detach-sign", "--local-user", &cfg.signing_key_id]); + cmd.arg("-o"); + let tmp = format!("{}.tmp", path.display()); + cmd.arg(&tmp); + cmd.arg(path); + cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: cfg.gpg_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + std::fs::rename(&tmp, format!("{}.sig", path.display()))?; + Ok(()) +} + +fn fsync_file(p: &Path) -> Result<()> { + if let Ok(f) = std::fs::File::open(p) { + let _ = f.sync_all(); + } + Ok(()) +} + +fn fsync_dir(p: &Path) -> Result<()> { + if let Ok(d) = std::fs::File::open(p) { + let _ = d.sync_all(); + } + Ok(()) +} + + +/// Keep one entry per package name; the newest file wins. The name comes from +/// `.PKGINFO` inside the tarball, not from the filename, because package names +/// contain dashes. +fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> { + let mut seen: BTreeSet<String> = BTreeSet::new(); + let mut out: Vec<PathBuf> = Vec::new(); + for p in paths.into_iter().rev() { + let name = package_name(&p).unwrap_or_else(|| { + p.file_name() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default() + }); + if seen.insert(name) { + out.push(p); + } + } + out.reverse(); + out +} + +fn package_name(path: &Path) -> Option<String> { + let bytes = std::fs::read(path).ok()?; + let info = crate::shims::read_pkginfo(&bytes).ok()?; + for line in info.lines() { + if let Some(v) = line.strip_prefix("pkgname =") { + return Some(v.trim().to_string()); + } + } + None +} + +/// Re-materialize the served index from the DB. Run at startup: if a crash left +/// the DB ahead of the file, this closes the gap without inventing anything. +pub fn reconcile(cfg: &Config, db: &Db) -> Result<usize> { + let pkgs = db::index_packages(db)?; + let mut files = Vec::new(); + for p in &pkgs { + if let Some(aid) = p.artifact_id { + let path: Option<String> = db.read(|c| { + use rusqlite::OptionalExtension; + Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", rusqlite::params![aid], |r| r.get(0)) + .optional()?) + })?; + if let Some(path) = path.map(PathBuf::from).filter(|p| p.exists()) { + let arch_dir = cfg.repo_arch_dir(); + let _ = std::fs::create_dir_all(&arch_dir); + let dest = arch_dir.join(format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch)); + if !dest.exists() { + let _ = std::fs::copy(&path, &dest); + } + files.push(dest); + } + } + } + if files.is_empty() { + return Ok(0); + } + let arch_dir = cfg.repo_arch_dir(); + let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); + run_repo_add(cfg, &tmp, &dedupe_by_name(files.clone()))?; + std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + Ok(files.len()) +} + +/// Remove a package from the served index (§9 withdrawal path). +pub fn withdraw_package(cfg: &Config, db: &Db, name: &str) -> Result<()> { + let _guard = REPO_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let rid = db::repo_id(db)?; + let n = name.to_string(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2", + rusqlite::params![rid, n], + )?; + Ok(()) + })?; + let arch_dir = cfg.repo_arch_dir(); + let tmp = arch_dir.join(format!("{}.tar.gz.tmp", cfg.repo_db_name())); + let files = index_artifacts(db, &[])?; + run_repo_add(cfg, &tmp, &dedupe_by_name(files))?; + std::fs::rename(&tmp, arch_dir.join(format!("{}.tar.gz", cfg.repo_db_name())))?; + db::audit(&db.writer, "human", "cli", "withdraw.publish", "package", name, serde_json::json!({}))?; + Ok(()) +} diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs new file mode 100644 index 0000000..b925afb --- /dev/null +++ b/src/pipeline/steps.rs @@ -0,0 +1,456 @@ +//! The ten pipeline steps (§8.1). +//! +//! Every step is idempotent and records its result in one short transaction; +//! the long-running child process happens outside any transaction (§11a). + +use std::path::Path; +use std::process::Command; + +use crate::db::{self, builds, model::*}; +use crate::error::{Error, Result}; +use crate::git; +use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult}; +use crate::watch::digests::cached_path; + +pub fn run_step(ctx: &Ctx, step: &str) -> Result<StepResult> { + match step { + "materialize" => materialize(ctx), + "plan" => plan(ctx), + "chroot" => chroot(ctx), + "sources" => sources(ctx), + "pkgver" => pkgver(ctx), + "build" => build(ctx), + "collect" => collect(ctx), + "verify" => verify(ctx), + "ingest" => ingest(ctx), + "publish" => publish(ctx), + other => Err(Error::invalid(format!("unknown step {other}"))), + } +} + +/// Step 0 — materialize from the local mirror only, never the network, and +/// re-hash what we got. This is the `aur_commit` pin doing its job: there is no +/// path from "AUR moved since the review" to "we built it anyway". +fn materialize(ctx: &Ctx) -> Result<StepResult> { + let mirror = ctx + .pb + .mirror_path + .as_ref() + .map(Path::new) + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| ctx.cfg.mirror_path(&ctx.pb.name)); + if !mirror.exists() { + return Err(Error::fail_closed(format!( + "mirror {} missing; refusing to fetch a recipe from the network at build time", + mirror.display() + ))); + } + if ctx.src.aur_commit.is_empty() { + return Err(Error::fail_closed("no aur_commit on the source identity")); + } + let _ = std::fs::remove_dir_all(&ctx.srcdir); + git::materialize(&mirror, &ctx.src.aur_commit, &ctx.srcdir)?; + let tree = crate::watch::mirror::read_tree(&mirror, &ctx.src.aur_commit)?; + let computed = tree.recipe_hash(); + if !ctx.src.recipe_hash.is_empty() && computed != ctx.src.recipe_hash { + return Err(Error::fail_closed(format!( + "recipe_hash mismatch: approved {}, materialized {}", + ctx.src.recipe_hash, computed + ))); + } + ctx.log_line(&format!( + " materialized {} at {} (recipe_hash {})", + ctx.pb.name, + short(&ctx.src.aur_commit), + short(&computed) + )); + Ok(StepResult::Done(Some(computed))) +} + +/// A display-safe prefix; hashes are 64 hex chars but world digests can be tiny. +fn short(s: &str) -> String { + s.chars().take(12).collect() +} + +/// Step 1 — resolve dependencies against the current accepted index and compute +/// the intended world. Unresolvable means "a pkgbase we subscribe to that we have +/// not published yet": block and wait, do not fail (§10.4). +fn plan(ctx: &Ctx) -> Result<StepResult> { + let recipe = recipe_at(&ctx.srcdir)?; + let mut wanted: Vec<String> = Vec::new(); + for list in [&recipe.depends, &recipe.makedepends, &recipe.checkdepends] { + wanted.extend(crate::pkgver::dep_names(list)); + } + wanted.sort(); + wanted.dedup(); + + let ours = db::our_package_names(&ctx.db)?; + let mut missing = Vec::new(); + let mut official = 0; + for dep in &wanted { + if ours.contains(dep) || ctx.pb.name == *dep || recipe.pkgnames.contains(dep) { + continue; // satisfied by our own index, or by this very build + } + // Anything else is only a problem if we are supposed to be publishing it. + if db::get_subscription(&ctx.db, dep)?.is_some() || db::get_pkgbase(&ctx.db, dep)?.is_some() { + missing.push(dep.clone()); + } else { + official += 1; + } + } + if !missing.is_empty() { + builds::set_blocked_on(&ctx.db, &ctx.build.id, &missing)?; + return Ok(StepResult::Blocked(missing)); + } + let world = crate::pipeline::publish::index_world(&ctx.db)?; + let hash = crate::hash::canonical_json(&world); + ctx.log_line(&format!( + " deps: {} ours/official, {} from official repos, world {}", + wanted.len() - official, + official, + short(&hash) + )); + Ok(StepResult::Done(Some(hash))) +} + +/// Step 2 — warm chroot seed, created once per profile and never mutated; each +/// build gets a copy-on-write snapshot from it (§8.3). +fn chroot(ctx: &Ctx) -> Result<StepResult> { + let seed = ctx.cfg.chroot_seed(&ctx.profile); + if !seed.exists() { + std::fs::create_dir_all(seed.parent().unwrap_or(&ctx.cfg.chroot_dir()))?; + let mut cmd = Command::new(&ctx.cfg.mkarchroot_bin); + cmd.args(["-N", &seed.display().to_string()]); + ctx.cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: ctx.cfg.mkarchroot_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + ctx.log_line(&format!(" created chroot seed {}", seed.display())); + } + Ok(StepResult::Done(Some(seed.display().to_string()))) +} + +/// Step 3 — make sure every source we reviewed is on disk and hashes to what the +/// candidate recorded. For a `SKIP` source this is the only verification that +/// exists, and it closes the window between "we hashed it at review time" and +/// "makepkg downloaded something else just now" (§8.1). +fn sources(ctx: &Ctx) -> Result<StepResult> { + let digests: Vec<SourceDigest> = serde_json::from_str(&ctx.src.source_digests_json).unwrap_or_default(); + let mut verified = 0; + for d in &digests { + match d.kind.as_str() { + // Already materialized from the mirror at the pinned commit. + "local" => verified += 1, + // VCS kinds (git/svn/hg/bzr): honouring upstream_pins at build time + // is deferred to P1 (§20); the pkgver assertion is the interim guard. + "vcs" | "git" | "svn" | "hg" | "bzr" => verified += 1, + _ => { + let (digest, _size) = match cached_path(&ctx.db, &d.url, &d.digest) { + Some(p) => crate::hash::digest_file(&p)?, + None => crate::watch::digests::download_and_cache(&ctx.cfg, &ctx.db, &d.url)?, + }; + if digest != d.digest { + return Err(Error::fail_closed(format!( + "source {} hashed to {digest} but the candidate recorded {}", + d.url, d.digest + ))); + } + verified += 1; + } + } + } + ctx.log_line(&format!(" {}/{} source digests verified", verified, digests.len())); + Ok(StepResult::Done(Some(crate::hash::hex_str( + &ctx.src.source_digests_json, + )))) +} + +/// Step 4 — the belt-and-braces assertion that what we build is what was +/// approved. If upstream moved between approval and build, fail with both +/// versions instead of silently shipping the new one (§8.1). +fn pkgver(ctx: &Ctx) -> Result<StepResult> { + let recipe = recipe_at(&ctx.srcdir)?; + let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs()); + if !has_vcs { + let want = (ctx.src.pkgver.clone(), ctx.src.pkgrel.clone()); + let got = (recipe.pkgver.clone(), recipe.pkgrel.clone()); + if want != got { + return Err(Error::fail_closed(format!( + "approved {}-{} but the recipe says {}-{}", + want.0, want.1, got.0, got.1 + ))); + } + return Ok(StepResult::Skipped("no VCS sources; pkgver is static".into())); + } + let mut cmd = Command::new(&ctx.cfg.makepkg_bin); + cmd.current_dir(&ctx.srcdir).arg("--vercheck"); + ctx.cfg.child_env(&mut cmd); + let out = cmd.output()?; + if !out.status.success() { + return Err(Error::Subprocess { + cmd: ctx.cfg.makepkg_bin.clone(), + detail: String::from_utf8_lossy(&out.stderr).into_owned(), + }); + } + let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); + let (got_ver, got_rel) = match text.rsplit_once('-') { + Some((v, r)) => (v.to_string(), r.to_string()), + None => (text.clone(), "1".into()), + }; + if got_ver != ctx.src.pkgver || got_rel != ctx.src.pkgrel { + return Err(Error::fail_closed(format!( + "approved {}-{}, upstream now resolves to {got_ver}-{got_rel}", + ctx.src.pkgver, ctx.src.pkgrel + ))); + } + ctx.log_line(&format!(" pkgver resolves as approved: {text}")); + Ok(StepResult::Done(Some(text))) +} + +/// Step 5 — `makechrootpkg -c -r <chroot> -- -si<key> -f`, with the log going to +/// the file the SSE tail reads. +fn build(ctx: &Ctx) -> Result<StepResult> { + let seed = ctx.cfg.chroot_seed(&ctx.profile); + let mut cmd = Command::new(&ctx.cfg.makechrootpkg_bin); + cmd.current_dir(&ctx.srcdir); + cmd.args(["-c", "-r", &seed.display().to_string(), "--"]); + if !ctx.cfg.signing_key_id.is_empty() { + cmd.arg(format!("-si{}", ctx.cfg.signing_key_id)); + } + cmd.arg("-f"); + ctx.cfg.child_env(&mut cmd); + let out = cmd.output()?; + // Capture the child's output into the build log regardless of outcome. + if let Some(parent) = ctx.log.parent() { + let _ = std::fs::create_dir_all(parent); + } + use std::io::Write; + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&ctx.log) { + let _ = f.write_all(&out.stdout); + let _ = f.write_all(&out.stderr); + } + if !out.status.success() { + return Err(Error::Subprocess { + cmd: ctx.cfg.makechrootpkg_bin.clone(), + detail: tail(&out.stderr), + }); + } + Ok(StepResult::Done(Some(crate::hash::hex_str(&format!( + "build:{}", + ctx.build.id + ))))) +} + +fn tail(b: &[u8]) -> String { + let s = String::from_utf8_lossy(b).trim().to_string(); + let lines: Vec<&str> = s.lines().collect(); + lines[lines.len().saturating_sub(6)..].join(" | ") +} + +/// Step 6 — parse `.PKGINFO`/`.BUILDINFO` out of the produced artifacts (§10.1: +/// plain text in a tar, no libalpm needed). +fn collect(ctx: &Ctx) -> Result<StepResult> { + let mut pkgs = Vec::new(); + let mut entries: Vec<PathBuf> = std::fs::read_dir(&ctx.srcdir)? + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst")) + .collect(); + entries.sort(); + for path in entries { + let bytes = std::fs::read(&path)?; + let (digest, size) = crate::hash::digest_file(&path)?; + let pkginfo = crate::shims::read_pkginfo(&bytes) + .map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?; + let buildinfo = crate::shims::read_buildinfo(&bytes).unwrap_or_default(); + let meta = parse_pkginfo(&pkginfo); + let sig = path.with_extension("pkg.tar.zst.sig"); + pkgs.push(CollectedPkg { + name: meta.get("pkgname").cloned().unwrap_or_default(), + version: meta.get("pkgver").cloned().unwrap_or_default(), + arch: meta.get("pkgarch").cloned().unwrap_or_else(|| ctx.cfg.arch.clone()), + path: path.display().to_string(), + digest, + size, + signature_path: sig.exists().then(|| sig.display().to_string()), + depends: meta_multi(&pkginfo, "depend"), + makedepends: meta_multi(&pkginfo, "makedepend"), + provides: meta_multi(&pkginfo, "provides"), + conflicts: meta_multi(&pkginfo, "conflict"), + installed: parse_installed(&buildinfo), + }); + } + if pkgs.is_empty() { + return Err(Error::invalid("build produced no packages")); + } + let collect = Collect { packages: pkgs.clone() }; + collect.save(&ctx.collect_path)?; + // A split pkgbase is one approval and N index entries (§3). + ctx.log_line(&format!(" collected {}", pkgs.iter().map(|p| format!("{}-{}", p.name, p.version)).collect::<Vec<_>>().join(", "))); + Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?)))) +} + +/// Step 7 — signature present, dependencies satisfiable, no downgrade. +fn verify(ctx: &Ctx) -> Result<StepResult> { + let collect = Collect::load(&ctx.collect_path)?; + let ours = db::our_package_names(&ctx.db)?; + for p in &collect.packages { + if p.signature_path.is_none() && !ctx.cfg.signing_key_id.is_empty() { + return Err(Error::fail_closed(format!("{} has no signature", p.name))); + } + if crate::pkgver::is_downgrade( + &db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()), + &p.version, + ) { + // Downgrades are allowed but flagged (§16); the review already shows it. + ctx.log_line(&format!(" note: {} is a downgrade from what we serve", p.name)); + } + let mut provided: std::collections::BTreeSet<String> = ours.clone(); + provided.extend(collect.packages.iter().map(|q| q.name.clone())); + provided.extend(p.provides.iter().flat_map(|v| crate::pkgver::dep_names(std::slice::from_ref(v)))); + for dep in crate::pkgver::dep_names(&p.depends) { + if !provided.contains(&dep) && db::get_pkgbase(&ctx.db, &dep)?.is_some() { + return Err(Error::fail_closed(format!( + "{} depends on {dep}, which is not satisfiable in the target repo", + p.name + ))); + } + } + } + Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string( + &collect.packages.iter().map(|p| (&p.name, &p.version)).collect::<Vec<_>>(), + )?)))) +} + +/// Step 8 — move artifacts into the content-addressed store and record rows. +/// Staging stays disposable; a GC pass sweeps abandoned directories (§8.2). +fn ingest(ctx: &Ctx) -> Result<StepResult> { + let mut collect = Collect::load(&ctx.collect_path)?; + for p in &mut collect.packages { + let from = Path::new(&p.path); + let dest = ctx.cfg.store_path(&p.digest); + if !dest.exists() { + if let Some(parent) = dest.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::copy(from, &dest)?; + } + p.path = dest.display().to_string(); + if let Some(sig) = p.signature_path.clone() { + let sigdest = ctx.cfg.store_path(&format!("{}-sig", p.digest)); + if !sigdest.exists() && Path::new(&sig).exists() { + std::fs::copy(&sig, &sigdest)?; + } + p.signature_path = Some(sigdest.display().to_string()); + } + } + collect.save(&ctx.collect_path)?; + + let at = crate::time::now(); + let packages = collect.packages.clone(); + let packages_for_db = packages.clone(); + let build_id = ctx.build.id.clone(); + let log_path = ctx.log.display().to_string(); + ctx.db.writer.tx(move |tx| { + for p in &packages_for_db { + tx.execute( + "INSERT INTO artifact (digest, size, path, signature_path, build_log_path, build_id, created_at) + VALUES (?1,?2,?3,?4,?5,?6,?7) + ON CONFLICT(digest) DO UPDATE SET build_id=excluded.build_id", + rusqlite::params![p.digest, p.size as i64, p.path, p.signature_path, log_path, build_id, at], + )?; + } + Ok(()) + })?; + + // §10.1: the world snapshot is the build's installed set INTERSECTED with our + // own packages, filtered at ingest time, not at query time. Left unfiltered, + // every package would be permanently stale because Arch never stops moving. + let ours = db::our_package_names(&ctx.db)?; + let mut members: Vec<WorldMember> = Vec::new(); + for p in &collect.packages { + for (name, version) in &p.installed { + if ours.contains(name) { + members.push(WorldMember { pkgbase: name.clone(), version: version.clone() }); + } + } + } + let world_id = db::put_world_snapshot(&ctx.db.writer, &members)?; + builds::set_world(&ctx.db, &ctx.build.id, world_id)?; + ctx.log_line(&format!(" ingested {} artifact(s), world has {} of our packages", packages.len(), members.len())); + Ok(StepResult::Done(Some(crate::hash::hex_str(&format!( + "ingest:{}", + packages.len() + ))))) +} + +/// Step 9 — the only externally visible step, serialized per repo (§9). +fn publish(ctx: &Ctx) -> Result<StepResult> { + let release_id = crate::pipeline::publish::publish(ctx)?; + Ok(StepResult::Done(Some(format!("release:{release_id}")))) +} + +// ---------------------------------------------------------------- helpers -- + +use std::path::PathBuf; + +/// Read the recipe from a materialized tree, preferring `.SRCINFO`. +pub fn recipe_at(dir: &Path) -> Result<Recipe> { + let mut files = std::collections::BTreeMap::new(); + for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(|e| e.ok()) { + let p = entry.path(); + if !p.is_file() { + continue; + } + let rel = p.strip_prefix(dir).unwrap_or(p).display().to_string(); + if let Ok(body) = std::fs::read_to_string(p) { + files.insert(rel, body); + } + } + crate::recipe::recipe_from_tree(&files) +} + +fn parse_pkginfo(text: &str) -> std::collections::HashMap<String, String> { + let mut m = std::collections::HashMap::new(); + for line in text.lines() { + if let Some((k, v)) = line.split_once('=') { + m.insert(k.trim().to_string(), v.trim().to_string()); + } + } + m +} + +fn meta_multi(text: &str, key: &str) -> Vec<String> { + text.lines() + .filter_map(|l| l.split_once('=')) + .filter(|(k, _)| k.trim() == key) + .map(|(_, v)| v.trim().to_string()) + .collect() +} + +/// `.BUILDINFO` `installed =` block: ` name version arch sig` per line. +fn parse_installed(text: &str) -> Vec<(String, String)> { + let mut out = Vec::new(); + let mut in_block = false; + for line in text.lines() { + if line.trim_start().starts_with("installed") { + in_block = true; + continue; + } + if in_block { + if !line.starts_with(' ') && !line.starts_with('\t') { + in_block = false; + continue; + } + let mut it = line.split_whitespace(); + if let (Some(name), Some(version)) = (it.next(), it.next()) { + out.push((name.to_string(), version.to_string())); + } + } + } + out +} |
