mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-30 01:20:07 +08:00
refactor(backend): share single-owner drivers for background tasks (#8759)
* docs(backend): define background task ownership * refactor(backend): give background operations single task owners * test(backend): remove actor migration regression cases * docs(changelog): drop backend actor migration entry * refactor(backend): extract workspace task drivers * fix(timer): omit profile identifier from panic log * docs(backend): define workspace crate boundaries * refactor(lightweight): use the task countdown driver * refactor(lightweight): name countdown callbacks * refactor(task): simplify driver startup and coalescing requests * refactor(core): bind service handoff to the sidecar generation * refactor(tun): coalesce background run state reconciliation * refactor(core): own sidecar exit resources in one session * refactor(core): remove automatic Windows service handoff * refactor(task): simplify coalescing job signals * refactor(runstate): keep operation status with service state * refactor(dns): coalesce background override synchronization * refactor(sysproxy): own the local guard under its operation lock * fix(tray): read menu settings at publication * fix(dns): retain script lock across caller cancellation * refactor(profiles): own selected node restoration in one task * refactor(timer): own subscription schedules in the scheduler * test(timer): remove the added application test * fix(service): renew provider sync retry budget on refresh
This commit is contained in:
+130
-151
@@ -1,29 +1,23 @@
|
||||
use crate::process::AsyncHandler;
|
||||
use crate::{
|
||||
config::{Config, IVerge},
|
||||
feat::create_local_backup_with_namer,
|
||||
process::AsyncHandler,
|
||||
utils::dirs::local_backup_dir,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use chrono::Local;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
||||
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 +36,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 +46,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 +75,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(|| AsyncHandler::start_driver(scheduled_task::new(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 {
|
||||
|
||||
+105
-104
@@ -5,14 +5,16 @@ use crate::{
|
||||
};
|
||||
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_task::countdown::{self, Countdown};
|
||||
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use anyhow::Result;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU32, Ordering};
|
||||
use std::future::Future;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use tauri::Listener as _;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::{Duration, sleep};
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -41,27 +43,24 @@ impl LightweightState {
|
||||
static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8);
|
||||
|
||||
struct WindowListener {
|
||||
handler_id: AtomicU32,
|
||||
handler_id: Option<tauri::EventId>,
|
||||
event: &'static str,
|
||||
label: &'static str,
|
||||
}
|
||||
|
||||
impl WindowListener {
|
||||
fn setup(&self, on_event: impl Fn() + Send + 'static) {
|
||||
fn setup(&mut self, on_event: impl Fn() + Send + 'static) {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
let previous_handler_id = self.handler_id.swap(0, Ordering::AcqRel);
|
||||
if previous_handler_id != 0 {
|
||||
window.unlisten(previous_handler_id);
|
||||
if let Some(id) = self.handler_id.take() {
|
||||
window.unlisten(id);
|
||||
logging!(debug, Type::Lightweight, "覆盖旧的{}监听", self.label);
|
||||
}
|
||||
let handler_id = window.listen(self.event, move |_event| on_event());
|
||||
self.handler_id.store(handler_id, Ordering::Release);
|
||||
self.handler_id = Some(window.listen(self.event, move |_event| on_event()));
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel(&self) {
|
||||
let id = self.handler_id.swap(0, Ordering::AcqRel);
|
||||
if id != 0 {
|
||||
fn cancel(&mut self) {
|
||||
if let Some(id) = self.handler_id.take() {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
window.unlisten(id);
|
||||
}
|
||||
@@ -70,19 +69,28 @@ impl WindowListener {
|
||||
}
|
||||
}
|
||||
|
||||
static WINDOW_CLOSE_LISTENER: WindowListener = WindowListener {
|
||||
handler_id: AtomicU32::new(0),
|
||||
event: "tauri://close-requested",
|
||||
label: "窗口关闭",
|
||||
};
|
||||
struct WindowListeners {
|
||||
close: WindowListener,
|
||||
focus: WindowListener,
|
||||
}
|
||||
|
||||
static WEBVIEW_FOCUS_LISTENER: WindowListener = WindowListener {
|
||||
handler_id: AtomicU32::new(0),
|
||||
event: "tauri://focus",
|
||||
label: "窗口焦点",
|
||||
};
|
||||
static WINDOW_LISTENERS: Mutex<WindowListeners> = Mutex::new(WindowListeners {
|
||||
close: WindowListener {
|
||||
handler_id: None,
|
||||
event: "tauri://close-requested",
|
||||
label: "窗口关闭",
|
||||
},
|
||||
focus: WindowListener {
|
||||
handler_id: None,
|
||||
event: "tauri://focus",
|
||||
label: "窗口焦点",
|
||||
},
|
||||
});
|
||||
|
||||
static CANCEL_TX: Mutex<Option<oneshot::Sender<()>>> = Mutex::new(None);
|
||||
static TIMER_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
static COUNTDOWN: LazyLock<Countdown<u64>> =
|
||||
LazyLock::new(|| AsyncHandler::start_driver(countdown::new(prepare_countdown, enter_lightweight_on_timeout)));
|
||||
|
||||
#[inline]
|
||||
fn get_state() -> LightweightState {
|
||||
@@ -118,11 +126,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 +140,43 @@ pub async fn auto_lightweight_boot() -> Result<()> {
|
||||
}
|
||||
|
||||
pub async fn enable_auto_light_weight_mode() {
|
||||
enable_auto_light_weight_mode_at(TIMER_GENERATION.load(Ordering::Acquire)).await;
|
||||
}
|
||||
|
||||
async fn enable_auto_light_weight_mode_at(generation: u64) {
|
||||
if let Err(e) = Timer::global().init().await {
|
||||
logging!(error, Type::Lightweight, "Failed to initialize timer: {e}");
|
||||
return;
|
||||
}
|
||||
logging!(info, Type::Lightweight, "开启自动轻量模式");
|
||||
setup_window_close_listener();
|
||||
setup_webview_focus_listener();
|
||||
setup_auto_light_weight_listeners(generation);
|
||||
}
|
||||
|
||||
pub fn disable_auto_light_weight_mode() {
|
||||
logging!(info, Type::Lightweight, "关闭自动轻量模式");
|
||||
cancel_light_weight_timer();
|
||||
cancel_window_close_listener();
|
||||
cancel_webview_focus_listener();
|
||||
TIMER_GENERATION.fetch_add(1, Ordering::AcqRel);
|
||||
COUNTDOWN.disarm();
|
||||
let mut listeners = WINDOW_LISTENERS.lock();
|
||||
listeners.close.cancel();
|
||||
listeners.focus.cancel();
|
||||
}
|
||||
|
||||
pub async fn entry_lightweight_mode() -> bool {
|
||||
let entered = begin_lightweight_mode();
|
||||
if entered {
|
||||
COUNTDOWN.disarm();
|
||||
}
|
||||
refresh_lightweight_tray_state().await;
|
||||
entered
|
||||
}
|
||||
|
||||
fn begin_lightweight_mode() -> bool {
|
||||
if !try_transition(LightweightState::Normal, LightweightState::In) {
|
||||
logging!(debug, Type::Lightweight, "无需进入轻量模式,跳过调用");
|
||||
refresh_lightweight_tray_state().await;
|
||||
return false;
|
||||
}
|
||||
record_state_and_log(LightweightState::In);
|
||||
WindowManager::destroy_main_window();
|
||||
cancel_light_weight_timer();
|
||||
refresh_lightweight_tray_state().await;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -172,16 +192,11 @@ pub async fn exit_lightweight_mode() -> bool {
|
||||
}
|
||||
record_state_and_log(LightweightState::Exiting);
|
||||
WindowManager::show_main_window().await;
|
||||
let enable_auto_light_weight_mode = Config::verge()
|
||||
.await
|
||||
.data_arc()
|
||||
.enable_auto_light_weight_mode
|
||||
.unwrap_or(false);
|
||||
if enable_auto_light_weight_mode {
|
||||
setup_window_close_listener();
|
||||
setup_webview_focus_listener();
|
||||
let generation = TIMER_GENERATION.load(Ordering::Acquire);
|
||||
if auto_light_weight_is_enabled().await {
|
||||
setup_auto_light_weight_listeners(generation);
|
||||
}
|
||||
cancel_light_weight_timer();
|
||||
COUNTDOWN.disarm();
|
||||
record_state_and_log(LightweightState::Normal);
|
||||
refresh_lightweight_tray_state().await;
|
||||
true
|
||||
@@ -189,78 +204,64 @@ pub async fn exit_lightweight_mode() -> bool {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub async fn add_light_weight_timer() {
|
||||
setup_light_weight_timer().await;
|
||||
let generation = TIMER_GENERATION.load(Ordering::Acquire);
|
||||
if auto_light_weight_is_enabled().await {
|
||||
COUNTDOWN.arm(generation);
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_window_close_listener() {
|
||||
WINDOW_CLOSE_LISTENER.setup(|| {
|
||||
std::mem::drop(AsyncHandler::spawn(|| async {
|
||||
setup_light_weight_timer().await;
|
||||
}));
|
||||
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
|
||||
});
|
||||
async fn auto_light_weight_is_enabled() -> bool {
|
||||
let verge = Config::verge().await;
|
||||
// A disable applies before persistence. A rollback restores eligibility for future hides.
|
||||
verge.data_arc().enable_auto_light_weight_mode.unwrap_or(false)
|
||||
&& verge.latest_arc().enable_auto_light_weight_mode.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn cancel_window_close_listener() {
|
||||
WINDOW_CLOSE_LISTENER.cancel();
|
||||
}
|
||||
|
||||
fn setup_webview_focus_listener() {
|
||||
WEBVIEW_FOCUS_LISTENER.setup(|| {
|
||||
cancel_light_weight_timer();
|
||||
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
|
||||
});
|
||||
}
|
||||
|
||||
fn cancel_webview_focus_listener() {
|
||||
WEBVIEW_FOCUS_LISTENER.cancel();
|
||||
}
|
||||
|
||||
async fn setup_light_weight_timer() {
|
||||
let once_by_minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
|
||||
|
||||
let mut cancel_tx_guard = CANCEL_TX.lock();
|
||||
if cancel_tx_guard.is_some() {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Lightweight mode timer already exists, skipping setup"
|
||||
);
|
||||
fn setup_auto_light_weight_listeners(generation: u64) {
|
||||
let mut listeners = WINDOW_LISTENERS.lock();
|
||||
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
|
||||
let (tx, rx) = oneshot::channel::<()>();
|
||||
*cancel_tx_guard = Some(tx);
|
||||
drop(cancel_tx_guard);
|
||||
|
||||
AsyncHandler::spawn(move || async move {
|
||||
tokio::select! {
|
||||
_ = sleep(Duration::from_secs(once_by_minutes.saturating_mul(60))) => {
|
||||
logging!(info, Type::Timer, "Lightweight mode timer expired, entering lightweight mode");
|
||||
{
|
||||
let mut guard = CANCEL_TX.lock();
|
||||
*guard = None;
|
||||
}
|
||||
entry_lightweight_mode().await;
|
||||
}
|
||||
_ = rx => {
|
||||
logging!(debug, Type::Timer, "Received cancel signal, stopping lightweight mode timer");
|
||||
}
|
||||
listeners.close.setup(move || {
|
||||
COUNTDOWN.arm(generation);
|
||||
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
|
||||
});
|
||||
listeners.focus.setup(move || {
|
||||
if generation == TIMER_GENERATION.load(Ordering::Acquire) {
|
||||
COUNTDOWN.disarm();
|
||||
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn prepare_countdown(generation: u64) -> Option<impl Future<Output = Duration>> {
|
||||
// Unlisten can be deferred while Tauri is delivering an event.
|
||||
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(async {
|
||||
let minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"Lightweight mode timer set, entering lightweight mode in {} minutes",
|
||||
minutes
|
||||
);
|
||||
Duration::from_secs(minutes.saturating_mul(60))
|
||||
})
|
||||
}
|
||||
|
||||
fn enter_lightweight_on_timeout(generation: u64) {
|
||||
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"Lightweight mode timer set, entering lightweight mode in {} minutes",
|
||||
once_by_minutes
|
||||
"Lightweight mode timer expired, entering lightweight mode"
|
||||
);
|
||||
}
|
||||
|
||||
fn cancel_light_weight_timer() {
|
||||
let mut cancel_tx_guard = CANCEL_TX.lock();
|
||||
if let Some(tx) = cancel_tx_guard.take() {
|
||||
let _ = tx.send(());
|
||||
logging!(debug, Type::Timer, "Timer cancelled");
|
||||
}
|
||||
begin_lightweight_mode();
|
||||
AsyncHandler::spawn(refresh_lightweight_tray_state);
|
||||
}
|
||||
|
||||
@@ -326,13 +326,6 @@ where
|
||||
start_sidecar().await
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
enum HandoffOutcome {
|
||||
NotReady,
|
||||
Done,
|
||||
Failed,
|
||||
}
|
||||
|
||||
fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error {
|
||||
let error = match service_rejection {
|
||||
Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
|
||||
@@ -688,11 +681,6 @@ impl CoreManager {
|
||||
return result;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
if matches!(*self.get_running_mode(), RunningMode::Sidecar) {
|
||||
self.spawn_service_handoff_watcher().await;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
@@ -883,167 +871,6 @@ impl CoreManager {
|
||||
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
|
||||
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn spawn_service_handoff_watcher(&self) {
|
||||
use crate::constants::timing;
|
||||
use crate::process::AsyncHandler;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Instant;
|
||||
|
||||
// An accepted Sidecar is the user's decision for this session, not a wait for the Service.
|
||||
let needs_service = Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|
||||
&& !crate::core::runstate::RUN_STATE.state().sidecar_allowed;
|
||||
if !needs_service {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.handoff_watcher_running.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service not ready at startup; sidecar active, watching for handoff"
|
||||
);
|
||||
|
||||
AsyncHandler::spawn(|| async move {
|
||||
let manager = Self::global();
|
||||
let started = Instant::now();
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
let attempts = std::num::NonZeroUsize::MIN.saturating_add(
|
||||
(timing::SERVICE_HANDOFF_WINDOW.as_millis() / timing::SERVICE_HANDOFF_INTERVAL.as_millis()) as usize,
|
||||
);
|
||||
let _ = retry(RetryPolicy::fixed(attempts, std::time::Duration::ZERO), |_| async {
|
||||
if started.elapsed() >= timing::SERVICE_HANDOFF_WINDOW {
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service handoff window elapsed; staying in sidecar mode"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
// The window is checked before waiting, including the final handoff attempt.
|
||||
tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await;
|
||||
if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) {
|
||||
return Ok(());
|
||||
}
|
||||
match manager.try_handoff_sidecar_to_service().await {
|
||||
HandoffOutcome::Done => Ok(()),
|
||||
HandoffOutcome::Failed => {
|
||||
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
|
||||
Ok(())
|
||||
}
|
||||
HandoffOutcome::NotReady => Err(RetryError::Retry(())),
|
||||
}
|
||||
})
|
||||
.await;
|
||||
manager.handoff_watcher_running.store(false, Ordering::Release);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn refresh_service_readiness_for_handoff() -> bool {
|
||||
if SERVICE_MANAGER.confirm_ready().await.is_err() {
|
||||
return false;
|
||||
}
|
||||
crate::core::runstate::RUN_STATE.state().service_usable()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tracing::instrument(skip_all, level = "debug", fields(outcome = tracing::field::Empty))]
|
||||
async fn try_handoff_sidecar_to_service(&self) -> HandoffOutcome {
|
||||
// Before probing: a probe reply records an observation, which clears sidecar_allowed.
|
||||
if crate::core::runstate::RUN_STATE.state().sidecar_allowed {
|
||||
return HandoffOutcome::Done;
|
||||
}
|
||||
if !Self::refresh_service_readiness_for_handoff().await {
|
||||
return HandoffOutcome::NotReady;
|
||||
}
|
||||
|
||||
if !self.try_start_config_update() {
|
||||
return HandoffOutcome::NotReady;
|
||||
}
|
||||
let _config_update = DropGuard::new((), |()| {
|
||||
self.finish_config_update();
|
||||
});
|
||||
|
||||
// Lock order is config then lifecycle.
|
||||
let _life = self.lifecycle_lock.lock().await;
|
||||
|
||||
if !matches!(*self.get_running_mode(), RunningMode::Sidecar)
|
||||
|| !Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|
||||
|| crate::core::runstate::RUN_STATE.state().sidecar_allowed
|
||||
{
|
||||
return HandoffOutcome::Done;
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service became ready; handing off from sidecar to service"
|
||||
);
|
||||
if let Err(error) = self.stop_sidecar_after_proxy_clear().await {
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"failed to clear proxy before sidecar handoff: {error:#}"
|
||||
);
|
||||
return HandoffOutcome::Failed;
|
||||
}
|
||||
|
||||
let service_result = run_ready_core_start_transition(
|
||||
|| self.start_core_by_service(),
|
||||
|| {
|
||||
matches!(*self.get_running_mode(), RunningMode::Service)
|
||||
&& self.current_core_readiness_generation().is_some()
|
||||
},
|
||||
|| self.apply_proxy_after_start(),
|
||||
)
|
||||
.await;
|
||||
let Err(service_error) = service_result else {
|
||||
logging!(info, Type::Core, "handoff to service mode succeeded");
|
||||
return HandoffOutcome::Done;
|
||||
};
|
||||
|
||||
logging!(error, Type::Core, "handoff to service failed: {service_error:#}");
|
||||
if let Err(cleanup_error) = self.controlled_stop_core_inner().await {
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"failed to stop service before sidecar fallback: {cleanup_error:#}"
|
||||
);
|
||||
return HandoffOutcome::Failed;
|
||||
}
|
||||
|
||||
let sidecar_result = run_ready_core_start_transition(
|
||||
|| self.start_core_by_sidecar(),
|
||||
|| {
|
||||
matches!(*self.get_running_mode(), RunningMode::Sidecar)
|
||||
&& self.current_core_readiness_generation().is_some()
|
||||
},
|
||||
|| self.apply_proxy_after_start(),
|
||||
)
|
||||
.await;
|
||||
if let Err(sidecar_error) = sidecar_result {
|
||||
logging!(error, Type::Core, "sidecar fallback failed: {sidecar_error:#}");
|
||||
if let Err(cleanup_error) = self.rollback_failed_sidecar_transition().await {
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"failed to clear proxy before sidecar rollback: {cleanup_error:#}"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"sidecar fallback became ready and restored proxy state"
|
||||
);
|
||||
}
|
||||
HandoffOutcome::Failed
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -4,8 +4,8 @@ mod lifecycle;
|
||||
mod state;
|
||||
|
||||
use anyhow::Result;
|
||||
use arc_swap::{ArcSwap, ArcSwapOption};
|
||||
use clash_verge_logging::{LogRing, Type, logging, logging_error};
|
||||
use arc_swap::ArcSwapOption;
|
||||
use clash_verge_logging::{LogRing, Type, logging};
|
||||
use std::{
|
||||
fmt,
|
||||
sync::{
|
||||
@@ -14,12 +14,9 @@ use std::{
|
||||
},
|
||||
time::Instant,
|
||||
};
|
||||
use tauri_plugin_shell::process::CommandChild;
|
||||
|
||||
use crate::core::runstate::{RUN_STATE, RealEnv, RunStateStore};
|
||||
use crate::singleton;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
|
||||
pub(crate) static CLASH_LOGGER: LazyLock<Arc<LogRing>> = LazyLock::new(|| Arc::new(LogRing::new()));
|
||||
|
||||
@@ -89,46 +86,26 @@ pub struct CoreManager {
|
||||
/// A reference rather than the global directly, so a test can supervise a Core without
|
||||
/// racing every other test for one process-wide Running Mode.
|
||||
run_state: &'static RunStateStore<RealEnv>,
|
||||
state: ArcSwap<State>,
|
||||
sidecar: parking_lot::Mutex<state::SidecarSession>,
|
||||
last_update: ArcSwapOption<Instant>,
|
||||
#[cfg(target_os = "windows")]
|
||||
job_handle: ArcSwapOption<OwnedHandle>,
|
||||
config_update_in_progress: AtomicBool,
|
||||
core_readiness_state: AtomicU64,
|
||||
startup_error: parking_lot::Mutex<Option<CoreFailure>>,
|
||||
sidecar_exit: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
// 串行化 start/stop/restart 和 sidecar→service 交接。
|
||||
// 锁序固定为 config_update_in_progress → lifecycle_lock。
|
||||
pub(crate) lifecycle_lock: tokio::sync::Mutex<()>,
|
||||
// sidecar→service 交接 watcher 单实例标志。
|
||||
#[cfg(target_os = "windows")]
|
||||
handoff_watcher_running: AtomicBool,
|
||||
}
|
||||
|
||||
/// Process-level state owned by `CoreManager`.
|
||||
///
|
||||
/// Running Mode deliberately does *not* live here — it belongs to `core::runstate`, which
|
||||
/// keeps it consistent with Service Health and derives PAC availability from it.
|
||||
#[derive(Debug, Default)]
|
||||
struct State {
|
||||
child_sidecar: ArcSwapOption<CommandChild>,
|
||||
}
|
||||
|
||||
impl Default for CoreManager {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
run_state: &RUN_STATE,
|
||||
state: ArcSwap::new(Arc::new(State::default())),
|
||||
sidecar: parking_lot::Mutex::default(),
|
||||
last_update: ArcSwapOption::new(None),
|
||||
#[cfg(target_os = "windows")]
|
||||
job_handle: ArcSwapOption::new(None),
|
||||
config_update_in_progress: AtomicBool::new(false),
|
||||
core_readiness_state: AtomicU64::new(0),
|
||||
startup_error: parking_lot::Mutex::new(None),
|
||||
sidecar_exit: tokio::sync::Mutex::new(None),
|
||||
lifecycle_lock: tokio::sync::Mutex::new(()),
|
||||
#[cfg(target_os = "windows")]
|
||||
handoff_watcher_running: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,18 +139,6 @@ impl CoreManager {
|
||||
self.startup_error.lock().clone()
|
||||
}
|
||||
|
||||
pub fn take_child_sidecar(&self) -> Option<CommandChild> {
|
||||
self.state
|
||||
.load()
|
||||
.child_sidecar
|
||||
.swap(None)
|
||||
.and_then(|arc| Arc::try_unwrap(arc).ok())
|
||||
}
|
||||
|
||||
pub fn get_running_sidecar_pid(&self) -> Option<u32> {
|
||||
self.state.load().child_sidecar.load_full().map(|child| child.pid())
|
||||
}
|
||||
|
||||
pub fn get_last_update(&self) -> Option<Arc<Instant>> {
|
||||
self.last_update.load_full()
|
||||
}
|
||||
@@ -218,11 +183,6 @@ impl CoreManager {
|
||||
self.run_state.core_start_settled();
|
||||
}
|
||||
|
||||
pub fn set_running_child_sidecar(&self, child: CommandChild) {
|
||||
let state = self.state.load();
|
||||
state.child_sidecar.store(Some(Arc::new(child)));
|
||||
}
|
||||
|
||||
fn mark_core_ready(&self) -> u64 {
|
||||
let mut current = self.core_readiness_state.load(Ordering::Acquire);
|
||||
loop {
|
||||
@@ -257,27 +217,14 @@ impl CoreManager {
|
||||
self.last_update.store(Some(Arc::new(time)));
|
||||
}
|
||||
|
||||
/// Replaces the Windows Job Object handle owned by the core manager
|
||||
///
|
||||
/// Passing `None` drops the current handle, which closes the Job Object
|
||||
/// and terminates its assigned processes due to `KILL_ON_JOB_CLOSE`.
|
||||
///
|
||||
/// This method is currently only used on Windows.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn set_job_handle(&self, handle: Option<OwnedHandle>) {
|
||||
self.job_handle.store(handle.map(Arc::new));
|
||||
}
|
||||
|
||||
pub(crate) fn try_start_config_update(&self) -> bool {
|
||||
!self.config_update_in_progress.swap(true, Ordering::AcqRel)
|
||||
}
|
||||
|
||||
pub(crate) fn finish_config_update(&self) {
|
||||
self.config_update_in_progress.store(false, Ordering::Release);
|
||||
// Spawned because the caller may still hold the config write lock this waits for.
|
||||
crate::process::AsyncHandler::spawn(|| async {
|
||||
logging_error!(Type::Config, crate::config::Config::sync_dns_override().await);
|
||||
});
|
||||
// The caller may still hold the config write lock that synchronization needs.
|
||||
crate::config::Config::request_dns_override_sync();
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(retries = 0))]
|
||||
|
||||
@@ -11,11 +11,18 @@ use crate::{
|
||||
};
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_logging::Type;
|
||||
use futures::{
|
||||
FutureExt as _,
|
||||
future::{Map, Shared},
|
||||
};
|
||||
use log::Level;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tauri_plugin_mihomo::MihomoExt as _;
|
||||
use tauri_plugin_shell::ShellExt as _;
|
||||
use tauri_plugin_shell::process::CommandChild;
|
||||
use tokio::task::{JoinError, JoinHandle};
|
||||
|
||||
pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
|
||||
let detail = error.to_string();
|
||||
@@ -130,8 +137,34 @@ where
|
||||
.context("Mihomo API did not become ready")
|
||||
}
|
||||
|
||||
fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool {
|
||||
matches!(running_mode, RunningMode::Sidecar) && current_pid == Some(terminated_pid)
|
||||
fn should_clear_terminated_sidecar(
|
||||
running_mode: &RunningMode,
|
||||
current_generation: Option<u64>,
|
||||
terminated_generation: u64,
|
||||
) -> bool {
|
||||
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
|
||||
}
|
||||
|
||||
type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc<JoinError>>;
|
||||
type SidecarExit = Shared<Map<JoinHandle<()>, ShareExitResult>>;
|
||||
|
||||
fn share_exit(exit: JoinHandle<()>) -> SidecarExit {
|
||||
let share_error: ShareExitResult = |result| result.map_err(Arc::new);
|
||||
exit.map(share_error).shared()
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct SidecarSession {
|
||||
process: Option<SidecarProcess>,
|
||||
exit: Option<SidecarExit>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SidecarProcess {
|
||||
generation: u64,
|
||||
child: CommandChild,
|
||||
#[cfg(target_os = "windows")]
|
||||
job: OwnedHandle,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -218,7 +251,8 @@ impl CoreManager {
|
||||
)
|
||||
})?;
|
||||
let (terminated, termination) = tokio::sync::oneshot::channel();
|
||||
*self.sidecar_exit.lock().await = Some(execution.release_after_exit(child.pid(), termination));
|
||||
let exit = execution.release_after_exit(child.pid(), termination);
|
||||
self.sidecar.lock().exit = Some(share_exit(exit));
|
||||
#[cfg(target_os = "windows")]
|
||||
let job = {
|
||||
match create_and_assign_sidecar_job(child.pid()) {
|
||||
@@ -274,7 +308,7 @@ impl CoreManager {
|
||||
};
|
||||
Logger::global().writer_sidecar_log(Level::Info, &message);
|
||||
CLASH_LOGGER.clear_logs();
|
||||
manager.clear_terminated_sidecar(pid).await;
|
||||
manager.clear_terminated_sidecar(core_readiness_generation).await;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
@@ -302,9 +336,12 @@ impl CoreManager {
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
self.set_job_handle(Some(job));
|
||||
self.set_running_child_sidecar(child);
|
||||
self.sidecar.lock().process = Some(SidecarProcess {
|
||||
generation: core_readiness_generation,
|
||||
child,
|
||||
#[cfg(target_os = "windows")]
|
||||
job,
|
||||
});
|
||||
self.core_started(RunningMode::Sidecar);
|
||||
self.restore_selected_nodes().await;
|
||||
|
||||
@@ -314,18 +351,13 @@ impl CoreManager {
|
||||
/// Terminates the sidecar after its caller has successfully cleared the
|
||||
/// system proxy.
|
||||
pub(super) async fn stop_core_by_sidecar_unprepared(&self) -> Result<()> {
|
||||
if let Some(child) = self.take_child_sidecar() {
|
||||
let pid = child.pid();
|
||||
|
||||
let process = self.sidecar.lock().process.take();
|
||||
if let Some(process) = process {
|
||||
let pid = process.child.pid();
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// Setting the job handle to None clears the stored handle and
|
||||
// closes the previous Windows job handle in `set_job_handle`.
|
||||
self.set_job_handle(None);
|
||||
let _ = pid;
|
||||
}
|
||||
drop(process.job);
|
||||
|
||||
if let Err(error) = child.kill() {
|
||||
if let Err(error) = process.child.kill() {
|
||||
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
|
||||
}
|
||||
}
|
||||
@@ -335,15 +367,15 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
async fn wait_for_sidecar_exit(&self) -> Result<()> {
|
||||
let mut exit = self.sidecar_exit.lock().await;
|
||||
if let Some(task) = exit.as_mut() {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), task)
|
||||
// The lifecycle lock serializes callers. Keep a receipt in the session across timeouts.
|
||||
let exit = self.sidecar.lock().exit.clone();
|
||||
if let Some(exit) = exit {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), exit)
|
||||
.await
|
||||
.context("Sidecar has not exited; core handoff is blocked")?
|
||||
.context("Sidecar exit monitoring failed")?;
|
||||
exit.take();
|
||||
self.sidecar.lock().exit.take();
|
||||
}
|
||||
drop(exit);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -392,15 +424,17 @@ impl CoreManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn clear_terminated_sidecar(&self, terminated_pid: u32) {
|
||||
async fn clear_terminated_sidecar(&self, terminated_generation: u64) {
|
||||
let _life = self.lifecycle_lock.lock().await;
|
||||
if !should_clear_terminated_sidecar(&self.get_running_mode(), self.get_running_sidecar_pid(), terminated_pid) {
|
||||
return;
|
||||
}
|
||||
|
||||
let _ = self.take_child_sidecar();
|
||||
#[cfg(target_os = "windows")]
|
||||
self.set_job_handle(None);
|
||||
let process = {
|
||||
let mut session = self.sidecar.lock();
|
||||
let current = session.process.as_ref().map(|process| process.generation);
|
||||
if !should_clear_terminated_sidecar(&self.get_running_mode(), current, terminated_generation) {
|
||||
return;
|
||||
}
|
||||
session.process.take()
|
||||
};
|
||||
drop(process);
|
||||
proxy_control::stop_guard().await;
|
||||
self.core_stopped();
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -3,13 +3,25 @@
|
||||
//! 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::AsyncHandler,
|
||||
};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_task::scheduled_task::{self, CoalescingJob};
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::LazyLock;
|
||||
use sysproxy::NetworkServiceMonitor;
|
||||
|
||||
static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None);
|
||||
|
||||
static REAPPLY: LazyLock<CoalescingJob> = LazyLock::new(|| {
|
||||
AsyncHandler::start_driver(scheduled_task::coalescing(reapply, || {
|
||||
logging!(error, Type::Core, "network proxy reapply panicked");
|
||||
}))
|
||||
});
|
||||
|
||||
pub fn is_armed() -> bool {
|
||||
MONITOR.lock().is_some()
|
||||
}
|
||||
@@ -18,7 +30,7 @@ pub fn is_armed() -> bool {
|
||||
/// appearing from here on is never missed.
|
||||
pub fn start() {
|
||||
match NetworkServiceMonitor::start(|| {
|
||||
AsyncHandler::spawn(reapply);
|
||||
REAPPLY.request();
|
||||
}) {
|
||||
Ok(monitor) => {
|
||||
*MONITOR.lock() = Some(monitor);
|
||||
|
||||
@@ -18,13 +18,20 @@ use crate::{
|
||||
use anyhow::{Result, ensure};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome};
|
||||
use clash_verge_task::watch_task;
|
||||
use std::{
|
||||
borrow::Borrow,
|
||||
future::Future,
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
sync::{
|
||||
Arc, LazyLock, Once,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{sync::Mutex, time::timeout};
|
||||
use tokio::{
|
||||
sync::{Mutex, watch},
|
||||
time::timeout,
|
||||
};
|
||||
|
||||
const CLEAR_ATTEMPTS: u32 = 3;
|
||||
const CLEAR_RETRY_DELAY: Duration = Duration::from_millis(100);
|
||||
@@ -215,23 +222,40 @@ const fn refusal_classification(service_usable: Option<bool>) -> SysproxyFailure
|
||||
const LOOPBACK_HOST: &str = "127.0.0.1";
|
||||
const MAX_SERVICE_BYPASS_LEN: usize = 8192;
|
||||
|
||||
static SERVICE_PROXY_OPERATIONS: ServiceProxyOperations = ServiceProxyOperations::new();
|
||||
static SERVICE_PROXY_OPERATIONS: LazyLock<ServiceProxyOperations> = LazyLock::new(ServiceProxyOperations::new);
|
||||
|
||||
struct ServiceProxyOperations {
|
||||
guard: watch::Sender<Option<Arc<ServiceGuard>>>,
|
||||
guard_generation: AtomicU64,
|
||||
operation_lock: Mutex<()>,
|
||||
}
|
||||
|
||||
impl ServiceProxyOperations {
|
||||
const fn new() -> Self {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
guard: watch::channel(None).0,
|
||||
guard_generation: AtomicU64::new(0),
|
||||
operation_lock: Mutex::const_new(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_guard(&self) -> u64 {
|
||||
self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1)
|
||||
let mut generation = 0;
|
||||
self.guard.send_if_modified(|active| {
|
||||
generation = self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1);
|
||||
active.take().is_some()
|
||||
});
|
||||
generation
|
||||
}
|
||||
|
||||
fn start_guard(&self, guard: ServiceGuard) -> bool {
|
||||
self.guard.send_if_modified(|active| {
|
||||
if !guard_generation_is_current(&self.guard_generation, guard.generation) {
|
||||
return false;
|
||||
}
|
||||
*active = Some(Arc::new(guard));
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
async fn run_service_operation<F, Fut, T>(&self, operation: F) -> T
|
||||
@@ -606,51 +630,90 @@ pub async fn refresh_guard() -> Result<()> {
|
||||
let proxy = current_service_proxy_config(&verge).await?;
|
||||
let proof = service::active_service_session()?;
|
||||
let interval = Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30).max(1));
|
||||
AsyncHandler::spawn(move || async move {
|
||||
let mut consecutive_failures = 0u32;
|
||||
loop {
|
||||
tokio::time::sleep(interval).await;
|
||||
match SERVICE_PROXY_OPERATIONS
|
||||
.run_guard_request(
|
||||
generation,
|
||||
&proof,
|
||||
&proxy,
|
||||
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
|
||||
service::active_service_session,
|
||||
|| service::set_system_proxy_by_service_with_session(&proxy, &proof),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(true) => consecutive_failures = 0,
|
||||
Ok(false) => {
|
||||
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
|
||||
break;
|
||||
}
|
||||
Err(error) if is_missing_network_service_failure(&error) => {
|
||||
consecutive_failures = 0;
|
||||
logging!(debug, Type::Core, "system proxy guard waits for a network service");
|
||||
}
|
||||
Err(error) => {
|
||||
consecutive_failures += 1;
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}",
|
||||
consecutive_failures,
|
||||
GUARD_FAILURES_BEFORE_STOPPING,
|
||||
error
|
||||
);
|
||||
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
|
||||
report_guard_stopped(generation, &error).await;
|
||||
break;
|
||||
}
|
||||
static START_GUARD_MONITOR: Once = Once::new();
|
||||
START_GUARD_MONITOR.call_once(|| {
|
||||
let receiver = SERVICE_PROXY_OPERATIONS.guard.subscribe();
|
||||
AsyncHandler::spawn(move || {
|
||||
watch_task::run(receiver, monitor_guard, |guard| {
|
||||
let generation = guard.generation;
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"service proxy guard panicked (generation {generation})"
|
||||
);
|
||||
})
|
||||
});
|
||||
});
|
||||
if SERVICE_PROXY_OPERATIONS.start_guard(ServiceGuard {
|
||||
generation,
|
||||
proof,
|
||||
proxy,
|
||||
interval,
|
||||
}) {
|
||||
notification::retire_guard_failures();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ServiceGuard {
|
||||
generation: u64,
|
||||
proof: Arc<OwnerSessionProof>,
|
||||
proxy: MacosProxyConfig,
|
||||
interval: Duration,
|
||||
}
|
||||
|
||||
async fn monitor_guard(guard: Arc<ServiceGuard>, mut updates: watch::Receiver<Option<Arc<ServiceGuard>>>) {
|
||||
let ServiceGuard {
|
||||
generation,
|
||||
proof,
|
||||
proxy,
|
||||
interval,
|
||||
} = guard.as_ref();
|
||||
let mut consecutive_failures = 0u32;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = updates.changed() => return,
|
||||
() = tokio::time::sleep(*interval) => {}
|
||||
}
|
||||
|
||||
match SERVICE_PROXY_OPERATIONS
|
||||
.run_guard_request(
|
||||
*generation,
|
||||
proof,
|
||||
proxy,
|
||||
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
|
||||
service::active_service_session,
|
||||
|| service::set_system_proxy_by_service_with_session(proxy, proof),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(true) => consecutive_failures = 0,
|
||||
Ok(false) => {
|
||||
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
|
||||
return;
|
||||
}
|
||||
Err(error) if is_missing_network_service_failure(&error) => {
|
||||
consecutive_failures = 0;
|
||||
logging!(debug, Type::Core, "system proxy guard waits for a network service");
|
||||
}
|
||||
Err(error) => {
|
||||
consecutive_failures += 1;
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}",
|
||||
consecutive_failures,
|
||||
GUARD_FAILURES_BEFORE_STOPPING,
|
||||
error
|
||||
);
|
||||
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
|
||||
report_guard_stopped(*generation, &error).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
// Retire only after the replacement guard starts successfully.
|
||||
notification::retire_guard_failures();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
const GUARD_FAILURES_BEFORE_STOPPING: u32 = 3;
|
||||
|
||||
@@ -93,9 +93,7 @@ impl RunStateEnv for RealEnv {
|
||||
|
||||
fn publish(&self, state: &RunState) {
|
||||
// Reconciliation must run before the app handle exists and must not block this transition.
|
||||
crate::process::AsyncHandler::spawn(|| async {
|
||||
crate::feat::reconcile_tun_availability().await;
|
||||
});
|
||||
crate::feat::request_tun_reconciliation();
|
||||
|
||||
let Some(app_handle) = crate::APP_HANDLE.get() else {
|
||||
return;
|
||||
|
||||
@@ -9,10 +9,7 @@ mod owner;
|
||||
mod probe;
|
||||
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, LazyLock,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
sync::{Arc, LazyLock},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
@@ -57,6 +54,7 @@ impl std::fmt::Display for ReadyWaitError {
|
||||
#[derive(Debug, Default)]
|
||||
struct VersionedService {
|
||||
service: StoredService,
|
||||
operation_running: bool,
|
||||
generation: u64,
|
||||
observation: u64,
|
||||
}
|
||||
@@ -79,7 +77,6 @@ pub struct RunStateStore<E: RunStateEnv> {
|
||||
env: E,
|
||||
service: Mutex<VersionedService>,
|
||||
mode: ArcSwap<RunningMode>,
|
||||
operation_running: AtomicBool,
|
||||
operation_done: Notify,
|
||||
}
|
||||
|
||||
@@ -89,7 +86,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
env,
|
||||
service: Mutex::new(VersionedService::default()),
|
||||
mode: ArcSwap::new(Arc::new(RunningMode::NotRunning)),
|
||||
operation_running: AtomicBool::new(false),
|
||||
operation_done: Notify::new(),
|
||||
}
|
||||
}
|
||||
@@ -97,8 +93,18 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
/// The last known Run State, without waiting and without probing.
|
||||
/// It reports when a privileged operation may make the snapshot stale.
|
||||
pub fn state(&self) -> RunState {
|
||||
let service = self.service.lock().service.clone();
|
||||
self.snapshot(service)
|
||||
let (service, op_in_flight) = {
|
||||
let state = self.service.lock();
|
||||
(state.service.clone(), state.operation_running)
|
||||
};
|
||||
RunState {
|
||||
health: service.health,
|
||||
pending: service.pending,
|
||||
sidecar_allowed: service.sidecar_allowed,
|
||||
mode: *self.mode.load().as_ref(),
|
||||
is_admin: self.env.is_elevated(),
|
||||
op_in_flight,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns one snapshot taken after any operation visible in that snapshot has settled.
|
||||
@@ -309,7 +315,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
/// Accepts Sidecar only while the Service is unusable and no conflicting operation is active.
|
||||
pub fn allow_sidecar_for_session(&self) -> Result<()> {
|
||||
let mut state = self.service.lock();
|
||||
if self.operation_running.load(Ordering::Acquire) {
|
||||
if state.operation_running {
|
||||
bail!("service operation already running");
|
||||
}
|
||||
let permitted = match (state.service.pending, state.service.sidecar_allowed) {
|
||||
@@ -333,7 +339,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn allow_sidecar_after_service_refusal(&self, reason: String) -> Result<()> {
|
||||
let mut state = self.service.lock();
|
||||
if self.operation_running.load(Ordering::Acquire) || state.service.pending.is_some() {
|
||||
if state.operation_running || state.service.pending.is_some() {
|
||||
bail!("cannot fall back while a service operation is pending");
|
||||
}
|
||||
// Publish the refusal and allowance together so it never asks the UI for a repair.
|
||||
@@ -348,7 +354,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
/// Requests installation only for a confirmed absent Service.
|
||||
pub fn require_install_for_session(&self) -> Result<()> {
|
||||
let mut state = self.service.lock();
|
||||
if self.operation_running.load(Ordering::Acquire) {
|
||||
if state.operation_running {
|
||||
bail!("service operation already running");
|
||||
}
|
||||
if state.service.pending.is_none()
|
||||
@@ -427,9 +433,10 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
/// Only one privileged operation may be in flight; [`Self::settled`] waits on this.
|
||||
pub fn begin_operation(&self) -> Result<OperationGuard<'_, E>> {
|
||||
let mut state = self.service.lock();
|
||||
if self.operation_running.swap(true, Ordering::AcqRel) {
|
||||
if state.operation_running {
|
||||
bail!("service operation already running");
|
||||
}
|
||||
state.operation_running = true;
|
||||
state.bump();
|
||||
drop(state);
|
||||
self.announce();
|
||||
@@ -438,7 +445,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn operation_in_flight(&self) -> bool {
|
||||
self.operation_running.load(Ordering::Acquire)
|
||||
self.service.lock().operation_running
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -455,17 +462,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
fn announce(&self) {
|
||||
self.env.publish(&self.state());
|
||||
}
|
||||
|
||||
fn snapshot(&self, service: StoredService) -> RunState {
|
||||
RunState {
|
||||
health: service.health,
|
||||
pending: service.pending,
|
||||
sidecar_allowed: service.sidecar_allowed,
|
||||
mode: *self.mode.load().as_ref(),
|
||||
is_admin: self.env.is_elevated(),
|
||||
op_in_flight: self.operation_running.load(Ordering::Acquire),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases the privileged-operation slot and wakes everything waiting in [`RunStateStore::settled`].
|
||||
@@ -476,7 +472,7 @@ pub struct OperationGuard<'a, E: RunStateEnv> {
|
||||
|
||||
impl<E: RunStateEnv> Drop for OperationGuard<'_, E> {
|
||||
fn drop(&mut self) {
|
||||
self.store.operation_running.store(false, Ordering::Release);
|
||||
self.store.service.lock().operation_running = false;
|
||||
self.store.operation_done.notify_waiters();
|
||||
self.store.announce();
|
||||
}
|
||||
|
||||
+146
-101
@@ -26,9 +26,9 @@ use clash_verge_service_ipc::{
|
||||
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
|
||||
StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||
};
|
||||
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
||||
use clash_verge_task::watch_task;
|
||||
use parking_lot::Mutex;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::sync::LazyLock;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
env::current_exe,
|
||||
@@ -36,11 +36,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 +839,85 @@ 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(|| {
|
||||
AsyncHandler::start_driver(scheduled_task::new(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);
|
||||
}
|
||||
|
||||
let retry_attempt = self
|
||||
.retry
|
||||
.take_if(|(due, _)| *due <= now)
|
||||
.map_or(1, |(_, attempt)| attempt);
|
||||
let fresh_request = self.requested.take_if(|due| *due <= now).is_some();
|
||||
Next::Run(if fresh_request { 1 } else { retry_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"
|
||||
);
|
||||
self.retry = Some((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 +1474,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 +1625,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 {
|
||||
|
||||
@@ -6,13 +6,9 @@ use crate::{
|
||||
};
|
||||
use anyhow::Result;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use parking_lot::RwLock;
|
||||
use std::{
|
||||
mem::DropGuard,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
use sysproxy::{Autoproxy, GuardMonitor, GuardType, Sysproxy};
|
||||
@@ -243,18 +239,16 @@ async fn current_os_proxy_state(sys: Sysproxy, auto: Autoproxy) -> OsProxyState
|
||||
pub(crate) struct Sysopt {
|
||||
// Owns the proxy target pair; every reader and writer goes through this lock.
|
||||
proxy_state_lock: TokioMutex<(Sysproxy, Autoproxy)>,
|
||||
guard_operation_lock: TokioMutex<()>,
|
||||
reset_sysproxy: AtomicBool,
|
||||
guard: Arc<RwLock<GuardMonitor>>,
|
||||
guard: TokioMutex<GuardMonitor>,
|
||||
}
|
||||
|
||||
impl Default for Sysopt {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
proxy_state_lock: TokioMutex::new((Sysproxy::default(), Autoproxy::default())),
|
||||
guard_operation_lock: TokioMutex::new(()),
|
||||
reset_sysproxy: AtomicBool::new(false),
|
||||
guard: Arc::new(RwLock::new(GuardMonitor::new(GuardType::None, Duration::from_secs(30)))),
|
||||
guard: TokioMutex::new(GuardMonitor::new(GuardType::None, Duration::from_secs(30))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -295,14 +289,9 @@ impl Sysopt {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn access_guard(&self) -> Arc<RwLock<GuardMonitor>> {
|
||||
Arc::clone(&self.guard)
|
||||
}
|
||||
|
||||
/// Stop the guard and return whether it drained.
|
||||
async fn stop_proxy_guard_locked(&self) -> bool {
|
||||
// Drop the parking_lot read guard before awaiting.
|
||||
let idle = self.access_guard().read().shutdown();
|
||||
async fn drain_guard(guard: &GuardMonitor) -> bool {
|
||||
let idle = guard.shutdown();
|
||||
let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await;
|
||||
if !drained {
|
||||
logging!(
|
||||
@@ -316,23 +305,23 @@ impl Sysopt {
|
||||
|
||||
/// Stop the guard before handing OS proxy ownership elsewhere.
|
||||
pub(super) async fn stop_proxy_guard(&self) -> bool {
|
||||
let _operation = self.guard_operation_lock.lock().await;
|
||||
self.stop_proxy_guard_locked().await
|
||||
let guard = self.guard.lock().await;
|
||||
Self::drain_guard(&guard).await
|
||||
}
|
||||
|
||||
/// Reconcile guard state with configuration and report success.
|
||||
pub(super) async fn refresh_guard(&self) -> bool {
|
||||
logging!(info, Type::Core, "Refreshing system proxy guard...");
|
||||
let verge = Config::verge().await.latest_arc();
|
||||
let _operation = self.guard_operation_lock.lock().await;
|
||||
let mut guard = self.guard.lock().await;
|
||||
if !verge.enable_system_proxy.unwrap_or_default() {
|
||||
logging!(info, Type::Core, "System proxy is disabled.");
|
||||
let _drained = self.stop_proxy_guard_locked().await;
|
||||
let _drained = Self::drain_guard(&guard).await;
|
||||
return true;
|
||||
}
|
||||
if !verge.enable_proxy_guard.unwrap_or_default() {
|
||||
logging!(info, Type::Core, "System proxy guard is disabled.");
|
||||
let _drained = self.stop_proxy_guard_locked().await;
|
||||
let _drained = Self::drain_guard(&guard).await;
|
||||
return true;
|
||||
}
|
||||
logging!(
|
||||
@@ -341,52 +330,27 @@ impl Sysopt {
|
||||
"Updating system proxy with duration: {} seconds",
|
||||
verge.proxy_guard_duration.unwrap_or(30)
|
||||
);
|
||||
{
|
||||
let guard = self.access_guard();
|
||||
guard
|
||||
.write()
|
||||
.set_interval(Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30)));
|
||||
}
|
||||
guard.set_interval(Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30)));
|
||||
logging!(info, Type::Core, "Starting system proxy guard...");
|
||||
{
|
||||
let guard = self.access_guard();
|
||||
if !guard.read().start() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"the system proxy guard refused to start; a previous run has not finished"
|
||||
);
|
||||
}
|
||||
if !guard.start() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"the system proxy guard refused to start; a previous run has not finished"
|
||||
);
|
||||
}
|
||||
while self.access_guard().read().get_state().is_pendding() {
|
||||
while guard.get_state().is_pendding() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
// `start()` false may also mean a guard was already running.
|
||||
!self.access_guard().read().get_state().is_stopped()
|
||||
}
|
||||
|
||||
/// Recover OS and guard state after a failed write.
|
||||
async fn recover_from_failed_write(
|
||||
&self,
|
||||
error: anyhow::Error,
|
||||
earlier_step_completed: bool,
|
||||
guard_was_running: bool,
|
||||
off: (Sysproxy, Autoproxy),
|
||||
) -> anyhow::Error {
|
||||
recover_from_failed_write(
|
||||
error,
|
||||
earlier_step_completed,
|
||||
|state| self.recover_guard_after_failure(state, guard_was_running),
|
||||
|| disable_all_proxies(off.0, off.1),
|
||||
)
|
||||
.await
|
||||
!guard.get_state().is_stopped()
|
||||
}
|
||||
|
||||
/// Reconcile the guard with the authoritative state.
|
||||
fn recover_guard_after_failure(&self, state: AuthoritativeState, was_running: bool) {
|
||||
fn recover_guard_after_failure(guard: &mut GuardMonitor, state: AuthoritativeState, was_running: bool) {
|
||||
match state {
|
||||
AuthoritativeState::Unchanged if was_running => {
|
||||
let restarted = self.access_guard().read().start();
|
||||
let restarted = guard.start();
|
||||
if !restarted {
|
||||
logging!(
|
||||
warn,
|
||||
@@ -397,7 +361,7 @@ impl Sysopt {
|
||||
}
|
||||
AuthoritativeState::Unchanged => {}
|
||||
AuthoritativeState::Unknown => {
|
||||
self.access_guard().write().set_guard_type(GuardType::None);
|
||||
guard.set_guard_type(GuardType::None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -465,11 +429,11 @@ impl Sysopt {
|
||||
(sys.clone(), auto.clone(), guard_type)
|
||||
};
|
||||
|
||||
let _guard_operation = self.guard_operation_lock.lock().await;
|
||||
let mut guard = self.guard.lock().await;
|
||||
|
||||
// Drain the guard before any OS read or write.
|
||||
let guard_was_running = !self.access_guard().read().get_state().is_stopped();
|
||||
let idle = self.access_guard().read().shutdown();
|
||||
let guard_was_running = !guard.get_state().is_stopped();
|
||||
let idle = guard.shutdown();
|
||||
let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await;
|
||||
|
||||
// A slow guard does not stop the write, but it does make the OS read untrustworthy.
|
||||
@@ -477,7 +441,7 @@ impl Sysopt {
|
||||
&& drained
|
||||
&& current_os_proxy_state(sys.clone(), auto.clone()).await == OsProxyState::AlreadyApplied
|
||||
{
|
||||
self.access_guard().write().set_guard_type(guard_type);
|
||||
guard.set_guard_type(guard_type);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -508,24 +472,25 @@ impl Sysopt {
|
||||
})
|
||||
.await;
|
||||
|
||||
match applied {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err((earlier_step_completed, error))) => {
|
||||
return Err(self
|
||||
.recover_from_failed_write(error, earlier_step_completed, guard_was_running, compensation)
|
||||
.await);
|
||||
let (earlier_step_completed, error) = match applied {
|
||||
Ok(Ok(())) => {
|
||||
guard.set_guard_type(guard_type);
|
||||
return Ok(());
|
||||
}
|
||||
Err(join_error) => {
|
||||
let error = anyhow::Error::from(join_error).context("the system proxy write task did not finish");
|
||||
return Err(self
|
||||
.recover_from_failed_write(error, false, guard_was_running, compensation)
|
||||
.await);
|
||||
}
|
||||
}
|
||||
Ok(Err(failure)) => failure,
|
||||
Err(error) => (
|
||||
false,
|
||||
anyhow::Error::from(error).context("the system proxy write task did not finish"),
|
||||
),
|
||||
};
|
||||
|
||||
// Never point the guard at a target that failed to reach the OS.
|
||||
self.access_guard().write().set_guard_type(guard_type);
|
||||
Ok(())
|
||||
Err(recover_from_failed_write(
|
||||
error,
|
||||
earlier_step_completed,
|
||||
|state| Self::recover_guard_after_failure(&mut guard, state, guard_was_running),
|
||||
|| disable_all_proxies(compensation.0, compensation.1),
|
||||
)
|
||||
.await)
|
||||
}
|
||||
|
||||
/// reset the sysproxy
|
||||
@@ -545,8 +510,8 @@ impl Sysopt {
|
||||
self.reset_sysproxy.store(false, Ordering::SeqCst);
|
||||
});
|
||||
let mut proxy_state = self.proxy_state_lock.lock().await;
|
||||
let _guard_operation = self.guard_operation_lock.lock().await;
|
||||
let drained = self.stop_proxy_guard_locked().await;
|
||||
let guard = self.guard.lock().await;
|
||||
let drained = Self::drain_guard(&guard).await;
|
||||
|
||||
// 直接关闭所有代理
|
||||
let (sys, auto) = {
|
||||
@@ -567,7 +532,7 @@ impl Sysopt {
|
||||
disable_until_the_last_write_is_ours(
|
||||
drained,
|
||||
|| disable_all_proxies(sys.clone(), auto.clone()),
|
||||
|| self.stop_proxy_guard_locked(),
|
||||
|| Self::drain_guard(&guard),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
+86
-189
@@ -1,32 +1,26 @@
|
||||
use crate::{
|
||||
config::{Config, PrfItem},
|
||||
config::{Config, IProfiles, PrfItem},
|
||||
feat,
|
||||
process::AsyncHandler,
|
||||
singleton,
|
||||
utils::resolve::is_resolve_done,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use futures::StreamExt as _;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use futures::{FutureExt as _, StreamExt as _};
|
||||
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
|
||||
use tokio::{
|
||||
sync::mpsc,
|
||||
sync::{mpsc, oneshot},
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
use tokio_util::time::{DelayQueue, delay_queue::Key};
|
||||
use tristr::alias::String;
|
||||
|
||||
enum TimerCommand {
|
||||
Apply(HashMap<String, TaskSchedule>),
|
||||
RunNow(String),
|
||||
Initialize(oneshot::Sender<()>),
|
||||
Refresh(oneshot::Sender<()>),
|
||||
NextUpdateTime(String, oneshot::Sender<Option<i64>>),
|
||||
TaskFinished(String),
|
||||
}
|
||||
|
||||
@@ -70,19 +64,19 @@ 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();
|
||||
}
|
||||
|
||||
impl TaskState {
|
||||
const fn new(key: Key, interval_minutes: u64) -> Self {
|
||||
const fn new(key: Option<Key>, interval_minutes: u64) -> Self {
|
||||
Self {
|
||||
key: Some(key),
|
||||
key,
|
||||
interval_minutes,
|
||||
running: false,
|
||||
retired: false,
|
||||
@@ -92,10 +86,6 @@ impl TaskState {
|
||||
|
||||
pub struct Timer {
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
command_rx: Mutex<Option<mpsc::UnboundedReceiver<TimerCommand>>>,
|
||||
refresh_lock: tokio::sync::Mutex<()>,
|
||||
pub timer_map: Arc<RwLock<HashMap<String, u64>>>,
|
||||
pub initialized: AtomicBool,
|
||||
}
|
||||
|
||||
singleton!(Timer, TIMER_INSTANCE);
|
||||
@@ -103,115 +93,31 @@ singleton!(Timer, TIMER_INSTANCE);
|
||||
impl Timer {
|
||||
fn new() -> Self {
|
||||
let (command_tx, command_rx) = mpsc::unbounded_channel();
|
||||
Self {
|
||||
command_tx,
|
||||
command_rx: Mutex::new(Some(command_rx)),
|
||||
refresh_lock: tokio::sync::Mutex::new(()),
|
||||
timer_map: Arc::new(RwLock::new(HashMap::new())),
|
||||
initialized: AtomicBool::new(false),
|
||||
}
|
||||
let scheduler_tx = command_tx.clone();
|
||||
AsyncHandler::spawn(move || async move {
|
||||
let profiles = Config::profiles().await;
|
||||
Self::run_scheduler(command_rx, scheduler_tx, profiles).await;
|
||||
});
|
||||
Self { command_tx }
|
||||
}
|
||||
|
||||
pub async fn init(&self) -> Result<()> {
|
||||
if self
|
||||
.initialized
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
logging!(debug, Type::Timer, "Timer already initialized, skipping...");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let command_rx = { self.command_rx.lock().take() };
|
||||
if let Some(command_rx) = command_rx {
|
||||
let command_tx = self.command_tx.clone();
|
||||
AsyncHandler::spawn(move || async move {
|
||||
Self::run_scheduler(command_rx, command_tx).await;
|
||||
});
|
||||
}
|
||||
|
||||
if let Err(e) = self.refresh().await {
|
||||
self.initialized.store(false, Ordering::SeqCst);
|
||||
logging!(error, Type::Timer, "Failed to initialize timer: {e:#}");
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
{
|
||||
let timer_map = self.timer_map.read();
|
||||
logging!(debug, Type::Timer, "Registered timer task count: {}", timer_map.len());
|
||||
for (uid, interval) in timer_map.iter() {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Registered timer task: uid={}, interval={}min",
|
||||
uid,
|
||||
interval
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Redundant with first_delay == ZERO, kept as the immediate path; mark_task_running
|
||||
// no-ops whichever of the two arrives second.
|
||||
let cur_timestamp = chrono::Local::now().timestamp();
|
||||
if let Some(items) = Config::profiles().await.data_arc().items.as_ref() {
|
||||
for item in items.iter() {
|
||||
if let Some(option) = item.option.as_ref()
|
||||
&& option.allow_auto_update.unwrap_or(true)
|
||||
&& let Some(interval) = option.update_interval
|
||||
&& interval > 0
|
||||
&& let Some(uid) = item.uid.as_ref()
|
||||
&& let Some(updated) = item.updated
|
||||
&& cur_timestamp - (updated as i64) >= (interval as i64) * 60
|
||||
{
|
||||
logging!(info, Type::Timer, "Running overdue timer task immediately: uid={}", uid);
|
||||
let _ = self.command_tx.send(TimerCommand::RunNow(uid.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logging!(info, Type::Timer, "Timer initialization completed");
|
||||
Ok(())
|
||||
self.update_schedule(TimerCommand::Initialize).await
|
||||
}
|
||||
|
||||
pub async fn refresh(&self) -> Result<()> {
|
||||
let _refresh_guard = self.refresh_lock.lock().await;
|
||||
let new_schedule = self.gen_map().await;
|
||||
// Cache intervals only: first_delay shrinks every second, so comparing it would make
|
||||
// every refresh look like a change.
|
||||
let new_map: HashMap<String, u64> = new_schedule
|
||||
.iter()
|
||||
.map(|(uid, schedule)| (uid.clone(), schedule.interval_minutes))
|
||||
.collect();
|
||||
|
||||
let mut cache = self.timer_map.write();
|
||||
if *cache == new_map {
|
||||
logging!(debug, Type::Timer, "No timer changes needed");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"Refreshing timer tasks map, count: {}",
|
||||
new_map.len()
|
||||
);
|
||||
*cache = new_map;
|
||||
drop(cache);
|
||||
|
||||
let _ = self.command_tx.send(TimerCommand::Apply(new_schedule));
|
||||
|
||||
Ok(())
|
||||
self.update_schedule(TimerCommand::Refresh).await
|
||||
}
|
||||
|
||||
async fn gen_map(&self) -> HashMap<String, TaskSchedule> {
|
||||
if let Some(items) = Config::profiles().await.data_arc().items.as_ref() {
|
||||
return Self::gen_map_from_items(items);
|
||||
}
|
||||
|
||||
HashMap::new()
|
||||
async fn update_schedule(&self, command: fn(oneshot::Sender<()>) -> TimerCommand) -> Result<()> {
|
||||
let (reply, done) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(command(reply))
|
||||
.context("profile timer scheduler stopped")?;
|
||||
done.await.context("profile timer scheduler stopped")
|
||||
}
|
||||
|
||||
fn gen_map_from_items(items: &[PrfItem]) -> HashMap<String, TaskSchedule> {
|
||||
fn gen_map_from_items(items: &[PrfItem], initializing: bool) -> HashMap<String, TaskSchedule> {
|
||||
let now = chrono::Local::now().timestamp();
|
||||
let mut new_map = HashMap::new();
|
||||
|
||||
@@ -221,7 +127,12 @@ impl Timer {
|
||||
&& option.allow_auto_update.unwrap_or(true)
|
||||
&& interval > 0
|
||||
{
|
||||
new_map.insert(uid.clone(), TaskSchedule::new(interval, item.updated, now));
|
||||
let mut schedule = TaskSchedule::new(interval, item.updated, now);
|
||||
// Startup historically treats an explicit zero timestamp as overdue.
|
||||
if initializing && item.updated == Some(0) {
|
||||
schedule.first_delay = Duration::ZERO;
|
||||
}
|
||||
new_map.insert(uid.clone(), schedule);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -231,24 +142,50 @@ impl Timer {
|
||||
async fn run_scheduler(
|
||||
mut command_rx: mpsc::UnboundedReceiver<TimerCommand>,
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
profiles: Draft<IProfiles>,
|
||||
) {
|
||||
let mut queue = DelayQueue::new();
|
||||
let mut tasks = HashMap::new();
|
||||
let mut initialized = false;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
Some(expired) = queue.next() => {
|
||||
Some(expired) = queue.next(), if initialized => {
|
||||
let uid = expired.into_inner();
|
||||
Self::run_expired_task(&mut tasks, uid, command_tx.clone());
|
||||
}
|
||||
|
||||
command = command_rx.recv() => {
|
||||
match command {
|
||||
Some(TimerCommand::Apply(new_map)) => {
|
||||
Self::apply_timer_map(&mut queue, &mut tasks, new_map);
|
||||
Some(TimerCommand::Initialize(reply)) => {
|
||||
if !initialized {
|
||||
// Pre-init refreshes are queryable. Start from the current
|
||||
// timestamps when the queue first becomes eligible to fire.
|
||||
let profiles = profiles.data_arc();
|
||||
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), true);
|
||||
tasks.clear();
|
||||
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
|
||||
initialized = true;
|
||||
logging!(info, Type::Timer, "Timer initialization completed");
|
||||
}
|
||||
let _ = reply.send(());
|
||||
}
|
||||
Some(TimerCommand::RunNow(uid)) => {
|
||||
Self::run_task_now(&mut queue, &mut tasks, uid, command_tx.clone());
|
||||
Some(TimerCommand::Refresh(reply)) => {
|
||||
let profiles = profiles.data_arc();
|
||||
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), false);
|
||||
if initialized {
|
||||
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
|
||||
} else {
|
||||
tasks = schedule
|
||||
.into_iter()
|
||||
.map(|(uid, schedule)| (uid, TaskState::new(None, schedule.interval_minutes)))
|
||||
.collect();
|
||||
}
|
||||
let _ = reply.send(());
|
||||
}
|
||||
Some(TimerCommand::NextUpdateTime(uid, reply)) => {
|
||||
let next = Self::next_update_time(&tasks, &profiles.latest_arc(), &uid);
|
||||
let _ = reply.send(next);
|
||||
}
|
||||
Some(TimerCommand::TaskFinished(uid)) => {
|
||||
Self::finish_task(&mut queue, &mut tasks, uid);
|
||||
@@ -321,7 +258,7 @@ impl Timer {
|
||||
schedule.interval_minutes,
|
||||
schedule.first_delay.as_secs()
|
||||
);
|
||||
tasks.insert(uid, TaskState::new(key, schedule.interval_minutes));
|
||||
tasks.insert(uid, TaskState::new(Some(key), schedule.interval_minutes));
|
||||
}
|
||||
|
||||
fn update_task_interval(queue: &mut DelayQueue<String>, uid: &str, state: &mut TaskState, schedule: &TaskSchedule) {
|
||||
@@ -353,52 +290,13 @@ impl Timer {
|
||||
};
|
||||
|
||||
state.key = None;
|
||||
if !Self::mark_task_running(state, &uid, false) {
|
||||
if state.running {
|
||||
return;
|
||||
}
|
||||
|
||||
state.running = true;
|
||||
Self::spawn_update_task(uid, command_tx);
|
||||
}
|
||||
|
||||
fn run_task_now(
|
||||
queue: &mut DelayQueue<String>,
|
||||
tasks: &mut HashMap<String, TaskState>,
|
||||
uid: String,
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
) {
|
||||
let Some(state) = tasks.get_mut(&uid) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if !Self::mark_task_running(state, &uid, true) {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(key) = state.key.take() {
|
||||
queue.remove(&key);
|
||||
}
|
||||
Self::spawn_update_task(uid, command_tx);
|
||||
}
|
||||
|
||||
fn mark_task_running(state: &mut TaskState, uid: &str, immediate: bool) -> bool {
|
||||
if !state.running {
|
||||
state.running = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
if immediate {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Timer task already running, skip immediate uid={}",
|
||||
uid
|
||||
);
|
||||
} else {
|
||||
logging!(debug, Type::Timer, "Timer task already running, skip uid={}", uid);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn finish_task(queue: &mut DelayQueue<String>, tasks: &mut HashMap<String, TaskState>, uid: String) {
|
||||
let Some(state) = tasks.get_mut(&uid) else {
|
||||
return;
|
||||
@@ -441,21 +339,19 @@ impl Timer {
|
||||
}
|
||||
|
||||
pub async fn get_next_update_time(&self, uid: &str) -> Option<i64> {
|
||||
logging!(debug, Type::Timer, "Getting next update time, uid={}", uid);
|
||||
let (reply, result) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(TimerCommand::NextUpdateTime(uid.into(), reply))
|
||||
.ok()?;
|
||||
result.await.ok().flatten()
|
||||
}
|
||||
|
||||
let task_interval = *self.timer_map.read().get(uid)?;
|
||||
let profiles = Config::profiles().await;
|
||||
let profiles_guard = profiles.latest_arc();
|
||||
let items = profiles_guard.items.as_ref()?;
|
||||
|
||||
let profile = items.iter().find(|item| item.uid.as_deref() == Some(uid))?;
|
||||
let updated = profile.updated.unwrap_or(0) as i64;
|
||||
|
||||
if updated > 0 {
|
||||
Some(updated + (task_interval as i64 * 60))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
|
||||
let task = tasks.get(uid).filter(|task| !task.retired)?;
|
||||
let updated = profiles.get_item(uid).ok()?.updated.filter(|updated| *updated > 0)?;
|
||||
let updated = i64::try_from(updated).ok()?;
|
||||
let interval = i64::try_from(task.interval_minutes).ok()?.checked_mul(60)?;
|
||||
updated.checked_add(interval)
|
||||
}
|
||||
|
||||
fn emit_update_event(uid: &str, is_start: bool) {
|
||||
@@ -474,12 +370,13 @@ impl Timer {
|
||||
|| Self::emit_update_event(uid, true),
|
||||
|| feat::update_profile(uid, None, false),
|
||||
|result| match result {
|
||||
Ok(_) => {
|
||||
Ok(Ok(_)) => {
|
||||
logging!(debug, Type::Timer, "timer task completed for uid: {}", uid);
|
||||
}
|
||||
Err(e) => {
|
||||
Ok(Err(e)) => {
|
||||
logging_error!(Type::Timer, "Failed to update profile uid {}: {e:#}", uid);
|
||||
}
|
||||
Err(_) => logging!(error, Type::Timer, "Profile update worker panicked"),
|
||||
},
|
||||
|| Self::emit_update_event(uid, false),
|
||||
)
|
||||
@@ -552,7 +449,7 @@ mod tests {
|
||||
remote_profile("missing-interval", Some(true), None),
|
||||
];
|
||||
|
||||
let map = Timer::gen_map_from_items(&items);
|
||||
let map = Timer::gen_map_from_items(&items, false);
|
||||
|
||||
assert_eq!(map.len(), 2);
|
||||
assert_eq!(map.get("enabled").map(|s| s.interval_minutes), Some(30));
|
||||
@@ -763,8 +660,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");
|
||||
}
|
||||
},
|
||||
|
||||
@@ -212,22 +212,9 @@ impl Tray {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let verge = Config::verge().await.latest_arc();
|
||||
let system_proxy = verge.enable_system_proxy.unwrap_or(false);
|
||||
let tun_mode = verge.enable_tun_mode.unwrap_or(false);
|
||||
let mode = {
|
||||
Config::clash()
|
||||
.await
|
||||
.latest_arc()
|
||||
.0
|
||||
.get("mode")
|
||||
.map_or("rule", |val| val.as_str().unwrap_or("rule"))
|
||||
.to_owned()
|
||||
};
|
||||
let is_lightweight_mode = is_in_lightweight_mode();
|
||||
|
||||
let verge = Config::verge().await;
|
||||
let fetch_proxy_groups =
|
||||
include_proxy_groups && verge.tray_proxy_groups_display_mode.as_deref() != Some("disable");
|
||||
include_proxy_groups && verge.latest_arc().tray_proxy_groups_display_mode.as_deref() != Some("disable");
|
||||
|
||||
// TODO: should update tray menu again when it was timeout error
|
||||
let (proxy_nodes_data, runtime_proxy_groups_order) = if fetch_proxy_groups {
|
||||
@@ -257,29 +244,28 @@ impl Tray {
|
||||
(None, None)
|
||||
};
|
||||
|
||||
let verge = if fetch_proxy_groups {
|
||||
Config::verge().await.latest_arc()
|
||||
} else {
|
||||
verge
|
||||
};
|
||||
let profiles = Config::profiles().await.latest_arc();
|
||||
let clash = Config::clash().await;
|
||||
let profiles = Config::profiles().await;
|
||||
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
let dispatch_handle = app_handle.clone();
|
||||
app_handle
|
||||
.run_on_main_thread(move || {
|
||||
let _ = tx.send((|| -> Result<()> {
|
||||
let verge = verge.latest_arc();
|
||||
let clash = clash.latest_arc();
|
||||
let mode = clash.0.get("mode").and_then(|mode| mode.as_str()).unwrap_or("rule");
|
||||
let menu = build_tray_menu(
|
||||
&dispatch_handle,
|
||||
TrayMenuOptions {
|
||||
mode: Some(mode.as_str()),
|
||||
system_proxy_enabled: system_proxy,
|
||||
tun_mode_enabled: tun_mode,
|
||||
is_lightweight_mode,
|
||||
mode: Some(mode),
|
||||
system_proxy_enabled: verge.enable_system_proxy.unwrap_or(false),
|
||||
tun_mode_enabled: verge.enable_tun_mode.unwrap_or(false),
|
||||
is_lightweight_mode: is_in_lightweight_mode(),
|
||||
include_proxy_groups,
|
||||
},
|
||||
&verge,
|
||||
&profiles,
|
||||
&profiles.latest_arc(),
|
||||
runtime_proxy_groups_order,
|
||||
proxy_nodes_data,
|
||||
)?;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user