refactor(backend): give background operations single task owners

This commit is contained in:
Tunglies
2026-11-28 20:53:02 +08:00
parent 50ddb84f19
commit 5cc9531a15
17 changed files with 1045 additions and 559 deletions
+1
View File
@@ -45,6 +45,7 @@
- 修复规则模式下 Muse AI 解锁检测显示错误的出口地区
- 修复使用系统代理或本地代理认证时首页 IP 信息显示直连地址或报错
- 修复打开「链式代理」时自动对全部节点发起延迟测试
- 修复修改无关设置或切换「关键变更时自动备份」后定时备份重新计时
**🖥️ Windows**
+2 -2
View File
@@ -3,7 +3,7 @@ use crate::{
cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, PrfItem},
core::auto_backup::{AutoBackupManager, AutoBackupTrigger},
core::auto_backup::{self, AutoBackupTrigger},
core::{
CoreManager, handle,
validate::{CoreConfigValidator, ValidationOutcome},
@@ -86,7 +86,7 @@ pub async fn save_profile_file(
if changes_applied.is_valid()
&& let Some(trigger) = backup_trigger
{
AutoBackupManager::trigger_backup(trigger);
auto_backup::trigger_backup(trigger);
}
Ok(changes_applied)
+274 -151
View File
@@ -1,29 +1,22 @@
use crate::{
config::{Config, IVerge},
feat::create_local_backup_with_namer,
process::AsyncHandler,
process::scheduled_task::{self, Mailbox, Next, ScheduledTask},
utils::dirs::local_backup_dir,
};
use anyhow::Result;
use chrono::Local;
use clash_verge_logging::{Type, logging};
use std::{
path::PathBuf,
sync::{
OnceLock,
atomic::{AtomicBool, AtomicI64, Ordering},
},
sync::{Arc, LazyLock},
time::{Duration, UNIX_EPOCH},
};
use tokio::{
fs,
sync::{Mutex, watch},
};
use tokio::{fs, time::Instant};
const DEFAULT_INTERVAL_HOURS: u64 = 24;
const MIN_INTERVAL_HOURS: u64 = 1;
const MAX_INTERVAL_HOURS: u64 = 168;
const MIN_BACKUP_INTERVAL_SECS: i64 = 60;
const MIN_BACKUP_INTERVAL: Duration = Duration::from_secs(60);
const AUTO_BACKUP_KEEP: usize = 20;
const AUTO_MARKER: &str = "-auto-";
@@ -42,13 +35,9 @@ impl AutoBackupTrigger {
Self::GlobalScript => "script",
}
}
const fn is_schedule(self) -> bool {
matches!(self, Self::Scheduled)
}
}
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct AutoBackupSettings {
schedule_enabled: bool,
interval_hours: u64,
@@ -56,6 +45,11 @@ struct AutoBackupSettings {
}
impl AutoBackupSettings {
fn interval(self) -> Option<Duration> {
self.schedule_enabled
.then(|| Duration::from_secs(self.interval_hours * 3600))
}
fn from_verge(verge: &IVerge) -> Self {
let interval = verge
.auto_backup_interval_hours
@@ -80,155 +74,139 @@ impl Default for AutoBackupSettings {
}
}
pub struct AutoBackupManager {
settings_tx: watch::Sender<AutoBackupSettings>,
// The watch channel is the single settings store; no duplicate copies.
settings_rx: watch::Receiver<AutoBackupSettings>,
runner_started: AtomicBool,
exec_lock: Mutex<()>,
last_backup: AtomicI64,
#[derive(Default)]
struct BackupInput {
settings: Option<AutoBackupSettings>,
restart_schedule: bool,
clear_pending_edit: bool,
edit_before_settings: Option<AutoBackupTrigger>,
edit: Option<AutoBackupTrigger>,
}
impl AutoBackupManager {
pub fn global() -> &'static Self {
static INSTANCE: OnceLock<AutoBackupManager> = OnceLock::new();
INSTANCE.get_or_init(|| {
let (settings_tx, settings_rx) = watch::channel(AutoBackupSettings::default());
Self {
settings_tx,
settings_rx,
runner_started: AtomicBool::new(false),
exec_lock: Mutex::new(()),
last_backup: AtomicI64::new(0),
impl BackupInput {
fn update_settings(&mut self, settings: AutoBackupSettings) -> bool {
if self.settings == Some(settings) {
return false;
}
// A pending off/on or interval round trip still restarts the countdown.
self.restart_schedule |= self
.settings
.is_some_and(|previous| previous.interval() != settings.interval());
self.settings = Some(settings);
if !settings.change_enabled {
self.clear_pending_edit = true;
self.edit = None;
self.edit_before_settings = None;
}
true
}
const fn request_edit(&mut self, trigger: AutoBackupTrigger) -> bool {
let pending = match self.settings {
Some(settings) if settings.change_enabled => &mut self.edit,
Some(_) => return false,
None => &mut self.edit_before_settings,
};
if pending.is_some() {
return false;
}
*pending = Some(trigger);
true
}
}
static BACKUP_REQUESTS: LazyLock<Arc<Mailbox<BackupInput>>> =
LazyLock::new(|| scheduled_task::spawn(BackupSchedule::default(), execute_backup));
pub(crate) async fn init() {
let _write = Config::lock_config_write().await;
publish_settings(&Config::verge().await.data_arc());
}
pub(crate) fn publish_settings(verge: &IVerge) {
let settings = AutoBackupSettings::from_verge(verge);
BACKUP_REQUESTS.update(|pending| pending.update_settings(settings));
}
pub(crate) fn trigger_backup(trigger: AutoBackupTrigger) {
BACKUP_REQUESTS.update(|pending| pending.request_edit(trigger));
}
#[derive(Default)]
struct BackupSchedule {
settings: AutoBackupSettings,
due: Option<Instant>,
edit: Option<AutoBackupTrigger>,
last_backup: Option<Instant>,
}
impl ScheduledTask for BackupSchedule {
type Input = BackupInput;
type Work = AutoBackupTrigger;
type Output = Result<Instant>;
fn on_input(&mut self, input: BackupInput, now: Instant) {
if input.clear_pending_edit {
self.edit = None;
}
let previous_edit = if self.settings.change_enabled {
input.edit_before_settings
} else {
None
};
if let Some(settings) = input.settings {
if input.restart_schedule || self.settings.interval() != settings.interval() {
self.due = settings.interval().map(|interval| now + interval);
}
})
self.settings = settings;
}
if self.settings.change_enabled {
self.edit = self.edit.or(previous_edit).or(input.edit);
} else {
self.edit = None;
}
}
pub async fn init(&self) -> Result<()> {
let settings = Self::load_settings().await;
let _ = self.settings_tx.send_replace(settings);
self.maybe_start_runner(settings);
Ok(())
}
pub async fn refresh_settings(&self) -> Result<()> {
let settings = Self::load_settings().await;
let _ = self.settings_tx.send_replace(settings);
self.maybe_start_runner(settings);
Ok(())
}
pub fn trigger_backup(trigger: AutoBackupTrigger) {
AsyncHandler::spawn(move || async move {
if let Err(err) = Self::global().execute_trigger(trigger).await {
logging!(
warn,
Type::Backup,
"Auto backup execution failed ({:?}): {err:#?}",
trigger
);
fn next(&mut self, now: Instant) -> Next<AutoBackupTrigger> {
let throttled = self.last_backup.is_some_and(|last| now - last < MIN_BACKUP_INTERVAL);
if self.due.is_some_and(|due| due <= now) {
self.due = None;
if !throttled {
return Next::Run(AutoBackupTrigger::Scheduled);
}
});
self.due = self.settings.interval().map(|interval| now + interval);
}
if let Some(edit) = self.edit.take()
&& !throttled
{
return Next::Run(edit);
}
self.due.map_or(Next::Idle, Next::At)
}
fn maybe_start_runner(&self, settings: AutoBackupSettings) {
if settings.schedule_enabled {
self.ensure_runner();
fn finished(&mut self, trigger: AutoBackupTrigger, result: std::thread::Result<Self::Output>, now: Instant) {
if trigger == AutoBackupTrigger::Scheduled {
self.due = self.settings.interval().map(|interval| now + interval);
}
match result {
Ok(Ok(created_at)) => self.last_backup = Some(created_at),
Ok(Err(err)) => logging!(warn, Type::Backup, "Auto backup failed ({trigger:?}): {err:#}"),
Err(_) => logging!(error, Type::Backup, "Auto backup panicked ({trigger:?})"),
}
}
}
fn ensure_runner(&self) {
if self.runner_started.swap(true, Ordering::SeqCst) {
return;
}
async fn execute_backup(trigger: AutoBackupTrigger) -> Result<Instant> {
let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
let created_at = Instant::now();
let mut rx = self.settings_tx.subscribe();
AsyncHandler::spawn(move || async move {
Self::run_scheduler(&mut rx).await;
});
if let Err(err) = cleanup_auto_backups().await {
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
}
async fn run_scheduler(rx: &mut watch::Receiver<AutoBackupSettings>) {
let mut current = *rx.borrow();
loop {
if !current.schedule_enabled {
if rx.changed().await.is_err() {
break;
}
current = *rx.borrow();
continue;
}
let duration = Duration::from_secs(current.interval_hours.saturating_mul(3600));
let sleeper = tokio::time::sleep(duration);
tokio::pin!(sleeper);
tokio::select! {
_ = &mut sleeper => {
if let Err(err) = Self::global()
.execute_trigger(AutoBackupTrigger::Scheduled)
.await
{
logging!(
warn,
Type::Backup,
"Scheduled auto backup failed: {err:#?}"
);
}
}
changed = rx.changed() => {
if changed.is_err() {
break;
}
current = *rx.borrow();
}
}
}
}
async fn execute_trigger(&self, trigger: AutoBackupTrigger) -> Result<()> {
let snapshot = *self.settings_rx.borrow();
if trigger.is_schedule() && !snapshot.schedule_enabled {
return Ok(());
}
if !trigger.is_schedule() && !snapshot.change_enabled {
return Ok(());
}
if !self.should_run_now() {
return Ok(());
}
let _guard = self.exec_lock.lock().await;
if !self.should_run_now() {
return Ok(());
}
let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
self.last_backup.store(Local::now().timestamp(), Ordering::Release);
if let Err(err) = cleanup_auto_backups().await {
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
}
logging!(info, Type::Backup, "Auto backup created ({:?}): {}", trigger, file_name);
Ok(())
}
fn should_run_now(&self) -> bool {
let last = self.last_backup.load(Ordering::Acquire);
if last == 0 {
return true;
}
let now = Local::now().timestamp();
now.saturating_sub(last) >= MIN_BACKUP_INTERVAL_SECS
}
async fn load_settings() -> AutoBackupSettings {
let verge = Config::verge().await;
AutoBackupSettings::from_verge(&verge.latest_arc())
}
logging!(info, Type::Backup, "Auto backup created ({trigger:?}): {file_name}");
Ok(created_at)
}
fn append_auto_suffix(file_name: &str, slug: &str) -> String {
@@ -303,3 +281,148 @@ async fn cleanup_auto_backups() -> Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn edit_settings_leave_the_scheduled_deadline_in_place() {
let mut schedule = BackupSchedule::default();
let now = Instant::now();
let settings = AutoBackupSettings {
schedule_enabled: true,
interval_hours: 1,
change_enabled: true,
};
schedule.on_input(
BackupInput {
settings: Some(settings),
..Default::default()
},
now,
);
let due = now + Duration::from_secs(3600);
let before_due = due - Duration::from_secs(60);
schedule.on_input(
BackupInput {
settings: Some(settings),
..Default::default()
},
before_due,
);
schedule.on_input(
BackupInput {
settings: Some(AutoBackupSettings {
change_enabled: false,
..settings
}),
edit: Some(AutoBackupTrigger::GlobalMerge),
..Default::default()
},
before_due,
);
assert!(matches!(schedule.next(before_due), Next::At(at) if at == due));
assert!(matches!(schedule.next(due), Next::Run(AutoBackupTrigger::Scheduled)));
}
#[test]
fn coalescing_keeps_schedule_resets_and_drops_edits_while_disabled() {
let mut schedule = BackupSchedule::default();
let now = Instant::now();
let enabled = AutoBackupSettings {
schedule_enabled: true,
interval_hours: 1,
change_enabled: true,
};
let disabled = AutoBackupSettings {
schedule_enabled: false,
change_enabled: false,
..enabled
};
let mut input = BackupInput::default();
input.update_settings(enabled);
schedule.on_input(input, now);
let mut pending = BackupInput::default();
pending.request_edit(AutoBackupTrigger::GlobalMerge);
pending.update_settings(disabled);
assert!(!pending.request_edit(AutoBackupTrigger::GlobalScript));
pending.update_settings(enabled);
let restarted = now + Duration::from_secs(3540);
schedule.on_input(pending, restarted);
let due = restarted + Duration::from_secs(3600);
assert!(matches!(schedule.next(restarted), Next::At(at) if at == due));
let mut pending = BackupInput::default();
pending.update_settings(disabled);
schedule.on_input(pending, restarted);
let mut pending = BackupInput::default();
pending.request_edit(AutoBackupTrigger::GlobalScript);
pending.update_settings(enabled);
pending.request_edit(AutoBackupTrigger::GlobalMerge);
schedule.on_input(pending, restarted);
assert!(matches!(
schedule.next(restarted),
Next::Run(AutoBackupTrigger::GlobalMerge)
));
assert!(matches!(schedule.next(restarted), Next::At(at) if at == due));
}
#[test]
fn disabling_edit_backups_clears_waiting_edits_after_a_scheduled_job() {
let mut schedule = BackupSchedule::default();
let now = Instant::now();
let enabled = AutoBackupSettings {
schedule_enabled: true,
interval_hours: 1,
change_enabled: true,
};
let mut input = BackupInput::default();
input.update_settings(enabled);
schedule.on_input(input, now);
let due = now + Duration::from_secs(3600);
let mut input = BackupInput::default();
input.request_edit(AutoBackupTrigger::GlobalMerge);
schedule.on_input(input, due);
assert!(matches!(schedule.next(due), Next::Run(AutoBackupTrigger::Scheduled)));
schedule.finished(
AutoBackupTrigger::Scheduled,
Ok(Err(anyhow::anyhow!("archive failed"))),
due,
);
let mut input = BackupInput::default();
input.update_settings(AutoBackupSettings {
change_enabled: false,
..enabled
});
input.update_settings(enabled);
schedule.on_input(input, due);
assert!(matches!(schedule.next(due), Next::At(at) if at > due));
}
#[test]
fn edit_backups_run_without_a_schedule_and_retry_after_failure() {
let mut schedule = BackupSchedule::default();
let now = Instant::now();
let edit = AutoBackupTrigger::GlobalScript;
let input = || BackupInput {
edit: Some(edit),
..Default::default()
};
schedule.on_input(input(), now);
assert!(matches!(schedule.next(now), Next::Run(AutoBackupTrigger::GlobalScript)));
schedule.finished(edit, Ok(Err(anyhow::anyhow!("archive failed"))), now);
schedule.on_input(input(), now);
assert!(matches!(schedule.next(now), Next::Run(AutoBackupTrigger::GlobalScript)));
schedule.finished(edit, Ok(Ok(now)), now);
schedule.on_input(input(), now);
assert!(matches!(schedule.next(now), Next::Idle));
}
}
+120 -96
View File
@@ -9,9 +9,10 @@ use clash_verge_logging::{Type, logging};
use crate::utils::window_manager::WindowManager;
use anyhow::Result;
use parking_lot::Mutex;
use std::sync::atomic::{AtomicU8, AtomicU32, Ordering};
use std::sync::LazyLock;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
use tauri::Listener as _;
use tokio::sync::oneshot;
use tokio::sync::mpsc;
use tokio::time::{Duration, sleep};
#[repr(u8)]
@@ -41,27 +42,24 @@ impl LightweightState {
static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8);
struct WindowListener {
handler_id: AtomicU32,
handler_id: Option<tauri::EventId>,
event: &'static str,
label: &'static str,
}
impl WindowListener {
fn setup(&self, on_event: impl Fn() + Send + 'static) {
fn setup(&mut self, on_event: impl Fn() + Send + 'static) {
if let Some(window) = WindowManager::get_main_window() {
let previous_handler_id = self.handler_id.swap(0, Ordering::AcqRel);
if previous_handler_id != 0 {
window.unlisten(previous_handler_id);
if let Some(id) = self.handler_id.take() {
window.unlisten(id);
logging!(debug, Type::Lightweight, "覆盖旧的{}监听", self.label);
}
let handler_id = window.listen(self.event, move |_event| on_event());
self.handler_id.store(handler_id, Ordering::Release);
self.handler_id = Some(window.listen(self.event, move |_event| on_event()));
}
}
fn cancel(&self) {
let id = self.handler_id.swap(0, Ordering::AcqRel);
if id != 0 {
fn cancel(&mut self) {
if let Some(id) = self.handler_id.take() {
if let Some(window) = WindowManager::get_main_window() {
window.unlisten(id);
}
@@ -70,19 +68,36 @@ impl WindowListener {
}
}
static WINDOW_CLOSE_LISTENER: WindowListener = WindowListener {
handler_id: AtomicU32::new(0),
event: "tauri://close-requested",
label: "窗口关闭",
};
struct WindowListeners {
close: WindowListener,
focus: WindowListener,
}
static WEBVIEW_FOCUS_LISTENER: WindowListener = WindowListener {
handler_id: AtomicU32::new(0),
event: "tauri://focus",
label: "窗口焦点",
};
static WINDOW_LISTENERS: Mutex<WindowListeners> = Mutex::new(WindowListeners {
close: WindowListener {
handler_id: None,
event: "tauri://close-requested",
label: "窗口关闭",
},
focus: WindowListener {
handler_id: None,
event: "tauri://focus",
label: "窗口焦点",
},
});
static CANCEL_TX: Mutex<Option<oneshot::Sender<()>>> = Mutex::new(None);
enum TimerCommand {
Arm(u64),
Disarm,
}
static TIMER_GENERATION: AtomicU64 = AtomicU64::new(0);
static TIMER_COMMANDS: LazyLock<mpsc::UnboundedSender<TimerCommand>> = LazyLock::new(|| {
let (sender, receiver) = mpsc::unbounded_channel();
AsyncHandler::spawn(move || run_light_weight_timer(receiver));
sender
});
#[inline]
fn get_state() -> LightweightState {
@@ -118,11 +133,12 @@ async fn refresh_lightweight_tray_state() {
}
pub async fn auto_lightweight_boot() -> Result<()> {
let generation = TIMER_GENERATION.load(Ordering::Acquire);
let verge_config = Config::verge().await;
let is_enable_auto = verge_config.data_arc().enable_auto_light_weight_mode.unwrap_or(false);
let is_silent_start = verge_config.data_arc().enable_silent_start.unwrap_or(false);
if is_enable_auto {
enable_auto_light_weight_mode().await;
if is_enable_auto && verge_config.latest_arc().enable_auto_light_weight_mode.unwrap_or(false) {
enable_auto_light_weight_mode_at(generation).await;
}
if is_silent_start {
entry_lightweight_mode().await;
@@ -131,32 +147,43 @@ pub async fn auto_lightweight_boot() -> Result<()> {
}
pub async fn enable_auto_light_weight_mode() {
enable_auto_light_weight_mode_at(TIMER_GENERATION.load(Ordering::Acquire)).await;
}
async fn enable_auto_light_weight_mode_at(generation: u64) {
if let Err(e) = Timer::global().init().await {
logging!(error, Type::Lightweight, "Failed to initialize timer: {e}");
return;
}
logging!(info, Type::Lightweight, "开启自动轻量模式");
setup_window_close_listener();
setup_webview_focus_listener();
setup_auto_light_weight_listeners(generation);
}
pub fn disable_auto_light_weight_mode() {
logging!(info, Type::Lightweight, "关闭自动轻量模式");
TIMER_GENERATION.fetch_add(1, Ordering::AcqRel);
cancel_light_weight_timer();
cancel_window_close_listener();
cancel_webview_focus_listener();
let mut listeners = WINDOW_LISTENERS.lock();
listeners.close.cancel();
listeners.focus.cancel();
}
pub async fn entry_lightweight_mode() -> bool {
let entered = begin_lightweight_mode();
if entered {
cancel_light_weight_timer();
}
refresh_lightweight_tray_state().await;
entered
}
fn begin_lightweight_mode() -> bool {
if !try_transition(LightweightState::Normal, LightweightState::In) {
logging!(debug, Type::Lightweight, "无需进入轻量模式,跳过调用");
refresh_lightweight_tray_state().await;
return false;
}
record_state_and_log(LightweightState::In);
WindowManager::destroy_main_window();
cancel_light_weight_timer();
refresh_lightweight_tray_state().await;
true
}
@@ -172,14 +199,9 @@ pub async fn exit_lightweight_mode() -> bool {
}
record_state_and_log(LightweightState::Exiting);
WindowManager::show_main_window().await;
let enable_auto_light_weight_mode = Config::verge()
.await
.data_arc()
.enable_auto_light_weight_mode
.unwrap_or(false);
if enable_auto_light_weight_mode {
setup_window_close_listener();
setup_webview_focus_listener();
let generation = TIMER_GENERATION.load(Ordering::Acquire);
if auto_light_weight_is_enabled().await {
setup_auto_light_weight_listeners(generation);
}
cancel_light_weight_timer();
record_state_and_log(LightweightState::Normal);
@@ -189,78 +211,80 @@ pub async fn exit_lightweight_mode() -> bool {
#[cfg(target_os = "macos")]
pub async fn add_light_weight_timer() {
setup_light_weight_timer().await;
let generation = TIMER_GENERATION.load(Ordering::Acquire);
if auto_light_weight_is_enabled().await {
let _ = TIMER_COMMANDS.send(TimerCommand::Arm(generation));
}
}
fn setup_window_close_listener() {
WINDOW_CLOSE_LISTENER.setup(|| {
std::mem::drop(AsyncHandler::spawn(|| async {
setup_light_weight_timer().await;
}));
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
});
async fn auto_light_weight_is_enabled() -> bool {
let verge = Config::verge().await;
// A disable applies before persistence. A rollback restores eligibility for future hides.
verge.data_arc().enable_auto_light_weight_mode.unwrap_or(false)
&& verge.latest_arc().enable_auto_light_weight_mode.unwrap_or(false)
}
fn cancel_window_close_listener() {
WINDOW_CLOSE_LISTENER.cancel();
}
fn setup_webview_focus_listener() {
WEBVIEW_FOCUS_LISTENER.setup(|| {
cancel_light_weight_timer();
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
});
}
fn cancel_webview_focus_listener() {
WEBVIEW_FOCUS_LISTENER.cancel();
}
async fn setup_light_weight_timer() {
let once_by_minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
let mut cancel_tx_guard = CANCEL_TX.lock();
if cancel_tx_guard.is_some() {
logging!(
debug,
Type::Timer,
"Lightweight mode timer already exists, skipping setup"
);
fn setup_auto_light_weight_listeners(generation: u64) {
let mut listeners = WINDOW_LISTENERS.lock();
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
return;
}
let (tx, rx) = oneshot::channel::<()>();
*cancel_tx_guard = Some(tx);
drop(cancel_tx_guard);
AsyncHandler::spawn(move || async move {
tokio::select! {
_ = sleep(Duration::from_secs(once_by_minutes.saturating_mul(60))) => {
logging!(info, Type::Timer, "Lightweight mode timer expired, entering lightweight mode");
{
let mut guard = CANCEL_TX.lock();
*guard = None;
}
entry_lightweight_mode().await;
}
_ = rx => {
logging!(debug, Type::Timer, "Received cancel signal, stopping lightweight mode timer");
}
listeners.close.setup(move || {
let _ = TIMER_COMMANDS.send(TimerCommand::Arm(generation));
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
});
listeners.focus.setup(move || {
if generation == TIMER_GENERATION.load(Ordering::Acquire) {
cancel_light_weight_timer();
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
}
});
}
async fn run_light_weight_timer(mut commands: mpsc::UnboundedReceiver<TimerCommand>) {
while let Some(command) = commands.recv().await {
let TimerCommand::Arm(generation) = command else {
continue;
};
// Unlisten can be deferred while Tauri is delivering an event.
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
continue;
}
let countdown = wait_for_light_weight_timeout();
tokio::pin!(countdown);
loop {
tokio::select! {
biased;
command = commands.recv() => match command {
Some(TimerCommand::Arm(_)) => {}
Some(TimerCommand::Disarm) => break,
None => return,
},
() = &mut countdown => {
if generation == TIMER_GENERATION.load(Ordering::Acquire) {
logging!(info, Type::Timer, "Lightweight mode timer expired, entering lightweight mode");
begin_lightweight_mode();
AsyncHandler::spawn(refresh_lightweight_tray_state);
}
break;
}
}
}
}
}
async fn wait_for_light_weight_timeout() {
let once_by_minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
logging!(
info,
Type::Timer,
"Lightweight mode timer set, entering lightweight mode in {} minutes",
once_by_minutes
);
sleep(Duration::from_secs(once_by_minutes.saturating_mul(60))).await;
}
fn cancel_light_weight_timer() {
let mut cancel_tx_guard = CANCEL_TX.lock();
if let Some(tx) = cancel_tx_guard.take() {
let _ = tx.send(());
logging!(debug, Type::Timer, "Timer cancelled");
}
let _ = TIMER_COMMANDS.send(TimerCommand::Disarm);
}
+40 -2
View File
@@ -3,13 +3,51 @@
//! Proxy settings live per network service. A write that found no service wrote nothing, and a
//! switch to another service leaves the proxy on the old one; both need the write repeated.
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler};
use crate::{
config::Config,
core::{CoreManager, proxy_control},
process::scheduled_task::{self, Mailbox, Next, ScheduledTask},
};
use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use std::sync::{Arc, LazyLock};
use sysproxy::NetworkServiceMonitor;
use tokio::time::Instant;
static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None);
static REAPPLY_REQUESTS: LazyLock<Arc<Mailbox<bool>>> =
LazyLock::new(|| scheduled_task::spawn(NetworkReapply::default(), |()| reapply()));
#[derive(Default)]
struct NetworkReapply {
pending: bool,
}
impl ScheduledTask for NetworkReapply {
type Input = bool;
type Work = ();
type Output = ();
fn on_input(&mut self, requested: bool, _: Instant) {
self.pending |= requested;
}
fn next(&mut self, _: Instant) -> Next<()> {
if std::mem::take(&mut self.pending) {
Next::Run(())
} else {
Next::Idle
}
}
fn finished(&mut self, (): (), result: std::thread::Result<()>, _: Instant) {
if result.is_err() {
logging!(error, Type::Core, "network proxy reapply panicked");
}
}
}
pub fn is_armed() -> bool {
MONITOR.lock().is_some()
}
@@ -18,7 +56,7 @@ pub fn is_armed() -> bool {
/// appearing from here on is never missed.
pub fn start() {
match NetworkServiceMonitor::start(|| {
AsyncHandler::spawn(reapply);
REAPPLY_REQUESTS.update(|pending| !std::mem::replace(pending, true));
}) {
Ok(monitor) => {
*MONITOR.lock() = Some(monitor);
+134 -48
View File
@@ -8,7 +8,7 @@ use crate::{
service,
sysopt::{Sysopt, format_bypass},
},
process::AsyncHandler,
process::{AsyncHandler, watch_task},
utils::{
notification::{NotificationEvent, needs_system_notification, notify_event},
server,
@@ -21,10 +21,16 @@ use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOut
use std::{
borrow::Borrow,
future::Future,
sync::atomic::{AtomicU64, Ordering},
sync::{
Arc, LazyLock, Once,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use tokio::{sync::Mutex, time::timeout};
use tokio::{
sync::{Mutex, watch},
time::timeout,
};
const CLEAR_ATTEMPTS: u32 = 3;
const CLEAR_RETRY_DELAY: Duration = Duration::from_millis(100);
@@ -215,23 +221,40 @@ const fn refusal_classification(service_usable: Option<bool>) -> SysproxyFailure
const LOOPBACK_HOST: &str = "127.0.0.1";
const MAX_SERVICE_BYPASS_LEN: usize = 8192;
static SERVICE_PROXY_OPERATIONS: ServiceProxyOperations = ServiceProxyOperations::new();
static SERVICE_PROXY_OPERATIONS: LazyLock<ServiceProxyOperations> = LazyLock::new(ServiceProxyOperations::new);
struct ServiceProxyOperations {
guard: watch::Sender<Option<Arc<ServiceGuard>>>,
guard_generation: AtomicU64,
operation_lock: Mutex<()>,
}
impl ServiceProxyOperations {
const fn new() -> Self {
fn new() -> Self {
Self {
guard: watch::channel(None).0,
guard_generation: AtomicU64::new(0),
operation_lock: Mutex::const_new(()),
}
}
fn invalidate_guard(&self) -> u64 {
self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1)
let mut generation = 0;
self.guard.send_if_modified(|active| {
generation = self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1);
active.take().is_some()
});
generation
}
fn start_guard(&self, guard: ServiceGuard) -> bool {
self.guard.send_if_modified(|active| {
if !guard_generation_is_current(&self.guard_generation, guard.generation) {
return false;
}
*active = Some(Arc::new(guard));
true
})
}
async fn run_service_operation<F, Fut, T>(&self, operation: F) -> T
@@ -606,51 +629,90 @@ pub async fn refresh_guard() -> Result<()> {
let proxy = current_service_proxy_config(&verge).await?;
let proof = service::active_service_session()?;
let interval = Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30).max(1));
AsyncHandler::spawn(move || async move {
let mut consecutive_failures = 0u32;
loop {
tokio::time::sleep(interval).await;
match SERVICE_PROXY_OPERATIONS
.run_guard_request(
generation,
&proof,
&proxy,
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
service::active_service_session,
|| service::set_system_proxy_by_service_with_session(&proxy, &proof),
)
.await
{
Ok(true) => consecutive_failures = 0,
Ok(false) => {
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
break;
}
Err(error) if is_missing_network_service_failure(&error) => {
consecutive_failures = 0;
logging!(debug, Type::Core, "system proxy guard waits for a network service");
}
Err(error) => {
consecutive_failures += 1;
logging!(
warn,
Type::Core,
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}",
consecutive_failures,
GUARD_FAILURES_BEFORE_STOPPING,
error
);
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
report_guard_stopped(generation, &error).await;
break;
}
static START_GUARD_MONITOR: Once = Once::new();
START_GUARD_MONITOR.call_once(|| {
let receiver = SERVICE_PROXY_OPERATIONS.guard.subscribe();
AsyncHandler::spawn(move || {
watch_task::run(receiver, monitor_guard, |guard| {
let generation = guard.generation;
logging!(
error,
Type::Core,
"service proxy guard panicked (generation {generation})"
);
})
});
});
if SERVICE_PROXY_OPERATIONS.start_guard(ServiceGuard {
generation,
proof,
proxy,
interval,
}) {
notification::retire_guard_failures();
}
Ok(())
}
struct ServiceGuard {
generation: u64,
proof: Arc<OwnerSessionProof>,
proxy: MacosProxyConfig,
interval: Duration,
}
async fn monitor_guard(guard: Arc<ServiceGuard>, mut updates: watch::Receiver<Option<Arc<ServiceGuard>>>) {
let ServiceGuard {
generation,
proof,
proxy,
interval,
} = guard.as_ref();
let mut consecutive_failures = 0u32;
loop {
tokio::select! {
biased;
_ = updates.changed() => return,
() = tokio::time::sleep(*interval) => {}
}
match SERVICE_PROXY_OPERATIONS
.run_guard_request(
*generation,
proof,
proxy,
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
service::active_service_session,
|| service::set_system_proxy_by_service_with_session(proxy, proof),
)
.await
{
Ok(true) => consecutive_failures = 0,
Ok(false) => {
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
return;
}
Err(error) if is_missing_network_service_failure(&error) => {
consecutive_failures = 0;
logging!(debug, Type::Core, "system proxy guard waits for a network service");
}
Err(error) => {
consecutive_failures += 1;
logging!(
warn,
Type::Core,
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}",
consecutive_failures,
GUARD_FAILURES_BEFORE_STOPPING,
error
);
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
report_guard_stopped(*generation, &error).await;
return;
}
}
}
});
// Retire only after the replacement guard starts successfully.
notification::retire_guard_failures();
Ok(())
}
}
const GUARD_FAILURES_BEFORE_STOPPING: u32 = 3;
@@ -725,6 +787,30 @@ mod tests {
);
}
#[test]
fn stale_guard_refresh_cannot_replace_or_revive_the_current_plan() {
let operations = ServiceProxyOperations::new();
let old = operations.invalidate_guard();
let current = operations.invalidate_guard();
let plan = |generation| super::ServiceGuard {
generation,
proof: Arc::new(proof(generation, "test")),
proxy: guarded_proxy(),
interval: std::time::Duration::from_secs(30),
};
assert!(operations.start_guard(plan(current)));
assert!(!operations.start_guard(plan(old)));
assert_eq!(
operations.guard.borrow().as_ref().map(|plan| plan.generation),
Some(current)
);
operations.invalidate_guard();
assert!(!operations.start_guard(plan(current)));
assert!(operations.guard.borrow().is_none());
}
#[tokio::test]
async fn final_service_mutation_finishes_after_in_flight_guard_request() {
let operations = Arc::new(ServiceProxyOperations::new());
+183 -102
View File
@@ -16,7 +16,11 @@ use crate::{
runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of},
tray::Tray,
},
process::AsyncHandler,
process::{
AsyncHandler,
scheduled_task::{self, Mailbox, Next, ScheduledTask},
watch_task,
},
};
use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_draft::Draft;
@@ -27,8 +31,6 @@ use clash_verge_service_ipc::{
StageRuntimeOutcome, StartClashRequest, WriterConfig,
};
use parking_lot::Mutex;
#[cfg(target_os = "macos")]
use std::sync::LazyLock;
use std::{
collections::HashMap,
env::current_exe,
@@ -36,11 +38,12 @@ use std::{
path::{Path, PathBuf},
process::Command as StdCommand,
sync::{
Arc,
Arc, LazyLock,
atomic::{AtomicBool, AtomicU64, Ordering},
},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::{sync::watch, time::Instant};
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
@@ -838,63 +841,84 @@ fn decode_hex(encoded: &str) -> Result<Vec<u8>> {
.collect()
}
static PROVIDER_SYNC_QUEUED: AtomicBool = AtomicBool::new(false);
// Serializing the whole read-and-publish pass prevents an older cache from replacing a newer one.
static PROVIDER_SYNC_SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static PROVIDER_SYNC_REQUESTS: LazyLock<Arc<Mailbox<Option<Instant>>>> =
LazyLock::new(|| scheduled_task::spawn(ProviderSchedule::default(), |_| sync_runtime_providers_by_service()));
static SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4;
const CONTENT_COMPARE_CHUNK: usize = 64 * 1024;
pub(crate) fn request_runtime_provider_sync(delay: Duration) {
if PROVIDER_SYNC_QUEUED.swap(true, Ordering::AcqRel) {
return;
}
AsyncHandler::spawn(move || async move {
tokio::time::sleep(delay).await;
use crate::utils::retry::{RetryError, RetryPolicy, retry};
let _ = retry(
RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add((RUNTIME_PROVIDER_SYNC_ATTEMPTS - 1) as usize),
constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY,
),
|index| async move {
let attempt = index as u32 + 1;
let outcome = {
let _serial = PROVIDER_SYNC_SERIAL.lock().await;
if attempt == 1 {
PROVIDER_SYNC_QUEUED.store(false, Ordering::Release);
}
sync_runtime_providers_by_service().await
};
match outcome {
Ok(ProviderSync { pending: 0, .. }) => Ok(()),
Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
logging!(
info,
Type::Service,
"{pending} provider caches are not ready yet; retrying"
);
Err(RetryError::Retry(()))
}
Ok(ProviderSync { pending, .. }) => {
logging!(warn, Type::Service, "{pending} provider caches were not synced");
Ok(())
}
Err(error) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
Ok(())
}
}
},
)
.await;
let due = Instant::now() + delay;
PROVIDER_SYNC_REQUESTS.update(|pending| {
if pending.is_some_and(|current| current <= due) {
return false;
}
*pending = Some(due);
true
});
}
#[derive(Default)]
struct ProviderSchedule {
requested: Option<Instant>,
retry: Option<(Instant, u32)>,
}
impl ScheduledTask for ProviderSchedule {
type Input = Option<Instant>;
type Work = u32;
type Output = Result<ProviderSync>;
fn on_input(&mut self, requested: Self::Input, _: Instant) {
if let Some(requested) = requested {
self.requested = Some(self.requested.map_or(requested, |current| current.min(requested)));
}
}
fn next(&mut self, now: Instant) -> Next<u32> {
let Some(due) = self.requested.into_iter().chain(self.retry.map(|(due, _)| due)).min() else {
return Next::Idle;
};
if due > now {
return Next::At(due);
}
self.requested.take_if(|due| *due <= now);
Next::Run(
self.retry
.take_if(|(due, _)| *due <= now)
.map_or(1, |(_, attempt)| attempt),
)
}
fn finished(&mut self, attempt: u32, result: std::thread::Result<Self::Output>, now: Instant) {
match result {
Ok(Ok(ProviderSync { pending: 0, .. })) => self.retry = None,
Ok(Ok(ProviderSync { pending, .. })) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
logging!(
info,
Type::Service,
"{pending} provider caches are not ready yet; retrying"
);
// A new request during backoff leaves the existing retry deadline and budget intact.
self.retry
.get_or_insert_with(|| (now + constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY, attempt + 1));
}
Ok(Ok(ProviderSync { pending, .. })) => {
logging!(warn, Type::Service, "{pending} provider caches were not synced");
}
Ok(Err(error)) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
}
Err(_) => logging!(error, Type::Service, "provider cache sync panicked"),
}
}
}
#[derive(Debug, Default)]
struct ProviderSync {
synced: usize,
@@ -1451,55 +1475,74 @@ const OWNER_MONITOR_INTERVAL: Duration = Duration::from_secs(5);
/// Mirrors `OwnerWatch`'s tolerance, for the log line only.
const SUSTAINED_OWNER_SAMPLES: u8 = 3;
fn start_owner_monitor() {
let generation = OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;
AsyncHandler::spawn(move || async move {
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
let mut watch = OwnerWatch::new();
let mut core_restarts = None;
loop {
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
if OWNER_MONITOR_GENERATION.load(Ordering::Acquire) != generation {
logging!(
debug,
Type::Service,
"owner monitor superseded (generation {generation})"
);
break;
}
if !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service) {
logging!(
debug,
Type::Service,
"owner monitor stopped; core no longer in service mode (generation {generation})"
);
break;
}
let (sample, status) = read_owner_sample().await;
if let Some(status) = &status {
log_core_restarts(&mut core_restarts, status);
}
let mut step = watch.observe(sample);
if matches!(step, OwnerStep::VerifyTransport) {
if watch.just_became_sustained() {
logging!(
warn,
Type::Service,
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples (generation {generation}); \
preserving local proxy state while the core endpoint still answers"
);
}
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
step = watch.resolve_transport(owner_endpoint_available);
}
if let OwnerStep::Recover(reason) = step {
recover_after_owner_loss(generation, reason, status.as_ref()).await;
break;
}
}
static OWNER_MONITOR: LazyLock<watch::Sender<Option<u64>>> = LazyLock::new(|| {
let (sender, receiver) = watch::channel(None);
AsyncHandler::spawn(move || {
watch_task::run(receiver, monitor_owner, |generation| {
logging!(error, Type::Service, "owner monitor panicked (generation {generation})");
})
});
sender
});
fn start_owner_monitor() {
OWNER_MONITOR.send_modify(|active| {
*active = Some(OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel).wrapping_add(1));
});
}
async fn monitor_owner(generation: u64, mut updates: watch::Receiver<Option<u64>>) {
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
let mut watch = OwnerWatch::new();
let mut core_restarts = None;
loop {
let (step, status) = tokio::select! {
biased;
_ = updates.changed() => return,
result = async {
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
if owner_monitor_generation() != generation
|| !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service)
{
return None;
}
Some(probe_owner(generation, &mut watch, &mut core_restarts).await)
} => match result {
Some(observation) => observation,
None => return,
}
};
if let OwnerStep::Recover(reason) = step {
recover_after_owner_loss(generation, reason, status.as_ref()).await;
return;
}
}
}
async fn probe_owner(
generation: u64,
watch: &mut OwnerWatch,
core_restarts: &mut Option<u32>,
) -> (OwnerStep, Option<ServiceStatusSnapshot>) {
let (sample, status) = read_owner_sample().await;
if let Some(status) = &status {
log_core_restarts(core_restarts, status);
}
let mut step = watch.observe(sample);
if matches!(step, OwnerStep::VerifyTransport) {
if watch.just_became_sustained() {
logging!(
warn,
Type::Service,
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples (generation {generation}); \
preserving local proxy state while the core endpoint still answers"
);
}
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
step = watch.resolve_transport(owner_endpoint_available);
}
(step, status)
}
/// The Service logs its watchdog restarts where the app cannot read them.
@@ -1583,7 +1626,10 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
}
fn cancel_owner_monitors() {
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel);
OWNER_MONITOR.send_modify(|active| {
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel);
*active = None;
});
}
pub(crate) fn owner_monitor_generation() -> u64 {
@@ -1916,6 +1962,41 @@ mod tests {
use clash_verge_service_ipc::OwnerSessionProof;
use std::sync::atomic::{AtomicU64, Ordering};
#[tokio::test(start_paused = true)]
async fn replacing_the_owner_monitor_interrupts_its_wait() {
let (sender, mut desired) = tokio::sync::watch::channel(Some(1));
let mut previous = Box::pin(super::monitor_owner(1, desired.clone()));
assert!(futures::poll!(&mut previous).is_pending());
sender.send_replace(Some(2));
assert!(futures::poll!(&mut previous).is_ready());
assert!(desired.has_changed().unwrap_or(false));
assert_eq!(*desired.borrow_and_update(), Some(2));
}
#[test]
fn early_provider_sync_keeps_the_later_retry_budget() {
use super::{Duration, Instant, Next, ProviderSchedule, ProviderSync, ScheduledTask as _};
let mut schedule = ProviderSchedule::default();
let now = Instant::now();
let pending = || Ok(Ok(ProviderSync { pending: 1, synced: 0 }));
schedule.on_input(Some(now), now);
assert!(matches!(schedule.next(now), Next::Run(1)));
schedule.finished(1, pending(), now);
let early = now + Duration::from_secs(2);
schedule.on_input(Some(now + Duration::from_secs(9)), now);
schedule.on_input(Some(early), now);
assert!(matches!(schedule.next(now), Next::At(due) if due == early));
assert!(matches!(schedule.next(early), Next::Run(1)));
schedule.finished(1, pending(), early);
let retry = now + crate::constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY;
assert!(matches!(schedule.next(early), Next::At(due) if due == retry));
assert!(matches!(schedule.next(retry), Next::Run(2)));
}
/// A Run State backed by a scripted environment, so these tests never touch the global.
fn fake_store() -> RunStateStore<FakeEnv> {
RunStateStore::new(FakeEnv::new())
+29 -7
View File
@@ -7,10 +7,11 @@ use crate::{
};
use anyhow::Result;
use clash_verge_logging::{Type, logging, logging_error};
use futures::StreamExt as _;
use futures::{FutureExt as _, StreamExt as _};
use parking_lot::{Mutex, RwLock};
use std::{
collections::HashMap,
panic::AssertUnwindSafe,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
@@ -70,11 +71,11 @@ async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Fini
Started: FnOnce(),
Update: FnOnce() -> UpdateFuture,
UpdateFuture: std::future::Future<Output = Output>,
Finished: FnOnce(Output),
Finished: FnOnce(std::thread::Result<Output>),
Completed: FnOnce(),
{
update_started();
let result = update_profile().await;
let result = AssertUnwindSafe(async { update_profile().await }).catch_unwind().await;
update_finished(result);
update_completed();
}
@@ -474,12 +475,13 @@ impl Timer {
|| Self::emit_update_event(uid, true),
|| feat::update_profile(uid, None, false),
|result| match result {
Ok(_) => {
Ok(Ok(_)) => {
logging!(debug, Type::Timer, "timer task completed for uid: {}", uid);
}
Err(e) => {
Ok(Err(e)) => {
logging_error!(Type::Timer, "Failed to update profile uid {}: {e:#}", uid);
}
Err(_) => logging!(error, Type::Timer, "Profile update worker panicked for uid: {uid}"),
},
|| Self::emit_update_event(uid, false),
)
@@ -732,6 +734,26 @@ mod tests {
assert!(nothing_due(&mut queue).await, "and must never be scheduled again");
}
#[tokio::test]
#[allow(clippy::panic, reason = "inject an unwind in the update worker")]
async fn panicking_profile_update_reports_completion() {
let calls = Mutex::new(Vec::new());
run_timer_profile_update_transition(
|| calls.lock().push("update-started"),
|| async { panic!("profile update panic") },
|result| {
assert!(result.is_err());
calls.lock().push("terminal-result");
},
|| calls.lock().push("update-completed"),
)
.await;
assert_eq!(
calls.into_inner(),
["update-started", "terminal-result", "update-completed"]
);
}
#[tokio::test(start_paused = true)]
async fn timer_profile_update_runs_past_former_deadline_and_pairs_events() -> anyhow::Result<()> {
let calls = Arc::new(Mutex::new(Vec::new()));
@@ -763,8 +785,8 @@ mod tests {
},
{
let calls = Arc::clone(&calls);
move |result: anyhow::Result<()>| {
assert!(result.is_ok());
move |result| {
assert!(matches!(result, Ok(Ok(()))));
calls.lock().push("terminal-result");
}
},
+88 -117
View File
@@ -2,28 +2,18 @@ use crate::core::handle;
use crate::process::AsyncHandler;
use crate::utils::{connections_stream, tray_speed};
use crate::{Type, logging};
use parking_lot::Mutex;
use std::sync::Arc;
use std::sync::OnceLock;
use std::time::Duration;
use tauri::async_runtime::JoinHandle;
use tauri_plugin_mihomo::models::WsConnectionId;
use tokio::sync::watch;
use connections_stream::{MihomoWsEventStream, StreamConsumeState, TrafficSpeedEvent};
const TRAY_SPEED_RETRY_DELAY: Duration = Duration::from_secs(1);
const TRAY_SPEED_STALE_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Clone)]
#[derive(Default)]
pub struct TraySpeedController {
speed_task: Arc<Mutex<Option<JoinHandle<()>>>>,
speed_connection_id: Arc<Mutex<Option<WsConnectionId>>>,
}
impl Default for TraySpeedController {
fn default() -> Self {
Self {
speed_task: Arc::new(Mutex::new(None)),
speed_connection_id: Arc::new(Mutex::new(None)),
}
}
enabled: OnceLock<watch::Sender<bool>>,
}
impl TraySpeedController {
@@ -32,104 +22,102 @@ impl TraySpeedController {
}
pub fn update_task(&self, enable_tray_speed: bool) {
if enable_tray_speed {
self.start_task();
} else {
self.stop_task();
let enabled = self.enabled.get_or_init(|| {
let (enabled, receiver) = watch::channel(false);
AsyncHandler::spawn(move || Self::run(receiver));
enabled
});
enabled.send_replace(enable_tray_speed);
}
async fn run(mut enabled: watch::Receiver<bool>) {
while enabled.changed().await.is_ok() {
let should_run = *enabled.borrow_and_update();
if should_run {
Self::run_enabled(&mut enabled).await;
} else {
Self::clear_tray_speed();
}
}
}
fn start_task(&self) {
if handle::Handle::global().is_exiting() {
return;
}
async fn run_enabled(enabled: &mut watch::Receiver<bool>) {
while !handle::Handle::global().is_exiting() {
if !Self::has_main_tray() {
logging!(warn, Type::Tray, "托盘不可用,停止托盘速率任务");
return;
}
if !Self::has_main_tray() {
logging!(warn, Type::Tray, "托盘不可用,跳过启动托盘速率任务");
return;
}
let mut guard = self.speed_task.lock();
if guard.as_ref().is_some_and(|task| !task.inner().is_finished()) {
return;
}
let speed_connection_id = Arc::clone(&self.speed_connection_id);
let task = AsyncHandler::spawn(move || async move {
loop {
if handle::Handle::global().is_exiting() {
break;
}
if !Self::has_main_tray() {
logging!(warn, Type::Tray, "托盘已不可用,停止托盘速率任务");
break;
}
let stream_connect_result = connections_stream::connect_traffic_stream().await;
let mut speed_stream = match stream_connect_result {
Ok(stream) => stream,
Err(err) => {
logging!(debug, Type::Tray, "托盘速率流连接失败,稍后重试: {err}");
Self::apply_tray_speed(0, 0);
tokio::time::sleep(TRAY_SPEED_RETRY_DELAY).await;
continue;
}
};
Self::set_speed_connection_id(&speed_connection_id, Some(speed_stream.connection_id));
loop {
let next_state = speed_stream
.next_event(TRAY_SPEED_STALE_TIMEOUT, || handle::Handle::global().is_exiting())
.await;
match next_state {
connections_stream::StreamConsumeState::Event(speed_event) => {
Self::apply_tray_speed(speed_event.up, speed_event.down);
}
connections_stream::StreamConsumeState::Stale => {
logging!(debug, Type::Tray, "托盘速率流长时间未收到有效数据,触发重连");
Self::apply_tray_speed(0, 0);
break;
}
connections_stream::StreamConsumeState::Closed
| connections_stream::StreamConsumeState::ExitRequested => {
break;
}
// Keep the registered stream outside the cancellable future until it is disconnected.
let mut stream = None;
let disabled = tokio::select! {
biased;
_ = Self::wait_until_disabled(enabled) => true,
_ = Self::read_speed(&mut stream) => false,
};
if disabled {
Self::clear_tray_speed();
}
if let Some(stream) = stream {
let disconnect = connections_stream::disconnect_connection(stream.connection_id);
tokio::pin!(disconnect);
tokio::select! {
biased;
_ = Self::wait_until_disabled(enabled), if !disabled => {
Self::clear_tray_speed();
disconnect.await;
return;
}
_ = &mut disconnect => {}
}
}
if disabled || handle::Handle::global().is_exiting() || !Self::has_main_tray() {
return;
}
Self::disconnect_speed_connection(&speed_connection_id).await;
if handle::Handle::global().is_exiting() || !Self::has_main_tray() {
break;
}
// `Stale` already reset the display; this covers remote close.
if *enabled.borrow() {
Self::apply_tray_speed(0, 0);
tokio::time::sleep(TRAY_SPEED_RETRY_DELAY).await;
}
Self::set_speed_connection_id(&speed_connection_id, None);
});
*guard = Some(task);
if tokio::time::timeout(TRAY_SPEED_RETRY_DELAY, Self::wait_until_disabled(enabled))
.await
.is_ok()
{
Self::clear_tray_speed();
return;
}
}
}
fn stop_task(&self) {
let task = self.speed_task.lock().take();
let speed_connection_id = Arc::clone(&self.speed_connection_id);
async fn wait_until_disabled(enabled: &mut watch::Receiver<bool>) {
let _ = enabled.wait_for(|enabled| !enabled).await;
}
AsyncHandler::spawn(move || async move {
// Await abort before disconnect so the task cannot consume and lose the connection ID.
if let Some(task) = task {
task.abort();
let _ = task.await;
async fn read_speed(stream: &mut Option<MihomoWsEventStream<TrafficSpeedEvent>>) {
let speed_stream = match connections_stream::connect_traffic_stream().await {
Ok(connected) => stream.insert(connected),
Err(err) => {
logging!(debug, Type::Tray, "托盘速率流连接失败,稍后重试: {err}");
return;
}
Self::disconnect_speed_connection(&speed_connection_id).await;
});
};
loop {
match speed_stream
.next_event(TRAY_SPEED_STALE_TIMEOUT, || handle::Handle::global().is_exiting())
.await
{
StreamConsumeState::Event(event) => Self::apply_tray_speed(event.up, event.down),
StreamConsumeState::Stale => {
logging!(debug, Type::Tray, "托盘速率流长时间未收到有效数据,触发重连");
Self::apply_tray_speed(0, 0);
return;
}
StreamConsumeState::Closed | StreamConsumeState::ExitRequested => return,
}
}
}
fn clear_tray_speed() {
let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
let result = tray.with_inner_tray_icon(|inner| {
@@ -147,23 +135,6 @@ impl TraySpeedController {
handle::Handle::app_handle().tray_by_id(super::TRAY_ID).is_some()
}
fn set_speed_connection_id(
speed_connection_id: &Arc<Mutex<Option<WsConnectionId>>>,
connection_id: Option<WsConnectionId>,
) {
*speed_connection_id.lock() = connection_id;
}
fn take_speed_connection_id(speed_connection_id: &Arc<Mutex<Option<WsConnectionId>>>) -> Option<WsConnectionId> {
speed_connection_id.lock().take()
}
async fn disconnect_speed_connection(speed_connection_id: &Arc<Mutex<Option<WsConnectionId>>>) {
if let Some(connection_id) = Self::take_speed_connection_id(speed_connection_id) {
connections_stream::disconnect_connection(connection_id).await;
}
}
fn apply_tray_speed(up: u64, down: u64) {
let app_handle = handle::Handle::app_handle();
if let Some(tray) = app_handle.tray_by_id(super::TRAY_ID) {
+2 -1
View File
@@ -1,6 +1,6 @@
use crate::{
config::{Config, IClashTemp, IProfiles, IVerge},
core::{CoreManager, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
@@ -58,6 +58,7 @@ async fn finalize_restored_verge_config(
*d = restored.clone();
});
verge_draft.apply();
auto_backup::publish_settings(&verge_draft.data_arc());
// Turn it off here; a failing core side effect below would otherwise skip this step.
if !restored.enable_system_proxy.unwrap_or_default() {
+46 -14
View File
@@ -21,24 +21,38 @@ pub(super) enum Effect {
pub(super) type Effects = BTreeSet<Effect>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum AfterCommit {
BackupSettings,
}
#[derive(Default)]
pub(super) struct EffectPlan {
pub(super) before_commit: Effects,
pub(super) after_commit: BTreeSet<AfterCommit>,
}
macro_rules! select_field {
($effects:ident, $field:ident, NoEffect) => { let _ = $field; };
($effects:ident, $field:ident, [$($effect:ident),*]) => {
if $field.is_some() { $effects.extend([$(Effect::$effect),*]); }
if $field.is_some() { $effects.before_commit.extend([$(Effect::$effect),*]); }
};
($effects:ident, $field:ident, (AfterCommit $effect:ident)) => {
if $field.is_some() { $effects.after_commit.insert(AfterCommit::$effect); }
};
($effects:ident, $field:ident, Tun) => {
select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]);
#[cfg(target_os = "linux")]
if *$field == Some(true) { $effects.insert(Effect::RestartCore); }
if *$field == Some(true) { $effects.before_commit.insert(Effect::RestartCore); }
};
}
macro_rules! verge_registry {
($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => {
pub(super) fn verge_effects(patch: &IVerge) -> Effects {
pub(super) fn verge_effects(patch: &IVerge) -> EffectPlan {
// No rest pattern: even fields omitted by serde must be classified at compile time.
let IVerge { $( $(#[$cfg])* $field, )* } = patch;
let mut effects = Effects::new();
let mut effects = EffectPlan::default();
$( $(#[$cfg])* { select_field!(effects, $field, $rule); } )*
effects
}
@@ -100,9 +114,9 @@ verge_registry! {
proxy_layout_column => NoEffect;
test_list => NoEffect;
auto_log_clean => NoEffect;
enable_auto_backup_schedule => NoEffect;
auto_backup_interval_hours => NoEffect;
auto_backup_on_change => NoEffect;
enable_auto_backup_schedule => (AfterCommit BackupSettings);
auto_backup_interval_hours => (AfterCommit BackupSettings);
auto_backup_on_change => (AfterCommit BackupSettings);
#[cfg(not(target_os = "windows"))]
verge_redir_port => [RestartCore];
#[cfg(not(target_os = "windows"))]
@@ -130,7 +144,7 @@ verge_registry! {
enable_external_controller => [RestartCore];
}
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> EffectPlan {
use clash_verge_logging::{Type, logging};
let mut effects = Effects::new();
for key in patch.keys() {
@@ -157,7 +171,10 @@ pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
if patch.is_empty() {
effects.insert(Effect::ClashConfig);
}
effects
EffectPlan {
before_commit: effects,
..Default::default()
}
}
#[cfg(test)]
@@ -172,7 +189,7 @@ mod tests {
#[test]
fn representative_verge_patches_map_to_frozen_effects() {
assert_eq!(verge_effects(&IVerge::default()), Effects::new());
assert_eq!(verge_effects(&IVerge::default()).before_commit, Effects::new());
let cases: [(IVerge, &[Effect]); 9] = [
(
@@ -216,7 +233,7 @@ mod tests {
];
for (patch, expected) in cases {
assert_eq!(
verge_effects(&patch),
verge_effects(&patch).before_commit,
expected.iter().copied().collect::<Effects>(),
"patch mapping drifted for {expected:?}"
);
@@ -225,7 +242,7 @@ mod tests {
let tun = verge_patch(|p| p.enable_tun_mode = Some(true));
#[cfg(target_os = "linux")]
assert_eq!(
verge_effects(&tun),
verge_effects(&tun).before_commit,
[
Effect::RestartCore,
Effect::ClashConfig,
@@ -238,7 +255,7 @@ mod tests {
);
#[cfg(not(target_os = "linux"))]
assert_eq!(
verge_effects(&tun),
verge_effects(&tun).before_commit,
[
Effect::ClashConfig,
Effect::TrayIcon,
@@ -250,6 +267,21 @@ mod tests {
);
}
#[test]
fn only_backup_fields_schedule_one_settings_publication() {
let unrelated = verge_patch(|patch| patch.language = Some("zh".into()));
assert!(verge_effects(&unrelated).after_commit.is_empty());
let backup = verge_patch(|patch| {
patch.enable_auto_backup_schedule = Some(true);
patch.auto_backup_interval_hours = Some(2);
patch.auto_backup_on_change = Some(false);
});
let effects = verge_effects(&backup);
assert!(effects.before_commit.is_empty());
assert_eq!(effects.after_commit, BTreeSet::from([AfterCommit::BackupSettings]));
}
fn clash_mapping(pairs: &[(&str, &str)]) -> serde_yaml_ng::Mapping {
let mut mapping = serde_yaml_ng::Mapping::new();
for (key, value) in pairs {
@@ -281,7 +313,7 @@ mod tests {
];
for (patch, expected) in cases {
assert_eq!(
clash_effects(&patch),
clash_effects(&patch).before_commit,
expected.iter().copied().collect::<Effects>(),
"clash mapping drifted for {expected:?}"
);
+10 -6
View File
@@ -1,11 +1,11 @@
use super::effects::{Effect, Effects};
use super::effects::{AfterCommit, Effect, EffectPlan};
use crate::core::notify::{Refresh, announce};
use crate::{
config::{
Config, IVerge,
snapshot::{capture_config_files, restore_files},
},
core::auto_backup::AutoBackupManager,
core::auto_backup,
core::{
CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control,
tray,
@@ -108,7 +108,7 @@ async fn ensure_effect(
Ok(())
}
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: EffectPlan) -> Result<()> {
let manager = CoreManager::global();
let update = manager.claim_config_update(config_write)?;
let clash = Config::clash().await;
@@ -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)),
}
let result: Result<()> = async {
for effect in effects.iter().copied() {
for effect in effects.before_commit.iter().copied() {
let result = Box::pin(ensure_effect(effect, verge_patch, manager, &update)).await;
if matches!(patch, Patch::Clash(_)) && matches!(effect, Effect::TrayMenu | Effect::TrayIcon) {
// Tray failures must not reject an applied Clash mode change.
@@ -166,10 +166,14 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
if patch.auto_check_update == Some(false) {
SilentUpdater::global().discard_pending().await;
}
if effects.contains(&Effect::ClashConfig) {
if effects.before_commit.contains(&Effect::ClashConfig) {
announce(Refresh::Clash);
}
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
for effect in effects.after_commit {
match effect {
AfterCommit::BackupSettings => auto_backup::publish_settings(&verge.data_arc()),
}
}
announce(Refresh::Verge);
}
Patch::Clash(_) => announce(Refresh::Clash),
+1 -11
View File
@@ -304,17 +304,7 @@ async fn clean_session_ending_best_effort() -> CleanupResult {
#[cfg(target_os = "macos")]
pub async fn hide() {
use crate::core::lightweight::add_light_weight_timer;
let enable_auto_light_weight_mode = Config::verge()
.await
.data_arc()
.enable_auto_light_weight_mode
.unwrap_or(false);
if enable_auto_light_weight_mode {
add_light_weight_timer().await;
}
crate::core::lightweight::add_light_weight_timer().await;
if let Some(window) = WindowManager::get_main_window()
&& window.is_visible().unwrap_or(false)
+3
View File
@@ -1,2 +1,5 @@
mod async_handler;
pub use async_handler::AsyncHandler;
pub(crate) mod scheduled_task;
pub(crate) mod watch_task;
+82
View File
@@ -0,0 +1,82 @@
use super::AsyncHandler;
use futures::FutureExt as _;
use parking_lot::Mutex;
use std::{future::Future, panic::AssertUnwindSafe, sync::Arc};
use tokio::{
sync::Notify,
time::{Instant, sleep_until},
};
pub(crate) enum Next<W> {
Idle,
At(Instant),
Run(W),
}
pub(crate) trait ScheduledTask {
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>;
fn finished(&mut self, work: Self::Work, result: std::thread::Result<Self::Output>, now: Instant);
}
pub(crate) struct Mailbox<I> {
pending: Mutex<I>,
changed: Notify,
}
impl<I> Mailbox<I> {
pub(crate) fn update(&self, merge: impl FnOnce(&mut I) -> bool) {
let changed = merge(&mut *self.pending.lock());
if changed {
self.changed.notify_one();
}
}
}
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 inbox = Arc::new(Mailbox {
pending: Mutex::default(),
changed: Notify::new(),
});
let receiver = Arc::clone(&inbox);
AsyncHandler::spawn(move || drive(policy, receiver, execute));
inbox
}
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());
}
}
}
}
+28
View File
@@ -0,0 +1,28 @@
use futures::FutureExt as _;
use std::{future::Future, panic::AssertUnwindSafe};
use tokio::sync::watch;
pub(crate) 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);
}
}
}
}
+2 -2
View File
@@ -12,7 +12,7 @@ use crate::{
service::{SERVICE_MANAGER, ServiceManager},
tray::Tray,
},
core::{auto_backup::AutoBackupManager, lightweight::auto_lightweight_boot},
core::{auto_backup, lightweight::auto_lightweight_boot},
feat,
process::AsyncHandler,
utils::{init, server, window_manager::WindowManager},
@@ -150,7 +150,7 @@ async fn init_auto_lightweight_boot() {
}
async fn init_auto_backup() {
logging_error!(Type::Setup, AutoBackupManager::global().init().await);
auto_backup::init().await;
}
fn init_silent_updater() {