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