mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-01-29 08:45:41 +08:00
refactor(async): migrate from sync-blocking async execution to true async with unified AsyncHandler::spawn (#4502)
* feat: replace all tokio::spawn with unified AsyncHandler::spawn - 🚀 Core Improvements: * Replace all tokio::spawn calls with AsyncHandler::spawn for unified Tauri async task management * Prioritize converting sync functions to async functions to reduce spawn usage * Use .await directly in async contexts instead of spawn - 🔧 Major Changes: * core/hotkey.rs: Use AsyncHandler::spawn for hotkey callback functions * module/lightweight.rs: Async lightweight mode switching * feat/window.rs: Convert window operation functions to async, use .await internally * feat/proxy.rs, feat/clash.rs: Async proxy and mode switching functions * lib.rs: Window focus handling with AsyncHandler::spawn * core/tray/mod.rs: Complete async tray event handling - ✨ Technical Advantages: * Unified task tracking and debugging capabilities (via tokio-trace feature) * Better error handling and task management * Consistency with Tauri runtime * Reduced async boundaries for better performance - 🧪 Verification: * Compilation successful with 0 errors, 0 warnings * Maintains complete original functionality * Optimized async execution flow * feat: complete tokio fs migration and replace tokio::spawn with AsyncHandler 🚀 Major achievements: - Migrate 8 core modules from std::fs to tokio::fs - Create 6 Send-safe wrapper functions using spawn_blocking pattern - Replace all tokio::spawn calls with AsyncHandler::spawn for unified async task management - Solve all 19 Send trait compilation errors through innovative spawn_blocking architecture 🔧 Core changes: - config/profiles.rs: Add profiles_*_safe functions to handle Send trait constraints - cmd/profile.rs: Update all Tauri commands to use Send-safe operations - config/prfitem.rs: Replace append_item calls with profiles_append_item_safe - utils/help.rs: Convert YAML operations to async (read_yaml, save_yaml) - Multiple modules: Replace tokio::task::spawn_blocking with AsyncHandler::spawn_blocking ✅ Technical innovations: - spawn_blocking wrapper pattern resolves parking_lot RwLock Send trait conflicts - Maintain parking_lot performance while achieving Tauri async command compatibility - Preserve backwards compatibility with gradual migration strategy 🎯 Results: - Zero compilation errors - Zero warnings - All async file operations working correctly - Complete Send trait compliance for Tauri commands * feat: refactor app handle and command functions to use async/await for improved performance * feat: update async handling in profiles and logging functions for improved error handling and performance * fix: update TRACE_MINI_SIZE constant to improve task logging threshold * fix(windows): convert service management functions to async for improved performance * fix: convert service management functions to async for improved responsiveness * fix(ubuntu): convert install and reinstall service functions to async for improved performance * fix(linux): convert uninstall_service function to async for improved performance * fix: convert uninstall_service call to async for improved performance * fix: convert file and directory creation calls to async for improved performance * fix: convert hotkey functions to async for improved responsiveness * chore: update UPDATELOG.md for v2.4.1 with major improvements and performance optimizations
This commit is contained in:
@@ -1,14 +1,14 @@
|
||||
use super::{Draft, IClashTemp, IProfiles, IRuntime, IVerge};
|
||||
use crate::{
|
||||
config::PrfItem,
|
||||
config::{profiles::profiles_append_item_safe, PrfItem},
|
||||
core::{handle, CoreManager},
|
||||
enhance, logging,
|
||||
process::AsyncHandler,
|
||||
utils::{dirs, help, logging::Type},
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
use once_cell::sync::OnceCell;
|
||||
use std::path::PathBuf;
|
||||
use tokio::sync::OnceCell;
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
pub const RUNTIME_CONFIG: &str = "clash-verge.yaml";
|
||||
@@ -22,64 +22,65 @@ pub struct Config {
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn global() -> &'static Config {
|
||||
static CONFIG: OnceCell<Config> = OnceCell::new();
|
||||
|
||||
CONFIG.get_or_init(|| Config {
|
||||
clash_config: Draft::from(Box::new(IClashTemp::new())),
|
||||
verge_config: Draft::from(Box::new(IVerge::new())),
|
||||
profiles_config: Draft::from(Box::new(IProfiles::new())),
|
||||
runtime_config: Draft::from(Box::new(IRuntime::new())),
|
||||
})
|
||||
pub async fn global() -> &'static Config {
|
||||
static CONFIG: OnceCell<Config> = OnceCell::const_new();
|
||||
CONFIG
|
||||
.get_or_init(|| async {
|
||||
Config {
|
||||
clash_config: Draft::from(Box::new(IClashTemp::new().await)),
|
||||
verge_config: Draft::from(Box::new(IVerge::new().await)),
|
||||
profiles_config: Draft::from(Box::new(IProfiles::new().await)),
|
||||
runtime_config: Draft::from(Box::new(IRuntime::new())),
|
||||
}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn clash() -> Draft<Box<IClashTemp>> {
|
||||
Self::global().clash_config.clone()
|
||||
pub async fn clash() -> Draft<Box<IClashTemp>> {
|
||||
Self::global().await.clash_config.clone()
|
||||
}
|
||||
|
||||
pub fn verge() -> Draft<Box<IVerge>> {
|
||||
Self::global().verge_config.clone()
|
||||
pub async fn verge() -> Draft<Box<IVerge>> {
|
||||
Self::global().await.verge_config.clone()
|
||||
}
|
||||
|
||||
pub fn profiles() -> Draft<Box<IProfiles>> {
|
||||
Self::global().profiles_config.clone()
|
||||
pub async fn profiles() -> Draft<Box<IProfiles>> {
|
||||
Self::global().await.profiles_config.clone()
|
||||
}
|
||||
|
||||
pub fn runtime() -> Draft<Box<IRuntime>> {
|
||||
Self::global().runtime_config.clone()
|
||||
pub async fn runtime() -> Draft<Box<IRuntime>> {
|
||||
Self::global().await.runtime_config.clone()
|
||||
}
|
||||
|
||||
/// 初始化订阅
|
||||
pub async fn init_config() -> Result<()> {
|
||||
if Self::profiles()
|
||||
.await
|
||||
.latest_ref()
|
||||
.get_item(&"Merge".to_string())
|
||||
.is_err()
|
||||
{
|
||||
let merge_item = PrfItem::from_merge(Some("Merge".to_string()))?;
|
||||
Self::profiles()
|
||||
.data_mut()
|
||||
.append_item(merge_item.clone())?;
|
||||
profiles_append_item_safe(merge_item.clone()).await?;
|
||||
}
|
||||
if Self::profiles()
|
||||
.await
|
||||
.latest_ref()
|
||||
.get_item(&"Script".to_string())
|
||||
.is_err()
|
||||
{
|
||||
let script_item = PrfItem::from_script(Some("Script".to_string()))?;
|
||||
Self::profiles()
|
||||
.data_mut()
|
||||
.append_item(script_item.clone())?;
|
||||
profiles_append_item_safe(script_item.clone()).await?;
|
||||
}
|
||||
// 生成运行时配置
|
||||
if let Err(err) = Self::generate() {
|
||||
if let Err(err) = Self::generate().await {
|
||||
logging!(error, Type::Config, true, "生成运行时配置失败: {}", err);
|
||||
} else {
|
||||
logging!(info, Type::Config, true, "生成运行时配置成功");
|
||||
}
|
||||
|
||||
// 生成运行时配置文件并验证
|
||||
let config_result = Self::generate_file(ConfigType::Run);
|
||||
let config_result = Self::generate_file(ConfigType::Run).await;
|
||||
|
||||
let validation_result = if config_result.is_ok() {
|
||||
// 验证配置文件
|
||||
@@ -96,7 +97,8 @@ impl Config {
|
||||
error_msg
|
||||
);
|
||||
CoreManager::global()
|
||||
.use_default_config("config_validate::boot_error", &error_msg)?;
|
||||
.use_default_config("config_validate::boot_error", &error_msg)
|
||||
.await?;
|
||||
Some(("config_validate::boot_error", error_msg))
|
||||
} else {
|
||||
logging!(info, Type::Config, true, "配置验证成功");
|
||||
@@ -106,13 +108,16 @@ impl Config {
|
||||
Err(err) => {
|
||||
logging!(warn, Type::Config, true, "验证进程执行失败: {}", err);
|
||||
CoreManager::global()
|
||||
.use_default_config("config_validate::process_terminated", "")?;
|
||||
.use_default_config("config_validate::process_terminated", "")
|
||||
.await?;
|
||||
Some(("config_validate::process_terminated", String::new()))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logging!(warn, Type::Config, true, "生成配置文件失败,使用默认配置");
|
||||
CoreManager::global().use_default_config("config_validate::error", "")?;
|
||||
CoreManager::global()
|
||||
.use_default_config("config_validate::error", "")
|
||||
.await?;
|
||||
Some(("config_validate::error", String::new()))
|
||||
};
|
||||
|
||||
@@ -128,28 +133,30 @@ impl Config {
|
||||
}
|
||||
|
||||
/// 将订阅丢到对应的文件中
|
||||
pub fn generate_file(typ: ConfigType) -> Result<PathBuf> {
|
||||
pub async fn generate_file(typ: ConfigType) -> Result<PathBuf> {
|
||||
let path = match typ {
|
||||
ConfigType::Run => dirs::app_home_dir()?.join(RUNTIME_CONFIG),
|
||||
ConfigType::Check => dirs::app_home_dir()?.join(CHECK_CONFIG),
|
||||
};
|
||||
|
||||
let runtime = Config::runtime();
|
||||
let runtime = runtime.latest_ref();
|
||||
let runtime = Config::runtime().await;
|
||||
let config = runtime
|
||||
.latest_ref()
|
||||
.config
|
||||
.as_ref()
|
||||
.ok_or(anyhow!("failed to get runtime config"))?;
|
||||
.ok_or(anyhow!("failed to get runtime config"))?
|
||||
.clone();
|
||||
drop(runtime); // 显式释放锁
|
||||
|
||||
help::save_yaml(&path, &config, Some("# Generated by Clash Verge"))?;
|
||||
help::save_yaml(&path, &config, Some("# Generated by Clash Verge")).await?;
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// 生成订阅存好
|
||||
pub fn generate() -> Result<()> {
|
||||
let (config, exists_keys, logs) = enhance::enhance();
|
||||
pub async fn generate() -> Result<()> {
|
||||
let (config, exists_keys, logs) = enhance::enhance().await;
|
||||
|
||||
*Config::runtime().draft_mut() = Box::new(IRuntime {
|
||||
*Config::runtime().await.draft_mut() = Box::new(IRuntime {
|
||||
config: Some(config),
|
||||
exists_keys,
|
||||
chain_logs: logs,
|
||||
|
||||
Reference in New Issue
Block a user