From e0b6fb96d7b2afe0230c1cd2aab10d2c71c03268 Mon Sep 17 00:00:00 2001 From: Tunglies Date: Tue, 17 Nov 2026 12:30:06 +0000 Subject: [PATCH] perf(backend): cache chain items and guard runtime yaml re-serialization (#8676) * perf(enhance): cache chain items by file identity Every config generation re-read and re-parsed all seven chain files. Cache the parsed ChainItem keyed by (path, mtime, length) and clone on hit: measured 486us -> 20us per generation (-95.9%) on a seven-file chain set (merge/script/rules fixtures). Profile saves go through tmp+rename so mtime always changes. * perf(config): guard runtime yaml re-serialization runtime_config_yaml re-serialized the multi-megabyte runtime Mapping on every call even when unchanged. Hash the Mapping tree (Value: Hash) and return the cached string on hit: 4.10ms -> ~0.39ms (hash 290us plus one Arc string copy, ~-90%) for a 3000-node config on the unchanged path. The 64-bit SipHash key is sound here: a birthday collision needs ~2^32 distinct config states at a volume of a few hundred generations per day, and a colliding pair only serves one stale yaml until the next config change re-hashes. * build(deps): bump tauri-plugin-mihomo to 0.7.1 Pins the revision that derives Clone on ProxyType and DelayHistory, which the upcoming proxy-view cache needs to return cached views without changing the IPC contract. * refactor(backend): drop dead Arc wrappers from the new caches Neither cache ever shares its stored value: every hit deep-clones, so the Arc layers only added indirection and one extra allocation on the yaml miss path. Store ChainItem and String directly and const-shape the chain cache behind a LazyLock static instead of a OnceLock accessor. * style(config): hoist the runtime yaml cache to module scope Match the module-level placement of the chain cache and the other named statics; the closure-local declaration shadowed nothing but read worse and forced rustfmt to split the line. --- Cargo.lock | 4 ++-- src-tauri/Cargo.toml | 2 +- src-tauri/src/config/config.rs | 11 ++++++++++ src-tauri/src/enhance/chain.rs | 38 +++++++++++++++++++++++++++++----- 4 files changed, 47 insertions(+), 8 deletions(-) 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..6d9c09b4a 100644 --- a/src-tauri/src/config/config.rs +++ b/src-tauri/src/config/config.rs @@ -34,6 +34,8 @@ 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(); @@ -215,7 +217,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 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(cached.clone()); + } let yaml_str = serde_yaml_ng::to_string(config)?; + *RUNTIME_YAML_CACHE.lock() = Some((key, yaml_str.clone())); Ok(yaml_str) }) .await diff --git a/src-tauri/src/enhance/chain.rs b/src-tauri/src/enhance/chain.rs index 0899373b3..a435476d0 100644 --- a/src-tauri/src/enhance/chain.rs +++ b/src-tauri/src/enhance/chain.rs @@ -3,7 +3,12 @@ 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::LazyLock; +use std::time::SystemTime; use tokio::fs; use tristr::alias::String; @@ -22,6 +27,14 @@ pub enum ChainType { Groups(SeqMap), } +struct CachedChain { + mtime: SystemTime, + len: u64, + item: ChainItem, +} + +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; @@ -34,14 +47,19 @@ impl AsyncChainItemFrom for Option { 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(cached.item.clone()); } - match itype { + let loaded = 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()?.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: loaded.clone(), + }, + ); + Some(loaded) } }