refactor: use async instead of block_on

This commit is contained in:
MystiPanda 2024-06-29 19:02:37 +08:00
parent c1a201f358
commit 1293d25e1b
No known key found for this signature in database
11 changed files with 81 additions and 74 deletions

1
src-tauri/Cargo.lock generated
View File

@ -4505,7 +4505,6 @@ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"bytes", "bytes",
"encoding_rs", "encoding_rs",
"futures-channel",
"futures-core", "futures-core",
"futures-util", "futures-util",
"h2 0.4.5", "h2 0.4.5",

View File

@ -35,7 +35,7 @@ percent-encoding = "2.3.1"
window-shadows = { version = "0.2" } window-shadows = { version = "0.2" }
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
reqwest = { version = "0.12", features = ["json", "rustls-tls", "blocking"] } reqwest = { version = "0.12", features = ["json", "rustls-tls"] }
sysproxy = { git="https://github.com/zzzgydi/sysproxy-rs", branch = "main" } sysproxy = { git="https://github.com/zzzgydi/sysproxy-rs", branch = "main" }
tauri = { git="https://github.com/tauri-apps/tauri",branch = "1.x", features = [ "fs-read-file", "fs-exists", "path-all", "protocol-asset", "dialog-open", "notification-all", "icon-png", "icon-ico", "clipboard-all", "global-shortcut-all", "process-all", "shell-all", "system-tray", "updater", "window-all", "devtools"] } tauri = { git="https://github.com/tauri-apps/tauri",branch = "1.x", features = [ "fs-read-file", "fs-exists", "path-all", "protocol-asset", "dialog-open", "notification-all", "icon-png", "icon-ico", "clipboard-all", "global-shortcut-all", "process-all", "shell-all", "system-tray", "updater", "window-all", "devtools"] }
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]

View File

