Compare commits

..
Author SHA1 Message Date
Tunglies 69420ebdea refactor(lightweight): name countdown callbacks 2026-11-28 21:53:59 +08:00
Tunglies 12ad0c85d9 refactor(lightweight): use the task countdown driver 2026-11-28 21:49:56 +08:00
Tunglies 63100bbc80 docs(backend): define workspace crate boundaries 2026-11-28 21:45:28 +08:00
Tunglies f5d824c80b fix(timer): omit profile identifier from panic log 2026-11-28 21:13:29 +08:00
Tunglies f059d1ebb5 refactor(backend): extract workspace task drivers 2026-11-28 21:13:05 +08:00
Tunglies d4b138d553 docs(changelog): drop backend actor migration entry 2026-11-28 20:57:52 +08:00
Tunglies 47811bd76b test(backend): remove actor migration regression cases 2026-11-28 20:57:17 +08:00
Tunglies 5cc9531a15 refactor(backend): give background operations single task owners 2026-11-28 20:53:02 +08:00
Tunglies 50ddb84f19 docs(backend): define background task ownership 2026-11-28 20:51:41 +08:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 377d497eb3 chore(deps): update rust toolchain to v1.100.1 (#8757)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 09:55:39 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 2bce842968 chore(deps): update rust crate zip to 9.9.0 (#8756)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-28 08:35:13 +00:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
e813a80902 chore(deps): update github/gh-aw-actions action to v1.4.1 (#8755)
* chore(deps): update github/gh-aw-actions action to v1.4.1

* chore(deps): bump agentic workflows to v1.4.1

- Upgrade via `gh aw upgrade`

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-11-28 07:51:25 +00:00
49 changed files with 1685 additions and 1348 deletions
+1 -1
View File
@@ -8,7 +8,7 @@
"pnpmVersion": "12.23.0"
},
"ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.0",
"version": "1.100.1",
"profile": "default"
},
"ghcr.io/devcontainers/features/git:1": {},
+32 -7
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.4.0": {
"github/gh-aw-actions/setup@v1.4.1": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.4.0",
"sha": "b907753c079ddd7d6829a0d8c24e02e818b4b45f"
"version": "v1.4.1",
"sha": "367d4dc4e89caf85422092845006e4a4a660d926"
}
},
"containers": {
@@ -47,6 +47,11 @@
"digest": "sha256:b9cd8d7d1a9c2693e5d91db035a678fb1ea8d87ce691e08ec091b327e5e8ba75",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.20@sha256:b9cd8d7d1a9c2693e5d91db035a678fb1ea8d87ce691e08ec091b327e5e8ba75"
},
"ghcr.io/github/gh-aw-firewall/agent:0.29.21": {
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21",
"digest": "sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21@sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
@@ -82,6 +87,11 @@
"digest": "sha256:fc6c1eff686514d26ff90ae1398e0f6e3dcad8d2e43d11b16df312c1e72c0ace",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.20@sha256:fc6c1eff686514d26ff90ae1398e0f6e3dcad8d2e43d11b16df312c1e72c0ace"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21",
"digest": "sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21@sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
@@ -97,6 +107,11 @@
"digest": "sha256:743396030b149763880978f35ad679fe02b1c0be6697b01fbf6d43f4ac2ae081",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.20@sha256:743396030b149763880978f35ad679fe02b1c0be6697b01fbf6d43f4ac2ae081"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21",
"digest": "sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21@sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
@@ -107,6 +122,11 @@
"digest": "sha256:732c3741e866099c6c2095aad7c84a18266486563deb51d7cce723f9bfc48721",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.20@sha256:732c3741e866099c6c2095aad7c84a18266486563deb51d7cce723f9bfc48721"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.21": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.21",
"digest": "sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.21@sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a"
},
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
@@ -142,10 +162,15 @@
"digest": "sha256:1c4a4a12fcea206a81d656cb1f73847420a2c041d02ab51235364079a1e31d71",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.20@sha256:1c4a4a12fcea206a81d656cb1f73847420a2c041d02ab51235364079a1e31d71"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.14": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.14",
"digest": "sha256:716b41d53a20660e945c351c08140380430d65d98d3263596e45114c29fa7a43",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.14@sha256:716b41d53a20660e945c351c08140380430d65d98d3263596e45114c29fa7a43"
"ghcr.io/github/gh-aw-firewall/squid:0.29.21": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21",
"digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21@sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.15": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.15",
"digest": "sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.15@sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1"
},
"ghcr.io/github/gh-aw-node": {
"image": "ghcr.io/github/gh-aw-node",
@@ -156,6 +156,7 @@ Use the task routes above first. This inventory is not required startup context.
- `.github/aw/otel.md`
- `.github/aw/patterns.md`
- `.github/aw/playwright.md`
- `.github/aw/pr-finisher.md`
- `.github/aw/pr-reviewer.md`
- `.github/aw/release-workflow.md`
- `.github/aw/repo-factory.md`
+3 -3
View File
@@ -154,7 +154,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.100.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -240,7 +240,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.100.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -373,7 +373,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.100.1'
targets: ${{ matrix.target }}
- name: Rust Cache
+2 -2
View File
@@ -31,9 +31,9 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@b907753c079ddd7d6829a0d8c24e02e818b4b45f # v1.4.0
uses: github/gh-aw-actions/setup-cli@367d4dc4e89caf85422092845006e4a4a660d926 # v1.4.1
with:
version: v1.4.0
version: v1.4.1
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
+2 -2
View File
@@ -74,7 +74,7 @@ jobs:
- name: Install Rust Stable
if: github.event.inputs[matrix.input] == 'true'
uses: dtolnay/rust-toolchain@1.100.0
uses: dtolnay/rust-toolchain@1.100.1
- name: Rust Cache
if: github.event.inputs[matrix.input] == 'true'
@@ -121,7 +121,7 @@ jobs:
if: github.event.inputs[matrix.input] == 'true'
run: |
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
rustup target add ${{ matrix.target }} --toolchain 1.100.0 || rustup target add ${{ matrix.target }}
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
rustup target list --installed
echo "Rust target ${{ matrix.target }} installed."
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -203,7 +203,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.100.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -308,7 +308,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.100.1'
targets: ${{ matrix.target }}
- name: Rust Cache
@@ -439,7 +439,7 @@ jobs:
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.100.1'
targets: ${{ matrix.target }}
- name: Rust Cache
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -22,7 +22,7 @@ jobs:
- name: Install Rust
uses: dtolnay/rust-toolchain@master
with:
toolchain: '1.100.0'
toolchain: '1.100.1'
targets: x86_64-pc-windows-msvc
- name: Install Node
+1 -1
View File
@@ -1,3 +1,3 @@
nodejs 26.13.1
pnpm 12.23.0
rust 1.100.0
rust 1.100.1
Generated
+12 -2
View File
@@ -1098,6 +1098,7 @@ dependencies = [
"clash-verge-logging",
"clash-verge-media-unlock",
"clash-verge-signal",
"clash-verge-task",
"clash_verge_service_ipc",
"dark-light",
"deelevate",
@@ -1222,6 +1223,15 @@ dependencies = [
"tokio",
]
[[package]]
name = "clash-verge-task"
version = "0.1.0"
dependencies = [
"futures",
"parking_lot 0.13.0",
"tokio",
]
[[package]]
name = "clash_verge_service_ipc"
version = "2.8.2"
@@ -10199,9 +10209,9 @@ dependencies = [
[[package]]
name = "zip"
version = "9.8.2"
version = "9.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9"
dependencies = [
"aes",
"bzip2",
+3
View File
@@ -2,6 +2,7 @@
members = [
"src-tauri",
"crates/clash-verge-draft",
"crates/clash-verge-task",
"crates/clash-verge-media-unlock",
"crates/clash-verge-logging",
"crates/clash-verge-signal",
@@ -52,6 +53,7 @@ muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdf
[workspace.dependencies]
clash-verge-draft = { path = "crates/clash-verge-draft" }
clash-verge-task = { path = "crates/clash-verge-task" }
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
clash-verge-logging = { path = "crates/clash-verge-logging" }
clash-verge-signal = { path = "crates/clash-verge-signal" }
@@ -65,6 +67,7 @@ tauri = { version = "2.12.7" }
tauri-plugin-clipboard-manager = "2.5.0"
parking_lot = "0.13.0"
anyhow = "1.0.105"
futures = "0.3.34"
chrono = "0.4.45"
criterion = { version = "0.8.2", features = ["async_tokio"] }
tokio = { version = "1.54.1", features = [
+51
View File
@@ -0,0 +1,51 @@
# Workspace Crate Architecture
## Choose the boundary
- Extract a capability whose invariants can be owned behind a small API. Before
creating a crate, identify its owner, what callers supply, and what can be
verified through the crate API. Keep a module when the proposed boundary only
relocates implementation or introduces a pass-through API.
- Keep the dependency direction from the app to the crate. Resolve app paths,
read product settings, start app-owned tasks, and publish UI events in the app.
Pass the values, resources, or callbacks the crate needs. For example,
[logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the
app supplies directories and limits through `LoggerConfig`.
- Keep framework and platform dependencies scoped to the capability that needs
them. Runtime-independent logic should be runnable without the desktop app.
A platform adapter can own runtime startup when its resource lifetime requires
it, as [signal](clash-verge-signal/src/lib.rs) does for Linux shutdown.
## Design the API
- Start with concrete types for data and outcomes. Use a trait when methods must
cooperate under one contract, a closure for one supplied operation, and
`impl Future` when the caller owns scheduling. Add type parameters and bounds
where the contract needs them. Use dynamic dispatch when the API needs to hold
heterogeneous implementations, as [draft](clash-verge-draft/src/lib.rs) does
for the layers claimed by `DraftTransaction`.
- Keep state and its invariants with one owner. Expose snapshots, typed
operations, or guards. Draft owns claim, commit, and rollback of its in-memory
layers. The caller owns persistence and the recovery of external effects.
- Name product workspace libraries with the `clash-verge-` prefix and inherit
workspace lints. Reuse workspace dependencies where available and declare
only the features the crate needs.
## Own background work
- Give ordered start, replacement, and cleanup to one task owner. Reuse
[`clash-verge-task`](clash-verge-task/src/lib.rs) for coalescing scheduled jobs
and replaceable sessions. Keep domain policy, execution callbacks, and runtime
startup at the call site. Select a driver whose delivery guarantees match the
caller's needs.
- Use typed inputs. Coalesce only when intermediate requests may be skipped.
Reply with the actual outcome when a caller waits for completion. Preserve
transaction boundaries and keep the reply path free of locks held by the
waiting caller. Cancel only at safe boundaries and own issued effects through
completion or explicit reconciliation.
Verify the extracted contract through its public API when practical. Use
`cargo test -p <crate>` for focused tests and keep native behavior checks at the
app boundary. For timing, prefer Tokio's paused clock for task drivers or a
small clock interface where time is an input, as in
[`clash-verge-limiter`](clash-verge-limiter/src/lib.rs).
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "clash-verge-task"
version = "0.1.0"
edition = "2024"
publish = false
[dependencies]
futures = { workspace = true }
parking_lot = { workspace = true }
tokio = { workspace = true }
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
[lints]
workspace = true
+60
View File
@@ -0,0 +1,60 @@
use std::{future::Future, time::Duration};
use tokio::{sync::mpsc, time::sleep};
enum Command<T> {
Arm(T),
Disarm,
}
pub struct Countdown<T> {
commands: mpsc::UnboundedSender<Command<T>>,
}
impl<T> Countdown<T> {
pub fn arm(&self, input: T) {
let _ = self.commands.send(Command::Arm(input));
}
pub fn disarm(&self) {
let _ = self.commands.send(Command::Disarm);
}
}
/// Create a countdown with a caller-owned driver. An active countdown ignores
/// additional arms. Disarm and channel closure take precedence over expiry.
///
/// Return `None` from `delay` to reject an arm before starting the countdown.
/// The delay future may be dropped on disarm, including while it loads the duration.
pub fn new<T, Fut>(
mut delay: impl FnMut(T) -> Option<Fut> + Send,
mut elapsed: impl FnMut(T) + Send,
) -> (Countdown<T>, impl Future<Output = ()> + Send)
where
T: Copy + Send,
Fut: Future<Output = Duration> + Send,
{
let (commands, mut receiver) = mpsc::unbounded_channel();
let driver = async move {
while let Some(command) = receiver.recv().await {
let Command::Arm(input) = command else { continue };
let Some(delay) = delay(input) else { continue };
let countdown = async { sleep(delay.await).await };
tokio::pin!(countdown);
loop {
tokio::select! {
biased;
command = receiver.recv() => match command {
Some(Command::Arm(_)) => {}
Some(Command::Disarm) => break,
None => return,
},
() = &mut countdown => {
elapsed(input);
break;
}
}
}
}
};
(Countdown { commands }, driver)
}
+5
View File
@@ -0,0 +1,5 @@
//! Single-owner task drivers with caller-managed runtime and cancellation.
pub mod countdown;
pub mod scheduled_task;
pub mod watch_task;
@@ -0,0 +1,94 @@
use futures::FutureExt as _;
use parking_lot::Mutex;
use std::{future::Future, panic::AssertUnwindSafe, sync::Arc};
use tokio::{
sync::Notify,
time::{Instant, sleep_until},
};
/// The next decision after the driver drains pending inputs.
pub enum Next<W> {
Idle,
At(Instant),
Run(W),
}
/// Synchronous policy owned and called by one driver.
pub trait ScheduledTask {
/// The merged pending input. Its default value represents no requests.
type Input: Default;
type Work: Copy + Send;
type Output;
fn on_input(&mut self, input: Self::Input, now: Instant);
fn next(&mut self, now: Instant) -> Next<Self::Work>;
/// Receives the execution result or an unwind from the execution callback.
fn finished(&mut self, work: Self::Work, result: std::thread::Result<Self::Output>, now: Instant);
}
/// A coalescing slot shared with one driver.
pub struct Mailbox<I> {
pending: Mutex<I>,
changed: Notify,
}
impl<I> Mailbox<I> {
/// Merge into the pending slot under a short synchronous lock.
///
/// Return true from `merge` when the driver should wake up. This only
/// submits input. Any completion reply belongs to the caller's protocol.
pub fn update(&self, merge: impl FnOnce(&mut I) -> bool) {
let changed = merge(&mut *self.pending.lock());
if changed {
self.changed.notify_one();
}
}
}
/// Create the mailbox and its driver. The caller chooses how to run the future.
///
/// While the driver is running, pending inputs wake idle waits and do not
/// interrupt an active job. Keep the driver alive until any issued effects
/// complete. Dropping producers does not shut it down.
pub fn new<P, F, Fut>(policy: P, execute: F) -> (Arc<Mailbox<P::Input>>, impl Future<Output = ()> + Send + 'static)
where
P: ScheduledTask + Send + 'static,
P::Input: Send + 'static,
F: FnMut(P::Work) -> Fut + Send + 'static,
Fut: Future<Output = P::Output> + Send + 'static,
{
let inbox = Arc::new(Mailbox {
pending: Mutex::default(),
changed: Notify::new(),
});
let receiver = Arc::clone(&inbox);
(inbox, drive(policy, receiver, execute))
}
async fn drive<P, F, Fut>(mut policy: P, inbox: Arc<Mailbox<P::Input>>, mut execute: F)
where
P: ScheduledTask,
F: FnMut(P::Work) -> Fut,
Fut: Future<Output = P::Output>,
{
loop {
let input = std::mem::take(&mut *inbox.pending.lock());
let now = Instant::now();
policy.on_input(input, now);
match policy.next(now) {
Next::Idle => inbox.changed.notified().await,
Next::At(due) => {
tokio::select! {
_ = inbox.changed.notified() => {}
_ = sleep_until(due) => {}
}
}
Next::Run(work) => {
// Pending inputs merge while the job runs. They cannot interrupt its effects.
let run = &mut execute;
let result = AssertUnwindSafe(async move { run(work).await }).catch_unwind().await;
policy.finished(work, result, Instant::now());
}
}
}
}
+31
View File
@@ -0,0 +1,31 @@
use futures::FutureExt as _;
use std::{future::Future, panic::AssertUnwindSafe};
use tokio::sync::watch;
/// Run a session for each observed nonempty plan, beginning on the first change.
///
/// Subscribe while the plan is `None` before publishing the first session.
/// While a session runs, plans may coalesce to the latest value. The callback
/// chooses where to observe replacements and owns any issued effects until it
/// returns. An unwinding callback is reported before observing the next plan.
pub async fn run<T, F, Fut>(mut desired: watch::Receiver<Option<T>>, mut run: F, mut on_panic: impl FnMut(T) + Send)
where
T: Clone + Send + Sync,
F: FnMut(T, watch::Receiver<Option<T>>) -> Fut + Send,
Fut: Future<Output = ()> + Send,
{
while desired.changed().await.is_ok() {
let state = desired.borrow_and_update().clone();
if let Some(state) = state {
// Cancellation can consume updates on this clone without skipping them in the owner.
let updates = desired.clone();
if AssertUnwindSafe(async { run(state.clone(), updates).await })
.catch_unwind()
.await
.is_err()
{
on_panic(state);
}
}
}
}
+213
View File
@@ -0,0 +1,213 @@
use clash_verge_task::{
countdown,
scheduled_task::{self, Mailbox, Next, ScheduledTask},
watch_task,
};
use std::{error::Error, future::ready, time::Duration};
use tokio::{
sync::{mpsc, oneshot, watch},
time::{Instant, advance, timeout},
};
type TestResult = Result<(), Box<dyn Error>>;
struct Schedule {
due: Option<Instant>,
completed: mpsc::UnboundedSender<bool>,
}
impl ScheduledTask for Schedule {
type Input = Option<Instant>;
type Work = Instant;
type Output = ();
fn on_input(&mut self, input: Self::Input, _: Instant) {
self.due = self.due.into_iter().chain(input).min();
}
fn next(&mut self, now: Instant) -> Next<Instant> {
match self.due {
Some(due) if due <= now => {
self.due = None;
Next::Run(due)
}
Some(due) => Next::At(due),
None => Next::Idle,
}
}
fn finished(&mut self, _: Instant, result: std::thread::Result<()>, _: Instant) {
let _ = self.completed.send(result.is_ok());
}
}
fn request(mailbox: &Mailbox<Option<Instant>>, due: Instant) {
mailbox.update(|pending| {
if pending.is_some_and(|current| current <= due) {
return false;
}
*pending = Some(due);
true
});
}
async fn receive<T: Send>(receiver: &mut mpsc::UnboundedReceiver<T>) -> Result<T, Box<dyn Error>> {
timeout(Duration::from_secs(10), receiver.recv())
.await?
.ok_or_else(|| "driver event channel closed".into())
}
#[tokio::test(start_paused = true)]
async fn countdown_keeps_the_first_arm_until_it_expires() -> TestResult {
let delay = Duration::from_secs(4);
let (elapsed, mut events) = mpsc::unbounded_channel();
let (countdown, driver) = countdown::new(
move |_| Some(ready(delay)),
move |input| {
let _ = elapsed.send(input);
},
);
let mut driver = Box::pin(driver);
let start = Instant::now();
countdown.arm(1);
assert!(futures::poll!(driver.as_mut()).is_pending());
advance(Duration::from_secs(2)).await;
countdown.arm(2);
let driver = tokio::spawn(driver);
assert_eq!(receive(&mut events).await?, 1);
assert_eq!(Instant::now() - start, delay);
drop(countdown);
driver.await?;
assert!(events.try_recv().is_err());
Ok(())
}
#[tokio::test(start_paused = true)]
async fn ready_disarm_wins_and_the_next_arm_starts_a_new_countdown() -> TestResult {
let delay = Duration::from_secs(4);
let (elapsed, mut events) = mpsc::unbounded_channel();
let (countdown, driver) = countdown::new(
move |_| Some(ready(delay)),
move |input| {
let _ = elapsed.send(input);
},
);
let mut driver = Box::pin(driver);
countdown.arm(1);
assert!(futures::poll!(driver.as_mut()).is_pending());
advance(delay).await;
countdown.disarm();
countdown.arm(2);
let rearmed_at = Instant::now();
let driver = tokio::spawn(driver);
assert_eq!(receive(&mut events).await?, 2);
assert_eq!(Instant::now() - rearmed_at, delay);
drop(countdown);
driver.await?;
Ok(())
}
#[tokio::test(start_paused = true)]
async fn an_earlier_request_reschedules_an_idle_wait() -> TestResult {
let (completed, mut results) = mpsc::unbounded_channel();
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, |_| async {});
let mut driver = Box::pin(driver);
let start = Instant::now();
request(&mailbox, start + Duration::from_secs(8));
assert!(futures::poll!(driver.as_mut()).is_pending());
request(&mailbox, start + Duration::from_secs(2));
let driver = tokio::spawn(driver);
assert!(receive(&mut results).await?);
assert_eq!(Instant::now() - start, Duration::from_secs(2));
driver.abort();
Ok(())
}
#[tokio::test(start_paused = true)]
async fn active_work_finishes_before_one_coalesced_successor() -> TestResult {
let (completed, mut results) = mpsc::unbounded_channel();
let (started, mut runs) = mpsc::unbounded_channel();
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, move |due| {
let (release, wait) = oneshot::channel();
let _ = started.send((due, release));
async move {
let _ = wait.await;
}
});
let driver = tokio::spawn(driver);
let start = Instant::now();
request(&mailbox, start);
let (_, release) = receive(&mut runs).await?;
let next = start + Duration::from_secs(2);
request(&mailbox, start + Duration::from_secs(4));
request(&mailbox, next);
advance(Duration::from_secs(5)).await;
assert!(runs.try_recv().is_err());
assert!(results.try_recv().is_err());
release.send(()).map_err(|()| "first job was dropped")?;
assert!(receive(&mut results).await?);
let (due, release) = receive(&mut runs).await?;
assert_eq!(due, next);
release.send(()).map_err(|()| "second job was dropped")?;
assert!(receive(&mut results).await?);
assert!(timeout(Duration::from_secs(1), runs.recv()).await.is_err());
driver.abort();
Ok(())
}
#[tokio::test(start_paused = true)]
#[allow(clippy::panic, reason = "inject an unwind into the execution future")]
async fn a_job_panic_reports_failure_and_allows_more_work() -> TestResult {
let (completed, mut results) = mpsc::unbounded_channel();
let start = Instant::now();
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, move |due| async move {
if due == start {
panic!("test job panic");
}
});
let driver = tokio::spawn(driver);
request(&mailbox, start);
assert!(!receive(&mut results).await?);
request(&mailbox, start + Duration::from_secs(1));
assert!(receive(&mut results).await?);
driver.abort();
Ok(())
}
#[tokio::test(start_paused = true)]
#[allow(clippy::panic, reason = "inject an unwind after observing session replacement")]
async fn a_session_panic_does_not_consume_the_replacement() -> TestResult {
let (plan, desired) = watch::channel(None);
let (event, mut events) = mpsc::unbounded_channel();
let panicked = event.clone();
let driver = tokio::spawn(watch_task::run(
desired,
move |session, mut updates| {
let event = event.clone();
async move {
let _ = event.send((session, false));
if session == 1 && updates.changed().await.is_ok() {
panic!("test session panic");
}
}
},
move |session| {
let _ = panicked.send((session, true));
},
));
plan.send_replace(Some(1));
assert_eq!(receive(&mut events).await?, (1, false));
plan.send_replace(Some(2));
assert_eq!(receive(&mut events).await?, (1, true));
assert_eq!(receive(&mut events).await?, (2, false));
drop(plan);
driver.await?;
Ok(())
}
+1 -1
View File
@@ -1,3 +1,3 @@
[toolchain]
channel = "1.100.0"
channel = "1.100.1"
components = ["rustfmt", "clippy"]
+16 -21
View File
@@ -1,24 +1,19 @@
# Backend Architecture Guardrails
These rules supplement the repository's root `AGENTS.md`.
Use [Workspace Crate Architecture](../crates/AGENTS.md) when extracting backend
capabilities or changing background task ownership.
- **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.
- **Configuration and effects.** `config` owns source configuration, drafts, and
persistence. The effects layer classifies every Verge patch field, including
fields without effects and platform-specific fields, and reconciles requested
state in dependency order. Publish rollbackable state after persistence and
commit. On failure, preserve already applied runtime effects, independently
committed state, their notifications, and the error.
- **Wire contract.** Use typed notifications and preserve event names, status
values, and payload compatibility with frontend consumers.
- **Lock order.** Acquire configuration-write, configuration-update, Core
lifecycle, and DNS ownership in that order when needed. Preserve independent
transaction boundaries and release synchronous guards before suspension.
- **Retries.** Reuse the backend retry policy and preserve attempts, delays, and
terminal errors. Keep monitor lifetime, condition waits, and candidate fallback
under their own contracts.
+3 -2
View File
@@ -31,6 +31,7 @@ tauri-build = { version = "2.7.6", features = [] }
[dependencies]
clash-verge-draft = { workspace = true }
clash-verge-task = { workspace = true }
clash-verge-media-unlock = { workspace = true }
clash-verge-logging = { workspace = true }
clash-verge-i18n = { workspace = true }
@@ -75,14 +76,14 @@ tauri-plugin-dialog = "2.8.4"
tauri-plugin-fs = "2.7.1"
tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "2.5.0"
zip = "9.8.2"
zip = "9.9.0"
flate2 = "1.1.11"
reqwest_dav = "0.4.0"
aes-gcm = { version = "0.11.1" }
base64 = "0.23.1"
sha2 = "0.11.2"
getrandom = "0.4.3"
futures = "0.3.34"
futures = { workspace = true }
gethostname = "1.1.0"
tauri-plugin-notification = "2.8.1"
backon = { version = "1.6.0", features = ["tokio-sleep"] }
+2 -15
View File
@@ -66,8 +66,7 @@ pub async fn install_update(
on_event: Channel<DownloadEvent>,
) -> CmdResult<InstallUpdateOutcome> {
SilentUpdater::global()
.ok_or("silent updater is not running")?
.install_update(&app_handle, &version, move |event| {
.install_update(&app_handle, &version, |event| {
let _ = on_event.send(event);
})
.await
@@ -77,19 +76,7 @@ pub async fn install_update(
#[tauri::command]
#[specta::specta]
pub fn cancel_update_download() {
if let Some(updater) = SilentUpdater::global() {
updater.cancel_download();
}
}
#[tauri::command]
#[specta::specta]
pub async fn get_staged_update() -> CmdResult<Option<std::string::String>> {
SilentUpdater::global()
.ok_or("silent updater is not running")?
.staged_version()
.await
.stringify_err()
SilentUpdater::global().cancel_download();
}
#[tauri::command]
+2 -2
View File
@@ -3,7 +3,7 @@ use crate::{
cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, PrfItem},
core::auto_backup::{AutoBackupManager, AutoBackupTrigger},
core::auto_backup::{self, AutoBackupTrigger},
core::{
CoreManager, handle,
validate::{CoreConfigValidator, ValidationOutcome},
@@ -86,7 +86,7 @@ pub async fn save_profile_file(
if changes_applied.is_valid()
&& let Some(trigger) = backup_trigger
{
AutoBackupManager::trigger_backup(trigger);
auto_backup::trigger_backup(trigger);
}
Ok(changes_applied)
+129 -151
View File
@@ -1,29 +1,22 @@
use crate::{
config::{Config, IVerge},
feat::create_local_backup_with_namer,
process::AsyncHandler,
process::scheduled_task::{self, Mailbox, Next, ScheduledTask},
utils::dirs::local_backup_dir,
};
use anyhow::Result;
use chrono::Local;
use clash_verge_logging::{Type, logging};
use std::{
path::PathBuf,
sync::{
OnceLock,
atomic::{AtomicBool, AtomicI64, Ordering},
},
sync::{Arc, LazyLock},
time::{Duration, UNIX_EPOCH},
};
use tokio::{
fs,
sync::{Mutex, watch},
};
use tokio::{fs, time::Instant};
const DEFAULT_INTERVAL_HOURS: u64 = 24;
const MIN_INTERVAL_HOURS: u64 = 1;
const MAX_INTERVAL_HOURS: u64 = 168;
const MIN_BACKUP_INTERVAL_SECS: i64 = 60;
const MIN_BACKUP_INTERVAL: Duration = Duration::from_secs(60);
const AUTO_BACKUP_KEEP: usize = 20;
const AUTO_MARKER: &str = "-auto-";
@@ -42,13 +35,9 @@ impl AutoBackupTrigger {
Self::GlobalScript => "script",
}
}
const fn is_schedule(self) -> bool {
matches!(self, Self::Scheduled)
}
}
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct AutoBackupSettings {
schedule_enabled: bool,
interval_hours: u64,
@@ -56,6 +45,11 @@ struct AutoBackupSettings {
}
impl AutoBackupSettings {
fn interval(self) -> Option<Duration> {
self.schedule_enabled
.then(|| Duration::from_secs(self.interval_hours * 3600))
}
fn from_verge(verge: &IVerge) -> Self {
let interval = verge
.auto_backup_interval_hours
@@ -80,155 +74,139 @@ impl Default for AutoBackupSettings {
}
}
pub struct AutoBackupManager {
settings_tx: watch::Sender<AutoBackupSettings>,
// The watch channel is the single settings store; no duplicate copies.
settings_rx: watch::Receiver<AutoBackupSettings>,
runner_started: AtomicBool,
exec_lock: Mutex<()>,
last_backup: AtomicI64,
#[derive(Default)]
struct BackupInput {
settings: Option<AutoBackupSettings>,
restart_schedule: bool,
clear_pending_edit: bool,
edit_before_settings: Option<AutoBackupTrigger>,
edit: Option<AutoBackupTrigger>,
}
impl AutoBackupManager {
pub fn global() -> &'static Self {
static INSTANCE: OnceLock<AutoBackupManager> = OnceLock::new();
INSTANCE.get_or_init(|| {
let (settings_tx, settings_rx) = watch::channel(AutoBackupSettings::default());
Self {
settings_tx,
settings_rx,
runner_started: AtomicBool::new(false),
exec_lock: Mutex::new(()),
last_backup: AtomicI64::new(0),
impl BackupInput {
fn update_settings(&mut self, settings: AutoBackupSettings) -> bool {
if self.settings == Some(settings) {
return false;
}
// A pending off/on or interval round trip still restarts the countdown.
self.restart_schedule |= self
.settings
.is_some_and(|previous| previous.interval() != settings.interval());
self.settings = Some(settings);
if !settings.change_enabled {
self.clear_pending_edit = true;
self.edit = None;
self.edit_before_settings = None;
}
true
}
const fn request_edit(&mut self, trigger: AutoBackupTrigger) -> bool {
let pending = match self.settings {
Some(settings) if settings.change_enabled => &mut self.edit,
Some(_) => return false,
None => &mut self.edit_before_settings,
};
if pending.is_some() {
return false;
}
*pending = Some(trigger);
true
}
}
static BACKUP_REQUESTS: LazyLock<Arc<Mailbox<BackupInput>>> =
LazyLock::new(|| scheduled_task::spawn(BackupSchedule::default(), execute_backup));
pub(crate) async fn init() {
let _write = Config::lock_config_write().await;
publish_settings(&Config::verge().await.data_arc());
}
pub(crate) fn publish_settings(verge: &IVerge) {
let settings = AutoBackupSettings::from_verge(verge);
BACKUP_REQUESTS.update(|pending| pending.update_settings(settings));
}
pub(crate) fn trigger_backup(trigger: AutoBackupTrigger) {
BACKUP_REQUESTS.update(|pending| pending.request_edit(trigger));
}
#[derive(Default)]
struct BackupSchedule {
settings: AutoBackupSettings,
due: Option<Instant>,
edit: Option<AutoBackupTrigger>,
last_backup: Option<Instant>,
}
impl ScheduledTask for BackupSchedule {
type Input = BackupInput;
type Work = AutoBackupTrigger;
type Output = Result<Instant>;
fn on_input(&mut self, input: BackupInput, now: Instant) {
if input.clear_pending_edit {
self.edit = None;
}
let previous_edit = if self.settings.change_enabled {
input.edit_before_settings
} else {
None
};
if let Some(settings) = input.settings {
if input.restart_schedule || self.settings.interval() != settings.interval() {
self.due = settings.interval().map(|interval| now + interval);
}
})
self.settings = settings;
}
if self.settings.change_enabled {
self.edit = self.edit.or(previous_edit).or(input.edit);
} else {
self.edit = None;
}
}
pub async fn init(&self) -> Result<()> {
let settings = Self::load_settings().await;
let _ = self.settings_tx.send_replace(settings);
self.maybe_start_runner(settings);
Ok(())
}
pub async fn refresh_settings(&self) -> Result<()> {
let settings = Self::load_settings().await;
let _ = self.settings_tx.send_replace(settings);
self.maybe_start_runner(settings);
Ok(())
}
pub fn trigger_backup(trigger: AutoBackupTrigger) {
AsyncHandler::spawn(move || async move {
if let Err(err) = Self::global().execute_trigger(trigger).await {
logging!(
warn,
Type::Backup,
"Auto backup execution failed ({:?}): {err:#?}",
trigger
);
fn next(&mut self, now: Instant) -> Next<AutoBackupTrigger> {
let throttled = self.last_backup.is_some_and(|last| now - last < MIN_BACKUP_INTERVAL);
if self.due.is_some_and(|due| due <= now) {
self.due = None;
if !throttled {
return Next::Run(AutoBackupTrigger::Scheduled);
}
});
self.due = self.settings.interval().map(|interval| now + interval);
}
if let Some(edit) = self.edit.take()
&& !throttled
{
return Next::Run(edit);
}
self.due.map_or(Next::Idle, Next::At)
}
fn maybe_start_runner(&self, settings: AutoBackupSettings) {
if settings.schedule_enabled {
self.ensure_runner();
fn finished(&mut self, trigger: AutoBackupTrigger, result: std::thread::Result<Self::Output>, now: Instant) {
if trigger == AutoBackupTrigger::Scheduled {
self.due = self.settings.interval().map(|interval| now + interval);
}
match result {
Ok(Ok(created_at)) => self.last_backup = Some(created_at),
Ok(Err(err)) => logging!(warn, Type::Backup, "Auto backup failed ({trigger:?}): {err:#}"),
Err(_) => logging!(error, Type::Backup, "Auto backup panicked ({trigger:?})"),
}
}
}
fn ensure_runner(&self) {
if self.runner_started.swap(true, Ordering::SeqCst) {
return;
}
async fn execute_backup(trigger: AutoBackupTrigger) -> Result<Instant> {
let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
let created_at = Instant::now();
let mut rx = self.settings_tx.subscribe();
AsyncHandler::spawn(move || async move {
Self::run_scheduler(&mut rx).await;
});
if let Err(err) = cleanup_auto_backups().await {
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
}
async fn run_scheduler(rx: &mut watch::Receiver<AutoBackupSettings>) {
let mut current = *rx.borrow();
loop {
if !current.schedule_enabled {
if rx.changed().await.is_err() {
break;
}
current = *rx.borrow();
continue;
}
let duration = Duration::from_secs(current.interval_hours.saturating_mul(3600));
let sleeper = tokio::time::sleep(duration);
tokio::pin!(sleeper);
tokio::select! {
_ = &mut sleeper => {
if let Err(err) = Self::global()
.execute_trigger(AutoBackupTrigger::Scheduled)
.await
{
logging!(
warn,
Type::Backup,
"Scheduled auto backup failed: {err:#?}"
);
}
}
changed = rx.changed() => {
if changed.is_err() {
break;
}
current = *rx.borrow();
}
}
}
}
async fn execute_trigger(&self, trigger: AutoBackupTrigger) -> Result<()> {
let snapshot = *self.settings_rx.borrow();
if trigger.is_schedule() && !snapshot.schedule_enabled {
return Ok(());
}
if !trigger.is_schedule() && !snapshot.change_enabled {
return Ok(());
}
if !self.should_run_now() {
return Ok(());
}
let _guard = self.exec_lock.lock().await;
if !self.should_run_now() {
return Ok(());
}
let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
self.last_backup.store(Local::now().timestamp(), Ordering::Release);
if let Err(err) = cleanup_auto_backups().await {
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
}
logging!(info, Type::Backup, "Auto backup created ({:?}): {}", trigger, file_name);
Ok(())
}
fn should_run_now(&self) -> bool {
let last = self.last_backup.load(Ordering::Acquire);
if last == 0 {
return true;
}
let now = Local::now().timestamp();
now.saturating_sub(last) >= MIN_BACKUP_INTERVAL_SECS
}
async fn load_settings() -> AutoBackupSettings {
let verge = Config::verge().await;
AutoBackupSettings::from_verge(&verge.latest_arc())
}
logging!(info, Type::Backup, "Auto backup created ({trigger:?}): {file_name}");
Ok(created_at)
}
fn append_auto_suffix(file_name: &str, slug: &str) -> String {
+108 -104
View File
@@ -5,14 +5,16 @@ use crate::{
};
use clash_verge_logging::{Type, logging};
use clash_verge_task::countdown::{self, Countdown};
use crate::utils::window_manager::WindowManager;
use anyhow::Result;
use parking_lot::Mutex;
use std::sync::atomic::{AtomicU8, AtomicU32, Ordering};
use std::future::Future;
use std::sync::LazyLock;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use std::time::Duration;
use tauri::Listener as _;
use tokio::sync::oneshot;
use tokio::time::{Duration, sleep};
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -41,27 +43,24 @@ impl LightweightState {
static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8);
struct WindowListener {
handler_id: AtomicU32,
handler_id: Option<tauri::EventId>,
event: &'static str,
label: &'static str,
}
impl WindowListener {
fn setup(&self, on_event: impl Fn() + Send + 'static) {
fn setup(&mut self, on_event: impl Fn() + Send + 'static) {
if let Some(window) = WindowManager::get_main_window() {
let previous_handler_id = self.handler_id.swap(0, Ordering::AcqRel);
if previous_handler_id != 0 {
window.unlisten(previous_handler_id);
if let Some(id) = self.handler_id.take() {
window.unlisten(id);
logging!(debug, Type::Lightweight, "覆盖旧的{}监听", self.label);
}
let handler_id = window.listen(self.event, move |_event| on_event());
self.handler_id.store(handler_id, Ordering::Release);
self.handler_id = Some(window.listen(self.event, move |_event| on_event()));
}
}
fn cancel(&self) {
let id = self.handler_id.swap(0, Ordering::AcqRel);
if id != 0 {
fn cancel(&mut self) {
if let Some(id) = self.handler_id.take() {
if let Some(window) = WindowManager::get_main_window() {
window.unlisten(id);
}
@@ -70,19 +69,31 @@ impl WindowListener {
}
}
static WINDOW_CLOSE_LISTENER: WindowListener = WindowListener {
handler_id: AtomicU32::new(0),
event: "tauri://close-requested",
label: "窗口关闭",
};
struct WindowListeners {
close: WindowListener,
focus: WindowListener,
}
static WEBVIEW_FOCUS_LISTENER: WindowListener = WindowListener {
handler_id: AtomicU32::new(0),
event: "tauri://focus",
label: "窗口焦点",
};
static WINDOW_LISTENERS: Mutex<WindowListeners> = Mutex::new(WindowListeners {
close: WindowListener {
handler_id: None,
event: "tauri://close-requested",
label: "窗口关闭",
},
focus: WindowListener {
handler_id: None,
event: "tauri://focus",
label: "窗口焦点",
},
});
static CANCEL_TX: Mutex<Option<oneshot::Sender<()>>> = Mutex::new(None);
static TIMER_GENERATION: AtomicU64 = AtomicU64::new(0);
static COUNTDOWN: LazyLock<Countdown<u64>> = LazyLock::new(|| {
let (countdown, driver) = countdown::new(prepare_countdown, enter_lightweight_on_timeout);
AsyncHandler::spawn(move || driver);
countdown
});
#[inline]
fn get_state() -> LightweightState {
@@ -118,11 +129,12 @@ async fn refresh_lightweight_tray_state() {
}
pub async fn auto_lightweight_boot() -> Result<()> {
let generation = TIMER_GENERATION.load(Ordering::Acquire);
let verge_config = Config::verge().await;
let is_enable_auto = verge_config.data_arc().enable_auto_light_weight_mode.unwrap_or(false);
let is_silent_start = verge_config.data_arc().enable_silent_start.unwrap_or(false);
if is_enable_auto {
enable_auto_light_weight_mode().await;
if is_enable_auto && verge_config.latest_arc().enable_auto_light_weight_mode.unwrap_or(false) {
enable_auto_light_weight_mode_at(generation).await;
}
if is_silent_start {
entry_lightweight_mode().await;
@@ -131,32 +143,43 @@ pub async fn auto_lightweight_boot() -> Result<()> {
}
pub async fn enable_auto_light_weight_mode() {
enable_auto_light_weight_mode_at(TIMER_GENERATION.load(Ordering::Acquire)).await;
}
async fn enable_auto_light_weight_mode_at(generation: u64) {
if let Err(e) = Timer::global().init().await {
logging!(error, Type::Lightweight, "Failed to initialize timer: {e}");
return;
}
logging!(info, Type::Lightweight, "开启自动轻量模式");
setup_window_close_listener();
setup_webview_focus_listener();
setup_auto_light_weight_listeners(generation);
}
pub fn disable_auto_light_weight_mode() {
logging!(info, Type::Lightweight, "关闭自动轻量模式");
cancel_light_weight_timer();
cancel_window_close_listener();
cancel_webview_focus_listener();
TIMER_GENERATION.fetch_add(1, Ordering::AcqRel);
COUNTDOWN.disarm();
let mut listeners = WINDOW_LISTENERS.lock();
listeners.close.cancel();
listeners.focus.cancel();
}
pub async fn entry_lightweight_mode() -> bool {
let entered = begin_lightweight_mode();
if entered {
COUNTDOWN.disarm();
}
refresh_lightweight_tray_state().await;
entered
}
fn begin_lightweight_mode() -> bool {
if !try_transition(LightweightState::Normal, LightweightState::In) {
logging!(debug, Type::Lightweight, "无需进入轻量模式,跳过调用");
refresh_lightweight_tray_state().await;
return false;
}
record_state_and_log(LightweightState::In);
WindowManager::destroy_main_window();
cancel_light_weight_timer();
refresh_lightweight_tray_state().await;
true
}
@@ -172,16 +195,11 @@ pub async fn exit_lightweight_mode() -> bool {
}
record_state_and_log(LightweightState::Exiting);
WindowManager::show_main_window().await;
let enable_auto_light_weight_mode = Config::verge()
.await
.data_arc()
.enable_auto_light_weight_mode
.unwrap_or(false);
if enable_auto_light_weight_mode {
setup_window_close_listener();
setup_webview_focus_listener();
let generation = TIMER_GENERATION.load(Ordering::Acquire);
if auto_light_weight_is_enabled().await {
setup_auto_light_weight_listeners(generation);
}
cancel_light_weight_timer();
COUNTDOWN.disarm();
record_state_and_log(LightweightState::Normal);
refresh_lightweight_tray_state().await;
true
@@ -189,78 +207,64 @@ pub async fn exit_lightweight_mode() -> bool {
#[cfg(target_os = "macos")]
pub async fn add_light_weight_timer() {
setup_light_weight_timer().await;
let generation = TIMER_GENERATION.load(Ordering::Acquire);
if auto_light_weight_is_enabled().await {
COUNTDOWN.arm(generation);
}
}
fn setup_window_close_listener() {
WINDOW_CLOSE_LISTENER.setup(|| {
std::mem::drop(AsyncHandler::spawn(|| async {
setup_light_weight_timer().await;
}));
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
});
async fn auto_light_weight_is_enabled() -> bool {
let verge = Config::verge().await;
// A disable applies before persistence. A rollback restores eligibility for future hides.
verge.data_arc().enable_auto_light_weight_mode.unwrap_or(false)
&& verge.latest_arc().enable_auto_light_weight_mode.unwrap_or(false)
}
fn cancel_window_close_listener() {
WINDOW_CLOSE_LISTENER.cancel();
}
fn setup_webview_focus_listener() {
WEBVIEW_FOCUS_LISTENER.setup(|| {
cancel_light_weight_timer();
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
});
}
fn cancel_webview_focus_listener() {
WEBVIEW_FOCUS_LISTENER.cancel();
}
async fn setup_light_weight_timer() {
let once_by_minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
let mut cancel_tx_guard = CANCEL_TX.lock();
if cancel_tx_guard.is_some() {
logging!(
debug,
Type::Timer,
"Lightweight mode timer already exists, skipping setup"
);
fn setup_auto_light_weight_listeners(generation: u64) {
let mut listeners = WINDOW_LISTENERS.lock();
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
return;
}
let (tx, rx) = oneshot::channel::<()>();
*cancel_tx_guard = Some(tx);
drop(cancel_tx_guard);
AsyncHandler::spawn(move || async move {
tokio::select! {
_ = sleep(Duration::from_secs(once_by_minutes.saturating_mul(60))) => {
logging!(info, Type::Timer, "Lightweight mode timer expired, entering lightweight mode");
{
let mut guard = CANCEL_TX.lock();
*guard = None;
}
entry_lightweight_mode().await;
}
_ = rx => {
logging!(debug, Type::Timer, "Received cancel signal, stopping lightweight mode timer");
}
listeners.close.setup(move || {
COUNTDOWN.arm(generation);
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
});
listeners.focus.setup(move || {
if generation == TIMER_GENERATION.load(Ordering::Acquire) {
COUNTDOWN.disarm();
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
}
});
}
fn prepare_countdown(generation: u64) -> Option<impl Future<Output = Duration>> {
// Unlisten can be deferred while Tauri is delivering an event.
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
return None;
}
Some(async {
let minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
logging!(
info,
Type::Timer,
"Lightweight mode timer set, entering lightweight mode in {} minutes",
minutes
);
Duration::from_secs(minutes.saturating_mul(60))
})
}
fn enter_lightweight_on_timeout(generation: u64) {
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
return;
}
logging!(
info,
Type::Timer,
"Lightweight mode timer set, entering lightweight mode in {} minutes",
once_by_minutes
"Lightweight mode timer expired, entering lightweight mode"
);
}
fn cancel_light_weight_timer() {
let mut cancel_tx_guard = CANCEL_TX.lock();
if let Some(tx) = cancel_tx_guard.take() {
let _ = tx.send(());
logging!(debug, Type::Timer, "Timer cancelled");
}
begin_lightweight_mode();
AsyncHandler::spawn(refresh_lightweight_tray_state);
}
+40 -2
View File
@@ -3,13 +3,51 @@
//! Proxy settings live per network service. A write that found no service wrote nothing, and a
//! switch to another service leaves the proxy on the old one; both need the write repeated.
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler};
use crate::{
config::Config,
core::{CoreManager, proxy_control},
process::scheduled_task::{self, Mailbox, Next, ScheduledTask},
};
use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use std::sync::{Arc, LazyLock};
use sysproxy::NetworkServiceMonitor;
use tokio::time::Instant;
static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None);
static REAPPLY_REQUESTS: LazyLock<Arc<Mailbox<bool>>> =
LazyLock::new(|| scheduled_task::spawn(NetworkReapply::default(), |()| reapply()));
#[derive(Default)]
struct NetworkReapply {
pending: bool,
}
impl ScheduledTask for NetworkReapply {
type Input = bool;
type Work = ();
type Output = ();
fn on_input(&mut self, requested: bool, _: Instant) {
self.pending |= requested;
}
fn next(&mut self, _: Instant) -> Next<()> {
if std::mem::take(&mut self.pending) {
Next::Run(())
} else {
Next::Idle
}
}
fn finished(&mut self, (): (), result: std::thread::Result<()>, _: Instant) {
if result.is_err() {
logging!(error, Type::Core, "network proxy reapply panicked");
}
}
}
pub fn is_armed() -> bool {
MONITOR.lock().is_some()
}
@@ -18,7 +56,7 @@ pub fn is_armed() -> bool {
/// appearing from here on is never missed.
pub fn start() {
match NetworkServiceMonitor::start(|| {
AsyncHandler::spawn(reapply);
REAPPLY_REQUESTS.update(|pending| !std::mem::replace(pending, true));
}) {
Ok(monitor) => {
*MONITOR.lock() = Some(monitor);
-6
View File
@@ -74,12 +74,6 @@ impl Handle {
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
}
/// A verified installer became ready (or was cleared); the frontend refetches the staged
/// version.
pub fn notify_staged_update_changed() {
Self::send_event(FrontendEvent::StagedUpdateChanged);
}
pub fn notice(status: NoticeStatus, message: impl Into<Arc<str>>) {
Self::send_event(FrontendEvent::NoticeMessage {
status,
@@ -35,7 +35,6 @@ pub enum FrontendEvent<'a> {
state: crate::core::runstate::RunStateView,
},
PendingFailuresChanged,
StagedUpdateChanged,
#[cfg(target_os = "linux")]
ThemeChanged {
theme: tauri::Theme,
@@ -409,11 +408,6 @@ fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, se
"verge://pending-failures-changed",
json!(null),
),
(
FrontendEvent::StagedUpdateChanged,
"verge://staged-update-changed",
json!(null),
),
(
FrontendEvent::ProfileChanged {
current_profile_id: uid,
@@ -466,7 +460,6 @@ frontend_events! {
profile_completed: ProfileUpdatePayload = "profile-update-completed", FrontendEvent::ProfileUpdateCompleted { uid } => ProfileUpdatePayload { uid: uid.to_string() };
run_state: crate::core::runstate::RunStateView = "verge://run-state-changed", FrontendEvent::RunStateChanged { state } => state;
pending_failures: () = "verge://pending-failures-changed", FrontendEvent::PendingFailuresChanged => ();
staged_update: () = "verge://staged-update-changed", FrontendEvent::StagedUpdateChanged => ();
}
#[derive(serde::Serialize, specta::Type)]
+110 -47
View File
@@ -18,13 +18,20 @@ use crate::{
use anyhow::{Result, ensure};
use clash_verge_logging::{Type, logging};
use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome};
use clash_verge_task::watch_task;
use std::{
borrow::Borrow,
future::Future,
sync::atomic::{AtomicU64, Ordering},
sync::{
Arc, LazyLock, Once,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use tokio::{sync::Mutex, time::timeout};
use tokio::{
sync::{Mutex, watch},
time::timeout,
};
const CLEAR_ATTEMPTS: u32 = 3;
const CLEAR_RETRY_DELAY: Duration = Duration::from_millis(100);
@@ -215,23 +222,40 @@ const fn refusal_classification(service_usable: Option<bool>) -> SysproxyFailure
const LOOPBACK_HOST: &str = "127.0.0.1";
const MAX_SERVICE_BYPASS_LEN: usize = 8192;
static SERVICE_PROXY_OPERATIONS: ServiceProxyOperations = ServiceProxyOperations::new();
static SERVICE_PROXY_OPERATIONS: LazyLock<ServiceProxyOperations> = LazyLock::new(ServiceProxyOperations::new);
struct ServiceProxyOperations {
guard: watch::Sender<Option<Arc<ServiceGuard>>>,
guard_generation: AtomicU64,
operation_lock: Mutex<()>,
}
impl ServiceProxyOperations {
const fn new() -> Self {
fn new() -> Self {
Self {
guard: watch::channel(None).0,
guard_generation: AtomicU64::new(0),
operation_lock: Mutex::const_new(()),
}
}
fn invalidate_guard(&self) -> u64 {
self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1)
let mut generation = 0;
self.guard.send_if_modified(|active| {
generation = self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1);
active.take().is_some()
});
generation
}
fn start_guard(&self, guard: ServiceGuard) -> bool {
self.guard.send_if_modified(|active| {
if !guard_generation_is_current(&self.guard_generation, guard.generation) {
return false;
}
*active = Some(Arc::new(guard));
true
})
}
async fn run_service_operation<F, Fut, T>(&self, operation: F) -> T
@@ -606,51 +630,90 @@ pub async fn refresh_guard() -> Result<()> {
let proxy = current_service_proxy_config(&verge).await?;
let proof = service::active_service_session()?;
let interval = Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30).max(1));
AsyncHandler::spawn(move || async move {
let mut consecutive_failures = 0u32;
loop {
tokio::time::sleep(interval).await;
match SERVICE_PROXY_OPERATIONS
.run_guard_request(
generation,
&proof,
&proxy,
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
service::active_service_session,
|| service::set_system_proxy_by_service_with_session(&proxy, &proof),
)
.await
{
Ok(true) => consecutive_failures = 0,
Ok(false) => {
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
break;
}
Err(error) if is_missing_network_service_failure(&error) => {
consecutive_failures = 0;
logging!(debug, Type::Core, "system proxy guard waits for a network service");
}
Err(error) => {
consecutive_failures += 1;
logging!(
warn,
Type::Core,
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}",
consecutive_failures,
GUARD_FAILURES_BEFORE_STOPPING,
error
);
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
report_guard_stopped(generation, &error).await;
break;
}
static START_GUARD_MONITOR: Once = Once::new();
START_GUARD_MONITOR.call_once(|| {
let receiver = SERVICE_PROXY_OPERATIONS.guard.subscribe();
AsyncHandler::spawn(move || {
watch_task::run(receiver, monitor_guard, |guard| {
let generation = guard.generation;
logging!(
error,
Type::Core,
"service proxy guard panicked (generation {generation})"
);
})
});
});
if SERVICE_PROXY_OPERATIONS.start_guard(ServiceGuard {
generation,
proof,
proxy,
interval,
}) {
notification::retire_guard_failures();
}
Ok(())
}
struct ServiceGuard {
generation: u64,
proof: Arc<OwnerSessionProof>,
proxy: MacosProxyConfig,
interval: Duration,
}
async fn monitor_guard(guard: Arc<ServiceGuard>, mut updates: watch::Receiver<Option<Arc<ServiceGuard>>>) {
let ServiceGuard {
generation,
proof,
proxy,
interval,
} = guard.as_ref();
let mut consecutive_failures = 0u32;
loop {
tokio::select! {
biased;
_ = updates.changed() => return,
() = tokio::time::sleep(*interval) => {}
}
match SERVICE_PROXY_OPERATIONS
.run_guard_request(
*generation,
proof,
proxy,
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
service::active_service_session,
|| service::set_system_proxy_by_service_with_session(proxy, proof),
)
.await
{
Ok(true) => consecutive_failures = 0,
Ok(false) => {
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
return;
}
Err(error) if is_missing_network_service_failure(&error) => {
consecutive_failures = 0;
logging!(debug, Type::Core, "system proxy guard waits for a network service");
}
Err(error) => {
consecutive_failures += 1;
logging!(
warn,
Type::Core,
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}",
consecutive_failures,
GUARD_FAILURES_BEFORE_STOPPING,
error
);
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
report_guard_stopped(*generation, &error).await;
return;
}
}
}
});
// Retire only after the replacement guard starts successfully.
notification::retire_guard_failures();
Ok(())
}
}
const GUARD_FAILURES_BEFORE_STOPPING: u32 = 3;
+148 -102
View File
@@ -16,7 +16,10 @@ use crate::{
runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of},
tray::Tray,
},
process::AsyncHandler,
process::{
AsyncHandler,
scheduled_task::{self, Mailbox, Next, ScheduledTask},
},
};
use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_draft::Draft;
@@ -26,9 +29,8 @@ use clash_verge_service_ipc::{
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
StageRuntimeOutcome, StartClashRequest, WriterConfig,
};
use clash_verge_task::watch_task;
use parking_lot::Mutex;
#[cfg(target_os = "macos")]
use std::sync::LazyLock;
use std::{
collections::HashMap,
env::current_exe,
@@ -36,11 +38,12 @@ use std::{
path::{Path, PathBuf},
process::Command as StdCommand,
sync::{
Arc,
Arc, LazyLock,
atomic::{AtomicBool, AtomicU64, Ordering},
},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::{sync::watch, time::Instant};
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
@@ -838,63 +841,84 @@ fn decode_hex(encoded: &str) -> Result<Vec<u8>> {
.collect()
}
static PROVIDER_SYNC_QUEUED: AtomicBool = AtomicBool::new(false);
// Serializing the whole read-and-publish pass prevents an older cache from replacing a newer one.
static PROVIDER_SYNC_SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static PROVIDER_SYNC_REQUESTS: LazyLock<Arc<Mailbox<Option<Instant>>>> =
LazyLock::new(|| scheduled_task::spawn(ProviderSchedule::default(), |_| sync_runtime_providers_by_service()));
static SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4;
const CONTENT_COMPARE_CHUNK: usize = 64 * 1024;
pub(crate) fn request_runtime_provider_sync(delay: Duration) {
if PROVIDER_SYNC_QUEUED.swap(true, Ordering::AcqRel) {
return;
}
AsyncHandler::spawn(move || async move {
tokio::time::sleep(delay).await;
use crate::utils::retry::{RetryError, RetryPolicy, retry};
let _ = retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add((RUNTIME_PROVIDER_SYNC_ATTEMPTS - 1) as usize),
constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY,
),
|index| async move {
let attempt = index as u32 + 1;
let outcome = {
let _serial = PROVIDER_SYNC_SERIAL.lock().await;
if attempt == 1 {
PROVIDER_SYNC_QUEUED.store(false, Ordering::Release);
}
sync_runtime_providers_by_service().await
};
match outcome {
Ok(ProviderSync { pending: 0, .. }) => Ok(()),
Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
logging!(
info,
Type::Service,
"{pending} provider caches are not ready yet; retrying"
);
Err(RetryError::Retry(()))
}
Ok(ProviderSync { pending, .. }) => {
logging!(warn, Type::Service, "{pending} provider caches were not synced");
Ok(())
}
Err(error) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
Ok(())
}
}
},
)
.await;
let due = Instant::now() + delay;
PROVIDER_SYNC_REQUESTS.update(|pending| {
if pending.is_some_and(|current| current <= due) {
return false;
}
*pending = Some(due);
true
});
}
#[derive(Default)]
struct ProviderSchedule {
requested: Option<Instant>,
retry: Option<(Instant, u32)>,
}
impl ScheduledTask for ProviderSchedule {
type Input = Option<Instant>;
type Work = u32;
type Output = Result<ProviderSync>;
fn on_input(&mut self, requested: Self::Input, _: Instant) {
if let Some(requested) = requested {
self.requested = Some(self.requested.map_or(requested, |current| current.min(requested)));
}
}
fn next(&mut self, now: Instant) -> Next<u32> {
let Some(due) = self.requested.into_iter().chain(self.retry.map(|(due, _)| due)).min() else {
return Next::Idle;
};
if due > now {
return Next::At(due);
}
self.requested.take_if(|due| *due <= now);
Next::Run(
self.retry
.take_if(|(due, _)| *due <= now)
.map_or(1, |(_, attempt)| attempt),
)
}
fn finished(&mut self, attempt: u32, result: std::thread::Result<Self::Output>, now: Instant) {
match result {
Ok(Ok(ProviderSync { pending: 0, .. })) => self.retry = None,
Ok(Ok(ProviderSync { pending, .. })) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
logging!(
info,
Type::Service,
"{pending} provider caches are not ready yet; retrying"
);
// A new request during backoff leaves the existing retry deadline and budget intact.
self.retry
.get_or_insert_with(|| (now + constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY, attempt + 1));
}
Ok(Ok(ProviderSync { pending, .. })) => {
logging!(warn, Type::Service, "{pending} provider caches were not synced");
}
Ok(Err(error)) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
}
Err(_) => logging!(error, Type::Service, "provider cache sync panicked"),
}
}
}
#[derive(Debug, Default)]
struct ProviderSync {
synced: usize,
@@ -1451,55 +1475,74 @@ const OWNER_MONITOR_INTERVAL: Duration = Duration::from_secs(5);
/// Mirrors `OwnerWatch`'s tolerance, for the log line only.
const SUSTAINED_OWNER_SAMPLES: u8 = 3;
fn start_owner_monitor() {
let generation = OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;
AsyncHandler::spawn(move || async move {
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
let mut watch = OwnerWatch::new();
let mut core_restarts = None;
loop {
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
if OWNER_MONITOR_GENERATION.load(Ordering::Acquire) != generation {
logging!(
debug,
Type::Service,
"owner monitor superseded (generation {generation})"
);
break;
}
if !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service) {
logging!(
debug,
Type::Service,
"owner monitor stopped; core no longer in service mode (generation {generation})"
);
break;
}
let (sample, status) = read_owner_sample().await;
if let Some(status) = &status {
log_core_restarts(&mut core_restarts, status);
}
let mut step = watch.observe(sample);
if matches!(step, OwnerStep::VerifyTransport) {
if watch.just_became_sustained() {
logging!(
warn,
Type::Service,
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples (generation {generation}); \
preserving local proxy state while the core endpoint still answers"
);
}
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
step = watch.resolve_transport(owner_endpoint_available);
}
if let OwnerStep::Recover(reason) = step {
recover_after_owner_loss(generation, reason, status.as_ref()).await;
break;
}
}
static OWNER_MONITOR: LazyLock<watch::Sender<Option<u64>>> = LazyLock::new(|| {
let (sender, receiver) = watch::channel(None);
AsyncHandler::spawn(move || {
watch_task::run(receiver, monitor_owner, |generation| {
logging!(error, Type::Service, "owner monitor panicked (generation {generation})");
})
});
sender
});
fn start_owner_monitor() {
OWNER_MONITOR.send_modify(|active| {
*active = Some(OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel).wrapping_add(1));
});
}
async fn monitor_owner(generation: u64, mut updates: watch::Receiver<Option<u64>>) {
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
let mut watch = OwnerWatch::new();
let mut core_restarts = None;
loop {
let (step, status) = tokio::select! {
biased;
_ = updates.changed() => return,
result = async {
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
if owner_monitor_generation() != generation
|| !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service)
{
return None;
}
Some(probe_owner(generation, &mut watch, &mut core_restarts).await)
} => match result {
Some(observation) => observation,
None => return,
}
};
if let OwnerStep::Recover(reason) = step {
recover_after_owner_loss(generation, reason, status.as_ref()).await;
return;
}
}
}
async fn probe_owner(
generation: u64,
watch: &mut OwnerWatch,
core_restarts: &mut Option<u32>,
) -> (OwnerStep, Option<ServiceStatusSnapshot>) {
let (sample, status) = read_owner_sample().await;
if let Some(status) = &status {
log_core_restarts(core_restarts, status);
}
let mut step = watch.observe(sample);
if matches!(step, OwnerStep::VerifyTransport) {
if watch.just_became_sustained() {
logging!(
warn,
Type::Service,
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples (generation {generation}); \
preserving local proxy state while the core endpoint still answers"
);
}
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
step = watch.resolve_transport(owner_endpoint_available);
}
(step, status)
}
/// The Service logs its watchdog restarts where the app cannot read them.
@@ -1583,7 +1626,10 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
}
fn cancel_owner_monitors() {
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel);
OWNER_MONITOR.send_modify(|active| {
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel);
*active = None;
});
}
pub(crate) fn owner_monitor_generation() -> u64 {
+9 -7
View File
@@ -7,10 +7,11 @@ use crate::{
};
use anyhow::Result;
use clash_verge_logging::{Type, logging, logging_error};
use futures::StreamExt as _;
use futures::{FutureExt as _, StreamExt as _};
use parking_lot::{Mutex, RwLock};
use std::{
collections::HashMap,
panic::AssertUnwindSafe,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
@@ -70,11 +71,11 @@ async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Fini
Started: FnOnce(),
Update: FnOnce() -> UpdateFuture,
UpdateFuture: std::future::Future<Output = Output>,
Finished: FnOnce(Output),
Finished: FnOnce(std::thread::Result<Output>),
Completed: FnOnce(),
{
update_started();
let result = update_profile().await;
let result = AssertUnwindSafe(async { update_profile().await }).catch_unwind().await;
update_finished(result);
update_completed();
}
@@ -474,12 +475,13 @@ impl Timer {
|| Self::emit_update_event(uid, true),
|| feat::update_profile(uid, None, false),
|result| match result {
Ok(_) => {
Ok(Ok(_)) => {
logging!(debug, Type::Timer, "timer task completed for uid: {}", uid);
}
Err(e) => {
Ok(Err(e)) => {
logging_error!(Type::Timer, "Failed to update profile uid {}: {e:#}", uid);
}
Err(_) => logging!(error, Type::Timer, "Profile update worker panicked"),
},
|| Self::emit_update_event(uid, false),
)
@@ -763,8 +765,8 @@ mod tests {
},
{
let calls = Arc::clone(&calls);
move |result: anyhow::Result<()>| {
assert!(result.is_ok());
move |result| {
assert!(matches!(result, Ok(Ok(()))));
calls.lock().push("terminal-result");
}
},
+88 -117
View File
@@ -2,28 +2,18 @@ use crate::core::handle;
use crate::process::AsyncHandler;
use crate::utils::{connections_stream, tray_speed};
use crate::{Type, logging};
use parking_lot::Mutex;
use std::sync::Arc;
use std::sync::OnceLock;
use std::time::Duration;
use tauri::async_runtime::JoinHandle;
use tauri_plugin_mihomo::models::WsConnectionId;
use tokio::sync::watch;
use connections_stream::{MihomoWsEventStream, StreamConsumeState, TrafficSpeedEvent};
const TRAY_SPEED_RETRY_DELAY: Duration = Duration::from_secs(1);
const TRAY_SPEED_STALE_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone)]
#[derive(Default)]
pub struct TraySpeedController {
speed_task: Arc<Mutex<Option<JoinHandle<()>>>>,
speed_connection_id: Arc<Mutex<Option<WsConnectionId>>>,
}
impl Default for TraySpeedController {
fn default() -> Self {
Self {
speed_task: Arc::new(Mutex::new(None)),
speed_connection_id: Arc::new(Mutex::new(None)),
}
}
enabled: OnceLock<watch::Sender<bool>>,
}
impl TraySpeedController {
@@ -32,104 +22,102 @@ impl TraySpeedController {
}
pub fn update_task(&self, enable_tray_speed: bool) {
if enable_tray_speed {
self.start_task();
} else {
self.stop_task();
let enabled = self.enabled.get_or_init(|| {
let (enabled, receiver) = watch::channel(false);
AsyncHandler::spawn(move || Self::run(receiver));
enabled
});
enabled.send_replace(enable_tray_speed);
}
async fn run(mut enabled: watch::Receiver<bool>) {
while enabled.changed().await.is_ok() {
let should_run = *enabled.borrow_and_update();
if should_run {
Self::run_enabled(&mut enabled).await;
} else {
Self::clear_tray_speed();
}
}
}
fn start_task(&self) {
if handle::Handle::global().is_exiting() {
return;
}
async fn run_enabled(enabled: &mut watch::Receiver<bool>) {
while !handle::Handle::global().is_exiting() {
if !Self::has_main_tray() {
logging!(warn, Type::Tray, "托盘不可用,停止托盘速率任务");
return;
}
if !Self::has_main_tray() {
logging!(warn, Type::Tray, "托盘不可用,跳过启动托盘速率任务");
return;
}
let mut guard = self.speed_task.lock();
if guard.as_ref().is_some_and(|task| !task.inner().is_finished()) {
return;
}
let speed_connection_id = Arc::clone(&self.speed_connection_id);
let task = AsyncHandler::spawn(move || async move {
loop {
if handle::Handle::global().is_exiting() {
break;
}
if !Self::has_main_tray() {
logging!(warn, Type::Tray, "托盘已不可用,停止托盘速率任务");
break;
}
let stream_connect_result = connections_stream::connect_traffic_stream().await;
let mut speed_stream = match stream_connect_result {
Ok(stream) => stream,
Err(err) => {
logging!(debug, Type::Tray, "托盘速率流连接失败,稍后重试: {err}");
Self::apply_tray_speed(0, 0);
tokio::time::sleep(TRAY_SPEED_RETRY_DELAY).await;
continue;
}
};
Self::set_speed_connection_id(&speed_connection_id, Some(speed_stream.connection_id));
loop {
let next_state = speed_stream
.next_event(TRAY_SPEED_STALE_TIMEOUT, || handle::Handle::global().is_exiting())
.await;
match next_state {
connections_stream::StreamConsumeState::Event(speed_event) => {
Self::apply_tray_speed(speed_event.up, speed_event.down);
}
connections_stream::StreamConsumeState::Stale => {
logging!(debug, Type::Tray, "托盘速率流长时间未收到有效数据,触发重连");
Self::apply_tray_speed(0, 0);
break;
}
connections_stream::StreamConsumeState::Closed
| connections_stream::StreamConsumeState::ExitRequested => {
break;
}
// Keep the registered stream outside the cancellable future until it is disconnected.
let mut stream = None;
let disabled = tokio::select! {
biased;
_ = Self::wait_until_disabled(enabled) => true,
_ = Self::read_speed(&mut stream) => false,
};
if disabled {
Self::clear_tray_speed();
}
if let Some(stream) = stream {
let disconnect = connections_stream::disconnect_connection(stream.connection_id);
tokio::pin!(disconnect);
tokio::select! {
biased;
_ = Self::wait_until_disabled(enabled), if !disabled => {
Self::clear_tray_speed();
disconnect.await;
return;
}
_ = &mut disconnect => {}
}
}
if disabled || handle::Handle::global().is_exiting() || !Self::has_main_tray() {
return;
}
Self::disconnect_speed_connection(&speed_connection_id).await;
if handle::Handle::global().is_exiting() || !Self::has_main_tray() {
break;
}
// `Stale` already reset the display; this covers remote close.
if *enabled.borrow() {
Self::apply_tray_speed(0, 0);
tokio::time::sleep(TRAY_SPEED_RETRY_DELAY).await;
}
Self::set_speed_connection_id(&speed_connection_id, None);
});
*guard = Some(task);
if tokio::time::timeout(TRAY_SPEED_RETRY_DELAY, Self::wait_until_disabled(enabled))
.await
.is_ok()
{
Self::clear_tray_speed();
return;
}
}
}
fn stop_task(&self) {
let task = self.speed_task.lock().take();
let speed_connection_id = Arc::clone(&self.speed_connection_id);
async fn wait_until_disabled(enabled: &mut watch::Receiver<bool>) {
let _ = enabled.wait_for(|enabled| !enabled).await;
}
AsyncHandler::spawn(move || async move {
// Await abort before disconnect so the task cannot consume and lose the connection ID.
if let Some(task) = task {
task.abort();
let _ = task.await;
async fn read_speed(stream: &mut Option<MihomoWsEventStream<TrafficSpeedEvent>>) {
let speed_stream = match connections_stream::connect_traffic_stream().await {
Ok(connected) => stream.insert(connected),
Err(err) => {
logging!(debug, Type::Tray, "托盘速率流连接失败,稍后重试: {err}");
return;
}
Self::disconnect_speed_connection(&speed_connection_id).await;
});
};
loop {
match speed_stream
.next_event(TRAY_SPEED_STALE_TIMEOUT, || handle::Handle::global().is_exiting())
.await
{
StreamConsumeState::Event(event) => Self::apply_tray_speed(event.up, event.down),
StreamConsumeState::Stale => {
logging!(debug, Type::Tray, "托盘速率流长时间未收到有效数据,触发重连");
Self::apply_tray_speed(0, 0);
return;
}
StreamConsumeState::Closed | StreamConsumeState::ExitRequested => return,
}
}
}
fn clear_tray_speed() {
let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
let result = tray.with_inner_tray_icon(|inner| {
@@ -147,23 +135,6 @@ impl TraySpeedController {
handle::Handle::app_handle().tray_by_id(super::TRAY_ID).is_some()
}
fn set_speed_connection_id(
speed_connection_id: &Arc<Mutex<Option<WsConnectionId>>>,
connection_id: Option<WsConnectionId>,
) {
*speed_connection_id.lock() = connection_id;
}
fn take_speed_connection_id(speed_connection_id: &Arc<Mutex<Option<WsConnectionId>>>) -> Option<WsConnectionId> {
speed_connection_id.lock().take()
}
async fn disconnect_speed_connection(speed_connection_id: &Arc<Mutex<Option<WsConnectionId>>>) {
if let Some(connection_id) = Self::take_speed_connection_id(speed_connection_id) {
connections_stream::disconnect_connection(connection_id).await;
}
}
fn apply_tray_speed(up: u64, down: u64) {
let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
+239 -425
View File
@@ -1,23 +1,20 @@
use crate::{config::Config, core::handle::Handle, utils::dirs};
use crate::{config::Config, singleton, utils::dirs};
use anyhow::{Context as _, Result};
use clash_verge_logging::{Type, logging};
use futures::FutureExt as _;
use serde::Serialize;
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::{
panic::AssertUnwindSafe,
path::PathBuf,
sync::{
OnceLock,
atomic::{AtomicU64, Ordering},
},
sync::atomic::{AtomicU64, Ordering},
time::Duration,
};
use tauri_plugin_updater::{Update, UpdaterExt as _};
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
/// App-global handle to the updater actor, the single task that runs every updater operation.
pub struct SilentUpdater {
tx: mpsc::Sender<Cmd>,
manual_cancel: Mutex<Option<CancellationToken>>,
background_cancel: Mutex<Option<CancellationToken>>,
download_lock: tokio::sync::Mutex<()>,
}
#[derive(Serialize, specta::Type)]
@@ -28,153 +25,120 @@ pub enum InstallUpdateOutcome {
UpdateChanged,
}
static UPDATER: OnceLock<SilentUpdater> = OnceLock::new();
enum Cmd {
Install {
version: String,
on_event: Box<dyn Fn(DownloadEvent) + Send + Sync>,
reply: oneshot::Sender<Result<InstallUpdateOutcome>>,
},
Cancel,
StagedVersion {
reply: oneshot::Sender<Option<String>>,
},
}
/// 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<Option<String>>),
Displaced(Cmd),
}
/// How a dialog install's prepare phase ended.
enum Prepared {
/// The update record with its verified bytes, or `None` when the offer changed.
Ready(Option<Box<(Update, Vec<u8>)>>),
Failed(anyhow::Error),
/// Preempted by a cancel; the work future is already dropped.
Dropped,
}
singleton!(SilentUpdater, SILENT_UPDATER);
impl SilentUpdater {
/// Spawns the updater actor and installs the app-global handle.
pub fn start(app_handle: tauri::AppHandle) -> &'static Self {
UPDATER.get_or_init(|| {
let (tx, rx) = mpsc::channel(16);
tokio::spawn(Self::run(app_handle, rx));
Self { tx }
})
}
/// `None` only before `start`, which setup runs before any command can arrive.
pub fn global() -> Option<&'static Self> {
UPDATER.get()
const fn new() -> Self {
Self {
manual_cancel: Mutex::new(None),
background_cancel: Mutex::new(None),
download_lock: tokio::sync::Mutex::const_new(()),
}
}
}
#[derive(Serialize, Deserialize)]
struct UpdateCacheMeta {
version: String,
}
impl SilentUpdater {
fn staging_dir() -> Result<PathBuf> {
fn cache_dir() -> Result<PathBuf> {
Ok(dirs::app_home_dir()?.join("update_cache"))
}
/// Writes the installer under a name stamped with the version it was staged for, through
/// a temp file so a crash leaves no partial file; installer-sized IO stays off the async
/// runtime. Only the detachable blocking task writes the temp file — the rename that
/// stages it runs after its await, so a command preempting this future cannot publish
/// behind the preemption.
async fn write_staged(bytes: Vec<u8>, version: &str) -> Result<()> {
let staging_dir = Self::staging_dir()?;
let bin_name = staged_file_name(version);
let bin_path = staging_dir.join(&bin_name);
let tmp_path = staging_dir.join(format!("{bin_name}.tmp"));
let write_tmp = {
let staging_dir = staging_dir.clone();
let tmp_path = tmp_path.clone();
move || -> Result<()> {
std::fs::create_dir_all(&staging_dir)
.with_context(|| format!("failed to create update staging directory {}", staging_dir.display()))?;
std::fs::write(&tmp_path, &bytes)
.with_context(|| format!("failed to write update staging file {}", 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 publish update staging file {}", bin_path.display()))?;
Ok(())
/// 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()?;
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");
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 };
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",
meta.version,
bytes.len()
);
Ok(())
})
.await?
}
/// Returns the staged installer for `update`: the staged name carries the version it was
/// staged for, and the plugin's `verify` binds the bytes to the signed release — both
/// must agree with the current offer. A stage that fails either is removed.
async fn staged_bytes(update: &Update) -> Option<Vec<u8>> {
// A quiet miss for the common nothing-staged case; only a present-but-bad file logs.
let Ok(bin_path) = Self::staging_dir().map(|dir| dir.join(staged_file_name(&update.version))) else {
return None;
};
if !bin_path.exists() {
return None;
}
let read = tokio::task::spawn_blocking(move || {
std::fs::read(&bin_path).with_context(|| format!("failed to read staged update {}", bin_path.display()))
async fn read_cache_bytes() -> Result<Vec<u8>> {
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;
let bytes = match read {
Ok(result) => result.and_then(|bytes| {
.await?
}
fn read_cache_meta() -> Result<UpdateCacheMeta> {
let meta_path = Self::cache_dir()?.join("pending_update.json");
let content = std::fs::read_to_string(meta_path)?;
Ok(serde_json::from_str(&content)?)
}
async fn delete_cache() {
if let Ok(cache_dir) = Self::cache_dir()
&& cache_dir.exists()
{
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.
async fn verified_cache(update: &Update) -> Option<Vec<u8>> {
let meta = match Self::read_cache_meta() {
Ok(meta) => meta,
// A bin without its meta comes from an interrupted write.
Err(_) => {
Self::delete_cache().await;
return None;
}
};
let bytes = if meta.version == update.version {
Self::read_cache_bytes().await.and_then(|bytes| {
update.verify(&bytes)?;
Ok(bytes)
}),
Err(e) => Err(anyhow::anyhow!("staged update read failed: {e}")),
})
} else {
Err(anyhow::anyhow!("server offers v{}", update.version))
};
match bytes {
Ok(bytes) => Some(bytes),
Err(e) => {
logging!(info, Type::System, "Staged update is unusable: {e:#}, cleaning up");
Self::delete_staged().await;
logging!(
info,
Type::System,
"Update cache v{} is unusable: {e:#}, cleaning up",
meta.version
);
Self::delete_cache().await;
None
}
}
}
/// Removes the staging directory; a failed removal leaves bytes the next cycle
/// re-verifies and replaces.
async fn delete_staged() {
if let Ok(staging_dir) = Self::staging_dir()
&& staging_dir.exists()
{
let display = staging_dir.display().to_string();
match tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&staging_dir)).await {
Ok(Ok(())) => logging!(info, Type::System, "Staged update removed"),
Ok(Err(e)) => logging!(warn, Type::System, "Failed to remove staged update {display}: {e}"),
Err(e) => logging!(warn, Type::System, "Failed to remove staged update {display}: {e}"),
}
}
}
}
/// Filesystem-safe staging name for `version`: the name itself asserts which version the
/// staged installer belongs to, so an announcement can never adopt a stage of another
/// version regardless of signature details.
fn staged_file_name(version: &str) -> String {
let sanitized: String = version
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
c
} else {
'_'
}
})
.collect();
format!("pending_update_{sanitized}.bin")
}
pub fn is_build_to_stable(current: &str, remote: &str) -> bool {
@@ -215,8 +179,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"))]
@@ -306,18 +268,18 @@ impl SilentUpdater {
let updater_builder = app_handle.updater_builder();
#[cfg(target_os = "windows")]
let updater_builder = {
let verge_lang = crate::config::Config::verge().await.latest_arc().language.clone();
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?)
}
/// Installs verified bytes, consuming the staging copy first so a failed install leaves
/// nothing claiming readiness. A timeout abandons the await, not the detached install
/// task; a successful Windows install exits the process inside the plugin (#2558).
/// 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).
async fn install(update: Update, bytes: Vec<u8>) -> Result<()> {
Self::delete_staged().await;
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??),
@@ -326,271 +288,47 @@ impl SilentUpdater {
)),
}
}
}
impl SilentUpdater {
/// Installs `version` for the update dialog, reusing the staged installer when it holds
/// that version; a changed offer must be confirmed again before downloading or
/// installing it.
/// 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.
pub async fn install_update(
&self,
// The actor owns the app handle; the parameter keeps the command's call shape.
_app_handle: &tauri::AppHandle,
app_handle: &tauri::AppHandle,
version: &str,
on_event: impl Fn(DownloadEvent) + Send + Sync + 'static,
on_event: impl Fn(DownloadEvent) + Sync,
) -> Result<InstallUpdateOutcome> {
let (reply, reply_rx) = oneshot::channel();
self.tx
.send(Cmd::Install {
version: version.to_owned(),
on_event: Box::new(on_event),
reply,
})
.await
.map_err(|_| anyhow::anyhow!("updater stopped"))?;
reply_rx
.await
.unwrap_or_else(|_| Err(anyhow::anyhow!("updater stopped")))
}
pub fn cancel_download(&self) {
// try_send: a cancel must never block, and the mailbox never fills in practice.
let _ = self.tx.try_send(Cmd::Cancel);
}
/// The version whose installer is staged and ready for a one-action restart, or `None`.
pub async fn staged_version(&self) -> Result<Option<String>> {
let (reply, reply_rx) = oneshot::channel();
self.tx
.send(Cmd::StagedVersion { reply })
.await
.map_err(|_| anyhow::anyhow!("updater stopped"))?;
Ok(reply_rx.await.unwrap_or(None))
}
}
impl SilentUpdater {
/// The actor's supervisor: one `serve` epoch at a time. A panic drops the epoch — its
/// in-flight work and any reply it still owed — but not the mailbox or the staged
/// version, so the actor restarts instead of leaving updating dead for the rest of the
/// process.
async fn run(app_handle: tauri::AppHandle, mut rx: mpsc::Receiver<Cmd>) {
logging!(info, Type::System, "Silent updater: background task started");
let mut next_check = tokio::time::Instant::now() + Duration::from_secs(10);
let mut staged: Option<String> = None;
loop {
let epoch = AssertUnwindSafe(Self::serve(&app_handle, &mut rx, &mut next_check, &mut staged));
match epoch.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, the schedule, and the staged version below are 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);
}
}
let cancel = CancellationToken::new();
{
let mut slot = self.manual_cancel.lock();
anyhow::ensure!(slot.is_none(), "an update install is already in progress");
*slot = Some(cancel.clone());
}
}
/// The actor loop: idle until a command or the daily check, then run the work. A cancel
/// during the install's prepare phase drops the work future; a second install is
/// declined in place; an install displaces the daily cycle.
async fn serve(
app_handle: &tauri::AppHandle,
rx: &mut mpsc::Receiver<Cmd>,
next_check: &mut tokio::time::Instant,
staged: &mut Option<String>,
) {
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, staged).await;
break;
}
// The dialog's cancel only addresses a running install; idle it stops nothing.
Wake::Cmd(Cmd::Cancel) => break,
Wake::Cmd(Cmd::StagedVersion { reply }) => {
let _ = reply.send(staged.clone());
break;
}
Wake::DailyCheck => {
let end = Self::run_background_cycle(app_handle, rx, staged).await;
*next_check = tokio::time::Instant::now() + Duration::from_secs(24 * 60 * 60);
match end {
CycleEnd::Completed(Ok(new_staged)) => {
if *staged != new_staged {
*staged = new_staged;
Handle::notify_staged_update_changed();
}
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 and a staged-version
/// query are answered in place; an install 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<Cmd>,
staged: &Option<String>,
) -> CycleEnd {
let cycle = Self::stage_update(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;
};
match cmd {
Cmd::Cancel => {}
Cmd::StagedVersion { reply } => {
let _ = reply.send(staged.clone());
}
Cmd::Install { .. } => return CycleEnd::Displaced(cmd),
}
}
}
/// Checks for an update and stages its installer for a one-action restart: the staged
/// bytes are downloaded only when they no longer verify against the current offer.
async fn stage_update(app_handle: &tauri::AppHandle) -> Result<Option<String>> {
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(None);
}
logging!(info, Type::System, "Silent updater: checking for updates...");
let update = match app_handle.updater()?.check().await {
Ok(Some(update)) => update,
Ok(None) => {
logging!(info, Type::System, "Silent updater: no update available");
return Ok(None);
}
Err(e) => {
logging!(warn, Type::System, "Silent updater: check failed: {e}");
return Err(e.into());
}
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(prepared) = prepared.filter(|_| !cancel.is_cancelled()).transpose()? else {
logging!(info, Type::System, "Update v{version} cancelled");
return Ok(InstallUpdateOutcome::Cancelled);
};
let Some((update, bytes)) = prepared else {
return Ok(InstallUpdateOutcome::UpdateChanged);
};
let version = update.version.clone();
logging!(info, Type::System, "Silent updater: update available: v{version}");
if Self::staged_bytes(&update).await.is_some() {
logging!(info, Type::System, "Silent updater: v{version} already staged");
} else {
logging!(info, Type::System, "Silent updater: downloading v{version}...");
let bytes = download(&update, |_| {}).await?;
logging!(info, Type::System, "Silent updater: download complete");
// Remove any stage left by an earlier offer before publishing the new one.
Self::delete_staged().await;
Self::write_staged(bytes, &version).await?;
logging!(info, Type::System, "Silent updater: v{version} ready to install");
}
Ok(Some(version))
}
/// One dialog install from prepare to install; every exit path answers `reply`.
async fn run_install(
app_handle: &tauri::AppHandle,
version: &str,
on_event: Box<dyn Fn(DownloadEvent) + Send + Sync>,
reply: oneshot::Sender<Result<InstallUpdateOutcome>>,
rx: &mut mpsc::Receiver<Cmd>,
staged: &Option<String>,
) {
match Self::prepare_cancellable(app_handle, version, on_event.as_ref(), rx, staged).await {
// The prepare work is already dropped, so a cancel racing the last poll still wins.
Prepared::Dropped => {
logging!(info, Type::System, "Update v{version} cancelled");
let _ = reply.send(Ok(InstallUpdateOutcome::Cancelled));
}
Prepared::Failed(e) => {
let _ = reply.send(Err(e));
}
Prepared::Ready(None) => {
let _ = reply.send(Ok(InstallUpdateOutcome::UpdateChanged));
}
Prepared::Ready(Some(pair)) => {
let (update, bytes) = *pair;
logging!(info, Type::System, "Installing update v{version}...");
on_event(DownloadEvent::Installing);
let result = Self::finish_install(update, bytes, rx, staged).await;
let _ = reply.send(result.map(|_| InstallUpdateOutcome::Installed));
}
}
}
/// The cancellable prepare phase: check, version filter, staged reuse or download. A
/// second install is declined in place; a cancel drops the work.
async fn prepare_cancellable(
app_handle: &tauri::AppHandle,
version: &str,
on_event: &(impl Fn(DownloadEvent) + Sync + ?Sized),
rx: &mut mpsc::Receiver<Cmd>,
staged: &Option<String>,
) -> Prepared {
let prepare = Self::prepare_install(app_handle, version, on_event);
tokio::pin!(prepare);
let mut mailbox_open = true;
loop {
let maybe = tokio::select! {
biased;
maybe = rx.recv(), if mailbox_open => maybe,
prepared = &mut prepare => return match prepared {
Ok(prepared) => Prepared::Ready(prepared.map(Box::new)),
Err(e) => Prepared::Failed(e),
},
};
let Some(cmd) = maybe else {
mailbox_open = false;
continue;
};
match cmd {
Cmd::Cancel => return Prepared::Dropped,
Cmd::StagedVersion { reply } => {
let _ = reply.send(staged.clone());
}
Cmd::Install { reply, .. } => Self::decline_install(reply),
}
}
logging!(info, Type::System, "Installing update v{version}...");
on_event(DownloadEvent::Installing);
Self::install(update, bytes).await?;
Ok(InstallUpdateOutcome::Installed)
}
async fn prepare_install(
&self,
app_handle: &tauri::AppHandle,
version: &str,
on_event: &(impl Fn(DownloadEvent) + Sync + ?Sized),
on_event: &(impl Fn(DownloadEvent) + Sync),
) -> Result<Option<(Update, Vec<u8>)>> {
let Some(update) = Self::check(app_handle)
.await?
@@ -598,45 +336,121 @@ impl SilentUpdater {
else {
return Ok(None);
};
let bytes = match Self::staged_bytes(&update).await {
let _download_guard = self.download_lock.lock().await;
let bytes = match Self::verified_cache(&update).await {
Some(bytes) => bytes,
None => download(&update, on_event).await?,
};
Ok(Some((update, bytes)))
}
/// The install phase: once `install()` started it cannot be cancelled (the installer may
/// already run); the mailbox still gets answers while it finishes.
async fn finish_install(
update: Update,
bytes: Vec<u8>,
rx: &mut mpsc::Receiver<Cmd>,
staged: &Option<String>,
) -> Result<()> {
let install = Self::install(update, bytes);
tokio::pin!(install);
let mut mailbox_open = true;
loop {
let maybe = tokio::select! {
result = &mut install => return result,
maybe = rx.recv(), if mailbox_open => maybe,
};
let Some(cmd) = maybe else {
mailbox_open = false;
continue;
};
match cmd {
Cmd::Cancel => {}
Cmd::StagedVersion { reply } => {
let _ = reply.send(staged.clone());
}
Cmd::Install { reply, .. } => Self::decline_install(reply),
}
pub fn cancel_download(&self) {
let mut slot = self.manual_cancel.lock();
if let Some(cancel) = slot.take() {
cancel.cancel();
}
}
fn decline_install(reply: oneshot::Sender<Result<InstallUpdateOutcome>>) {
let _ = reply.send(Err(anyhow::anyhow!("an update install is already in progress")));
/// Drops the downloaded update and aborts a background download in flight.
pub async fn discard_pending(&self) {
let cancel = self.background_cancel.lock().take();
if let Some(cancel) = cancel {
cancel.cancel();
}
Self::delete_cache().await;
}
}
impl SilentUpdater {
async fn check_and_download(&self, app_handle: &tauri::AppHandle) -> Result<()> {
// Registered before reading the switch, so `discard_pending` either cancels it or ran first.
let cancel = CancellationToken::new();
*self.background_cancel.lock() = Some(cancel.clone());
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}");
let download_guard = self.download_lock.lock().await;
// A discard that arrived while waiting for the lock must not start a doomed download.
if cancel.is_cancelled() {
return Ok(());
}
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 downloaded = tokio::select! {
bytes = download(&update, |_| {}) => Some(bytes),
() = cancel.cancelled() => None,
};
let Some(bytes) = downloaded else {
logging!(info, Type::System, "Silent updater: download cancelled");
return Ok(());
};
let bytes = bytes?;
logging!(info, Type::System, "Silent updater: download complete");
Self::write_cache(bytes, version).await?;
}
drop(download_guard);
// 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().await;
return Ok(());
}
logging!(
info,
Type::System,
"Silent updater: v{version} ready to install from the update dialog"
);
Ok(())
}
pub async fn start_background_check(&self, app_handle: tauri::AppHandle) {
// Permanent watcher: daily update cycles for the lifetime of the app.
logging!(info, Type::System, "Silent updater: background task started");
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
loop {
if let Err(e) = self.check_and_download(&app_handle).await {
logging!(warn, Type::System, "Silent updater: cycle error: {e}");
}
tokio::time::sleep(std::time::Duration::from_secs(24 * 60 * 60)).await;
}
}
}
+2 -1
View File
@@ -1,6 +1,6 @@
use crate::{
config::{Config, IClashTemp, IProfiles, IVerge},
core::{CoreManager, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
@@ -58,6 +58,7 @@ async fn finalize_restored_verge_config(
*d = restored.clone();
});
verge_draft.apply();
auto_backup::publish_settings(&verge_draft.data_arc());
// Turn it off here; a failing core side effect below would otherwise skip this step.
if !restored.enable_system_proxy.unwrap_or_default() {
+31 -14
View File
@@ -21,24 +21,38 @@ pub(super) enum Effect {
pub(super) type Effects = BTreeSet<Effect>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum AfterCommit {
BackupSettings,
}
#[derive(Default)]
pub(super) struct EffectPlan {
pub(super) before_commit: Effects,
pub(super) after_commit: BTreeSet<AfterCommit>,
}
macro_rules! select_field {
($effects:ident, $field:ident, NoEffect) => { let _ = $field; };
($effects:ident, $field:ident, [$($effect:ident),*]) => {
if $field.is_some() { $effects.extend([$(Effect::$effect),*]); }
if $field.is_some() { $effects.before_commit.extend([$(Effect::$effect),*]); }
};
($effects:ident, $field:ident, (AfterCommit $effect:ident)) => {
if $field.is_some() { $effects.after_commit.insert(AfterCommit::$effect); }
};
($effects:ident, $field:ident, Tun) => {
select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]);
#[cfg(target_os = "linux")]
if *$field == Some(true) { $effects.insert(Effect::RestartCore); }
if *$field == Some(true) { $effects.before_commit.insert(Effect::RestartCore); }
};
}
macro_rules! verge_registry {
($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => {
pub(super) fn verge_effects(patch: &IVerge) -> Effects {
pub(super) fn verge_effects(patch: &IVerge) -> EffectPlan {
// No rest pattern: even fields omitted by serde must be classified at compile time.
let IVerge { $( $(#[$cfg])* $field, )* } = patch;
let mut effects = Effects::new();
let mut effects = EffectPlan::default();
$( $(#[$cfg])* { select_field!(effects, $field, $rule); } )*
effects
}
@@ -100,9 +114,9 @@ verge_registry! {
proxy_layout_column => NoEffect;
test_list => NoEffect;
auto_log_clean => NoEffect;
enable_auto_backup_schedule => NoEffect;
auto_backup_interval_hours => NoEffect;
auto_backup_on_change => NoEffect;
enable_auto_backup_schedule => (AfterCommit BackupSettings);
auto_backup_interval_hours => (AfterCommit BackupSettings);
auto_backup_on_change => (AfterCommit BackupSettings);
#[cfg(not(target_os = "windows"))]
verge_redir_port => [RestartCore];
#[cfg(not(target_os = "windows"))]
@@ -130,7 +144,7 @@ verge_registry! {
enable_external_controller => [RestartCore];
}
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> EffectPlan {
use clash_verge_logging::{Type, logging};
let mut effects = Effects::new();
for key in patch.keys() {
@@ -157,7 +171,10 @@ pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
if patch.is_empty() {
effects.insert(Effect::ClashConfig);
}
effects
EffectPlan {
before_commit: effects,
..Default::default()
}
}
#[cfg(test)]
@@ -172,7 +189,7 @@ mod tests {
#[test]
fn representative_verge_patches_map_to_frozen_effects() {
assert_eq!(verge_effects(&IVerge::default()), Effects::new());
assert_eq!(verge_effects(&IVerge::default()).before_commit, Effects::new());
let cases: [(IVerge, &[Effect]); 9] = [
(
@@ -216,7 +233,7 @@ mod tests {
];
for (patch, expected) in cases {
assert_eq!(
verge_effects(&patch),
verge_effects(&patch).before_commit,
expected.iter().copied().collect::<Effects>(),
"patch mapping drifted for {expected:?}"
);
@@ -225,7 +242,7 @@ mod tests {
let tun = verge_patch(|p| p.enable_tun_mode = Some(true));
#[cfg(target_os = "linux")]
assert_eq!(
verge_effects(&tun),
verge_effects(&tun).before_commit,
[
Effect::RestartCore,
Effect::ClashConfig,
@@ -238,7 +255,7 @@ mod tests {
);
#[cfg(not(target_os = "linux"))]
assert_eq!(
verge_effects(&tun),
verge_effects(&tun).before_commit,
[
Effect::ClashConfig,
Effect::TrayIcon,
@@ -281,7 +298,7 @@ mod tests {
];
for (patch, expected) in cases {
assert_eq!(
clash_effects(&patch),
clash_effects(&patch).before_commit,
expected.iter().copied().collect::<Effects>(),
"clash mapping drifted for {expected:?}"
);
+18 -8
View File
@@ -1,12 +1,15 @@
use super::effects::{Effect, Effects};
use super::effects::{AfterCommit, Effect, EffectPlan};
use crate::core::notify::{Refresh, announce};
use crate::{
config::{
Config, IVerge,
snapshot::{capture_config_files, restore_files},
},
core::auto_backup::AutoBackupManager,
core::{CoreManager, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control, tray},
core::auto_backup,
core::{
CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control,
tray,
},
};
use anyhow::Result;
use clash_verge_draft::DraftTransaction;
@@ -105,7 +108,7 @@ async fn ensure_effect(
Ok(())
}
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: EffectPlan) -> Result<()> {
let manager = CoreManager::global();
let update = manager.claim_config_update(config_write)?;
let clash = Config::clash().await;
@@ -127,7 +130,7 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
Patch::Clash(patch) => clash.edit_draft(|draft| draft.patch_config(patch)),
}
let result: Result<()> = async {
for effect in effects.iter().copied() {
for effect in effects.before_commit.iter().copied() {
let result = Box::pin(ensure_effect(effect, verge_patch, manager, &update)).await;
if matches!(patch, Patch::Clash(_)) && matches!(effect, Effect::TrayMenu | Effect::TrayIcon) {
// Tray failures must not reject an applied Clash mode change.
@@ -159,11 +162,18 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
}
transaction.commit();
match patch {
Patch::Verge { .. } => {
if effects.contains(&Effect::ClashConfig) {
Patch::Verge { patch, .. } => {
if patch.auto_check_update == Some(false) {
SilentUpdater::global().discard_pending().await;
}
if effects.before_commit.contains(&Effect::ClashConfig) {
announce(Refresh::Clash);
}
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
for effect in effects.after_commit {
match effect {
AfterCommit::BackupSettings => auto_backup::publish_settings(&verge.data_arc()),
}
}
announce(Refresh::Verge);
}
Patch::Clash(_) => announce(Refresh::Clash),
+1 -11
View File
@@ -304,17 +304,7 @@ async fn clean_session_ending_best_effort() -> CleanupResult {
#[cfg(target_os = "macos")]
pub async fn hide() {
use crate::core::lightweight::add_light_weight_timer;
let enable_auto_light_weight_mode = Config::verge()
.await
.data_arc()
.enable_auto_light_weight_mode
.unwrap_or(false);
if enable_auto_light_weight_mode {
add_light_weight_timer().await;
}
crate::core::lightweight::add_light_weight_timer().await;
if let Some(window) = WindowManager::get_main_window()
&& window.is_visible().unwrap_or(false)
-1
View File
@@ -20,7 +20,6 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
cmd::restart_app,
cmd::install_update,
cmd::cancel_update_download,
cmd::get_staged_update,
cmd::restart_core,
cmd::upgrade_clash_core,
cmd::get_runtime_state,
+2
View File
@@ -1,2 +1,4 @@
mod async_handler;
pub use async_handler::AsyncHandler;
pub(crate) mod scheduled_task;
+16
View File
@@ -0,0 +1,16 @@
use super::AsyncHandler;
use std::{future::Future, sync::Arc};
pub(crate) use clash_verge_task::scheduled_task::{Mailbox, Next, ScheduledTask};
pub(crate) fn spawn<P, F, Fut>(policy: P, execute: F) -> Arc<Mailbox<P::Input>>
where
P: ScheduledTask + Send + 'static,
P::Input: Send + 'static,
F: FnMut(P::Work) -> Fut + Send + 'static,
Fut: Future<Output = P::Output> + Send + 'static,
{
let (mailbox, driver) = clash_verge_task::scheduled_task::new(policy, execute);
AsyncHandler::spawn(move || driver);
mailbox
}
+7 -3
View File
@@ -12,7 +12,7 @@ use crate::{
service::{SERVICE_MANAGER, ServiceManager},
tray::Tray,
},
core::{auto_backup::AutoBackupManager, lightweight::auto_lightweight_boot},
core::{auto_backup, lightweight::auto_lightweight_boot},
feat,
process::AsyncHandler,
utils::{init, server, window_manager::WindowManager},
@@ -150,7 +150,7 @@ async fn init_auto_lightweight_boot() {
}
async fn init_auto_backup() {
logging_error!(Type::Setup, AutoBackupManager::global().init().await);
auto_backup::init().await;
}
fn init_silent_updater() {
@@ -159,7 +159,11 @@ fn init_silent_updater() {
logging!(debug, Type::Setup, "Initializing silent updater...");
SilentUpdater::start(Handle::app_handle().clone());
let app_handle = Handle::app_handle();
let app_handle = app_handle.clone();
tokio::spawn(async move {
SilentUpdater::global().start_background_check(app_handle).await;
});
logging!(info, Type::Setup, "Silent updater initialized");
}
+3 -27
View File
@@ -1,11 +1,8 @@
import { Button } from '@mui/material'
import { useLockFn } from 'ahooks'
import { useRef } from 'react'
import { DialogRef } from '@/components/base'
import { useUpdate } from '@/hooks/use-update'
import { installUpdate, restartApp } from '@/services/cmds'
import { showNotice } from '@/services/notice-service'
import { UpdateViewer } from '../setting/mods/update-viewer'
@@ -17,27 +14,10 @@ export const UpdateButton = (props: Props) => {
const { className } = props
const viewerRef = useRef<DialogRef>(null)
const { updateInfo, stagedVersion } = useUpdate()
const onRestartToUpdate = useLockFn(async (version: string) => {
try {
const outcome = await installUpdate(version, () => {})
if (outcome === 'installed') {
await restartApp()
} else {
viewerRef.current?.open()
}
} catch (err) {
showNotice.error(err)
}
})
const { updateInfo } = useUpdate()
if (!updateInfo?.available) return null
// The staged installer makes the install near-instant, so the click is the whole action;
// any other outcome falls back to the dialog.
const ready = stagedVersion != null && stagedVersion === updateInfo.version
return (
<>
<UpdateViewer ref={viewerRef} />
@@ -47,13 +27,9 @@ export const UpdateButton = (props: Props) => {
variant="contained"
size="small"
className={className}
onClick={
ready
? () => onRestartToUpdate(updateInfo.version)
: () => viewerRef.current?.open()
}
onClick={() => viewerRef.current?.open()}
>
{ready ? 'Restart' : 'New'}
New
</Button>
</>
)
-7
View File
@@ -1,4 +1,3 @@
import { getStagedUpdate } from '@/services/cmds'
import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client'
import { checkForUpdate } from '@/services/update'
@@ -55,16 +54,10 @@ export const useUpdate = (enabled: boolean = true) => {
refetchOnReconnect: false,
})
const { data: stagedVersion } = useQuery({
queryKey: ['getStagedUpdate'],
queryFn: () => getStagedUpdate(),
})
return {
updateInfo,
checkUpdate,
loading: isValidating,
lastCheckUpdate: lastCheckUpdate ?? null,
stagedVersion: stagedVersion ?? null,
}
}
-3
View File
@@ -32,7 +32,6 @@ export const commands = {
onEvent,
}),
cancelUpdateDownload: () => __TAURI_INVOKE<void>('cancel_update_download'),
getStagedUpdate: () => __TAURI_INVOKE<string | null>('get_staged_update'),
restartCore: () => __TAURI_INVOKE<null>('restart_core'),
/** Replaces the managed core binary atomically instead of letting mihomo overwrite itself. */
upgradeClashCore: (force: boolean) =>
@@ -1142,7 +1141,6 @@ export type VergeEventPayloads_Deserialize = {
'profile-update-completed': ProfileUpdatePayload
'verge://run-state-changed': RunStateView_Deserialize
'verge://pending-failures-changed': null
'verge://staged-update-changed': null
}
export type VergeEventPayloads_Serialize = {
@@ -1157,7 +1155,6 @@ export type VergeEventPayloads_Serialize = {
'profile-update-completed': ProfileUpdatePayload
'verge://run-state-changed': RunStateView_Serialize
'verge://pending-failures-changed': null
'verge://staged-update-changed': null
}
export type WebDavFile = {
-2
View File
@@ -81,8 +81,6 @@ export const createEventBus = (deps: BusHandlerDeps) => {
if (payload.mode !== 'NotRunning') forgetShownStartupError()
},
'verge://pending-failures-changed': () => deps.readPendingFailures(),
'verge://staged-update-changed': () =>
deps.revalidateKeys(['getStagedUpdate']),
[TEST_ALL_EVENT]: () => deps.dispatch({ type: 'testAll/requested' }),
}
-4
View File
@@ -306,10 +306,6 @@ export async function cancelUpdateDownload() {
return commands.cancelUpdateDownload()
}
export async function getStagedUpdate() {
return commands.getStagedUpdate()
}
export async function getAppDir() {
return commands.getAppDir()
}