refactor: api cleanup (#7812)

* refactor(config): unify YAML persistence

* refactor(config): remove redundant config APIs

* refactor(config): remove unused config APIs

* refactor(config): narrow profile APIs

* fix(config): preserve profiles on invalid reorder

* refactor(startup): narrow resolve helpers

* refactor(config): unify mixed port defaults

* refactor(network): simplify response APIs

* refactor(config): make profile builders infallible

* refactor(config): make profile activation infallible

* refactor(api): simplify internal runtime APIs

* refactor: consolidate internal config and window APIs
This commit is contained in:
Tunglies
2026-08-25 07:19:17 +00:00
committed by GitHub
parent 272c09568c
commit b7c4f7d39b
29 changed files with 277 additions and 413 deletions
+79 -90
View File
@@ -63,14 +63,6 @@ pub struct IProfilePreview<'a> {
pub is_current: bool,
}
/// 清理结果
#[derive(Debug, Clone)]
pub struct CleanupResult {
pub total_files: usize,
pub deleted_files: usize,
pub failed_deletions: usize,
}
pub(crate) struct ProfileDeletePlan {
files: Vec<String>,
}
@@ -135,7 +127,7 @@ impl IProfiles {
}
pub async fn save_file(&self) -> Result<()> {
help::save_yaml_atomic(&dirs::profiles_path()?, self, Some("# Profiles Config for Clash Verge")).await
help::save_yaml(&dirs::profiles_path()?, self, Some("# Profiles Config for Clash Verge")).await
}
/// 只修改current,valid和chain
@@ -154,14 +146,6 @@ impl IProfiles {
}
}
pub const fn get_current(&self) -> Option<&String> {
self.current.as_ref()
}
pub const fn get_items(&self) -> Option<&Vec<PrfItem>> {
self.items.as_ref()
}
pub fn get_item(&self, uid: impl AsRef<str>) -> Result<&PrfItem> {
let uid_str = uid.as_ref();
@@ -178,7 +162,7 @@ impl IProfiles {
bail!("failed to get the profile item \"uid:{}\"", uid_str);
}
pub async fn append_item(&mut self, item: &mut PrfItem) -> Result<()> {
async fn append_item(&mut self, item: &mut PrfItem) -> Result<()> {
let uid = &item.uid;
if uid.is_none() {
bail!("the uid should not be null");
@@ -215,31 +199,23 @@ impl IProfiles {
Ok(())
}
pub async fn reorder(&mut self, active_id: &String, over_id: &String) -> Result<()> {
let mut items = self.items.take().unwrap_or_default();
let mut old_index = None;
let mut new_index = None;
for (i, _) in items.iter().enumerate() {
if items[i].uid.as_ref() == Some(active_id) {
old_index = Some(i);
}
if items[i].uid.as_ref() == Some(over_id) {
new_index = Some(i);
}
async fn reorder(&mut self, active_id: &str, over_id: &str) -> Result<()> {
{
let Some(items) = self.items.as_mut() else {
return Ok(());
};
let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id));
let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id));
let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else {
return Ok(());
};
let item = items.remove(old_idx);
items.insert(new_idx, item);
}
let (old_idx, new_idx) = match (old_index, new_index) {
(Some(old), Some(new)) => (old, new),
_ => return Ok(()),
};
let item = items.remove(old_idx);
items.insert(new_idx, item);
self.items = Some(items);
self.save_file().await
}
pub async fn patch_item(&mut self, uid: &String, item: &PrfItem) -> Result<()> {
async fn patch_item(&mut self, uid: &str, item: &PrfItem) -> Result<()> {
if let Some(file) = &item.file {
Self::validate_profile_file(file)?;
}
@@ -247,7 +223,7 @@ impl IProfiles {
let mut items = self.items.take().unwrap_or_default();
for each in items.iter_mut() {
if each.uid.as_ref() == Some(uid) {
if each.uid.as_deref() == Some(uid) {
patch!(each, item, itype);
patch!(each, item, name);
patch!(each, item, desc);
@@ -284,7 +260,7 @@ impl IProfiles {
}
/// Updates fields returned by a remote profile refresh.
pub async fn update_item(&mut self, uid: &String, item: &mut PrfItem) -> Result<()> {
async fn update_item(&mut self, uid: &str, item: &mut PrfItem) -> Result<()> {
if self.items.is_none() {
self.items = Some(vec![]);
}
@@ -292,10 +268,8 @@ impl IProfiles {
let _ = self.get_item(uid)?;
if let Some(items) = self.items.as_mut() {
let some_uid = Some(uid.clone());
for each in items.iter_mut() {
if each.uid == some_uid {
if each.uid.as_deref() == Some(uid) {
each.extra = item.extra;
each.updated = item.updated;
each.home = item.home.to_owned();
@@ -343,8 +317,8 @@ impl IProfiles {
raised
}
pub(crate) fn plan_delete_item(&mut self, uid: &String) -> Result<(bool, ProfileDeletePlan)> {
let current = self.current.as_ref().unwrap_or(uid).clone();
pub(crate) fn plan_delete_item(&mut self, uid: &str) -> Result<(bool, ProfileDeletePlan)> {
let deleting_current = self.current.as_deref().is_none_or(|current| current == uid);
let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| {
[
op.merge.clone(),
@@ -359,7 +333,7 @@ impl IProfiles {
let mut items = self.items.take().unwrap_or_default();
let mut files = Vec::new();
if let Some(file) = Self::take_item_file_by_uid(&mut items, Some(uid.as_str())) {
if let Some(file) = Self::take_item_file_by_uid(&mut items, Some(uid)) {
files.push(file);
}
@@ -369,7 +343,7 @@ impl IProfiles {
}
}
if current == *uid {
if deleting_current {
self.current = None;
for item in items.iter() {
if item.itype == Some("remote".into()) || item.itype == Some("local".into()) {
@@ -380,7 +354,7 @@ impl IProfiles {
}
self.items = Some(items);
Ok((current == *uid, ProfileDeletePlan { files }))
Ok((deleting_current, ProfileDeletePlan { files }))
}
/// 获取current指向的订阅内容
@@ -400,17 +374,13 @@ impl IProfiles {
}
}
pub fn is_current_profile_index(&self, index: &String) -> bool {
self.current.as_ref() == Some(index)
}
pub fn profiles_preview(&self) -> Option<Vec<IProfilePreview<'_>>> {
self.items.as_ref().map(|items| {
items
.iter()
.filter_map(|e| {
if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) {
let is_current = self.is_current_profile_index(uid);
let is_current = self.current.as_ref() == Some(uid);
let preview = IProfilePreview { uid, name, is_current };
Some(preview)
} else {
@@ -421,17 +391,6 @@ impl IProfiles {
})
}
pub fn get_name_by_uid(&self, uid: &String) -> Option<&String> {
if let Some(items) = &self.items {
for item in items {
if item.uid.as_ref() == Some(uid) {
return item.name.as_ref();
}
}
}
None
}
/// 以 app 中的 profile 列表为准,删除不再需要的文件
pub async fn cleanup_orphaned_files(&self) -> Result<()> {
let profiles_dir = dirs::app_profiles_dir()?;
@@ -495,19 +454,13 @@ impl IProfiles {
}
}
let result = CleanupResult {
total_files,
deleted_files,
failed_deletions,
};
logging!(
info,
Type::Config,
"Profile 文件清理完成: 总文件数={}, 删除文件数={}, 失败数={}",
result.total_files,
result.deleted_files,
result.failed_deletions
total_files,
deleted_files,
failed_deletions
);
Ok(())
@@ -581,15 +534,15 @@ impl IProfiles {
}
}
// These helpers avoid holding a parking_lot guard across `await`.
// These helpers serialize asynchronous operations against committed profile data.
use crate::config::Config;
pub async fn profiles_append_item_with_filedata_safe(item: &PrfItem, file_data: Option<String>) -> Result<()> {
pub(crate) async fn profiles_append_item_with_filedata_safe(item: &PrfItem, file_data: Option<String>) -> Result<()> {
let item = &mut PrfItem::from(item, file_data).await?;
profiles_append_item_safe(item).await
}
pub async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()> {
pub(crate) async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()> {
let profiles = Config::profiles().await;
profiles_append_item_to_safe(&profiles, item).await
}
@@ -603,7 +556,7 @@ pub(super) async fn profiles_append_item_to_safe(profiles: &Draft<IProfiles>, it
.await
}
pub async fn profiles_patch_item_safe(index: &String, item: &PrfItem) -> Result<()> {
pub(crate) async fn profiles_patch_item_safe(index: &str, item: &PrfItem) -> Result<()> {
Config::profiles()
.await
.with_data_modify(|mut profiles| async move {
@@ -613,7 +566,7 @@ pub async fn profiles_patch_item_safe(index: &String, item: &PrfItem) -> Result<
.await
}
pub async fn profiles_reorder_safe(active_id: &String, over_id: &String) -> Result<()> {
pub(crate) async fn profiles_reorder_safe(active_id: &str, over_id: &str) -> Result<()> {
Config::profiles()
.await
.with_data_modify(|mut profiles| async move {
@@ -623,7 +576,7 @@ pub async fn profiles_reorder_safe(active_id: &String, over_id: &String) -> Resu
.await
}
pub async fn profiles_save_file_safe() -> Result<()> {
pub(crate) async fn profiles_save_file_safe() -> Result<()> {
Config::profiles()
.await
.with_data_modify(|profiles| async move {
@@ -633,7 +586,7 @@ pub async fn profiles_save_file_safe() -> Result<()> {
.await
}
pub async fn profiles_draft_update_item_safe(index: &String, item: &mut PrfItem) -> Result<()> {
pub(crate) async fn profiles_update_item_safe(index: &str, item: &mut PrfItem) -> Result<()> {
Config::profiles()
.await
.with_data_modify(|mut profiles| async move {
@@ -765,7 +718,7 @@ fn reconcile_selected_nodes(
}
/// Cancels restoration so it cannot overwrite a newer selection or profile snapshot.
pub fn supersede_selected_activation() {
pub(crate) fn supersede_selected_activation() {
ACTIVATE_SELECTED_GENERATION.fetch_add(1, Ordering::AcqRel);
}
@@ -866,7 +819,7 @@ async fn update_tray_after_activation(generation: u64) {
}
/// Records a backend-made selection so the next core start restores it.
pub async fn record_selected_node(group_name: &str, node: &str) -> Result<()> {
pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result<()> {
let group_name = String::from(group_name);
let node = String::from(node);
let recorded = Config::profiles()
@@ -918,7 +871,7 @@ fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bo
selected.len() != original_len
}
pub async fn forget_selected_node(group_name: &str) -> Result<()> {
pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
let cleared = Config::profiles()
.await
.with_data_modify(move |mut profiles| async move {
@@ -1150,22 +1103,21 @@ async fn activate_selected_nodes_worker(
/// Whether an activation may also prune the records it cannot match.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SelectionRepair {
enum SelectionRepair {
/// Prune records after a fully loaded profile switch.
Prune,
/// Preserve records during startup while provider-backed groups may still be absent.
KeepRecords,
}
pub fn activate_selected_nodes() -> Result<()> {
pub(crate) fn activate_selected_nodes() {
// The first-pass signal is for callers that wait; a profile switch does not, and dropping
// the receiver simply makes the send a no-op.
drop(activate_selected_nodes_with(SelectionRepair::Prune));
Ok(())
}
/// Restores available selections before the system proxy points at the core, then retries the rest.
pub async fn restore_selected_nodes() {
pub(crate) async fn restore_selected_nodes() {
let first_pass = activate_selected_nodes_with(SelectionRepair::KeepRecords);
if tokio::time::timeout(SELECTED_NODES_FIRST_PASS_BUDGET, first_pass)
.await
@@ -1199,7 +1151,7 @@ fn activate_selected_nodes_with(repair: SelectionRepair) -> tokio::sync::oneshot
let result = async {
// A draft may be a profile switch that has not passed validation yet.
let profiles = Config::profiles().await.data_arc();
let current = profiles.get_current().context("no current profile running")?.clone();
let current = profiles.current.clone().context("no current profile running")?;
let selected = profiles
.get_item(&current)
.context("failed to get current profile")?
@@ -1262,6 +1214,43 @@ mod tests {
}
}
#[tokio::test]
async fn missing_reorder_ids_preserve_ordered_items() -> Result<()> {
let mut profiles = IProfiles {
current: Some("a".into()),
items: Some(vec![
PrfItem {
uid: Some("a".into()),
..PrfItem::default()
},
PrfItem {
uid: Some("b".into()),
..PrfItem::default()
},
PrfItem {
uid: Some("c".into()),
..PrfItem::default()
},
]),
};
let expected = Some(vec![Some("a"), Some("b"), Some("c")]);
profiles.reorder("missing", "b").await?;
let ordered_uids = profiles
.items
.as_ref()
.map(|items| items.iter().map(|item| item.uid.as_deref()).collect::<Vec<_>>());
assert_eq!(ordered_uids, expected);
profiles.reorder("a", "missing").await?;
let ordered_uids = profiles
.items
.as_ref()
.map(|items| items.iter().map(|item| item.uid.as_deref()).collect::<Vec<_>>());
assert_eq!(ordered_uids, expected);
Ok(())
}
#[test]
fn raising_intervals_only_touches_those_scheduled_too_often() {
let mut profiles = IProfiles {
@@ -1313,7 +1302,7 @@ mod tests {
]),
};
let (should_update, plan) = profiles.plan_delete_item(&"a".into())?;
let (should_update, plan) = profiles.plan_delete_item("a")?;
assert!(should_update);
assert_eq!(profiles.current.as_deref(), Some("b"));