Skip to main content

rbnx/cmd/
check_remotes.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2//! Remote-provider freshness check.
3//!
4//! Deploy manifests pull some providers from a git `url:` into
5//! `rbnx-boot/cache/<name>/`. Once cloned, that checkout is reused on every
6//! boot/build and never advances on its own — so a teammate can be running
7//! a stale copy of an upstream package without noticing. This module compares
8//! each cloned provider against its remote branch tip and reports how far
9//! behind it is.
10//!
11//! `rbnx boot` and `rbnx build` call [`report_outdated`] (print-only, never
12//! fatal — a missing network must not block a deploy). `rbnx update` calls
13//! [`collect_remote_providers`] + [`status_of`] to act on the same data.
14
15use anyhow::{Context, Result};
16use std::path::{Path, PathBuf};
17use std::process::Command;
18
19use robonix_cli::output;
20
21/// A remote-backed provider declared in a deploy manifest.
22#[derive(Debug, Clone)]
23pub struct RemoteProvider {
24    pub name: String,
25    /// Manifest section: `primitive`, `service` or `skill`.
26    pub kind: &'static str,
27    pub url: String,
28    pub branch: Option<String>,
29    /// Local cache checkout (`rbnx-boot/cache/<name>`); may not exist yet.
30    pub dir: PathBuf,
31}
32
33/// How a local checkout compares to its remote branch tip.
34#[derive(Debug, Clone)]
35pub struct RemoteStatus {
36    pub name: String,
37    pub dir: PathBuf,
38    /// Commits the local checkout is behind the remote tip. `None` when the
39    /// count could not be determined (e.g. shallow history, fetch failed).
40    pub behind: Option<u32>,
41    pub local_sha: String,
42    pub remote_sha: String,
43    pub remote_date: String,
44    pub remote_subject: String,
45    /// Non-fatal explanation when the check is incomplete.
46    pub note: Option<String>,
47}
48
49impl RemoteStatus {
50    /// True when the remote tip differs from the local HEAD (i.e. an update
51    /// is available). Behind-count may be unknown but still outdated.
52    pub fn outdated(&self) -> bool {
53        self.behind.map(|b| b > 0).unwrap_or(false)
54            || (!self.remote_sha.is_empty() && self.remote_sha != self.local_sha)
55    }
56}
57
58/// Run a git command in `dir`, returning trimmed stdout on success.
59fn git(dir: &Path, args: &[&str]) -> Option<String> {
60    let out = Command::new("git")
61        .arg("-C")
62        .arg(dir)
63        .args(args)
64        .output()
65        .ok()?;
66    if !out.status.success() {
67        return None;
68    }
69    let s = String::from_utf8(out.stdout).ok()?.trim().to_string();
70    Some(s)
71}
72
73fn origin_url(dir: &Path) -> Option<String> {
74    git(dir, &["config", "--get", "remote.origin.url"]).filter(|s| !s.trim().is_empty())
75}
76
77/// Parse a deploy manifest and list its `url:` providers (cloned or not).
78pub fn collect_remote_providers(manifest_path: &Path) -> Result<Vec<RemoteProvider>> {
79    let raw = std::fs::read_to_string(manifest_path)
80        .with_context(|| format!("read deploy manifest {}", manifest_path.display()))?;
81    let doc: serde_yaml::Value = serde_yaml::from_str(&raw)
82        .with_context(|| format!("parse deploy manifest {}", manifest_path.display()))?;
83
84    let manifest_dir = manifest_path.parent().unwrap_or_else(|| Path::new("."));
85    let cache_root = manifest_dir.join("rbnx-boot").join("cache");
86
87    let mut providers = Vec::new();
88    for section in ["primitive", "service", "skill"] {
89        let Some(entries) = doc.get(section).and_then(|v| v.as_sequence()) else {
90            continue;
91        };
92        for entry in entries {
93            // A disabled provider is neither cloned nor updated.
94            if entry.get("status").and_then(|v| v.as_str()) == Some("disabled") {
95                continue;
96            }
97            let Some(url) = entry.get("url").and_then(|v| v.as_str()) else {
98                continue; // local `path:` provider — nothing to track
99            };
100            let name = entry
101                .get("name")
102                .and_then(|v| v.as_str())
103                .map(|s| s.to_string())
104                .filter(|s| !s.is_empty())
105                .unwrap_or_else(|| {
106                    url.trim_end_matches(".git")
107                        .rsplit('/')
108                        .next()
109                        .unwrap_or("pkg")
110                        .to_string()
111                });
112            let branch = entry
113                .get("branch")
114                .and_then(|v| v.as_str())
115                .map(|s| s.to_string());
116            providers.push(RemoteProvider {
117                // Cache dir = git repo name (one clone per repo), not the
118                // per-instance provider id. See deploy::repo_dir_name.
119                dir: cache_root.join(super::deploy::repo_dir_name(url)),
120                name,
121                kind: section,
122                url: url.to_string(),
123                branch,
124            });
125        }
126    }
127    Ok(providers)
128}
129
130/// Resolve the branch to compare against — the manifest's `branch:` or the
131/// remote's default branch (`origin/HEAD`).
132fn target_branch(p: &RemoteProvider) -> String {
133    if let Some(b) = &p.branch {
134        return b.clone();
135    }
136    git(&p.dir, &["rev-parse", "--abbrev-ref", "origin/HEAD"])
137        .and_then(|s| s.rsplit('/').next().map(|s| s.to_string()))
138        .unwrap_or_else(|| "main".to_string())
139}
140
141/// Fetch the remote branch and compare it to the local checkout. Best-effort:
142/// network / shallow-history problems surface as a `note`, not an error.
143pub fn status_of(p: &RemoteProvider) -> RemoteStatus {
144    let mut st = RemoteStatus {
145        name: p.name.clone(),
146        dir: p.dir.clone(),
147        behind: None,
148        local_sha: String::new(),
149        remote_sha: String::new(),
150        remote_date: String::new(),
151        remote_subject: String::new(),
152        note: None,
153    };
154
155    if !p.dir.join(".git").is_dir() {
156        st.note = Some("not cloned yet (will clone on next boot/build)".into());
157        return st;
158    }
159
160    st.local_sha = git(&p.dir, &["rev-parse", "HEAD"]).unwrap_or_default();
161    if origin_url(&p.dir).is_none() {
162        st.note = Some("local checkout has no origin remote — skipped".into());
163        return st;
164    }
165    let branch = target_branch(p);
166
167    // Deepen the fetch so HEAD..origin/branch is computable even on the
168    // --depth 1 clones boot creates. 200 covers any realistic drift.
169    //
170    // HARD time bound: this freshness check is a best-effort, non-fatal
171    // notice, but a plain `git fetch` against an unreachable/slow remote
172    // can block on TCP connect for ~130s — and since boot/build call this
173    // for EVERY url-provider, an offline or throttled github stalls the
174    // whole boot before atlas even starts. Wrap in `timeout(1)` so a
175    // wedged fetch is abandoned in seconds and the check just reports
176    // "skipped". `http.lowSpeedLimit/Time` additionally kills a transfer
177    // that connects but then stalls mid-stream. If the `timeout` binary
178    // isn't present (e.g. non-coreutils host), fall back to a bare fetch.
179    // Through the GitHub mirror first when there is one, as clone does.
180    let sources = origin_url(&p.dir)
181        .map(|url| super::run_package::url_candidates(&url))
182        .unwrap_or_else(|| vec!["origin".into()]);
183    let fetch = |source: &str| {
184        let fetch_args = [
185            "-C",
186            p.dir.to_str().unwrap_or("."),
187            "-c",
188            "http.lowSpeedLimit=1000",
189            "-c",
190            "http.lowSpeedTime=8",
191            "fetch",
192            "--quiet",
193            "--depth",
194            "200",
195            source,
196            &branch,
197        ];
198        // Keep this short: the freshness notice is cosmetic and must never
199        // noticeably delay boot. 6s is plenty for a reachable remote; an
200        // unreachable one fails fast and the check is skipped.
201        let timed = Command::new("timeout")
202            .arg("6")
203            .arg("git")
204            .args(fetch_args)
205            .status();
206        match timed {
207            Ok(s) => s.success(),
208            // `timeout` unavailable — fall back to a direct fetch.
209            Err(_) => Command::new("git")
210                .args(fetch_args)
211                .status()
212                .map(|s| s.success())
213                .unwrap_or(false),
214        }
215    };
216    let fetched = sources.iter().any(|source| fetch(source));
217    if !fetched {
218        st.note = Some("git fetch timed out / failed (offline?) — skipped".into());
219        return st;
220    }
221
222    let remote_ref = "FETCH_HEAD";
223    st.remote_sha = git(&p.dir, &["rev-parse", remote_ref]).unwrap_or_default();
224    st.remote_date = git(
225        &p.dir,
226        &["log", "-1", "--format=%cd", "--date=relative", remote_ref],
227    )
228    .unwrap_or_default();
229    st.remote_subject = git(&p.dir, &["log", "-1", "--format=%s", remote_ref]).unwrap_or_default();
230    st.behind = git(
231        &p.dir,
232        &["rev-list", "--count", &format!("HEAD..{remote_ref}")],
233    )
234    .and_then(|s| s.parse::<u32>().ok());
235    st
236}
237
238/// boot/build hook: print a one-line notice for every outdated remote provider
239/// plus how to update. Never fails the caller.
240pub fn report_outdated(manifest_path: &Path) {
241    let providers = match collect_remote_providers(manifest_path) {
242        Ok(p) => p,
243        Err(_) => return,
244    };
245    let remote: Vec<_> = providers
246        .into_iter()
247        .filter(|p| p.dir.join(".git").is_dir())
248        .collect();
249    if remote.is_empty() {
250        return;
251    }
252
253    // Each provider triggers a real `git fetch` (up to 6s on a slow/offline
254    // remote), serially. Show an in-place spinner per package while its fetch
255    // runs, then overwrite it with a definite verdict — `[ OK ] up to date`
256    // or `[ ↑ ] N behind …` — so nothing is left dangling on a `…`. Skip the
257    // whole phase with `rbnx boot --no-update-check`.
258    output::boot_section("checking remote providers for updates (skip: --no-update-check)");
259    let mut outdated = Vec::new();
260    for p in &remote {
261        if origin_url(&p.dir).is_none() {
262            let st = status_of(p);
263            output::boot_skip(
264                &p.name,
265                st.note
266                    .as_deref()
267                    .unwrap_or("local checkout has no origin remote — skipped"),
268            );
269            continue;
270        }
271        output::boot_progress(&p.name, "fetching origin…", 0);
272        let st = status_of(p);
273        if st.outdated() {
274            let behind = match st.behind {
275                Some(n) => format!("{n} behind"),
276                None => "behind".to_string(),
277            };
278            output::boot_update_avail(
279                &p.name,
280                &format!(
281                    "{behind}; remote {} ({}): {}",
282                    output::short_sha(&st.remote_sha),
283                    st.remote_date,
284                    st.remote_subject
285                ),
286            );
287            outdated.push(st);
288        } else if let Some(note) = &st.note {
289            // Couldn't determine (offline / shallow / fetch failed) — say so
290            // plainly rather than implying it's up to date.
291            output::boot_skip(&p.name, note);
292        } else {
293            output::boot_ok(&p.name, "up to date");
294        }
295    }
296
297    // Final, unambiguous verdict line.
298    if outdated.is_empty() {
299        output::sub_step(&format!(
300            "{} remote provider(s) up to date — nothing to update",
301            remote.len()
302        ));
303        return;
304    }
305    output::sub_step(&format!(
306        "{} of {} provider(s) have updates available:",
307        outdated.len(),
308        remote.len()
309    ));
310    output::info(&format!(
311        "update all:  rbnx update -f {}",
312        manifest_path.display()
313    ));
314    output::info("update one:  cd <pkg dir> && rbnx update   (or: rbnx update -p <pkg dir>)");
315}
浙ICP备2023005800号-2 浙公网安备33010902005384号