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 Arc<String> handle on hit: 4.10ms -> ~0.39ms (hash
290us, ~-90%) for a 3000-node config on the unchanged path, and the
handle keeps both hit and miss at a refcount clone instead of copying
the yaml body. 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): right-size the new caches' storage

The chain cache never shares its stored ChainItem -- every hit
deep-clones it -- so its Arc wrapper only added indirection; store it
directly and const-shape it behind a LazyLock static instead of a
OnceLock accessor. The yaml cache keeps Arc<String> because callers
receive the stored handle, making hit and miss clones O(1).

* 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.
This commit is contained in:
Tunglies
2026-11-18 09:23:12 +08:00
committed by Tunglies
parent fa3007d3a4
commit 80bab0ea5a
4 changed files with 50 additions and 10 deletions
Generated
+2 -2
View File
@@ -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",
+1 -1
View File
@@ -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",
+14 -2
View File
@@ -34,6 +34,9 @@ pub(crate) struct Config {
static CONFIG_WRITE_LOCK: Mutex<()> = Mutex::const_new(());
static RUNTIME_YAML_CACHE: parking_lot::Mutex<Option<(u64, std::sync::Arc<std::string::String>)>> =
parking_lot::Mutex::new(None);
impl Config {
async fn global() -> &'static Self {
static CONFIG: OnceCell<Config> = OnceCell::const_new();
@@ -205,7 +208,7 @@ impl Config {
Self::write_runtime_file(&yaml).await
}
pub(crate) async fn runtime_config_yaml() -> Result<std::string::String> {
pub(crate) async fn runtime_config_yaml() -> Result<std::sync::Arc<std::string::String>> {
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
+33 -5
View File
@@ -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<Mutex<HashMap<PathBuf, CachedChain>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
// Helper trait to allow async conversion
pub trait AsyncChainItemFrom {
async fn from_async(item: &PrfItem) -> Option<ChainItem>;
@@ -34,14 +47,19 @@ impl AsyncChainItemFrom for Option<ChainItem> {
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<ChainItem> {
Some(ChainItem { uid, data })
}
_ => None,
}
}?;
CHAIN_CACHE.lock().insert(
path,
CachedChain {
mtime,
len,
item: loaded.clone(),
},
);
Some(loaded)
}
}