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