diff --git a/Cargo.lock b/Cargo.lock index c70e4abff..e33b69da4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7545,8 +7545,8 @@ dependencies = [ [[package]] name = "tauri-plugin-mihomo" -version = "0.7.0" -source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=e49bbedcc67d60da2c10e81bc6433b0f8e8fa232#e49bbedcc67d60da2c10e81bc6433b0f8e8fa232" +version = "0.7.1" +source = "git+https://github.com/clash-verge-rev/tauri-plugin-mihomo?rev=7e4fa8642cf6c394ed88b5a969420d8eab60087f#7e4fa8642cf6c394ed88b5a969420d8eab60087f" dependencies = [ "arc-swap", "clashmap", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index ef93aec61..59bcdcddd 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -91,7 +91,7 @@ backon = { version = "1.6.0", features = ["tokio-sleep"] } tauri-plugin-http = "2.9.0" tracing = { workspace = true } tauri-plugin-devtools = { version = "2.2.3", optional = true } -tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "e49bbedcc67d60da2c10e81bc6433b0f8e8fa232" } +tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" } async-trait = "0.1.92" clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.8.1", version = "2.8.1", features = [ "client", diff --git a/src-tauri/src/config/config.rs b/src-tauri/src/config/config.rs index 8a7c25a85..93c2b8a67 100644 --- a/src-tauri/src/config/config.rs +++ b/src-tauri/src/config/config.rs @@ -34,6 +34,9 @@ pub(crate) struct Config { static CONFIG_WRITE_LOCK: Mutex<()> = Mutex::const_new(()); +static RUNTIME_YAML_CACHE: parking_lot::Mutex)>> = + parking_lot::Mutex::new(None); + impl Config { async fn global() -> &'static Self { static CONFIG: OnceCell = OnceCell::const_new(); @@ -205,7 +208,7 @@ impl Config { Self::write_runtime_file(&yaml).await } - pub(crate) async fn runtime_config_yaml() -> Result { + pub(crate) async fn runtime_config_yaml() -> Result> { let runtime = Self::runtime().await; AsyncHandler::spawn_blocking(move || { let runtime_lastest = runtime.latest_arc(); @@ -215,7 +218,16 @@ impl Config { .as_ref() .or_else(|| runtime_data.config.as_ref()) .ok_or_else(|| anyhow!("failed to generate runtime config, might need to restart application"))?; - let yaml_str = serde_yaml_ng::to_string(config)?; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + std::hash::Hash::hash(config, &mut hasher); + let key = std::hash::Hasher::finish(&hasher); + if let Some((cached_key, cached)) = RUNTIME_YAML_CACHE.lock().as_ref() + && *cached_key == key + { + return Ok(std::sync::Arc::clone(cached)); + } + let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?); + *RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str))); Ok(yaml_str) }) .await diff --git a/src-tauri/src/enhance/chain.rs b/src-tauri/src/enhance/chain.rs index 0899373b3..d4f3781b4 100644 --- a/src-tauri/src/enhance/chain.rs +++ b/src-tauri/src/enhance/chain.rs @@ -3,17 +3,22 @@ use crate::{ config::PrfItem, utils::{dirs, help}, }; +use parking_lot::Mutex; use serde_yaml_ng::Mapping; +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Arc, LazyLock}; +use std::time::SystemTime; use tokio::fs; use tristr::alias::String; -#[derive(Debug, Clone)] +#[derive(Debug)] pub struct ChainItem { pub uid: String, pub data: ChainType, } -#[derive(Debug, Clone)] +#[derive(Debug)] pub enum ChainType { Merge(Mapping), Script(String), @@ -22,26 +27,39 @@ pub enum ChainType { Groups(SeqMap), } -// Helper trait to allow async conversion -pub trait AsyncChainItemFrom { - async fn from_async(item: &PrfItem) -> Option; +struct CachedChain { + mtime: SystemTime, + len: u64, + item: Arc, } -impl AsyncChainItemFrom for Option { +static CHAIN_CACHE: LazyLock>> = LazyLock::new(|| Mutex::new(HashMap::new())); + +// Helper trait to allow async conversion +pub trait AsyncChainItemFrom { + async fn from_async(item: &PrfItem) -> Option>; +} + +impl AsyncChainItemFrom for Option> { async fn from_async(item: &PrfItem) -> Self { let itype = item.itype.as_ref()?.as_str(); let file = item.file.clone()?; let uid = item.uid.clone().unwrap_or_else(|| "".into()); let path = dirs::app_profiles_dir().ok()?.join(file.as_str()); - if !path.exists() { - return None; + let meta = fs::metadata(&path).await.ok()?; + let (mtime, len) = (meta.modified().ok()?, meta.len()); + if let Some(cached) = CHAIN_CACHE.lock().get(&path) + && cached.mtime == mtime + && cached.len == len + { + return Some(Arc::clone(&cached.item)); } - match itype { + let loaded = Arc::new(match itype { "script" => Some(ChainItem { uid, - data: ChainType::Script(fs::read_to_string(path).await.ok()?.into()), + data: ChainType::Script(fs::read_to_string(&path).await.ok()?.as_str().into()), }), "merge" => Some(ChainItem { uid, @@ -57,6 +75,16 @@ impl AsyncChainItemFrom for Option { Some(ChainItem { uid, data }) } _ => None, - } + }?); + + CHAIN_CACHE.lock().insert( + path, + CachedChain { + mtime, + len, + item: Arc::clone(&loaded), + }, + ); + Some(loaded) } } diff --git a/src-tauri/src/enhance/mod.rs b/src-tauri/src/enhance/mod.rs index d5e82bf56..8fa3c3944 100644 --- a/src-tauri/src/enhance/mod.rs +++ b/src-tauri/src/enhance/mod.rs @@ -28,6 +28,7 @@ use parking_lot::Mutex; use serde_yaml_ng::{Mapping, Value}; use std::collections::{HashMap, HashSet}; use std::hash::{Hash as _, Hasher as _}; +use std::sync::Arc; use tokio::fs; use tristr::alias::String; @@ -51,13 +52,13 @@ struct ConfigValues { #[derive(Debug)] struct ProfileItems { config: Mapping, - merge_item: ChainItem, - script_item: ChainItem, - rules_item: ChainItem, - proxies_item: ChainItem, - groups_item: ChainItem, - global_merge: ChainItem, - global_script: ChainItem, + merge_item: Arc, + script_item: Arc, + rules_item: Arc, + proxies_item: Arc, + groups_item: Arc, + global_merge: Arc, + global_script: Arc, profile_name: String, } @@ -66,41 +67,46 @@ impl Default for ProfileItems { Self { config: Default::default(), profile_name: Default::default(), - merge_item: ChainItem { + merge_item: Arc::new(ChainItem { uid: "".into(), data: ChainType::Merge(Mapping::new()), - }, - script_item: ChainItem { + }), + script_item: Arc::new(ChainItem { uid: "".into(), data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), - }, - rules_item: ChainItem { + }), + rules_item: Arc::new(ChainItem { uid: "".into(), data: ChainType::Rules(SeqMap::default()), - }, - proxies_item: ChainItem { + }), + proxies_item: Arc::new(ChainItem { uid: "".into(), data: ChainType::Proxies(SeqMap::default()), - }, - groups_item: ChainItem { + }), + groups_item: Arc::new(ChainItem { uid: "".into(), data: ChainType::Groups(SeqMap::default()), - }, - global_merge: ChainItem { + }), + global_merge: Arc::new(ChainItem { uid: "Merge".into(), data: ChainType::Merge(Mapping::new()), - }, - global_script: ChainItem { + }), + global_script: Arc::new(ChainItem { uid: "Script".into(), data: ChainType::Script(tmpl::ITEM_SCRIPT.into()), - }, + }), } } } -async fn chain_item_or_default(item: Option<&PrfItem>, default_item: impl FnOnce() -> ChainItem) -> ChainItem { +async fn chain_item_or_default( + item: Option<&PrfItem>, + default_item: impl FnOnce() -> Arc, +) -> Arc { if let Some(item) = item { - >::from_async(item).await.unwrap_or_else(default_item) + >>::from_async(item) + .await + .unwrap_or_else(default_item) } else { default_item() } @@ -235,28 +241,28 @@ async fn process_override_items( mut config: Mapping, mut exists_keys: Vec, mut result_map: HashMap, - merge_item: ChainItem, - script_item: ChainItem, + merge_item: Arc, + script_item: Arc, profile_name: &str, authoritative: &AuthoritativeFields, ) -> (Mapping, Vec, HashMap) { - if let ChainType::Merge(merge) = merge_item.data { - exists_keys.extend(use_keys(&merge)); + if let ChainType::Merge(merge) = &merge_item.data { + exists_keys.extend(use_keys(merge)); let before = authoritative.current(&config); - config = use_merge(merge, config); + config = use_merge(merge.clone(), config); let notes: ResultLog = authoritative .overridden(&before, &authoritative.current(&config)) .into_iter() .map(discarded_note) .collect(); if !notes.is_empty() { - result_map.entry(merge_item.uid).or_default().extend(notes); + result_map.entry(merge_item.uid.clone()).or_default().extend(notes); } } - if let ChainType::Script(script) = script_item.data { + if let ChainType::Script(script) = &script_item.data { let before = authoritative.current(&config); - let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.into()).await; + let (res_config, changed_keys, mut logs) = use_script(script.clone(), config, profile_name.into()).await; exists_keys.extend(changed_keys); config = res_config; logs.extend( @@ -265,7 +271,7 @@ async fn process_override_items( .into_iter() .map(discarded_note), ); - result_map.insert(script_item.uid, logs); + result_map.insert(script_item.uid.clone(), logs); } (config, exists_keys, result_map) @@ -273,20 +279,20 @@ async fn process_override_items( fn process_seq_items( mut config: Mapping, - rules_item: ChainItem, - proxies_item: ChainItem, - groups_item: ChainItem, + rules_item: Arc, + proxies_item: Arc, + groups_item: Arc, ) -> Mapping { - if let ChainType::Rules(rules) = rules_item.data { - config = use_seq(rules, config, "rules"); + if let ChainType::Rules(rules) = &rules_item.data { + config = use_seq(rules.clone(), config, "rules"); } - if let ChainType::Proxies(proxies) = proxies_item.data { - config = use_seq(proxies, config, "proxies"); + if let ChainType::Proxies(proxies) = &proxies_item.data { + config = use_seq(proxies.clone(), config, "proxies"); } - if let ChainType::Groups(groups) = groups_item.data { - config = use_seq(groups, config, "proxy-groups"); + if let ChainType::Groups(groups) = &groups_item.data { + config = use_seq(groups.clone(), config, "proxy-groups"); } config @@ -1397,6 +1403,7 @@ mod tests { process_override_items, use_keys, }; use std::collections::HashMap; + use std::sync::Arc; fn mapping(yaml: &str) -> serde_yaml_ng::Mapping { serde_yaml_ng::from_str(yaml).expect("test config should be valid") @@ -1437,9 +1444,11 @@ mod tests { (profile.clone(), Mapping::new()) }; let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings); - let merge_item = |uid: &str| ChainItem { - uid: uid.into(), - data: ChainType::Merge(merge.clone()), + let merge_item = |uid: &str| { + Arc::new(ChainItem { + uid: uid.into(), + data: ChainType::Merge(merge.clone()), + }) }; let profile_name = "test-profile"; let (config, keys, logs) = process_override_items( @@ -1447,10 +1456,10 @@ mod tests { vec![], HashMap::new(), merge_item("global-merge"), - ChainItem { + Arc::new(ChainItem { uid: "global-script".into(), data: ChainType::Script(script.into()), - }, + }), profile_name, &authoritative, ) @@ -1460,10 +1469,10 @@ mod tests { keys, logs, merge_item("profile-merge"), - ChainItem { + Arc::new(ChainItem { uid: "profile-script".into(), data: ChainType::Script(script.into()), - }, + }), profile_name, &authoritative, ) @@ -1500,15 +1509,15 @@ mod tests { let exists_keys = use_keys(&config).collect(); config.insert("application-only".into(), true.into()); - let global_merge = ChainItem { + let global_merge = Arc::new(ChainItem { uid: "Merge".into(), data: ChainType::Merge(mapping( r"{global-merge-wins: global-merge, global-script-wins: global-merge, profile-merge-wins: global-merge, profile-script-wins: global-merge, nested: {winner: global-merge}, dns: {enable: false}, tun: {enable: false}}", )), - }; - let global_script = ChainItem { + }); + let global_script = Arc::new(ChainItem { uid: "Script".into(), data: ChainType::Script( r#"function main(config) { @@ -1520,15 +1529,15 @@ mod tests { }"# .into(), ), - }; - let profile_merge = ChainItem { + }); + let profile_merge = Arc::new(ChainItem { uid: "profile-merge".into(), data: ChainType::Merge(mapping( r"{profile-merge-wins: profile-merge, profile-script-wins: profile-merge, nested: {winner: profile-merge}}", )), - }; - let profile_script = ChainItem { + }); + let profile_script = Arc::new(ChainItem { uid: "profile-script".into(), data: ChainType::Script( r#"function main(config) { @@ -1538,7 +1547,7 @@ mod tests { }"# .into(), ), - }; + }); let profile_name = "test-profile"; let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());