Skip to main content

eclipse_core/
update.rs

1//! What an install knows about itself, and the notice that says a newer commit exists.
2//!
3//! Two files live in the state directory, next to the sessions but not in them:
4//!
5//! - `install.json`, written by `install.sh` (never by this crate): which channel the install
6//!   came from, where its binaries and its checkout are, and the commit it was built from.
7//!   `eclipse upgrade` and the notice both read it; neither writes it.
8//! - `update.json`, written here: when the public repository was last asked and what it said.
9//!
10//! The notice is the only request this tool makes that is neither a model call nor something
11//! the user asked for. It is bounded accordingly: at most one `GET` per `[update] check` period,
12//! a 2 s timeout, no credentials, every failure silent, and `check = "off"` makes no request at
13//! all. It also only runs for an install that has an `install.json` with a commit, because
14//! without one there is nothing to compare the answer to.
15//!
16//! The notice and the badge are two readings of one comparison. The notice happens once per
17//! answer (`notified`); the badge is the comparison itself, [`behind`], and lasts as long as the
18//! install is behind — which is why a surface that repaints asks [`Watch`] again instead of
19//! remembering what it was told.
20
21use crate::config::{state_dir, EnvFn, Track, UpdateCheck, UpdateConfig};
22use crate::error::{Error, Result};
23use crate::http::{self, Reach};
24use serde::{Deserialize, Serialize};
25use std::fmt;
26use std::path::{Path, PathBuf};
27use std::time::Duration;
28
29pub const MARKER_FILE: &str = "install.json";
30pub const CACHE_FILE: &str = "update.json";
31
32/// The public repository's latest commit on `main`, which is the branch releases are cut from.
33/// GitHub answers with the bare id when asked for `application/vnd.github.sha`, and with a JSON
34/// object carrying `sha` otherwise; both are understood so `[update] remote` can point at either
35/// kind of server.
36pub const DEFAULT_LATEST_URL: &str = "https://api.github.com/repos/mmhorda/eclipse/commits/main";
37
38/// The same question about `develop`, for a source install that follows that track
39/// (`[update] track = "develop"`): the commits that are coming, not the ones that were released.
40pub const DEVELOP_LATEST_URL: &str = "https://api.github.com/repos/mmhorda/eclipse/commits/develop";
41
42/// The commit question for a track: the branch the track names, unless the user pointed
43/// `[update] remote` somewhere of their own — an explicit URL is the escape hatch, and a track
44/// must not quietly reroute it.
45fn latest_question(cfg: &UpdateConfig) -> (&str, Reach) {
46    match cfg.remote.as_deref() {
47        Some(remote) => (remote, Reach::Anywhere),
48        None => match cfg.track {
49            Track::Release => (DEFAULT_LATEST_URL, Reach::Public),
50            Track::Develop => (DEVELOP_LATEST_URL, Reach::Public),
51        },
52    }
53}
54
55/// The newest release. A `release` install compares a tag with a version, not a commit with a
56/// commit, so it asks a different question; the answer carries the tag and the asset URLs that
57/// `eclipse upgrade` downloads from, which is why a mirror can stand in for GitHub here too.
58pub const DEFAULT_RELEASES_URL: &str =
59    "https://api.github.com/repos/mmhorda/eclipse/releases/latest";
60
61/// The one asset a Linux install can use. Named rather than guessed from `uname`: a release with
62/// no matching asset is a refusal that lists what the release does carry.
63pub const TARBALL_SUFFIX: &str = "-x86_64-unknown-linux-gnu.tar.gz";
64
65/// The asset that says which bytes the tarball should be.
66pub const SUMS_NAME: &str = "SHA256SUMS";
67
68/// A release answer is a tag, a page and a handful of assets; a body larger than this is
69/// something else.
70const MAX_RELEASE_BYTES: usize = 64 * 1024;
71
72/// Asking for a release is two round trips' worth of latency on a bad day, not a 2 s notice.
73pub const RELEASE_TIMEOUT: Duration = Duration::from_secs(20);
74
75/// The whole budget for one check: name resolution, connect, and reading the answer.
76pub const CHECK_TIMEOUT: Duration = Duration::from_secs(2);
77
78/// An answer longer than this is not a commit id; reading stops here.
79const MAX_ANSWER_BYTES: usize = 8 * 1024;
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
82#[serde(rename_all = "lowercase")]
83pub enum Channel {
84    /// Built from a checkout by `install.sh`. Upgraded by `git pull` and a rebuild.
85    Source,
86    /// Installed from an unpacked release tarball. Upgraded by downloading the next tag's
87    /// tarball and swapping the binaries in place.
88    Release,
89}
90
91impl Channel {
92    pub fn label(self) -> &'static str {
93        match self {
94            Channel::Source => "source",
95            Channel::Release => "release",
96        }
97    }
98}
99
100/// A release version: three numbers, no pre-release. The workflow refuses a tag that disagrees
101/// with `Cargo.toml`, and `Cargo.toml` carries no pre-release, so a fourth field would be a
102/// parser nobody can reach from a real release.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
104pub struct Version {
105    pub major: u64,
106    pub minor: u64,
107    pub patch: u64,
108}
109
110impl Version {
111    /// `v0.2.1` or `0.2.1`; anything else is `None` rather than a guess.
112    pub fn parse(text: &str) -> Option<Version> {
113        let text = text.trim();
114        let text = text.strip_prefix('v').unwrap_or(text);
115        let mut parts = text.split('.');
116        let major = parts.next()?.parse().ok()?;
117        let minor = parts.next()?.parse().ok()?;
118        // A suffix on the last number is dropped: it is not part of what orders two releases,
119        // and no tag that survives the release workflow carries one.
120        let patch = parts.next()?.split(['-', '+']).next()?.parse().ok()?;
121        if parts.next().is_some() {
122            return None;
123        }
124        Some(Version {
125            major,
126            minor,
127            patch,
128        })
129    }
130}
131
132impl fmt::Display for Version {
133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
135    }
136}
137
138/// One release, as the API describes it: enough to fetch and verify the one asset this machine
139/// can use, and nothing else.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct Release {
142    /// The tag, `v` included, because that is how the release is named.
143    pub tag: String,
144    pub version: Version,
145    pub tarball_url: String,
146    pub tarball_name: String,
147    pub sums_url: String,
148    /// The release page, for a message that has to say what a major jump contains.
149    pub page: Option<String>,
150}
151
152/// Read a release answer. The assets are the API's, not a URL built from a template: a tag can
153/// be republished, an asset name can change with the platform rule, and a mirror answers the
154/// same shape with its own URLs.
155pub fn parse_release(body: &str) -> std::result::Result<Release, String> {
156    let value: serde_json::Value =
157        serde_json::from_str(body).map_err(|e| format!("not a release object: {e}"))?;
158    let tag = value
159        .get("tag_name")
160        .and_then(|v| v.as_str())
161        .ok_or("the answer carries no tag_name")?
162        .trim()
163        .to_string();
164    let version =
165        Version::parse(&tag).ok_or_else(|| format!("tag {tag:?} is not vMAJOR.MINOR.PATCH"))?;
166    let assets = value
167        .get("assets")
168        .and_then(|v| v.as_array())
169        .ok_or("the answer carries no assets")?;
170    let find = |want: &dyn Fn(&str) -> bool| -> Option<(String, String)> {
171        assets.iter().find_map(|a| {
172            let name = a.get("name")?.as_str()?;
173            if !want(name) {
174                return None;
175            }
176            let url = a.get("browser_download_url")?.as_str()?.to_string();
177            Some((name.to_string(), url))
178        })
179    };
180    let (tarball_name, tarball_url) = find(&|n| n.ends_with(TARBALL_SUFFIX)).ok_or_else(|| {
181        format!(
182            "{tag} has no {TARBALL_SUFFIX} asset (it carries: {})",
183            asset_names(assets)
184        )
185    })?;
186    let sums_url = find(&|n| n == SUMS_NAME)
187        .map(|(_, url)| url)
188        .ok_or_else(|| {
189            format!("{tag} has no {SUMS_NAME} asset, so a download could not be checked")
190        })?;
191    Ok(Release {
192        tag,
193        version,
194        tarball_url,
195        tarball_name,
196        sums_url,
197        page: value
198            .get("html_url")
199            .and_then(|v| v.as_str())
200            .map(str::to_string),
201    })
202}
203
204fn asset_names(assets: &[serde_json::Value]) -> String {
205    let names: Vec<&str> = assets
206        .iter()
207        .filter_map(|a| a.get("name").and_then(|n| n.as_str()))
208        .collect();
209    if names.is_empty() {
210        "nothing".to_string()
211    } else {
212        names.join(", ")
213    }
214}
215
216/// `<state>/install.json`: what `install.sh` recorded.
217#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
218pub struct InstallMarker {
219    pub channel: Channel,
220    /// Where the binaries live: `<prefix>/bin/eclipse`.
221    pub prefix: PathBuf,
222    /// The checkout that was built. Recorded rather than derived from `prefix`, because the
223    /// two have nothing to do with each other: `--prefix /usr/local` says where the binaries
224    /// went, not where the sources are. `None` for a release install, which has no checkout.
225    #[serde(default)]
226    pub workspace: Option<PathBuf>,
227    /// `git rev-parse HEAD` of the checkout at install time; `None` for an install that had no
228    /// git checkout, such as an unpacked tarball.
229    #[serde(default)]
230    pub commit: Option<String>,
231    /// RFC 3339, UTC.
232    pub installed_at: String,
233    /// `release` or `debug`: which cargo profile `install.sh` built, so an upgrade installs
234    /// the same kind rather than quietly switching.
235    #[serde(default)]
236    pub build: Option<String>,
237    /// The version the binaries report, without the `v`. Written for both channels: it is what
238    /// a release install compares against a newer tag, and what a refusal can name when the
239    /// marker is older than this field.
240    #[serde(default)]
241    pub version: Option<String>,
242}
243
244impl InstallMarker {
245    /// Where the marker is, or `None` when HOME and the XDG variables leave no state directory.
246    ///
247    /// Always the plain state directory, never a profile's: an install belongs to the machine
248    /// user, not to a profile, and `install.sh` has no notion of profiles.
249    pub fn path(env: EnvFn) -> Option<PathBuf> {
250        state_dir(env).map(|d| d.join(MARKER_FILE))
251    }
252
253    /// Read the marker at `path`. `None` means there is no such file, which is a state to report
254    /// (the caller says what to do), not an error; a file that is there but unreadable or not
255    /// understood is an error naming the file.
256    pub fn load(path: &Path) -> Result<Option<InstallMarker>> {
257        let text = match std::fs::read_to_string(path) {
258            Ok(t) => t,
259            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
260            Err(e) => return Err(Error::io(path, e)),
261        };
262        serde_json::from_str(&text)
263            .map(Some)
264            .map_err(|e| Error::Parse {
265                path: path.to_path_buf(),
266                message: format!("{e} (run install.sh again to rewrite it)"),
267            })
268    }
269}
270
271/// `<state>/update.json`: the last time the repository was asked, and what it said.
272#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
273#[serde(default)]
274pub struct UpdateCache {
275    /// Unix seconds of the last *attempt*. A failure counts: a server that is down is not asked
276    /// again until the period is up, or every run would pay for the question.
277    pub checked_at: u64,
278    /// The latest commit the last successful answer named.
279    pub latest: Option<String>,
280    /// The commit the notice was last printed for, so it is said once and not on every run.
281    pub notified: Option<String>,
282}
283
284impl UpdateCache {
285    /// A missing or unreadable cache is an empty one: it only ever saves a request.
286    pub fn load(path: &Path) -> UpdateCache {
287        std::fs::read_to_string(path)
288            .ok()
289            .and_then(|t| serde_json::from_str(&t).ok())
290            .unwrap_or_default()
291    }
292
293    /// Best effort and atomic (write beside, rename over): a cache that cannot be written
294    /// costs a request next time, and must not cost a run.
295    pub fn save(&self, path: &Path) {
296        let Ok(text) = serde_json::to_string_pretty(self) else {
297            return;
298        };
299        if let Some(dir) = path.parent() {
300            if std::fs::create_dir_all(dir).is_err() {
301                return;
302            }
303        }
304        let tmp = path.with_extension(format!("json.{}.tmp", std::process::id()));
305        if std::fs::write(&tmp, text + "\n").is_err() || std::fs::rename(&tmp, path).is_err() {
306            let _ = std::fs::remove_file(&tmp);
307        }
308    }
309
310    /// Whether the repository should be asked now.
311    pub fn is_due(&self, check: UpdateCheck, now_secs: u64) -> bool {
312        match check.period_secs() {
313            None => false,
314            Some(period) => now_secs.saturating_sub(self.checked_at) >= period,
315        }
316    }
317}
318
319/// A commit id out of an answer: the whole body, or a JSON object's `sha`.
320pub fn parse_latest(body: &str) -> Option<String> {
321    let is_id = |s: &str| matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit());
322    let bare = body.trim();
323    if is_id(bare) {
324        return Some(bare.to_ascii_lowercase());
325    }
326    let value: serde_json::Value = serde_json::from_str(bare).ok()?;
327    let sha = value.get("sha")?.as_str()?.trim();
328    is_id(sha).then(|| sha.to_ascii_lowercase())
329}
330
331/// One `GET`, read to a cap, inside one deadline. Both questions this module asks go through
332/// here so a mirror, a proxy and a captive portal behave identically for each of them.
333async fn get_body(
334    raw: &str,
335    reach: Reach,
336    accept: &str,
337    timeout: Duration,
338    cap: usize,
339) -> std::result::Result<String, String> {
340    let url = reqwest::Url::parse(raw).map_err(|e| format!("{raw:?}: {e}"))?;
341    let user_agent = format!("eclipse/{}", env!("CARGO_PKG_VERSION"));
342    let ask = async {
343        let mut resp = http::get(
344            &url,
345            timeout,
346            reach,
347            &[("Accept", accept), ("User-Agent", &user_agent)],
348        )
349        .await?;
350        if !resp.status().is_success() {
351            return Err(format!("{url} answered {}", resp.status()));
352        }
353        let mut body = Vec::new();
354        while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
355            body.extend_from_slice(&chunk);
356            if body.len() > cap {
357                // Truncating silently cut the JSON in half and handed the parser the pieces, so
358                // the person saw a serde error instead of "this answer is not a release list"
359                // (`#426`).
360                return Err(format!(
361                    "{url} answered more than {} KB, which is not a release list or a commit id; \
362                     nothing was read",
363                    cap / 1024
364                ));
365            }
366        }
367        Ok(String::from_utf8_lossy(&body).into_owned())
368    };
369    tokio::time::timeout(timeout, ask)
370        .await
371        .unwrap_or_else(|_| {
372            Err(format!(
373                "{url} did not answer within {} s",
374                timeout.as_secs()
375            ))
376        })
377}
378
379/// Ask for the latest commit on the track's branch. One `GET` through [`http::get`], inside
380/// [`CHECK_TIMEOUT`].
381pub async fn fetch_latest(cfg: &UpdateConfig) -> std::result::Result<String, String> {
382    let (raw, reach) = latest_question(cfg);
383    let body = get_body(
384        raw,
385        reach,
386        "application/vnd.github.sha",
387        CHECK_TIMEOUT,
388        MAX_ANSWER_BYTES,
389    )
390    .await?;
391    parse_latest(&body).ok_or_else(|| format!("{raw} did not answer with a commit id"))
392}
393
394/// Ask for the newest release, through the same `GET`. `[update] releases` is the user's URL, so
395/// it may be a host on their own network, exactly like `[update] remote`.
396pub async fn fetch_release(cfg: &UpdateConfig) -> std::result::Result<Release, String> {
397    let (raw, reach) = match cfg.releases.as_deref() {
398        Some(r) => (r, Reach::Anywhere),
399        None => (DEFAULT_RELEASES_URL, Reach::Public),
400    };
401    let body = get_body(
402        raw,
403        reach,
404        "application/vnd.github+json",
405        RELEASE_TIMEOUT,
406        MAX_RELEASE_BYTES,
407    )
408    .await?;
409    parse_release(&body).map_err(|e| format!("{raw}: {e}"))
410}
411
412/// Whether `latest` is something the install does not already contain.
413///
414/// Different ids are not enough: an install built from a commit *ahead* of the public branch
415/// (a fork, unpushed work) would be told to "update" backwards. When the recorded checkout
416/// still has the commit and it is an ancestor of what was installed, it is not news. Anything
417/// this cannot establish — no checkout, no git, a commit the checkout has never seen — is news.
418fn is_news(marker: &InstallMarker, installed: &str, latest: &str) -> bool {
419    if latest == installed {
420        return false;
421    }
422    let Some(workspace) = &marker.workspace else {
423        return true;
424    };
425    let contains = std::process::Command::new("git")
426        .arg("-C")
427        .arg(workspace)
428        .args(["merge-base", "--is-ancestor", latest, installed])
429        .stdin(std::process::Stdio::null())
430        .stdout(std::process::Stdio::null())
431        .stderr(std::process::Stdio::null())
432        .status()
433        .is_ok_and(|s| s.success());
434    !contains
435}
436
437/// What the marker says is installed, in the shape that channel compares. A marker that cannot
438/// answer for its own channel has nothing to check against, and the notice stays silent.
439#[derive(Debug, Clone, PartialEq, Eq)]
440enum Installed {
441    /// A source install: a commit id, compared with the branch's head.
442    Commit(String),
443    /// A release install: a version, compared with the newest tag.
444    Version(Version),
445}
446
447impl Installed {
448    fn of(marker: &InstallMarker) -> Option<Installed> {
449        match marker.channel {
450            Channel::Source => marker
451                .commit
452                .clone()
453                .filter(|c| !c.is_empty())
454                .map(Installed::Commit),
455            Channel::Release => marker
456                .version
457                .as_deref()
458                .and_then(Version::parse)
459                .map(Installed::Version),
460        }
461    }
462}
463
464/// A newer version exists and the install has not taken it yet.
465///
466/// This is what a surface keeps on screen: a comparison, not an event. The same install stays
467/// behind the same answer across any number of runs until `eclipse upgrade` rewrites
468/// `install.json`, which is why it cannot be gated by the cache's `notified` field — that field
469/// makes a line happen once, and the badge is a fact that lasts.
470#[derive(Debug, Clone, PartialEq, Eq)]
471pub struct Behind {
472    /// What the install has, in the shape its channel compares: a version, or a short commit.
473    pub installed: String,
474    /// The newest answer, the same shape: a tag as the release names it, or a short commit.
475    pub latest: String,
476}
477
478impl Behind {
479    /// `0.6.1` or `3f2a1c9`: the badge names the version, not the tag's `v` and not the whole
480    /// forty-character commit id.
481    pub fn shown_latest(&self) -> String {
482        Version::parse(&self.latest)
483            .map(|v| v.to_string())
484            .unwrap_or_else(|| self.latest.clone())
485    }
486
487    /// The badge as one line, for a surface with one colour to give it: the terminal's plain
488    /// REPL, and anything that logs.
489    pub fn line(&self) -> String {
490        format!("↑ {} available · eclipse upgrade", self.shown_latest())
491    }
492}
493
494/// The marker and the cache compared: `Some` exactly while the installed thing is behind the
495/// cached answer. One rule, so the badge, the REPL, the dashboard and the gateway cannot
496/// disagree about what "behind" means.
497pub fn behind(marker: &InstallMarker, cache: &UpdateCache) -> Option<Behind> {
498    let latest = cache.latest.as_deref()?;
499    match Installed::of(marker)? {
500        Installed::Commit(commit) => is_news(marker, &commit, latest).then(|| Behind {
501            installed: short(&commit).to_string(),
502            latest: short(latest).to_string(),
503        }),
504        Installed::Version(version) => {
505            // An answer that is not a version (an old commit id from a source install, a
506            // captive portal) is not news rather than an error, exactly as the notice treats it.
507            let newest = Version::parse(latest)?;
508            (newest > version).then(|| Behind {
509                installed: version.to_string(),
510                latest: latest.trim().to_string(),
511            })
512        }
513    }
514}
515
516/// How long an answer may stand before a surface that cannot refresh it stops repeating it. A
517/// week is longer than either `[update] check` period, so only a machine that has stopped
518/// asking reaches this.
519pub const STALE_AFTER_SECS: u64 = 7 * 86_400;
520
521/// What the dashboard renders: the cache's own numbers, with the comparison already made.
522#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
523pub struct Snapshot {
524    /// The version (release install) or short commit (source install) the marker names.
525    pub installed: Option<String>,
526    /// The newest answer cached, in the same shape. `None` when nothing was ever cached.
527    pub latest: Option<String>,
528    /// Whether this install is behind *and* the answer is fresh enough to still mean it.
529    pub behind: bool,
530    /// Unix seconds of the last attempt, successful or not. `0` when never asked.
531    pub checked_at: u64,
532    pub channel: Option<Channel>,
533}
534
535/// Where a badge is read from, for a surface that asks more than once per process: the state
536/// directory (the plain one, never a profile's — an install belongs to the machine user) and the
537/// `[update]` section that decides whether there is anything to say. Reading it is two small
538/// files, so a frame or a request may ask again rather than cache the answer in memory.
539#[derive(Debug, Clone, PartialEq, Eq)]
540pub struct Watch {
541    state: PathBuf,
542    cfg: UpdateConfig,
543}
544
545impl Watch {
546    /// The watch for a process's own environment. `None` when the user asked not to be told
547    /// (`check = "off"`) or when there is no state directory to look in: both mean no badge.
548    pub fn for_env(env: EnvFn, cfg: &UpdateConfig) -> Option<Watch> {
549        if cfg.check == UpdateCheck::Off {
550            return None;
551        }
552        Some(Watch {
553            state: state_dir(env)?,
554            cfg: cfg.clone(),
555        })
556    }
557
558    /// The watch for a process that resolved its own state directory — the gateway, whose
559    /// environment is the unit's, not a shell's.
560    pub fn at(state: PathBuf, cfg: &UpdateConfig) -> Watch {
561        Watch {
562            state,
563            cfg: cfg.clone(),
564        }
565    }
566
567    /// The badge as the files stand now, or `None` when there is nothing to say.
568    pub fn read(&self) -> Option<Behind> {
569        if self.cfg.check == UpdateCheck::Off {
570            return None;
571        }
572        let marker = InstallMarker::load(&self.state.join(MARKER_FILE))
573            .ok()
574            .flatten()?;
575        let cache = UpdateCache::load(&self.state.join(CACHE_FILE));
576        behind(&marker, &cache)
577    }
578
579    /// The same numbers, for a page: `checked_at` is kept so a stale claim can be recognised
580    /// rather than shown, and the channel because the two channels upgrade differently.
581    pub fn snapshot(&self, now_secs: u64) -> Snapshot {
582        if self.cfg.check == UpdateCheck::Off {
583            return Snapshot::default();
584        }
585        let marker = InstallMarker::load(&self.state.join(MARKER_FILE))
586            .ok()
587            .flatten();
588        let cache = UpdateCache::load(&self.state.join(CACHE_FILE));
589        let behind = marker.as_ref().and_then(|m| behind(m, &cache));
590        let fresh = now_secs.saturating_sub(cache.checked_at) <= STALE_AFTER_SECS;
591        Snapshot {
592            installed: behind
593                .as_ref()
594                .map(|b| b.installed.clone())
595                .or_else(|| marker.as_ref().and_then(installed_text)),
596            latest: behind
597                .as_ref()
598                .map(|b| b.latest.clone())
599                .or_else(|| cache.latest.clone()),
600            behind: behind.is_some() && fresh,
601            checked_at: cache.checked_at,
602            channel: marker.as_ref().map(|m| m.channel),
603        }
604    }
605}
606
607/// What the marker says it has, as a reader would write it: the version a release install
608/// reports, or the short commit a source install was built from.
609fn installed_text(marker: &InstallMarker) -> Option<String> {
610    match Installed::of(marker)? {
611        Installed::Commit(commit) => Some(short(&commit).to_string()),
612        Installed::Version(version) => Some(version.to_string()),
613    }
614}
615
616/// What one refresh did, for a caller that logs or tests it. `Behind` carries the badge, so a
617/// caller that only renders does not have to ask the disk again.
618#[derive(Debug, Clone, PartialEq, Eq)]
619pub enum Outcome {
620    /// Nothing was asked: `check = "off"`, no install marker, or the answer is still inside
621    /// the period and the install is current.
622    NotDue,
623    Current,
624    Behind(Behind),
625    Failed(String),
626}
627
628/// Ask the repository, if the cache says it is time, and leave the answer where every reader
629/// looks. This is what a long-lived process runs on its schedule: the CLI's per-run check and
630/// the gateway's tick write the same `update.json`, so one of them answering spares the other
631/// the request.
632///
633/// Nothing here installs anything: a version change is a decision, and a background timer is
634/// not the place to make it.
635pub async fn refresh(state: &Path, cfg: &UpdateConfig) -> Outcome {
636    if cfg.check == UpdateCheck::Off {
637        return Outcome::NotDue;
638    }
639    let Ok(Some(marker)) = InstallMarker::load(&state.join(MARKER_FILE)) else {
640        return Outcome::NotDue;
641    };
642    let Some(installed) = Installed::of(&marker) else {
643        return Outcome::NotDue;
644    };
645    let cache_path = state.join(CACHE_FILE);
646    let mut cache = UpdateCache::load(&cache_path);
647    let now = crate::session::now_ms() / 1000;
648    if !cache.is_due(cfg.check, now) {
649        return match behind(&marker, &cache) {
650            Some(b) => Outcome::Behind(b),
651            None => Outcome::NotDue,
652        };
653    }
654    // The attempt is recorded before the question. A server that is down must not be asked on
655    // every tick, and a process killed mid-request must not leave the next one asking either.
656    cache.checked_at = now;
657    cache.save(&cache_path);
658    match ask_and_cache(state, cfg, &installed).await {
659        Ok(_) => match behind(&marker, &UpdateCache::load(&cache_path)) {
660            Some(b) => Outcome::Behind(b),
661            None => Outcome::Current,
662        },
663        Err(why) => Outcome::Failed(why),
664    }
665}
666
667/// The one question this module asks on a schedule, answered into the cache. Returns the
668/// answer it wrote, which is what the caller's log line names.
669async fn ask_and_cache(
670    state: &Path,
671    cfg: &UpdateConfig,
672    installed: &Installed,
673) -> std::result::Result<String, String> {
674    let latest = match installed {
675        Installed::Version(_) => fetch_release(cfg).await.map(|release| release.tag),
676        Installed::Commit(_) => fetch_latest(cfg).await,
677    }?;
678    // Re-read before writing: another process may have recorded an attempt meanwhile, and its
679    // `checked_at` is the one that keeps the next run quiet.
680    let path = state.join(CACHE_FILE);
681    let mut cache = UpdateCache::load(&path);
682    cache.latest = Some(latest.clone());
683    cache.save(&path);
684    Ok(latest)
685}
686
687/// The marker's `installed_at`: RFC 3339 in UTC, the same shape `install.sh` writes with
688/// `date -u`, so the two cannot disagree about what a timestamp looks like.
689pub fn rfc3339_utc(ms: u64) -> String {
690    let secs = ms / 1000;
691    let (y, m, d) = crate::cron::civil_from_days((secs / 86_400) as i64);
692    let rem = secs % 86_400;
693    format!(
694        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
695        rem / 3600,
696        (rem % 3600) / 60,
697        rem % 60
698    )
699}
700
701fn short(id: &str) -> &str {
702    id.get(..7).unwrap_or(id)
703}
704
705/// What a front door (`run`, the interactive interface) does about the notice: the line to say
706/// once, if any, the badge, and the refresh that may still be in flight.
707#[derive(Default)]
708pub struct Check {
709    /// The one-line notice, already marked as shown in the cache.
710    pub notice: Option<String>,
711    /// The badge as the disk stood when the run started. A surface that repaints reads its
712    /// [`Watch`] again instead of this, so an answer that lands mid-run still shows up.
713    pub badge: Option<Behind>,
714    refresh: Option<tokio::task::JoinHandle<()>>,
715}
716
717impl Check {
718    /// Never started anything: `[update] check = "off"`, no install marker, or nothing due.
719    pub fn idle() -> Check {
720        Check::default()
721    }
722
723    /// Start the notice for this run. Never fails and never waits: the line printed comes from
724    /// what an earlier run cached, and a refresh, if one is due, runs in the background.
725    /// Needs a tokio runtime.
726    pub fn start(env: EnvFn, cfg: &UpdateConfig) -> Check {
727        if cfg.check == UpdateCheck::Off {
728            return Check::idle();
729        }
730        let Some(state) = state_dir(env) else {
731            return Check::idle();
732        };
733        let Ok(Some(marker)) = InstallMarker::load(&state.join(MARKER_FILE)) else {
734            return Check::idle();
735        };
736        let Some(installed) = Installed::of(&marker) else {
737            return Check::idle();
738        };
739        let cache_path = state.join(CACHE_FILE);
740        let mut cache = UpdateCache::load(&cache_path);
741
742        // The badge is the comparison; the notice is that comparison being said for the first
743        // time, which is what `notified` still keeps to one line per answer. The badge itself
744        // is not gated by it: an install that stays behind stays behind across every run.
745        let badge = behind(&marker, &cache);
746        let mut notice = None;
747        if let Some(behind) = &badge {
748            if cache.latest.as_deref() != cache.notified.as_deref() {
749                notice = Some(format!(
750                    "a newer eclipse is available ({}, installed {}): run `eclipse upgrade` \
751                     \u{2014} this notice is `[update] check`, set it to \"off\" to stop it",
752                    behind.latest, behind.installed
753                ));
754                cache.notified = cache.latest.clone();
755            }
756        }
757
758        let now = crate::session::now_ms() / 1000;
759        let due = cache.is_due(cfg.check, now);
760        if due {
761            cache.checked_at = now;
762        }
763        if notice.is_some() || due {
764            cache.save(&cache_path);
765        }
766
767        let refresh = due.then(|| {
768            let cfg = cfg.clone();
769            let state = state.clone();
770            tokio::spawn(async move {
771                let _ = ask_and_cache(&state, &cfg, &installed).await;
772            })
773        });
774        Check {
775            notice,
776            badge,
777            refresh,
778        }
779    }
780
781    /// Give a refresh still in flight its chance to land before the process exits. It was
782    /// started with the run, so after any real run this returns at once; the worst case is the
783    /// deadline the request itself is limited to.
784    pub async fn finish(self) {
785        if let Some(handle) = self.refresh {
786            let _ = tokio::time::timeout(RELEASE_TIMEOUT, handle).await;
787        }
788    }
789}
790
791#[cfg(test)]
792mod tests {
793    use super::*;
794    use std::io::{Read, Write};
795    use std::sync::atomic::{AtomicUsize, Ordering};
796    use std::sync::Arc;
797
798    const OLD: &str = "1111111111111111111111111111111111111111";
799    const NEW: &str = "2222222222222222222222222222222222222222";
800
801    /// A loopback server that answers every request with `body` and counts them.
802    fn serve(body: &'static str) -> (String, Arc<AtomicUsize>) {
803        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
804        let url = format!("http://{}/latest", listener.local_addr().unwrap());
805        let hits = Arc::new(AtomicUsize::new(0));
806        let counted = hits.clone();
807        std::thread::spawn(move || {
808            while let Ok((mut s, _)) = listener.accept() {
809                counted.fetch_add(1, Ordering::SeqCst);
810                let mut buf = [0u8; 2048];
811                let _ = s.read(&mut buf);
812                let _ = write!(
813                    s,
814                    "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
815                    body.len()
816                );
817            }
818        });
819        (url, hits)
820    }
821
822    /// A URL nothing listens on.
823    fn dead_url() -> String {
824        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
825        let url = format!("http://{}/latest", listener.local_addr().unwrap());
826        drop(listener);
827        url
828    }
829
830    /// A state directory holding a marker for an install built from `OLD`.
831    fn installed(remote: &str, check: UpdateCheck) -> (tempfile::TempDir, UpdateConfig) {
832        let home = tempfile::tempdir().unwrap();
833        let state = home.path().join(".eclipse/state");
834        std::fs::create_dir_all(&state).unwrap();
835        std::fs::write(
836            state.join(MARKER_FILE),
837            format!(
838                r#"{{"channel":"source","prefix":"/x","commit":"{OLD}","installed_at":"2026-01-01T00:00:00Z"}}"#
839            ),
840        )
841        .unwrap();
842        let cfg = UpdateConfig {
843            check,
844            track: Track::Release,
845            remote: Some(remote.to_string()),
846            releases: None,
847        };
848        (home, cfg)
849    }
850
851    fn env_of(home: &Path) -> impl Fn(&str) -> Option<String> {
852        let home = home.to_string_lossy().into_owned();
853        move |k| (k == "HOME").then(|| home.clone())
854    }
855
856    async fn one_run(home: &Path, cfg: &UpdateConfig) -> Option<String> {
857        let env = env_of(home);
858        let check = Check::start(&env, cfg);
859        let notice = check.notice.clone();
860        check.finish().await;
861        notice
862    }
863
864    #[tokio::test]
865    async fn the_latest_commit_is_asked_once_per_period_and_the_notice_is_said_once() {
866        let (url, hits) = serve(NEW);
867        let (home, cfg) = installed(&url, UpdateCheck::Daily);
868
869        // The first run has nothing cached to say, but it asks.
870        assert_eq!(one_run(home.path(), &cfg).await, None);
871        assert_eq!(hits.load(Ordering::SeqCst), 1);
872
873        // The second run says it, from the cache, without asking again.
874        let line = one_run(home.path(), &cfg).await.expect("a notice");
875        assert!(
876            line.contains("2222222") && line.contains("eclipse upgrade"),
877            "{line}"
878        );
879        assert!(
880            line.contains("off"),
881            "it says how to turn itself off: {line}"
882        );
883        assert_eq!(
884            hits.load(Ordering::SeqCst),
885            1,
886            "one request across two runs"
887        );
888
889        // And only once.
890        assert_eq!(one_run(home.path(), &cfg).await, None);
891        assert_eq!(hits.load(Ordering::SeqCst), 1);
892    }
893
894    #[tokio::test]
895    async fn a_server_that_is_down_is_silent_and_is_not_asked_again_within_the_period() {
896        let (home, cfg) = installed(&dead_url(), UpdateCheck::Daily);
897        assert_eq!(one_run(home.path(), &cfg).await, None);
898        let cache = UpdateCache::load(&home.path().join(".eclipse/state").join(CACHE_FILE));
899        assert!(cache.checked_at > 0, "the attempt is recorded");
900        assert_eq!(cache.latest, None);
901        assert!(!cache.is_due(UpdateCheck::Daily, cache.checked_at + 60));
902        assert_eq!(one_run(home.path(), &cfg).await, None);
903    }
904
905    #[tokio::test]
906    async fn an_answer_that_is_not_a_commit_id_is_never_cached_as_one() {
907        let (url, hits) = serve("<html>captive portal</html>");
908        let (home, cfg) = installed(&url, UpdateCheck::Daily);
909        assert_eq!(one_run(home.path(), &cfg).await, None);
910        assert_eq!(hits.load(Ordering::SeqCst), 1);
911        let cache = UpdateCache::load(&home.path().join(".eclipse/state").join(CACHE_FILE));
912        assert_eq!(cache.latest, None);
913    }
914
915    #[tokio::test]
916    async fn check_off_makes_no_request_and_writes_nothing() {
917        let (url, hits) = serve(NEW);
918        let (home, cfg) = installed(&url, UpdateCheck::Off);
919        assert_eq!(one_run(home.path(), &cfg).await, None);
920        assert_eq!(hits.load(Ordering::SeqCst), 0);
921        assert!(!home.path().join(".eclipse/state").join(CACHE_FILE).exists());
922    }
923
924    #[tokio::test]
925    async fn a_run_with_no_install_marker_makes_no_request() {
926        let (url, hits) = serve(NEW);
927        let home = tempfile::tempdir().unwrap();
928        let cfg = UpdateConfig {
929            check: UpdateCheck::Daily,
930            track: Track::Release,
931            remote: Some(url),
932            releases: None,
933        };
934        assert_eq!(one_run(home.path(), &cfg).await, None);
935        assert_eq!(
936            hits.load(Ordering::SeqCst),
937            0,
938            "nothing to compare with, nothing asked"
939        );
940    }
941
942    #[test]
943    fn a_commit_id_is_read_from_a_bare_body_or_a_json_sha_and_nothing_else() {
944        assert_eq!(parse_latest(&format!("{NEW}\n")).as_deref(), Some(NEW));
945        assert_eq!(
946            parse_latest(&format!(
947                r#"{{"sha":"{}","commit":{{}}}}"#,
948                NEW.to_uppercase()
949            ))
950            .as_deref(),
951            Some(NEW)
952        );
953        for bad in ["", "main", "abc123", r#"{"sha":"nope"}"#, "<html></html>"] {
954            assert_eq!(parse_latest(bad), None, "{bad:?}");
955        }
956    }
957
958    /// The track names a branch, and the question follows it — unless the person wrote a URL,
959    /// which is the escape hatch a track must not quietly reroute.
960    #[test]
961    fn the_commit_question_follows_the_tracks_branch_unless_a_remote_was_set() {
962        let asked = |track, remote: Option<&str>| {
963            let cfg = UpdateConfig {
964                check: UpdateCheck::Daily,
965                track,
966                remote: remote.map(str::to_string),
967                releases: None,
968            };
969            latest_question(&cfg).0.to_string()
970        };
971        assert_eq!(asked(Track::Release, None), DEFAULT_LATEST_URL);
972        assert_eq!(
973            asked(Track::Develop, None),
974            DEVELOP_LATEST_URL,
975            "a develop checkout is asked about develop, never about main"
976        );
977        assert!(DEVELOP_LATEST_URL.ends_with("/commits/develop"));
978        for track in [Track::Release, Track::Develop] {
979            assert_eq!(
980                asked(track, Some("http://mirror/latest")),
981                "http://mirror/latest",
982                "an explicit remote wins on either track"
983            );
984        }
985    }
986
987    #[test]
988    fn a_marker_that_is_missing_is_none_and_one_that_is_broken_names_its_file() {
989        let dir = tempfile::tempdir().unwrap();
990        let path = dir.path().join(MARKER_FILE);
991        assert_eq!(InstallMarker::load(&path).unwrap(), None);
992        std::fs::write(
993            &path,
994            r#"{"channel":"carrier-pigeon","prefix":"/x","installed_at":"t"}"#,
995        )
996        .unwrap();
997        let err = InstallMarker::load(&path).unwrap_err().to_string();
998        assert!(
999            err.contains("install.json") && err.contains("carrier-pigeon"),
1000            "{err}"
1001        );
1002    }
1003
1004    #[test]
1005    fn a_marker_from_a_tarball_install_has_no_commit_and_no_checkout() {
1006        let dir = tempfile::tempdir().unwrap();
1007        let path = dir.path().join(MARKER_FILE);
1008        std::fs::write(
1009            &path,
1010            r#"{"channel":"source","prefix":"/p","workspace":null,"commit":null,"installed_at":"2026-01-01T00:00:00Z"}"#,
1011        )
1012        .unwrap();
1013        let m = InstallMarker::load(&path).unwrap().unwrap();
1014        assert_eq!((m.commit, m.workspace), (None, None));
1015    }
1016
1017    fn git(dir: &Path, args: &[&str]) -> String {
1018        let out = std::process::Command::new("git")
1019            .arg("-C")
1020            .arg(dir)
1021            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
1022            .args(args)
1023            .output()
1024            .unwrap();
1025        assert!(out.status.success(), "git {args:?}: {out:?}");
1026        String::from_utf8_lossy(&out.stdout).trim().to_string()
1027    }
1028
1029    #[test]
1030    fn a_release_version_is_three_numbers_and_orders_by_them() {
1031        assert_eq!(
1032            Version::parse("v0.2.1"),
1033            Some(Version {
1034                major: 0,
1035                minor: 2,
1036                patch: 1
1037            })
1038        );
1039        assert_eq!(Version::parse(" 0.10.0 ").unwrap().to_string(), "0.10.0");
1040        assert!(Version::parse("v0.10.0") > Version::parse("v0.9.9"));
1041        assert!(Version::parse("v1.0.0") > Version::parse("v0.99.99"));
1042        for bad in [
1043            "",
1044            "v",
1045            "1",
1046            "1.2",
1047            "1.2.3.4",
1048            "v1.two.3",
1049            "main",
1050            "v0.2.1-rc1.x",
1051        ] {
1052            assert_eq!(Version::parse(bad), None, "{bad:?}");
1053        }
1054    }
1055
1056    #[test]
1057    fn a_release_answer_names_the_linux_tarball_and_its_sums_or_says_what_it_carries() {
1058        let body = format!(
1059            r#"{{
1060                "tag_name": "v0.3.0",
1061                "html_url": "https://example.invalid/releases/v0.3.0",
1062                "assets": [
1063                    {{"name": "eclipse-v0.3.0-aarch64-apple-darwin.tar.gz", "browser_download_url": "https://x/mac"}},
1064                    {{"name": "eclipse-v0.3.0-x86_64-unknown-linux-gnu.tar.gz", "browser_download_url": "https://x/linux"}},
1065                    {{"name": "{SUMS_NAME}", "browser_download_url": "https://x/sums"}}
1066                ]
1067            }}"#
1068        );
1069        let release = parse_release(&body).expect("a release");
1070        assert_eq!(release.version.to_string(), "0.3.0");
1071        assert_eq!(release.tarball_url, "https://x/linux");
1072        assert_eq!(release.sums_url, "https://x/sums");
1073        assert_eq!(
1074            release.page.as_deref(),
1075            Some("https://example.invalid/releases/v0.3.0")
1076        );
1077
1078        // No Linux asset: the refusal lists what the release does carry, which is what makes it
1079        // actionable rather than a bare "not found".
1080        let missing = parse_release(
1081            r#"{"tag_name":"v0.3.0","assets":[{"name":"eclipse-v0.3.0-aarch64-apple-darwin.tar.gz","browser_download_url":"https://x/mac"}]}"#,
1082        )
1083        .unwrap_err();
1084        assert!(
1085            missing.contains("no") && missing.contains("darwin"),
1086            "{missing}"
1087        );
1088
1089        // A tag that is not a version at all is refused by name, not parsed into nonsense.
1090        let bad_tag = parse_release(r#"{"tag_name":"nightly","assets":[]}"#).unwrap_err();
1091        assert!(bad_tag.contains("nightly"), "{bad_tag}");
1092    }
1093
1094    /// A state directory holding a release marker, and a config whose release question points at
1095    /// `url`.
1096    fn installed_release(version: &str, url: &str) -> (tempfile::TempDir, UpdateConfig) {
1097        let home = tempfile::tempdir().unwrap();
1098        let state = home.path().join(".eclipse/state");
1099        std::fs::create_dir_all(&state).unwrap();
1100        std::fs::write(
1101            state.join(MARKER_FILE),
1102            format!(
1103                r#"{{"channel":"release","prefix":"/x","workspace":null,"commit":null,"installed_at":"2026-01-01T00:00:00Z","build":"release","version":"{version}"}}"#
1104            ),
1105        )
1106        .unwrap();
1107        let cfg = UpdateConfig {
1108            check: UpdateCheck::Daily,
1109            track: Track::Release,
1110            remote: None,
1111            releases: Some(url.to_string()),
1112        };
1113        (home, cfg)
1114    }
1115
1116    #[tokio::test]
1117    async fn a_release_install_is_told_about_a_newer_tag_by_version_and_only_once() {
1118        let body: &'static str = Box::leak(
1119            format!(
1120                r#"{{"tag_name":"v0.3.0","assets":[{{"name":"eclipse-v0.3.0{TARBALL_SUFFIX}","browser_download_url":"https://x/linux"}},{{"name":"{SUMS_NAME}","browser_download_url":"https://x/sums"}}]}}"#
1121            )
1122            .into_boxed_str(),
1123        );
1124        let (url, hits) = serve(body);
1125        let (home, cfg) = installed_release("0.2.0", &url);
1126
1127        // The first run asks; the notice comes from the second run's cache.
1128        assert_eq!(one_run(home.path(), &cfg).await, None);
1129        assert_eq!(hits.load(Ordering::SeqCst), 1);
1130        let line = one_run(home.path(), &cfg).await.expect("a notice");
1131        assert!(
1132            line.contains("v0.3.0") && line.contains("0.2.0") && line.contains("eclipse upgrade"),
1133            "{line}"
1134        );
1135        assert_eq!(one_run(home.path(), &cfg).await, None, "said once");
1136        assert_eq!(hits.load(Ordering::SeqCst), 1);
1137    }
1138
1139    #[tokio::test]
1140    async fn a_release_install_on_the_newest_tag_is_silent() {
1141        let body: &'static str = Box::leak(
1142            format!(
1143                r#"{{"tag_name":"v0.2.0","assets":[{{"name":"eclipse-v0.2.0{TARBALL_SUFFIX}","browser_download_url":"https://x/linux"}},{{"name":"{SUMS_NAME}","browser_download_url":"https://x/sums"}}]}}"#
1144            )
1145            .into_boxed_str(),
1146        );
1147        let (url, _hits) = serve(body);
1148        let (home, cfg) = installed_release("0.2.0", &url);
1149        assert_eq!(one_run(home.path(), &cfg).await, None);
1150        assert_eq!(one_run(home.path(), &cfg).await, None, "never a notice");
1151    }
1152
1153    #[tokio::test]
1154    async fn a_release_marker_with_no_version_asks_nothing() {
1155        let (url, hits) = serve("{}");
1156        let home = tempfile::tempdir().unwrap();
1157        let state = home.path().join(".eclipse/state");
1158        std::fs::create_dir_all(&state).unwrap();
1159        std::fs::write(
1160            state.join(MARKER_FILE),
1161            r#"{"channel":"release","prefix":"/x","installed_at":"t"}"#,
1162        )
1163        .unwrap();
1164        let cfg = UpdateConfig {
1165            check: UpdateCheck::Daily,
1166            track: Track::Release,
1167            remote: None,
1168            releases: Some(url),
1169        };
1170        assert_eq!(one_run(home.path(), &cfg).await, None);
1171        assert_eq!(hits.load(Ordering::SeqCst), 0);
1172    }
1173
1174    #[test]
1175    fn a_commit_the_install_already_contains_is_not_news_and_one_it_has_never_seen_is() {
1176        let repo = tempfile::tempdir().unwrap();
1177        git(repo.path(), &["init", "-q"]);
1178        git(repo.path(), &["commit", "-q", "--allow-empty", "-m", "one"]);
1179        let first = git(repo.path(), &["rev-parse", "HEAD"]);
1180        git(repo.path(), &["commit", "-q", "--allow-empty", "-m", "two"]);
1181        let second = git(repo.path(), &["rev-parse", "HEAD"]);
1182        let marker = InstallMarker {
1183            channel: Channel::Source,
1184            prefix: "/x".into(),
1185            workspace: Some(repo.path().to_path_buf()),
1186            commit: Some(second.clone()),
1187            installed_at: "t".into(),
1188            build: None,
1189            version: None,
1190        };
1191        assert!(!is_news(&marker, &second, &second));
1192        assert!(
1193            !is_news(&marker, &second, &first),
1194            "an older commit is not an update"
1195        );
1196        assert!(is_news(&marker, &first, &second), "a newer one is");
1197        assert!(
1198            is_news(&marker, &second, NEW),
1199            "so is one this checkout has never seen"
1200        );
1201    }
1202
1203    /// A release answer for `tag`, as a static body a loopback server can hand back.
1204    fn release_body(tag: &str) -> &'static str {
1205        Box::leak(
1206            format!(
1207                r#"{{"tag_name":"{tag}","assets":[{{"name":"eclipse-{tag}{TARBALL_SUFFIX}","browser_download_url":"https://x/linux"}},{{"name":"{SUMS_NAME}","browser_download_url":"https://x/sums"}}]}}"#
1208            )
1209            .into_boxed_str(),
1210        )
1211    }
1212
1213    /// The same run `one_run` makes, keeping the badge as well as the notice.
1214    async fn one_run_check(home: &Path, cfg: &UpdateConfig) -> (Option<String>, Option<Behind>) {
1215        let env = env_of(home);
1216        let check = Check::start(&env, cfg);
1217        let seen = (check.notice.clone(), check.badge.clone());
1218        check.finish().await;
1219        seen
1220    }
1221
1222    fn state_of(home: &Path) -> PathBuf {
1223        home.join(".eclipse/state")
1224    }
1225
1226    /// The file `eclipse upgrade` rewrites, for the test that moves an install forward.
1227    fn rewrite_marker_version(home: &Path, version: &str) {
1228        std::fs::write(
1229            state_of(home).join(MARKER_FILE),
1230            format!(
1231                r#"{{"channel":"release","prefix":"/x","installed_at":"2026-01-01T00:00:00Z","version":"{version}"}}"#
1232            ),
1233        )
1234        .unwrap();
1235    }
1236
1237    fn write_cache(home: &Path, latest: &str, checked_at: u64) {
1238        let cache = UpdateCache {
1239            checked_at,
1240            latest: Some(latest.to_string()),
1241            notified: None,
1242        };
1243        cache.save(&state_of(home).join(CACHE_FILE));
1244    }
1245
1246    fn now_secs() -> u64 {
1247        crate::session::now_ms() / 1000
1248    }
1249
1250    /// The issue's headline: the notice is a one-shot, the badge is not. An install that stays
1251    /// behind says so on every run, and says it without asking again.
1252    #[tokio::test]
1253    async fn the_badge_lasts_across_runs_while_the_notice_is_only_said_once() {
1254        let (url, hits) = serve(release_body("v0.3.0"));
1255        let (home, cfg) = installed_release("0.2.0", &url);
1256
1257        // The first run asks, and there is nothing cached to badge yet.
1258        assert_eq!(one_run_check(home.path(), &cfg).await, (None, None));
1259        assert_eq!(hits.load(Ordering::SeqCst), 1);
1260
1261        // The second run says it, and shows it.
1262        let (notice, badge) = one_run_check(home.path(), &cfg).await;
1263        assert!(
1264            notice.expect("a notice").contains("v0.3.0"),
1265            "the notice still names the tag"
1266        );
1267        let badge = badge.expect("a badge");
1268        assert_eq!(badge.installed, "0.2.0");
1269        assert_eq!(
1270            badge.line(),
1271            "↑ 0.3.0 available · eclipse upgrade",
1272            "one version, without the tag's v"
1273        );
1274
1275        // The third run is the whole point: the notice is spent, the badge is not.
1276        let (notice, badge) = one_run_check(home.path(), &cfg).await;
1277        assert_eq!(notice, None, "a notice happens once per answer");
1278        assert!(
1279            badge.is_some(),
1280            "a badge lasts as long as the install is behind"
1281        );
1282        assert_eq!(hits.load(Ordering::SeqCst), 1, "neither run asked again");
1283    }
1284
1285    /// And it goes when the install moves, from the marker alone: no timer, no acknowledgement.
1286    #[tokio::test]
1287    async fn the_badge_clears_when_the_install_reaches_the_new_version() {
1288        let (url, _hits) = serve(release_body("v0.3.0"));
1289        let (home, cfg) = installed_release("0.2.0", &url);
1290        assert_eq!(one_run_check(home.path(), &cfg).await, (None, None));
1291        assert!(one_run_check(home.path(), &cfg).await.1.is_some());
1292
1293        rewrite_marker_version(home.path(), "0.3.0");
1294        let env = env_of(home.path());
1295        let watch = Watch::for_env(&env, &cfg).expect("a watch");
1296        assert_eq!(watch.read(), None, "the upgrade is what clears it");
1297    }
1298
1299    /// A source install has no version, so the badge names the short commit it was built from.
1300    #[test]
1301    fn a_source_install_badges_the_short_commit_it_has_never_seen() {
1302        let marker = InstallMarker {
1303            channel: Channel::Source,
1304            prefix: "/x".into(),
1305            workspace: None,
1306            commit: Some(OLD.into()),
1307            installed_at: "t".into(),
1308            build: None,
1309            version: None,
1310        };
1311        let cache = UpdateCache {
1312            checked_at: 1,
1313            latest: Some(NEW.into()),
1314            notified: Some(NEW.into()),
1315        };
1316        let badge = behind(&marker, &cache).expect("a badge");
1317        assert_eq!(badge.installed, "1111111");
1318        assert_eq!(badge.line(), "↑ 2222222 available · eclipse upgrade");
1319    }
1320
1321    /// `check = "off"` is not "do not ask" — it is "do not tell me", so a cached answer from
1322    /// before the switch cannot bring the badge back on either surface.
1323    #[tokio::test]
1324    async fn check_off_produces_no_badge_even_from_a_cached_answer() {
1325        let (home, mut cfg) = installed_release("0.2.0", "http://127.0.0.1:1/latest");
1326        write_cache(home.path(), "v0.3.0", now_secs());
1327        cfg.check = UpdateCheck::Off;
1328
1329        let env = env_of(home.path());
1330        assert!(Watch::for_env(&env, &cfg).is_none(), "nothing to watch");
1331        assert_eq!(Check::start(&env, &cfg).badge, None);
1332
1333        // The dashboard asks the same question through a state directory it already resolved.
1334        let snapshot = Watch::at(state_of(home.path()), &cfg).snapshot(now_secs());
1335        assert!(
1336            !snapshot.behind,
1337            "the answer is there and must not be shown"
1338        );
1339        assert_eq!(snapshot.latest, None);
1340    }
1341
1342    /// A gateway that has stopped asking must stop claiming: a week-old answer is a stale
1343    /// answer, and the page shows nothing rather than a version that may long since be gone.
1344    #[test]
1345    fn a_snapshot_stops_claiming_an_answer_older_than_a_week() {
1346        let (home, cfg) = installed_release("0.2.0", "http://127.0.0.1:1/latest");
1347        let now = now_secs();
1348        write_cache(home.path(), "v0.3.0", now - STALE_AFTER_SECS - 60);
1349
1350        let snapshot = Watch::at(state_of(home.path()), &cfg).snapshot(now);
1351        assert!(!snapshot.behind, "eight days old is not a claim to make");
1352        assert_eq!(snapshot.installed.as_deref(), Some("0.2.0"));
1353        assert_eq!(
1354            snapshot.latest.as_deref(),
1355            Some("v0.3.0"),
1356            "the number is still reported, it is the claim that is withheld"
1357        );
1358        assert_eq!(snapshot.channel, Some(Channel::Release));
1359
1360        // Inside the week, the same cache is the badge the CLI would show.
1361        write_cache(home.path(), "v0.3.0", now - 3600);
1362        let fresh = Watch::at(state_of(home.path()), &cfg).snapshot(now);
1363        assert!(fresh.behind);
1364        assert_eq!(fresh.checked_at, now - 3600);
1365    }
1366
1367    /// The gateway's tick and the CLI's run share one cache: whoever asks first spares the
1368    /// other the request, which is what keeps three dashboard tabs from hammering GitHub.
1369    #[tokio::test]
1370    async fn a_scheduled_refresh_writes_the_cache_and_asks_once_a_period() {
1371        let (url, hits) = serve(release_body("v0.3.0"));
1372        let (home, cfg) = installed_release("0.2.0", &url);
1373        let state = state_of(home.path());
1374
1375        match refresh(&state, &cfg).await {
1376            Outcome::Behind(badge) => assert_eq!(badge.latest, "v0.3.0"),
1377            other => panic!("expected a badge, got {other:?}"),
1378        }
1379        assert_eq!(hits.load(Ordering::SeqCst), 1);
1380        let cache = UpdateCache::load(&state.join(CACHE_FILE));
1381        assert!(cache.checked_at > 0, "the attempt is recorded");
1382        assert_eq!(cache.latest.as_deref(), Some("v0.3.0"));
1383
1384        // Inside the period: the answer is read, nothing is asked.
1385        assert!(matches!(refresh(&state, &cfg).await, Outcome::Behind(_)));
1386        assert_eq!(hits.load(Ordering::SeqCst), 1, "one request per period");
1387        assert_eq!(
1388            Watch::at(state.clone(), &cfg).read().map(|b| b.latest),
1389            Some("v0.3.0".to_string()),
1390            "and the CLI's reader sees exactly what the gateway wrote"
1391        );
1392    }
1393
1394    /// A check that cannot reach the repository says why, and still counts as the period's
1395    /// attempt so a downed server is not asked on every tick.
1396    #[tokio::test]
1397    async fn a_refresh_that_fails_reports_it_and_records_the_attempt() {
1398        let (home, cfg) = installed_release("0.2.0", &dead_url());
1399        let state = state_of(home.path());
1400        match refresh(&state, &cfg).await {
1401            Outcome::Failed(why) => assert!(!why.is_empty(), "{why}"),
1402            other => panic!("expected a failure, got {other:?}"),
1403        }
1404        let cache = UpdateCache::load(&state.join(CACHE_FILE));
1405        assert!(cache.checked_at > 0, "a failure is still an attempt");
1406        assert_eq!(cache.latest, None);
1407        assert!(
1408            matches!(refresh(&state, &cfg).await, Outcome::NotDue),
1409            "and the next tick inside the period asks nothing"
1410        );
1411    }
1412}