Compare commits

..
2 changed files with 70 additions and 55 deletions
+69 -54
View File
@@ -1,6 +1,5 @@
use crate::{config::Config, singleton, utils::dirs};
use anyhow::{Context as _, Result};
use chrono::Utc;
use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
@@ -41,7 +40,6 @@ impl SilentUpdater {
#[derive(Serialize, Deserialize)]
struct UpdateCacheMeta {
version: String,
downloaded_at: String,
}
impl SilentUpdater {
@@ -49,36 +47,45 @@ impl SilentUpdater {
Ok(dirs::app_home_dir()?.join("update_cache"))
}
fn write_cache(bytes: &[u8], version: &str) -> Result<()> {
/// Writes the payload through a temp file so a crash leaves no partial `pending_update.bin`;
/// installer-sized IO stays off the async runtime.
async fn write_cache(bytes: Vec<u8>, version: &str) -> Result<()> {
let cache_dir = Self::cache_dir()?;
std::fs::create_dir_all(&cache_dir)
.with_context(|| format!("failed to create update cache directory {}", cache_dir.display()))?;
let version = version.to_owned();
tokio::task::spawn_blocking(move || -> Result<()> {
std::fs::create_dir_all(&cache_dir)
.with_context(|| format!("failed to create update cache directory {}", cache_dir.display()))?;
let bin_path = cache_dir.join("pending_update.bin");
std::fs::write(&bin_path, bytes)
.with_context(|| format!("failed to write update cache {}", bin_path.display()))?;
let bin_path = cache_dir.join("pending_update.bin");
let tmp_path = cache_dir.join("pending_update.bin.tmp");
std::fs::write(&tmp_path, &bytes)
.with_context(|| format!("failed to write update cache {}", tmp_path.display()))?;
std::fs::rename(&tmp_path, &bin_path)
.with_context(|| format!("failed to rename update cache {}", bin_path.display()))?;
let meta = UpdateCacheMeta {
version: version.to_string(),
downloaded_at: Utc::now().to_rfc3339(),
};
let meta_path = cache_dir.join("pending_update.json");
std::fs::write(&meta_path, serde_json::to_string_pretty(&meta)?)
.with_context(|| format!("failed to write update metadata {}", meta_path.display()))?;
let meta = UpdateCacheMeta { version };
let meta_path = cache_dir.join("pending_update.json");
std::fs::write(&meta_path, serde_json::to_string_pretty(&meta)?)
.with_context(|| format!("failed to write update metadata {}", meta_path.display()))?;
logging!(
info,
Type::System,
"Update cache written: version={}, size={} bytes",
version,
bytes.len()
);
Ok(())
logging!(
info,
Type::System,
"Update cache written: version={}, size={} bytes",
meta.version,
bytes.len()
);
Ok(())
})
.await?
}
fn read_cache_bytes() -> Result<Vec<u8>> {
async fn read_cache_bytes() -> Result<Vec<u8>> {
let bin_path = Self::cache_dir()?.join("pending_update.bin");
std::fs::read(&bin_path).with_context(|| format!("failed to read update cache {}", bin_path.display()))
tokio::task::spawn_blocking(move || {
std::fs::read(&bin_path).with_context(|| format!("failed to read update cache {}", bin_path.display()))
})
.await?
}
fn read_cache_meta() -> Result<UpdateCacheMeta> {
@@ -87,28 +94,24 @@ impl SilentUpdater {
Ok(serde_json::from_str(&content)?)
}
fn delete_cache() {
async fn delete_cache() {
if let Ok(cache_dir) = Self::cache_dir()
&& cache_dir.exists()
{
if let Err(e) = std::fs::remove_dir_all(&cache_dir) {
logging!(
warn,
Type::System,
"Failed to delete update cache {}: {e}",
cache_dir.display()
);
} else {
logging!(info, Type::System, "Update cache deleted");
let display = cache_dir.display().to_string();
match tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&cache_dir)).await {
Ok(Ok(())) => logging!(info, Type::System, "Update cache deleted"),
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 match it.
fn verified_cache(update: &Update) -> Option<Vec<u8>> {
async fn verified_cache(update: &Update) -> Option<Vec<u8>> {
let meta = Self::read_cache_meta().ok()?;
let bytes = if meta.version == update.version {
Self::read_cache_bytes().and_then(|bytes| {
Self::read_cache_bytes().await.and_then(|bytes| {
update.verify(&bytes)?;
Ok(bytes)
})
@@ -124,7 +127,7 @@ impl SilentUpdater {
"Update cache v{} is unusable: {e:#}, cleaning up",
meta.version
);
Self::delete_cache();
Self::delete_cache().await;
None
}
}
@@ -280,7 +283,7 @@ impl SilentUpdater {
/// re-trigger. 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<u8>) -> Result<()> {
Self::delete_cache();
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??),
@@ -293,7 +296,7 @@ impl SilentUpdater {
/// Installs a newer cached update before normal startup, if the user confirms.
pub async fn try_install_on_startup(&self, app_handle: &tauri::AppHandle) -> bool {
if !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true) {
Self::delete_cache();
Self::delete_cache().await;
return false;
}
@@ -301,7 +304,11 @@ impl SilentUpdater {
let meta = match Self::read_cache_meta() {
Ok(meta) => meta,
Err(_) => return false, // No cache, nothing to do
Err(_) => {
// A bin without its meta is a torn write from a previous session.
Self::delete_cache().await;
return false;
}
};
let cached_version = &meta.version;
@@ -314,7 +321,7 @@ impl SilentUpdater {
cached_version,
current_version
);
Self::delete_cache();
Self::delete_cache().await;
return false;
}
@@ -337,7 +344,7 @@ impl SilentUpdater {
Type::System,
"No update available from server, cache may be stale, cleaning up"
);
Self::delete_cache();
Self::delete_cache().await;
return false;
}
Ok(Err(e)) => {
@@ -358,7 +365,7 @@ impl SilentUpdater {
}
};
let Some(bytes) = Self::verified_cache(&update) else {
let Some(bytes) = Self::verified_cache(&update).await else {
return false;
};
@@ -396,7 +403,11 @@ impl SilentUpdater {
on_event: impl Fn(DownloadEvent) + Sync,
) -> Result<InstallUpdateOutcome> {
let cancel = CancellationToken::new();
*self.manual_cancel.lock() = Some(cancel.clone());
{
let mut slot = self.manual_cancel.lock();
anyhow::ensure!(slot.is_none(), "an update install is already in progress");
*slot = Some(cancel.clone());
}
let prepared = tokio::select! {
prepared = self.prepare_install(app_handle, version, &on_event) => Some(prepared),
() = cancel.cancelled() => None,
@@ -431,7 +442,7 @@ impl SilentUpdater {
return Ok(None);
};
let _download_guard = self.download_lock.lock().await;
let bytes = match Self::verified_cache(&update) {
let bytes = match Self::verified_cache(&update).await {
Some(bytes) => bytes,
None => download(&update, on_event).await?,
};
@@ -446,12 +457,12 @@ impl SilentUpdater {
}
/// Drops the downloaded update and aborts a background download in flight.
pub fn discard_pending(&self) {
pub async fn discard_pending(&self) {
let cancel = self.background_cancel.lock().take();
if let Some(cancel) = cancel {
cancel.cancel();
}
Self::delete_cache();
Self::delete_cache().await;
}
}
@@ -597,7 +608,7 @@ impl SilentUpdater {
return Ok(());
}
if Self::verified_cache(&update).is_some() {
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}...");
@@ -611,19 +622,23 @@ impl SilentUpdater {
};
let bytes = bytes?;
logging!(info, Type::System, "Silent updater: download complete");
Self::write_cache(&bytes, version)?;
Self::write_cache(bytes, version).await?;
}
drop(download_guard);
// Serialized with `discard_pending` in the verge patch, which holds the same lock.
let _config_write = Config::lock_config_write().await;
if cancel.is_cancelled() || !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true) {
// Serialized with `discard_pending` in the verge patch, which holds the same lock;
// the deletion itself is idempotent, so it runs after the lock.
let discard = {
let _config_write = Config::lock_config_write().await;
cancel.is_cancelled() || !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();
Self::delete_cache().await;
return Ok(());
}
+1 -1
View File
@@ -164,7 +164,7 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
match patch {
Patch::Verge { patch, .. } => {
if patch.auto_check_update == Some(false) {
SilentUpdater::global().discard_pending();
SilentUpdater::global().discard_pending().await;
}
if effects.contains(&Effect::ClashConfig) {
announce(Refresh::Clash);