Skip to main content

sovereign_update/
fetch.rs

1//! What is published: the latest release, the green nightly, and ancestry.
2//!
3//! Parsing is pure (`release_candidate`, `nightly_candidate`, `ancestry_of`);
4//! only [`Net`] touches the network, so tests hand in a fake.
5
6use crate::decide::{Ancestry, Candidate, Source};
7use crate::Product;
8use serde_json::Value;
9
10/// One HTTP GET. `Ok(None)` is a 404; every other failure is `Err`.
11pub trait Net {
12    fn get(&self, url: &str) -> Result<Option<Vec<u8>>, String>;
13}
14
15/// The real network: ureq with a hard timeout.
16pub struct Http {
17    agent: ureq::Agent,
18}
19
20impl Http {
21    #[must_use]
22    pub fn new(timeout: std::time::Duration, user_agent: &str) -> Self {
23        let agent = ureq::AgentBuilder::new()
24            .timeout(timeout)
25            .user_agent(user_agent)
26            .build();
27        Self { agent }
28    }
29}
30
31impl Net for Http {
32    fn get(&self, url: &str) -> Result<Option<Vec<u8>>, String> {
33        match self.agent.get(url).call() {
34            Ok(r) => {
35                let mut buf = Vec::new();
36                std::io::Read::read_to_end(&mut r.into_reader(), &mut buf)
37                    .map_err(|e| format!("{url}: {e}"))?;
38                Ok(Some(buf))
39            }
40            Err(ureq::Error::Status(404, _)) => Ok(None),
41            Err(e) => Err(format!("{url}: {e}")),
42        }
43    }
44}
45
46fn json(bytes: &[u8]) -> Option<Value> {
47    serde_json::from_slice(bytes).ok()
48}
49
50/// Fill `{bin}`, `{tag}`, `{version}` and `{target}` in an asset template.
51#[must_use]
52pub fn asset_name(template: &str, bin: &str, tag: &str, target: &str) -> String {
53    template
54        .replace("{bin}", bin)
55        .replace("{tag}", tag)
56        .replace("{version}", tag.trim_start_matches('v'))
57        .replace("{target}", target)
58}
59
60/// A release's asset for this product and target, if it has one. A release
61/// without this bin's asset is no candidate: never announce a build that
62/// `update` could not install.
63#[must_use]
64pub fn release_candidate(body: &[u8], p: &Product, target: &str) -> Option<Candidate> {
65    candidate_of(&json(body)?, p, target)
66}
67
68/// The line a release manager writes into an `-rc` prerelease's notes once
69/// the hand-smoke passed. Until it is there the prerelease is not installable.
70pub const HAND_SMOKE_MARKER: &str = "Hand-smoke: PASS";
71
72fn hand_smoked(v: &Value) -> bool {
73    v.get("body").and_then(Value::as_str).is_some_and(|b| {
74        b.lines().any(|l| {
75            l.trim_start_matches(|c: char| c == '#' || c == '*' || c == '-' || c.is_whitespace())
76                .starts_with(HAND_SMOKE_MARKER)
77        })
78    })
79}
80
81/// Whether a `/releases` entry may be installed: not a draft, a semver tag
82/// (the rolling `nightly` release is a prerelease with no version — it comes
83/// in through its manifest instead), and a prerelease only once hand-smoked.
84/// Every intermediate release is dogfooded (operator, 2026-09-24: "we use all
85/// intermediate releases for dogfood").
86fn eligible(v: &Value) -> bool {
87    let flag = |k: &str| v.get(k).and_then(Value::as_bool);
88    let Some(tag) = v.get("tag_name").and_then(Value::as_str) else {
89        return false;
90    };
91    if flag("draft") != Some(false) || semver::Version::parse(tag.trim_start_matches('v')).is_err()
92    {
93        return false;
94    }
95    match flag("prerelease") {
96        Some(false) => true,
97        Some(true) => hand_smoked(v),
98        None => false,
99    }
100}
101
102/// The highest-versioned eligible release in a `/releases` list that carries
103/// this target's asset. Semver orders `0.69.1 < 0.69.3-rc.1 < 0.69.3`, so a
104/// hand-smoked rc supersedes the last release and the final tag supersedes it.
105#[must_use]
106pub fn newest_release_candidate(body: &[u8], p: &Product, target: &str) -> Option<Candidate> {
107    json(body)?
108        .as_array()?
109        .iter()
110        .filter(|v| eligible(v))
111        .filter_map(|v| candidate_of(v, p, target))
112        .filter_map(|c| Some((semver::Version::parse(&c.version).ok()?, c)))
113        .max_by(|a, b| a.0.cmp(&b.0))
114        .map(|(_, c)| c)
115}
116
117fn candidate_of(v: &Value, p: &Product, target: &str) -> Option<Candidate> {
118    let tag = v.get("tag_name")?.as_str()?;
119    let want = asset_name(p.release_asset?, p.bin, tag, target);
120    let url = v
121        .get("assets")?
122        .as_array()?
123        .iter()
124        .find(|a| a.get("name").and_then(Value::as_str) == Some(want.as_str()))?
125        .get("browser_download_url")?
126        .as_str()?;
127    Some(Candidate {
128        source: Source::Release,
129        version: tag.trim_start_matches('v').to_string(),
130        git_ref: tag.to_string(),
131        asset_url: url.to_string(),
132        sha256: None,
133        bin_sha256: None,
134    })
135}
136
137/// First whitespace-separated token of a `--version` line that is a semver.
138fn version_in(line: &str) -> Option<String> {
139    line.split_whitespace()
140        .map(|t| t.trim_matches(|c: char| c == '(' || c == ')' || c == ','))
141        .find(|t| semver::Version::parse(t.trim_start_matches('v')).is_ok())
142        .map(|t| t.trim_start_matches('v').to_string())
143}
144
145/// This target's tool entry in an `aprender-nightly-manifest/v1` (#4189), if
146/// the target is green and carries both digests.
147#[must_use]
148pub fn nightly_candidate(body: &[u8], p: &Product, target: &str) -> Option<Candidate> {
149    let v = json(body)?;
150    if v.get("schema")?.as_str()? != "aprender-nightly-manifest/v1" {
151        return None;
152    }
153    let t = v.get("targets")?.get(target)?;
154    if t.get("status")?.as_str()? != "green" {
155        return None;
156    }
157    let tool = t.get("tools")?.get(p.bin)?;
158    let s = |k: &str| tool.get(k).and_then(Value::as_str).map(str::to_string);
159    let asset = s("asset")?;
160    Some(Candidate {
161        source: Source::Nightly,
162        version: version_in(&s("version_output")?)?,
163        git_ref: t.get("green_sha")?.as_str()?.to_string(),
164        asset_url: format!(
165            "https://github.com/{}/releases/download/nightly/{asset}",
166            p.repo
167        ),
168        sha256: Some(s("sha256")?),
169        bin_sha256: Some(s("bin_sha256")?),
170    })
171}
172
173/// The `status` field of a GitHub compare response.
174#[must_use]
175pub fn ancestry_of(body: &[u8]) -> Option<Ancestry> {
176    match json(body)?.get("status")?.as_str()? {
177        "ahead" => Some(Ancestry::Ahead),
178        "behind" => Some(Ancestry::Behind),
179        "identical" => Some(Ancestry::Identical),
180        "diverged" => Some(Ancestry::Diverged),
181        _ => None,
182    }
183}
184
185pub fn latest_release(
186    net: &dyn Net,
187    p: &Product,
188    target: &str,
189) -> Result<Option<Candidate>, String> {
190    if p.release_asset.is_none() {
191        return Ok(None);
192    }
193    // Not /releases/latest: GitHub leaves every prerelease out of it, and a
194    // hand-smoked -rc is installable.
195    let url = format!(
196        "https://api.github.com/repos/{}/releases?per_page=30",
197        p.repo
198    );
199    Ok(net
200        .get(&url)?
201        .and_then(|b| newest_release_candidate(&b, p, target)))
202}
203
204pub fn nightly(net: &dyn Net, p: &Product, target: &str) -> Result<Option<Candidate>, String> {
205    if !p.nightly {
206        return Ok(None);
207    }
208    let url = format!(
209        "https://github.com/{}/releases/download/nightly/nightly-manifest.json",
210        p.repo
211    );
212    Ok(net
213        .get(&url)?
214        .and_then(|b| nightly_candidate(&b, p, target)))
215}
216
217/// Ancestry by the compare API; any failure is `None` (unknown), which the
218/// decision treats conservatively.
219pub fn ancestry(net: &dyn Net, repo: &str, base: &str, head: &str) -> Option<Ancestry> {
220    let url = format!("https://api.github.com/repos/{repo}/compare/{base}...{head}");
221    net.get(&url).ok().flatten().and_then(|b| ancestry_of(&b))
222}
223
224#[cfg(test)]
225#[allow(clippy::disallowed_methods)] // serde_json::json! expands to Result::unwrap
226mod tests {
227    use super::*;
228
229    const P: Product = Product {
230        bin: "apr",
231        repo: "paiml/aprender",
232        version: "0.69.0",
233        build_sha: None,
234        release_asset: Some("{bin}-{tag}-{target}-cpu.tar.gz"),
235        nightly: true,
236    };
237    const T: &str = "x86_64-unknown-linux-gnu";
238
239    fn release_json(assets: &[&str]) -> Vec<u8> {
240        let a: Vec<Value> = assets
241            .iter()
242            .map(|n| serde_json::json!({"name": n, "browser_download_url": format!("https://dl/{n}")}))
243            .collect();
244        serde_json::to_vec(&serde_json::json!({"tag_name": "v0.69.1", "assets": a})).expect("json")
245    }
246
247    #[test]
248    fn release_candidate_rows() {
249        let c = release_candidate(
250            &release_json(&["apr-v0.69.1-x86_64-unknown-linux-gnu-cpu.tar.gz"]),
251            &P,
252            T,
253        )
254        .expect("asset for this target is a candidate");
255        assert_eq!(
256            (c.version.as_str(), c.git_ref.as_str()),
257            ("0.69.1", "v0.69.1")
258        );
259        assert_eq!(
260            c.asset_url,
261            "https://dl/apr-v0.69.1-x86_64-unknown-linux-gnu-cpu.tar.gz"
262        );
263        assert!(
264            release_candidate(
265                &release_json(&["apr-v0.69.1-aarch64-unknown-linux-gnu-cpu.tar.gz"]),
266                &P,
267                T
268            )
269            .is_none(),
270            "a release without THIS target's asset is no candidate"
271        );
272        assert!(release_candidate(b"not json", &P, T).is_none());
273        let no_release = Product {
274            release_asset: None,
275            ..P
276        };
277        assert!(release_candidate(&release_json(&["x"]), &no_release, T).is_none());
278    }
279
280    /// One `/releases` entry: (tag, prerelease, draft, body, has this target's asset).
281    fn rel(tag: &str, pre: bool, draft: bool, body: &str, asset: bool) -> Value {
282        let name = format!("apr-{tag}-{T}-cpu.tar.gz");
283        let assets = if asset {
284            vec![
285                serde_json::json!({"name": name, "browser_download_url": format!("https://dl/{name}")}),
286            ]
287        } else {
288            vec![]
289        };
290        serde_json::json!({"tag_name": tag, "prerelease": pre, "draft": draft, "body": body, "assets": assets})
291    }
292
293    fn newest(list: &[Value]) -> Option<String> {
294        let body = serde_json::to_vec(&Value::Array(list.to_vec())).expect("json");
295        newest_release_candidate(&body, &P, T).map(|c| c.git_ref)
296    }
297
298    /// Every intermediate release is dogfooded; an -rc only once hand-smoked.
299    #[test]
300    fn newest_release_candidate_case_table() {
301        let smoked =
302            "Pre-release of 0.69.3.\n\n## Hand-smoke: PASS on lambda-labs (apr serve, qwen3.5)\n";
303        let bullet = "notes\n- **Hand-smoke: PASS** 2026-09-24\n";
304        let unsmoked = "Pre-release of 0.69.3. Use it to dogfood today.";
305        let r0691 = rel("v0.69.1", false, false, "", true);
306        let nightly = rel("nightly", true, false, smoked, true);
307        let rows: Vec<(&str, Vec<Value>, Option<&str>)> = vec![
308            ("R1 release only", vec![r0691.clone()], Some("v0.69.1")),
309            (
310                "R2 rc WITHOUT hand-smoke is not installable",
311                vec![
312                    rel("v0.69.3-rc.1", true, false, unsmoked, true),
313                    r0691.clone(),
314                ],
315                Some("v0.69.1"),
316            ),
317            (
318                "R3 hand-smoked rc supersedes the release",
319                vec![
320                    rel("v0.69.3-rc.1", true, false, smoked, true),
321                    r0691.clone(),
322                ],
323                Some("v0.69.3-rc.1"),
324            ),
325            (
326                "R4 marker as a markdown bullet counts",
327                vec![
328                    rel("v0.69.3-rc.1", true, false, bullet, true),
329                    r0691.clone(),
330                ],
331                Some("v0.69.3-rc.1"),
332            ),
333            (
334                "R5 final tag supersedes its rc",
335                vec![
336                    rel("v0.69.3", false, false, "", true),
337                    rel("v0.69.3-rc.2", true, false, smoked, true),
338                    r0691.clone(),
339                ],
340                Some("v0.69.3"),
341            ),
342            (
343                "R6 rc.10 > rc.2 by semver, not by string",
344                vec![
345                    rel("v0.69.3-rc.2", true, false, smoked, true),
346                    rel("v0.69.3-rc.10", true, false, smoked, true),
347                ],
348                Some("v0.69.3-rc.10"),
349            ),
350            (
351                "R7 the rolling nightly release is never a release candidate",
352                vec![nightly.clone(), r0691.clone()],
353                Some("v0.69.1"),
354            ),
355            (
356                "R8 a draft is never installable",
357                vec![rel("v0.69.4", false, true, smoked, true), r0691.clone()],
358                Some("v0.69.1"),
359            ),
360            (
361                "R9 smoked rc without THIS target's asset is skipped",
362                vec![
363                    rel("v0.69.3-rc.1", true, false, smoked, false),
364                    r0691.clone(),
365                ],
366                Some("v0.69.1"),
367            ),
368            (
369                "R10 list order does not matter",
370                vec![
371                    r0691.clone(),
372                    rel("v0.69.3-rc.1", true, false, smoked, true),
373                ],
374                Some("v0.69.3-rc.1"),
375            ),
376            (
377                "R11 marker mid-sentence is not a hand-smoke",
378                vec![
379                    rel(
380                        "v0.69.3-rc.1",
381                        true,
382                        false,
383                        "hand-smoke pending; not Hand-smoke: PASS yet",
384                        true,
385                    ),
386                    r0691.clone(),
387                ],
388                Some("v0.69.1"),
389            ),
390            (
391                "R13 a Hand-smoke: FAIL line is not installable",
392                vec![
393                    rel(
394                        "v0.69.3-rc.1",
395                        true,
396                        false,
397                        "Hand-smoke: FAIL apr-v0.69.3-rc.1-x86_64-unknown-linux-gnu-cuda.tar.gz used_gpu=false",
398                        true,
399                    ),
400                    r0691.clone(),
401                ],
402                Some("v0.69.1"),
403            ),
404            (
405                "R14 the line the release driver writes (aprender-36's format)",
406                vec![
407                    rel(
408                        "v0.69.3-rc.1",
409                        true,
410                        false,
411                        "Pre-release.\nHand-smoke: PASS apr-v0.69.3-rc.1-x86_64-unknown-linux-gnu-cuda.tar.gz sha256=ab12 version=apr 0.69.3-rc.1 commit=7ff50ec2a==tag used_gpu=true\n",
412                        true,
413                    ),
414                    r0691.clone(),
415                ],
416                Some("v0.69.3-rc.1"),
417            ),
418            (
419                "R12 nothing eligible",
420                vec![nightly, rel("v0.69.3-rc.1", true, false, unsmoked, true)],
421                None,
422            ),
423        ];
424        for (name, list, want) in rows {
425            assert_eq!(newest(&list).as_deref(), want, "{name}");
426        }
427        assert!(
428            newest_release_candidate(b"{\"tag_name\":\"v1.0.0\"}", &P, T).is_none(),
429            "an object is not a /releases list"
430        );
431    }
432
433    fn manifest(status: &str, schema: &str) -> Vec<u8> {
434        serde_json::to_vec(&serde_json::json!({
435            "schema": schema,
436            "targets": {T: {"status": status, "green_sha": "abc123",
437                "tools": {"apr": {"asset": "apr-x86_64-unknown-linux-gnu.tar.gz", "sha256": "aa",
438                    "bin_sha256": "bb", "version_output": "apr 0.69.1 (abc1234)"}}}}
439        }))
440        .expect("json")
441    }
442
443    #[test]
444    fn nightly_candidate_rows() {
445        let c = nightly_candidate(&manifest("green", "aprender-nightly-manifest/v1"), &P, T)
446            .expect("green");
447        assert_eq!(
448            (
449                c.version.as_str(),
450                c.git_ref.as_str(),
451                c.sha256.as_deref(),
452                c.bin_sha256.as_deref()
453            ),
454            ("0.69.1", "abc123", Some("aa"), Some("bb"))
455        );
456        assert_eq!(c.asset_url, "https://github.com/paiml/aprender/releases/download/nightly/apr-x86_64-unknown-linux-gnu.tar.gz");
457        assert!(
458            nightly_candidate(&manifest("red", "aprender-nightly-manifest/v1"), &P, T).is_none(),
459            "red target"
460        );
461        assert!(
462            nightly_candidate(&manifest("green", "v2"), &P, T).is_none(),
463            "unknown schema"
464        );
465        assert!(nightly_candidate(
466            &manifest("green", "aprender-nightly-manifest/v1"),
467            &P,
468            "riscv64"
469        )
470        .is_none());
471        let pv = Product { bin: "pv", ..P };
472        assert!(
473            nightly_candidate(&manifest("green", "aprender-nightly-manifest/v1"), &pv, T).is_none(),
474            "bin absent"
475        );
476    }
477
478    #[test]
479    fn version_and_ancestry_parsing() {
480        assert_eq!(
481            version_in("pv 0.69.0 (aprender provable-contracts verifier)").as_deref(),
482            Some("0.69.0")
483        );
484        assert_eq!(
485            version_in("apr v0.69.1+no-git").as_deref(),
486            Some("0.69.1+no-git")
487        );
488        assert_eq!(version_in("nothing here"), None);
489        for (s, a) in [
490            ("ahead", Some(Ancestry::Ahead)),
491            ("behind", Some(Ancestry::Behind)),
492            ("identical", Some(Ancestry::Identical)),
493            ("diverged", Some(Ancestry::Diverged)),
494            ("weird", None),
495        ] {
496            assert_eq!(
497                ancestry_of(format!("{{\"status\":\"{s}\"}}").as_bytes()),
498                a,
499                "{s}"
500            );
501        }
502        assert_eq!(
503            asset_name("{bin}-{tag}-{target}.tar.gz", "pv", "v1.2.3", "t"),
504            "pv-v1.2.3-t.tar.gz"
505        );
506        assert_eq!(
507            asset_name("{bin}-{version}.zip", "pv", "v1.2.3", "t"),
508            "pv-1.2.3.zip"
509        );
510    }
511}