refactor: clean up and improve code structure (#6010)

This commit is contained in:
Tunglies
2026-01-04 19:21:45 +08:00
committed by GitHub
parent 421bbd090e
commit 9e4e0c81a4
10 changed files with 49 additions and 268 deletions
+9 -8
View File
@@ -53,16 +53,16 @@ impl Operation {
}
pub struct WebDavClient {
config: Arc<ArcSwapOption<WebDavConfig>>,
clients: Arc<ArcSwap<HashMap<Operation, reqwest_dav::Client>>>,
config: ArcSwapOption<WebDavConfig>,
clients: ArcSwap<HashMap<Operation, reqwest_dav::Client>>,
}
impl WebDavClient {
pub fn global() -> &'static Self {
static WEBDAV_CLIENT: OnceCell<WebDavClient> = OnceCell::new();
WEBDAV_CLIENT.get_or_init(|| Self {
config: Arc::new(ArcSwapOption::new(None)),
clients: Arc::new(ArcSwap::new(Arc::new(HashMap::new()))),
config: ArcSwapOption::new(None),
clients: ArcSwap::new(Arc::new(HashMap::new())),
})
}
@@ -147,11 +147,12 @@ impl WebDavClient {
}
}
// 缓存客户端(替换 Arc<Mutex<HashMap<...>>> 的写法)
{
let mut map = (**self.clients.load()).clone();
map.insert(op, client.clone());
self.clients.store(map.into());
self.clients.rcu(|clients_map| {
let mut new_map = (**clients_map).clone();
new_map.insert(op, client.clone());
Arc::new(new_map)
});
}
Ok(client)
+14 -66
View File
@@ -1,24 +1,19 @@
use crate::{APP_HANDLE, constants::timing, singleton};
use crate::{APP_HANDLE, singleton, utils::window_manager::WindowManager};
use parking_lot::RwLock;
use smartstring::alias::String;
use std::{
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
thread,
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use tauri::{AppHandle, Manager as _, WebviewWindow};
use tauri_plugin_mihomo::{Mihomo, MihomoExt as _};
use tokio::sync::RwLockReadGuard;
use super::notification::{ErrorMessage, FrontendEvent, NotificationSystem};
use super::notification::{FrontendEvent, NotificationSystem};
#[derive(Debug)]
pub struct Handle {
is_exiting: AtomicBool,
startup_errors: Arc<RwLock<Vec<ErrorMessage>>>,
startup_completed: AtomicBool,
pub(crate) notification_system: Arc<RwLock<Option<NotificationSystem>>>,
}
@@ -26,8 +21,6 @@ impl Default for Handle {
fn default() -> Self {
Self {
is_exiting: AtomicBool::new(false),
startup_errors: Arc::new(RwLock::new(Vec::new())),
startup_completed: AtomicBool::new(false),
notification_system: Arc::new(RwLock::new(Some(NotificationSystem::new()))),
}
}
@@ -47,7 +40,7 @@ impl Handle {
let mut system_opt = self.notification_system.write();
if let Some(system) = system_opt.as_mut()
&& !system.is_running
&& !system.is_running()
{
system.start();
}
@@ -111,21 +104,19 @@ impl Handle {
// TODO 利用 &str 等缩短 Clone
pub fn notice_message<S: Into<String>, M: Into<String>>(status: S, msg: M) {
let handle = Self::global();
let status_str = status.into();
let msg_str = msg.into();
if !handle.startup_completed.load(Ordering::Acquire) {
handle.startup_errors.write().push(ErrorMessage {
status: status_str,
message: msg_str,
});
return;
}
if handle.is_exiting() {
return;
}
// We only send notice when main window exists
if WindowManager::get_main_window().is_none() {
return;
}
let status_str = status.into();
let msg_str = msg.into();
Self::send_event(FrontendEvent::NoticeMessage {
status: status_str,
message: msg_str,
@@ -144,49 +135,6 @@ impl Handle {
}
}
pub fn mark_startup_completed(&self) {
self.startup_completed.store(true, Ordering::Release);
self.send_startup_errors();
}
fn send_startup_errors(&self) {
let errors = {
let mut errors = self.startup_errors.write();
std::mem::take(&mut *errors)
};
if errors.is_empty() {
return;
}
let _ = thread::Builder::new()
.name("startup-errors-sender".into())
.spawn(move || {
thread::sleep(timing::STARTUP_ERROR_DELAY);
let handle = Self::global();
if handle.is_exiting() {
return;
}
let system_opt = handle.notification_system.read();
if let Some(system) = system_opt.as_ref() {
for error in errors {
if handle.is_exiting() {
break;
}
system.send_event(FrontendEvent::NoticeMessage {
status: error.status,
message: error.message,
});
thread::sleep(timing::ERROR_BATCH_DELAY);
}
}
});
}
pub fn set_is_exiting(&self) {
self.is_exiting.store(true, Ordering::Release);
-2
View File
@@ -134,7 +134,6 @@ impl Logger {
/// only update app log level
pub fn update_log_level(&self, level: LevelFilter) -> Result<()> {
println!("refresh log level");
*self.log_level.write() = level;
let log_level = self.log_level.read().to_owned();
if let Some(handle) = self.handle.lock().as_mut() {
@@ -149,7 +148,6 @@ impl Logger {
/// update app and mihomo core log config
pub async fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<()> {
println!("refresh log file");
self.log_max_size.store(log_max_size, Ordering::SeqCst);
self.log_max_count.store(log_max_count, Ordering::SeqCst);
if let Some(handle) = self.handle.lock().as_ref() {
+12 -67
View File
@@ -1,16 +1,8 @@
use super::handle::Handle;
use crate::constants::{retry, timing};
use crate::constants::timing;
use clash_verge_logging::{Type, logging};
use parking_lot::RwLock;
use smartstring::alias::String;
use std::{
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
mpsc,
},
thread,
time::Instant,
};
use std::{sync::mpsc, thread};
use tauri::{Emitter as _, WebviewWindow};
// TODO 重构或优化,避免 Clone 过多
@@ -25,27 +17,11 @@ pub enum FrontendEvent {
ProfileUpdateCompleted { uid: String },
}
#[derive(Debug, Default)]
struct EventStats {
total_sent: AtomicU64,
total_errors: AtomicU64,
last_error_time: RwLock<Option<Instant>>,
}
#[derive(Debug, Clone)]
pub struct ErrorMessage {
pub status: String,
pub message: String,
}
#[derive(Debug)]
pub struct NotificationSystem {
sender: Option<mpsc::Sender<FrontendEvent>>,
#[allow(clippy::type_complexity)]
worker_handle: Option<thread::JoinHandle<()>>,
pub(super) is_running: bool,
stats: EventStats,
emergency_mode: AtomicBool,
}
impl Default for NotificationSystem {
@@ -55,25 +31,26 @@ impl Default for NotificationSystem {
}
impl NotificationSystem {
pub fn new() -> Self {
pub const fn new() -> Self {
Self {
sender: None,
worker_handle: None,
is_running: false,
stats: EventStats::default(),
emergency_mode: AtomicBool::new(false),
}
}
pub const fn is_running(&self) -> bool {
self.sender.is_some() && self.worker_handle.is_some()
}
pub fn start(&mut self) {
if self.is_running {
if self.is_running() {
return;
}
let (tx, rx) = mpsc::channel();
self.sender = Some(tx);
self.is_running = true;
//? Do we have to create a new thread for this?
let result = thread::Builder::new()
.name("frontend-notifier".into())
.spawn(move || Self::worker_loop(rx));
@@ -107,10 +84,6 @@ impl NotificationSystem {
None => return,
};
if system.should_skip_event(&event) {
return;
}
if let Some(window) = super::handle::Handle::get_window() {
system.emit_to_window(&window, event);
drop(binding);
@@ -118,30 +91,15 @@ impl NotificationSystem {
}
}
fn should_skip_event(&self, event: &FrontendEvent) -> bool {
let is_emergency = self.emergency_mode.load(Ordering::Acquire);
matches!(
(is_emergency, event),
(true, FrontendEvent::NoticeMessage { status, .. }) if status == "info"
)
}
fn emit_to_window(&self, window: &WebviewWindow, event: FrontendEvent) {
let (event_name, payload) = self.serialize_event(event);
let Ok(payload) = payload else {
self.stats.total_errors.fetch_add(1, Ordering::Relaxed);
return;
};
match window.emit(event_name, payload) {
Ok(_) => {
self.stats.total_sent.fetch_add(1, Ordering::Relaxed);
}
Err(e) => {
logging!(warn, Type::Frontend, "Event emit failed: {}", e);
self.handle_emit_error();
}
if let Err(e) = window.emit(event_name, payload) {
logging!(warn, Type::Frontend, "Event emit failed: {}", e);
}
}
@@ -161,19 +119,8 @@ impl NotificationSystem {
}
}
fn handle_emit_error(&self) {
self.stats.total_errors.fetch_add(1, Ordering::Relaxed);
*self.stats.last_error_time.write() = Some(Instant::now());
let errors = self.stats.total_errors.load(Ordering::Relaxed);
if errors > retry::EVENT_EMIT_THRESHOLD && !self.emergency_mode.load(Ordering::Acquire) {
logging!(warn, Type::Frontend, "Entering emergency mode after {} errors", errors);
self.emergency_mode.store(true, Ordering::Release);
}
}
pub fn send_event(&self, event: FrontendEvent) -> bool {
if self.should_skip_event(&event) {
if !self.is_running() {
return false;
}
@@ -185,8 +132,6 @@ impl NotificationSystem {
}
pub fn shutdown(&mut self) {
self.is_running = false;
if let Some(sender) = self.sender.take() {
drop(sender);
}
+5 -8
View File
@@ -1,10 +1,3 @@
use governor::{DefaultDirectRateLimiter, Quota, RateLimiter};
use tauri::tray::TrayIconBuilder;
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
use tauri_plugin_mihomo::models::Proxies;
use tokio::fs;
#[cfg(target_os = "macos")]
pub mod speed_rate;
use crate::config::{IProfilePreview, IVerge};
use crate::core::service;
use crate::core::tray::menu_def::TrayAction;
@@ -16,6 +9,11 @@ use crate::{
Type, cmd, config::Config, feat, logging, module::lightweight::is_in_lightweight_mode,
utils::dirs::find_target_icons,
};
use governor::{DefaultDirectRateLimiter, Quota, RateLimiter};
use tauri::tray::TrayIconBuilder;
use tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin;
use tauri_plugin_mihomo::models::Proxies;
use tokio::fs;
use super::handle;
use anyhow::Result;
@@ -955,7 +953,6 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
}
MenuIds::COPY_ENV => feat::copy_clash_env().await,
MenuIds::CONF_DIR => {
println!("Open directory submenu clicked");
let _ = cmd::open_app_dir().await;
}
MenuIds::CORE_DIR => {
-1
View File
@@ -1 +0,0 @@