From 11af96dba1723455a8602de38514da88af8235af Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:07:17 +0800 Subject: [PATCH] refactor(updater): drop the prefetch cache and the daily cycle The cache's consumer, the startup auto-install UI, was retired in #8747; what remained was a faster dialog install for later-session clicks. That did not carry the cost: every cache function, the discard handshake with the config write lock, the daily tick, and a persistent installer-sized directory for users who never install. The actor now serves Install and Cancel only: the dialog install always downloads with progress events, which the dialog already renders, and auto_check_update keeps gating the frontend's own update check. --- Changelog.md | 1 + src-tauri/src/core/updater.rs | 332 +++------------------------------ src-tauri/src/feat/executor.rs | 12 +- 3 files changed, 32 insertions(+), 313 deletions(-) diff --git a/Changelog.md b/Changelog.md index fbfe25a88..aaf80c98c 100644 --- a/Changelog.md +++ b/Changelog.md @@ -80,6 +80,7 @@ - 优化设置页开关和选项所在行的鼠标悬停高亮,便于对应说明与控件 - 优化首页「当前节点」卡片:按规则指向的代理组逐级显示和切换实际生效的节点,选中后下拉菜单自动收起 - 优化延迟测试:节点超时后自动重测一次再显示结果,减少网络波动造成的误报 +- 优化更新下载:检测到新版本后不再后台预下载安装包,改在更新弹窗内下载 **🖥️ Windows** diff --git a/src-tauri/src/core/updater.rs b/src-tauri/src/core/updater.rs index 173f40c46..d5aed8c46 100644 --- a/src-tauri/src/core/updater.rs +++ b/src-tauri/src/core/updater.rs @@ -1,11 +1,9 @@ -use crate::{config::Config, utils::dirs}; -use anyhow::{Context as _, Result}; +use anyhow::Result; use clash_verge_logging::{Type, logging}; use futures::FutureExt as _; use serde::Serialize; use std::{ panic::AssertUnwindSafe, - path::PathBuf, sync::{ OnceLock, atomic::{AtomicU64, Ordering}, @@ -37,31 +35,15 @@ enum Cmd { reply: oneshot::Sender>, }, Cancel, - Discard { - reply: oneshot::Sender<()>, - }, } -/// What wakes the idle actor. -enum Wake { - Cmd(Cmd), - DailyCheck, -} - -/// How a background cycle ended: `Displaced` carries the command that dropped it. -enum CycleEnd { - Completed(Result<()>), - Displaced(Cmd), -} - -/// `Dropped`'s ack is present when a discard is waiting for the cache deletion. +/// How a dialog install's prepare phase ended. enum Prepared { - /// The verified bytes with their update record, or `None` when the offer changed. + /// The update record with its verified bytes, or `None` when the offer changed. Ready(Option)>>), Failed(anyhow::Error), - Dropped { - ack: Option>, - }, + /// Preempted by a cancel; the work future is already dropped. + Dropped, } impl SilentUpdater { @@ -80,112 +62,6 @@ impl SilentUpdater { } } -impl SilentUpdater { - fn cache_dir() -> Result { - Ok(dirs::app_home_dir()?.join("update_cache")) - } - - /// Writes the payload through a temp file so a crash leaves no partial `pending_update.bin`; - /// installer-sized IO stays off the async runtime. Only the detachable blocking task writes - /// the temp file — the rename that publishes the cache runs after its await, so a command - /// preempting this future cannot leave a published cache behind the preemption. - async fn write_cache(bytes: Vec, version: &str) -> Result<()> { - let cache_dir = Self::cache_dir()?; - let size = bytes.len(); - let bin_path = cache_dir.join("pending_update.bin"); - let tmp_path = cache_dir.join("pending_update.bin.tmp"); - let write_tmp = { - let cache_dir = cache_dir.clone(); - let tmp_path = tmp_path.clone(); - move || -> Result<()> { - std::fs::create_dir_all(&cache_dir) - .with_context(|| format!("failed to create update cache directory {}", cache_dir.display()))?; - std::fs::write(&tmp_path, &bytes) - .with_context(|| format!("failed to write update cache {}", tmp_path.display()))?; - Ok(()) - } - }; - tokio::task::spawn_blocking(write_tmp).await??; - // Metadata-sized, so inline on the actor thread rather than a detachable task. - std::fs::rename(&tmp_path, &bin_path) - .with_context(|| format!("failed to rename update cache {}", bin_path.display()))?; - logging!( - info, - Type::System, - "Update cache written: version={version}, size={size} bytes" - ); - Ok(()) - } - - async fn read_cache_bytes() -> Result> { - let bin_path = Self::cache_dir()?.join("pending_update.bin"); - tokio::task::spawn_blocking(move || { - std::fs::read(&bin_path).with_context(|| format!("failed to read update cache {}", bin_path.display())) - }) - .await? - } - - /// Invalidates the cache by renaming it out of the way, then removes the renamed directory - /// in a detached task: the awaited part is metadata-sized — bar clearing residue left by a - /// crashed detached removal — so a discard ack is never owed for the bulk unlink while the - /// config write lock is held. - async fn delete_cache() { - if let Ok(cache_dir) = Self::cache_dir() - && cache_dir.exists() - { - let discarding = cache_dir.with_file_name("update_cache_discarding"); - let display = cache_dir.display().to_string(); - let invalidate = { - let discarding = discarding.clone(); - move || -> std::io::Result<()> { - // Best-effort: the rename is the invalidation, and a failed residue clear - // surfaces as the rename's own error. - if discarding.exists() - && let Err(e) = std::fs::remove_dir_all(&discarding) - { - logging!(warn, Type::System, "Failed to clear update cache discard residue: {e}"); - } - std::fs::rename(&cache_dir, &discarding) - } - }; - match tokio::task::spawn_blocking(invalidate).await { - Ok(Ok(())) => { - logging!(info, Type::System, "Update cache deleted"); - // Nothing reads the discarding name, so the bulk unlink may detach. - tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&discarding)); - } - Ok(Err(e)) => logging!(warn, Type::System, "Failed to delete update cache {display}: {e}"), - Err(e) => logging!(warn, Type::System, "Failed to delete update cache {display}: {e}"), - } - } - } - - /// Returns the cached installer for `update`, deleting a cache that does not verify. The - /// plugin's `verify` binds the bytes to the signed release version, so a cache left by an - /// earlier offer is rejected the same way as a corrupted one. - async fn verified_cache(update: &Update) -> Option> { - // A quiet miss for the common no-cache case; only a present-but-bad cache logs. - let Ok(bin_path) = Self::cache_dir().map(|dir| dir.join("pending_update.bin")) else { - return None; - }; - if !bin_path.exists() { - return None; - } - let bytes = Self::read_cache_bytes().await.and_then(|bytes| { - update.verify(&bytes)?; - Ok(bytes) - }); - match bytes { - Ok(bytes) => Some(bytes), - Err(e) => { - logging!(info, Type::System, "Update cache is unusable: {e:#}, cleaning up"); - Self::delete_cache().await; - None - } - } - } -} - pub fn is_build_to_stable(current: &str, remote: &str) -> bool { let Some((base, build)) = current.trim_start_matches('v').split_once('+') else { return false; @@ -224,8 +100,6 @@ const MIRRORS: [&str; 2] = ["https://update.hwdns.net/", "https://gh-proxy.org/" /// A source delivering less than this per window is dropped for the next one. const MIN_PROGRESS: u64 = 1024 * 1024; const PROGRESS_WINDOW: Duration = Duration::from_secs(30); -/// How long the actor waits after a panic before re-arming the daily check. -const PANIC_BACKOFF: Duration = Duration::from_secs(600); #[cfg(target_os = "windows")] const INSTALL_TIMEOUT: Duration = Duration::from_secs(30); #[cfg(not(target_os = "windows"))] @@ -315,18 +189,16 @@ impl SilentUpdater { let updater_builder = app_handle.updater_builder(); #[cfg(target_os = "windows")] let updater_builder = { - let verge_lang = Config::verge().await.latest_arc().language.clone(); + let verge_lang = crate::config::Config::verge().await.latest_arc().language.clone(); let lang_id = nsis_language_id(&clash_verge_i18n::current_language(verge_lang.as_deref())); updater_builder.installer_arg(format!("/LANG={lang_id}")) }; Ok(updater_builder.build()?.check().await?) } - /// Installs verified bytes, dropping the cache first so a failure leaves nothing to - /// re-trigger. A timeout abandons the await, not the detached install task; a successful - /// Windows install exits the process inside the plugin (#2558). + /// Installs verified bytes. A timeout abandons the await, not the detached install task; + /// a successful Windows install exits the process inside the plugin (#2558). async fn install(update: Update, bytes: Vec) -> Result<()> { - Self::delete_cache().await; let install = tokio::task::spawn_blocking(move || update.install(&bytes)); match tokio::time::timeout(INSTALL_TIMEOUT, install).await { Ok(result) => Ok(result??), @@ -338,8 +210,8 @@ impl SilentUpdater { } impl SilentUpdater { - /// Installs `version` for the update dialog, reusing the cache when it holds that version; - /// A changed offer must be confirmed again before downloading or installing it. + /// Installs `version` for the update dialog; a changed offer must be confirmed again + /// before downloading or installing it. pub async fn install_update( &self, // The actor owns the app handle; the parameter keeps the command's call shape. @@ -365,16 +237,6 @@ impl SilentUpdater { // try_send: a cancel must never block, and the mailbox never fills in practice. let _ = self.tx.try_send(Cmd::Cancel); } - - /// Drops the downloaded update and aborts a background download in flight. - pub async fn discard_pending(&self) { - // Awaiting the ack serializes with the verge patch, which holds the config write - // lock until the actor has finished the abort and the deletion. - let (reply, reply_rx) = oneshot::channel(); - if self.tx.send(Cmd::Discard { reply }).await.is_ok() { - let _ = reply_rx.await; - } - } } impl SilentUpdater { @@ -384,157 +246,38 @@ impl SilentUpdater { async fn run(app_handle: tauri::AppHandle, mut rx: mpsc::Receiver) { logging!(info, Type::System, "Silent updater: background task started"); - let mut next_check = tokio::time::Instant::now() + Duration::from_secs(10); loop { - match AssertUnwindSafe(Self::serve(&app_handle, &mut rx, &mut next_check)) - .catch_unwind() - .await - { + match AssertUnwindSafe(Self::serve(&app_handle, &mut rx)).catch_unwind().await { // The mailbox closed; the handle holds the only sender, so this is shutdown. Ok(()) => return, Err(_) => { // The global panic hook logged the payload; this marks the recovery. The // epoch future is dropped during the unwind, ending its borrows, so the - // mailbox and the check schedule below are intact. + // mailbox below is intact. logging!(error, Type::System, "Silent updater: actor panicked, restarting"); - // Back the daily check off so a persistently panicking path cannot hot-loop. - next_check = next_check.max(tokio::time::Instant::now() + PANIC_BACKOFF); } } } } - /// The actor loop: idle until a command or the daily check, then run the work. Commands - /// preempt running work; a preempting command re-enters the dispatch after the preempted - /// work is dropped. - async fn serve(app_handle: &tauri::AppHandle, rx: &mut mpsc::Receiver, next_check: &mut tokio::time::Instant) { - loop { - let mut wake = tokio::select! { - maybe = rx.recv() => match maybe { - Some(cmd) => Wake::Cmd(cmd), - None => return, - }, - _ = tokio::time::sleep_until(*next_check) => Wake::DailyCheck, - }; - loop { - match wake { - Wake::Cmd(Cmd::Install { - version, - on_event, - reply, - }) => { - Self::run_install(app_handle, &version, on_event, reply, rx).await; - break; - } - // The dialog's cancel only addresses a running install; idle it stops nothing. - Wake::Cmd(Cmd::Cancel) => break, - Wake::Cmd(Cmd::Discard { reply }) => { - Self::run_discard(reply).await; - break; - } - Wake::DailyCheck => { - let end = Self::run_background_cycle(app_handle, rx).await; - *next_check = tokio::time::Instant::now() + Duration::from_secs(24 * 60 * 60); - match end { - CycleEnd::Completed(Ok(())) => break, - CycleEnd::Completed(Err(e)) => { - logging!(warn, Type::System, "Silent updater: cycle error: {e}"); - break; - } - CycleEnd::Displaced(cmd) => wake = Wake::Cmd(cmd), - } - } - } - } - } - } - - /// Runs one daily cycle, pre-empted by user commands: a cancel is ignored; an install - /// or a discard drops the cycle, and the cycle future is gone before the follow-up - /// dispatch runs. - async fn run_background_cycle(app_handle: &tauri::AppHandle, rx: &mut mpsc::Receiver) -> CycleEnd { - let cycle = Self::check_and_download(app_handle); - tokio::pin!(cycle); - let mut mailbox_open = true; - loop { - let maybe = tokio::select! { - biased; - maybe = rx.recv(), if mailbox_open => maybe, - result = &mut cycle => return CycleEnd::Completed(result), - }; - let Some(cmd) = maybe else { - mailbox_open = false; - continue; - }; + /// The actor loop: idle until a command, then run the work. A cancel during the + /// cancellable phases drops the work future; a second install is declined in place. + async fn serve(app_handle: &tauri::AppHandle, rx: &mut mpsc::Receiver) { + while let Some(cmd) = rx.recv().await { match cmd { - Cmd::Cancel => {} - Cmd::Install { .. } => return CycleEnd::Displaced(cmd), - Cmd::Discard { .. } => { - logging!(info, Type::System, "Silent updater: background cycle discarded"); - return CycleEnd::Displaced(cmd); + Cmd::Install { + version, + on_event, + reply, + } => { + Self::run_install(app_handle, &version, on_event, reply, rx).await; } + // The dialog's cancel only addresses a running install; idle it stops nothing. + Cmd::Cancel => {} } } } - async fn check_and_download(app_handle: &tauri::AppHandle) -> Result<()> { - let auto_check = Config::verge().await.latest_arc().auto_check_update.unwrap_or(true); - if !auto_check { - logging!(debug, Type::System, "Silent update skipped: auto_check_update is false"); - return Ok(()); - } - - logging!(info, Type::System, "Silent updater: checking for updates..."); - - let updater = app_handle.updater()?; - let update = match updater.check().await { - Ok(Some(update)) => update, - Ok(None) => { - logging!(info, Type::System, "Silent updater: no update available"); - return Ok(()); - } - Err(e) => { - logging!(warn, Type::System, "Silent updater: check failed: {e}"); - return Err(e.into()); - } - }; - - let version = update.version.as_str(); - logging!(info, Type::System, "Silent updater: update available: v{version}"); - - if Self::verified_cache(&update).await.is_some() { - logging!(info, Type::System, "Silent updater: v{version} already cached"); - } else { - logging!(info, Type::System, "Silent updater: downloading v{version}..."); - let bytes = download(&update, |_| {}).await?; - logging!(info, Type::System, "Silent updater: download complete"); - Self::write_cache(bytes, version).await?; - } - - // The verge patch's discard holds this lock while awaiting the actor's ack, so a - // discard arriving during this wait preempts the cycle rather than deadlock on it. - let discard = { - let _config_write = Config::lock_config_write().await; - !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true) - }; - if discard { - logging!( - info, - Type::System, - "Silent updater: auto check was disabled, discarding v{version}" - ); - Self::delete_cache().await; - return Ok(()); - } - - logging!( - info, - Type::System, - "Silent updater: v{version} ready to install from the update dialog" - ); - Ok(()) - } - /// One dialog install from prepare to install; every exit path answers `reply`. async fn run_install( app_handle: &tauri::AppHandle, @@ -545,13 +288,9 @@ impl SilentUpdater { ) { match Self::prepare_cancellable(app_handle, version, on_event.as_ref(), rx).await { // The prepare work is already dropped, so a cancel racing the last poll still wins. - Prepared::Dropped { ack } => { + Prepared::Dropped => { logging!(info, Type::System, "Update v{version} cancelled"); let _ = reply.send(Ok(InstallUpdateOutcome::Cancelled)); - if let Some(ack) = ack { - Self::delete_cache().await; - let _ = ack.send(()); - } } Prepared::Failed(e) => { let _ = reply.send(Err(e)); @@ -569,8 +308,8 @@ impl SilentUpdater { } } - /// The cancellable prepare phase: check, version filter, cache reuse or download. A - /// second install is declined in place; a cancel or a discard drops the work. + /// The cancellable prepare phase: check, version filter, download. A second install is + /// declined in place; a cancel drops the work. async fn prepare_cancellable( app_handle: &tauri::AppHandle, version: &str, @@ -594,8 +333,7 @@ impl SilentUpdater { continue; }; match cmd { - Cmd::Cancel => return Prepared::Dropped { ack: None }, - Cmd::Discard { reply: ack } => return Prepared::Dropped { ack: Some(ack) }, + Cmd::Cancel => return Prepared::Dropped, Cmd::Install { reply, .. } => Self::decline_install(reply), } } @@ -612,10 +350,7 @@ impl SilentUpdater { else { return Ok(None); }; - let bytes = match Self::verified_cache(&update).await { - Some(bytes) => bytes, - None => download(&update, on_event).await?, - }; + let bytes = download(&update, on_event).await?; Ok(Some((update, bytes))) } @@ -637,10 +372,6 @@ impl SilentUpdater { match cmd { Cmd::Cancel => {} Cmd::Install { reply, .. } => Self::decline_install(reply), - Cmd::Discard { reply } => { - // install() drops the cache before launching, so the ack is all that is owed. - let _ = reply.send(()); - } } } } @@ -648,11 +379,6 @@ impl SilentUpdater { fn decline_install(reply: oneshot::Sender>) { let _ = reply.send(Err(anyhow::anyhow!("an update install is already in progress"))); } - - async fn run_discard(reply: oneshot::Sender<()>) { - Self::delete_cache().await; - let _ = reply.send(()); - } } #[cfg(test)] diff --git a/src-tauri/src/feat/executor.rs b/src-tauri/src/feat/executor.rs index 98fa592a4..375a1e227 100644 --- a/src-tauri/src/feat/executor.rs +++ b/src-tauri/src/feat/executor.rs @@ -6,10 +6,7 @@ use crate::{ snapshot::{capture_config_files, restore_files}, }, core::auto_backup::AutoBackupManager, - core::{ - CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control, - tray, - }, + core::{CoreManager, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control, tray}, }; use anyhow::Result; use clash_verge_draft::DraftTransaction; @@ -162,12 +159,7 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e } transaction.commit(); match patch { - Patch::Verge { patch, .. } => { - if patch.auto_check_update == Some(false) - && let Some(updater) = SilentUpdater::global() - { - updater.discard_pending().await; - } + Patch::Verge { .. } => { if effects.contains(&Effect::ClashConfig) { announce(Refresh::Clash); }