//! 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> { 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> { let mut out: Vec = Vec::new(); for p in db::index_packages(db)? { if let Some(aid) = p.artifact_id { let path: Option = 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 { 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::>())?; // 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::>(), "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 { 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 { let at = time::now(); let pkgbase_id = ctx.pb.id; let candidate_id = ctx.build.candidate_id; let approval_id: Option = 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 = 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 = 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 = 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::>().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 = 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 -R ` (§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) -> Vec { let mut seen: BTreeSet = BTreeSet::new(); let mut out: Vec = 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 { 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 { 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 = 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(()) }