summaryrefslogtreecommitdiffstats
path: root/src/watch/upstream.rs
blob: c2772a2e89f27716d0386301154aa0d7f7385428 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//! The two-stage VCS watcher (§5.2) — the expensive path, made cheap.
//!
//! For a `-git` package the `pkgver=` field is frozen and the real version is
//! computed by `pkgver()` at build time, so detection cannot read it off the
//! recipe. Running the real thing every poll would be absurd, so:
//!
//! **Stage A** asks each upstream where its tip is now (`git ls-remote`, which
//! costs one network round trip and no clone). If the set of tips is identical
//! to the set recorded on the accepted release, *nothing can have changed* and
//! we stop. This is the common case: most days, nothing moves.
//!
//! **Stage B** runs only when Stage A saw movement: clone/fetch into the
//! persistent cache, run `makepkg --vercheck` against the recipe, and read back
//! the computed `epoch:pkgver-pkgrel` — the only correct answer, because
//! `pkgver()` can do arbitrary things. The clone is already there, so this is
//! also where the pins are captured.

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::*, Db, Pkgbase};
use crate::error::{Error, Result};
use crate::git;

/// What Stage A found.
#[derive(Debug, Clone)]
pub struct StageA {
    /// One pin per VCS source, in `source=()` order.
    pub pins: Vec<UpstreamPin>,
    /// URLs we could not probe cheaply (svn, hg, or a dead remote). Treated as
    /// "assume it moved" — we would rather run Stage B than miss a release.
    pub unprobed: Vec<String>,
    /// True when the tip set differs from the accepted release's pins.
    pub moved: bool,
}

impl StageA {
    /// Stage B is worth running: something upstream moved, or we cannot prove
    /// that nothing did.
    pub fn needs_stage_b(&self) -> bool {
        self.moved || !self.unprobed.is_empty()
    }
}

/// Probe every VCS source in the recipe. **Every** one, not just the first: a
/// pkgbase can build from two upstream repos and either can move alone.
pub fn probe(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result<StageA> {
    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 {
            // Pinned to a commit by the recipe itself: it cannot move.
            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,
                    }),
                    // The remote is gone or the ref vanished: that is movement
                    // we must not swallow, and Stage B will report it properly.
                    None => unprobed.push(entry.url.clone()),
                }
            }
            // svn/hg/bzr: no cheap universal probe. Be honest about it and let
            // Stage B decide, rather than claiming nothing moved.
            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 })
}

/// What Stage B produced: the authoritative version plus the pins it was
/// computed from.
#[derive(Debug, Clone)]
pub struct StageB {
    pub epoch: String,
    pub pkgver: String,
    pub pkgrel: String,
    pub pins: Vec<UpstreamPin>,
    /// True when the answer came from the cache instead of a fresh resolution.
    pub cached: bool,
}

impl StageB {
    pub fn version(&self) -> String {
        crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel)
    }

    /// Rebuild an answer from its cache row. The `cached` flag is ours to set:
    /// the row says nothing about how this call got its answer (§6 M-6).
    fn from_cache(row: StageBCacheRow) -> Self {
        StageB {
            epoch: row.epoch,
            pkgver: row.pkgver,
            pkgrel: row.pkgrel,
            pins: row.pins,
            cached: true,
        }
    }

    /// The row this answer occupies in `stage_b_cache`.
    fn as_row(&self) -> StageBCacheRow {
        StageBCacheRow {
            epoch: self.epoch.clone(),
            pkgver: self.pkgver.clone(),
            pkgrel: self.pkgrel.clone(),
            pins: self.pins.clone(),
        }
    }
}

/// A process-wide cap on concurrent Stage B resolutions (§5.2 "a global
/// concurrency cap"). Each one clones repositories and runs a chroot-less
/// makepkg; letting twenty run at once would be silly.
static RUNNING: AtomicUsize = AtomicUsize::new(0);
static SLOT_FREE: Condvar = Condvar::new();
static SLOT_LOCK: Mutex<()> = Mutex::new(());

pub struct StageBSlot(());

impl StageBSlot {
    /// Take a Stage B slot, blocking until one is free.
    pub fn acquire(cap: usize) -> Self {
        let cap = cap.max(1);
        let guard = SLOT_LOCK.lock().unwrap_or_else(|e| e.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(|e| e.into_inner());
        }
    }
}

impl Drop for StageBSlot {
    fn drop(&mut self) {
        RUNNING.fetch_sub(1, Ordering::SeqCst);
        SLOT_FREE.notify_one();
    }
}

/// Stage B: resolve the real `pkgver` for a VCS pkgbase.
///
/// `None` means "there is nothing to resolve" — the recipe has no VCS sources,
/// so the literal `pkgver=` is already the answer.
pub fn resolve(
    cfg: &Config,
    db: &Db,
    pb: &Pkgbase,
    recipe: &Recipe,
    recipe_hash: &str,
    stage_a: &StageA,
) -> Result<Option<StageB>> {
    if !recipe.source_entries.iter().any(|e| e.is_vcs()) {
        return Ok(None);
    }
    let tip_hash = tip_hash(&stage_a.pins);

    // Cache hit: same recipe, same upstream tips. Keyed on
    // (pkgbase, recipe_hash, upstream_tip) exactly as §5.2 asks.
    if let Some(hit) = db::stage_b_cache_get(db, pb.id, recipe_hash, &tip_hash)? {
        return Ok(Some(StageB::from_cache(hit)));
    }

    // Per-pkgbase cooldown: even if the tips moved again, we do not re-resolve
    // the same pkgbase more than once per cooldown window. The previous answer
    // is reused, so a chatty upstream cannot turn detection into a build loop.
    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))
}

/// The actual work: warm the clone cache, then ask `makepkg` what it computes.
fn run(
    cfg: &Config,
    pb: &Pkgbase,
    recipe: &Recipe,
    recipe_hash: &str,
    tip_hash: &str,
    stage_a: &StageA,
) -> Result<StageB> {
    // Clone reuse: fetch into a persistent bare cache rather than re-cloning a
    // multi-gigabyte upstream every day (§5.2).
    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() {
            git::clone_bare(&pin.url, &cache)
                .map_err(|e| Error::transient(format!("vcs_cache clone {}: {e}", pin.url)))?;
        } else {
            let _ = git::fetch_and_head(&cache);
        }
        // The clone is here anyway, so confirm the tip locally: that also proves
        // the commit we probed actually exists and is reachable.
        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));
            }
        }
    }

    // Run `makepkg --vercheck` against the recipe in a scratch directory. The
    // real tool clones the sources itself; the shim reports the fixture value.
    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,
        cached: false,
    })
}

fn default_branch(cache: &std::path::Path) -> Option<String> {
    git::git(Some(cache), &["symbolic-ref", "--short", "HEAD"])
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
}

/// A stable hash of the upstream tip set — the cache key's third component.
pub fn tip_hash(pins: &[UpstreamPin]) -> String {
    let mut v: Vec<String> = 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())]))
}