//! 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 { 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 { 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 { let recipe = recipe_at(&ctx.srcdir)?; let mut wanted: Vec = 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 { 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); // Real devtools usage: `mkarchroot [options] `. cmd.arg(&seed).args(&ctx.cfg.mkarchroot_args); 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 { let digests: Vec = 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 { 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 -- -si -f`, with the log going to /// the file the SSE tail reads. fn build(ctx: &Ctx) -> Result { 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 { let mut pkgs = Vec::new(); let mut entries: Vec = 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(); // I9: the build is untrusted. In production it runs in a chroot, but the // control plane must not *depend* on that for its own safety. Everything // below takes a path that a PKGBUILD could have arranged to exist in the // srcdir, and the next step copies whatever that path points at into the // content-addressed store — from where it is served from our repo and signed // with our key. A symlink to the signing keyring, the database, or anyone's // home directory would otherwise become a signed artifact we publish. So: // no symlinks, and the resolved target must live inside this build's own // staging directory. Anything else fails the build closed. let staging_root = ctx.staging.canonicalize()?; for path in entries { if std::fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(true) { return Err(Error::fail_closed(format!( "{} is a symlink; a build may not smuggle bytes in from outside its own staging dir (I9)", path.display() ))); } let resolved = path.canonicalize()?; if !resolved.starts_with(&staging_root) { return Err(Error::fail_closed(format!( "{} resolves outside this build's staging dir ({staging_root:?}); refusing to ingest it (I9)", path.display() ))); } let path = resolved; let bytes = std::fs::read(&path)?; let (digest, size) = crate::hash::digest_file(&path)?; // Read what the package says about itself out of the archive, rather // than trusting what the build claimed on stdout (§10.1). let pkginfo = crate::pkginfo::pkginfo_text(&bytes) .map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?; let meta = crate::pkginfo::parse_pkginfo(&pkginfo); // `.BUILDINFO` is what the world snapshot is built from. Absent is not // fatal — the snapshot is then simply empty for this package — but a // present-but-unparseable one would be a lie we should not swallow. let buildinfo = crate::pkginfo::buildinfo_text(&bytes).unwrap_or_default(); let sig = path.with_extension("pkg.tar.zst.sig"); pkgs.push(CollectedPkg { name: meta.name.clone(), version: meta.version.clone(), arch: if meta.arch.is_empty() { ctx.cfg.arch.clone() } else { meta.arch.clone() }, path: path.display().to_string(), digest, size, signature_path: sig.exists().then(|| sig.display().to_string()), depends: meta.depends.clone(), makedepends: meta.makedepends.clone(), provides: meta.provides.clone(), conflicts: meta.conflicts.clone(), installed: crate::pkginfo::parse_installed(&buildinfo) .into_iter() .map(|i| (i.name, i.version)) .collect(), }); } 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::>().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 { 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 = 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::>(), )?)))) } /// 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 { 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 { db::insert_artifact_in( tx, &db::NewArtifact { digest: &p.digest, size: p.size as i64, path: &p.path, signature_path: p.signature_path.as_deref(), build_log_path: Some(&log_path), build_id: &build_id, at: &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 = 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 { 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(crate) fn recipe_at(dir: &Path) -> Result { 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) }