Skip to main content

ant_node/upgrade/
apply.rs

1//! Auto-apply upgrade functionality.
2//!
3//! This module handles the complete auto-upgrade workflow:
4//! 1. Download archive from GitHub releases
5//! 2. Extract the binary from tar.gz/zip
6//! 3. Verify ML-DSA signature
7//! 4. Replace running binary with backup
8//! 5. Restart the node process
9
10use crate::error::{Error, Result};
11use crate::logging::{debug, error, info, warn};
12use crate::upgrade::binary_cache::BinaryCache;
13use crate::upgrade::traffic::{self, UpgradeFetch};
14use crate::upgrade::{signature, UpgradeInfo, UpgradeResult};
15use flate2::read::GzDecoder;
16use semver::Version;
17use std::env;
18use std::fs::{self, File};
19use std::io::Read;
20use std::path::{Path, PathBuf};
21use tar::Archive;
22
23/// Maximum allowed upgrade archive size (200 MiB).
24pub(super) const MAX_ARCHIVE_SIZE_BYTES: usize = 200 * 1024 * 1024;
25
26/// Exit code that signals the service manager to restart the process.
27///
28/// On Windows, `trigger_restart` exits with this code instead of using
29/// `exec()`.  The wrapping service (e.g. NSSM or Windows Service) should be
30/// configured to restart on this exit code.
31pub const RESTART_EXIT_CODE: i32 = 100;
32
33/// Auto-apply upgrader with archive support.
34pub struct AutoApplyUpgrader {
35    /// Current running version.
36    current_version: Version,
37    /// HTTP client for downloads.
38    client: reqwest::Client,
39    /// Shared binary cache (optional).
40    binary_cache: Option<BinaryCache>,
41    /// When true, exit cleanly for service manager restart instead of spawning.
42    stop_on_upgrade: bool,
43}
44
45impl AutoApplyUpgrader {
46    /// Create a new auto-apply upgrader.
47    #[must_use]
48    pub fn new() -> Self {
49        let current_version =
50            Version::parse(env!("CARGO_PKG_VERSION")).unwrap_or_else(|_| Version::new(0, 0, 0));
51
52        Self {
53            current_version,
54            client: reqwest::Client::builder()
55                .user_agent(concat!("ant-node/", env!("CARGO_PKG_VERSION")))
56                .timeout(std::time::Duration::from_mins(5))
57                .build()
58                .unwrap_or_else(|_| reqwest::Client::new()),
59            binary_cache: None,
60            stop_on_upgrade: false,
61        }
62    }
63
64    /// Configure a shared binary cache for downloaded upgrades.
65    ///
66    /// When set, `apply_upgrade` will check the cache before downloading
67    /// and store freshly verified binaries so other nodes can reuse them.
68    #[must_use]
69    pub fn with_binary_cache(mut self, cache: BinaryCache) -> Self {
70        self.binary_cache = Some(cache);
71        self
72    }
73
74    /// Configure the upgrader to exit cleanly instead of spawning a new process.
75    ///
76    /// When enabled, the node exits after applying an upgrade, relying on an
77    /// external service manager (systemd, launchd, Windows Service) to restart it.
78    #[must_use]
79    pub fn with_stop_on_upgrade(mut self, stop: bool) -> Self {
80        self.stop_on_upgrade = stop;
81        self
82    }
83
84    /// Get the current version.
85    #[must_use]
86    pub fn current_version(&self) -> &Version {
87        &self.current_version
88    }
89
90    /// Get the path to the currently running binary.
91    ///
92    /// On Linux, `/proc/self/exe` may have a `" (deleted)"` suffix when the on-disk binary has
93    /// been replaced by another node's upgrade. This function strips that suffix so that backup
94    /// creation, binary replacement, and restart all target the correct on-disk path.
95    ///
96    /// # Errors
97    ///
98    /// Returns an error if the binary path cannot be determined.
99    pub fn current_binary_path() -> Result<PathBuf> {
100        // Prefer the invoked path (argv[0]) if it exists, as it preserves symlinks.
101        // Fall back to current_exe() which resolves symlinks via /proc/self/exe.
102        let invoked_path = env::args().next().map(PathBuf::from);
103
104        if let Some(ref invoked) = invoked_path {
105            // Check for "(deleted)" suffix first — on Linux, /proc/self/exe
106            // reports this when the on-disk binary has been replaced. The
107            // `exists()` check below would return false for the suffixed path,
108            // so we must strip it before testing existence.
109            let path_str = invoked.to_string_lossy();
110            let cleaned = if path_str.ends_with(" (deleted)") {
111                let stripped = path_str.trim_end_matches(" (deleted)");
112                debug!("Stripped '(deleted)' suffix from invoked path: {stripped}");
113                PathBuf::from(stripped)
114            } else {
115                invoked.clone()
116            };
117
118            if cleaned.exists() {
119                // Canonicalize to an absolute path so that trigger_restart
120                // works even if the CWD has changed since startup.
121                if let Ok(canonical) = cleaned.canonicalize() {
122                    return Ok(canonical);
123                }
124                return Ok(cleaned);
125            }
126        }
127
128        // Fall back to current_exe (resolves symlinks on Linux)
129        let path = env::current_exe()
130            .map_err(|e| Error::Upgrade(format!("Cannot determine binary path: {e}")))?;
131
132        #[cfg(unix)]
133        {
134            let path_str = path.to_string_lossy();
135            if path_str.ends_with(" (deleted)") {
136                let cleaned = path_str.trim_end_matches(" (deleted)");
137                debug!("Stripped '(deleted)' suffix from binary path: {cleaned}");
138                return Ok(PathBuf::from(cleaned));
139            }
140        }
141
142        Ok(path)
143    }
144
145    /// Perform the complete auto-apply upgrade workflow.
146    ///
147    /// # Arguments
148    ///
149    /// * `info` - Upgrade information from the monitor
150    ///
151    /// # Returns
152    ///
153    /// Returns `UpgradeResult::Success` and triggers a restart on success.
154    /// Returns `UpgradeResult::RolledBack` if any step fails.
155    ///
156    /// # Errors
157    ///
158    /// Returns an error only for critical failures where rollback also fails.
159    pub async fn apply_upgrade(&self, info: &UpgradeInfo) -> Result<UpgradeResult> {
160        info!(
161            "Starting auto-apply upgrade from {} to {}",
162            self.current_version, info.version
163        );
164
165        // Validate upgrade (prevent downgrade)
166        if info.version <= self.current_version {
167            warn!(
168                "Ignoring downgrade attempt: {} -> {}",
169                self.current_version, info.version
170            );
171            return Ok(UpgradeResult::NoUpgrade);
172        }
173
174        // Get current binary path
175        let current_binary = Self::current_binary_path()?;
176        let binary_dir = current_binary
177            .parent()
178            .ok_or_else(|| Error::Upgrade("Cannot determine binary directory".to_string()))?;
179
180        // Create temp directory for upgrade.
181        //
182        // On Unix, create it with 0700 so a same-host attacker on a different
183        // UID cannot read/write the staging area between when the cache
184        // re-verifies the ML-DSA signature on a private copy and when
185        // `extract_binary` reads it (closes a verify-vs-extract TOCTOU on
186        // the staging directory). The `tempfile::Builder::permissions`
187        // path is supported on tempfile 3 — on platforms that don't honour
188        // it the call is a no-op and the ML-DSA verification on the
189        // private copy still bounds the residual.
190        let mut tempdir_builder = tempfile::Builder::new();
191        tempdir_builder.prefix("ant-upgrade-");
192        #[cfg(unix)]
193        {
194            use std::os::unix::fs::PermissionsExt;
195            tempdir_builder.permissions(std::fs::Permissions::from_mode(0o700));
196        }
197        let temp_dir = tempdir_builder
198            .tempdir_in(binary_dir)
199            .map_err(|e| Error::Upgrade(format!("Failed to create temp dir: {e}")))?;
200
201        let version_str = info.version.to_string();
202
203        // Try the binary cache first; download/verify/extract errors are
204        // recoverable and result in RolledBack rather than a hard error.
205        let extracted_binary = match self
206            .resolve_upgrade_binary(info, temp_dir.path(), &version_str)
207            .await
208        {
209            Ok(path) => path,
210            Err(e) => {
211                warn!("Download/verify/extract failed: {e}");
212                return Ok(UpgradeResult::RolledBack {
213                    reason: format!("{e}"),
214                });
215            }
216        };
217
218        // Check if the on-disk binary has already been upgraded by a sibling service.
219        // This prevents redundant backup/replace cycles when multiple nodes share one binary.
220        if let Some(disk_version) = on_disk_version(&current_binary).await {
221            if disk_version == info.version {
222                info!(
223                    "Binary already upgraded to {} by another service, skipping replacement",
224                    info.version
225                );
226                let exit_code = self.prepare_restart(&current_binary)?;
227                return Ok(UpgradeResult::Success {
228                    version: info.version.clone(),
229                    exit_code,
230                });
231            }
232        }
233
234        // Step 5: Create backup of current binary
235        let backup_path = binary_dir.join(format!(
236            "{}.backup",
237            current_binary
238                .file_name()
239                .map_or_else(|| "ant-node".into(), |s| s.to_string_lossy())
240        ));
241        info!("Creating backup at {}...", backup_path.display());
242        if let Err(e) = fs::copy(&current_binary, &backup_path) {
243            warn!("Backup creation failed: {e}");
244            return Ok(UpgradeResult::RolledBack {
245                reason: format!("Backup failed: {e}"),
246            });
247        }
248
249        // Step 6: Replace binary (offloaded to blocking thread to avoid
250        // starving the tokio runtime, especially on Windows where retries sleep)
251        info!("Replacing binary...");
252        let new_bin = extracted_binary.clone();
253        let target_bin = current_binary.clone();
254        let replace_result =
255            tokio::task::spawn_blocking(move || Self::replace_binary(&new_bin, &target_bin))
256                .await
257                .map_err(|e| Error::Upgrade(format!("Binary replacement task panicked: {e}")))?;
258        if let Err(e) = replace_result {
259            warn!("Binary replacement failed: {e}");
260            // Attempt rollback
261            if let Err(restore_err) = fs::copy(&backup_path, &current_binary) {
262                error!("CRITICAL: Replacement failed ({e}) AND rollback failed ({restore_err})");
263                return Err(Error::Upgrade(format!(
264                    "Critical: replacement failed ({e}) AND rollback failed ({restore_err})"
265                )));
266            }
267            return Ok(UpgradeResult::RolledBack {
268                reason: format!("Replacement failed: {e}"),
269            });
270        }
271
272        info!(
273            "Successfully upgraded to version {}! Restarting...",
274            info.version
275        );
276
277        // Step 7: Prepare restart (spawn new process if standalone mode)
278        let exit_code = self.prepare_restart(&current_binary)?;
279
280        Ok(UpgradeResult::Success {
281            version: info.version.clone(),
282            exit_code,
283        })
284    }
285
286    /// Download a file to the specified path.
287    async fn download(&self, url: &str, dest: &Path, kind: UpgradeFetch) -> Result<()> {
288        debug!("Downloading: {}", url);
289
290        // V2-834: count the body once fully read; anything short of that is
291        // an error for this fetch kind.
292        let bytes = match self.fetch_body(url).await {
293            Ok(bytes) => bytes,
294            Err(e) => {
295                traffic::record_error(kind);
296                return Err(e);
297            }
298        };
299        traffic::record_rx(kind, bytes.len());
300
301        if bytes.len() > MAX_ARCHIVE_SIZE_BYTES {
302            return Err(Error::Upgrade(format!(
303                "Downloaded file too large: {} bytes (max {})",
304                bytes.len(),
305                MAX_ARCHIVE_SIZE_BYTES
306            )));
307        }
308
309        fs::write(dest, &bytes)?;
310        debug!("Downloaded {} bytes to {}", bytes.len(), dest.display());
311        Ok(())
312    }
313
314    /// GET `url` and read the whole body.
315    async fn fetch_body(&self, url: &str) -> Result<bytes::Bytes> {
316        let response = self
317            .client
318            .get(url)
319            .send()
320            .await
321            .map_err(|e| Error::Network(format!("Download failed: {e}")))?;
322
323        if !response.status().is_success() {
324            return Err(Error::Network(format!(
325                "Download returned status: {}",
326                response.status()
327            )));
328        }
329
330        response
331            .bytes()
332            .await
333            .map_err(|e| Error::Network(format!("Failed to read response: {e}")))
334    }
335
336    /// Resolve the upgrade binary, checking the cache first and falling back
337    /// to a full download/verify/extract cycle.
338    ///
339    /// On a cache miss the exclusive download lock is acquired (via
340    /// `spawn_blocking` to avoid blocking the tokio runtime), the cache is
341    /// re-checked, and if still missing the full download runs while the lock
342    /// is held so that only one node downloads per version.
343    async fn resolve_upgrade_binary(
344        &self,
345        info: &UpgradeInfo,
346        dest_dir: &Path,
347        version_str: &str,
348    ) -> Result<PathBuf> {
349        if let Some(ref cache) = self.binary_cache {
350            // Fast path — cache hit without locking. The cache re-verifies
351            // the ML-DSA signature over the archive on every call, so a
352            // tampered cache entry returns None here and we fall through to
353            // a fresh, fully verified download.
354            // `dest_dir` is this upgrade's process-private temp dir, so the
355            // cache stages + verifies the archive there; extraction then
356            // reads exactly the verified bytes (no shared-file TOCTOU).
357            if let Some(verified_archive) = cache.get_verified_archive(version_str, dest_dir) {
358                match Self::extract_binary(&verified_archive, dest_dir) {
359                    Ok(binary) => {
360                        info!("Reused signature-verified cached archive for {version_str}");
361                        return Ok(binary);
362                    }
363                    Err(e) => {
364                        warn!("Failed to extract from cached archive, will re-download: {e}");
365                        return self
366                            .download_verify_extract(info, dest_dir, Some(cache))
367                            .await;
368                    }
369                }
370            }
371
372            // Cache miss — acquire exclusive download lock via spawn_blocking
373            // to avoid blocking the tokio runtime while waiting for the lock.
374            let cache_clone = cache.clone();
375            // Named `lock_guard` (not `_lock_guard`) so the compiler keeps it
376            // alive across the `.await` below — dropping it would release the
377            // file lock before the download completes.
378            let lock_guard =
379                tokio::task::spawn_blocking(move || cache_clone.acquire_download_lock())
380                    .await
381                    .map_err(|e| Error::Upgrade(format!("Lock task failed: {e}")))??;
382
383            // Re-check cache under the lock — another node may have populated
384            // it. Same re-verification guarantee as the fast path.
385            if let Some(verified_archive) = cache.get_verified_archive(version_str, dest_dir) {
386                if let Ok(binary) = Self::extract_binary(&verified_archive, dest_dir) {
387                    info!(
388                        "Signature-verified cached archive became available under lock for {version_str}"
389                    );
390                    return Ok(binary);
391                }
392            }
393
394            // Still missing — download while holding the lock
395            let result = self
396                .download_verify_extract(info, dest_dir, Some(cache))
397                .await;
398            drop(lock_guard);
399            result
400        } else {
401            self.download_verify_extract(info, dest_dir, None).await
402        }
403    }
404
405    /// Download archive, verify signature, extract binary, and optionally
406    /// store in the binary cache.
407    ///
408    /// # Errors
409    ///
410    /// Returns an error if any step (download, signature verification,
411    /// extraction) fails.
412    async fn download_verify_extract(
413        &self,
414        info: &UpgradeInfo,
415        dest_dir: &Path,
416        cache: Option<&BinaryCache>,
417    ) -> Result<PathBuf> {
418        let archive_path = dest_dir.join("archive");
419        let sig_path = dest_dir.join("signature");
420
421        // Step 1: Download archive
422        info!("Downloading ant-node binary...");
423        self.download(&info.download_url, &archive_path, UpgradeFetch::Archive)
424            .await?;
425
426        // Step 2: Download signature
427        info!("Downloading signature...");
428        self.download(&info.signature_url, &sig_path, UpgradeFetch::Signature)
429            .await?;
430
431        // Step 3: Verify signature on archive BEFORE extraction
432        info!("Verifying ML-DSA signature on archive...");
433        signature::verify_from_file(&archive_path, &sig_path)?;
434        info!("Archive signature verified successfully");
435
436        // Step 4: Extract binary from the just-verified archive.
437        info!("Extracting binary from archive...");
438        let extracted_binary = Self::extract_binary(&archive_path, dest_dir)?;
439
440        // Step 5: Cache the signature-verified ARCHIVE (+ its signature)
441        // AFTER successful extraction. We cache the signed artifact, never
442        // the extracted binary, so every later cache hit can re-verify the
443        // signature. Caching only after extract proves the archive is
444        // actually usable on this platform avoids turning a
445        // validly-signed-but-malformed release into a shared cache poison
446        // pill (every later node would hit cache, fail extract, and
447        // re-download).
448        if let Some(c) = cache {
449            let version_str = info.version.to_string();
450            if let Err(e) = c.store_archive(&version_str, &archive_path, &sig_path) {
451                warn!("Failed to store verified archive in cache: {e}");
452            }
453        }
454
455        Ok(extracted_binary)
456    }
457
458    /// Extract the ant-node binary from an archive (tar.gz or zip).
459    ///
460    /// The archive format is detected by magic bytes:
461    /// - `1f 8b` → gzip (tar.gz)
462    /// - `50 4b` → zip
463    fn extract_binary(archive_path: &Path, dest_dir: &Path) -> Result<PathBuf> {
464        let mut file = File::open(archive_path)?;
465        let mut magic = [0u8; 2];
466        file.read_exact(&mut magic)
467            .map_err(|e| Error::Upgrade(format!("Failed to read archive header: {e}")))?;
468        drop(file);
469
470        match magic {
471            [0x1f, 0x8b] => Self::extract_from_tar_gz(archive_path, dest_dir),
472            [0x50, 0x4b] => Self::extract_from_zip(archive_path, dest_dir),
473            _ => Err(Error::Upgrade(format!(
474                "Unknown archive format (magic bytes: {:02x} {:02x})",
475                magic[0], magic[1]
476            ))),
477        }
478    }
479
480    /// Extract the ant-node binary from a tar.gz archive.
481    fn extract_from_tar_gz(archive_path: &Path, dest_dir: &Path) -> Result<PathBuf> {
482        let file = File::open(archive_path)?;
483        let decoder = GzDecoder::new(file);
484        let mut archive = Archive::new(decoder);
485
486        let binary_name = if cfg!(windows) {
487            "ant-node.exe"
488        } else {
489            "ant-node"
490        };
491        let extracted_binary = dest_dir.join(binary_name);
492
493        for entry in archive
494            .entries()
495            .map_err(|e| Error::Upgrade(format!("Failed to read archive: {e}")))?
496        {
497            let mut entry =
498                entry.map_err(|e| Error::Upgrade(format!("Failed to read entry: {e}")))?;
499            let path = entry
500                .path()
501                .map_err(|e| Error::Upgrade(format!("Invalid path in archive: {e}")))?;
502
503            // Look for the ant-node binary
504            if let Some(name) = path.file_name() {
505                let name_str = name.to_string_lossy();
506                if name_str == "ant-node" || name_str == "ant-node.exe" {
507                    debug!("Found binary in tar.gz archive: {}", path.display());
508
509                    // Stream directly to disk to avoid large heap allocations
510                    let mut out = File::create(&extracted_binary)?;
511                    std::io::copy(&mut entry, &mut out)
512                        .map_err(|e| Error::Upgrade(format!("Failed to write binary: {e}")))?;
513
514                    // Make executable on Unix
515                    #[cfg(unix)]
516                    {
517                        use std::os::unix::fs::PermissionsExt;
518                        let mut perms = fs::metadata(&extracted_binary)?.permissions();
519                        perms.set_mode(0o755);
520                        fs::set_permissions(&extracted_binary, perms)?;
521                    }
522
523                    return Ok(extracted_binary);
524                }
525            }
526        }
527
528        Err(Error::Upgrade(
529            "ant-node binary not found in tar.gz archive".to_string(),
530        ))
531    }
532
533    /// Extract the ant-node binary from a zip archive.
534    fn extract_from_zip(archive_path: &Path, dest_dir: &Path) -> Result<PathBuf> {
535        let file = File::open(archive_path)?;
536        let mut archive = zip::ZipArchive::new(file)
537            .map_err(|e| Error::Upgrade(format!("Failed to open zip archive: {e}")))?;
538
539        let binary_name = if cfg!(windows) {
540            "ant-node.exe"
541        } else {
542            "ant-node"
543        };
544        let extracted_binary = dest_dir.join(binary_name);
545
546        for i in 0..archive.len() {
547            let mut entry = archive
548                .by_index(i)
549                .map_err(|e| Error::Upgrade(format!("Failed to read zip entry: {e}")))?;
550
551            let path = match entry.enclosed_name() {
552                Some(p) => p.clone(),
553                None => continue,
554            };
555
556            if let Some(name) = path.file_name() {
557                let name_str = name.to_string_lossy();
558                if name_str == "ant-node" || name_str == "ant-node.exe" {
559                    debug!("Found binary in zip archive: {}", path.display());
560
561                    // Stream directly to disk to avoid large heap allocations
562                    let mut out = File::create(&extracted_binary)?;
563                    std::io::copy(&mut entry, &mut out)
564                        .map_err(|e| Error::Upgrade(format!("Failed to write binary: {e}")))?;
565
566                    // Make executable on Unix
567                    #[cfg(unix)]
568                    {
569                        use std::os::unix::fs::PermissionsExt;
570                        let mut perms = fs::metadata(&extracted_binary)?.permissions();
571                        perms.set_mode(0o755);
572                        fs::set_permissions(&extracted_binary, perms)?;
573                    }
574
575                    return Ok(extracted_binary);
576                }
577            }
578        }
579
580        Err(Error::Upgrade(
581            "ant-node binary not found in zip archive".to_string(),
582        ))
583    }
584
585    /// Replace the current binary with the new one.
586    ///
587    /// This is a blocking operation (filesystem I/O, and on Windows potentially
588    /// retries with back-off). Call via `spawn_blocking` from async context.
589    fn replace_binary(new_binary: &Path, target: &Path) -> Result<()> {
590        #[cfg(unix)]
591        {
592            // Preserve original permissions on Unix
593            if let Ok(meta) = fs::metadata(target) {
594                let perms = meta.permissions();
595                fs::set_permissions(new_binary, perms)?;
596            }
597            // Atomic rename
598            fs::rename(new_binary, target)?;
599        }
600
601        #[cfg(windows)]
602        {
603            let _ = target; // target is the current exe — self_replace handles it
604                            // Retry with back-off: Windows file locks may delay replacement
605            let delays = [500u64, 1000, 2000];
606            let mut last_err = None;
607            for (attempt, delay_ms) in delays.iter().enumerate() {
608                match self_replace::self_replace(new_binary) {
609                    Ok(()) => {
610                        last_err = None;
611                        break;
612                    }
613                    Err(e) => {
614                        warn!(
615                            "self_replace attempt {} failed: {e}, retrying in {delay_ms}ms",
616                            attempt + 1
617                        );
618                        last_err = Some(e);
619                        std::thread::sleep(std::time::Duration::from_millis(*delay_ms));
620                    }
621                }
622            }
623            if let Some(e) = last_err {
624                return Err(Error::Upgrade(format!(
625                    "self_replace failed after retries: {e}"
626                )));
627            }
628        }
629
630        debug!("Binary replacement complete");
631        Ok(())
632    }
633
634    /// Prepare for a restart after a successful upgrade.
635    ///
636    /// Returns the exit code that the process should use after graceful shutdown.
637    /// The caller is responsible for triggering graceful shutdown (e.g. via
638    /// `CancellationToken`) and then calling `std::process::exit()` with the
639    /// returned code **after** all async cleanup has completed.
640    ///
641    /// **Service manager mode** (`stop_on_upgrade = true`):
642    /// Returns exit code 0 on Unix or [`RESTART_EXIT_CODE`] on Windows so the
643    /// service manager (systemd, launchd, Windows Service) restarts the process.
644    ///
645    /// **Standalone mode** (`stop_on_upgrade = false`):
646    /// Spawns the new binary as a child process with the same arguments, then
647    /// returns exit code 0.
648    fn prepare_restart(&self, binary_path: &Path) -> Result<i32> {
649        if self.stop_on_upgrade {
650            let exit_code;
651
652            #[cfg(unix)]
653            {
654                info!("Service manager mode: will exit with code 0 after graceful shutdown");
655                exit_code = 0;
656            }
657
658            #[cfg(windows)]
659            {
660                let _ = binary_path;
661                info!(
662                    "Service manager mode: will exit with code {} after graceful shutdown",
663                    RESTART_EXIT_CODE
664                );
665                exit_code = RESTART_EXIT_CODE;
666            }
667
668            #[cfg(not(any(unix, windows)))]
669            {
670                let _ = binary_path;
671                warn!("Auto-restart not supported on this platform. Please restart manually.");
672                exit_code = 0;
673            }
674
675            Ok(exit_code)
676        } else {
677            // Standalone mode: spawn new process, then exit after graceful shutdown
678            let args: Vec<String> = env::args().skip(1).collect();
679
680            info!("Spawning new process: {} {:?}", binary_path.display(), args);
681
682            std::process::Command::new(binary_path)
683                .args(&args)
684                .stdin(std::process::Stdio::null())
685                .stdout(std::process::Stdio::inherit())
686                .stderr(std::process::Stdio::inherit())
687                .spawn()
688                .map_err(|e| Error::Upgrade(format!("Failed to spawn new binary: {e}")))?;
689
690            info!("New process spawned, will exit after graceful shutdown");
691            Ok(0)
692        }
693    }
694}
695
696/// Run the on-disk binary with `--version` and parse the reported version.
697///
698/// Returns `None` if the binary cannot be executed, times out, or the output
699/// cannot be parsed.  Uses `tokio::process::Command` with a 5-second timeout
700/// to avoid blocking the async runtime.
701///
702/// Output format is expected to be "ant-node X.Y.Z" or "ant-node X.Y.Z-rc.N".
703async fn on_disk_version(binary_path: &Path) -> Option<Version> {
704    let output = tokio::time::timeout(
705        std::time::Duration::from_secs(5),
706        tokio::process::Command::new(binary_path)
707            .arg("--version")
708            .output(),
709    )
710    .await
711    .ok()?
712    .ok()?;
713    let stdout = String::from_utf8_lossy(&output.stdout);
714    let version_str = stdout.trim().strip_prefix("ant-node ")?;
715    Version::parse(version_str).ok()
716}
717
718impl Default for AutoApplyUpgrader {
719    fn default() -> Self {
720        Self::new()
721    }
722}
723
724#[cfg(test)]
725#[allow(clippy::unwrap_used, clippy::expect_used)]
726mod tests {
727    use super::*;
728
729    #[test]
730    fn test_auto_apply_upgrader_creation() {
731        let upgrader = AutoApplyUpgrader::new();
732        assert!(
733            !upgrader.current_version().to_string().is_empty(),
734            "expected a non-empty current version"
735        );
736    }
737
738    #[test]
739    fn test_current_binary_path() {
740        let result = AutoApplyUpgrader::current_binary_path();
741        assert!(result.is_ok());
742        let path = result.unwrap();
743        assert!(path.exists() || path.to_string_lossy().contains("test"));
744    }
745
746    #[test]
747    fn test_default_impl() {
748        let upgrader = AutoApplyUpgrader::default();
749        assert!(
750            !upgrader.current_version().to_string().is_empty(),
751            "expected a non-empty current version"
752        );
753    }
754
755    /// Helper: create a tar.gz archive containing a fake binary.
756    fn create_tar_gz_archive(dir: &Path, binary_name: &str, content: &[u8]) -> PathBuf {
757        use flate2::write::GzEncoder;
758        use flate2::Compression;
759
760        let archive_path = dir.join("test.tar.gz");
761        let file = File::create(&archive_path).unwrap();
762        let encoder = GzEncoder::new(file, Compression::default());
763        let mut builder = tar::Builder::new(encoder);
764
765        let mut header = tar::Header::new_gnu();
766        header.set_size(content.len() as u64);
767        header.set_mode(0o755);
768        header.set_cksum();
769        builder
770            .append_data(&mut header, binary_name, content)
771            .unwrap();
772        builder.finish().unwrap();
773
774        archive_path
775    }
776
777    /// Helper: create a zip archive containing a fake binary.
778    fn create_zip_archive(dir: &Path, binary_name: &str, content: &[u8]) -> PathBuf {
779        use std::io::Write;
780
781        let archive_path = dir.join("test.zip");
782        let file = File::create(&archive_path).unwrap();
783        let mut zip_writer = zip::ZipWriter::new(file);
784        let options = zip::write::SimpleFileOptions::default()
785            .compression_method(zip::CompressionMethod::Stored);
786        zip_writer.start_file(binary_name, options).unwrap();
787        zip_writer.write_all(content).unwrap();
788        zip_writer.finish().unwrap();
789
790        archive_path
791    }
792
793    #[test]
794    fn test_extract_binary_from_tar_gz() {
795        let dir = tempfile::tempdir().unwrap();
796        let content = b"fake-binary-content";
797        let archive = create_tar_gz_archive(dir.path(), "ant-node", content);
798
799        let dest = tempfile::tempdir().unwrap();
800        let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
801        assert!(result.is_ok());
802
803        let extracted = result.unwrap();
804        assert!(extracted.exists());
805        assert_eq!(fs::read(&extracted).unwrap(), content);
806    }
807
808    #[test]
809    fn test_extract_binary_from_zip() {
810        let dir = tempfile::tempdir().unwrap();
811        let content = b"fake-binary-content";
812        let archive = create_zip_archive(dir.path(), "ant-node", content);
813
814        let dest = tempfile::tempdir().unwrap();
815        let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
816        assert!(result.is_ok());
817
818        let extracted = result.unwrap();
819        assert!(extracted.exists());
820        assert_eq!(fs::read(&extracted).unwrap(), content);
821    }
822
823    #[test]
824    fn test_extract_binary_from_zip_with_exe() {
825        let dir = tempfile::tempdir().unwrap();
826        let content = b"fake-windows-binary";
827        let archive = create_zip_archive(dir.path(), "ant-node.exe", content);
828
829        let dest = tempfile::tempdir().unwrap();
830        let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
831        assert!(result.is_ok());
832
833        let extracted = result.unwrap();
834        assert!(extracted.exists());
835        assert_eq!(fs::read(&extracted).unwrap(), content);
836    }
837
838    #[test]
839    fn test_extract_binary_from_tar_gz_nested_path() {
840        let dir = tempfile::tempdir().unwrap();
841        let content = b"nested-binary";
842        let archive = create_tar_gz_archive(dir.path(), "some/nested/path/ant-node", content);
843
844        let dest = tempfile::tempdir().unwrap();
845        let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
846        assert!(result.is_ok());
847
848        let extracted = result.unwrap();
849        assert!(extracted.exists());
850        assert_eq!(fs::read(&extracted).unwrap(), content);
851    }
852
853    #[test]
854    fn test_extract_binary_unknown_format() {
855        let dir = tempfile::tempdir().unwrap();
856        let archive_path = dir.path().join("bad_archive");
857        fs::write(&archive_path, b"XX not a real archive").unwrap();
858
859        let dest = tempfile::tempdir().unwrap();
860        let result = AutoApplyUpgrader::extract_binary(&archive_path, dest.path());
861        assert!(result.is_err());
862
863        let err = result.unwrap_err().to_string();
864        assert!(err.contains("Unknown archive format"));
865    }
866
867    #[test]
868    fn test_extract_binary_missing_binary_in_tar_gz() {
869        let dir = tempfile::tempdir().unwrap();
870        let content = b"not-the-binary";
871        let archive = create_tar_gz_archive(dir.path(), "other-file", content);
872
873        let dest = tempfile::tempdir().unwrap();
874        let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
875        assert!(result.is_err());
876
877        let err = result.unwrap_err().to_string();
878        assert!(err.contains("not found in tar.gz archive"));
879    }
880
881    #[test]
882    fn test_extract_binary_missing_binary_in_zip() {
883        let dir = tempfile::tempdir().unwrap();
884        let content = b"not-the-binary";
885        let archive = create_zip_archive(dir.path(), "other-file", content);
886
887        let dest = tempfile::tempdir().unwrap();
888        let result = AutoApplyUpgrader::extract_binary(&archive, dest.path());
889        assert!(result.is_err());
890
891        let err = result.unwrap_err().to_string();
892        assert!(err.contains("not found in zip archive"));
893    }
894
895    #[test]
896    fn test_extract_binary_empty_file() {
897        let dir = tempfile::tempdir().unwrap();
898        let archive_path = dir.path().join("empty");
899        fs::write(&archive_path, b"").unwrap();
900
901        let dest = tempfile::tempdir().unwrap();
902        let result = AutoApplyUpgrader::extract_binary(&archive_path, dest.path());
903        assert!(result.is_err());
904    }
905}