ctb_workspace/
update_status.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Background update checking for ctoolbox.
21//!
22//! This module handles automatic update checking at startup:
23//! - Generates a random time-of-day on first run and stores it in `pc_settings`
24//! - Spawns a detached task that waits until the scheduled time (or runs
25//!   immediately if past) and checks for updates
26//! - Stores update status in memory accessible by other parts of the process
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35use ctb_build_info::build_info;
36
37use std::path::PathBuf;
38use std::sync::LazyLock;
39use std::time::Duration;
40
41use jiff::{Timestamp, Zoned};
42use rand::Rng;
43use serde::{Deserialize, Serialize};
44use tokio::sync::RwLock;
45use tokio::time::timeout;
46
47use ctb_installer::download::{
48    ChunkDownloader, current_platform, no_progress_callback,
49};
50use ctb_utilities::json::maybe_value::MaybeOption;
51use ctb_utilities::pc_settings::{PcSettingBoolKey, PcSettings};
52use ctb_utilities::storage::get_storage_dir;
53
54/// Seconds in a day (24 hours).
55const SECONDS_IN_DAY: u32 = 86400;
56
57/// Global update status stored in memory.
58static UPDATE_STATUS: LazyLock<RwLock<UpdateStatus>> =
59    LazyLock::new(|| RwLock::new(UpdateStatus::new()));
60
61#[derive(Debug, Clone)]
62struct BuildIdentity {
63    version: semver::Version,
64    build_date: Timestamp,
65}
66
67#[derive(Debug, Deserialize)]
68struct ServerUpdateStatusResponse {
69    is_newer: bool,
70    server_version: String,
71    server_build_date: String,
72}
73
74/// Status of available updates.
75#[derive(Debug, Clone, Default, Serialize, Deserialize)]
76pub struct UpdateStatus {
77    /// Whether an update is available.
78    pub available: bool,
79    /// The new version string (if available).
80    pub version: Option<String>,
81    /// URL to release notes (if available).
82    pub release_notes_url: Option<String>,
83    /// Last time we checked for updates.
84    #[serde(default, with = "ctb_utilities::time::serde_rfc3339_auto_si_opt")]
85    pub last_check: Option<Timestamp>,
86    /// Error message if the last check failed.
87    pub last_error: Option<String>,
88    /// Whether automatic restart is enabled (no user prompting).
89    /// This is true when `serve_public_web_site_only` is on and the domain
90    /// is not the official collectivetoolbox.com domain.
91    #[serde(default)]
92    pub auto_restart_enabled: bool,
93}
94
95impl UpdateStatus {
96    /// Creates a new empty update status.
97    pub fn new() -> Self {
98        Self::default()
99    }
100}
101
102/// Record of a pending update that has been fully downloaded and is ready to
103/// install. This is written to disk so it persists across restarts.
104#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct PendingUpdate {
106    /// Version that will be installed.
107    pub version: String,
108    /// Path to the downloaded binary.
109    pub binary_path: PathBuf,
110    /// Timestamp when the download completed.
111    #[serde(with = "ctb_utilities::time::serde_rfc3339_auto_si")]
112    pub download_completed: Timestamp,
113}
114
115impl PendingUpdate {
116    /// Path to the pending update file in the storage directory.
117    fn file_path() -> Result<PathBuf> {
118        Ok(get_storage_dir()?.join("pending_update.json"))
119    }
120
121    /// Saves this pending update record to disk.
122    ///
123    /// # Errors
124    /// Returns an error if the file cannot be written.
125    pub fn save(&self) -> Result<()> {
126        let path = Self::file_path()?;
127        let json = serde_json::to_string_pretty(self)
128            .context("Failed to serialize pending update")?;
129        std::fs::write(&path, json).with_context(|| {
130            format!("Failed to write pending update to {path:?}")
131        })
132    }
133
134    /// Loads a pending update record from disk, if one exists.
135    ///
136    /// # Returns
137    /// `Ok(Some(pending))` if a valid pending update exists
138    /// `Ok(None)` if no pending update file exists
139    ///
140    /// # Errors
141    /// Returns an error if the file exists but cannot be read or parsed.
142    pub fn load() -> Result<Option<Self>> {
143        let path = Self::file_path()?;
144        if !path.exists() {
145            return Ok(None);
146        }
147
148        let json = std::fs::read_to_string(&path).with_context(|| {
149            format!("Failed to read pending update from {path:?}")
150        })?;
151        let pending: Self = serde_json::from_str(&json)
152            .context("Failed to parse pending update JSON")?;
153
154        // Verify the binary still exists
155        if !pending.binary_path.exists() {
156            // Binary was deleted - remove the stale record
157            Self::clear()?;
158            return Ok(None);
159        }
160
161        Ok(Some(pending))
162    }
163
164    /// Removes the pending update record from disk.
165    ///
166    /// # Errors
167    /// Returns an error if the file cannot be deleted.
168    pub fn clear() -> Result<()> {
169        let path = Self::file_path()?;
170        if path.exists() {
171            std::fs::remove_file(&path).with_context(|| {
172                format!("Failed to remove pending update file {path:?}")
173            })?;
174        }
175        Ok(())
176    }
177}
178
179/// Gets the current update status as a JSON string.
180///
181/// # Errors
182/// Returns an error if serialization fails.
183#[ipc_method]
184pub async fn get_update_status() -> Result<String> {
185    let status = UPDATE_STATUS.read().await;
186    serde_json::to_string_pretty(&*status)
187        .context("Failed to serialize update status")
188}
189
190/// Gets the update check time from settings, generating one if not present.
191///
192/// The time is stored as seconds since midnight (0-86400).
193///
194/// # Errors
195/// Returns an error if settings cannot be loaded or saved.
196pub fn get_or_generate_update_check_time() -> Result<u32> {
197    let settings = PcSettings::load()?;
198
199    // Check if we already have a time set
200    if let MaybeOption::Value(time) = settings.update_check_time {
201        return Ok(time);
202    }
203
204    // Generate a random time between 0 and 86400 seconds (24 hours)
205    let mut rng = rand::rng();
206    let random_time: u32 = rng.random_range(0..SECONDS_IN_DAY);
207
208    // Save to settings
209    PcSettings::apply_patch(PcSettings {
210        update_check_time: MaybeOption::Value(random_time),
211        ..Default::default()
212    })?;
213
214    log_fmt!(
215        "Generated random update check time: {:02}:{:02}:{:02}",
216        random_time / 3600,
217        (random_time % 3600) / 60,
218        random_time % 60
219    );
220
221    Ok(random_time)
222}
223
224/// Resolves the version that should be used for update comparisons.
225///
226/// Prefers the installed version from `installation.json`, but falls back to
227/// the currently running build version so web UI update checks still work when
228/// ctoolbox is running without a persisted installation record.
229fn parse_build_date(build_date: &str) -> Result<Timestamp> {
230    ctb_utilities::time::parse_rfc3339(build_date).with_context(|| {
231        format!(
232            "Failed to parse build timestamp for update checks: {build_date}"
233        )
234    })
235}
236
237fn current_build_identity_for_update_checks() -> Result<BuildIdentity> {
238    let current_build = build_info();
239    Ok(BuildIdentity {
240        version: semver::Version::parse(&current_build.version).with_context(
241            || {
242                format!(
243                    "Failed to parse running build version for update checks: {}",
244                    current_build.version
245                )
246            },
247        )?,
248        build_date: parse_build_date(&current_build.build_date)?,
249    })
250}
251
252fn build_update_status_url(
253    server_url: &str,
254    current: &BuildIdentity,
255) -> Result<String> {
256    let api_url =
257        format!("{}/api/update-status", server_url.trim_end_matches('/'));
258    let current_version = current.version.to_string();
259    let current_build_date =
260        ctb_utilities::time::format_rfc3339_auto_si(current.build_date);
261
262    let mut url = reqwest::Url::parse(&api_url)?;
263    url.query_pairs_mut()
264        .append_pair("version", &current_version)
265        .append_pair("build_date", &current_build_date);
266
267    Ok(url.to_string())
268}
269
270async fn query_server_update_status(
271    server_url: &str,
272    current: &BuildIdentity,
273) -> Result<ServerUpdateStatusResponse> {
274    let url_str = build_update_status_url(server_url, current)?;
275    let body_bytes =
276        utilities::https::get_success_with_backoff(&url_str, 10).await?;
277    let body = String::from_utf8(body_bytes)
278        .context("Failed to decode response body as UTF-8")?;
279
280    serde_json::from_str(&body)
281        .context("Failed to parse update-status API response")
282}
283
284async fn query_server_update_status_fast(
285    server_url: &str,
286    current: &BuildIdentity,
287) -> Result<ServerUpdateStatusResponse> {
288    let client = utilities::https::async_client(
289        utilities::https::ClientOptions::startup(),
290    )?;
291    let url_str = build_update_status_url(server_url, current)?;
292    let response = client.get_with_backoff(&url_str, 3).await?;
293    let body = response.text().await?;
294
295    serde_json::from_str(&body)
296        .context("Failed to parse update-status API response")
297}
298
299/// Calculates how many seconds to wait until the scheduled update check time.
300///
301/// If the scheduled time has already passed today, returns 0 (check immediately).
302fn seconds_until_check_time(scheduled_seconds: u32) -> u64 {
303    let current_seconds =
304        ctb_utilities::time::seconds_from_midnight(Zoned::now().time());
305
306    if current_seconds >= scheduled_seconds {
307        // Time has passed today, check immediately
308        0
309    } else {
310        // Wait until the scheduled time
311        u64::from(scheduled_seconds.saturating_sub(current_seconds))
312    }
313}
314
315/// Performs the actual update check.
316///
317/// # Arguments
318/// - `server_url`: URL of the update server
319/// - `auto_restart_enabled`: If true, the update status will flag that the
320///   workspace should restart automatically without prompting
321async fn perform_update_check(server_url: &str, auto_restart_enabled: bool) {
322    log!("Checking for updates...");
323
324    let current_build = match current_build_identity_for_update_checks() {
325        Ok(build) => build,
326        Err(e) => {
327            let status = UpdateStatus {
328                last_check: Some(Timestamp::now()),
329                last_error: Some(format!(
330                    "Failed to determine current version for update check: {e}"
331                )),
332                ..Default::default()
333            };
334            *UPDATE_STATUS.write().await = status.clone();
335            log_fmt!(
336                "Update check skipped: {}",
337                // Reason for fallback: empty string fallback when last_error field is None
338                status.last_error.as_ref().unwrap_or(&String::new())
339            );
340            return;
341        }
342    };
343
344    let api_status =
345        match query_server_update_status(server_url, &current_build).await {
346            Ok(status) => status,
347            Err(e) => {
348                let status = UpdateStatus {
349                    last_check: Some(Timestamp::now()),
350                    last_error: Some(format!(
351                        "Update-status API preflight failed: {e}"
352                    )),
353                    ..Default::default()
354                };
355                *UPDATE_STATUS.write().await = status.clone();
356                warn_fmt!(
357                    "Update-status API preflight failed: {}",
358                    // Reason for fallback: empty string fallback when last_error field is None
359                    status.last_error.as_ref().unwrap_or(&String::new())
360                );
361                return;
362            }
363        };
364
365    if !api_status.is_newer {
366        let status = UpdateStatus {
367            available: false,
368            version: None,
369            release_notes_url: None,
370            last_check: Some(Timestamp::now()),
371            last_error: None,
372            auto_restart_enabled: false,
373        };
374        *UPDATE_STATUS.write().await = status;
375        log_fmt!(
376            "No update available (current: {} @ {})",
377            current_build.version,
378            current_build.build_date
379        );
380        return;
381    }
382
383    // Download latest manifest from server
384    let downloader =
385        match ChunkDownloader::new(server_url, no_progress_callback()) {
386            Ok(d) => d,
387            Err(e) => {
388                let status = UpdateStatus {
389                    last_check: Some(Timestamp::now()),
390                    last_error: Some(format!(
391                        "Failed to create downloader: {e}"
392                    )),
393                    ..Default::default()
394                };
395                *UPDATE_STATUS.write().await = status.clone();
396                warn_fmt!(
397                    "Update check failed: {}",
398                    // Reason for fallback: empty string fallback when last_error field is None
399                    status.last_error.as_ref().unwrap_or(&String::new())
400                );
401                return;
402            }
403        };
404
405    let manifest = match downloader
406        .download_manifest(&current_platform(), None)
407        .await
408    {
409        Ok(m) => m,
410        Err(e) => {
411            let status = UpdateStatus {
412                available: true,
413                version: Some(api_status.server_version.clone()),
414                release_notes_url: Some(format!(
415                    "{server_url}/releases/notes/{}",
416                    api_status.server_version
417                )),
418                last_check: Some(Timestamp::now()),
419                last_error: Some(format!(
420                    "Failed to download manifest after API reported newer build: {e}"
421                )),
422                auto_restart_enabled,
423            };
424            *UPDATE_STATUS.write().await = status.clone();
425            warn_fmt!(
426                "Manifest download failed after API reported newer build: {}",
427                // Reason for fallback: empty string fallback when last_error field is None
428                status.last_error.as_ref().unwrap_or(&String::new())
429            );
430            return;
431        }
432    };
433
434    let latest_version = manifest.ctoolbox_version.clone();
435    let available = api_status.is_newer;
436
437    let status = UpdateStatus {
438        available,
439        version: if available {
440            Some(latest_version.to_string())
441        } else {
442            None
443        },
444        // Build release notes URL from server URL
445        release_notes_url: if available {
446            Some(format!("{server_url}/releases/notes/{latest_version}"))
447        } else {
448            None
449        },
450        last_check: Some(Timestamp::now()),
451        last_error: None,
452        auto_restart_enabled: available && auto_restart_enabled,
453    };
454
455    *UPDATE_STATUS.write().await = status.clone();
456
457    if available {
458        log_fmt!(
459            "Update available: {} ({}) -> {} ({})",
460            current_build.version,
461            current_build.build_date,
462            latest_version,
463            manifest.date
464        );
465        if auto_restart_enabled {
466            log!(
467                "Auto-restart is enabled - update will be applied automatically"
468            );
469        }
470    } else {
471        log_fmt!(
472            "No update available (current: {} @ {})",
473            current_build.version,
474            current_build.build_date
475        );
476    }
477}
478
479/// Spawns the background update checker task.
480///
481/// This task:
482/// 1. Waits until the scheduled time (or runs immediately if past)
483/// 2. Checks for updates from the server
484/// 3. Updates the global status
485///
486/// If `serve_public_web_site_only` is enabled and the domain is the official
487/// collectivetoolbox.com domain, automatic updates are skipped (deployments are
488/// handled separately).
489///
490/// If `serve_public_web_site_only` is enabled and the domain is NOT the official
491/// domain, the `auto_restart_enabled` flag is set to skip interactive prompts.
492///
493/// # Arguments
494/// - `server_url`: URL of the update server
495///
496/// # Errors
497/// Returns an error if the scheduled time cannot be determined.
498pub fn spawn_update_checker(server_url: String) -> Result<()> {
499    // Check if serve_public_web_site_only mode affects update behavior
500    let settings = PcSettings::load()?;
501    let serve_public_only =
502        settings.get_bool(&PcSettingBoolKey::ServePublicWebSiteOnly);
503    let is_ctb = environment::is_official_public_website();
504
505    // If serve_public_web_site_only is on AND domain is CTB, skip updates
506    // (deployments are handled by a separate deploy script)
507    if serve_public_only && is_ctb {
508        log!("Automatic updates disabled for official CTB domain deployment");
509        return Ok(());
510    }
511
512    // If serve_public_web_site_only is on AND domain is NOT CTB,
513    // enable auto-restart (skip interactive prompts)
514    let auto_restart_enabled = serve_public_only && !is_ctb;
515    if auto_restart_enabled {
516        log!("Auto-restart enabled: updates will apply without prompting");
517    }
518
519    let scheduled_time = get_or_generate_update_check_time()?;
520    let wait_seconds = seconds_until_check_time(scheduled_time);
521
522    log_fmt!(
523        "Update checker scheduled for {:02}:{:02}:{:02} (in {} seconds)",
524        scheduled_time / 3600,
525        (scheduled_time % 3600) / 60,
526        scheduled_time % 60,
527        wait_seconds
528    );
529
530    tokio::spawn(async move {
531        // Wait until scheduled time
532        if wait_seconds > 0 {
533            tokio::time::sleep(std::time::Duration::from_secs(wait_seconds))
534                .await;
535        }
536
537        // Perform the update check
538        perform_update_check(&server_url, auto_restart_enabled).await;
539    });
540
541    Ok(())
542}
543
544/// Timeout for the startup update check in seconds.
545const STARTUP_CHECK_TIMEOUT_SECS: u64 = 5;
546
547/// Result of the startup update check.
548#[derive(Debug)]
549pub enum StartupUpdateResult {
550    /// No pending update was found.
551    NoPendingUpdate,
552    /// A pending update was found and the upgrade process was started.
553    /// The workspace should exit to allow the canary process to take over.
554    UpgradeStarted,
555    /// The update check timed out. Startup should continue normally.
556    TimedOut,
557    /// An error occurred during the check.
558    Error(String),
559}
560
561/// Checks if a previously downloaded update is ready on disk and starts the
562/// atomic upgrade if found.
563///
564/// This is a purely local check with no network I/O so it can run before the
565/// UI opens.
566pub fn apply_pending_startup_update() -> StartupUpdateResult {
567    match PendingUpdate::load() {
568        Ok(Some(pending)) => {
569            log_fmt!(
570                "Found pending update to version {} downloaded at {}",
571                pending.version,
572                pending.download_completed
573            );
574
575            // Get the current executable path
576            let current_exe = match std::env::current_exe() {
577                Ok(p) => p,
578                Err(e) => {
579                    return StartupUpdateResult::Error(format!(
580                        "Failed to get current executable path: {e}"
581                    ));
582                }
583            };
584
585            // Start the atomic upgrade
586            if let Err(e) = ctb_installer::upgrade::start_atomic_upgrade(
587                &pending.binary_path,
588                &current_exe,
589                None,
590            ) {
591                // Clear the pending update since it failed
592                let _ = PendingUpdate::clear();
593                return StartupUpdateResult::Error(format!(
594                    "Failed to start upgrade from pending update: {e}"
595                ));
596            }
597
598            // Clear the pending update record (canary process will handle the
599            // rest)
600            let _ = PendingUpdate::clear();
601
602            StartupUpdateResult::UpgradeStarted
603        }
604        Ok(None) => StartupUpdateResult::NoPendingUpdate,
605        Err(e) => {
606            warn_fmt!("Error loading pending update record: {e}");
607            StartupUpdateResult::NoPendingUpdate
608        }
609    }
610}
611
612/// Runs the bounded network startup update check (without downloading).
613pub async fn check_startup_network_update() -> StartupUpdateResult {
614    let check_future = async { quick_update_check().await };
615
616    if let Ok(result) = timeout(
617        Duration::from_secs(STARTUP_CHECK_TIMEOUT_SECS),
618        check_future,
619    )
620    .await
621    {
622        result
623    } else {
624        log!("Startup update check timed out, continuing startup");
625        StartupUpdateResult::TimedOut
626    }
627}
628
629/// Checks for a pending downloaded update at startup and applies it if ready.
630///
631/// This function:
632/// 1. Checks if there's a `PendingUpdate` record indicating a fully downloaded
633///    update
634/// 2. If found, starts the atomic upgrade process
635/// 3. If not found, quickly checks for updates (with a 5-second timeout)
636/// 4. Returns immediately if the timeout is exceeded
637///
638/// This should be called early in workspace startup. If `UpgradeStarted` is
639/// returned, the process should exit to allow the canary upgrade to proceed.
640///
641/// # Returns
642/// - `NoPendingUpdate`: No update ready, continue startup
643/// - `UpgradeStarted`: Upgrade initiated, should exit
644/// - `TimedOut`: Check took too long, continue startup
645/// - `Error`: Something went wrong (logged, continue startup)
646pub async fn check_startup_update() -> StartupUpdateResult {
647    match apply_pending_startup_update() {
648        StartupUpdateResult::NoPendingUpdate => {
649            check_startup_network_update().await
650        }
651        other => other,
652    }
653}
654
655/// Performs a quick update check without downloading.
656///
657/// This just checks if an update is available and logs it. Full download and
658/// installation happens via the background checker or manual update command.
659async fn quick_update_check() -> StartupUpdateResult {
660    let current_build = match current_build_identity_for_update_checks() {
661        Ok(build) => build,
662        Err(_) => return StartupUpdateResult::NoPendingUpdate,
663    };
664
665    // Get server URL from settings
666    // Reason for fallback: unconfigured server URL setting uses default official server URL
667    let server_url = ctb_utilities::pc_settings::get_str_setting(
668        ctb_utilities::pc_settings::PcSettingStrKey::ServerUrl,
669    )
670    .unwrap_or_else(default_url);
671
672    let Ok(api_status) =
673        query_server_update_status_fast(&server_url, &current_build).await
674    else {
675        return StartupUpdateResult::NoPendingUpdate;
676    };
677
678    if !api_status.is_newer {
679        return StartupUpdateResult::NoPendingUpdate;
680    }
681
682    // Quick manifest check with fast startup client
683    let Ok(http_client) = utilities::https::async_client(
684        utilities::https::ClientOptions::startup(),
685    ) else {
686        return StartupUpdateResult::NoPendingUpdate;
687    };
688    let downloader = ChunkDownloader::with_client(
689        &server_url,
690        http_client,
691        no_progress_callback(),
692    );
693
694    let manifest = if let Ok(m) = downloader
695        .download_manifest(&current_platform(), None)
696        .await
697    {
698        m
699    } else {
700        log_fmt!(
701            "Update available at startup: {} ({}) -> {} ({})",
702            current_build.version,
703            current_build.build_date,
704            api_status.server_version,
705            api_status.server_build_date
706        );
707        return StartupUpdateResult::NoPendingUpdate;
708    };
709
710    log_fmt!(
711        "Update available at startup: {} ({}) -> {} ({})",
712        current_build.version,
713        current_build.build_date,
714        manifest.ctoolbox_version,
715        manifest.date
716    );
717
718    StartupUpdateResult::NoPendingUpdate
719}
720
721#[cfg(test)]
722#[allow(
723    clippy::panic,
724    clippy::expect_used,
725    clippy::unwrap_used,
726    clippy::unwrap_in_result,
727    clippy::panic_in_result_fn,
728    clippy::indexing_slicing,
729    clippy::arithmetic_side_effects,
730    reason = "Standard repository test boilerplate"
731)]
732mod tests {
733    use super::*;
734
735    #[crate::ctb_test]
736    fn test_get_or_generate_update_check_time() -> Result<()> {
737        // First call should generate and save a time
738        let time1 = get_or_generate_update_check_time()?;
739        assert!(time1 < SECONDS_IN_DAY);
740
741        // Second call should return the same time
742        let time2 = get_or_generate_update_check_time()?;
743        assert_eq!(time1, time2);
744
745        Ok(())
746    }
747
748    #[crate::ctb_test]
749    fn test_seconds_until_check_time() {
750        // Get current seconds since midnight
751        let current_seconds =
752            ctb_utilities::time::seconds_from_midnight(Zoned::now().time());
753
754        // If we schedule for "now", it should be 0 or very small
755        let wait = seconds_until_check_time(current_seconds);
756        assert_eq!(wait, 0);
757
758        // If we schedule for the past, it should be 0
759        if current_seconds > 100 {
760            let wait =
761                seconds_until_check_time(current_seconds.saturating_sub(100));
762            assert_eq!(wait, 0);
763        }
764
765        // If we schedule for the future, it should be positive
766        if current_seconds < SECONDS_IN_DAY - 100 {
767            let wait =
768                seconds_until_check_time(current_seconds.saturating_add(100));
769            assert!(wait > 0);
770            assert!(wait <= 100);
771        }
772    }
773}