perf(config): write yaml headers in place and record selections without copying

- save_yaml_str takes an optional header prefix written as separate chunks,
  so the MB-scale serialized payload is never duplicated by format! just
  to prepend a comment (profiles/verge/clash/runtime yaml all benefit;
  file bytes unchanged)
- the runtime yaml string no longer round-trips through a prefixed copy;
  write_runtime_file adds the header when persisting
- record/forget selected nodes mutate the stored selection list in place
  instead of cloning it per click
This commit is contained in:
Tunglies
2026-11-16 23:24:35 +08:00
parent 4c82a6cddb
commit eacf138cc2
5 changed files with 25 additions and 21 deletions
+2 -2
View File
@@ -216,7 +216,7 @@ impl Config {
.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)?;
Ok(format!("# Generated by Clash Verge\n\n{}", yaml_str))
Ok(yaml_str)
})
.await
.map_err(|join| anyhow!("runtime serialization task failed: {join}"))?
@@ -224,7 +224,7 @@ impl Config {
pub(crate) async fn write_runtime_file(yaml: &str) -> Result<PathBuf> {
let path = dirs::app_home_dir()?.join(files::RUNTIME_CONFIG);
help::save_yaml_str(&path, yaml).await?;
help::save_yaml_str(&path, yaml, Some("# Generated by Clash Verge")).await?;
Ok(path)
}
+9 -5
View File
@@ -761,7 +761,7 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
return Ok((profiles, false));
};
let mut selected = item.selected.clone().unwrap_or_default();
let selected = item.selected.get_or_insert_with(Vec::new);
match selected
.iter_mut()
.find(|entry| entry.name.as_ref() == Some(&group_name))
@@ -770,14 +770,13 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result
if entry.now.as_ref() == Some(&node) {
return Ok((profiles, false));
}
entry.now = Some(node);
entry.now = Some(node.clone());
}
None => selected.push(PrfSelected {
name: Some(group_name),
now: Some(node),
}),
}
item.selected = Some(selected);
profiles.save_file().await?;
Ok((profiles, true))
})
@@ -796,12 +795,17 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
return Ok((profiles, false));
};
let mut selected = item.selected.clone().unwrap_or_default();
let Some(mut selected) = item.selected.take() else {
return Ok((profiles, false));
};
if !remove_selected_node(&mut selected, group_name) {
item.selected = Some(selected);
return Ok((profiles, false));
}
item.selected = (!selected.is_empty()).then_some(selected);
if !selected.is_empty() {
item.selected = Some(selected);
}
profiles.save_file().await?;
Ok((profiles, true))
})
+1 -1
View File
@@ -435,7 +435,7 @@ impl CoreConfigValidator {
}
let check_path = dirs::app_home_dir()?.join(crate::constants::files::CHECK_CONFIG);
help::save_yaml_str(&check_path, yaml).await?;
help::save_yaml_str(&check_path, yaml, None).await?;
let outcome = Self::validate_config_internal_outcome(dirs::path_to_str(&check_path)?).await?;
if outcome.is_valid() {
*LAST_VALIDATED.lock() = Some(fingerprint);
+1 -3
View File
@@ -578,7 +578,6 @@ fn ensure_tun_default_mtu(mut config: Mapping) -> Mapping {
config
}
}
/// Merges the app's clash config over the profile; switches are parameters to keep it pure.
fn merge_default_config(
@@ -601,7 +600,6 @@ fn merge_default_config(
}
config.insert(Value::from("tun"), Value::Mapping(tun));
}
}
} else {
if key.as_str() == Some("socks-port") && !socks_enabled {
config.remove("socks-port");
@@ -656,7 +654,7 @@ fn merge_default_config(
fn apply_builtin_scripts(mut config: Mapping, enable_builtin: bool) -> Mapping {
if enable_builtin {
// The JS path saw a lowercased view; lowercase once, only when the builtin runs.
config = use_lowercase(&config);
config = use_lowercase(config);
logging!(debug, Type::Core, "run builtin script verge_hy_alpn");
config = builtin_hy_alpn(config);
}
+12 -10
View File
@@ -137,16 +137,11 @@ fn is_short_id(key: &Value) -> bool {
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
let yaml_str = match prefix {
Some(prefix) => format!("{prefix}\n\n{data_str}"),
None => data_str,
};
save_yaml_str(path, &yaml_str).await
save_yaml_str(path, &data_str, prefix).await
}
/// Atomic replace with pre-serialized content; the payload must not need the encryption scope.
pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
pub async fn save_yaml_str(path: &Path, yaml_str: &str, prefix: Option<&str>) -> Result<()> {
let (temporary, file) = loop {
let temporary = path.with_extension(format!("tmp-{}-{}", std::process::id(), nanoid!()));
match std::fs::OpenOptions::new()
@@ -172,9 +167,16 @@ pub async fn save_yaml_str(path: &Path, yaml_str: &str) -> Result<()> {
let _ = std::fs::remove_file(path);
});
let mut file = tokio::fs::File::from_std(file);
file.write_all(yaml_str.as_bytes())
.await
.with_context(|| format!("failed to write temporary file for \"{}\"", path.display()))?;
async fn write_chunk(file: &mut tokio::fs::File, bytes: &[u8], path: &Path) -> Result<()> {
file.write_all(bytes)
.await
.with_context(|| format!("failed to write temporary file for \"{}\"", path.display()))
}
if let Some(prefix) = prefix {
write_chunk(&mut file, prefix.as_bytes(), path).await?;
write_chunk(&mut file, b"\n\n", path).await?;
}
write_chunk(&mut file, yaml_str.as_bytes(), path).await?;
file.flush()
.await
.with_context(|| format!("failed to flush temporary file for \"{}\"", path.display()))?;