Skip to main content

ant_node/upgrade/
monitor.rs

1//! GitHub release monitor for auto-upgrades.
2//!
3//! This module provides functionality to:
4//! - Poll GitHub releases API for new versions
5//! - Filter releases by channel (stable/beta)
6//! - Find platform-specific binary assets
7//! - Detect available upgrades
8//! - Staged rollout with deterministic delays
9
10use crate::config::UpgradeChannel;
11use crate::error::{Error, Result};
12use crate::logging::{debug, info, warn};
13use crate::upgrade::release_cache::ReleaseCache;
14use crate::upgrade::rollout::StagedRollout;
15use crate::upgrade::UpgradeInfo;
16use semver::Version;
17use serde::Deserialize;
18use std::time::{Duration, Instant};
19
20/// GitHub release API response.
21#[derive(Debug, Deserialize)]
22pub struct GitHubRelease {
23    /// Git tag name (e.g., "v1.2.0").
24    pub tag_name: String,
25    /// Release title.
26    pub name: String,
27    /// Release description/notes.
28    pub body: String,
29    /// Whether this is a pre-release.
30    pub prerelease: bool,
31    /// Attached binary assets.
32    pub assets: Vec<Asset>,
33}
34
35/// GitHub release asset (attached file).
36#[derive(Debug, Deserialize, Clone)]
37pub struct Asset {
38    /// Filename of the asset.
39    pub name: String,
40    /// Direct download URL.
41    pub browser_download_url: String,
42}
43
44/// Monitors GitHub releases for new versions.
45pub struct UpgradeMonitor {
46    /// GitHub repository (owner/repo format).
47    repo: String,
48    /// Release channel to track.
49    channel: UpgradeChannel,
50    /// How often to check for updates.
51    check_interval: Duration,
52    /// Current version.
53    current_version: Version,
54    /// HTTP client for GitHub API requests.
55    client: reqwest::Client,
56    /// Staged rollout calculator (optional).
57    staged_rollout: Option<StagedRollout>,
58    /// Disk cache for GitHub release metadata (shared across instances).
59    release_cache: Option<ReleaseCache>,
60    /// When the current pending upgrade was first detected.
61    pending_upgrade_detected: Option<Instant>,
62    /// The version of the pending upgrade (for tracking rollout state).
63    pending_upgrade_version: Option<Version>,
64}
65
66impl UpgradeMonitor {
67    /// Create a new upgrade monitor.
68    ///
69    /// # Arguments
70    ///
71    /// * `repo` - GitHub repository in "owner/repo" format
72    /// * `channel` - Release channel to track (Stable or Beta)
73    /// * `check_interval_hours` - How often to check for updates
74    #[must_use]
75    pub fn new(repo: String, channel: UpgradeChannel, check_interval_hours: u64) -> Self {
76        let current_version =
77            Version::parse(env!("CARGO_PKG_VERSION")).unwrap_or_else(|_| Version::new(0, 0, 0));
78
79        let client = reqwest::Client::builder()
80            .user_agent(concat!("ant-node/", env!("CARGO_PKG_VERSION")))
81            .timeout(Duration::from_secs(30))
82            .build()
83            .unwrap_or_else(|e| {
84                warn!("Failed to build reqwest client for upgrades: {e}");
85                reqwest::Client::new()
86            });
87
88        Self {
89            repo,
90            channel,
91            check_interval: Duration::from_secs(check_interval_hours * 3600),
92            current_version,
93            client,
94            staged_rollout: None,
95            release_cache: None,
96            pending_upgrade_detected: None,
97            pending_upgrade_version: None,
98        }
99    }
100
101    /// Configure a shared disk cache for release metadata.
102    ///
103    /// When set, `check_for_updates` will consult the cache before hitting
104    /// the GitHub API.  Fresh results are written back so that other nodes
105    /// on the same machine can reuse them.
106    #[must_use]
107    pub fn with_release_cache(mut self, cache: ReleaseCache) -> Self {
108        self.release_cache = Some(cache);
109        self
110    }
111
112    /// Configure staged rollout for this monitor.
113    ///
114    /// # Arguments
115    ///
116    /// * `node_id` - The node's unique identifier for deterministic delay calculation
117    /// * `max_delay_hours` - Maximum rollout window (0 to disable)
118    #[must_use]
119    pub fn with_staged_rollout(mut self, node_id: &[u8], max_delay_hours: u64) -> Self {
120        if max_delay_hours > 0 {
121            self.staged_rollout = Some(StagedRollout::new(node_id, max_delay_hours));
122            info!("Staged rollout enabled: {} hour window", max_delay_hours);
123        }
124        self
125    }
126
127    /// Create a monitor with a custom current version (for testing).
128    #[cfg(test)]
129    #[must_use]
130    pub fn with_version(
131        repo: String,
132        channel: UpgradeChannel,
133        check_interval_hours: u64,
134        current_version: Version,
135    ) -> Self {
136        let client = reqwest::Client::builder()
137            .user_agent(concat!("ant-node/", env!("CARGO_PKG_VERSION")))
138            .timeout(Duration::from_secs(30))
139            .build()
140            .unwrap_or_else(|e| {
141                warn!("Failed to build reqwest client for upgrades: {e}");
142                reqwest::Client::new()
143            });
144
145        Self {
146            repo,
147            channel,
148            check_interval: Duration::from_secs(check_interval_hours * 3600),
149            current_version,
150            client,
151            staged_rollout: None,
152            release_cache: None,
153            pending_upgrade_detected: None,
154            pending_upgrade_version: None,
155        }
156    }
157
158    /// Get the check interval.
159    #[must_use]
160    pub fn check_interval(&self) -> Duration {
161        self.check_interval
162    }
163
164    /// Get the current version.
165    #[must_use]
166    pub fn current_version(&self) -> &Version {
167        &self.current_version
168    }
169
170    /// Get the tracked repository.
171    #[must_use]
172    pub fn repo(&self) -> &str {
173        &self.repo
174    }
175
176    /// Check if version matches the configured channel.
177    ///
178    /// - Stable: only final releases, i.e. no pre-release component at all.
179    /// - Beta: final releases, plus pre-releases whose first identifier is exactly `beta`
180    ///   (`0.17.0-beta.1`, `0.17.0-beta`).
181    ///
182    /// Every other pre-release suffix, `-rc.*` included, is rejected on both channels.
183    #[must_use]
184    pub fn version_matches_channel(&self, version: &Version) -> bool {
185        version_matches_channel(version, self.channel)
186    }
187
188    /// Check GitHub for available updates.
189    ///
190    /// This method only checks for available updates, it does not respect
191    /// staged rollout delays. Use [`Self::check_for_ready_upgrade`] for staged rollout
192    /// aware upgrade checking.
193    ///
194    /// # Errors
195    ///
196    /// Returns an error if the GitHub API request fails.
197    pub async fn check_for_updates(&self) -> Result<Option<UpgradeInfo>> {
198        // Try the shared disk cache first (lock-free fast path)
199        if let Some(ref cache) = self.release_cache {
200            if let Some(cached_releases) = cache.read_if_valid(&self.repo) {
201                info!(
202                    "Using cached release info ({} releases)",
203                    cached_releases.len()
204                );
205                return Ok(select_upgrade_from_releases(
206                    &cached_releases,
207                    &self.current_version,
208                    self.channel,
209                    self.pending_upgrade_version.as_ref(),
210                ));
211            }
212
213            // Cache stale/missing — acquire lock and re-check so only one
214            // node actually hits the GitHub API while the rest wait.
215            let cache_clone = cache.clone();
216            let repo_clone = self.repo.clone();
217            let (lock_guard, rechecked) =
218                tokio::task::spawn_blocking(move || cache_clone.lock_and_recheck(&repo_clone))
219                    .await
220                    .map_err(|e| Error::Upgrade(format!("Cache lock task failed: {e}")))??;
221
222            if let Some(cached_releases) = rechecked {
223                info!(
224                    "Using cached release info after lock ({} releases)",
225                    cached_releases.len()
226                );
227                return Ok(select_upgrade_from_releases(
228                    &cached_releases,
229                    &self.current_version,
230                    self.channel,
231                    self.pending_upgrade_version.as_ref(),
232                ));
233            }
234
235            info!("No valid cache under lock, fetching from API");
236
237            // Fetch from API while holding the lock
238            let releases = self.fetch_releases_from_api().await?;
239
240            // Write fresh results under the lock for other nodes
241            if let Err(e) = cache.write_under_lock(lock_guard, &self.repo, &releases) {
242                warn!("Failed to write release cache: {e}");
243            }
244
245            return Ok(select_upgrade_from_releases(
246                &releases,
247                &self.current_version,
248                self.channel,
249                self.pending_upgrade_version.as_ref(),
250            ));
251        }
252
253        // No cache configured — fetch directly
254        let releases = self.fetch_releases_from_api().await?;
255        Ok(select_upgrade_from_releases(
256            &releases,
257            &self.current_version,
258            self.channel,
259            self.pending_upgrade_version.as_ref(),
260        ))
261    }
262
263    /// Check for available updates with staged rollout awareness.
264    ///
265    /// This method:
266    /// 1. Checks GitHub for available updates
267    /// 2. If staged rollout is enabled and an upgrade is found:
268    ///    - Starts tracking the upgrade detection time
269    ///    - Returns `None` until the calculated delay has passed
270    ///    - Returns the upgrade info once the node is ready to apply it
271    ///
272    /// # Errors
273    ///
274    /// Returns an error if the GitHub API request fails.
275    pub async fn check_for_ready_upgrade(&mut self) -> Result<Option<UpgradeInfo>> {
276        let upgrade_info = self.check_for_updates().await?;
277
278        let Some(info) = upgrade_info else {
279            // No upgrade available - reset tracking state
280            self.pending_upgrade_detected = None;
281            self.pending_upgrade_version = None;
282            return Ok(None);
283        };
284
285        // If staged rollout is not enabled, return immediately
286        let Some(ref rollout) = self.staged_rollout else {
287            let restart_time = chrono::Utc::now();
288            info!(
289                "Node will stop/restart for upgrade at {}",
290                restart_time.to_rfc3339()
291            );
292            return Ok(Some(info));
293        };
294
295        // Check if this is a new version or we're still tracking the same one
296        let is_new_version = self
297            .pending_upgrade_version
298            .as_ref()
299            .map_or(true, |v| *v != info.version);
300
301        if is_new_version {
302            // New version detected - start rollout timer
303            self.pending_upgrade_detected = Some(Instant::now());
304            self.pending_upgrade_version = Some(info.version.clone());
305
306            let delay = rollout.calculate_delay_for_version(&info.version);
307            let restart_time = chrono::Utc::now()
308                + chrono::Duration::from_std(delay).unwrap_or_else(|_| chrono::Duration::hours(1));
309            info!(
310                new_version = %info.version,
311                delay_hours = delay.as_secs() / 3600,
312                delay_minutes = (delay.as_secs() % 3600) / 60,
313                "New version detected, staged rollout delay calculated"
314            );
315            info!(
316                "Node will stop/restart for upgrade at {}",
317                restart_time.to_rfc3339()
318            );
319        }
320
321        // Calculate if we're past the rollout delay
322        let Some(detected_at) = self.pending_upgrade_detected else {
323            // Should not happen, but handle gracefully
324            warn!("Pending upgrade detected but no timestamp recorded");
325            return Ok(Some(info));
326        };
327
328        let delay = rollout.calculate_delay_for_version(&info.version);
329        let elapsed = detected_at.elapsed();
330
331        if elapsed >= delay {
332            info!(
333                version = %info.version,
334                "Staged rollout delay elapsed, ready to upgrade"
335            );
336            Ok(Some(info))
337        } else {
338            let remaining = delay.saturating_sub(elapsed);
339            debug!(
340                "Staged rollout: {}h {}m remaining before upgrade to {}",
341                remaining.as_secs() / 3600,
342                (remaining.as_secs() % 3600) / 60,
343                info.version
344            );
345            Ok(None)
346        }
347    }
348
349    /// Fetch releases from the GitHub API.
350    async fn fetch_releases_from_api(&self) -> Result<Vec<GitHubRelease>> {
351        let api_url = format!("https://api.github.com/repos/{}/releases", self.repo);
352        debug!("Checking for updates from: {}", api_url);
353
354        let response = self
355            .client
356            .get(&api_url)
357            .header("Accept", "application/vnd.github+json")
358            .send()
359            .await
360            .map_err(|e| Error::Network(format!("GitHub API request failed: {e}")))?;
361
362        if !response.status().is_success() {
363            return Err(Error::Network(format!(
364                "GitHub API returned status: {}",
365                response.status()
366            )));
367        }
368
369        response
370            .json()
371            .await
372            .map_err(|e| Error::Network(format!("Failed to parse releases: {e}")))
373    }
374
375    /// Get the remaining time until this node should upgrade.
376    ///
377    /// Returns `None` if no upgrade is pending or staged rollout is disabled.
378    #[must_use]
379    pub fn time_until_upgrade(&self) -> Option<Duration> {
380        let rollout = self.staged_rollout.as_ref()?;
381        let version = self.pending_upgrade_version.as_ref()?;
382        let detected_at = self.pending_upgrade_detected?;
383
384        let delay = rollout.calculate_delay_for_version(version);
385        let elapsed = detected_at.elapsed();
386
387        if elapsed >= delay {
388            Some(Duration::ZERO)
389        } else {
390            Some(delay.saturating_sub(elapsed))
391        }
392    }
393
394    /// Check if staged rollout is enabled.
395    #[must_use]
396    pub fn has_staged_rollout(&self) -> bool {
397        self.staged_rollout.is_some()
398    }
399
400    /// Get the pending upgrade version, if any.
401    #[must_use]
402    pub fn pending_version(&self) -> Option<&Version> {
403        self.pending_upgrade_version.as_ref()
404    }
405
406    /// Process a GitHub release and determine if an upgrade is available.
407    #[allow(dead_code)]
408    fn process_release(&self, release: &GitHubRelease) -> Option<UpgradeInfo> {
409        let latest_version = version_from_tag(&release.tag_name)?;
410
411        // Check if newer
412        if latest_version <= self.current_version {
413            debug!("Current version {} is up to date", self.current_version);
414            return None;
415        }
416
417        // Check channel filter
418        if !self.version_matches_channel(&latest_version) {
419            debug!(
420                "Version {} doesn't match channel {:?}",
421                latest_version, self.channel
422            );
423            return None;
424        }
425
426        if is_redundant_beta_promotion(&latest_version, &self.current_version, self.channel) {
427            debug!("Skipping {latest_version}: promotion of the beta already running");
428            return None;
429        }
430
431        // Find platform assets
432        let binary_asset = find_platform_asset(&release.assets)?;
433
434        let sig_name = format!("{}.sig", binary_asset.name);
435        let sig_asset = release.assets.iter().find(|a| a.name == sig_name)?;
436
437        info!(
438            current_version = %self.current_version,
439            new_version = %latest_version,
440            "New version available"
441        );
442
443        Some(UpgradeInfo {
444            version: latest_version,
445            download_url: binary_asset.browser_download_url.clone(),
446            signature_url: sig_asset.browser_download_url.clone(),
447            release_notes: release.body.clone(),
448        })
449    }
450}
451
452/// Check whether a version is eligible for the given upgrade channel.
453///
454/// - Stable: only final releases, i.e. no pre-release component at all.
455/// - Beta: final releases, plus pre-releases whose first identifier is exactly `beta`
456///   (`0.17.0-beta.1`, `0.17.0-beta`).
457///
458/// Every other pre-release suffix is rejected on both channels. In particular `-rc.*`
459/// is not a beta candidate: release candidates are published before the release gates
460/// have given a verdict, and semver ranks `-rc` above `-beta`, so accepting them would
461/// pull beta nodes off their soak build and onto un-gated code.
462#[must_use]
463fn version_matches_channel(version: &Version, channel: UpgradeChannel) -> bool {
464    if version.pre.is_empty() {
465        return true;
466    }
467
468    match channel {
469        UpgradeChannel::Stable => false,
470        UpgradeChannel::Beta => is_beta_prerelease(version),
471    }
472}
473
474/// Whether a version's pre-release component marks it as a beta build.
475///
476/// Matches on the exact first identifier, so `0.17.0-beta.1` and `0.17.0-beta` qualify while
477/// `0.17.0-betax.1` does not.
478#[must_use]
479fn is_beta_prerelease(version: &Version) -> bool {
480    version.pre.as_str().split('.').next() == Some("beta")
481}
482
483/// Whether upgrading to `candidate` would only trade a beta build for its own promotion.
484///
485/// Promoting `X.Y.Z-beta.N` to the final `X.Y.Z` re-tags the same code, so a node already running
486/// that beta would swap its binary and restart for no behavioural change. Semver ranks the final
487/// above the pre-release, so without this the hop would happen on every release train, to every
488/// beta node.
489///
490/// Only the matching final is skipped. A genuinely newer final — `0.19.0` while running
491/// `0.18.0-beta.1` — is still taken, so a node does not stagnate if the beta line stalls.
492///
493/// `current` is the build the node is *committed to*, which during a staged rollout is the target
494/// it has already selected rather than the one it is still running. Without that, a node part-way
495/// through its rollout delay for `0.19.0-beta.1` would compare `0.19.0` against the older
496/// `0.18.0-beta.1`, find the cores differ, and take the final instead — so whether a node kept its
497/// beta identity would depend on where its rollout jitter fell.
498///
499/// Beta channel only: a node running a beta build while configured for `stable` should land on the
500/// final, since that is its route back to the stable line.
501#[must_use]
502fn is_redundant_beta_promotion(
503    candidate: &Version,
504    current: &Version,
505    channel: UpgradeChannel,
506) -> bool {
507    channel == UpgradeChannel::Beta
508        && candidate.pre.is_empty()
509        && is_beta_prerelease(current)
510        && (candidate.major, candidate.minor, candidate.patch)
511            == (current.major, current.minor, current.patch)
512}
513
514/// Select the most appropriate upgrade from a list of releases.
515///
516/// Only versions eligible for the channel are considered, and a beta node skips the promotion of
517/// the build it is committed to; see `version_matches_channel` and `is_redundant_beta_promotion`.
518///
519/// Returns the newest version that matches the channel and has platform assets.
520fn select_upgrade_from_releases(
521    releases: &[GitHubRelease],
522    current_version: &Version,
523    channel: UpgradeChannel,
524    pending_version: Option<&Version>,
525) -> Option<UpgradeInfo> {
526    // The build this node is committed to: the staged-rollout target it has already selected if
527    // there is one, otherwise whatever it is running. Only the redundancy check uses this — the
528    // "is it newer" guard stays on the running version, so a withdrawn pending release cannot
529    // strand the node above everything still published.
530    let committed_version = pending_version.unwrap_or(current_version);
531    let mut best: Option<UpgradeInfo> = None;
532
533    for release in releases {
534        let Some(version) = version_from_tag(&release.tag_name) else {
535            continue;
536        };
537
538        if version <= *current_version {
539            continue;
540        }
541
542        if !version_matches_channel(&version, channel) {
543            continue;
544        }
545
546        if is_redundant_beta_promotion(&version, committed_version, channel) {
547            debug!("Skipping {version}: promotion of the beta already running");
548            continue;
549        }
550
551        let Some(binary_asset) = find_platform_asset(&release.assets) else {
552            continue;
553        };
554
555        let sig_name = format!("{}.sig", binary_asset.name);
556        let Some(sig_asset) = release.assets.iter().find(|a| a.name == sig_name) else {
557            continue;
558        };
559
560        let candidate = UpgradeInfo {
561            version: version.clone(),
562            download_url: binary_asset.browser_download_url.clone(),
563            signature_url: sig_asset.browser_download_url.clone(),
564            release_notes: release.body.clone(),
565        };
566
567        let should_replace = best
568            .as_ref()
569            .map_or(true, |b| candidate.version > b.version);
570
571        if should_replace {
572            best = Some(candidate);
573        }
574    }
575
576    best
577}
578
579/// Parse version from git tag.
580///
581/// Handles both "v1.2.3" and "1.2.3" formats.
582#[must_use]
583pub fn version_from_tag(tag: &str) -> Option<Version> {
584    let version_str = tag.strip_prefix('v').unwrap_or(tag);
585    Version::parse(version_str).ok()
586}
587
588/// Find the appropriate binary asset for the current platform.
589///
590/// Looks for assets matching the current OS and architecture.
591/// On Windows, also looks for `.exe` suffixed binaries.
592#[must_use]
593pub fn find_platform_asset(assets: &[Asset]) -> Option<&Asset> {
594    let arch = std::env::consts::ARCH;
595    let os = std::env::consts::OS;
596
597    // Build platform-specific patterns
598    let patterns = build_platform_patterns(arch, os);
599
600    // Try each pattern in order of specificity
601    for pattern in &patterns {
602        if let Some(asset) = assets
603            .iter()
604            .find(|a| a.name.contains(pattern) && is_binary_asset(&a.name))
605        {
606            return Some(asset);
607        }
608    }
609
610    None
611}
612
613/// Check if an asset name represents a downloadable binary or archive.
614///
615/// This includes direct executables, as well as archive formats (`.tar.gz`, `.zip`)
616/// that contain binaries.
617#[allow(clippy::case_sensitive_file_extension_comparisons)]
618fn is_binary_asset(name: &str) -> bool {
619    let lower = name.to_lowercase();
620
621    // Exclude signatures and other non-binary files (already lowercased above)
622    if lower.ends_with(".sig")
623        || lower.ends_with(".sha256")
624        || lower.ends_with(".md5")
625        || lower.ends_with(".txt")
626        || lower.ends_with(".md")
627        || lower.ends_with(".deb")
628        || lower.ends_with(".rpm")
629        || lower.ends_with(".msi")
630    {
631        return false;
632    }
633
634    // Accept archive formats on all platforms
635    if lower.ends_with(".tar.gz") || lower.ends_with(".zip") {
636        return true;
637    }
638
639    // On Windows, prefer .exe files for direct binary downloads
640    #[cfg(windows)]
641    if !lower.ends_with(".exe") {
642        return false;
643    }
644
645    true
646}
647
648/// Build platform-specific search patterns.
649fn build_platform_patterns(arch: &str, os: &str) -> Vec<String> {
650    let mut patterns = Vec::new();
651
652    // Map arch to common naming conventions
653    let arch_patterns: Vec<&str> = match arch {
654        "x86_64" => vec!["x86_64", "amd64", "x64"],
655        "aarch64" => vec!["aarch64", "arm64"],
656        "x86" => vec!["i686", "i386", "x86"],
657        _ => vec![arch],
658    };
659
660    // Map OS to common naming conventions
661    let os_patterns: Vec<&str> = match os {
662        "linux" => vec!["linux", "unknown-linux-gnu", "linux-gnu"],
663        "macos" => vec!["darwin", "macos", "apple-darwin"],
664        "windows" => vec!["windows", "pc-windows-msvc", "win64"],
665        _ => vec![os],
666    };
667
668    // Generate all combinations
669    for arch_pat in &arch_patterns {
670        for os_pat in &os_patterns {
671            patterns.push(format!("{arch_pat}-{os_pat}"));
672            patterns.push(format!("{os_pat}-{arch_pat}"));
673        }
674    }
675
676    // Add individual patterns as fallback
677    for arch_pat in &arch_patterns {
678        patterns.push((*arch_pat).to_string());
679    }
680
681    patterns
682}
683
684#[cfg(test)]
685#[allow(
686    clippy::unwrap_used,
687    clippy::expect_used,
688    clippy::case_sensitive_file_extension_comparisons
689)]
690mod tests {
691    use super::*;
692
693    /// Test 1: Version comparison - newer available
694    #[test]
695    fn test_version_newer_available() {
696        let current = Version::new(1, 0, 0);
697        let latest = Version::new(1, 1, 0);
698        assert!(latest > current);
699    }
700
701    /// Test 2: Version comparison - same version
702    #[test]
703    fn test_version_same() {
704        let current = Version::new(1, 0, 0);
705        let latest = Version::new(1, 0, 0);
706        assert!(latest <= current);
707    }
708
709    /// Test 3: Version comparison - older available (downgrade prevention)
710    #[test]
711    fn test_version_older_rejected() {
712        let current = Version::new(1, 1, 0);
713        let latest = Version::new(1, 0, 0);
714        assert!(latest <= current);
715    }
716
717    /// Test 4: Pre-release handling
718    #[test]
719    fn test_prerelease_version() {
720        let stable = Version::parse("1.0.0").unwrap();
721        let beta = Version::parse("1.1.0-beta.1").unwrap();
722        // Beta 1.1.0 considered newer than stable 1.0.0
723        assert!(beta > stable);
724    }
725
726    /// Test 5: Channel filtering - stable only
727    #[test]
728    fn test_stable_channel_filters_beta() {
729        let monitor = UpgradeMonitor::new(
730            "WithAutonomi/ant-node".to_string(),
731            UpgradeChannel::Stable,
732            24,
733        );
734
735        let beta_version = Version::parse("1.0.0-beta.1").unwrap();
736        assert!(!monitor.version_matches_channel(&beta_version));
737
738        let stable_version = Version::parse("1.0.0").unwrap();
739        assert!(monitor.version_matches_channel(&stable_version));
740    }
741
742    /// Test 5b: Stable rejects release candidates too
743    #[test]
744    fn test_stable_channel_filters_rc() {
745        let monitor = UpgradeMonitor::new(
746            "WithAutonomi/ant-node".to_string(),
747            UpgradeChannel::Stable,
748            24,
749        );
750
751        assert!(!monitor.version_matches_channel(&Version::parse("1.0.0-rc.1").unwrap()));
752        assert!(monitor.version_matches_channel(&Version::parse("1.0.0").unwrap()));
753    }
754
755    /// Test 6: Channel filtering - beta includes beta
756    #[test]
757    fn test_beta_channel_accepts_beta() {
758        let monitor = UpgradeMonitor::new(
759            "WithAutonomi/ant-node".to_string(),
760            UpgradeChannel::Beta,
761            24,
762        );
763
764        let beta_version = Version::parse("1.0.0-beta.1").unwrap();
765        assert!(monitor.version_matches_channel(&beta_version));
766
767        let stable_version = Version::parse("1.0.0").unwrap();
768        assert!(monitor.version_matches_channel(&stable_version));
769    }
770
771    /// Test 6b: Beta rejects release candidates and any other pre-release suffix
772    #[test]
773    fn test_beta_channel_rejects_rc() {
774        let monitor = UpgradeMonitor::new(
775            "WithAutonomi/ant-node".to_string(),
776            UpgradeChannel::Beta,
777            24,
778        );
779
780        assert!(!monitor.version_matches_channel(&Version::parse("1.0.0-rc.1").unwrap()));
781        assert!(!monitor.version_matches_channel(&Version::parse("1.0.0-alpha.1").unwrap()));
782        // Only an exact `beta` identifier qualifies, not a prefix match.
783        assert!(!monitor.version_matches_channel(&Version::parse("1.0.0-betax.1").unwrap()));
784        assert!(monitor.version_matches_channel(&Version::parse("1.0.0-beta").unwrap()));
785    }
786
787    /// Test 7: Parse GitHub release response
788    #[test]
789    fn test_parse_github_release() {
790        let json = r#"{
791            "tag_name": "v1.2.0",
792            "name": "Release 1.2.0",
793            "body": "Release notes here",
794            "prerelease": false,
795            "assets": [
796                {
797                    "name": "ant-node-x86_64-unknown-linux-gnu",
798                    "browser_download_url": "https://example.com/binary"
799                },
800                {
801                    "name": "ant-node-x86_64-unknown-linux-gnu.sig",
802                    "browser_download_url": "https://example.com/binary.sig"
803                }
804            ]
805        }"#;
806
807        let release: GitHubRelease = serde_json::from_str(json).unwrap();
808        assert_eq!(release.tag_name, "v1.2.0");
809        assert_eq!(release.name, "Release 1.2.0");
810        assert_eq!(release.body, "Release notes here");
811        assert!(!release.prerelease);
812        assert_eq!(release.assets.len(), 2);
813    }
814
815    /// Test 8: Extract version from tag
816    #[test]
817    fn test_version_from_tag() {
818        assert_eq!(version_from_tag("v1.2.3"), Some(Version::new(1, 2, 3)));
819        assert_eq!(version_from_tag("1.2.3"), Some(Version::new(1, 2, 3)));
820        assert_eq!(
821            version_from_tag("v1.0.0-beta.1"),
822            Some(Version::parse("1.0.0-beta.1").unwrap())
823        );
824        assert_eq!(version_from_tag("invalid"), None);
825        assert_eq!(version_from_tag(""), None);
826    }
827
828    /// Test 9: Find correct asset for platform
829    #[test]
830    fn test_find_platform_asset() {
831        // Test with archive format (CLI releases)
832        let assets = vec![
833            Asset {
834                name: "ant-node-cli-linux-x64.tar.gz".to_string(),
835                browser_download_url: "https://example.com/linux".to_string(),
836            },
837            Asset {
838                name: "ant-node-cli-linux-x64.tar.gz.sig".to_string(),
839                browser_download_url: "https://example.com/linux.sig".to_string(),
840            },
841            Asset {
842                name: "ant-node-cli-macos-arm64.tar.gz".to_string(),
843                browser_download_url: "https://example.com/macos".to_string(),
844            },
845            Asset {
846                name: "ant-node-cli-macos-arm64.tar.gz.sig".to_string(),
847                browser_download_url: "https://example.com/macos.sig".to_string(),
848            },
849            Asset {
850                name: "ant-node-cli-windows-x64.zip".to_string(),
851                browser_download_url: "https://example.com/windows".to_string(),
852            },
853            Asset {
854                name: "ant-node-cli-windows-x64.zip.sig".to_string(),
855                browser_download_url: "https://example.com/windows.sig".to_string(),
856            },
857        ];
858
859        let asset = find_platform_asset(&assets);
860        assert!(asset.is_some(), "Should find platform asset");
861        let asset = asset.unwrap();
862        // Should not be a .sig file
863        assert!(!asset.name.to_lowercase().ends_with(".sig"));
864        // Should be an archive
865        let lower = asset.name.to_lowercase();
866        assert!(
867            lower.ends_with(".tar.gz") || lower.ends_with(".zip"),
868            "Should be an archive format"
869        );
870    }
871
872    /// Test: `is_binary_asset` correctly identifies binaries and archives
873    #[test]
874    fn test_is_binary_asset() {
875        // Archive formats should be identified (CLI releases)
876        assert!(is_binary_asset("ant-node-cli-linux-x64.tar.gz"));
877        assert!(is_binary_asset("ant-node-cli-macos-arm64.tar.gz"));
878        assert!(is_binary_asset("ant-node-cli-windows-x64.zip"));
879
880        // Signature and metadata files should be excluded
881        assert!(!is_binary_asset("ant-node.sig"));
882        assert!(!is_binary_asset("ant-node.sha256"));
883        assert!(!is_binary_asset("ant-node.md5"));
884        assert!(!is_binary_asset("RELEASE_NOTES.txt"));
885        assert!(!is_binary_asset("README.md"));
886
887        // Installer packages should be excluded (handled separately)
888        assert!(!is_binary_asset("ant-node.deb"));
889        assert!(!is_binary_asset("ant-node.rpm"));
890        assert!(!is_binary_asset("ant-node.msi"));
891    }
892
893    /// Test 10: Monitor check interval
894    #[test]
895    fn test_check_interval() {
896        let monitor = UpgradeMonitor::new("test/repo".to_string(), UpgradeChannel::Stable, 24);
897        assert_eq!(monitor.check_interval(), Duration::from_secs(24 * 3600));
898
899        let monitor2 = UpgradeMonitor::new("test/repo".to_string(), UpgradeChannel::Stable, 6);
900        assert_eq!(monitor2.check_interval(), Duration::from_secs(6 * 3600));
901    }
902
903    /// Test 11: Process release - upgrade available
904    #[test]
905    fn test_process_release_upgrade_available() {
906        let monitor = UpgradeMonitor::with_version(
907            "test/repo".to_string(),
908            UpgradeChannel::Stable,
909            24,
910            Version::new(1, 0, 0),
911        );
912
913        // Build platform-specific archive name using friendly naming
914        let (friendly_os, archive_ext) = match std::env::consts::OS {
915            "linux" => ("linux", "tar.gz"),
916            "macos" => ("macos", "tar.gz"),
917            "windows" => ("windows", "zip"),
918            _ => ("unknown", "tar.gz"),
919        };
920        let friendly_arch = match std::env::consts::ARCH {
921            "x86_64" => "x64",
922            "aarch64" => "arm64",
923            _ => std::env::consts::ARCH,
924        };
925        let archive_name = format!("ant-node-cli-{friendly_os}-{friendly_arch}.{archive_ext}");
926
927        let release = GitHubRelease {
928            tag_name: "v1.1.0".to_string(),
929            name: "Release 1.1.0".to_string(),
930            body: "New features".to_string(),
931            prerelease: false,
932            assets: vec![
933                Asset {
934                    name: archive_name.clone(),
935                    browser_download_url: "https://example.com/binary".to_string(),
936                },
937                Asset {
938                    name: format!("{archive_name}.sig"),
939                    browser_download_url: "https://example.com/binary.sig".to_string(),
940                },
941            ],
942        };
943
944        let result = monitor.process_release(&release);
945        assert!(result.is_some(), "Should find upgrade");
946        let info = result.unwrap();
947        assert_eq!(info.version, Version::new(1, 1, 0));
948        assert_eq!(info.release_notes, "New features");
949    }
950
951    /// Test 12: Process release - no upgrade (same version)
952    #[test]
953    fn test_process_release_no_upgrade_same_version() {
954        let monitor = UpgradeMonitor::with_version(
955            "test/repo".to_string(),
956            UpgradeChannel::Stable,
957            24,
958            Version::new(1, 0, 0),
959        );
960
961        let release = GitHubRelease {
962            tag_name: "v1.0.0".to_string(),
963            name: "Release 1.0.0".to_string(),
964            body: "Current version".to_string(),
965            prerelease: false,
966            assets: vec![],
967        };
968
969        let result = monitor.process_release(&release);
970        assert!(result.is_none(), "Should not find upgrade for same version");
971    }
972
973    /// Test 13: Process release - no upgrade (older version)
974    #[test]
975    fn test_process_release_no_upgrade_older_version() {
976        let monitor = UpgradeMonitor::with_version(
977            "test/repo".to_string(),
978            UpgradeChannel::Stable,
979            24,
980            Version::new(1, 1, 0),
981        );
982
983        let release = GitHubRelease {
984            tag_name: "v1.0.0".to_string(),
985            name: "Release 1.0.0".to_string(),
986            body: "Old version".to_string(),
987            prerelease: false,
988            assets: vec![],
989        };
990
991        let result = monitor.process_release(&release);
992        assert!(
993            result.is_none(),
994            "Should not find upgrade for older version"
995        );
996    }
997
998    /// Test 14: Process release - beta filtered by stable channel
999    #[test]
1000    fn test_process_release_beta_filtered() {
1001        let monitor = UpgradeMonitor::with_version(
1002            "test/repo".to_string(),
1003            UpgradeChannel::Stable,
1004            24,
1005            Version::new(1, 0, 0),
1006        );
1007
1008        let release = GitHubRelease {
1009            tag_name: "v1.1.0-beta.1".to_string(),
1010            name: "Beta Release".to_string(),
1011            body: "Beta features".to_string(),
1012            prerelease: true,
1013            assets: vec![],
1014        };
1015
1016        let result = monitor.process_release(&release);
1017        assert!(
1018            result.is_none(),
1019            "Stable channel should filter beta releases"
1020        );
1021    }
1022
1023    /// Test 15: Monitor repo getter
1024    #[test]
1025    fn test_monitor_repo() {
1026        let monitor = UpgradeMonitor::new(
1027            "WithAutonomi/ant-node".to_string(),
1028            UpgradeChannel::Stable,
1029            24,
1030        );
1031        assert_eq!(monitor.repo(), "WithAutonomi/ant-node");
1032    }
1033
1034    /// Test 16: Current version getter
1035    #[test]
1036    fn test_monitor_current_version() {
1037        let monitor = UpgradeMonitor::with_version(
1038            "test/repo".to_string(),
1039            UpgradeChannel::Stable,
1040            24,
1041            Version::new(2, 3, 4),
1042        );
1043        assert_eq!(*monitor.current_version(), Version::new(2, 3, 4));
1044    }
1045
1046    /// Test 17: Build platform patterns
1047    #[test]
1048    fn test_build_platform_patterns() {
1049        let patterns = build_platform_patterns("x86_64", "linux");
1050        assert!(patterns.iter().any(|p| p.contains("x86_64")));
1051        assert!(patterns.iter().any(|p| p.contains("x64")));
1052        assert!(patterns.iter().any(|p| p.contains("linux")));
1053
1054        let patterns_arm = build_platform_patterns("aarch64", "macos");
1055        assert!(patterns_arm
1056            .iter()
1057            .any(|p| p.contains("aarch64") || p.contains("arm64")));
1058        assert!(patterns_arm
1059            .iter()
1060            .any(|p| p.contains("darwin") || p.contains("macos")));
1061    }
1062
1063    /// Test 18: Invalid tag handling
1064    #[test]
1065    fn test_process_release_invalid_tag() {
1066        let monitor = UpgradeMonitor::with_version(
1067            "test/repo".to_string(),
1068            UpgradeChannel::Stable,
1069            24,
1070            Version::new(1, 0, 0),
1071        );
1072
1073        let release = GitHubRelease {
1074            tag_name: "not-a-version".to_string(),
1075            name: "Invalid Release".to_string(),
1076            body: "Invalid".to_string(),
1077            prerelease: false,
1078            assets: vec![],
1079        };
1080
1081        let result = monitor.process_release(&release);
1082        assert!(result.is_none(), "Should gracefully handle invalid tag");
1083    }
1084
1085    #[test]
1086    fn test_select_upgrade_stable_ignores_prerelease() {
1087        let current = Version::new(1, 0, 0);
1088        let arch = std::env::consts::ARCH;
1089        let os = std::env::consts::OS;
1090        // On Windows, binary assets require .exe extension
1091        #[cfg(windows)]
1092        let bin_name = format!("ant-node-{arch}-{os}.exe");
1093        #[cfg(not(windows))]
1094        let bin_name = format!("ant-node-{arch}-{os}");
1095        let releases = vec![
1096            GitHubRelease {
1097                tag_name: "v1.1.0-beta.1".to_string(),
1098                name: "beta".to_string(),
1099                body: "beta".to_string(),
1100                prerelease: true,
1101                assets: vec![
1102                    Asset {
1103                        name: bin_name.clone(),
1104                        browser_download_url: "https://example.com/beta".to_string(),
1105                    },
1106                    Asset {
1107                        name: format!("{bin_name}.sig"),
1108                        browser_download_url: "https://example.com/beta.sig".to_string(),
1109                    },
1110                ],
1111            },
1112            GitHubRelease {
1113                tag_name: "v1.1.0".to_string(),
1114                name: "stable".to_string(),
1115                body: "stable".to_string(),
1116                prerelease: false,
1117                assets: vec![
1118                    Asset {
1119                        name: bin_name.clone(),
1120                        browser_download_url: "https://example.com/stable".to_string(),
1121                    },
1122                    Asset {
1123                        name: format!("{bin_name}.sig"),
1124                        browser_download_url: "https://example.com/stable.sig".to_string(),
1125                    },
1126                ],
1127            },
1128        ];
1129
1130        let upgrade =
1131            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Stable, None)
1132                .unwrap();
1133        assert_eq!(upgrade.version, Version::new(1, 1, 0));
1134        assert!(upgrade.download_url.contains("stable"));
1135    }
1136
1137    #[test]
1138    fn test_select_upgrade_beta_accepts_prerelease_if_newest() {
1139        let current = Version::new(1, 0, 0);
1140        let arch = std::env::consts::ARCH;
1141        let os = std::env::consts::OS;
1142        // On Windows, binary assets require .exe extension
1143        #[cfg(windows)]
1144        let bin_name = format!("ant-node-{arch}-{os}.exe");
1145        #[cfg(not(windows))]
1146        let bin_name = format!("ant-node-{arch}-{os}");
1147        let releases = vec![
1148            GitHubRelease {
1149                tag_name: "v1.1.0".to_string(),
1150                name: "stable".to_string(),
1151                body: "stable".to_string(),
1152                prerelease: false,
1153                assets: vec![
1154                    Asset {
1155                        name: bin_name.clone(),
1156                        browser_download_url: "https://example.com/stable".to_string(),
1157                    },
1158                    Asset {
1159                        name: format!("{bin_name}.sig"),
1160                        browser_download_url: "https://example.com/stable.sig".to_string(),
1161                    },
1162                ],
1163            },
1164            GitHubRelease {
1165                tag_name: "v1.2.0-beta.1".to_string(),
1166                name: "beta".to_string(),
1167                body: "beta".to_string(),
1168                prerelease: true,
1169                assets: vec![
1170                    Asset {
1171                        name: bin_name.clone(),
1172                        browser_download_url: "https://example.com/beta".to_string(),
1173                    },
1174                    Asset {
1175                        name: format!("{bin_name}.sig"),
1176                        browser_download_url: "https://example.com/beta.sig".to_string(),
1177                    },
1178                ],
1179            },
1180        ];
1181
1182        let upgrade =
1183            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Beta, None).unwrap();
1184        assert_eq!(upgrade.version, Version::parse("1.2.0-beta.1").unwrap());
1185        assert!(upgrade.download_url.contains("beta"));
1186    }
1187
1188    /// Build a release fixture carrying the platform binary and its signature, so that
1189    /// `select_upgrade_from_releases` does not skip it for missing assets.
1190    fn release_with_assets(tag: &str) -> GitHubRelease {
1191        let arch = std::env::consts::ARCH;
1192        let os = std::env::consts::OS;
1193        #[cfg(windows)]
1194        let bin_name = format!("ant-node-{arch}-{os}.exe");
1195        #[cfg(not(windows))]
1196        let bin_name = format!("ant-node-{arch}-{os}");
1197
1198        GitHubRelease {
1199            tag_name: tag.to_string(),
1200            name: tag.to_string(),
1201            body: format!("notes for {tag}"),
1202            prerelease: tag.contains('-'),
1203            assets: vec![
1204                Asset {
1205                    name: bin_name.clone(),
1206                    browser_download_url: format!("https://example.com/{tag}"),
1207                },
1208                Asset {
1209                    name: format!("{bin_name}.sig"),
1210                    browser_download_url: format!("https://example.com/{tag}.sig"),
1211                },
1212            ],
1213        }
1214    }
1215
1216    /// Mixed release list: stable takes the final, beta takes the beta, neither takes the rc.
1217    #[test]
1218    fn test_select_upgrade_never_picks_rc() {
1219        let current = Version::parse("0.15.0").unwrap();
1220        let releases = vec![
1221            release_with_assets("v0.16.0"),
1222            release_with_assets("v0.17.0-beta.1"),
1223            release_with_assets("v0.17.0-rc.1"),
1224        ];
1225
1226        let stable =
1227            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Stable, None)
1228                .unwrap();
1229        assert_eq!(stable.version, Version::parse("0.16.0").unwrap());
1230
1231        let beta =
1232            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Beta, None).unwrap();
1233        assert_eq!(beta.version, Version::parse("0.17.0-beta.1").unwrap());
1234    }
1235
1236    /// A beta node does not restart onto the promotion of the build it is already running:
1237    /// `0.18.0-beta.1` -> `0.18.0` re-tags the same code.
1238    #[test]
1239    fn test_select_upgrade_beta_skips_own_promotion() {
1240        let current = Version::parse("0.18.0-beta.1").unwrap();
1241        let releases = vec![release_with_assets("v0.18.0")];
1242
1243        assert!(
1244            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Beta, None).is_none(),
1245            "beta node should stay on 0.18.0-beta.1 when only its own promotion is published"
1246        );
1247    }
1248
1249    /// A node part-way through its staged rollout for `0.19.0-beta.1` holds that target when the
1250    /// promoted `0.19.0` appears, instead of being retargeted onto the final.
1251    #[test]
1252    fn test_select_upgrade_beta_holds_pending_beta_against_its_promotion() {
1253        let current = Version::parse("0.18.0-beta.1").unwrap();
1254        let pending = Version::parse("0.19.0-beta.1").unwrap();
1255        let releases = vec![
1256            release_with_assets("v0.19.0-beta.1"),
1257            release_with_assets("v0.19.0"),
1258        ];
1259
1260        let upgrade =
1261            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Beta, Some(&pending))
1262                .unwrap();
1263        assert_eq!(upgrade.version, Version::parse("0.19.0-beta.1").unwrap());
1264    }
1265
1266    /// Without a pending target the same release pair resolves to the final: the node is running
1267    /// `0.18.0-beta.1`, whose core differs from `0.19.0`, so nothing marks the final redundant.
1268    /// This is what makes threading the pending target through necessary.
1269    #[test]
1270    fn test_select_upgrade_beta_without_pending_takes_the_final() {
1271        let current = Version::parse("0.18.0-beta.1").unwrap();
1272        let releases = vec![
1273            release_with_assets("v0.19.0-beta.1"),
1274            release_with_assets("v0.19.0"),
1275        ];
1276
1277        let upgrade =
1278            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Beta, None).unwrap();
1279        assert_eq!(upgrade.version, Version::parse("0.19.0").unwrap());
1280    }
1281
1282    /// The skip is narrow: a genuinely newer final is still taken, so a beta node does not
1283    /// stagnate if the beta line stalls.
1284    #[test]
1285    fn test_select_upgrade_beta_takes_newer_final() {
1286        let current = Version::parse("0.18.0-beta.1").unwrap();
1287        let releases = vec![
1288            release_with_assets("v0.18.0"),
1289            release_with_assets("v0.19.0"),
1290        ];
1291
1292        let upgrade =
1293            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Beta, None).unwrap();
1294        assert_eq!(upgrade.version, Version::parse("0.19.0").unwrap());
1295    }
1296
1297    /// With its own promotion and a newer beta both published, the beta wins and the promotion is
1298    /// skipped rather than taken first.
1299    #[test]
1300    fn test_select_upgrade_beta_prefers_next_beta_over_own_promotion() {
1301        let current = Version::parse("0.18.0-beta.1").unwrap();
1302        let releases = vec![
1303            release_with_assets("v0.18.0"),
1304            release_with_assets("v0.19.0-beta.1"),
1305        ];
1306
1307        let upgrade =
1308            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Beta, None).unwrap();
1309        assert_eq!(upgrade.version, Version::parse("0.19.0-beta.1").unwrap());
1310    }
1311
1312    /// The skip is beta-channel only. A node running a beta build but configured for stable takes
1313    /// the final, since that is its route back onto the stable line.
1314    #[test]
1315    fn test_select_upgrade_stable_takes_promotion_of_running_beta() {
1316        let current = Version::parse("0.18.0-beta.1").unwrap();
1317        let releases = vec![release_with_assets("v0.18.0")];
1318
1319        let upgrade =
1320            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Stable, None)
1321                .unwrap();
1322        assert_eq!(upgrade.version, Version::parse("0.18.0").unwrap());
1323    }
1324
1325    /// A later beta of the same version is still an upgrade — the skip only covers finals.
1326    #[test]
1327    fn test_select_upgrade_beta_takes_later_beta_of_same_version() {
1328        let current = Version::parse("0.18.0-beta.1").unwrap();
1329        let releases = vec![release_with_assets("v0.18.0-beta.2")];
1330
1331        let upgrade =
1332            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Beta, None).unwrap();
1333        assert_eq!(upgrade.version, Version::parse("0.18.0-beta.2").unwrap());
1334    }
1335
1336    /// Ship-and-promote on the same day: a node soaking `0.16.0-beta.1` sees both the promoted
1337    /// `0.16.0` and the next cut `0.17.0-beta.1`, and hops straight to the new beta.
1338    #[test]
1339    fn test_select_upgrade_beta_ship_and_promote_same_day() {
1340        let current = Version::parse("0.16.0-beta.1").unwrap();
1341        let releases = vec![
1342            release_with_assets("v0.16.0"),
1343            release_with_assets("v0.17.0-beta.1"),
1344        ];
1345
1346        let beta =
1347            select_upgrade_from_releases(&releases, &current, UpgradeChannel::Beta, None).unwrap();
1348        assert_eq!(beta.version, Version::parse("0.17.0-beta.1").unwrap());
1349    }
1350}