1#[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
54const SECONDS_IN_DAY: u32 = 86400;
56
57static 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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
76pub struct UpdateStatus {
77 pub available: bool,
79 pub version: Option<String>,
81 pub release_notes_url: Option<String>,
83 #[serde(default, with = "ctb_utilities::time::serde_rfc3339_auto_si_opt")]
85 pub last_check: Option<Timestamp>,
86 pub last_error: Option<String>,
88 #[serde(default)]
92 pub auto_restart_enabled: bool,
93}
94
95impl UpdateStatus {
96 pub fn new() -> Self {
98 Self::default()
99 }
100}
101
102#[derive(Debug, Clone, Serialize, Deserialize)]
105pub struct PendingUpdate {
106 pub version: String,
108 pub binary_path: PathBuf,
110 #[serde(with = "ctb_utilities::time::serde_rfc3339_auto_si")]
112 pub download_completed: Timestamp,
113}
114
115impl PendingUpdate {
116 fn file_path() -> Result<PathBuf> {
118 Ok(get_storage_dir()?.join("pending_update.json"))
119 }
120
121 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 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 if !pending.binary_path.exists() {
156 Self::clear()?;
158 return Ok(None);
159 }
160
161 Ok(Some(pending))
162 }
163
164 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#[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
190pub fn get_or_generate_update_check_time() -> Result<u32> {
197 let settings = PcSettings::load()?;
198
199 if let MaybeOption::Value(time) = settings.update_check_time {
201 return Ok(time);
202 }
203
204 let mut rng = rand::rng();
206 let random_time: u32 = rng.random_range(0..SECONDS_IN_DAY);
207
208 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
224fn 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(¤t_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(¤t_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", ¤t_version)
265 .append_pair("build_date", ¤t_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
299fn 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 0
309 } else {
310 u64::from(scheduled_seconds.saturating_sub(current_seconds))
312 }
313}
314
315async 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 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, ¤t_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 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 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 status.last_error.as_ref().unwrap_or(&String::new())
400 );
401 return;
402 }
403 };
404
405 let manifest = match downloader
406 .download_manifest(¤t_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 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 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
479pub fn spawn_update_checker(server_url: String) -> Result<()> {
499 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_only && is_ctb {
508 log!("Automatic updates disabled for official CTB domain deployment");
509 return Ok(());
510 }
511
512 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 if wait_seconds > 0 {
533 tokio::time::sleep(std::time::Duration::from_secs(wait_seconds))
534 .await;
535 }
536
537 perform_update_check(&server_url, auto_restart_enabled).await;
539 });
540
541 Ok(())
542}
543
544const STARTUP_CHECK_TIMEOUT_SECS: u64 = 5;
546
547#[derive(Debug)]
549pub enum StartupUpdateResult {
550 NoPendingUpdate,
552 UpgradeStarted,
555 TimedOut,
557 Error(String),
559}
560
561pub 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 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 if let Err(e) = ctb_installer::upgrade::start_atomic_upgrade(
587 &pending.binary_path,
588 ¤t_exe,
589 None,
590 ) {
591 let _ = PendingUpdate::clear();
593 return StartupUpdateResult::Error(format!(
594 "Failed to start upgrade from pending update: {e}"
595 ));
596 }
597
598 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
612pub 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
629pub 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
655async 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 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, ¤t_build).await
674 else {
675 return StartupUpdateResult::NoPendingUpdate;
676 };
677
678 if !api_status.is_newer {
679 return StartupUpdateResult::NoPendingUpdate;
680 }
681
682 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(¤t_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 let time1 = get_or_generate_update_check_time()?;
739 assert!(time1 < SECONDS_IN_DAY);
740
741 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 let current_seconds =
752 ctb_utilities::time::seconds_from_midnight(Zoned::now().time());
753
754 let wait = seconds_until_check_time(current_seconds);
756 assert_eq!(wait, 0);
757
758 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 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}