mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-19 02:12:10 +08:00
chore: sync repairs and dev into once-cell cleanup
This commit is contained in:
+20
-36
@@ -2,39 +2,23 @@
|
||||
|
||||
These rules supplement the repository's root `AGENTS.md`.
|
||||
|
||||
1. **Keep configuration ownership in `config`.** Configuration writes must use
|
||||
its draft and persistence APIs. Patch orchestration must use
|
||||
`feat/effects.rs` and `feat/executor.rs`; refresh notifications must use
|
||||
`core::notify::announce` after successful persistence and commit. This keeps
|
||||
rolled-back transactions from publishing state. If runtime and memory state
|
||||
are already committed and cannot be rolled back, announce that state even
|
||||
when persistence fails, while preserving the persistence error. Independent
|
||||
transactions retain their boundaries and announce their own committed
|
||||
results; runtime-only profile activation announces after successful
|
||||
application. Cross-layer operations must preserve these ownership and
|
||||
transaction boundaries.
|
||||
2. **Register every new `IVerge` field.** Register the field in the
|
||||
exhaustive effect registry, including an explicit `NoEffect` where
|
||||
appropriate, and preserve its platform attributes. Manual field-to-flag
|
||||
chains hide missing effects and are forbidden.
|
||||
3. **Use `utils::retry` for bounded retries.** Do not introduce handwritten retry
|
||||
loops, including `loop` plus `sleep`; preserve attempt budgets, delays and
|
||||
terminal errors. Permanent watchers are the exception and must document
|
||||
their exit conditions. Traversal of distinct data or port candidates is not
|
||||
a retry policy.
|
||||
4. **Keep notifications typed.** Send notice statuses through `NoticeStatus` and
|
||||
use `Arc<str>` for notice message payloads. Preserve the event names and
|
||||
status strings as a shared wire contract. Contract changes must keep
|
||||
frontend consumers and backend producers aligned.
|
||||
5. **Preserve lock order.** The order is `config_write` before
|
||||
`config_update_in_progress` before `lifecycle_lock`. Patch callers must use
|
||||
the executor's guarded claim instead of independently combining these locks;
|
||||
this preserves Busy rejection and prevents inverted acquisition. Existing
|
||||
lifecycle and independent port transactions keep their established locking
|
||||
boundaries. A new lock requires registering its position in this rule before
|
||||
introducing acquisition sites.
|
||||
6. **Prefer reconciliation.** Express new effects as idempotent `ensure`
|
||||
operations in `EFFECT_ORDER` so repeated application converges on the same
|
||||
state. A trigger chain is an exception only with a code comment explaining
|
||||
why the operation cannot be idempotent. Configuration rollback does not
|
||||
authorize reverse OS effects.
|
||||
- **Configuration ownership.** `config` owns source configuration, drafts and
|
||||
persistence. The effects layer owns patch orchestration. Rollbackable
|
||||
transactions publish state after persistence and commit; already applied
|
||||
runtime and independently committed state remain authoritative even when a
|
||||
later step fails. Preserve that state, its notifications and the error.
|
||||
- **Effect ownership.** The declarative registry classifies every Verge patch field,
|
||||
including fields without effects and platform-specific fields. Effects
|
||||
reconcile toward the requested state with explicit dependencies and ordering.
|
||||
Configuration rollback does not imply reversal of OS or lifecycle effects.
|
||||
- **Shared wire contract.** Notifications are typed. Event names, status values
|
||||
and payload shapes stay compatible with frontend producers and consumers.
|
||||
- **Synchronization ownership.** Configuration-write serialization precedes
|
||||
configuration-update ownership, which precedes Core lifecycle ownership.
|
||||
When both are held, the lifecycle lock precedes the DNS lock. Independent
|
||||
transactions retain their ownership boundaries; asynchronous work does not
|
||||
hold synchronous data guards across suspension.
|
||||
- **Retry ownership.** Bounded retries share backend policy while preserving
|
||||
attempts, delays and terminal errors. Background monitors own their lifetime
|
||||
and cancellation separately; waiting for a condition or traversing distinct
|
||||
candidates is not a retry policy.
|
||||
|
||||
@@ -85,6 +85,7 @@ flate2 = "1.1.10"
|
||||
reqwest_dav = "0.3.3"
|
||||
aes-gcm = { version = "0.11.1" }
|
||||
base64 = "0.23.1"
|
||||
minisign-verify = "0.2.5"
|
||||
sha2 = "0.11"
|
||||
getrandom = "0.4.3"
|
||||
futures = "0.3.34"
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
use super::CmdResult;
|
||||
use crate::{cmd::StringifyErr as _, feat, utils::dirs};
|
||||
use crate::{
|
||||
cmd::StringifyErr as _,
|
||||
core::{SilentUpdater, updater::DownloadEvent},
|
||||
feat,
|
||||
utils::dirs,
|
||||
};
|
||||
use smartstring::alias::String;
|
||||
use tauri::{AppHandle, Manager as _};
|
||||
use tauri::{AppHandle, Manager as _, ipc::Channel};
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn open_app_dir() -> CmdResult<()> {
|
||||
@@ -44,6 +49,25 @@ pub async fn restart_app() -> CmdResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn install_update(
|
||||
app_handle: AppHandle,
|
||||
version: String,
|
||||
on_event: Channel<DownloadEvent>,
|
||||
) -> CmdResult<bool> {
|
||||
SilentUpdater::global()
|
||||
.install_update(&app_handle, &version, |event| {
|
||||
let _ = on_event.send(event);
|
||||
})
|
||||
.await
|
||||
.stringify_err()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn cancel_update_download() {
|
||||
SilentUpdater::global().cancel_download();
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn get_app_dir() -> CmdResult<String> {
|
||||
let app_home_dir = dirs::app_home_dir().stringify_err()?.to_string_lossy().into();
|
||||
|
||||
@@ -322,7 +322,7 @@ impl CoreManager {
|
||||
self.validate_and_apply(transaction).await
|
||||
}
|
||||
|
||||
/// Validates and applies the caller's transaction, committing only on success.
|
||||
/// Commits the applied runtime even if restoring the system proxy subsequently fails.
|
||||
async fn validate_and_apply(&self, transaction: DraftTransaction<'_>) -> Result<ValidationOutcome> {
|
||||
let outcome = self.validate_and_apply_draft().await?;
|
||||
if outcome.is_valid() {
|
||||
@@ -342,7 +342,10 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
let run_path = Config::write_runtime_file(&yaml).await?;
|
||||
self.apply_config(run_path).await?;
|
||||
let previous = self.current_core_readiness_generation();
|
||||
let result = self.apply_config(run_path).await;
|
||||
self.retain_applied_runtime(&Config::runtime().await, previous, &result);
|
||||
result?;
|
||||
// Under the lifecycle lock, so a stop for exit waits for this write instead of outrunning it.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
@@ -352,6 +355,21 @@ impl CoreManager {
|
||||
Ok(ValidationOutcome::Valid)
|
||||
}
|
||||
|
||||
fn retain_applied_runtime(
|
||||
&self,
|
||||
runtime: &clash_verge_draft::Draft<IRuntime>,
|
||||
previous: Option<u64>,
|
||||
result: &Result<()>,
|
||||
) {
|
||||
if result.is_ok()
|
||||
|| self
|
||||
.current_core_readiness_generation()
|
||||
.is_some_and(|current| Some(current) != previous)
|
||||
{
|
||||
runtime.apply();
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a generated configuration through the active core owner.
|
||||
async fn apply_config(&self, path: PathBuf) -> Result<()> {
|
||||
if matches!(*self.get_running_mode(), RunningMode::Service) {
|
||||
@@ -443,6 +461,31 @@ mod tests {
|
||||
use clash_verge_service_ipc::{StageRejection, StageRuntimeOutcome};
|
||||
use std::{cell::Cell, time::Duration};
|
||||
|
||||
#[test]
|
||||
fn a_ready_replacement_keeps_the_applied_runtime_when_proxy_restore_fails() -> anyhow::Result<()> {
|
||||
use crate::{config::runtime::IRuntime, core::CoreManager};
|
||||
use clash_verge_draft::{Draft, DraftTransaction};
|
||||
|
||||
for replaced in [false, true] {
|
||||
let manager = CoreManager::default();
|
||||
manager.mark_core_ready();
|
||||
let previous = manager.current_core_readiness_generation();
|
||||
let runtime = Draft::new(IRuntime::default());
|
||||
let transaction = DraftTransaction::begin(vec![&runtime])?;
|
||||
runtime.edit_draft(|draft| {
|
||||
draft.exists_keys.insert("replacement".into());
|
||||
});
|
||||
if replaced {
|
||||
manager.mark_core_ready();
|
||||
}
|
||||
let result = Err(anyhow::anyhow!("system proxy restore failed"));
|
||||
manager.retain_applied_runtime(&runtime, previous, &result);
|
||||
transaction.rollback();
|
||||
assert_eq!(runtime.data_arc().exists_keys.contains("replacement"), replaced);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const CONFIRM_WITHIN: Duration = Duration::from_secs(5);
|
||||
|
||||
fn staged() -> StageAttempt {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::{handle::Handle, notification::FrontendEvent};
|
||||
use anyhow::Result;
|
||||
use parking_lot::Mutex;
|
||||
use std::{cell::RefCell, future::Future, time::Duration};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Refresh {
|
||||
@@ -11,10 +10,6 @@ pub enum Refresh {
|
||||
Proxies,
|
||||
}
|
||||
|
||||
tokio::task_local! {
|
||||
static PENDING: RefCell<Vec<Refresh>>;
|
||||
}
|
||||
|
||||
const REFRESH_WINDOW: Duration = Duration::from_millis(20);
|
||||
static BATCH: RefreshBatch = RefreshBatch(Mutex::new(Vec::new()));
|
||||
|
||||
@@ -42,7 +37,7 @@ impl RefreshBatch {
|
||||
}
|
||||
|
||||
pub fn announce(refresh: Refresh) {
|
||||
if PENDING.try_with(|pending| pending.borrow_mut().push(refresh)).is_err() && BATCH.enqueue(refresh) {
|
||||
if BATCH.enqueue(refresh) {
|
||||
crate::AsyncHandler::spawn(|| BATCH.flush(emit));
|
||||
}
|
||||
}
|
||||
@@ -56,54 +51,12 @@ fn emit(refresh: Refresh) {
|
||||
});
|
||||
}
|
||||
|
||||
async fn collect_committed<T: Send>(operation: impl Future<Output = Result<T>> + Send) -> Result<(T, Vec<Refresh>)> {
|
||||
PENDING
|
||||
.scope(RefCell::new(Vec::new()), async {
|
||||
let value = operation.await?;
|
||||
let refreshes = PENDING.with(|pending| pending.take());
|
||||
Ok((value, refreshes))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn after_commit<T: Send>(operation: impl Future<Output = Result<T>> + Send) -> Result<T> {
|
||||
let (value, refreshes) = collect_committed(operation).await?;
|
||||
// Nested transactions hand their notifications to the outer transaction.
|
||||
for refresh in refreshes {
|
||||
announce(refresh);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_successful_transactions_publish_refreshes() -> Result<()> {
|
||||
let (_, refreshes) = collect_committed(async {
|
||||
announce(Refresh::Clash);
|
||||
after_commit(async {
|
||||
announce(Refresh::Verge);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
let failed = after_commit(async {
|
||||
announce(Refresh::Profiles);
|
||||
Err::<(), _>(anyhow::anyhow!("persistence failed"))
|
||||
})
|
||||
.await;
|
||||
assert!(failed.is_err());
|
||||
announce(Refresh::Clash);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(refreshes, [Refresh::Clash, Refresh::Verge, Refresh::Clash]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bursts_keep_each_refresh_kind_and_rearm_during_delivery() -> Result<()> {
|
||||
async fn bursts_keep_each_refresh_kind_and_rearm_during_delivery() -> anyhow::Result<()> {
|
||||
let batch = RefreshBatch::default();
|
||||
let delivered = Mutex::new(Vec::new());
|
||||
assert!(batch.enqueue(Refresh::Clash));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
mod announce;
|
||||
pub use announce::{Refresh, after_commit, announce};
|
||||
pub use announce::{Refresh, announce};
|
||||
pub mod desktop;
|
||||
pub mod handle;
|
||||
pub mod notification;
|
||||
|
||||
+261
-100
@@ -2,15 +2,19 @@ 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};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
sync::atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
use tauri_plugin_updater::UpdaterExt as _;
|
||||
use tauri_plugin_updater::{Update, UpdaterExt as _};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
pub struct SilentUpdater {
|
||||
update_ready: AtomicBool,
|
||||
manual_cancel: Mutex<Option<CancellationToken>>,
|
||||
}
|
||||
|
||||
singleton!(SilentUpdater, SILENT_UPDATER);
|
||||
@@ -19,6 +23,7 @@ impl SilentUpdater {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
update_ready: AtomicBool::new(false),
|
||||
manual_cancel: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +97,72 @@ impl SilentUpdater {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the cached installer for `update`, deleting a cache that does not match it.
|
||||
fn verified_cache(app_handle: &tauri::AppHandle, 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| {
|
||||
verify_signature(app_handle, &bytes, &update.signature, &update.version)?;
|
||||
Ok(bytes)
|
||||
})
|
||||
} else {
|
||||
Err(anyhow::anyhow!("server offers v{}", update.version))
|
||||
};
|
||||
match bytes {
|
||||
Ok(bytes) => Some(bytes),
|
||||
Err(e) => {
|
||||
logging!(
|
||||
info,
|
||||
Type::System,
|
||||
"Update cache v{} is unusable: {e:#}, cleaning up",
|
||||
meta.version
|
||||
);
|
||||
Self::delete_cache();
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache directory is user-writable and feeds an elevated installer, so it is re-verified
|
||||
/// with the same rules `Update::download` applies.
|
||||
fn verify_signature(app_handle: &tauri::AppHandle, bytes: &[u8], signature: &str, version: &str) -> Result<()> {
|
||||
use base64::Engine as _;
|
||||
|
||||
let decode = |value: &str| -> Result<String> {
|
||||
Ok(String::from_utf8(
|
||||
base64::engine::general_purpose::STANDARD.decode(value)?,
|
||||
)?)
|
||||
};
|
||||
let config: tauri_plugin_updater::Config = serde_json::from_value(
|
||||
app_handle
|
||||
.config()
|
||||
.plugins
|
||||
.0
|
||||
.get("updater")
|
||||
.cloned()
|
||||
.context("updater is not configured")?,
|
||||
)?;
|
||||
|
||||
let public_key = minisign_verify::PublicKey::decode(&decode(&config.pubkey)?)?;
|
||||
let signature = minisign_verify::Signature::decode(&decode(signature)?)?;
|
||||
public_key
|
||||
.verify(bytes, &signature, true)
|
||||
.context("signature mismatch")?;
|
||||
|
||||
match signature
|
||||
.trusted_comment()
|
||||
.split('\t')
|
||||
.find_map(|field| field.strip_prefix("version:"))
|
||||
{
|
||||
Some(signed) => anyhow::ensure!(
|
||||
signed.trim_start_matches('v') == version,
|
||||
"signed for v{signed}, not v{version}"
|
||||
),
|
||||
None => anyhow::ensure!(!config.require_signed_version, "signature carries no version"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn is_build_to_stable(current: &str, remote: &str) -> bool {
|
||||
@@ -140,7 +211,121 @@ fn nsis_language_id(app_language: &str) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Same wire shape as the updater plugin's JS `DownloadEvent`.
|
||||
#[derive(Clone, Serialize)]
|
||||
#[serde(tag = "event", content = "data")]
|
||||
pub enum DownloadEvent {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Started {
|
||||
content_length: Option<u64>,
|
||||
},
|
||||
#[serde(rename_all = "camelCase")]
|
||||
Progress {
|
||||
chunk_length: usize,
|
||||
},
|
||||
Finished,
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
/// The manifest's URL, then the other mirror, then GitHub itself.
|
||||
fn download_sources(url: &tauri::Url) -> Vec<tauri::Url> {
|
||||
let origin = MIRRORS
|
||||
.iter()
|
||||
.find_map(|mirror| url.as_str().strip_prefix(mirror))
|
||||
.unwrap_or(url.as_str());
|
||||
let mut sources = vec![url.clone()];
|
||||
if origin.starts_with("https://github.com/") {
|
||||
let candidates = MIRRORS.iter().map(|mirror| format!("{mirror}{origin}"));
|
||||
for candidate in candidates.chain([origin.to_owned()]) {
|
||||
if let Ok(candidate) = tauri::Url::parse(&candidate)
|
||||
&& !sources.contains(&candidate)
|
||||
{
|
||||
sources.push(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
sources
|
||||
}
|
||||
|
||||
/// Tries every source with a throughput floor, then again stopping only on a stall, so a link
|
||||
/// that is slow everywhere still finishes.
|
||||
async fn download(update: &Update, on_event: impl Fn(DownloadEvent) + Sync) -> Result<Vec<u8>> {
|
||||
let sources = download_sources(&update.download_url);
|
||||
let mut last_error = None;
|
||||
for floor in [MIN_PROGRESS, 1] {
|
||||
for url in &sources {
|
||||
logging!(info, Type::System, "Downloading update v{} from {url}", update.version);
|
||||
match download_from(update, url, floor, &on_event).await {
|
||||
Ok(bytes) => {
|
||||
on_event(DownloadEvent::Finished);
|
||||
return Ok(bytes);
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(warn, Type::System, "Update download from {url} failed: {e:#}");
|
||||
last_error = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("no update download source")))
|
||||
}
|
||||
|
||||
async fn download_from(
|
||||
update: &Update,
|
||||
url: &tauri::Url,
|
||||
floor: u64,
|
||||
on_event: &(impl Fn(DownloadEvent) + Sync),
|
||||
) -> Result<Vec<u8>> {
|
||||
let mut source = update.clone();
|
||||
source.download_url = url.clone();
|
||||
let received = AtomicU64::new(0);
|
||||
let mut started = false;
|
||||
let fetch = source.download(
|
||||
|chunk_length, content_length| {
|
||||
if !std::mem::replace(&mut started, true) {
|
||||
on_event(DownloadEvent::Started { content_length });
|
||||
}
|
||||
received.fetch_add(chunk_length as u64, Ordering::Relaxed);
|
||||
on_event(DownloadEvent::Progress { chunk_length });
|
||||
},
|
||||
|| {},
|
||||
);
|
||||
tokio::pin!(fetch);
|
||||
let mut seen = 0;
|
||||
loop {
|
||||
tokio::select! {
|
||||
result = &mut fetch => return Ok(result?),
|
||||
() = tokio::time::sleep(PROGRESS_WINDOW) => {
|
||||
let total = received.load(Ordering::Relaxed);
|
||||
anyhow::ensure!(total - seen >= floor, "only {} bytes in {PROGRESS_WINDOW:?}", total - seen);
|
||||
seen = total;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SilentUpdater {
|
||||
/// Checks the server; Windows receives `/LANG` to suppress the NSIS language dialog,
|
||||
/// see `packages/windows/installer.nsi`.
|
||||
async fn check(app_handle: &tauri::AppHandle) -> Result<Option<Update>> {
|
||||
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 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?)
|
||||
}
|
||||
|
||||
async fn install(update: Update, bytes: Vec<u8>) -> Result<()> {
|
||||
Ok(tokio::task::spawn_blocking(move || update.install(&bytes)).await??)
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let current_version = env!("CARGO_PKG_VERSION");
|
||||
@@ -178,71 +363,30 @@ impl SilentUpdater {
|
||||
return false;
|
||||
}
|
||||
|
||||
let bytes = match Self::read_cache_bytes() {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
let update = match Self::check(app_handle).await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => {
|
||||
logging!(
|
||||
warn,
|
||||
info,
|
||||
Type::System,
|
||||
"Failed to read cached update bytes: {e:#}, cleaning up"
|
||||
"No update available from server, cache may be stale, cleaning up"
|
||||
);
|
||||
Self::delete_cache();
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
// Refresh metadata without re-downloading. Windows receives `/LANG` to suppress the
|
||||
// NSIS language dialog; see `packages/windows/installer.nsi`.
|
||||
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 lang_id = nsis_language_id(&clash_verge_i18n::current_language(verge_lang.as_deref()));
|
||||
updater_builder.installer_arg(format!("/LANG={lang_id}"))
|
||||
};
|
||||
let update = match updater_builder.build() {
|
||||
Ok(updater) => match updater.check().await {
|
||||
Ok(Some(u)) => u,
|
||||
Ok(None) => {
|
||||
logging!(
|
||||
info,
|
||||
Type::System,
|
||||
"No update available from server, cache may be stale, cleaning up"
|
||||
);
|
||||
Self::delete_cache();
|
||||
return false;
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::System,
|
||||
"Failed to check for update at startup: {e}, will retry next launch"
|
||||
);
|
||||
return false; // Keep cache for next attempt
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::System,
|
||||
"Failed to create updater: {e}, will retry next launch"
|
||||
"Failed to check for update at startup: {e:#}, will retry next launch"
|
||||
);
|
||||
return false;
|
||||
return false; // Keep cache for next attempt
|
||||
}
|
||||
};
|
||||
|
||||
// A changed server version invalidates the cached bytes.
|
||||
if update.version != *cached_version {
|
||||
logging!(
|
||||
info,
|
||||
Type::System,
|
||||
"Server version ({}) != cached version ({}), cache is stale, cleaning up",
|
||||
update.version,
|
||||
cached_version
|
||||
);
|
||||
Self::delete_cache();
|
||||
let Some(bytes) = Self::verified_cache(app_handle, &update) else {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
let version = update.version.clone();
|
||||
logging!(info, Type::System, "Installing cached update v{version} at startup...");
|
||||
@@ -250,49 +394,77 @@ impl SilentUpdater {
|
||||
Self::show_update_splash(app_handle, &version);
|
||||
|
||||
// `install()` may hang (#2558); on Windows NSIS can take over without returning.
|
||||
let install_result = tokio::task::spawn_blocking({
|
||||
let bytes = bytes.clone();
|
||||
let update = update.clone();
|
||||
move || update.install(&bytes)
|
||||
});
|
||||
|
||||
let success = match tokio::time::timeout(std::time::Duration::from_secs(30), install_result).await {
|
||||
Ok(Ok(Ok(()))) => {
|
||||
let install = tokio::time::timeout(std::time::Duration::from_secs(30), Self::install(update, bytes));
|
||||
match install
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(anyhow::anyhow!("install timed out (30s)")))
|
||||
{
|
||||
Ok(()) => {
|
||||
logging!(info, Type::System, "Update v{version} install triggered at startup");
|
||||
Self::delete_cache();
|
||||
true
|
||||
}
|
||||
Ok(Ok(Err(e))) => {
|
||||
Err(e) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::System,
|
||||
"Startup install failed: {e}, will retry next launch"
|
||||
);
|
||||
false
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::System,
|
||||
"Startup install task panicked: {e}, will retry next launch"
|
||||
);
|
||||
false
|
||||
}
|
||||
Err(_) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::System,
|
||||
"Startup install timed out (30s), will retry next launch"
|
||||
"Startup install failed: {e:#}, will retry next launch"
|
||||
);
|
||||
Self::close_update_splash(app_handle);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs `version` for the update dialog, reusing the cache when it holds that version;
|
||||
/// `false` when cancelled before the installer starts.
|
||||
pub async fn install_update(
|
||||
&self,
|
||||
app_handle: &tauri::AppHandle,
|
||||
version: &str,
|
||||
on_event: impl Fn(DownloadEvent) + Sync,
|
||||
) -> Result<bool> {
|
||||
let cancel = CancellationToken::new();
|
||||
*self.manual_cancel.lock() = Some(cancel.clone());
|
||||
let prepared = tokio::select! {
|
||||
prepared = Self::prepare_install(app_handle, version, on_event) => Some(prepared),
|
||||
() = cancel.cancelled() => None,
|
||||
};
|
||||
// `cancel_download` cancels under the lock, so once the token is taken back its state is
|
||||
// final; a cancel during the last synchronous poll of `prepare_install` still wins.
|
||||
self.manual_cancel.lock().take();
|
||||
let Some((update, bytes)) = prepared.filter(|_| !cancel.is_cancelled()).transpose()? else {
|
||||
logging!(info, Type::System, "Update v{version} cancelled");
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
if !success {
|
||||
Self::close_update_splash(app_handle);
|
||||
}
|
||||
logging!(info, Type::System, "Installing update v{version}...");
|
||||
Self::install(update, bytes).await?;
|
||||
Self::delete_cache();
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
success
|
||||
async fn prepare_install(
|
||||
app_handle: &tauri::AppHandle,
|
||||
version: &str,
|
||||
on_event: impl Fn(DownloadEvent) + Sync,
|
||||
) -> Result<(Update, Vec<u8>)> {
|
||||
let update = Self::check(app_handle)
|
||||
.await?
|
||||
.filter(|update| update.version == version)
|
||||
.with_context(|| format!("v{version} is no longer offered"))?;
|
||||
let bytes = match Self::verified_cache(app_handle, &update) {
|
||||
Some(bytes) => bytes,
|
||||
None => download(&update, on_event).await?,
|
||||
};
|
||||
Ok((update, bytes))
|
||||
}
|
||||
|
||||
pub fn cancel_download(&self) {
|
||||
let mut slot = self.manual_cancel.lock();
|
||||
if let Some(cancel) = slot.take() {
|
||||
cancel.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,24 +621,13 @@ impl SilentUpdater {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
logging!(info, Type::System, "Silent updater: downloading v{version}...");
|
||||
let bytes = update
|
||||
.download(
|
||||
|chunk_len, content_len| {
|
||||
logging!(
|
||||
debug,
|
||||
Type::System,
|
||||
"Silent updater download progress: chunk={chunk_len}, total={content_len:?}"
|
||||
);
|
||||
},
|
||||
|| {
|
||||
logging!(info, Type::System, "Silent updater: download complete");
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
if let Err(e) = Self::write_cache(&bytes, &version) {
|
||||
logging!(warn, Type::System, "Silent updater: failed to write cache: {e:#}");
|
||||
if Self::verified_cache(app_handle, &update).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)?;
|
||||
}
|
||||
|
||||
self.update_ready.store(true, Ordering::Release);
|
||||
|
||||
@@ -63,8 +63,6 @@ async fn ensure_effect(
|
||||
}
|
||||
Effect::ClashConfig => {
|
||||
manager.update_config_in_patch(update).await?;
|
||||
Config::runtime().await.apply();
|
||||
announce(Refresh::Clash);
|
||||
}
|
||||
Effect::Autostart => autostart::update_launch().await?,
|
||||
Effect::Language => {
|
||||
@@ -123,7 +121,7 @@ async fn ensure_effect(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn apply_inner(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
|
||||
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
|
||||
let manager = CoreManager::global();
|
||||
let update = manager.claim_config_update(config_write)?;
|
||||
let clash = Config::clash().await;
|
||||
@@ -167,6 +165,7 @@ async fn apply_inner(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effect
|
||||
if let Err(error) = result {
|
||||
transaction.rollback();
|
||||
if !Arc::ptr_eq(&original_runtime, &runtime.data_arc()) {
|
||||
announce(Refresh::Clash);
|
||||
// The Core already loaded this runtime; restoring its file would only hide that state.
|
||||
let runtime_path = crate::utils::dirs::app_home_dir()?.join(crate::constants::files::RUNTIME_CONFIG);
|
||||
snapshots.retain(|snapshot| snapshot.path != runtime_path);
|
||||
@@ -179,6 +178,9 @@ async fn apply_inner(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effect
|
||||
transaction.commit();
|
||||
match patch {
|
||||
Patch::Verge { .. } => {
|
||||
if effects.contains(&Effect::ClashConfig) {
|
||||
announce(Refresh::Clash);
|
||||
}
|
||||
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
|
||||
announce(Refresh::Verge);
|
||||
}
|
||||
@@ -187,16 +189,6 @@ async fn apply_inner(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effect
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
|
||||
let runtime = Config::runtime().await;
|
||||
let original = runtime.data_arc();
|
||||
let result = crate::core::notify::after_commit(apply_inner(config_write, patch, effects)).await;
|
||||
if result.is_err() && !Arc::ptr_eq(&original, &runtime.data_arc()) {
|
||||
announce(Refresh::Clash);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -142,6 +142,8 @@ mod app_init {
|
||||
cmd::get_network_interfaces,
|
||||
cmd::get_system_hostname,
|
||||
cmd::restart_app,
|
||||
cmd::install_update,
|
||||
cmd::cancel_update_download,
|
||||
cmd::restart_core,
|
||||
cmd::upgrade_clash_core,
|
||||
cmd::get_runtime_state,
|
||||
|
||||
@@ -1,46 +1,18 @@
|
||||
use backon::{BackoffBuilder as _, ExponentialBackoff, ExponentialBuilder};
|
||||
use std::{future::Future, num::NonZeroUsize, time::Duration};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Backoff {
|
||||
Fixed(Duration),
|
||||
#[allow(dead_code)]
|
||||
Exponential {
|
||||
base: Duration,
|
||||
cap: Duration,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct RetryPolicy {
|
||||
pub attempts: NonZeroUsize,
|
||||
pub backoff: Backoff,
|
||||
pub jitter: bool,
|
||||
delay: Duration,
|
||||
}
|
||||
|
||||
impl RetryPolicy {
|
||||
pub const fn fixed(attempts: NonZeroUsize, delay: Duration) -> Self {
|
||||
Self {
|
||||
attempts,
|
||||
backoff: Backoff::Fixed(delay),
|
||||
jitter: false,
|
||||
}
|
||||
Self { attempts, delay }
|
||||
}
|
||||
|
||||
fn delays(self) -> ExponentialBackoff {
|
||||
let (base, cap, factor) = match self.backoff {
|
||||
Backoff::Fixed(delay) => (delay, delay, 1.0),
|
||||
Backoff::Exponential { base, cap } => (base, cap, 2.0),
|
||||
};
|
||||
let mut builder = ExponentialBuilder::default()
|
||||
.with_min_delay(base)
|
||||
.with_max_delay(cap)
|
||||
.with_factor(factor)
|
||||
.with_max_times(self.attempts.get() - 1);
|
||||
if self.jitter {
|
||||
builder = builder.with_jitter();
|
||||
}
|
||||
builder.build()
|
||||
fn delays(self) -> impl Iterator<Item = Duration> {
|
||||
std::iter::repeat_n(self.delay, self.attempts.get() - 1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,11 +54,7 @@ pub async fn try_strategies<
|
||||
mut operation: impl FnMut(S) -> Fut + Send,
|
||||
) -> Result<(S, T), E> {
|
||||
retry(
|
||||
RetryPolicy {
|
||||
attempts: NonZeroUsize::MIN.saturating_add(N),
|
||||
backoff: Backoff::Fixed(Duration::ZERO),
|
||||
jitter: false,
|
||||
},
|
||||
RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(N), Duration::ZERO),
|
||||
move |attempt| {
|
||||
let strategy = if attempt == 0 { first } else { rest[attempt - 1] };
|
||||
let future = operation(strategy);
|
||||
@@ -145,11 +113,7 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn retries_stop_at_success_terminal_error_or_attempt_limit() {
|
||||
let policy = RetryPolicy {
|
||||
attempts: NonZeroUsize::MIN.saturating_add(2),
|
||||
backoff: Backoff::Fixed(Duration::ZERO),
|
||||
jitter: false,
|
||||
};
|
||||
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), Duration::ZERO);
|
||||
let mut calls = 0;
|
||||
let success = retry(policy, |attempt| {
|
||||
calls += 1;
|
||||
|
||||
Reference in New Issue
Block a user