mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-29 00:40:18 +08:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9724aa6d4d | ||
|
|
1be3ee67f8 | ||
|
|
cc99c90a66 |
Generated
-10
@@ -1098,7 +1098,6 @@ dependencies = [
|
|||||||
"clash-verge-logging",
|
"clash-verge-logging",
|
||||||
"clash-verge-media-unlock",
|
"clash-verge-media-unlock",
|
||||||
"clash-verge-signal",
|
"clash-verge-signal",
|
||||||
"clash-verge-task",
|
|
||||||
"clash_verge_service_ipc",
|
"clash_verge_service_ipc",
|
||||||
"dark-light",
|
"dark-light",
|
||||||
"deelevate",
|
"deelevate",
|
||||||
@@ -1223,15 +1222,6 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "clash-verge-task"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"futures",
|
|
||||||
"parking_lot 0.13.0",
|
|
||||||
"tokio",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clash_verge_service_ipc"
|
name = "clash_verge_service_ipc"
|
||||||
version = "2.8.2"
|
version = "2.8.2"
|
||||||
|
|||||||
@@ -2,7 +2,6 @@
|
|||||||
members = [
|
members = [
|
||||||
"src-tauri",
|
"src-tauri",
|
||||||
"crates/clash-verge-draft",
|
"crates/clash-verge-draft",
|
||||||
"crates/clash-verge-task",
|
|
||||||
"crates/clash-verge-media-unlock",
|
"crates/clash-verge-media-unlock",
|
||||||
"crates/clash-verge-logging",
|
"crates/clash-verge-logging",
|
||||||
"crates/clash-verge-signal",
|
"crates/clash-verge-signal",
|
||||||
@@ -53,7 +52,6 @@ muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdf
|
|||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
clash-verge-draft = { path = "crates/clash-verge-draft" }
|
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-media-unlock = { path = "crates/clash-verge-media-unlock" }
|
||||||
clash-verge-logging = { path = "crates/clash-verge-logging" }
|
clash-verge-logging = { path = "crates/clash-verge-logging" }
|
||||||
clash-verge-signal = { path = "crates/clash-verge-signal" }
|
clash-verge-signal = { path = "crates/clash-verge-signal" }
|
||||||
@@ -67,7 +65,6 @@ tauri = { version = "2.12.7" }
|
|||||||
tauri-plugin-clipboard-manager = "2.5.0"
|
tauri-plugin-clipboard-manager = "2.5.0"
|
||||||
parking_lot = "0.13.0"
|
parking_lot = "0.13.0"
|
||||||
anyhow = "1.0.105"
|
anyhow = "1.0.105"
|
||||||
futures = "0.3.34"
|
|
||||||
chrono = "0.4.45"
|
chrono = "0.4.45"
|
||||||
criterion = { version = "0.8.2", features = ["async_tokio"] }
|
criterion = { version = "0.8.2", features = ["async_tokio"] }
|
||||||
tokio = { version = "1.54.1", features = [
|
tokio = { version = "1.54.1", features = [
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
# 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).
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
[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
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
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)
|
|
||||||
}
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
//! Single-owner task drivers with caller-managed runtime and cancellation.
|
|
||||||
|
|
||||||
pub mod countdown;
|
|
||||||
pub mod scheduled_task;
|
|
||||||
pub mod watch_task;
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,213 +0,0 @@
|
|||||||
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(())
|
|
||||||
}
|
|
||||||
@@ -73,4 +73,4 @@ Native UI strings (tray menu, notifications, dialogs) use `rust-i18n` with YAML
|
|||||||
|
|
||||||
- File an issue for missing context, tooling bugs, or localization gaps so we can track them.
|
- File an issue for missing context, tooling bugs, or localization gaps so we can track them.
|
||||||
- PRs that touch UI should include screenshots or GIFs whenever text length may affect layout.
|
- PRs that touch UI should include screenshots or GIFs whenever text length may affect layout.
|
||||||
- Mention the commands you ran (formatting, type generation, tests) in the PR checklist. If you need extra context or review help, request it via a PR comment.
|
- Keep routine command results in the working conversation rather than the PR body; report only material localization or layout gaps. If you need extra context or review help, request it via a PR comment.
|
||||||
|
|||||||
+2
-2
@@ -78,7 +78,7 @@
|
|||||||
"rehype-sanitize": "^6.0.0",
|
"rehype-sanitize": "^6.0.0",
|
||||||
"swr": "^2.5.1",
|
"swr": "^2.5.1",
|
||||||
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
|
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
|
||||||
"tldts": "7.5.5",
|
"tldts": "7.6.2",
|
||||||
"types-pac": "^1.0.3",
|
"types-pac": "^1.0.3",
|
||||||
"validator": "^13.15.35"
|
"validator": "^13.15.35"
|
||||||
},
|
},
|
||||||
@@ -90,7 +90,7 @@
|
|||||||
"@tauri-apps/cli": "2.12.6",
|
"@tauri-apps/cli": "2.12.6",
|
||||||
"@types/lodash-es": "^4.17.12",
|
"@types/lodash-es": "^4.17.12",
|
||||||
"@types/node": "^26.0.0",
|
"@types/node": "^26.0.0",
|
||||||
"@types/react": "19.3.0",
|
"@types/react": "19.3.3",
|
||||||
"@types/react-dom": "19.3.0",
|
"@types/react-dom": "19.3.0",
|
||||||
"@types/validator": "^13.15.10",
|
"@types/validator": "^13.15.10",
|
||||||
"@vitejs/plugin-legacy": "^8.2.3",
|
"@vitejs/plugin-legacy": "^8.2.3",
|
||||||
|
|||||||
Generated
+67
-67
@@ -199,10 +199,10 @@ importers:
|
|||||||
version: 0.5.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
version: 0.5.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||||
'@emotion/react':
|
'@emotion/react':
|
||||||
specifier: ^11.14.0
|
specifier: ^11.14.0
|
||||||
version: 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
version: 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
'@emotion/styled':
|
'@emotion/styled':
|
||||||
specifier: ^11.14.1
|
specifier: ^11.14.1
|
||||||
version: 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
version: 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
'@juggle/resize-observer':
|
'@juggle/resize-observer':
|
||||||
specifier: ^3.4.0
|
specifier: ^3.4.0
|
||||||
version: 3.4.0
|
version: 3.4.0
|
||||||
@@ -211,10 +211,10 @@ importers:
|
|||||||
version: 4.7.0(monaco-editor@0.58.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
version: 4.7.0(monaco-editor@0.58.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||||
'@mui/icons-material':
|
'@mui/icons-material':
|
||||||
specifier: ^9.4.0
|
specifier: ^9.4.0
|
||||||
version: 9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.0)(react@19.3.1)
|
version: 9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.3)(react@19.3.1)
|
||||||
'@mui/material':
|
'@mui/material':
|
||||||
specifier: ^9.4.0
|
specifier: ^9.4.0
|
||||||
version: 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
version: 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||||
'@tanstack/react-virtual':
|
'@tanstack/react-virtual':
|
||||||
specifier: ^3.14.13
|
specifier: ^3.14.13
|
||||||
version: 3.14.13(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
version: 3.14.13(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||||
@@ -286,16 +286,16 @@ importers:
|
|||||||
version: 19.3.1(react@19.3.1)
|
version: 19.3.1(react@19.3.1)
|
||||||
react-error-boundary:
|
react-error-boundary:
|
||||||
specifier: 6.1.6
|
specifier: 6.1.6
|
||||||
version: 6.1.6(@types/react@19.3.0)(react@19.3.1)
|
version: 6.1.6(@types/react@19.3.3)(react@19.3.1)
|
||||||
react-hook-form:
|
react-hook-form:
|
||||||
specifier: ^7.88.0
|
specifier: ^7.88.0
|
||||||
version: 7.88.0(react@19.3.1)
|
version: 7.88.0(react@19.3.1)
|
||||||
react-i18next:
|
react-i18next:
|
||||||
specifier: 18.0.3
|
specifier: 18.0.3
|
||||||
version: 18.0.3(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3)
|
version: 18.0.3(@types/react@19.3.3)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3)
|
||||||
react-markdown:
|
react-markdown:
|
||||||
specifier: 10.1.0
|
specifier: 10.1.0
|
||||||
version: 10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
version: 10.1.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
react-router:
|
react-router:
|
||||||
specifier: ^8.4.0
|
specifier: ^8.4.0
|
||||||
version: 8.4.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
version: 8.4.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||||
@@ -312,8 +312,8 @@ importers:
|
|||||||
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
|
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
|
||||||
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f
|
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f
|
||||||
tldts:
|
tldts:
|
||||||
specifier: 7.5.5
|
specifier: 7.6.2
|
||||||
version: 7.5.5
|
version: 7.6.2
|
||||||
types-pac:
|
types-pac:
|
||||||
specifier: ^1.0.3
|
specifier: ^1.0.3
|
||||||
version: 1.0.3
|
version: 1.0.3
|
||||||
@@ -343,11 +343,11 @@ importers:
|
|||||||
specifier: ^26.0.0
|
specifier: ^26.0.0
|
||||||
version: 26.6.5
|
version: 26.6.5
|
||||||
'@types/react':
|
'@types/react':
|
||||||
specifier: 19.3.0
|
specifier: 19.3.3
|
||||||
version: 19.3.0
|
version: 19.3.3
|
||||||
'@types/react-dom':
|
'@types/react-dom':
|
||||||
specifier: 19.3.0
|
specifier: 19.3.0
|
||||||
version: 19.3.0(@types/react@19.3.0)
|
version: 19.3.0(@types/react@19.3.3)
|
||||||
'@types/validator':
|
'@types/validator':
|
||||||
specifier: ^13.15.10
|
specifier: ^13.15.10
|
||||||
version: 13.15.10
|
version: 13.15.10
|
||||||
@@ -2283,8 +2283,8 @@ packages:
|
|||||||
peerDependencies:
|
peerDependencies:
|
||||||
'@types/react': '*'
|
'@types/react': '*'
|
||||||
|
|
||||||
'@types/react@19.3.0':
|
'@types/react@19.3.3':
|
||||||
resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}
|
resolution: {integrity: sha512-K8uWpJc4teiuOPdiP1umjeA9rGMgVPiXuoL66fcS1QlwBT1WMqY8PORmub9FadopIs+RCW6siYEs7Lpq+vDlog==}
|
||||||
|
|
||||||
'@types/trusted-types@2.0.7':
|
'@types/trusted-types@2.0.7':
|
||||||
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
||||||
@@ -4057,11 +4057,11 @@ packages:
|
|||||||
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
|
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
|
||||||
engines: {node: '>=12.0.0'}
|
engines: {node: '>=12.0.0'}
|
||||||
|
|
||||||
tldts-core@7.5.5:
|
tldts-core@7.6.2:
|
||||||
resolution: {integrity: sha512-rEJz/8cJFY/bdF354gl14yxavbrIbvM+FcbkYVQ6CSCMQTJdUFUIm39TTWSiGPvcpQh7/F6qHrD3SkwwdgtDCw==}
|
resolution: {integrity: sha512-/ZG+gignPzfgtpWNnbS7AKcU1ptt9jDqhIlr7vHOaw/Psz6HjXyB2CeFS3RrUGYwER/Q4F6IS8+9rZuYfRUz+Q==}
|
||||||
|
|
||||||
tldts@7.5.5:
|
tldts@7.6.2:
|
||||||
resolution: {integrity: sha512-Hy6IImaWALzJOgCIss4gIFi4G0M9lqk95pFKCUVxQPZw+biZ1Pv6f28JpYgahpJB+BufA0HYsIU/aP/WIx3KRg==}
|
resolution: {integrity: sha512-IylRLICacWmPVf5tQIOvKkZzf2Vp8qJT3bAZox+3bWXj5P/pn45PC1a9l86loP7D/ywbSt/h/NnyIoR0fg4utA==}
|
||||||
hasBin: true
|
hasBin: true
|
||||||
|
|
||||||
trim-lines@3.0.1:
|
trim-lines@3.0.1:
|
||||||
@@ -5201,7 +5201,7 @@ snapshots:
|
|||||||
|
|
||||||
'@emotion/memoize@0.9.0': {}
|
'@emotion/memoize@0.9.0': {}
|
||||||
|
|
||||||
'@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)':
|
'@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
'@emotion/babel-plugin': 11.13.5(supports-color@7.2.0)
|
'@emotion/babel-plugin': 11.13.5(supports-color@7.2.0)
|
||||||
@@ -5213,7 +5213,7 @@ snapshots:
|
|||||||
hoist-non-react-statics: 3.3.2
|
hoist-non-react-statics: 3.3.2
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
@@ -5227,18 +5227,18 @@ snapshots:
|
|||||||
|
|
||||||
'@emotion/sheet@1.4.0': {}
|
'@emotion/sheet@1.4.0': {}
|
||||||
|
|
||||||
'@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)':
|
'@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
'@emotion/babel-plugin': 11.13.5(supports-color@7.2.0)
|
'@emotion/babel-plugin': 11.13.5(supports-color@7.2.0)
|
||||||
'@emotion/is-prop-valid': 1.4.0
|
'@emotion/is-prop-valid': 1.4.0
|
||||||
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
'@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
'@emotion/serialize': 1.3.3
|
'@emotion/serialize': 1.3.3
|
||||||
'@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.3.1)
|
'@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.3.1)
|
||||||
'@emotion/utils': 1.4.2
|
'@emotion/utils': 1.4.2
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- supports-color
|
- supports-color
|
||||||
|
|
||||||
@@ -5519,23 +5519,23 @@ snapshots:
|
|||||||
|
|
||||||
'@mui/core-downloads-tracker@9.4.0': {}
|
'@mui/core-downloads-tracker@9.4.0': {}
|
||||||
|
|
||||||
'@mui/icons-material@9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.0)(react@19.3.1)':
|
'@mui/icons-material@9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.3)(react@19.3.1)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
'@mui/material': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
'@mui/material': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
|
|
||||||
'@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
|
'@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
'@mui/core-downloads-tracker': 9.4.0
|
'@mui/core-downloads-tracker': 9.4.0
|
||||||
'@mui/system': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)
|
'@mui/system': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)
|
||||||
'@mui/types': 9.4.0(@types/react@19.3.0)
|
'@mui/types': 9.4.0(@types/react@19.3.3)
|
||||||
'@mui/utils': 9.4.0(@types/react@19.3.0)(react@19.3.1)
|
'@mui/utils': 9.4.0(@types/react@19.3.3)(react@19.3.1)
|
||||||
'@popperjs/core': 2.11.8
|
'@popperjs/core': 2.11.8
|
||||||
'@types/react-transition-group': 4.4.12(@types/react@19.3.0)
|
'@types/react-transition-group': 4.4.12(@types/react@19.3.3)
|
||||||
clsx: 2.1.1
|
clsx: 2.1.1
|
||||||
csstype: 3.2.3
|
csstype: 3.2.3
|
||||||
prop-types: 15.8.1
|
prop-types: 15.8.1
|
||||||
@@ -5544,20 +5544,20 @@ snapshots:
|
|||||||
react-is: 19.3.0
|
react-is: 19.3.0
|
||||||
react-transition-group: 4.4.5(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
react-transition-group: 4.4.5(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
'@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
|
|
||||||
'@mui/private-theming@9.4.0(@types/react@19.3.0)(react@19.3.1)':
|
'@mui/private-theming@9.4.0(@types/react@19.3.3)(react@19.3.1)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
'@mui/utils': 9.4.0(@types/react@19.3.0)(react@19.3.1)
|
'@mui/utils': 9.4.0(@types/react@19.3.3)(react@19.3.1)
|
||||||
prop-types: 15.8.1
|
prop-types: 15.8.1
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
|
|
||||||
'@mui/styled-engine@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)':
|
'@mui/styled-engine@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
'@emotion/cache': 11.14.0
|
'@emotion/cache': 11.14.0
|
||||||
@@ -5567,42 +5567,42 @@ snapshots:
|
|||||||
prop-types: 15.8.1
|
prop-types: 15.8.1
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
'@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
|
|
||||||
'@mui/system@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)':
|
'@mui/system@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
'@mui/private-theming': 9.4.0(@types/react@19.3.0)(react@19.3.1)
|
'@mui/private-theming': 9.4.0(@types/react@19.3.3)(react@19.3.1)
|
||||||
'@mui/styled-engine': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)
|
'@mui/styled-engine': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)
|
||||||
'@mui/types': 9.4.0(@types/react@19.3.0)
|
'@mui/types': 9.4.0(@types/react@19.3.3)
|
||||||
'@mui/utils': 9.4.0(@types/react@19.3.0)(react@19.3.1)
|
'@mui/utils': 9.4.0(@types/react@19.3.3)(react@19.3.1)
|
||||||
clsx: 2.1.1
|
clsx: 2.1.1
|
||||||
csstype: 3.2.3
|
csstype: 3.2.3
|
||||||
prop-types: 15.8.1
|
prop-types: 15.8.1
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
'@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
|
|
||||||
'@mui/types@9.4.0(@types/react@19.3.0)':
|
'@mui/types@9.4.0(@types/react@19.3.3)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
|
|
||||||
'@mui/utils@9.4.0(@types/react@19.3.0)(react@19.3.1)':
|
'@mui/utils@9.4.0(@types/react@19.3.3)(react@19.3.1)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@babel/runtime': 7.29.7
|
'@babel/runtime': 7.29.7
|
||||||
'@mui/types': 9.4.0(@types/react@19.3.0)
|
'@mui/types': 9.4.0(@types/react@19.3.3)
|
||||||
'@types/prop-types': 15.7.15
|
'@types/prop-types': 15.7.15
|
||||||
clsx: 2.1.1
|
clsx: 2.1.1
|
||||||
prop-types: 15.8.1
|
prop-types: 15.8.1
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
react-is: 19.3.0
|
react-is: 19.3.0
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
|
|
||||||
'@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
|
'@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
|
||||||
dependencies:
|
dependencies:
|
||||||
@@ -6134,15 +6134,15 @@ snapshots:
|
|||||||
|
|
||||||
'@types/prop-types@15.7.15': {}
|
'@types/prop-types@15.7.15': {}
|
||||||
|
|
||||||
'@types/react-dom@19.3.0(@types/react@19.3.0)':
|
'@types/react-dom@19.3.0(@types/react@19.3.3)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
|
|
||||||
'@types/react-transition-group@4.4.12(@types/react@19.3.0)':
|
'@types/react-transition-group@4.4.12(@types/react@19.3.3)':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
|
|
||||||
'@types/react@19.3.0':
|
'@types/react@19.3.3':
|
||||||
dependencies:
|
dependencies:
|
||||||
csstype: 3.2.3
|
csstype: 3.2.3
|
||||||
|
|
||||||
@@ -7894,11 +7894,11 @@ snapshots:
|
|||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
scheduler: 0.28.0
|
scheduler: 0.28.0
|
||||||
|
|
||||||
react-error-boundary@6.1.6(@types/react@19.3.0)(react@19.3.1):
|
react-error-boundary@6.1.6(@types/react@19.3.3)(react@19.3.1):
|
||||||
dependencies:
|
dependencies:
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
|
|
||||||
react-fast-compare@3.2.2: {}
|
react-fast-compare@3.2.2: {}
|
||||||
|
|
||||||
@@ -7906,24 +7906,24 @@ snapshots:
|
|||||||
dependencies:
|
dependencies:
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
|
|
||||||
react-i18next@18.0.3(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3):
|
react-i18next@18.0.3(@types/react@19.3.3)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3):
|
||||||
dependencies:
|
dependencies:
|
||||||
html-parse-stringify: 4.0.1
|
html-parse-stringify: 4.0.1
|
||||||
i18next: 27.0.1(typescript@6.0.3)
|
i18next: 27.0.1(typescript@6.0.3)
|
||||||
react: 19.3.1
|
react: 19.3.1
|
||||||
optionalDependencies:
|
optionalDependencies:
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
typescript: 6.0.3
|
typescript: 6.0.3
|
||||||
|
|
||||||
react-is@16.13.1: {}
|
react-is@16.13.1: {}
|
||||||
|
|
||||||
react-is@19.3.0: {}
|
react-is@19.3.0: {}
|
||||||
|
|
||||||
react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0):
|
react-markdown@10.1.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0):
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/hast': 3.0.5
|
'@types/hast': 3.0.5
|
||||||
'@types/mdast': 4.0.4
|
'@types/mdast': 4.0.4
|
||||||
'@types/react': 19.3.0
|
'@types/react': 19.3.3
|
||||||
devlop: 1.1.0
|
devlop: 1.1.0
|
||||||
hast-util-to-jsx-runtime: 2.3.6(supports-color@7.2.0)
|
hast-util-to-jsx-runtime: 2.3.6(supports-color@7.2.0)
|
||||||
html-url-attributes: 3.0.1
|
html-url-attributes: 3.0.1
|
||||||
@@ -8170,11 +8170,11 @@ snapshots:
|
|||||||
fdir: 6.5.0(picomatch@4.0.7)
|
fdir: 6.5.0(picomatch@4.0.7)
|
||||||
picomatch: 4.0.7
|
picomatch: 4.0.7
|
||||||
|
|
||||||
tldts-core@7.5.5: {}
|
tldts-core@7.6.2: {}
|
||||||
|
|
||||||
tldts@7.5.5:
|
tldts@7.6.2:
|
||||||
dependencies:
|
dependencies:
|
||||||
tldts-core: 7.5.5
|
tldts-core: 7.6.2
|
||||||
|
|
||||||
trim-lines@3.0.1: {}
|
trim-lines@3.0.1: {}
|
||||||
|
|
||||||
|
|||||||
+21
-16
@@ -1,19 +1,24 @@
|
|||||||
# Backend Architecture Guardrails
|
# Backend Architecture Guardrails
|
||||||
|
|
||||||
Use [Workspace Crate Architecture](../crates/AGENTS.md) when extracting backend
|
These rules supplement the repository's root `AGENTS.md`.
|
||||||
capabilities or changing background task ownership.
|
|
||||||
|
|
||||||
- **Configuration and effects.** `config` owns source configuration, drafts, and
|
- **Configuration ownership.** `config` owns source configuration, drafts and
|
||||||
persistence. The effects layer classifies every Verge patch field, including
|
persistence. The effects layer owns patch orchestration. Rollbackable
|
||||||
fields without effects and platform-specific fields, and reconciles requested
|
transactions publish state after persistence and commit; already applied
|
||||||
state in dependency order. Publish rollbackable state after persistence and
|
runtime and independently committed state remain authoritative even when a
|
||||||
commit. On failure, preserve already applied runtime effects, independently
|
later step fails. Preserve that state, its notifications and the error.
|
||||||
committed state, their notifications, and the error.
|
- **Effect ownership.** The declarative registry classifies every Verge patch field,
|
||||||
- **Wire contract.** Use typed notifications and preserve event names, status
|
including fields without effects and platform-specific fields. Effects
|
||||||
values, and payload compatibility with frontend consumers.
|
reconcile toward the requested state with explicit dependencies and ordering.
|
||||||
- **Lock order.** Acquire configuration-write, configuration-update, Core
|
Configuration rollback does not imply reversal of OS or lifecycle effects.
|
||||||
lifecycle, and DNS ownership in that order when needed. Preserve independent
|
- **Shared wire contract.** Notifications are typed. Event names, status values
|
||||||
transaction boundaries and release synchronous guards before suspension.
|
and payload shapes stay compatible with frontend producers and consumers.
|
||||||
- **Retries.** Reuse the backend retry policy and preserve attempts, delays, and
|
- **Synchronization ownership.** Configuration-write serialization precedes
|
||||||
terminal errors. Keep monitor lifetime, condition waits, and candidate fallback
|
configuration-update ownership, which precedes Core lifecycle ownership.
|
||||||
under their own contracts.
|
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.
|
||||||
|
|||||||
@@ -31,7 +31,6 @@ tauri-build = { version = "2.7.6", features = [] }
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clash-verge-draft = { workspace = true }
|
clash-verge-draft = { workspace = true }
|
||||||
clash-verge-task = { workspace = true }
|
|
||||||
clash-verge-media-unlock = { workspace = true }
|
clash-verge-media-unlock = { workspace = true }
|
||||||
clash-verge-logging = { workspace = true }
|
clash-verge-logging = { workspace = true }
|
||||||
clash-verge-i18n = { workspace = true }
|
clash-verge-i18n = { workspace = true }
|
||||||
@@ -83,7 +82,7 @@ aes-gcm = { version = "0.11.1" }
|
|||||||
base64 = "0.23.1"
|
base64 = "0.23.1"
|
||||||
sha2 = "0.11.2"
|
sha2 = "0.11.2"
|
||||||
getrandom = "0.4.3"
|
getrandom = "0.4.3"
|
||||||
futures = { workspace = true }
|
futures = "0.3.34"
|
||||||
gethostname = "1.1.0"
|
gethostname = "1.1.0"
|
||||||
tauri-plugin-notification = "2.8.1"
|
tauri-plugin-notification = "2.8.1"
|
||||||
backon = { version = "1.6.0", features = ["tokio-sleep"] }
|
backon = { version = "1.6.0", features = ["tokio-sleep"] }
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use crate::{
|
|||||||
cmd::StringifyErr as _,
|
cmd::StringifyErr as _,
|
||||||
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
||||||
config::{Config, IProfiles, PrfItem},
|
config::{Config, IProfiles, PrfItem},
|
||||||
core::auto_backup::{self, AutoBackupTrigger},
|
core::auto_backup::{AutoBackupManager, AutoBackupTrigger},
|
||||||
core::{
|
core::{
|
||||||
CoreManager, handle,
|
CoreManager, handle,
|
||||||
validate::{CoreConfigValidator, ValidationOutcome},
|
validate::{CoreConfigValidator, ValidationOutcome},
|
||||||
@@ -86,7 +86,7 @@ pub async fn save_profile_file(
|
|||||||
if changes_applied.is_valid()
|
if changes_applied.is_valid()
|
||||||
&& let Some(trigger) = backup_trigger
|
&& let Some(trigger) = backup_trigger
|
||||||
{
|
{
|
||||||
auto_backup::trigger_backup(trigger);
|
AutoBackupManager::trigger_backup(trigger);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(changes_applied)
|
Ok(changes_applied)
|
||||||
|
|||||||
+135
-113
@@ -1,22 +1,29 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IVerge},
|
config::{Config, IVerge},
|
||||||
feat::create_local_backup_with_namer,
|
feat::create_local_backup_with_namer,
|
||||||
process::scheduled_task::{self, Mailbox, Next, ScheduledTask},
|
process::AsyncHandler,
|
||||||
utils::dirs::local_backup_dir,
|
utils::dirs::local_backup_dir,
|
||||||
};
|
};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
use chrono::Local;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use std::{
|
use std::{
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::{Arc, LazyLock},
|
sync::{
|
||||||
|
OnceLock,
|
||||||
|
atomic::{AtomicBool, AtomicI64, Ordering},
|
||||||
|
},
|
||||||
time::{Duration, UNIX_EPOCH},
|
time::{Duration, UNIX_EPOCH},
|
||||||
};
|
};
|
||||||
use tokio::{fs, time::Instant};
|
use tokio::{
|
||||||
|
fs,
|
||||||
|
sync::{Mutex, watch},
|
||||||
|
};
|
||||||
|
|
||||||
const DEFAULT_INTERVAL_HOURS: u64 = 24;
|
const DEFAULT_INTERVAL_HOURS: u64 = 24;
|
||||||
const MIN_INTERVAL_HOURS: u64 = 1;
|
const MIN_INTERVAL_HOURS: u64 = 1;
|
||||||
const MAX_INTERVAL_HOURS: u64 = 168;
|
const MAX_INTERVAL_HOURS: u64 = 168;
|
||||||
const MIN_BACKUP_INTERVAL: Duration = Duration::from_secs(60);
|
const MIN_BACKUP_INTERVAL_SECS: i64 = 60;
|
||||||
const AUTO_BACKUP_KEEP: usize = 20;
|
const AUTO_BACKUP_KEEP: usize = 20;
|
||||||
const AUTO_MARKER: &str = "-auto-";
|
const AUTO_MARKER: &str = "-auto-";
|
||||||
|
|
||||||
@@ -35,9 +42,13 @@ impl AutoBackupTrigger {
|
|||||||
Self::GlobalScript => "script",
|
Self::GlobalScript => "script",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fn is_schedule(self) -> bool {
|
||||||
|
matches!(self, Self::Scheduled)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug)]
|
||||||
struct AutoBackupSettings {
|
struct AutoBackupSettings {
|
||||||
schedule_enabled: bool,
|
schedule_enabled: bool,
|
||||||
interval_hours: u64,
|
interval_hours: u64,
|
||||||
@@ -45,11 +56,6 @@ struct AutoBackupSettings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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 {
|
fn from_verge(verge: &IVerge) -> Self {
|
||||||
let interval = verge
|
let interval = verge
|
||||||
.auto_backup_interval_hours
|
.auto_backup_interval_hours
|
||||||
@@ -74,139 +80,155 @@ impl Default for AutoBackupSettings {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
pub struct AutoBackupManager {
|
||||||
struct BackupInput {
|
settings_tx: watch::Sender<AutoBackupSettings>,
|
||||||
settings: Option<AutoBackupSettings>,
|
// The watch channel is the single settings store; no duplicate copies.
|
||||||
restart_schedule: bool,
|
settings_rx: watch::Receiver<AutoBackupSettings>,
|
||||||
clear_pending_edit: bool,
|
runner_started: AtomicBool,
|
||||||
edit_before_settings: Option<AutoBackupTrigger>,
|
exec_lock: Mutex<()>,
|
||||||
edit: Option<AutoBackupTrigger>,
|
last_backup: AtomicI64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BackupInput {
|
impl AutoBackupManager {
|
||||||
fn update_settings(&mut self, settings: AutoBackupSettings) -> bool {
|
pub fn global() -> &'static Self {
|
||||||
if self.settings == Some(settings) {
|
static INSTANCE: OnceLock<AutoBackupManager> = OnceLock::new();
|
||||||
return false;
|
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),
|
||||||
}
|
}
|
||||||
// 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 {
|
pub async fn init(&self) -> Result<()> {
|
||||||
let pending = match self.settings {
|
let settings = Self::load_settings().await;
|
||||||
Some(settings) if settings.change_enabled => &mut self.edit,
|
let _ = self.settings_tx.send_replace(settings);
|
||||||
Some(_) => return false,
|
self.maybe_start_runner(settings);
|
||||||
None => &mut self.edit_before_settings,
|
Ok(())
|
||||||
};
|
|
||||||
if pending.is_some() {
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
*pending = Some(trigger);
|
|
||||||
true
|
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 maybe_start_runner(&self, settings: AutoBackupSettings) {
|
||||||
|
if settings.schedule_enabled {
|
||||||
|
self.ensure_runner();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static BACKUP_REQUESTS: LazyLock<Arc<Mailbox<BackupInput>>> =
|
fn ensure_runner(&self) {
|
||||||
LazyLock::new(|| scheduled_task::spawn(BackupSchedule::default(), execute_backup));
|
if self.runner_started.swap(true, Ordering::SeqCst) {
|
||||||
|
return;
|
||||||
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 mut rx = self.settings_tx.subscribe();
|
||||||
let settings = AutoBackupSettings::from_verge(verge);
|
AsyncHandler::spawn(move || async move {
|
||||||
BACKUP_REQUESTS.update(|pending| pending.update_settings(settings));
|
Self::run_scheduler(&mut rx).await;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn trigger_backup(trigger: AutoBackupTrigger) {
|
async fn run_scheduler(rx: &mut watch::Receiver<AutoBackupSettings>) {
|
||||||
BACKUP_REQUESTS.update(|pending| pending.request_edit(trigger));
|
let mut current = *rx.borrow();
|
||||||
|
loop {
|
||||||
|
if !current.schedule_enabled {
|
||||||
|
if rx.changed().await.is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
current = *rx.borrow();
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
let duration = Duration::from_secs(current.interval_hours.saturating_mul(3600));
|
||||||
struct BackupSchedule {
|
let sleeper = tokio::time::sleep(duration);
|
||||||
settings: AutoBackupSettings,
|
tokio::pin!(sleeper);
|
||||||
due: Option<Instant>,
|
|
||||||
edit: Option<AutoBackupTrigger>,
|
|
||||||
last_backup: Option<Instant>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ScheduledTask for BackupSchedule {
|
tokio::select! {
|
||||||
type Input = BackupInput;
|
_ = &mut sleeper => {
|
||||||
type Work = AutoBackupTrigger;
|
if let Err(err) = Self::global()
|
||||||
type Output = Result<Instant>;
|
.execute_trigger(AutoBackupTrigger::Scheduled)
|
||||||
|
.await
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::Backup,
|
||||||
|
"Scheduled auto backup failed: {err:#?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
self.due.map_or(Next::Idle, Next::At)
|
|
||||||
}
|
}
|
||||||
|
changed = rx.changed() => {
|
||||||
fn finished(&mut self, trigger: AutoBackupTrigger, result: std::thread::Result<Self::Output>, now: Instant) {
|
if changed.is_err() {
|
||||||
if trigger == AutoBackupTrigger::Scheduled {
|
break;
|
||||||
self.due = self.settings.interval().map(|interval| now + interval);
|
}
|
||||||
|
current = *rx.borrow();
|
||||||
}
|
}
|
||||||
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:?})"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute_backup(trigger: AutoBackupTrigger) -> Result<Instant> {
|
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?;
|
let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
|
||||||
let created_at = Instant::now();
|
self.last_backup.store(Local::now().timestamp(), Ordering::Release);
|
||||||
|
|
||||||
if let Err(err) = cleanup_auto_backups().await {
|
if let Err(err) = cleanup_auto_backups().await {
|
||||||
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
|
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
logging!(info, Type::Backup, "Auto backup created ({trigger:?}): {file_name}");
|
logging!(info, Type::Backup, "Auto backup created ({:?}): {}", trigger, file_name);
|
||||||
Ok(created_at)
|
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())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn append_auto_suffix(file_name: &str, slug: &str) -> String {
|
fn append_auto_suffix(file_name: &str, slug: &str) -> String {
|
||||||
|
|||||||
@@ -5,16 +5,14 @@ use crate::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use clash_verge_task::countdown::{self, Countdown};
|
|
||||||
|
|
||||||
use crate::utils::window_manager::WindowManager;
|
use crate::utils::window_manager::WindowManager;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use std::future::Future;
|
use std::sync::atomic::{AtomicU8, AtomicU32, Ordering};
|
||||||
use std::sync::LazyLock;
|
|
||||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
|
|
||||||
use std::time::Duration;
|
|
||||||
use tauri::Listener as _;
|
use tauri::Listener as _;
|
||||||
|
use tokio::sync::oneshot;
|
||||||
|
use tokio::time::{Duration, sleep};
|
||||||
|
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
@@ -43,24 +41,27 @@ impl LightweightState {
|
|||||||
static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8);
|
static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8);
|
||||||
|
|
||||||
struct WindowListener {
|
struct WindowListener {
|
||||||
handler_id: Option<tauri::EventId>,
|
handler_id: AtomicU32,
|
||||||
event: &'static str,
|
event: &'static str,
|
||||||
label: &'static str,
|
label: &'static str,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WindowListener {
|
impl WindowListener {
|
||||||
fn setup(&mut self, on_event: impl Fn() + Send + 'static) {
|
fn setup(&self, on_event: impl Fn() + Send + 'static) {
|
||||||
if let Some(window) = WindowManager::get_main_window() {
|
if let Some(window) = WindowManager::get_main_window() {
|
||||||
if let Some(id) = self.handler_id.take() {
|
let previous_handler_id = self.handler_id.swap(0, Ordering::AcqRel);
|
||||||
window.unlisten(id);
|
if previous_handler_id != 0 {
|
||||||
|
window.unlisten(previous_handler_id);
|
||||||
logging!(debug, Type::Lightweight, "覆盖旧的{}监听", self.label);
|
logging!(debug, Type::Lightweight, "覆盖旧的{}监听", self.label);
|
||||||
}
|
}
|
||||||
self.handler_id = Some(window.listen(self.event, move |_event| on_event()));
|
let handler_id = window.listen(self.event, move |_event| on_event());
|
||||||
|
self.handler_id.store(handler_id, Ordering::Release);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cancel(&mut self) {
|
fn cancel(&self) {
|
||||||
if let Some(id) = self.handler_id.take() {
|
let id = self.handler_id.swap(0, Ordering::AcqRel);
|
||||||
|
if id != 0 {
|
||||||
if let Some(window) = WindowManager::get_main_window() {
|
if let Some(window) = WindowManager::get_main_window() {
|
||||||
window.unlisten(id);
|
window.unlisten(id);
|
||||||
}
|
}
|
||||||
@@ -69,31 +70,19 @@ impl WindowListener {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct WindowListeners {
|
static WINDOW_CLOSE_LISTENER: WindowListener = WindowListener {
|
||||||
close: WindowListener,
|
handler_id: AtomicU32::new(0),
|
||||||
focus: WindowListener,
|
|
||||||
}
|
|
||||||
|
|
||||||
static WINDOW_LISTENERS: Mutex<WindowListeners> = Mutex::new(WindowListeners {
|
|
||||||
close: WindowListener {
|
|
||||||
handler_id: None,
|
|
||||||
event: "tauri://close-requested",
|
event: "tauri://close-requested",
|
||||||
label: "窗口关闭",
|
label: "窗口关闭",
|
||||||
},
|
};
|
||||||
focus: WindowListener {
|
|
||||||
handler_id: None,
|
static WEBVIEW_FOCUS_LISTENER: WindowListener = WindowListener {
|
||||||
|
handler_id: AtomicU32::new(0),
|
||||||
event: "tauri://focus",
|
event: "tauri://focus",
|
||||||
label: "窗口焦点",
|
label: "窗口焦点",
|
||||||
},
|
};
|
||||||
});
|
|
||||||
|
|
||||||
static TIMER_GENERATION: AtomicU64 = AtomicU64::new(0);
|
static CANCEL_TX: Mutex<Option<oneshot::Sender<()>>> = Mutex::new(None);
|
||||||
|
|
||||||
static COUNTDOWN: LazyLock<Countdown<u64>> = LazyLock::new(|| {
|
|
||||||
let (countdown, driver) = countdown::new(prepare_countdown, enter_lightweight_on_timeout);
|
|
||||||
AsyncHandler::spawn(move || driver);
|
|
||||||
countdown
|
|
||||||
});
|
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn get_state() -> LightweightState {
|
fn get_state() -> LightweightState {
|
||||||
@@ -129,12 +118,11 @@ async fn refresh_lightweight_tray_state() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn auto_lightweight_boot() -> Result<()> {
|
pub async fn auto_lightweight_boot() -> Result<()> {
|
||||||
let generation = TIMER_GENERATION.load(Ordering::Acquire);
|
|
||||||
let verge_config = Config::verge().await;
|
let verge_config = Config::verge().await;
|
||||||
let is_enable_auto = verge_config.data_arc().enable_auto_light_weight_mode.unwrap_or(false);
|
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);
|
let is_silent_start = verge_config.data_arc().enable_silent_start.unwrap_or(false);
|
||||||
if is_enable_auto && verge_config.latest_arc().enable_auto_light_weight_mode.unwrap_or(false) {
|
if is_enable_auto {
|
||||||
enable_auto_light_weight_mode_at(generation).await;
|
enable_auto_light_weight_mode().await;
|
||||||
}
|
}
|
||||||
if is_silent_start {
|
if is_silent_start {
|
||||||
entry_lightweight_mode().await;
|
entry_lightweight_mode().await;
|
||||||
@@ -143,43 +131,32 @@ pub async fn auto_lightweight_boot() -> Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn enable_auto_light_weight_mode() {
|
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 {
|
if let Err(e) = Timer::global().init().await {
|
||||||
logging!(error, Type::Lightweight, "Failed to initialize timer: {e}");
|
logging!(error, Type::Lightweight, "Failed to initialize timer: {e}");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
logging!(info, Type::Lightweight, "开启自动轻量模式");
|
logging!(info, Type::Lightweight, "开启自动轻量模式");
|
||||||
setup_auto_light_weight_listeners(generation);
|
setup_window_close_listener();
|
||||||
|
setup_webview_focus_listener();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn disable_auto_light_weight_mode() {
|
pub fn disable_auto_light_weight_mode() {
|
||||||
logging!(info, Type::Lightweight, "关闭自动轻量模式");
|
logging!(info, Type::Lightweight, "关闭自动轻量模式");
|
||||||
TIMER_GENERATION.fetch_add(1, Ordering::AcqRel);
|
cancel_light_weight_timer();
|
||||||
COUNTDOWN.disarm();
|
cancel_window_close_listener();
|
||||||
let mut listeners = WINDOW_LISTENERS.lock();
|
cancel_webview_focus_listener();
|
||||||
listeners.close.cancel();
|
|
||||||
listeners.focus.cancel();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn entry_lightweight_mode() -> bool {
|
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) {
|
if !try_transition(LightweightState::Normal, LightweightState::In) {
|
||||||
logging!(debug, Type::Lightweight, "无需进入轻量模式,跳过调用");
|
logging!(debug, Type::Lightweight, "无需进入轻量模式,跳过调用");
|
||||||
|
refresh_lightweight_tray_state().await;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
record_state_and_log(LightweightState::In);
|
record_state_and_log(LightweightState::In);
|
||||||
WindowManager::destroy_main_window();
|
WindowManager::destroy_main_window();
|
||||||
|
cancel_light_weight_timer();
|
||||||
|
refresh_lightweight_tray_state().await;
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,11 +172,16 @@ pub async fn exit_lightweight_mode() -> bool {
|
|||||||
}
|
}
|
||||||
record_state_and_log(LightweightState::Exiting);
|
record_state_and_log(LightweightState::Exiting);
|
||||||
WindowManager::show_main_window().await;
|
WindowManager::show_main_window().await;
|
||||||
let generation = TIMER_GENERATION.load(Ordering::Acquire);
|
let enable_auto_light_weight_mode = Config::verge()
|
||||||
if auto_light_weight_is_enabled().await {
|
.await
|
||||||
setup_auto_light_weight_listeners(generation);
|
.data_arc()
|
||||||
|
.enable_auto_light_weight_mode
|
||||||
|
.unwrap_or(false);
|
||||||
|
if enable_auto_light_weight_mode {
|
||||||
|
setup_window_close_listener();
|
||||||
|
setup_webview_focus_listener();
|
||||||
}
|
}
|
||||||
COUNTDOWN.disarm();
|
cancel_light_weight_timer();
|
||||||
record_state_and_log(LightweightState::Normal);
|
record_state_and_log(LightweightState::Normal);
|
||||||
refresh_lightweight_tray_state().await;
|
refresh_lightweight_tray_state().await;
|
||||||
true
|
true
|
||||||
@@ -207,64 +189,78 @@ pub async fn exit_lightweight_mode() -> bool {
|
|||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
pub async fn add_light_weight_timer() {
|
pub async fn add_light_weight_timer() {
|
||||||
let generation = TIMER_GENERATION.load(Ordering::Acquire);
|
setup_light_weight_timer().await;
|
||||||
if auto_light_weight_is_enabled().await {
|
|
||||||
COUNTDOWN.arm(generation);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn auto_light_weight_is_enabled() -> bool {
|
fn setup_window_close_listener() {
|
||||||
let verge = Config::verge().await;
|
WINDOW_CLOSE_LISTENER.setup(|| {
|
||||||
// A disable applies before persistence. A rollback restores eligibility for future hides.
|
std::mem::drop(AsyncHandler::spawn(|| async {
|
||||||
verge.data_arc().enable_auto_light_weight_mode.unwrap_or(false)
|
setup_light_weight_timer().await;
|
||||||
&& verge.latest_arc().enable_auto_light_weight_mode.unwrap_or(false)
|
}));
|
||||||
}
|
|
||||||
|
|
||||||
fn setup_auto_light_weight_listeners(generation: u64) {
|
|
||||||
let mut listeners = WINDOW_LISTENERS.lock();
|
|
||||||
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
listeners.close.setup(move || {
|
|
||||||
COUNTDOWN.arm(generation);
|
|
||||||
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
|
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
|
||||||
});
|
});
|
||||||
listeners.focus.setup(move || {
|
|
||||||
if generation == TIMER_GENERATION.load(Ordering::Acquire) {
|
|
||||||
COUNTDOWN.disarm();
|
|
||||||
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 prepare_countdown(generation: u64) -> Option<impl Future<Output = Duration>> {
|
fn cancel_webview_focus_listener() {
|
||||||
// Unlisten can be deferred while Tauri is delivering an event.
|
WEBVIEW_FOCUS_LISTENER.cancel();
|
||||||
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
|
|
||||||
return None;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Some(async {
|
async fn setup_light_weight_timer() {
|
||||||
let minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
|
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"
|
||||||
|
);
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
logging!(
|
logging!(
|
||||||
info,
|
info,
|
||||||
Type::Timer,
|
Type::Timer,
|
||||||
"Lightweight mode timer set, entering lightweight mode in {} minutes",
|
"Lightweight mode timer set, entering lightweight mode in {} minutes",
|
||||||
minutes
|
once_by_minutes
|
||||||
);
|
);
|
||||||
Duration::from_secs(minutes.saturating_mul(60))
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn enter_lightweight_on_timeout(generation: u64) {
|
fn cancel_light_weight_timer() {
|
||||||
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
|
let mut cancel_tx_guard = CANCEL_TX.lock();
|
||||||
return;
|
if let Some(tx) = cancel_tx_guard.take() {
|
||||||
|
let _ = tx.send(());
|
||||||
|
logging!(debug, Type::Timer, "Timer cancelled");
|
||||||
}
|
}
|
||||||
|
|
||||||
logging!(
|
|
||||||
info,
|
|
||||||
Type::Timer,
|
|
||||||
"Lightweight mode timer expired, entering lightweight mode"
|
|
||||||
);
|
|
||||||
begin_lightweight_mode();
|
|
||||||
AsyncHandler::spawn(refresh_lightweight_tray_state);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,51 +3,13 @@
|
|||||||
//! Proxy settings live per network service. A write that found no service wrote nothing, and a
|
//! 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.
|
//! switch to another service leaves the proxy on the old one; both need the write repeated.
|
||||||
|
|
||||||
use crate::{
|
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler};
|
||||||
config::Config,
|
|
||||||
core::{CoreManager, proxy_control},
|
|
||||||
process::scheduled_task::{self, Mailbox, Next, ScheduledTask},
|
|
||||||
};
|
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use std::sync::{Arc, LazyLock};
|
|
||||||
use sysproxy::NetworkServiceMonitor;
|
use sysproxy::NetworkServiceMonitor;
|
||||||
use tokio::time::Instant;
|
|
||||||
|
|
||||||
static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None);
|
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 {
|
pub fn is_armed() -> bool {
|
||||||
MONITOR.lock().is_some()
|
MONITOR.lock().is_some()
|
||||||
}
|
}
|
||||||
@@ -56,7 +18,7 @@ pub fn is_armed() -> bool {
|
|||||||
/// appearing from here on is never missed.
|
/// appearing from here on is never missed.
|
||||||
pub fn start() {
|
pub fn start() {
|
||||||
match NetworkServiceMonitor::start(|| {
|
match NetworkServiceMonitor::start(|| {
|
||||||
REAPPLY_REQUESTS.update(|pending| !std::mem::replace(pending, true));
|
AsyncHandler::spawn(reapply);
|
||||||
}) {
|
}) {
|
||||||
Ok(monitor) => {
|
Ok(monitor) => {
|
||||||
*MONITOR.lock() = Some(monitor);
|
*MONITOR.lock() = Some(monitor);
|
||||||
|
|||||||
@@ -18,20 +18,13 @@ use crate::{
|
|||||||
use anyhow::{Result, ensure};
|
use anyhow::{Result, ensure};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome};
|
use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome};
|
||||||
use clash_verge_task::watch_task;
|
|
||||||
use std::{
|
use std::{
|
||||||
borrow::Borrow,
|
borrow::Borrow,
|
||||||
future::Future,
|
future::Future,
|
||||||
sync::{
|
sync::atomic::{AtomicU64, Ordering},
|
||||||
Arc, LazyLock, Once,
|
|
||||||
atomic::{AtomicU64, Ordering},
|
|
||||||
},
|
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
use tokio::{
|
use tokio::{sync::Mutex, time::timeout};
|
||||||
sync::{Mutex, watch},
|
|
||||||
time::timeout,
|
|
||||||
};
|
|
||||||
|
|
||||||
const CLEAR_ATTEMPTS: u32 = 3;
|
const CLEAR_ATTEMPTS: u32 = 3;
|
||||||
const CLEAR_RETRY_DELAY: Duration = Duration::from_millis(100);
|
const CLEAR_RETRY_DELAY: Duration = Duration::from_millis(100);
|
||||||
@@ -222,40 +215,23 @@ const fn refusal_classification(service_usable: Option<bool>) -> SysproxyFailure
|
|||||||
const LOOPBACK_HOST: &str = "127.0.0.1";
|
const LOOPBACK_HOST: &str = "127.0.0.1";
|
||||||
const MAX_SERVICE_BYPASS_LEN: usize = 8192;
|
const MAX_SERVICE_BYPASS_LEN: usize = 8192;
|
||||||
|
|
||||||
static SERVICE_PROXY_OPERATIONS: LazyLock<ServiceProxyOperations> = LazyLock::new(ServiceProxyOperations::new);
|
static SERVICE_PROXY_OPERATIONS: ServiceProxyOperations = ServiceProxyOperations::new();
|
||||||
|
|
||||||
struct ServiceProxyOperations {
|
struct ServiceProxyOperations {
|
||||||
guard: watch::Sender<Option<Arc<ServiceGuard>>>,
|
|
||||||
guard_generation: AtomicU64,
|
guard_generation: AtomicU64,
|
||||||
operation_lock: Mutex<()>,
|
operation_lock: Mutex<()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ServiceProxyOperations {
|
impl ServiceProxyOperations {
|
||||||
fn new() -> Self {
|
const fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
guard: watch::channel(None).0,
|
|
||||||
guard_generation: AtomicU64::new(0),
|
guard_generation: AtomicU64::new(0),
|
||||||
operation_lock: Mutex::const_new(()),
|
operation_lock: Mutex::const_new(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn invalidate_guard(&self) -> u64 {
|
fn invalidate_guard(&self) -> u64 {
|
||||||
let mut generation = 0;
|
self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1)
|
||||||
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
|
async fn run_service_operation<F, Fut, T>(&self, operation: F) -> T
|
||||||
@@ -630,68 +606,25 @@ pub async fn refresh_guard() -> Result<()> {
|
|||||||
let proxy = current_service_proxy_config(&verge).await?;
|
let proxy = current_service_proxy_config(&verge).await?;
|
||||||
let proof = service::active_service_session()?;
|
let proof = service::active_service_session()?;
|
||||||
let interval = Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30).max(1));
|
let interval = Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30).max(1));
|
||||||
static START_GUARD_MONITOR: Once = Once::new();
|
AsyncHandler::spawn(move || async move {
|
||||||
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;
|
let mut consecutive_failures = 0u32;
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::time::sleep(interval).await;
|
||||||
biased;
|
|
||||||
_ = updates.changed() => return,
|
|
||||||
() = tokio::time::sleep(*interval) => {}
|
|
||||||
}
|
|
||||||
|
|
||||||
match SERVICE_PROXY_OPERATIONS
|
match SERVICE_PROXY_OPERATIONS
|
||||||
.run_guard_request(
|
.run_guard_request(
|
||||||
*generation,
|
generation,
|
||||||
proof,
|
&proof,
|
||||||
proxy,
|
&proxy,
|
||||||
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
|
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
|
||||||
service::active_service_session,
|
service::active_service_session,
|
||||||
|| service::set_system_proxy_by_service_with_session(proxy, proof),
|
|| service::set_system_proxy_by_service_with_session(&proxy, &proof),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(true) => consecutive_failures = 0,
|
Ok(true) => consecutive_failures = 0,
|
||||||
Ok(false) => {
|
Ok(false) => {
|
||||||
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
|
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
|
||||||
return;
|
break;
|
||||||
}
|
}
|
||||||
Err(error) if is_missing_network_service_failure(&error) => {
|
Err(error) if is_missing_network_service_failure(&error) => {
|
||||||
consecutive_failures = 0;
|
consecutive_failures = 0;
|
||||||
@@ -708,12 +641,16 @@ async fn monitor_guard(guard: Arc<ServiceGuard>, mut updates: watch::Receiver<Op
|
|||||||
error
|
error
|
||||||
);
|
);
|
||||||
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
|
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
|
||||||
report_guard_stopped(*generation, &error).await;
|
report_guard_stopped(generation, &error).await;
|
||||||
return;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
// Retire only after the replacement guard starts successfully.
|
||||||
|
notification::retire_guard_failures();
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
const GUARD_FAILURES_BEFORE_STOPPING: u32 = 3;
|
const GUARD_FAILURES_BEFORE_STOPPING: u32 = 3;
|
||||||
|
|||||||
+60
-106
@@ -16,10 +16,7 @@ use crate::{
|
|||||||
runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of},
|
runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of},
|
||||||
tray::Tray,
|
tray::Tray,
|
||||||
},
|
},
|
||||||
process::{
|
process::AsyncHandler,
|
||||||
AsyncHandler,
|
|
||||||
scheduled_task::{self, Mailbox, Next, ScheduledTask},
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
use anyhow::{Context as _, Result, anyhow, bail};
|
use anyhow::{Context as _, Result, anyhow, bail};
|
||||||
use clash_verge_draft::Draft;
|
use clash_verge_draft::Draft;
|
||||||
@@ -29,8 +26,9 @@ use clash_verge_service_ipc::{
|
|||||||
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
|
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
|
||||||
StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||||
};
|
};
|
||||||
use clash_verge_task::watch_task;
|
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
use std::sync::LazyLock;
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
env::current_exe,
|
env::current_exe,
|
||||||
@@ -38,12 +36,11 @@ use std::{
|
|||||||
path::{Path, PathBuf},
|
path::{Path, PathBuf},
|
||||||
process::Command as StdCommand,
|
process::Command as StdCommand,
|
||||||
sync::{
|
sync::{
|
||||||
Arc, LazyLock,
|
Arc,
|
||||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||||
},
|
},
|
||||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||||
};
|
};
|
||||||
use tokio::{sync::watch, time::Instant};
|
|
||||||
|
|
||||||
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
|
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||||
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
|
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
|
||||||
@@ -841,82 +838,61 @@ fn decode_hex(encoded: &str) -> Result<Vec<u8>> {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
static PROVIDER_SYNC_REQUESTS: LazyLock<Arc<Mailbox<Option<Instant>>>> =
|
static PROVIDER_SYNC_QUEUED: AtomicBool = AtomicBool::new(false);
|
||||||
LazyLock::new(|| scheduled_task::spawn(ProviderSchedule::default(), |_| sync_runtime_providers_by_service()));
|
// 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 SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
static SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||||
const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4;
|
const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4;
|
||||||
const CONTENT_COMPARE_CHUNK: usize = 64 * 1024;
|
const CONTENT_COMPARE_CHUNK: usize = 64 * 1024;
|
||||||
|
|
||||||
pub(crate) fn request_runtime_provider_sync(delay: Duration) {
|
pub(crate) fn request_runtime_provider_sync(delay: Duration) {
|
||||||
let due = Instant::now() + delay;
|
if PROVIDER_SYNC_QUEUED.swap(true, Ordering::AcqRel) {
|
||||||
PROVIDER_SYNC_REQUESTS.update(|pending| {
|
return;
|
||||||
if pending.is_some_and(|current| current <= due) {
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
*pending = Some(due);
|
AsyncHandler::spawn(move || async move {
|
||||||
true
|
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
|
||||||
#[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 {
|
match outcome {
|
||||||
return Next::At(due);
|
Ok(ProviderSync { pending: 0, .. }) => Ok(()),
|
||||||
}
|
Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
|
||||||
|
|
||||||
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!(
|
logging!(
|
||||||
info,
|
info,
|
||||||
Type::Service,
|
Type::Service,
|
||||||
"{pending} provider caches are not ready yet; retrying"
|
"{pending} provider caches are not ready yet; retrying"
|
||||||
);
|
);
|
||||||
// A new request during backoff leaves the existing retry deadline and budget intact.
|
Err(RetryError::Retry(()))
|
||||||
self.retry
|
|
||||||
.get_or_insert_with(|| (now + constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY, attempt + 1));
|
|
||||||
}
|
}
|
||||||
Ok(Ok(ProviderSync { pending, .. })) => {
|
Ok(ProviderSync { pending, .. }) => {
|
||||||
logging!(warn, Type::Service, "{pending} provider caches were not synced");
|
logging!(warn, Type::Service, "{pending} provider caches were not synced");
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
Ok(Err(error)) => {
|
Err(error) => {
|
||||||
logging!(
|
logging!(
|
||||||
warn,
|
warn,
|
||||||
Type::Service,
|
Type::Service,
|
||||||
"failed to sync provider caches from the service: {error:#}"
|
"failed to sync provider caches from the service: {error:#}"
|
||||||
);
|
);
|
||||||
}
|
Ok(())
|
||||||
Err(_) => logging!(error, Type::Service, "provider cache sync panicked"),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
@@ -1475,59 +1451,34 @@ const OWNER_MONITOR_INTERVAL: Duration = Duration::from_secs(5);
|
|||||||
/// Mirrors `OwnerWatch`'s tolerance, for the log line only.
|
/// Mirrors `OwnerWatch`'s tolerance, for the log line only.
|
||||||
const SUSTAINED_OWNER_SAMPLES: u8 = 3;
|
const SUSTAINED_OWNER_SAMPLES: u8 = 3;
|
||||||
|
|
||||||
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() {
|
fn start_owner_monitor() {
|
||||||
OWNER_MONITOR.send_modify(|active| {
|
let generation = OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;
|
||||||
*active = Some(OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel).wrapping_add(1));
|
AsyncHandler::spawn(move || async move {
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn monitor_owner(generation: u64, mut updates: watch::Receiver<Option<u64>>) {
|
|
||||||
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
|
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
|
||||||
let mut watch = OwnerWatch::new();
|
let mut watch = OwnerWatch::new();
|
||||||
let mut core_restarts = None;
|
let mut core_restarts = None;
|
||||||
loop {
|
loop {
|
||||||
let (step, status) = tokio::select! {
|
|
||||||
biased;
|
|
||||||
_ = updates.changed() => return,
|
|
||||||
result = async {
|
|
||||||
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
|
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
|
||||||
if owner_monitor_generation() != generation
|
if OWNER_MONITOR_GENERATION.load(Ordering::Acquire) != generation {
|
||||||
|| !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service)
|
logging!(
|
||||||
{
|
debug,
|
||||||
return None;
|
Type::Service,
|
||||||
}
|
"owner monitor superseded (generation {generation})"
|
||||||
Some(probe_owner(generation, &mut watch, &mut core_restarts).await)
|
);
|
||||||
} => match result {
|
break;
|
||||||
Some(observation) => observation,
|
|
||||||
None => return,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
if let OwnerStep::Recover(reason) = step {
|
|
||||||
recover_after_owner_loss(generation, reason, status.as_ref()).await;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn probe_owner(
|
|
||||||
generation: u64,
|
|
||||||
watch: &mut OwnerWatch,
|
|
||||||
core_restarts: &mut Option<u32>,
|
|
||||||
) -> (OwnerStep, Option<ServiceStatusSnapshot>) {
|
|
||||||
let (sample, status) = read_owner_sample().await;
|
let (sample, status) = read_owner_sample().await;
|
||||||
if let Some(status) = &status {
|
if let Some(status) = &status {
|
||||||
log_core_restarts(core_restarts, status);
|
log_core_restarts(&mut core_restarts, status);
|
||||||
}
|
}
|
||||||
let mut step = watch.observe(sample);
|
let mut step = watch.observe(sample);
|
||||||
if matches!(step, OwnerStep::VerifyTransport) {
|
if matches!(step, OwnerStep::VerifyTransport) {
|
||||||
@@ -1542,7 +1493,13 @@ async fn probe_owner(
|
|||||||
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
|
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
|
||||||
step = watch.resolve_transport(owner_endpoint_available);
|
step = watch.resolve_transport(owner_endpoint_available);
|
||||||
}
|
}
|
||||||
(step, status)
|
|
||||||
|
if let OwnerStep::Recover(reason) = step {
|
||||||
|
recover_after_owner_loss(generation, reason, status.as_ref()).await;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Service logs its watchdog restarts where the app cannot read them.
|
/// The Service logs its watchdog restarts where the app cannot read them.
|
||||||
@@ -1626,10 +1583,7 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn cancel_owner_monitors() {
|
fn cancel_owner_monitors() {
|
||||||
OWNER_MONITOR.send_modify(|active| {
|
|
||||||
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel);
|
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel);
|
||||||
*active = None;
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn owner_monitor_generation() -> u64 {
|
pub(crate) fn owner_monitor_generation() -> u64 {
|
||||||
|
|||||||
@@ -7,11 +7,10 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
use clash_verge_logging::{Type, logging, logging_error};
|
||||||
use futures::{FutureExt as _, StreamExt as _};
|
use futures::StreamExt as _;
|
||||||
use parking_lot::{Mutex, RwLock};
|
use parking_lot::{Mutex, RwLock};
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
panic::AssertUnwindSafe,
|
|
||||||
sync::{
|
sync::{
|
||||||
Arc,
|
Arc,
|
||||||
atomic::{AtomicBool, Ordering},
|
atomic::{AtomicBool, Ordering},
|
||||||
@@ -71,11 +70,11 @@ async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Fini
|
|||||||
Started: FnOnce(),
|
Started: FnOnce(),
|
||||||
Update: FnOnce() -> UpdateFuture,
|
Update: FnOnce() -> UpdateFuture,
|
||||||
UpdateFuture: std::future::Future<Output = Output>,
|
UpdateFuture: std::future::Future<Output = Output>,
|
||||||
Finished: FnOnce(std::thread::Result<Output>),
|
Finished: FnOnce(Output),
|
||||||
Completed: FnOnce(),
|
Completed: FnOnce(),
|
||||||
{
|
{
|
||||||
update_started();
|
update_started();
|
||||||
let result = AssertUnwindSafe(async { update_profile().await }).catch_unwind().await;
|
let result = update_profile().await;
|
||||||
update_finished(result);
|
update_finished(result);
|
||||||
update_completed();
|
update_completed();
|
||||||
}
|
}
|
||||||
@@ -475,13 +474,12 @@ impl Timer {
|
|||||||
|| Self::emit_update_event(uid, true),
|
|| Self::emit_update_event(uid, true),
|
||||||
|| feat::update_profile(uid, None, false),
|
|| feat::update_profile(uid, None, false),
|
||||||
|result| match result {
|
|result| match result {
|
||||||
Ok(Ok(_)) => {
|
Ok(_) => {
|
||||||
logging!(debug, Type::Timer, "timer task completed for uid: {}", uid);
|
logging!(debug, Type::Timer, "timer task completed for uid: {}", uid);
|
||||||
}
|
}
|
||||||
Ok(Err(e)) => {
|
Err(e) => {
|
||||||
logging_error!(Type::Timer, "Failed to update profile uid {}: {e:#}", uid);
|
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),
|
|| Self::emit_update_event(uid, false),
|
||||||
)
|
)
|
||||||
@@ -765,8 +763,8 @@ mod tests {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
let calls = Arc::clone(&calls);
|
let calls = Arc::clone(&calls);
|
||||||
move |result| {
|
move |result: anyhow::Result<()>| {
|
||||||
assert!(matches!(result, Ok(Ok(()))));
|
assert!(result.is_ok());
|
||||||
calls.lock().push("terminal-result");
|
calls.lock().push("terminal-result");
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -2,18 +2,28 @@ use crate::core::handle;
|
|||||||
use crate::process::AsyncHandler;
|
use crate::process::AsyncHandler;
|
||||||
use crate::utils::{connections_stream, tray_speed};
|
use crate::utils::{connections_stream, tray_speed};
|
||||||
use crate::{Type, logging};
|
use crate::{Type, logging};
|
||||||
use std::sync::OnceLock;
|
use parking_lot::Mutex;
|
||||||
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::sync::watch;
|
use tauri::async_runtime::JoinHandle;
|
||||||
|
use tauri_plugin_mihomo::models::WsConnectionId;
|
||||||
use connections_stream::{MihomoWsEventStream, StreamConsumeState, TrafficSpeedEvent};
|
|
||||||
|
|
||||||
const TRAY_SPEED_RETRY_DELAY: Duration = Duration::from_secs(1);
|
const TRAY_SPEED_RETRY_DELAY: Duration = Duration::from_secs(1);
|
||||||
const TRAY_SPEED_STALE_TIMEOUT: Duration = Duration::from_secs(5);
|
const TRAY_SPEED_STALE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Clone)]
|
||||||
pub struct TraySpeedController {
|
pub struct TraySpeedController {
|
||||||
enabled: OnceLock<watch::Sender<bool>>,
|
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)),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TraySpeedController {
|
impl TraySpeedController {
|
||||||
@@ -22,102 +32,104 @@ impl TraySpeedController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_task(&self, enable_tray_speed: bool) {
|
pub fn update_task(&self, enable_tray_speed: bool) {
|
||||||
let enabled = self.enabled.get_or_init(|| {
|
if enable_tray_speed {
|
||||||
let (enabled, receiver) = watch::channel(false);
|
self.start_task();
|
||||||
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 {
|
} else {
|
||||||
Self::clear_tray_speed();
|
self.stop_task();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_enabled(enabled: &mut watch::Receiver<bool>) {
|
fn start_task(&self) {
|
||||||
while !handle::Handle::global().is_exiting() {
|
if handle::Handle::global().is_exiting() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if !Self::has_main_tray() {
|
if !Self::has_main_tray() {
|
||||||
logging!(warn, Type::Tray, "托盘不可用,停止托盘速率任务");
|
logging!(warn, Type::Tray, "托盘不可用,跳过启动托盘速率任务");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keep the registered stream outside the cancellable future until it is disconnected.
|
let mut guard = self.speed_task.lock();
|
||||||
let mut stream = None;
|
if guard.as_ref().is_some_and(|task| !task.inner().is_finished()) {
|
||||||
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if *enabled.borrow() {
|
let speed_connection_id = Arc::clone(&self.speed_connection_id);
|
||||||
Self::apply_tray_speed(0, 0);
|
let task = AsyncHandler::spawn(move || async move {
|
||||||
}
|
loop {
|
||||||
if tokio::time::timeout(TRAY_SPEED_RETRY_DELAY, Self::wait_until_disabled(enabled))
|
if handle::Handle::global().is_exiting() {
|
||||||
.await
|
break;
|
||||||
.is_ok()
|
|
||||||
{
|
|
||||||
Self::clear_tray_speed();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn wait_until_disabled(enabled: &mut watch::Receiver<bool>) {
|
if !Self::has_main_tray() {
|
||||||
let _ = enabled.wait_for(|enabled| !enabled).await;
|
logging!(warn, Type::Tray, "托盘已不可用,停止托盘速率任务");
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn read_speed(stream: &mut Option<MihomoWsEventStream<TrafficSpeedEvent>>) {
|
let stream_connect_result = connections_stream::connect_traffic_stream().await;
|
||||||
let speed_stream = match connections_stream::connect_traffic_stream().await {
|
let mut speed_stream = match stream_connect_result {
|
||||||
Ok(connected) => stream.insert(connected),
|
Ok(stream) => stream,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
logging!(debug, Type::Tray, "托盘速率流连接失败,稍后重试: {err}");
|
logging!(debug, Type::Tray, "托盘速率流连接失败,稍后重试: {err}");
|
||||||
return;
|
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 {
|
loop {
|
||||||
match speed_stream
|
let next_state = speed_stream
|
||||||
.next_event(TRAY_SPEED_STALE_TIMEOUT, || handle::Handle::global().is_exiting())
|
.next_event(TRAY_SPEED_STALE_TIMEOUT, || handle::Handle::global().is_exiting())
|
||||||
.await
|
.await;
|
||||||
{
|
|
||||||
StreamConsumeState::Event(event) => Self::apply_tray_speed(event.up, event.down),
|
match next_state {
|
||||||
StreamConsumeState::Stale => {
|
connections_stream::StreamConsumeState::Event(speed_event) => {
|
||||||
|
Self::apply_tray_speed(speed_event.up, speed_event.down);
|
||||||
|
}
|
||||||
|
connections_stream::StreamConsumeState::Stale => {
|
||||||
logging!(debug, Type::Tray, "托盘速率流长时间未收到有效数据,触发重连");
|
logging!(debug, Type::Tray, "托盘速率流长时间未收到有效数据,触发重连");
|
||||||
Self::apply_tray_speed(0, 0);
|
Self::apply_tray_speed(0, 0);
|
||||||
return;
|
break;
|
||||||
}
|
}
|
||||||
StreamConsumeState::Closed | StreamConsumeState::ExitRequested => return,
|
connections_stream::StreamConsumeState::Closed
|
||||||
|
| connections_stream::StreamConsumeState::ExitRequested => {
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn clear_tray_speed() {
|
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.
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stop_task(&self) {
|
||||||
|
let task = self.speed_task.lock().take();
|
||||||
|
let speed_connection_id = Arc::clone(&self.speed_connection_id);
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
Self::disconnect_speed_connection(&speed_connection_id).await;
|
||||||
|
});
|
||||||
|
|
||||||
let app_handle = handle::Handle::app_handle();
|
let app_handle = handle::Handle::app_handle();
|
||||||
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
|
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
|
||||||
let result = tray.with_inner_tray_icon(|inner| {
|
let result = tray.with_inner_tray_icon(|inner| {
|
||||||
@@ -135,6 +147,23 @@ impl TraySpeedController {
|
|||||||
handle::Handle::app_handle().tray_by_id(super::TRAY_ID).is_some()
|
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) {
|
fn apply_tray_speed(up: u64, down: u64) {
|
||||||
let app_handle = handle::Handle::app_handle();
|
let app_handle = handle::Handle::app_handle();
|
||||||
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
|
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IClashTemp, IProfiles, IVerge},
|
config::{Config, IClashTemp, IProfiles, IVerge},
|
||||||
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
|
core::{CoreManager, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
|
||||||
process::AsyncHandler,
|
process::AsyncHandler,
|
||||||
utils::{
|
utils::{
|
||||||
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
|
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
|
||||||
@@ -58,7 +58,6 @@ async fn finalize_restored_verge_config(
|
|||||||
*d = restored.clone();
|
*d = restored.clone();
|
||||||
});
|
});
|
||||||
verge_draft.apply();
|
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.
|
// Turn it off here; a failing core side effect below would otherwise skip this step.
|
||||||
if !restored.enable_system_proxy.unwrap_or_default() {
|
if !restored.enable_system_proxy.unwrap_or_default() {
|
||||||
|
|||||||
@@ -21,38 +21,24 @@ pub(super) enum Effect {
|
|||||||
|
|
||||||
pub(super) type Effects = BTreeSet<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 {
|
macro_rules! select_field {
|
||||||
($effects:ident, $field:ident, NoEffect) => { let _ = $field; };
|
($effects:ident, $field:ident, NoEffect) => { let _ = $field; };
|
||||||
($effects:ident, $field:ident, [$($effect:ident),*]) => {
|
($effects:ident, $field:ident, [$($effect:ident),*]) => {
|
||||||
if $field.is_some() { $effects.before_commit.extend([$(Effect::$effect),*]); }
|
if $field.is_some() { $effects.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) => {
|
($effects:ident, $field:ident, Tun) => {
|
||||||
select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]);
|
select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]);
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
if *$field == Some(true) { $effects.before_commit.insert(Effect::RestartCore); }
|
if *$field == Some(true) { $effects.insert(Effect::RestartCore); }
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
macro_rules! verge_registry {
|
macro_rules! verge_registry {
|
||||||
($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => {
|
($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => {
|
||||||
pub(super) fn verge_effects(patch: &IVerge) -> EffectPlan {
|
pub(super) fn verge_effects(patch: &IVerge) -> Effects {
|
||||||
// No rest pattern: even fields omitted by serde must be classified at compile time.
|
// No rest pattern: even fields omitted by serde must be classified at compile time.
|
||||||
let IVerge { $( $(#[$cfg])* $field, )* } = patch;
|
let IVerge { $( $(#[$cfg])* $field, )* } = patch;
|
||||||
let mut effects = EffectPlan::default();
|
let mut effects = Effects::new();
|
||||||
$( $(#[$cfg])* { select_field!(effects, $field, $rule); } )*
|
$( $(#[$cfg])* { select_field!(effects, $field, $rule); } )*
|
||||||
effects
|
effects
|
||||||
}
|
}
|
||||||
@@ -114,9 +100,9 @@ verge_registry! {
|
|||||||
proxy_layout_column => NoEffect;
|
proxy_layout_column => NoEffect;
|
||||||
test_list => NoEffect;
|
test_list => NoEffect;
|
||||||
auto_log_clean => NoEffect;
|
auto_log_clean => NoEffect;
|
||||||
enable_auto_backup_schedule => (AfterCommit BackupSettings);
|
enable_auto_backup_schedule => NoEffect;
|
||||||
auto_backup_interval_hours => (AfterCommit BackupSettings);
|
auto_backup_interval_hours => NoEffect;
|
||||||
auto_backup_on_change => (AfterCommit BackupSettings);
|
auto_backup_on_change => NoEffect;
|
||||||
#[cfg(not(target_os = "windows"))]
|
#[cfg(not(target_os = "windows"))]
|
||||||
verge_redir_port => [RestartCore];
|
verge_redir_port => [RestartCore];
|
||||||
#[cfg(not(target_os = "windows"))]
|
#[cfg(not(target_os = "windows"))]
|
||||||
@@ -144,7 +130,7 @@ verge_registry! {
|
|||||||
enable_external_controller => [RestartCore];
|
enable_external_controller => [RestartCore];
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> EffectPlan {
|
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
let mut effects = Effects::new();
|
let mut effects = Effects::new();
|
||||||
for key in patch.keys() {
|
for key in patch.keys() {
|
||||||
@@ -171,10 +157,7 @@ pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> EffectPlan {
|
|||||||
if patch.is_empty() {
|
if patch.is_empty() {
|
||||||
effects.insert(Effect::ClashConfig);
|
effects.insert(Effect::ClashConfig);
|
||||||
}
|
}
|
||||||
EffectPlan {
|
effects
|
||||||
before_commit: effects,
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -189,7 +172,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn representative_verge_patches_map_to_frozen_effects() {
|
fn representative_verge_patches_map_to_frozen_effects() {
|
||||||
assert_eq!(verge_effects(&IVerge::default()).before_commit, Effects::new());
|
assert_eq!(verge_effects(&IVerge::default()), Effects::new());
|
||||||
|
|
||||||
let cases: [(IVerge, &[Effect]); 9] = [
|
let cases: [(IVerge, &[Effect]); 9] = [
|
||||||
(
|
(
|
||||||
@@ -233,7 +216,7 @@ mod tests {
|
|||||||
];
|
];
|
||||||
for (patch, expected) in cases {
|
for (patch, expected) in cases {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
verge_effects(&patch).before_commit,
|
verge_effects(&patch),
|
||||||
expected.iter().copied().collect::<Effects>(),
|
expected.iter().copied().collect::<Effects>(),
|
||||||
"patch mapping drifted for {expected:?}"
|
"patch mapping drifted for {expected:?}"
|
||||||
);
|
);
|
||||||
@@ -242,7 +225,7 @@ mod tests {
|
|||||||
let tun = verge_patch(|p| p.enable_tun_mode = Some(true));
|
let tun = verge_patch(|p| p.enable_tun_mode = Some(true));
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
verge_effects(&tun).before_commit,
|
verge_effects(&tun),
|
||||||
[
|
[
|
||||||
Effect::RestartCore,
|
Effect::RestartCore,
|
||||||
Effect::ClashConfig,
|
Effect::ClashConfig,
|
||||||
@@ -255,7 +238,7 @@ mod tests {
|
|||||||
);
|
);
|
||||||
#[cfg(not(target_os = "linux"))]
|
#[cfg(not(target_os = "linux"))]
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
verge_effects(&tun).before_commit,
|
verge_effects(&tun),
|
||||||
[
|
[
|
||||||
Effect::ClashConfig,
|
Effect::ClashConfig,
|
||||||
Effect::TrayIcon,
|
Effect::TrayIcon,
|
||||||
@@ -298,7 +281,7 @@ mod tests {
|
|||||||
];
|
];
|
||||||
for (patch, expected) in cases {
|
for (patch, expected) in cases {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
clash_effects(&patch).before_commit,
|
clash_effects(&patch),
|
||||||
expected.iter().copied().collect::<Effects>(),
|
expected.iter().copied().collect::<Effects>(),
|
||||||
"clash mapping drifted for {expected:?}"
|
"clash mapping drifted for {expected:?}"
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use super::effects::{AfterCommit, Effect, EffectPlan};
|
use super::effects::{Effect, Effects};
|
||||||
use crate::core::notify::{Refresh, announce};
|
use crate::core::notify::{Refresh, announce};
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
Config, IVerge,
|
Config, IVerge,
|
||||||
snapshot::{capture_config_files, restore_files},
|
snapshot::{capture_config_files, restore_files},
|
||||||
},
|
},
|
||||||
core::auto_backup,
|
core::auto_backup::AutoBackupManager,
|
||||||
core::{
|
core::{
|
||||||
CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control,
|
CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control,
|
||||||
tray,
|
tray,
|
||||||
@@ -108,7 +108,7 @@ async fn ensure_effect(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: EffectPlan) -> Result<()> {
|
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
|
||||||
let manager = CoreManager::global();
|
let manager = CoreManager::global();
|
||||||
let update = manager.claim_config_update(config_write)?;
|
let update = manager.claim_config_update(config_write)?;
|
||||||
let clash = Config::clash().await;
|
let clash = Config::clash().await;
|
||||||
@@ -130,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)),
|
Patch::Clash(patch) => clash.edit_draft(|draft| draft.patch_config(patch)),
|
||||||
}
|
}
|
||||||
let result: Result<()> = async {
|
let result: Result<()> = async {
|
||||||
for effect in effects.before_commit.iter().copied() {
|
for effect in effects.iter().copied() {
|
||||||
let result = Box::pin(ensure_effect(effect, verge_patch, manager, &update)).await;
|
let result = Box::pin(ensure_effect(effect, verge_patch, manager, &update)).await;
|
||||||
if matches!(patch, Patch::Clash(_)) && matches!(effect, Effect::TrayMenu | Effect::TrayIcon) {
|
if matches!(patch, Patch::Clash(_)) && matches!(effect, Effect::TrayMenu | Effect::TrayIcon) {
|
||||||
// Tray failures must not reject an applied Clash mode change.
|
// Tray failures must not reject an applied Clash mode change.
|
||||||
@@ -166,14 +166,10 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
|
|||||||
if patch.auto_check_update == Some(false) {
|
if patch.auto_check_update == Some(false) {
|
||||||
SilentUpdater::global().discard_pending().await;
|
SilentUpdater::global().discard_pending().await;
|
||||||
}
|
}
|
||||||
if effects.before_commit.contains(&Effect::ClashConfig) {
|
if effects.contains(&Effect::ClashConfig) {
|
||||||
announce(Refresh::Clash);
|
announce(Refresh::Clash);
|
||||||
}
|
}
|
||||||
for effect in effects.after_commit {
|
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
|
||||||
match effect {
|
|
||||||
AfterCommit::BackupSettings => auto_backup::publish_settings(&verge.data_arc()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
announce(Refresh::Verge);
|
announce(Refresh::Verge);
|
||||||
}
|
}
|
||||||
Patch::Clash(_) => announce(Refresh::Clash),
|
Patch::Clash(_) => announce(Refresh::Clash),
|
||||||
|
|||||||
@@ -304,7 +304,17 @@ async fn clean_session_ending_best_effort() -> CleanupResult {
|
|||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
pub async fn hide() {
|
pub async fn hide() {
|
||||||
crate::core::lightweight::add_light_weight_timer().await;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(window) = WindowManager::get_main_window()
|
if let Some(window) = WindowManager::get_main_window()
|
||||||
&& window.is_visible().unwrap_or(false)
|
&& window.is_visible().unwrap_or(false)
|
||||||
|
|||||||
@@ -1,4 +1,2 @@
|
|||||||
mod async_handler;
|
mod async_handler;
|
||||||
pub use async_handler::AsyncHandler;
|
pub use async_handler::AsyncHandler;
|
||||||
|
|
||||||
pub(crate) mod scheduled_task;
|
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
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
|
|
||||||
}
|
|
||||||
@@ -12,7 +12,7 @@ use crate::{
|
|||||||
service::{SERVICE_MANAGER, ServiceManager},
|
service::{SERVICE_MANAGER, ServiceManager},
|
||||||
tray::Tray,
|
tray::Tray,
|
||||||
},
|
},
|
||||||
core::{auto_backup, lightweight::auto_lightweight_boot},
|
core::{auto_backup::AutoBackupManager, lightweight::auto_lightweight_boot},
|
||||||
feat,
|
feat,
|
||||||
process::AsyncHandler,
|
process::AsyncHandler,
|
||||||
utils::{init, server, window_manager::WindowManager},
|
utils::{init, server, window_manager::WindowManager},
|
||||||
@@ -150,7 +150,7 @@ async fn init_auto_lightweight_boot() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn init_auto_backup() {
|
async fn init_auto_backup() {
|
||||||
auto_backup::init().await;
|
logging_error!(Type::Setup, AutoBackupManager::global().init().await);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn init_silent_updater() {
|
fn init_silent_updater() {
|
||||||
|
|||||||
Reference in New Issue
Block a user