mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-19 02:12:10 +08:00
refactor(backend): declarative effects (#8128)
* refactor(core): type notice statuses behind the frozen wire contract * refactor(utils): unified retry and strategy-list helpers * refactor(feat): declarative effect registry for verge and clash patches * refactor(core): derive refresh announcements from transaction commit * refactor(core): fold tray, hotkey, autostart updates into effect ensures * refactor(utils): migrate remaining bounded retry loops * docs: add src-tauri architecture guardrails * refactor(core): coalesce burst refresh announcements * refactor(core): complete bounded service retry migration * ci(backend): add architecture ban gates * test(feat): freeze representative effect registry mappings * docs(backend): record dead wire contract entries * chore(core): document watcher exit conditions * fix(backend): preserve applied state across later failures * fix(config): retain runtime after an applied core replacement * refactor(backend): flatten refresh publication and retry policies * docs(backend): focus guardrails on architecture ownership * refactor(effects): use one execution order * fix(config): publish retained runtime and reconcile proxy settings
This commit is contained in:
@@ -0,0 +1,313 @@
|
||||
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 once_cell::sync::OnceCell;
|
||||
use parking_lot::RwLock;
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicI64, Ordering},
|
||||
},
|
||||
time::{Duration, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::{
|
||||
fs,
|
||||
sync::{Mutex, watch},
|
||||
};
|
||||
|
||||
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 AUTO_BACKUP_KEEP: usize = 20;
|
||||
const AUTO_MARKER: &str = "-auto-";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum AutoBackupTrigger {
|
||||
Scheduled,
|
||||
GlobalMerge,
|
||||
GlobalScript,
|
||||
}
|
||||
|
||||
impl AutoBackupTrigger {
|
||||
const fn slug(self) -> &'static str {
|
||||
match self {
|
||||
Self::Scheduled => "scheduled",
|
||||
Self::GlobalMerge => "merge",
|
||||
Self::GlobalScript => "script",
|
||||
}
|
||||
}
|
||||
|
||||
const fn is_schedule(self) -> bool {
|
||||
matches!(self, Self::Scheduled)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct AutoBackupSettings {
|
||||
schedule_enabled: bool,
|
||||
interval_hours: u64,
|
||||
change_enabled: bool,
|
||||
}
|
||||
|
||||
impl AutoBackupSettings {
|
||||
fn from_verge(verge: &IVerge) -> Self {
|
||||
let interval = verge
|
||||
.auto_backup_interval_hours
|
||||
.unwrap_or(DEFAULT_INTERVAL_HOURS)
|
||||
.clamp(MIN_INTERVAL_HOURS, MAX_INTERVAL_HOURS);
|
||||
|
||||
Self {
|
||||
schedule_enabled: verge.enable_auto_backup_schedule.unwrap_or(false),
|
||||
interval_hours: interval,
|
||||
change_enabled: verge.auto_backup_on_change.unwrap_or(true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for AutoBackupSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
schedule_enabled: false,
|
||||
interval_hours: DEFAULT_INTERVAL_HOURS,
|
||||
change_enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AutoBackupManager {
|
||||
settings: Arc<RwLock<AutoBackupSettings>>,
|
||||
settings_tx: watch::Sender<AutoBackupSettings>,
|
||||
runner_started: AtomicBool,
|
||||
exec_lock: Mutex<()>,
|
||||
last_backup: AtomicI64,
|
||||
}
|
||||
|
||||
impl AutoBackupManager {
|
||||
pub fn global() -> &'static Self {
|
||||
static INSTANCE: OnceCell<AutoBackupManager> = OnceCell::new();
|
||||
INSTANCE.get_or_init(|| {
|
||||
let (tx, _rx) = watch::channel(AutoBackupSettings::default());
|
||||
Self {
|
||||
settings: Arc::new(RwLock::new(AutoBackupSettings::default())),
|
||||
settings_tx: tx,
|
||||
runner_started: AtomicBool::new(false),
|
||||
exec_lock: Mutex::new(()),
|
||||
last_backup: AtomicI64::new(0),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn init(&self) -> Result<()> {
|
||||
let settings = Self::load_settings().await;
|
||||
{
|
||||
*self.settings.write() = settings;
|
||||
}
|
||||
let _ = self.settings_tx.send(settings);
|
||||
self.maybe_start_runner(settings);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn refresh_settings(&self) -> Result<()> {
|
||||
let settings = Self::load_settings().await;
|
||||
{
|
||||
*self.settings.write() = settings;
|
||||
}
|
||||
let _ = self.settings_tx.send(settings);
|
||||
self.maybe_start_runner(settings);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn trigger_backup(trigger: AutoBackupTrigger) {
|
||||
AsyncHandler::spawn(move || async move {
|
||||
if let Err(err) = Self::global().execute_trigger(trigger).await {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Backup,
|
||||
"Auto backup execution failed ({:?}): {err:#?}",
|
||||
trigger
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn maybe_start_runner(&self, settings: AutoBackupSettings) {
|
||||
if settings.schedule_enabled {
|
||||
self.ensure_runner();
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_runner(&self) {
|
||||
if self.runner_started.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut rx = self.settings_tx.subscribe();
|
||||
AsyncHandler::spawn(move || async move {
|
||||
Self::run_scheduler(&mut rx).await;
|
||||
});
|
||||
}
|
||||
|
||||
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.read();
|
||||
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
fn append_auto_suffix(file_name: &str, slug: &str) -> String {
|
||||
match file_name.rsplit_once('.') {
|
||||
Some((stem, ext)) => format!("{stem}{AUTO_MARKER}{slug}.{ext}"),
|
||||
None => format!("{file_name}{AUTO_MARKER}{slug}"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn cleanup_auto_backups() -> Result<()> {
|
||||
if AUTO_BACKUP_KEEP == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let backup_dir = local_backup_dir()?;
|
||||
if !backup_dir.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut entries = match fs::read_dir(&backup_dir).await {
|
||||
Ok(dir) => dir,
|
||||
Err(err) => {
|
||||
logging!(warn, Type::Backup, "Failed to read backup directory: {err:#?}");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let mut files: Vec<(PathBuf, u64)> = Vec::new();
|
||||
|
||||
while let Some(entry) = entries.next_entry().await? {
|
||||
let path = entry.path();
|
||||
if !path.is_file() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let file_name = match entry.file_name().into_string() {
|
||||
Ok(name) => name,
|
||||
Err(_) => continue,
|
||||
};
|
||||
|
||||
if !file_name.contains(AUTO_MARKER) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let modified = entry
|
||||
.metadata()
|
||||
.await
|
||||
.and_then(|meta| meta.modified())
|
||||
.ok()
|
||||
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
|
||||
.map(|dur| dur.as_secs())
|
||||
.unwrap_or(0);
|
||||
|
||||
files.push((path, modified));
|
||||
}
|
||||
|
||||
if files.len() <= AUTO_BACKUP_KEEP {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
files.sort_by_key(|(_, ts)| *ts);
|
||||
let remove_count = files.len() - AUTO_BACKUP_KEEP;
|
||||
for (path, _) in files.into_iter().take(remove_count) {
|
||||
if let Err(err) = fs::remove_file(&path).await {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Backup,
|
||||
"Failed to remove auto backup {}: {err:#?}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
use crate::core::notify::NoticeStatus;
|
||||
use crate::process::AsyncHandler;
|
||||
use crate::singleton;
|
||||
use crate::utils::notification::{NotificationEvent, notify_event};
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use crate::{config::Config, core::handle, feat, module::lightweight::entry_lightweight_mode};
|
||||
use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_mode, feat};
|
||||
use anyhow::{Result, bail};
|
||||
use arc_swap::ArcSwap;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
@@ -177,7 +178,7 @@ impl Hotkey {
|
||||
"Hotkey profile reactivation failed validation: {}",
|
||||
message.as_str()
|
||||
);
|
||||
handle::Handle::notice_message("reactivate_profiles::error", message);
|
||||
handle::Handle::notice(NoticeStatus::ReactivateProfilesError, message);
|
||||
}
|
||||
Err(err) => {
|
||||
logging!(
|
||||
@@ -186,7 +187,7 @@ impl Hotkey {
|
||||
"Failed to reactivate subscriptions via hotkey: {}",
|
||||
err
|
||||
);
|
||||
handle::Handle::notice_message("reactivate_profiles::error", err.to_string());
|
||||
handle::Handle::notice(NoticeStatus::ReactivateProfilesError, err.to_string());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
use crate::{
|
||||
config::Config,
|
||||
core::{timer::Timer, tray::Tray},
|
||||
process::AsyncHandler,
|
||||
};
|
||||
|
||||
use clash_verge_logging::{Type, logging};
|
||||
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use anyhow::Result;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU32, Ordering};
|
||||
use tauri::Listener as _;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::{Duration, sleep};
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum LightweightState {
|
||||
Normal = 0,
|
||||
In = 1,
|
||||
Exiting = 2,
|
||||
}
|
||||
|
||||
impl From<u8> for LightweightState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => Self::In,
|
||||
2 => Self::Exiting,
|
||||
_ => Self::Normal,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LightweightState {
|
||||
const fn as_u8(self) -> u8 {
|
||||
self as u8
|
||||
}
|
||||
}
|
||||
|
||||
static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8);
|
||||
|
||||
static WINDOW_CLOSE_HANDLER_ID: AtomicU32 = AtomicU32::new(0);
|
||||
static WEBVIEW_FOCUS_HANDLER_ID: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
static CANCEL_TX: Mutex<Option<oneshot::Sender<()>>> = Mutex::new(None);
|
||||
|
||||
#[inline]
|
||||
fn get_state() -> LightweightState {
|
||||
LIGHTWEIGHT_STATE.load(Ordering::Acquire).into()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_transition(from: LightweightState, to: LightweightState) -> bool {
|
||||
LIGHTWEIGHT_STATE
|
||||
.compare_exchange(from.as_u8(), to.as_u8(), Ordering::AcqRel, Ordering::Relaxed)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn record_state_and_log(state: LightweightState) {
|
||||
LIGHTWEIGHT_STATE.store(state.as_u8(), Ordering::Release);
|
||||
match state {
|
||||
LightweightState::Normal => logging!(info, Type::Lightweight, "轻量模式已关闭"),
|
||||
LightweightState::In => logging!(info, Type::Lightweight, "轻量模式已开启"),
|
||||
LightweightState::Exiting => logging!(info, Type::Lightweight, "正在退出轻量模式"),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_in_lightweight_mode() -> bool {
|
||||
get_state() == LightweightState::In
|
||||
}
|
||||
|
||||
async fn refresh_lightweight_tray_state() {
|
||||
if let Err(err) = Tray::global().update_menu().await {
|
||||
logging!(warn, Type::Lightweight, "更新托盘轻量模式状态失败: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn auto_lightweight_boot() -> Result<()> {
|
||||
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_silent_start {
|
||||
entry_lightweight_mode().await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn enable_auto_light_weight_mode() {
|
||||
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();
|
||||
}
|
||||
|
||||
pub fn disable_auto_light_weight_mode() {
|
||||
logging!(info, Type::Lightweight, "关闭自动轻量模式");
|
||||
cancel_light_weight_timer();
|
||||
cancel_window_close_listener();
|
||||
cancel_webview_focus_listener();
|
||||
}
|
||||
|
||||
pub async fn entry_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
|
||||
}
|
||||
|
||||
pub async fn exit_lightweight_mode() -> bool {
|
||||
if !try_transition(LightweightState::In, LightweightState::Exiting) {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Lightweight,
|
||||
"轻量模式不在退出条件(可能已退出或正在退出),跳过调用"
|
||||
);
|
||||
refresh_lightweight_tray_state().await;
|
||||
return false;
|
||||
}
|
||||
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();
|
||||
}
|
||||
cancel_light_weight_timer();
|
||||
record_state_and_log(LightweightState::Normal);
|
||||
refresh_lightweight_tray_state().await;
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub async fn add_light_weight_timer() {
|
||||
setup_light_weight_timer().await;
|
||||
}
|
||||
|
||||
fn setup_window_close_listener() {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
let previous_handler_id = WINDOW_CLOSE_HANDLER_ID.swap(0, Ordering::AcqRel);
|
||||
if previous_handler_id != 0 {
|
||||
window.unlisten(previous_handler_id);
|
||||
logging!(debug, Type::Lightweight, "覆盖旧的窗口关闭监听");
|
||||
}
|
||||
let handler_id = window.listen("tauri://close-requested", move |_event| {
|
||||
std::mem::drop(AsyncHandler::spawn(|| async {
|
||||
setup_light_weight_timer().await;
|
||||
}));
|
||||
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
|
||||
});
|
||||
WINDOW_CLOSE_HANDLER_ID.store(handler_id, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_window_close_listener() {
|
||||
let id = WINDOW_CLOSE_HANDLER_ID.swap(0, Ordering::AcqRel);
|
||||
if id != 0 {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
window.unlisten(id);
|
||||
}
|
||||
logging!(debug, Type::Lightweight, "取消了窗口关闭监听");
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_webview_focus_listener() {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
let previous_handler_id = WEBVIEW_FOCUS_HANDLER_ID.swap(0, Ordering::AcqRel);
|
||||
if previous_handler_id != 0 {
|
||||
window.unlisten(previous_handler_id);
|
||||
logging!(debug, Type::Lightweight, "覆盖旧的窗口焦点监听");
|
||||
}
|
||||
let handler_id = window.listen("tauri://focus", move |_event| {
|
||||
cancel_light_weight_timer();
|
||||
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
|
||||
});
|
||||
WEBVIEW_FOCUS_HANDLER_ID.store(handler_id, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_webview_focus_listener() {
|
||||
let id = WEBVIEW_FOCUS_HANDLER_ID.swap(0, Ordering::AcqRel);
|
||||
if id != 0 {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
window.unlisten(id);
|
||||
}
|
||||
logging!(debug, Type::Lightweight, "取消了窗口焦点监听");
|
||||
}
|
||||
}
|
||||
|
||||
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"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let (tx, rx) = oneshot::channel::<()>();
|
||||
*cancel_tx_guard = Some(tx);
|
||||
drop(cancel_tx_guard);
|
||||
|
||||
AsyncHandler::spawn(move || async move {
|
||||
tokio::select! {
|
||||
_ = sleep(Duration::from_secs(once_by_minutes.saturating_mul(60))) => {
|
||||
logging!(info, Type::Timer, "Lightweight mode timer expired, entering lightweight mode");
|
||||
{
|
||||
let mut guard = CANCEL_TX.lock();
|
||||
*guard = None;
|
||||
}
|
||||
entry_lightweight_mode().await;
|
||||
}
|
||||
_ = rx => {
|
||||
logging!(debug, Type::Timer, "Received cancel signal, stopping lightweight mode timer");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"Lightweight mode timer set, entering lightweight mode in {} minutes",
|
||||
once_by_minutes
|
||||
);
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
||||
use crate::core::notify::NoticeStatus;
|
||||
use crate::core::service::StageRequest;
|
||||
use crate::{
|
||||
config::{Config, IProfiles, runtime::IRuntime},
|
||||
@@ -18,6 +19,7 @@ use smartstring::alias::String;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
path::PathBuf,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tauri_plugin_mihomo::Error as MihomoError;
|
||||
@@ -129,7 +131,31 @@ where
|
||||
}
|
||||
|
||||
impl CoreManager {
|
||||
pub async fn use_default_config(&self, error_key: &str, error_msg: &str) -> Result<()> {
|
||||
pub(crate) fn claim_config_update(
|
||||
&self,
|
||||
_config_write: &tokio::sync::MutexGuard<'_, ()>,
|
||||
) -> Result<ConfigUpdateGuard<'_>> {
|
||||
if !self.try_start_config_update() {
|
||||
anyhow::bail!("configuration update is already running");
|
||||
}
|
||||
Ok(ConfigUpdateGuard(self))
|
||||
}
|
||||
|
||||
pub(crate) async fn update_config_in_patch(&self, _update: &ConfigUpdateGuard<'_>) -> Result<()> {
|
||||
if handle::Handle::global().is_exiting() {
|
||||
anyhow::bail!("application is exiting");
|
||||
}
|
||||
self.set_last_update(Instant::now());
|
||||
Config::generate().await?;
|
||||
let outcome = self.validate_and_apply_draft().await?;
|
||||
if outcome.is_valid() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("{outcome}"))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn use_default_config(&self, status: NoticeStatus, message: &str) -> Result<()> {
|
||||
use crate::constants::files::RUNTIME_CONFIG;
|
||||
|
||||
let runtime_path = dirs::app_home_dir()?.join(RUNTIME_CONFIG);
|
||||
@@ -145,7 +171,7 @@ impl CoreManager {
|
||||
});
|
||||
|
||||
help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
|
||||
handle::Handle::notice_message(error_key, error_msg);
|
||||
handle::Handle::notice(status, message);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -234,6 +260,7 @@ impl CoreManager {
|
||||
let outcome = self.perform_config_update(Some(profiles)).await?;
|
||||
if outcome.is_valid() {
|
||||
crate::config::profiles::restore_selected_nodes().await;
|
||||
handle::Handle::refresh_clash();
|
||||
Ok(())
|
||||
} else {
|
||||
Err(anyhow!("failed to restore previous Core configuration: {outcome}"))
|
||||
@@ -297,8 +324,27 @@ impl CoreManager {
|
||||
self.validate_and_apply(transaction).await
|
||||
}
|
||||
|
||||
/// Validates and applies the caller's transaction, committing only on success.
|
||||
/// Commits the applied runtime even if restoring the system proxy subsequently fails.
|
||||
async fn validate_and_apply(&self, transaction: DraftTransaction<'_>) -> Result<ValidationOutcome> {
|
||||
let runtime = Config::runtime().await;
|
||||
let original_runtime = runtime.data_arc();
|
||||
let outcome = match self.validate_and_apply_draft().await {
|
||||
Ok(outcome) => outcome,
|
||||
Err(error) => {
|
||||
transaction.rollback();
|
||||
if !Arc::ptr_eq(&original_runtime, &runtime.data_arc()) {
|
||||
handle::Handle::refresh_clash();
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
if outcome.is_valid() {
|
||||
transaction.commit();
|
||||
}
|
||||
Ok(outcome)
|
||||
}
|
||||
|
||||
async fn validate_and_apply_draft(&self) -> Result<ValidationOutcome> {
|
||||
// One serialization feeds check and run files; the core never applies unvalidated bytes.
|
||||
let yaml = Config::runtime_config_yaml().await?;
|
||||
let outcome = CoreConfigValidator::global()
|
||||
@@ -309,8 +355,10 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
let run_path = Config::write_runtime_file(&yaml).await?;
|
||||
self.apply_config(run_path).await?;
|
||||
transaction.commit();
|
||||
let previous = self.current_core_readiness_generation();
|
||||
let result = self.apply_config(run_path).await;
|
||||
self.retain_applied_runtime(&Config::runtime().await, previous, &result);
|
||||
result?;
|
||||
// Under the lifecycle lock, so a stop for exit waits for this write instead of outrunning it.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
@@ -320,6 +368,21 @@ impl CoreManager {
|
||||
Ok(ValidationOutcome::Valid)
|
||||
}
|
||||
|
||||
fn retain_applied_runtime(
|
||||
&self,
|
||||
runtime: &clash_verge_draft::Draft<IRuntime>,
|
||||
previous: Option<u64>,
|
||||
result: &Result<()>,
|
||||
) {
|
||||
if result.is_ok()
|
||||
|| self
|
||||
.current_core_readiness_generation()
|
||||
.is_some_and(|current| Some(current) != previous)
|
||||
{
|
||||
runtime.apply();
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a generated configuration through the active core owner.
|
||||
async fn apply_config(&self, path: PathBuf) -> Result<()> {
|
||||
if matches!(*self.get_running_mode(), RunningMode::Service) {
|
||||
@@ -411,6 +474,31 @@ mod tests {
|
||||
use clash_verge_service_ipc::{StageRejection, StageRuntimeOutcome};
|
||||
use std::{cell::Cell, time::Duration};
|
||||
|
||||
#[test]
|
||||
fn a_ready_replacement_keeps_the_applied_runtime_when_proxy_restore_fails() -> anyhow::Result<()> {
|
||||
use crate::{config::runtime::IRuntime, core::CoreManager};
|
||||
use clash_verge_draft::{Draft, DraftTransaction};
|
||||
|
||||
for replaced in [false, true] {
|
||||
let manager = CoreManager::default();
|
||||
manager.mark_core_ready();
|
||||
let previous = manager.current_core_readiness_generation();
|
||||
let runtime = Draft::new(IRuntime::default());
|
||||
let transaction = DraftTransaction::begin(vec![&runtime])?;
|
||||
runtime.edit_draft(|draft| {
|
||||
draft.exists_keys.insert("replacement".into());
|
||||
});
|
||||
if replaced {
|
||||
manager.mark_core_ready();
|
||||
}
|
||||
let result = Err(anyhow::anyhow!("system proxy restore failed"));
|
||||
manager.retain_applied_runtime(&runtime, previous, &result);
|
||||
transaction.rollback();
|
||||
assert_eq!(runtime.data_arc().exists_keys.contains("replacement"), replaced);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const CONFIRM_WITHIN: Duration = Duration::from_secs(5);
|
||||
|
||||
fn staged() -> StageAttempt {
|
||||
|
||||
@@ -884,29 +884,34 @@ impl CoreManager {
|
||||
AsyncHandler::spawn(|| async move {
|
||||
let manager = Self::global();
|
||||
let started = Instant::now();
|
||||
loop {
|
||||
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"
|
||||
);
|
||||
break;
|
||||
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) {
|
||||
break;
|
||||
return Ok(());
|
||||
}
|
||||
match manager.try_handoff_sidecar_to_service().await {
|
||||
HandoffOutcome::Done => break,
|
||||
HandoffOutcome::Done => Ok(()),
|
||||
HandoffOutcome::Failed => {
|
||||
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
|
||||
break;
|
||||
Ok(())
|
||||
}
|
||||
HandoffOutcome::NotReady => {}
|
||||
HandoffOutcome::NotReady => Err(RetryError::Retry(())),
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
manager.handoff_watcher_running.store(false, Ordering::Release);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
mod config;
|
||||
pub(crate) use config::ConfigUpdateGuard;
|
||||
mod lifecycle;
|
||||
mod state;
|
||||
|
||||
@@ -237,7 +238,7 @@ impl CoreManager {
|
||||
}
|
||||
}
|
||||
|
||||
fn current_core_readiness_generation(&self) -> Option<u64> {
|
||||
pub(crate) fn current_core_readiness_generation(&self) -> Option<u64> {
|
||||
active_core_readiness_generation(self.core_readiness_state.load(Ordering::Acquire))
|
||||
}
|
||||
|
||||
@@ -284,48 +285,56 @@ impl CoreManager {
|
||||
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
|
||||
}
|
||||
|
||||
let mut retries = 0;
|
||||
loop {
|
||||
match self.start_core().await {
|
||||
Ok(()) => {
|
||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||
return Ok(!matches!(*self.get_running_mode(), RunningMode::NotRunning));
|
||||
}
|
||||
Err(start_error) if retries < MAX_PORT_FALLBACK_RETRIES => {
|
||||
if !matches!(*self.get_running_mode(), RunningMode::NotRunning) {
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
|
||||
std::time::Duration::ZERO,
|
||||
),
|
||||
|retries| async move {
|
||||
match self.start_core().await {
|
||||
Ok(()) => {
|
||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||
return Err(start_error);
|
||||
Ok(!matches!(*self.get_running_mode(), RunningMode::NotRunning))
|
||||
}
|
||||
match crate::config::Config::resolve_startup_mixed_port().await {
|
||||
Ok(true) => {
|
||||
retries += 1;
|
||||
tracing::Span::current().record("retries", retries);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"Retrying core startup after mixed proxy port fallback ({}/{}): {start_error:#}",
|
||||
retries,
|
||||
MAX_PORT_FALLBACK_RETRIES
|
||||
);
|
||||
}
|
||||
Ok(false) => {
|
||||
Err(start_error) if retries < MAX_PORT_FALLBACK_RETRIES => {
|
||||
if !matches!(*self.get_running_mode(), RunningMode::NotRunning) {
|
||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||
return Err(start_error);
|
||||
return Err(RetryError::Stop(start_error));
|
||||
}
|
||||
Err(fallback_error) => {
|
||||
crate::config::Config::block_startup_core(&fallback_error);
|
||||
return Err(start_error.context(format!(
|
||||
"the mixed proxy port fallback did not rescue core startup: {fallback_error:#}"
|
||||
)));
|
||||
match crate::config::Config::resolve_startup_mixed_port().await {
|
||||
Ok(true) => {
|
||||
let retries = retries + 1;
|
||||
tracing::Span::current().record("retries", retries);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"Retrying core startup after mixed proxy port fallback ({}/{}): {start_error:#}",
|
||||
retries,
|
||||
MAX_PORT_FALLBACK_RETRIES
|
||||
);
|
||||
Err(RetryError::Retry(start_error))
|
||||
}
|
||||
Ok(false) => {
|
||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||
Err(RetryError::Stop(start_error))
|
||||
}
|
||||
Err(fallback_error) => {
|
||||
crate::config::Config::block_startup_core(&fallback_error);
|
||||
Err(RetryError::Stop(start_error.context(format!(
|
||||
"the mixed proxy port fallback did not rescue core startup: {fallback_error:#}"
|
||||
))))
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||
Err(RetryError::Stop(error))
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#[cfg(test)]
|
||||
use super::claim_core_readiness_generation;
|
||||
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
use crate::{
|
||||
AsyncHandler,
|
||||
config::Config,
|
||||
@@ -11,6 +12,7 @@ use crate::{
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_logging::Type;
|
||||
use log::Level;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::Path;
|
||||
use tauri_plugin_mihomo::MihomoExt as _;
|
||||
use tauri_plugin_shell::ShellExt as _;
|
||||
@@ -41,14 +43,15 @@ async fn retry_service_start<Start, StartFuture>(
|
||||
mut start: Start,
|
||||
) -> Result<()>
|
||||
where
|
||||
Start: FnMut() -> StartFuture,
|
||||
StartFuture: std::future::Future<Output = Result<()>>,
|
||||
Start: FnMut() -> StartFuture + Send,
|
||||
StartFuture: std::future::Future<Output = Result<()>> + Send,
|
||||
{
|
||||
let mut last_error = None;
|
||||
for attempt in 0..attempts {
|
||||
match start().await {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(error) => {
|
||||
let attempts = NonZeroUsize::new(attempts).ok_or_else(|| anyhow::anyhow!("service start failed"))?;
|
||||
retry(RetryPolicy::fixed(attempts, retry_delay), |attempt| {
|
||||
// The Windows Service IPC future would otherwise inflate every enclosing lifecycle future.
|
||||
let future = Box::pin(start());
|
||||
async move {
|
||||
future.await.map_err(|error| {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
@@ -60,16 +63,14 @@ where
|
||||
.downcast_ref::<service::ServiceStartRefusal>()
|
||||
.is_some_and(|refusal| service::StageRequest::is_about_the_bundle(refusal.code))
|
||||
{
|
||||
return Err(error);
|
||||
RetryError::Stop(error)
|
||||
} else {
|
||||
RetryError::Retry(error)
|
||||
}
|
||||
last_error = Some(error);
|
||||
if attempt + 1 < attempts {
|
||||
tokio::time::sleep(retry_delay).await;
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("service start failed")))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
impl CoreManager {
|
||||
@@ -95,14 +96,16 @@ async fn poll_sidecar_readiness<F, Fut>(
|
||||
mut probe: F,
|
||||
) -> Result<()>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: std::future::Future<Output = Result<()>>,
|
||||
F: FnMut() -> Fut + Send,
|
||||
Fut: std::future::Future<Output = Result<()>> + Send,
|
||||
{
|
||||
let mut last_error = None;
|
||||
for attempt in 0..max_attempts {
|
||||
match probe().await {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(error) => {
|
||||
let attempts = NonZeroUsize::new(max_attempts)
|
||||
.context("sidecar readiness was configured with no attempts")
|
||||
.context("Mihomo API did not become ready")?;
|
||||
retry(RetryPolicy::fixed(attempts, retry_delay), |attempt| {
|
||||
let future = probe();
|
||||
async move {
|
||||
future.await.map_err(|error| {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Core,
|
||||
@@ -110,16 +113,12 @@ where
|
||||
attempt + 1,
|
||||
max_attempts
|
||||
);
|
||||
last_error = Some(error);
|
||||
}
|
||||
RetryError::Retry(error)
|
||||
})
|
||||
}
|
||||
if attempt + 1 < max_attempts {
|
||||
tokio::time::sleep(retry_delay).await;
|
||||
}
|
||||
}
|
||||
Err(last_error
|
||||
.unwrap_or_else(|| anyhow::anyhow!("sidecar readiness was configured with no attempts"))
|
||||
.context("Mihomo API did not become ready"))
|
||||
})
|
||||
.await
|
||||
.context("Mihomo API did not become ready")
|
||||
}
|
||||
|
||||
fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
pub mod auto_backup;
|
||||
pub mod autostart;
|
||||
pub mod backup;
|
||||
pub mod handle;
|
||||
pub mod hotkey;
|
||||
pub mod lightweight;
|
||||
pub mod listener;
|
||||
pub mod logger;
|
||||
pub mod manager;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub mod network_watch;
|
||||
pub mod notification;
|
||||
pub mod notify;
|
||||
pub(crate) mod owner_identity;
|
||||
pub mod proxy_control;
|
||||
pub mod proxy_view;
|
||||
@@ -22,3 +23,4 @@ pub mod validate;
|
||||
pub mod win_uwp;
|
||||
|
||||
pub use self::{manager::CoreManager, timer::Timer, updater::SilentUpdater};
|
||||
pub use notify::{handle, notification};
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
use super::{handle::Handle, notification::FrontendEvent};
|
||||
use parking_lot::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Refresh {
|
||||
Clash,
|
||||
Verge,
|
||||
Profiles,
|
||||
Proxies,
|
||||
}
|
||||
|
||||
const REFRESH_WINDOW: Duration = Duration::from_millis(20);
|
||||
static BATCH: RefreshBatch = RefreshBatch(Mutex::new(Vec::new()));
|
||||
|
||||
#[derive(Default)]
|
||||
struct RefreshBatch(Mutex<Vec<Refresh>>);
|
||||
|
||||
impl RefreshBatch {
|
||||
fn enqueue(&self, refresh: Refresh) -> bool {
|
||||
let mut pending = self.0.lock();
|
||||
let start_window = pending.is_empty();
|
||||
if !pending.contains(&refresh) {
|
||||
pending.push(refresh);
|
||||
}
|
||||
start_window
|
||||
}
|
||||
|
||||
async fn flush(&self, emit: impl Fn(Refresh)) {
|
||||
// A fixed window bounds latency even under a continuous stream of refreshes.
|
||||
tokio::time::sleep(REFRESH_WINDOW).await;
|
||||
let refreshes = std::mem::take(&mut *self.0.lock());
|
||||
for refresh in refreshes {
|
||||
emit(refresh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn announce(refresh: Refresh) {
|
||||
if BATCH.enqueue(refresh) {
|
||||
crate::AsyncHandler::spawn(|| BATCH.flush(emit));
|
||||
}
|
||||
}
|
||||
|
||||
fn emit(refresh: Refresh) {
|
||||
Handle::send_event(match refresh {
|
||||
Refresh::Clash => FrontendEvent::RefreshClash,
|
||||
Refresh::Verge => FrontendEvent::RefreshVerge,
|
||||
Refresh::Profiles => FrontendEvent::RefreshProfiles,
|
||||
Refresh::Proxies => FrontendEvent::RefreshProxyConfig,
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn bursts_keep_each_refresh_kind_and_rearm_during_delivery() -> anyhow::Result<()> {
|
||||
let batch = RefreshBatch::default();
|
||||
let delivered = Mutex::new(Vec::new());
|
||||
assert!(batch.enqueue(Refresh::Clash));
|
||||
for refresh in [Refresh::Verge, Refresh::Clash, Refresh::Profiles, Refresh::Proxies] {
|
||||
assert!(!batch.enqueue(refresh));
|
||||
}
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
batch
|
||||
.flush(|refresh| {
|
||||
delivered.lock().push(refresh);
|
||||
if refresh == Refresh::Clash {
|
||||
assert!(batch.enqueue(Refresh::Clash));
|
||||
assert!(!batch.enqueue(Refresh::Clash));
|
||||
}
|
||||
})
|
||||
.await;
|
||||
batch.flush(|refresh| delivered.lock().push(refresh)).await;
|
||||
})
|
||||
.await?;
|
||||
assert_eq!(
|
||||
*delivered.lock(),
|
||||
[
|
||||
Refresh::Clash,
|
||||
Refresh::Verge,
|
||||
Refresh::Profiles,
|
||||
Refresh::Proxies,
|
||||
Refresh::Clash
|
||||
]
|
||||
);
|
||||
assert!(batch.enqueue(Refresh::Verge));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::{core::handle, utils::window_manager::WindowState};
|
||||
use clash_verge_i18n;
|
||||
use tauri_plugin_notification::NotificationExt as _;
|
||||
|
||||
pub enum NotificationEvent<'a> {
|
||||
DashboardToggled,
|
||||
ClashModeChanged {
|
||||
mode: &'a str,
|
||||
},
|
||||
SystemProxyToggled(bool),
|
||||
/// A proxy change failed while no window could report it.
|
||||
SystemProxyFailed,
|
||||
/// The system proxy guard stopped.
|
||||
SystemProxyGuardStopped,
|
||||
TunModeToggled(bool),
|
||||
LightweightModeEntered,
|
||||
ProfilesReactivated,
|
||||
AppQuit,
|
||||
}
|
||||
|
||||
/// Whether no app window can currently show the failure.
|
||||
pub const fn needs_system_notification(state: WindowState) -> bool {
|
||||
match state {
|
||||
WindowState::Hidden | WindowState::Minimized | WindowState::NotExist => true,
|
||||
WindowState::VisibleFocused | WindowState::VisibleUnfocused => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn notify(title: Cow<'_, str>, body: Cow<'_, str>) {
|
||||
let app_handle = handle::Handle::app_handle();
|
||||
app_handle.notification().builder().title(title).body(body).show().ok();
|
||||
}
|
||||
|
||||
pub async fn notify_event<'a>(event: NotificationEvent<'a>) {
|
||||
match event {
|
||||
NotificationEvent::DashboardToggled => {
|
||||
let title = clash_verge_i18n::t!("notifications.dashboardToggled.title");
|
||||
let body = clash_verge_i18n::t!("notifications.dashboardToggled.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::ClashModeChanged { mode } => {
|
||||
let title = clash_verge_i18n::t!("notifications.clashModeChanged.title");
|
||||
let body = clash_verge_i18n::t!("notifications.clashModeChanged.body")
|
||||
.replace("{mode}", mode)
|
||||
.into();
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::SystemProxyToggled(enabled) => {
|
||||
let title = clash_verge_i18n::t!("notifications.systemProxyToggled.title");
|
||||
let key = if enabled {
|
||||
"notifications.systemProxyToggled.on"
|
||||
} else {
|
||||
"notifications.systemProxyToggled.off"
|
||||
};
|
||||
|
||||
let body = clash_verge_i18n::t!(key);
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::SystemProxyFailed => {
|
||||
let title = clash_verge_i18n::t!("notifications.systemProxyFailed.title");
|
||||
let body = clash_verge_i18n::t!("notifications.systemProxyFailed.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::SystemProxyGuardStopped => {
|
||||
let title = clash_verge_i18n::t!("notifications.systemProxyGuardStopped.title");
|
||||
let body = clash_verge_i18n::t!("notifications.systemProxyGuardStopped.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::TunModeToggled(enabled) => {
|
||||
let title = clash_verge_i18n::t!("notifications.tunModeToggled.title");
|
||||
let key = if enabled {
|
||||
"notifications.tunModeToggled.on"
|
||||
} else {
|
||||
"notifications.tunModeToggled.off"
|
||||
};
|
||||
let body = clash_verge_i18n::t!(key);
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::LightweightModeEntered => {
|
||||
let title = clash_verge_i18n::t!("notifications.lightweightModeEntered.title");
|
||||
let body = clash_verge_i18n::t!("notifications.lightweightModeEntered.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::ProfilesReactivated => {
|
||||
let title = clash_verge_i18n::t!("notifications.profilesReactivated.title");
|
||||
let body = clash_verge_i18n::t!("notifications.profilesReactivated.body");
|
||||
notify(title, body);
|
||||
}
|
||||
NotificationEvent::AppQuit => {
|
||||
let title = clash_verge_i18n::t!("notifications.appQuit.title");
|
||||
let body = clash_verge_i18n::t!("notifications.appQuit.body");
|
||||
notify(title, body);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
use super::NoticeStatus;
|
||||
use crate::{APP_HANDLE, singleton};
|
||||
use smartstring::alias::String;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use tauri::AppHandle;
|
||||
use tauri_plugin_mihomo::{Mihomo, MihomoExt as _};
|
||||
|
||||
@@ -36,19 +40,11 @@ impl Handle {
|
||||
}
|
||||
|
||||
pub fn refresh_clash() {
|
||||
Self::send_event(FrontendEvent::RefreshClash);
|
||||
super::announce(super::Refresh::Clash);
|
||||
}
|
||||
|
||||
pub fn refresh_verge() {
|
||||
Self::send_event(FrontendEvent::RefreshVerge);
|
||||
}
|
||||
|
||||
pub fn refresh_profiles() {
|
||||
Self::send_event(FrontendEvent::RefreshProfiles);
|
||||
}
|
||||
|
||||
pub fn refresh_proxy_config() {
|
||||
Self::send_event(FrontendEvent::RefreshProxyConfig);
|
||||
super::announce(super::Refresh::Verge);
|
||||
}
|
||||
|
||||
/// Push a Run State snapshot to the frontend.
|
||||
@@ -80,13 +76,10 @@ impl Handle {
|
||||
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
||||
}
|
||||
|
||||
pub fn notice_message<S: AsRef<str>, M: Into<String>>(status: S, msg: M) {
|
||||
let status_str = status.as_ref();
|
||||
let msg_str = msg.into();
|
||||
|
||||
pub fn notice(status: NoticeStatus, message: impl Into<Arc<str>>) {
|
||||
Self::send_event(FrontendEvent::NoticeMessage {
|
||||
status: status_str,
|
||||
message: msg_str,
|
||||
status,
|
||||
message: message.into(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -102,7 +95,7 @@ impl Handle {
|
||||
self.is_exiting.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn send_event(event: FrontendEvent) {
|
||||
pub(super) fn send_event(event: FrontendEvent) {
|
||||
let handle = Self::global();
|
||||
if handle.is_exiting() {
|
||||
return;
|
||||
@@ -0,0 +1,208 @@
|
||||
mod announce;
|
||||
pub use announce::{Refresh, announce};
|
||||
pub mod desktop;
|
||||
pub mod handle;
|
||||
pub mod notification;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||
pub enum NoticeStatus {
|
||||
// dead send: no frontend handler
|
||||
#[serde(rename = "info")]
|
||||
Info,
|
||||
#[serde(rename = "import_sub_url::ok")]
|
||||
ImportSubUrlOk,
|
||||
#[serde(rename = "import_sub_url::error")]
|
||||
ImportSubUrlError,
|
||||
#[serde(rename = "set_config::error")]
|
||||
SetConfigError,
|
||||
#[serde(rename = "core_start::error")]
|
||||
CoreStartError,
|
||||
#[serde(rename = "service_core::repair_required")]
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
ServiceCoreRepairRequired,
|
||||
#[serde(rename = "service_core::app_data_not_owned")]
|
||||
ServiceCoreAppDataNotOwned,
|
||||
#[serde(rename = "service_core::sidecar_fallback")]
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
ServiceCoreSidecarFallback,
|
||||
#[serde(rename = "dns_override::auto_disabled")]
|
||||
DnsOverrideAutoDisabled,
|
||||
#[serde(rename = "enhance::discarded_keys")]
|
||||
EnhanceDiscardedKeys,
|
||||
#[serde(rename = "tun_mode::auto_disabled")]
|
||||
TunModeAutoDisabled,
|
||||
#[serde(rename = "tun_mode::auto_disable_failed")]
|
||||
TunModeAutoDisableFailed,
|
||||
#[serde(rename = "app_restart::core_stop_failed")]
|
||||
AppRestartCoreStopFailed,
|
||||
#[serde(rename = "app_quit::core_stop_failed")]
|
||||
AppQuitCoreStopFailed,
|
||||
#[serde(rename = "update_with_clash_proxy")]
|
||||
UpdateWithClashProxy,
|
||||
#[serde(rename = "update_failed_even_with_clash")]
|
||||
UpdateFailedEvenWithClash,
|
||||
#[serde(rename = "reactivate_profiles::error")]
|
||||
ReactivateProfilesError,
|
||||
#[serde(rename = "update_failed")]
|
||||
UpdateFailed,
|
||||
#[serde(rename = "config_validate::boot_error")]
|
||||
ConfigValidateBootError,
|
||||
#[serde(rename = "config_validate::error")]
|
||||
ConfigValidateError,
|
||||
#[serde(rename = "config_validate::process_terminated")]
|
||||
ConfigValidateProcessTerminated,
|
||||
#[serde(rename = "config_validate::script_error")]
|
||||
ConfigValidateScriptError,
|
||||
#[serde(rename = "config_validate::script_syntax_error")]
|
||||
ConfigValidateScriptSyntaxError,
|
||||
#[serde(rename = "config_validate::script_missing_main")]
|
||||
ConfigValidateScriptMissingMain,
|
||||
#[serde(rename = "config_validate::file_not_found")]
|
||||
ConfigValidateFileNotFound,
|
||||
#[serde(rename = "config_validate::yaml_syntax_error")]
|
||||
ConfigValidateYamlSyntaxError,
|
||||
#[serde(rename = "config_validate::yaml_read_error")]
|
||||
ConfigValidateYamlReadError,
|
||||
#[serde(rename = "config_validate::yaml_mapping_error")]
|
||||
ConfigValidateYamlMappingError,
|
||||
#[serde(rename = "config_validate::merge_syntax_error")]
|
||||
ConfigValidateMergeSyntaxError,
|
||||
#[serde(rename = "config_validate::merge_mapping_error")]
|
||||
ConfigValidateMergeMappingError,
|
||||
#[serde(rename = "config_core::change_success")]
|
||||
ConfigCoreChangeSuccess,
|
||||
#[serde(rename = "config_core::change_error")]
|
||||
ConfigCoreChangeError,
|
||||
#[serde(rename = "mixed_port::fallback")]
|
||||
MixedPortFallback,
|
||||
#[serde(rename = "mixed_port::fallback_error")]
|
||||
MixedPortFallbackError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::core_change")]
|
||||
ConfigValidateCoreChange,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::stdout_error")]
|
||||
ConfigValidateStdoutError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::yaml_key_error")]
|
||||
ConfigValidateYamlKeyError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::yaml_error")]
|
||||
ConfigValidateYamlError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::merge_key_error")]
|
||||
ConfigValidateMergeKeyError,
|
||||
// dead listener: frontend handler retained
|
||||
#[allow(dead_code)]
|
||||
#[serde(rename = "config_validate::merge_error")]
|
||||
ConfigValidateMergeError,
|
||||
// dead send: no frontend handler
|
||||
#[serde(rename = "set_config::ok")]
|
||||
SetConfigOk,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::NoticeStatus;
|
||||
|
||||
#[test]
|
||||
fn notice_status_wire_contract() -> Result<(), serde_json::Error> {
|
||||
let statuses = [
|
||||
NoticeStatus::Info,
|
||||
NoticeStatus::ImportSubUrlOk,
|
||||
NoticeStatus::ImportSubUrlError,
|
||||
NoticeStatus::SetConfigError,
|
||||
NoticeStatus::CoreStartError,
|
||||
NoticeStatus::ServiceCoreRepairRequired,
|
||||
NoticeStatus::ServiceCoreAppDataNotOwned,
|
||||
NoticeStatus::ServiceCoreSidecarFallback,
|
||||
NoticeStatus::DnsOverrideAutoDisabled,
|
||||
NoticeStatus::EnhanceDiscardedKeys,
|
||||
NoticeStatus::TunModeAutoDisabled,
|
||||
NoticeStatus::TunModeAutoDisableFailed,
|
||||
NoticeStatus::AppRestartCoreStopFailed,
|
||||
NoticeStatus::AppQuitCoreStopFailed,
|
||||
NoticeStatus::UpdateWithClashProxy,
|
||||
NoticeStatus::UpdateFailedEvenWithClash,
|
||||
NoticeStatus::ReactivateProfilesError,
|
||||
NoticeStatus::UpdateFailed,
|
||||
NoticeStatus::ConfigValidateBootError,
|
||||
NoticeStatus::ConfigValidateError,
|
||||
NoticeStatus::ConfigValidateProcessTerminated,
|
||||
NoticeStatus::ConfigValidateScriptError,
|
||||
NoticeStatus::ConfigValidateScriptSyntaxError,
|
||||
NoticeStatus::ConfigValidateScriptMissingMain,
|
||||
NoticeStatus::ConfigValidateFileNotFound,
|
||||
NoticeStatus::ConfigValidateYamlSyntaxError,
|
||||
NoticeStatus::ConfigValidateYamlReadError,
|
||||
NoticeStatus::ConfigValidateYamlMappingError,
|
||||
NoticeStatus::ConfigValidateMergeSyntaxError,
|
||||
NoticeStatus::ConfigValidateMergeMappingError,
|
||||
NoticeStatus::ConfigCoreChangeSuccess,
|
||||
NoticeStatus::ConfigCoreChangeError,
|
||||
NoticeStatus::MixedPortFallback,
|
||||
NoticeStatus::MixedPortFallbackError,
|
||||
NoticeStatus::ConfigValidateCoreChange,
|
||||
NoticeStatus::ConfigValidateStdoutError,
|
||||
NoticeStatus::ConfigValidateYamlKeyError,
|
||||
NoticeStatus::ConfigValidateYamlError,
|
||||
NoticeStatus::ConfigValidateMergeKeyError,
|
||||
NoticeStatus::ConfigValidateMergeError,
|
||||
NoticeStatus::SetConfigOk,
|
||||
];
|
||||
let expected = [
|
||||
"info",
|
||||
"import_sub_url::ok",
|
||||
"import_sub_url::error",
|
||||
"set_config::error",
|
||||
"core_start::error",
|
||||
"service_core::repair_required",
|
||||
"service_core::app_data_not_owned",
|
||||
"service_core::sidecar_fallback",
|
||||
"dns_override::auto_disabled",
|
||||
"enhance::discarded_keys",
|
||||
"tun_mode::auto_disabled",
|
||||
"tun_mode::auto_disable_failed",
|
||||
"app_restart::core_stop_failed",
|
||||
"app_quit::core_stop_failed",
|
||||
"update_with_clash_proxy",
|
||||
"update_failed_even_with_clash",
|
||||
"reactivate_profiles::error",
|
||||
"update_failed",
|
||||
"config_validate::boot_error",
|
||||
"config_validate::error",
|
||||
"config_validate::process_terminated",
|
||||
"config_validate::script_error",
|
||||
"config_validate::script_syntax_error",
|
||||
"config_validate::script_missing_main",
|
||||
"config_validate::file_not_found",
|
||||
"config_validate::yaml_syntax_error",
|
||||
"config_validate::yaml_read_error",
|
||||
"config_validate::yaml_mapping_error",
|
||||
"config_validate::merge_syntax_error",
|
||||
"config_validate::merge_mapping_error",
|
||||
"config_core::change_success",
|
||||
"config_core::change_error",
|
||||
"mixed_port::fallback",
|
||||
"mixed_port::fallback_error",
|
||||
"config_validate::core_change",
|
||||
"config_validate::stdout_error",
|
||||
"config_validate::yaml_key_error",
|
||||
"config_validate::yaml_error",
|
||||
"config_validate::merge_key_error",
|
||||
"config_validate::merge_error",
|
||||
"set_config::ok",
|
||||
];
|
||||
let actual: Vec<_> = statuses
|
||||
.into_iter()
|
||||
.map(serde_json::to_value)
|
||||
.collect::<Result<_, _>>()?;
|
||||
assert_eq!(actual, expected.map(serde_json::Value::from));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
use super::NoticeStatus;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::Mutex;
|
||||
use serde_json::json;
|
||||
use smartstring::alias::String;
|
||||
use std::sync::Arc;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
future::Future,
|
||||
@@ -17,8 +19,8 @@ pub enum FrontendEvent<'a> {
|
||||
RefreshProfiles,
|
||||
RefreshProxyConfig,
|
||||
NoticeMessage {
|
||||
status: &'a str,
|
||||
message: String,
|
||||
status: NoticeStatus,
|
||||
message: Arc<str>,
|
||||
},
|
||||
ProfileChanged {
|
||||
current_profile_id: &'a String,
|
||||
@@ -323,9 +325,10 @@ impl NotificationSystem {
|
||||
FrontendEvent::RefreshVerge => ("verge://refresh-verge-config", Ok(json!("yes"))),
|
||||
FrontendEvent::RefreshProfiles => ("verge://refresh-profiles", Ok(json!("yes"))),
|
||||
FrontendEvent::RefreshProxyConfig => ("verge://refresh-proxy-config", Ok(serde_json::Value::Null)),
|
||||
FrontendEvent::NoticeMessage { status, message } => {
|
||||
("verge://notice-message", serde_json::to_value((status, message)))
|
||||
}
|
||||
FrontendEvent::NoticeMessage { status, message } => (
|
||||
"verge://notice-message",
|
||||
serde_json::to_value((status, message.as_ref())),
|
||||
),
|
||||
FrontendEvent::ProfileChanged { current_profile_id } => ("profile-changed", Ok(json!(current_profile_id))),
|
||||
FrontendEvent::TimerUpdated { profile_index } => ("verge://timer-updated", Ok(json!(profile_index))),
|
||||
FrontendEvent::ProfileUpdateStarted { uid } => ("profile-update-started", Ok(json!({ "uid": uid }))),
|
||||
@@ -353,3 +356,79 @@ impl NotificationSystem {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod wire_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn frontend_event_wire_contract() -> Result<(), serde_json::Error> {
|
||||
let uid = String::from("profile");
|
||||
let events = [
|
||||
(
|
||||
FrontendEvent::RefreshClash,
|
||||
"verge://refresh-clash-config",
|
||||
json!("yes"),
|
||||
),
|
||||
(
|
||||
FrontendEvent::RefreshVerge,
|
||||
"verge://refresh-verge-config",
|
||||
json!("yes"),
|
||||
),
|
||||
(FrontendEvent::RefreshProfiles, "verge://refresh-profiles", json!("yes")),
|
||||
(
|
||||
FrontendEvent::RefreshProxyConfig,
|
||||
"verge://refresh-proxy-config",
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
FrontendEvent::NoticeMessage {
|
||||
status: NoticeStatus::SetConfigOk,
|
||||
message: Arc::from("ok"),
|
||||
},
|
||||
"verge://notice-message",
|
||||
json!(["set_config::ok", "ok"]),
|
||||
),
|
||||
(
|
||||
FrontendEvent::TimerUpdated { profile_index: &uid },
|
||||
"verge://timer-updated",
|
||||
json!("profile"),
|
||||
),
|
||||
(
|
||||
FrontendEvent::RunStateChanged {
|
||||
state: json!({"running": true}),
|
||||
},
|
||||
"verge://run-state-changed",
|
||||
json!({"running": true}),
|
||||
),
|
||||
(
|
||||
FrontendEvent::PendingFailuresChanged,
|
||||
"verge://pending-failures-changed",
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
FrontendEvent::ProfileChanged {
|
||||
current_profile_id: &uid,
|
||||
},
|
||||
"profile-changed",
|
||||
json!("profile"),
|
||||
),
|
||||
(
|
||||
FrontendEvent::ProfileUpdateStarted { uid: &uid },
|
||||
"profile-update-started",
|
||||
json!({"uid": "profile"}),
|
||||
),
|
||||
(
|
||||
FrontendEvent::ProfileUpdateCompleted { uid: &uid },
|
||||
"profile-update-completed",
|
||||
json!({"uid": "profile"}),
|
||||
),
|
||||
];
|
||||
for (event, name, payload) in events {
|
||||
let (actual_name, actual_payload) = NotificationSystem::serialize_event(event);
|
||||
assert_eq!(actual_name, name);
|
||||
assert_eq!(actual_payload?, payload);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -522,25 +522,34 @@ pub async fn clear() -> Result<()> {
|
||||
|
||||
/// A failed system call is usually a transient RPC hiccup, so give it a few tries.
|
||||
async fn clear_with_retry() -> Result<()> {
|
||||
for attempt in 1..CLEAR_ATTEMPTS {
|
||||
match clear_inner().await {
|
||||
Err(error)
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
|
||||
CLEAR_RETRY_DELAY,
|
||||
),
|
||||
|attempt| async move {
|
||||
clear_inner().await.map_err(|error| {
|
||||
if matches!(
|
||||
SysproxyFailure::from_chain(&error),
|
||||
Some(SysproxyFailure::SystemCallFailed)
|
||||
) =>
|
||||
{
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"clearing the system proxy failed (attempt {attempt}/{CLEAR_ATTEMPTS}); retrying: {error:#}"
|
||||
);
|
||||
tokio::time::sleep(CLEAR_RETRY_DELAY).await;
|
||||
}
|
||||
other => return other,
|
||||
}
|
||||
}
|
||||
clear_inner().await
|
||||
) {
|
||||
if attempt + 1 < CLEAR_ATTEMPTS as usize {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"clearing the system proxy failed (attempt {}/{CLEAR_ATTEMPTS}); retrying: {error:#}",
|
||||
attempt + 1
|
||||
);
|
||||
}
|
||||
RetryError::Retry(error)
|
||||
} else {
|
||||
RetryError::Stop(error)
|
||||
}
|
||||
})
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(route = tracing::field::Empty))]
|
||||
|
||||
@@ -130,20 +130,21 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
|
||||
/// Retries transport failures but stops at the first readable reply, including a rejection.
|
||||
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
|
||||
let mut last_error = None;
|
||||
for attempt in 0..attempts {
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| {
|
||||
ReadyWaitError::Unreachable(anyhow::anyhow!(
|
||||
"service readiness wait was configured with no attempts"
|
||||
))
|
||||
})?;
|
||||
retry(RetryPolicy::fixed(attempts, interval), |_| async {
|
||||
match self.env.probe_service_version().await {
|
||||
Ok(reply) => return self.record_reply(&reply).map_err(ReadyWaitError::Rejected),
|
||||
Err(error) => last_error = Some(error),
|
||||
Ok(reply) => self
|
||||
.record_reply(&reply)
|
||||
.map_err(|error| RetryError::Stop(ReadyWaitError::Rejected(error))),
|
||||
Err(error) => Err(RetryError::Retry(ReadyWaitError::Unreachable(error))),
|
||||
}
|
||||
if attempt + 1 < attempts {
|
||||
tokio::time::sleep(interval).await;
|
||||
}
|
||||
}
|
||||
|
||||
Err(ReadyWaitError::Unreachable(last_error.unwrap_or_else(|| {
|
||||
anyhow::anyhow!("service readiness wait was configured with no attempts")
|
||||
})))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn record_reply(&self, reply: &ServiceVersionReply) -> Result<RunState> {
|
||||
|
||||
+114
-85
@@ -1,3 +1,4 @@
|
||||
use crate::core::notify::NoticeStatus;
|
||||
use crate::utils::dirs;
|
||||
use crate::{
|
||||
config::{Config, runtime::IRuntime},
|
||||
@@ -63,7 +64,7 @@ pub(crate) fn is_not_auto_started(reason: &str) -> bool {
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(crate) fn notify_service_fallback(reason: &str) {
|
||||
*PENDING_SERVICE_FALLBACK_NOTICE.lock() = Some(reason.to_owned());
|
||||
Handle::notice_message("service_core::sidecar_fallback", "");
|
||||
Handle::notice(NoticeStatus::ServiceCoreSidecarFallback, "");
|
||||
}
|
||||
|
||||
pub(crate) fn take_service_fallback_notice() -> Option<ServiceFallbackNotice> {
|
||||
@@ -351,35 +352,40 @@ static SERVICE_CORE_STAGING_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))]
|
||||
fn create_service_core_staging_file(directory: &Path, core_name: &std::ffi::OsStr) -> Result<(PathBuf, std::fs::File)> {
|
||||
for _ in 0..32 {
|
||||
let generation = SERVICE_CORE_STAGING_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
let temporary_name = format!(
|
||||
".{}.{}.{generation}.tmp",
|
||||
core_name.to_string_lossy(),
|
||||
std::process::id()
|
||||
);
|
||||
let temporary_path = directory.join(temporary_name);
|
||||
match std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary_path)
|
||||
{
|
||||
Ok(file) => return Ok((temporary_path, file)),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(error) => {
|
||||
return Err(error).with_context(|| {
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
|
||||
retry_sync(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(31),
|
||||
std::time::Duration::ZERO,
|
||||
),
|
||||
|_| {
|
||||
let generation = SERVICE_CORE_STAGING_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
let temporary_name = format!(
|
||||
".{}.{}.{generation}.tmp",
|
||||
core_name.to_string_lossy(),
|
||||
std::process::id()
|
||||
);
|
||||
let temporary_path = directory.join(temporary_name);
|
||||
match std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temporary_path)
|
||||
{
|
||||
Ok(file) => Ok((temporary_path, file)),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||
Err(RetryError::Retry(anyhow::anyhow!(
|
||||
"failed to create a unique temporary development Service core in {}",
|
||||
directory.display()
|
||||
)))
|
||||
}
|
||||
Err(error) => Err(RetryError::Stop(anyhow::Error::from(error).context({
|
||||
format!(
|
||||
"failed to create temporary development Service core {}",
|
||||
temporary_path.display()
|
||||
)
|
||||
});
|
||||
}))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bail!(
|
||||
"failed to create a unique temporary development Service core in {}",
|
||||
directory.display()
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
@@ -923,11 +929,11 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
||||
#[cfg(target_os = "windows")]
|
||||
if response.code == ServiceErrorCode::InvalidInstallLocation as u16 {
|
||||
PENDING_SERVICE_REPAIR_NOTICE.store(true, Ordering::Relaxed);
|
||||
Handle::notice_message("service_core::repair_required", "");
|
||||
Handle::notice(NoticeStatus::ServiceCoreRepairRequired, "");
|
||||
}
|
||||
if response.code == ServiceErrorCode::AppDataRootNotOwned as u16 {
|
||||
*PENDING_SERVICE_OWNER_NOTICE.lock() = app_data_owner_command(&credentials);
|
||||
Handle::notice_message("service_core::app_data_not_owned", "");
|
||||
Handle::notice(NoticeStatus::ServiceCoreAppDataNotOwned, "");
|
||||
}
|
||||
start_owner_monitor();
|
||||
return Err(record_service_start_refusal(
|
||||
@@ -1050,38 +1056,47 @@ pub(crate) fn request_runtime_provider_sync(delay: Duration) {
|
||||
}
|
||||
AsyncHandler::spawn(move || async move {
|
||||
tokio::time::sleep(delay).await;
|
||||
for attempt in 1..=RUNTIME_PROVIDER_SYNC_ATTEMPTS {
|
||||
let outcome = {
|
||||
let _serial = PROVIDER_SYNC_SERIAL.lock().await;
|
||||
if attempt == 1 {
|
||||
PROVIDER_SYNC_QUEUED.store(false, Ordering::Release);
|
||||
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(())
|
||||
}
|
||||
}
|
||||
sync_runtime_providers_by_service().await
|
||||
};
|
||||
match outcome {
|
||||
Ok(ProviderSync { pending: 0, .. }) => return,
|
||||
Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
"{pending} provider caches are not ready yet; retrying"
|
||||
);
|
||||
}
|
||||
Ok(ProviderSync { pending, .. }) => {
|
||||
logging!(warn, Type::Service, "{pending} provider caches were not synced");
|
||||
return;
|
||||
}
|
||||
Err(error) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"failed to sync provider caches from the service: {error:#}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY).await;
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1389,21 +1404,29 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> {
|
||||
.file_name()
|
||||
.map(|name| name.to_string_lossy())
|
||||
.unwrap_or_default();
|
||||
for _ in 0..8 {
|
||||
let sequence = SYNC_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let temp = target.with_file_name(format!(".{name}.sync-{}-{sequence}.tmp", std::process::id()));
|
||||
match tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
.await
|
||||
{
|
||||
Ok(file) => return Ok((temp, file)),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(error) => return Err(error).with_context(|| format!("failed to create {}", temp.display())),
|
||||
}
|
||||
}
|
||||
bail!("no free temporary name beside {}", target.display())
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
retry(
|
||||
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
|
||||
|_| async {
|
||||
let sequence = SYNC_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
|
||||
let temp = target.with_file_name(format!(".{name}.sync-{}-{sequence}.tmp", std::process::id()));
|
||||
match tokio::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&temp)
|
||||
.await
|
||||
{
|
||||
Ok(file) => Ok((temp, file)),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Err(RetryError::Retry(
|
||||
anyhow::anyhow!("no free temporary name beside {}", target.display()),
|
||||
)),
|
||||
Err(error) => Err(RetryError::Stop(
|
||||
anyhow::anyhow!(error).context(format!("failed to create {}", temp.display())),
|
||||
)),
|
||||
}
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn same_contents(temp: &Path, target: &Path) -> bool {
|
||||
@@ -1647,7 +1670,7 @@ fn report_service_core_stopped(status: &ServiceStatusSnapshot) {
|
||||
);
|
||||
logging!(error, Type::Service, "service core stopped: {detail}");
|
||||
CoreManager::global().record_startup_error(CoreFailure::ServiceCoreStopped(detail));
|
||||
Handle::notice_message("core_start::error", "");
|
||||
Handle::notice(NoticeStatus::CoreStartError, "");
|
||||
}
|
||||
|
||||
/// Samples ownership, treating every unusable reply as unreadable.
|
||||
@@ -1776,22 +1799,28 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
|
||||
}
|
||||
|
||||
async fn clear_proxy_after_owner_loss() {
|
||||
let mut last_error = None;
|
||||
for attempt in 1..=3 {
|
||||
match proxy_control::clear().await {
|
||||
Ok(()) => return,
|
||||
Err(error) => {
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
let result = retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(2),
|
||||
Duration::from_millis(100),
|
||||
),
|
||||
|index| async move {
|
||||
let attempt = index + 1;
|
||||
proxy_control::clear().await.map_err(|error| {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"proxy clear attempt {attempt}/3 after owner loss failed: {error:#}"
|
||||
);
|
||||
last_error = Some(error);
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(error) = last_error {
|
||||
RetryError::Retry(error)
|
||||
})
|
||||
},
|
||||
)
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
// The existing recovery path also waits after its final failed clear.
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use crate::config::{IProfilePreview, IVerge};
|
||||
use crate::core::lightweight;
|
||||
use crate::core::tray::menu_def::TrayAction;
|
||||
use crate::module::lightweight;
|
||||
use crate::process::AsyncHandler;
|
||||
use crate::singleton;
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use crate::{
|
||||
Type, cmd,
|
||||
config::Config,
|
||||
core::lightweight::is_in_lightweight_mode,
|
||||
feat, logging,
|
||||
module::lightweight::is_in_lightweight_mode,
|
||||
utils::{dirs::find_target_icons, help},
|
||||
};
|
||||
use clash_verge_limiter::{Limiter, SystemClock, SystemLimiter};
|
||||
|
||||
@@ -570,12 +570,14 @@ impl SilentUpdater {
|
||||
|
||||
// The new webview may not accept evaluation immediately.
|
||||
std::thread::spawn(move || {
|
||||
for i in 0..10 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100 * (i + 1)));
|
||||
if window.eval(&js).is_ok() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
|
||||
let _ = retry_sync(
|
||||
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(9), std::time::Duration::ZERO),
|
||||
|index| {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100 * (index as u64 + 1)));
|
||||
window.eval(&js).map_err(RetryError::Retry)
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
logging!(info, Type::System, "Update splash window shown");
|
||||
@@ -632,8 +634,8 @@ impl SilentUpdater {
|
||||
Type::System,
|
||||
"Silent updater: breaking change detected in v{version}, notifying frontend"
|
||||
);
|
||||
super::handle::Handle::notice_message(
|
||||
"info",
|
||||
super::handle::Handle::notice(
|
||||
super::notify::NoticeStatus::Info,
|
||||
format!("New version v{version} contains breaking changes. Please update manually."),
|
||||
);
|
||||
return Ok(());
|
||||
@@ -679,6 +681,7 @@ impl SilentUpdater {
|
||||
}
|
||||
|
||||
pub async fn start_background_check(&self, app_handle: tauri::AppHandle) {
|
||||
// Permanent watcher: daily update cycles for the lifetime of the app.
|
||||
logging!(info, Type::System, "Silent updater: background task started");
|
||||
|
||||
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
|
||||
|
||||
Reference in New Issue
Block a user