@ -46,8 +46,8 @@ impl Config {
} }
/// 初始化订阅 /// 初始化订阅
pub fn init_config() -> Result<()> { pub async fn init_config() -> Result<()> {
crate::log_err!(Self::generate()); crate::log_err!(Self::generate().await);
if let Err(err) = Self::generate_file(ConfigType::Run) { if let Err(err) = Self::generate_file(ConfigType::Run) {
log::error!(target: "app", "{err}"); log::error!(target: "app", "{err}");
@ -83,8 +83,8 @@ impl Config {
} }
/// 生成订阅存好 /// 生成订阅存好
pub fn generate() -> Result<()> { pub async fn generate() -> Result<()> {
let (config, exists_keys, logs) = enhance::enhance(); let (config, exists_keys, logs) = enhance::enhance().await;
*Config::runtime().draft() = IRuntime { *Config::runtime().draft() = IRuntime {
config: Some(config), config: Some(config),

View File

@ -219,22 +219,18 @@ impl CoreManager {
} }
/// 停止核心运行 /// 停止核心运行
pub fn stop_core(&self) -> Result<()> { pub async fn stop_core(&self) -> Result<()> {
// 关闭tun模式 // 关闭tun模式
tauri::async_runtime::block_on(async move { let mut disable = Mapping::new();
let mut disable = Mapping::new(); let mut tun = Mapping::new();
let mut tun = Mapping::new(); tun.insert("enable".into(), false.into());
tun.insert("enable".into(), false.into()); disable.insert("tun".into(), tun.into());
disable.insert("tun".into(), tun.into()); log::debug!(target: "app", "disable tun mode");
log::debug!(target: "app", "disable tun mode"); let _ = clash_api::patch_configs(&disable).await;
let _ = clash_api::patch_configs(&disable).await;
});
if *self.use_service_mode.lock() { if *self.use_service_mode.lock() {
log::debug!(target: "app", "stop the core by service"); log::debug!(target: "app", "stop the core by service");
tauri::async_runtime::block_on(async move { log_err!(service::stop_core_by_service().await);
log_err!(service::stop_core_by_service().await);
});
return Ok(()); return Ok(());
} }
@ -265,7 +261,7 @@ impl CoreManager {
Config::verge().draft().clash_core = Some(clash_core); Config::verge().draft().clash_core = Some(clash_core);
// 更新订阅 // 更新订阅
Config::generate()?; Config::generate().await?;
self.check_config()?; self.check_config()?;
@ -293,7 +289,7 @@ impl CoreManager {
log::debug!(target: "app", "try to update clash config"); log::debug!(target: "app", "try to update clash config");
// 更新订阅 // 更新订阅
Config::generate()?; Config::generate().await?;
// 检查订阅是否正常 // 检查订阅是否正常
self.check_config()?; self.check_config()?;

View File

@ -314,14 +314,16 @@ pub(super) async fn stop_core_by_service() -> Result<()> {
} }
/// set dns by service /// set dns by service
pub fn set_dns_by_service() -> Result<()> { pub async fn set_dns_by_service() -> Result<()> {
let url = format!("{SERVICE_URL}/set_dns"); let url = format!("{SERVICE_URL}/set_dns");
let res = reqwest::blocking::ClientBuilder::new() let res = reqwest::ClientBuilder::new()
.no_proxy() .no_proxy()
.build()? .build()?
.post(url) .post(url)
.send()? .send()
.await?
.json::<JsonResponse>() .json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?; .context("failed to connect to the Clash Verge Service")?;
if res.code != 0 { if res.code != 0 {
@ -332,14 +334,16 @@ pub fn set_dns_by_service() -> Result<()> {
} }
/// unset dns by service /// unset dns by service
pub fn unset_dns_by_service() -> Result<()> { pub async fn unset_dns_by_service() -> Result<()> {
let url = format!("{SERVICE_URL}/unset_dns"); let url = format!("{SERVICE_URL}/unset_dns");
let res = reqwest::blocking::ClientBuilder::new() let res = reqwest::ClientBuilder::new()
.no_proxy() .no_proxy()
.build()? .build()?
.post(url) .post(url)
.send()? .send()
.await?
.json::<JsonResponse>() .json::<JsonResponse>()
.await
.context("failed to connect to the Clash Verge Service")?; .context("failed to connect to the Clash Verge Service")?;
if res.code != 0 { if res.code != 0 {

View File

@ -18,7 +18,7 @@ type ResultLog = Vec<(String, String)>;
/// Enhance mode /// Enhance mode
/// 返回最终订阅、该订阅包含的键、和script执行的结果 /// 返回最终订阅、该订阅包含的键、和script执行的结果
pub fn enhance() -> (Mapping, Vec<String>, HashMap<String, ResultLog>) { pub async fn enhance() -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
// config.yaml 的订阅 // config.yaml 的订阅
let clash_config = { Config::clash().latest().0.clone() }; let clash_config = { Config::clash().latest().0.clone() };
@ -149,7 +149,7 @@ pub fn enhance() -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
}); });
} }
config = use_tun(config, enable_tun); config = use_tun(config, enable_tun).await;
config = use_sort(config); config = use_sort(config);
let mut exists_set = HashSet::new(); let mut exists_set = HashSet::new();

View File

@ -1,4 +1,4 @@
use crate::core::service; use crate::{core::service, log_err};
use serde_yaml::{Mapping, Value}; use serde_yaml::{Mapping, Value};
macro_rules! revise { macro_rules! revise {
@ -18,7 +18,7 @@ macro_rules! append {
}; };
} }
pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping { pub async fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
let tun_key = Value::from("tun"); let tun_key = Value::from("tun");
let tun_val = config.get(&tun_key); let tun_val = config.get(&tun_key);
@ -35,10 +35,10 @@ pub fn use_tun(mut config: Mapping, enable: bool) -> Mapping {
revise!(config, "tun", tun_val); revise!(config, "tun", tun_val);
if enable { if enable {
let _ = service::set_dns_by_service(); log_err!(service::set_dns_by_service().await);
use_dns_for_tun(config) use_dns_for_tun(config)
} else { } else {
let _ = service::unset_dns_by_service(); log_err!(service::unset_dns_by_service().await);
config config
} }
} }

View File

@ -139,7 +139,7 @@ pub async fn patch_clash(patch: Mapping) -> Result<()> {
|| patch.get("secret").is_some() || patch.get("secret").is_some()
|| patch.get("external-controller").is_some() || patch.get("external-controller").is_some()
{ {
Config::generate()?; Config::generate().await?;
CoreManager::global().run_core().await?; CoreManager::global().run_core().await?;
handle::Handle::refresh_clash(); handle::Handle::refresh_clash();
} }
@ -200,23 +200,23 @@ pub async fn patch_verge(patch: IVerge) -> Result<()> {
if service_mode.is_some() { if service_mode.is_some() {
log::debug!(target: "app", "change service mode to {}", service_mode.unwrap()); log::debug!(target: "app", "change service mode to {}", service_mode.unwrap());
Config::generate()?; Config::generate().await?;
CoreManager::global().run_core().await?; CoreManager::global().run_core().await?;
} else if tun_mode.is_some() { } else if tun_mode.is_some() {
update_core_config().await?; update_core_config().await?;
} }
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
if redir_enabled.is_some() { if redir_enabled.is_some() {
Config::generate()?; Config::generate().await?;
CoreManager::global().run_core().await?; CoreManager::global().run_core().await?;
} }
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
if tproxy_enabled.is_some() { if tproxy_enabled.is_some() {
Config::generate()?; Config::generate().await?;
CoreManager::global().run_core().await?; CoreManager::global().run_core().await?;
} }
if socks_enabled.is_some() || http_enabled.is_some() { if socks_enabled.is_some() || http_enabled.is_some() {
Config::generate()?; Config::generate().await?;
CoreManager::global().run_core().await?; CoreManager::global().run_core().await?;
} }
if auto_launch.is_some() { if auto_launch.is_some() {

View File

@ -15,8 +15,15 @@ use tauri::{api, SystemTray};
fn main() -> std::io::Result<()> { fn main() -> std::io::Result<()> {
// 单例检测 // 单例检测
if server::check_singleton().is_err() { let app_exists: bool = tauri::async_runtime::block_on(async move {
println!("app exists"); if server::check_singleton().await.is_err() {
println!("app exists");
true
} else {
false
}
});
if app_exists {
return Ok(()); return Ok(());
} }
@ -29,7 +36,9 @@ fn main() -> std::io::Result<()> {
let mut builder = tauri::Builder::default() let mut builder = tauri::Builder::default()
.system_tray(SystemTray::new()) .system_tray(SystemTray::new())
.setup(|app| { .setup(|app| {
resolve::resolve_setup(app); tauri::async_runtime::block_on(async move {
resolve::resolve_setup(app).await;
});
Ok(()) Ok(())
}) })
.on_system_tray_event(core::tray::Tray::on_system_tray_event) .on_system_tray_event(core::tray::Tray::on_system_tray_event)

View File

@ -34,7 +34,7 @@ pub fn find_unused_port() -> Result<u16> {
} }
/// handle something when start app /// handle something when start app
pub fn resolve_setup(app: &mut App) { pub async fn resolve_setup(app: &mut App) {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
app.set_activation_policy(tauri::ActivationPolicy::Accessory); app.set_activation_policy(tauri::ActivationPolicy::Accessory);
let version = app.package_info().version.to_string(); let version = app.package_info().version.to_string();
@ -73,7 +73,8 @@ pub fn resolve_setup(app: &mut App) {
// 启动核心 // 启动核心
log::trace!("init config"); log::trace!("init config");
log_err!(Config::init_config());
log_err!(Config::init_config().await);
log::trace!("launch core"); log::trace!("launch core");
log_err!(CoreManager::global().init()); log_err!(CoreManager::global().init());
@ -101,9 +102,7 @@ pub fn resolve_setup(app: &mut App) {
if argvs.len() > 1 { if argvs.len() > 1 {
let param = argvs[1].as_str(); let param = argvs[1].as_str();
if param.starts_with("clash:") { if param.starts_with("clash:") {
tauri::async_runtime::block_on(async { resolve_scheme(argvs[1].to_owned()).await;
resolve_scheme(argvs[1].to_owned()).await;
});
} }
} }
} }
@ -111,8 +110,10 @@ pub fn resolve_setup(app: &mut App) {
/// reset system proxy /// reset system proxy
pub fn resolve_reset() { pub fn resolve_reset() {
log_err!(sysopt::Sysopt::global().reset_sysproxy()); log_err!(sysopt::Sysopt::global().reset_sysproxy());
log_err!(CoreManager::global().stop_core()); tauri::async_runtime::block_on(async move {
let _ = service::unset_dns_by_service(); log_err!(CoreManager::global().stop_core().await);
log_err!(service::unset_dns_by_service().await);
});
} }
/// create main window /// create main window

View File

@ -14,40 +14,38 @@ struct QueryParam {
} }
/// check whether there is already exists /// check whether there is already exists
pub fn check_singleton() -> Result<()> { pub async fn check_singleton() -> Result<()> {
let port = IVerge::get_singleton_port(); let port = IVerge::get_singleton_port();
if !local_port_available(port) { if !local_port_available(port) {
tauri::async_runtime::block_on(async { let resp = reqwest::get(format!("http://127.0.0.1:{port}/commands/ping"))
let resp = reqwest::get(format!("http://127.0.0.1:{port}/commands/ping")) .await?
.await? .text()
.text() .await?;
.await?;
if &resp == "ok" { if &resp == "ok" {
let argvs: Vec<String> = std::env::args().collect(); let argvs: Vec<String> = std::env::args().collect();
if argvs.len() > 1 { if argvs.len() > 1 {
let param = argvs[1].as_str(); let param = argvs[1].as_str();
if param.starts_with("clash:") { if param.starts_with("clash:") {
reqwest::get(format!( reqwest::get(format!(
"http://127.0.0.1:{port}/commands/scheme?param={param}" "http://127.0.0.1:{port}/commands/scheme?param={param}"
)) ))
.await? .await?
.text() .text()
.await?; .await?;
}
} else {
reqwest::get(format!("http://127.0.0.1:{port}/commands/visible"))
.await?
.text()
.await?;
} }
bail!("app exists"); } else {
reqwest::get(format!("http://127.0.0.1:{port}/commands/visible"))
.await?
.text()
.await?;
} }
bail!("app exists");
}
log::error!("failed to setup singleton listen server"); log::error!("failed to setup singleton listen server");
Ok(()) Ok(())
})
} else { } else {
Ok(()) Ok(())
} }