use std::collections::BTreeSet; use std::path::PathBuf; use std::process::Command; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Condvar, Mutex}; use crate::config::Config; use crate::db::{ self, model::{Recipe, StageBCacheRow, UpstreamPin}, Db, Pkgbase, }; use crate::error::{Error, Result, TransientCause}; use crate::git; #[derive(Debug, Clone)] // StageA stays `pub`: what `upstream::probe` returns; tests/ops.rs and tests/vcs.rs call `probe` directly. pub struct StageA { pub pins: Vec, pub unprobed: Vec, pub moved: bool, } impl StageA { /// Detection consults it; the VCS test that asserts it needs a real mirror. /// /// Module-internal in a production build, `pub` only under `test-support`: /// one body behind two visibility declarations, exactly one of which compiles. #[cfg(feature = "test-support")] pub fn needs_stage_b(&self) -> bool { Self::needs_stage_b_impl(self) } #[cfg(not(feature = "test-support"))] pub(crate) fn needs_stage_b(&self) -> bool { Self::needs_stage_b_impl(self) } fn needs_stage_b_impl(&self) -> bool { self.moved || !self.unprobed.is_empty() } } /// Detection calls it on every expensive poll; the tests that pin it need a fixture. /// /// Module-internal in a production build, `pub` only under `test-support`: /// one body behind two visibility declarations, exactly one of which compiles. #[cfg(feature = "test-support")] pub fn probe(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result { probe_impl(recipe, accepted) } #[cfg(not(feature = "test-support"))] pub(crate) fn probe(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result { probe_impl(recipe, accepted) } fn probe_impl(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result { let mut pins = Vec::new(); let mut unprobed = Vec::new(); for entry in recipe.source_entries.iter().filter(|e| e.is_vcs()) { let want = if let Some(c) = &entry.commit { pins.push(UpstreamPin { index: entry.index, url: entry.url.clone(), ref_: format!("commit={c}"), branch: entry.branch.clone(), commit: c.clone(), }); continue; } else if let Some(t) = &entry.tag { (format!("refs/tags/{t}"), t.clone()) } else if let Some(b) = &entry.branch { (format!("refs/heads/{b}"), b.clone()) } else { ("HEAD".into(), "HEAD".into()) }; match entry.vcs.as_deref() { Some("git") | None => { let sha = match want.0.as_str() { "HEAD" => git::ls_remote_head(&entry.url)?, refname => git::ls_remote_ref(&entry.url, refname)?, }; match sha { Some(sha) => pins.push(UpstreamPin { index: entry.index, url: entry.url.clone(), ref_: want.1, branch: entry.branch.clone(), commit: sha, }), None => unprobed.push(entry.url.clone()), } } Some(other) => { unprobed.push(format!("{other}:{}", entry.url)); pins.push(UpstreamPin { index: entry.index, url: entry.url.clone(), ref_: want.1, branch: entry.branch.clone(), commit: String::new(), }); } } } let now: BTreeSet<(usize, String)> = pins.iter().map(|p| (p.index, p.commit.clone())).collect(); let then: BTreeSet<(usize, String)> = accepted.iter().map(|p| (p.index, p.commit.clone())).collect(); Ok(StageA { pins, unprobed, moved: now != then }) } #[derive(Debug, Clone)] pub(crate) struct StageB { pub epoch: String, pub pkgver: String, pub pkgrel: String, pub pins: Vec, } impl StageB { fn from_cache(row: StageBCacheRow) -> Self { StageB { epoch: row.epoch, pkgver: row.pkgver, pkgrel: row.pkgrel, pins: row.pins } } fn as_row(&self) -> StageBCacheRow { StageBCacheRow { epoch: self.epoch.clone(), pkgver: self.pkgver.clone(), pkgrel: self.pkgrel.clone(), pins: self.pins.clone(), } } } static RUNNING: AtomicUsize = AtomicUsize::new(0); static SLOT_FREE: Condvar = Condvar::new(); static SLOT_LOCK: Mutex<()> = Mutex::new(()); /// The real definition. The module is private, so this `pub` /// is not a nameable path from outside; the alias below is the /// only way to reach it, and the alias is what carries the /// feature-conditional visibility. mod stage_b_slot { use super::{Ordering, RUNNING, SLOT_FREE, SLOT_LOCK}; pub struct StageBSlot(()); impl StageBSlot { pub fn acquire(cap: usize) -> Self { let cap = cap.max(1); let guard = SLOT_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut guard = guard; loop { let n = RUNNING.load(Ordering::SeqCst); if n < cap { RUNNING.fetch_add(1, Ordering::SeqCst); drop(guard); return StageBSlot(()); } guard = SLOT_FREE.wait(guard).unwrap_or_else(std::sync::PoisonError::into_inner); } } } } /// The stage-B concurrency slot. The VCS test that asserts it needs a real mirror, so it cannot move into the module. /// /// `pub` only under `test-support`. Production reaches the type /// through its own module and never names it from outside; the /// outside reader that needs the name is a test. #[cfg(feature = "test-support")] pub use stage_b_slot::StageBSlot; #[cfg(not(feature = "test-support"))] pub(crate) use stage_b_slot::StageBSlot; impl Drop for StageBSlot { fn drop(&mut self) { RUNNING.fetch_sub(1, Ordering::SeqCst); SLOT_FREE.notify_one(); } } pub(crate) fn resolve( cfg: &Config, db: &Db, pb: &Pkgbase, recipe: &Recipe, recipe_hash: &str, stage_a: &StageA, ) -> Result> { if !recipe.source_entries.iter().any(super::super::db::model::SourceEntry::is_vcs) { return Ok(None); } let tip_hash = tip_hash(&stage_a.pins); if let Some(hit) = db::stage_b_cache_get(db, pb.id, recipe_hash, &tip_hash)? { return Ok(Some(StageB::from_cache(hit))); } let cooldown = db::setting_i64(db, "stage_b_cooldown", 86400); if let Some(recent) = db::stage_b_recent(db, pb.id, cooldown)? { return Ok(Some(StageB::from_cache(recent))); } let _slot = StageBSlot::acquire(db::setting_i64(db, "stage_b_concurrency", 1) as usize); let resolved = run(cfg, pb, recipe, recipe_hash, &tip_hash, stage_a)?; db::stage_b_cache_put(db, pb.id, recipe_hash, &tip_hash, &resolved.as_row())?; Ok(Some(resolved)) } fn run( cfg: &Config, pb: &Pkgbase, recipe: &Recipe, recipe_hash: &str, tip_hash: &str, stage_a: &StageA, ) -> Result { let mut pins = stage_a.pins.clone(); for pin in &mut pins { if pin.commit.is_empty() { continue; } let cache = cfg.vcs_cache_path(&pin.url); if cache.exists() { let _ = git::fetch_and_head(&cache); } else { git::clone_bare(&pin.url, &cache) .map_err(|e| Error::transient(TransientCause::Upstream(format!("vcs_cache clone {}: {e}", pin.url))))?; } if let Ok(local) = git::head(&cache) { if !local.is_empty() && git::has_commit(&cache, &pin.commit) { pin.branch = pin.branch.clone().or_else(|| default_branch(&cache)); } } } let scratch = scratch_dir(cfg, &pb.name, recipe_hash, tip_hash); let _ = std::fs::remove_dir_all(&scratch); std::fs::create_dir_all(&scratch)?; std::fs::write(scratch.join("PKGBUILD"), &recipe.pkgbuild)?; if let Some(srcinfo) = &recipe.srcinfo { std::fs::write(scratch.join(".SRCINFO"), srcinfo)?; } let mut cmd = Command::new(&cfg.makepkg_bin); cmd.current_dir(&scratch).arg("--vercheck"); cfg.child_env(&mut cmd); let out = cmd.output()?; let _ = std::fs::remove_dir_all(&scratch); if !out.status.success() { return Err(Error::transient(format!("makepkg --vercheck: {}", String::from_utf8_lossy(&out.stderr).trim()))); } let text = String::from_utf8_lossy(&out.stdout).trim().to_string(); let (pkgver, pkgrel) = match text.rsplit_once('-') { Some((v, r)) => (v.to_string(), r.to_string()), None => (text.clone(), "1".to_string()), }; if pkgver.is_empty() { return Err(Error::other(format!("makepkg --vercheck produced {text:?}"))); } Ok(StageB { epoch: recipe.epoch.clone(), pkgver, pkgrel, pins }) } fn default_branch(cache: &std::path::Path) -> Option { git::git(Some(cache), &["symbolic-ref", "--short", "HEAD"]) .ok() .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()) } pub fn tip_hash(pins: &[UpstreamPin]) -> String { let mut v: Vec = pins.iter().map(|p| format!("{}:{}:{}", p.index, p.url, p.commit)).collect(); v.sort(); crate::hash::hex_str(&v.join("\n")) } fn scratch_dir(cfg: &Config, pkgbase: &str, recipe_hash: &str, tip_hash: &str) -> PathBuf { cfg.staging_dir().join("vercheck").join(format!( "{pkgbase}-{}-{}", &recipe_hash[..8.min(recipe_hash.len())], &tip_hash[..8.min(tip_hash.len())] )) }