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
+11 -43
View File
@@ -1,4 +1,3 @@
use crate::config::Config;
use crate::constants::{network, tun as tun_const};
use crate::utils::dirs::{path_to_str, sidecar_ipc_path};
use crate::utils::{dirs, help};
@@ -118,7 +117,7 @@ impl IClashTemp {
let mixed_port = Self::guard_mixed_port(&config);
let socks_port = Self::guard_socks_port(&config);
let port = Self::guard_port(&config);
let ctrl = Self::guard_external_controller(&config);
let ctrl = Self::guard_server_ctrl(&config);
#[cfg(unix)]
let external_controller_unix = Self::guard_external_controller_ipc();
#[cfg(windows)]
@@ -154,16 +153,6 @@ impl IClashTemp {
Self::guard_mixed_port(&self.0)
}
#[allow(unused)]
pub fn get_socks_port(&self) -> u16 {
Self::guard_socks_port(&self.0)
}
#[allow(unused)]
pub fn get_port(&self) -> u16 {
Self::guard_port(&self.0)
}
pub fn get_client_info(&self) -> ClashInfo {
let config = &self.0;
@@ -192,7 +181,7 @@ impl IClashTemp {
})
}
#[cfg(not(target_os = "windows"))]
pub fn guard_redir_port(config: &Mapping) -> u16 {
fn guard_redir_port(config: &Mapping) -> u16 {
let mut port = config
.get("redir-port")
.and_then(|value| match value {
@@ -208,7 +197,7 @@ impl IClashTemp {
}
#[cfg(target_os = "linux")]
pub fn guard_tproxy_port(config: &Mapping) -> u16 {
fn guard_tproxy_port(config: &Mapping) -> u16 {
let mut port = config
.get("tproxy-port")
.and_then(|value| match value {
@@ -223,7 +212,7 @@ impl IClashTemp {
port
}
pub fn guard_mixed_port(config: &Mapping) -> u16 {
fn guard_mixed_port(config: &Mapping) -> u16 {
let raw_value = config.get("mixed-port");
let mut port = raw_value
@@ -232,16 +221,16 @@ impl IClashTemp {
Value::Number(val_num) => val_num.as_u64().map(|u| u as u16),
_ => None,
})
.unwrap_or(7897);
.unwrap_or(network::ports::DEFAULT_MIXED);
if port == 0 {
port = 7897;
port = network::ports::DEFAULT_MIXED;
}
port
}
pub fn guard_socks_port(config: &Mapping) -> u16 {
fn guard_socks_port(config: &Mapping) -> u16 {
let mut port = config
.get("socks-port")
.and_then(|value| match value {
@@ -256,7 +245,7 @@ impl IClashTemp {
port
}
pub fn guard_port(config: &Mapping) -> u16 {
fn guard_port(config: &Mapping) -> u16 {
let mut port = config
.get("port")
.and_then(|value| match value {
@@ -271,7 +260,7 @@ impl IClashTemp {
port
}
pub fn guard_server_ctrl(config: &Mapping) -> String {
pub(super) fn guard_server_ctrl(config: &Mapping) -> String {
config
.get("external-controller")
.and_then(|value| match value.as_str() {
@@ -290,28 +279,7 @@ impl IClashTemp {
.unwrap_or_else(|| "127.0.0.1:9097".into())
}
pub fn guard_external_controller(config: &Mapping) -> String {
// 在初始化阶段,直接返回配置中的值,不进行额外检查
// 这样可以避免在配置加载期间的循环依赖
Self::guard_server_ctrl(config)
}
pub async fn guard_external_controller_with_setting(config: &Mapping) -> String {
// 检查 enable_external_controller 设置,用于运行时配置生成
let enable_external_controller = Config::verge()
.await
.latest_arc()
.enable_external_controller
.unwrap_or(false);
if enable_external_controller {
Self::guard_server_ctrl(config)
} else {
"".into()
}
}
pub fn guard_client_ctrl(config: &Mapping) -> String {
fn guard_client_ctrl(config: &Mapping) -> String {
let value = Self::guard_server_ctrl(config);
match SocketAddr::from_str(value.as_str()) {
Ok(mut socket) => {
@@ -324,7 +292,7 @@ impl IClashTemp {
}
}
pub fn guard_external_controller_ipc() -> String {
pub(crate) fn guard_external_controller_ipc() -> String {
// 总是使用当前的 IPC 路径,确保配置文件与运行时路径一致
sidecar_ipc_path()
.ok()
+8 -13
View File
@@ -27,7 +27,7 @@ use std::{
use tokio::sync::{Mutex, MutexGuard, OnceCell};
use tokio::time::sleep;
pub struct Config {
pub(crate) struct Config {
clash_config: Draft<IClashTemp>,
verge_config: Draft<IVerge>,
profiles_config: Draft<IProfiles>,
@@ -38,7 +38,7 @@ static TUN_SESSION_SUPPRESSED: AtomicBool = AtomicBool::new(false);
static CONFIG_WRITE_LOCK: Mutex<()> = Mutex::const_new(());
impl Config {
pub async fn global() -> &'static Self {
async fn global() -> &'static Self {
static CONFIG: OnceCell<Config> = OnceCell::const_new();
CONFIG
.get_or_init(|| async {
@@ -46,7 +46,7 @@ impl Config {
clash_config: Draft::new(IClashTemp::new().await),
verge_config: Draft::new(IVerge::new().await),
profiles_config: Draft::new(IProfiles::new().await),
runtime_config: Draft::new(IRuntime::new()),
runtime_config: Draft::new(IRuntime::default()),
}
})
.await
@@ -73,11 +73,6 @@ impl Config {
CONFIG_WRITE_LOCK.lock().await
}
pub async fn init_config() -> Result<()> {
Self::init_config_before_window().await?;
Self::init_runtime_config().await
}
pub async fn init_config_before_window() -> Result<()> {
Self::ensure_default_profile_items().await?;
@@ -151,7 +146,7 @@ impl Config {
}
async fn ensure_default_profile_items_for(profiles: &Draft<IProfiles>) -> Result<()> {
if profiles.latest_arc().get_items().is_none() {
if profiles.latest_arc().items.is_none() {
logging!(
warn,
Type::Config,
@@ -161,11 +156,11 @@ impl Config {
}
if profiles.latest_arc().get_item("Merge").is_err() {
let merge_item = &mut PrfItem::from_merge(Some("Merge".into()))?;
let merge_item = &mut PrfItem::from_merge(Some("Merge".into()));
profiles_append_item_to_safe(profiles, merge_item).await?;
}
if profiles.latest_arc().get_item("Script").is_err() {
let script_item = &mut PrfItem::from_script(Some("Script".into()))?;
let script_item = &mut PrfItem::from_script(Some("Script".into()));
profiles_append_item_to_safe(profiles, script_item).await?;
}
Ok(())
@@ -381,7 +376,7 @@ fn collect_names(config: &Mapping, list_key: &str, out: &mut HashSet<String>) {
}
#[derive(Debug)]
pub enum ConfigType {
pub(crate) enum ConfigType {
Run,
Check,
}
@@ -405,7 +400,7 @@ mod tests {
tokio::fs::remove_dir_all(&profiles_dir).await?;
assert!(profile_was_preserved);
assert!(profiles.data_arc().get_items().is_none());
assert!(profiles.data_arc().items.is_none());
Ok(())
}
}
-3
View File
@@ -8,9 +8,6 @@ use anyhow::Result;
use super::Config;
use crate::core::handle::Handle;
/// The port mihomo listens on when nothing else is configured.
pub const DEFAULT_MIXED_PORT: u16 = 7897;
/// A startup fallback for this session only; persistence would make the port climb across launches.
static SESSION_FALLBACK: AtomicU16 = AtomicU16::new(0);
+2 -1
View File
@@ -10,7 +10,8 @@ pub mod runtime;
pub(crate) mod snapshot;
mod verge;
pub use self::{clash::*, config::*, encrypt::*, mixed_port::*, prfitem::*, profiles::*, verge::*};
pub(crate) use self::config::{Config, ConfigType};
pub use self::{clash::*, encrypt::*, mixed_port::*, prfitem::*, profiles::*, verge::*};
pub const DEFAULT_PAC: &str = r#"function FindProxyForURL(url, host) {
return "PROXY 127.0.0.1:%mixed-port%; SOCKS5 127.0.0.1:%mixed-port%; DIRECT;";
+1 -9
View File
@@ -36,14 +36,6 @@ static STARTUP_CORE_BLOCK_REASON: Lazy<Mutex<Option<String>>> = Lazy::new(|| Mut
impl Config {
pub(crate) async fn resolve_startup_mixed_port() -> Result<bool> {
Self::resolve_startup_mixed_port_inner().await
}
pub(crate) async fn retry_startup_mixed_port_fallback() -> Result<bool> {
Self::resolve_startup_mixed_port_inner().await
}
async fn resolve_startup_mixed_port_inner() -> Result<bool> {
let _config_write = Self::lock_config_write().await;
let clash = Self::clash().await.latest_arc();
let verge = Self::verge().await.latest_arc();
@@ -287,7 +279,7 @@ fn configured_listener_ports(clash: &IClashTemp, verge: &IVerge) -> HashSet<u16>
}
}
if let Ok(controller) = SocketAddr::from_str(IClashTemp::guard_external_controller(&clash.0).as_str()) {
if let Ok(controller) = SocketAddr::from_str(IClashTemp::guard_server_ctrl(&clash.0).as_str()) {
ports.insert(controller.port());
}
+37 -52
View File
@@ -104,7 +104,7 @@ pub struct PrfOption {
}
impl PrfOption {
pub fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
pub(crate) fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
match (one, other) {
(Some(a_ref), Some(b_ref)) => {
let mut result = a_ref.clone();
@@ -132,11 +132,7 @@ impl PrfOption {
impl PrfItem {
/// Builds an item from a partial value that must include `itype`.
pub async fn from(item: &Self, file_data: Option<String>) -> Result<Self> {
if item.itype.is_none() {
bail!("type should not be null");
}
pub(super) async fn from(item: &Self, file_data: Option<String>) -> Result<Self> {
let itype = item
.itype
.as_ref()
@@ -162,7 +158,7 @@ impl PrfItem {
}
}
pub async fn from_local(
async fn from_local(
name: String,
desc: String,
file_data: Option<String>,
@@ -179,27 +175,27 @@ impl PrfItem {
let mut groups = opt_ref.and_then(|o| o.groups.clone());
if merge.is_none() {
let merge_item = &mut Self::from_merge(None)?;
let merge_item = &mut Self::from_merge(None);
profiles::profiles_append_item_safe(merge_item).await?;
merge = merge_item.uid.clone();
}
if script.is_none() {
let script_item = &mut Self::from_script(None)?;
let script_item = &mut Self::from_script(None);
profiles::profiles_append_item_safe(script_item).await?;
script = script_item.uid.clone();
}
if rules.is_none() {
let rules_item = &mut Self::from_rules()?;
let rules_item = &mut Self::from_rules();
profiles::profiles_append_item_safe(rules_item).await?;
rules = rules_item.uid.clone();
}
if proxies.is_none() {
let proxies_item = &mut Self::from_proxies()?;
let proxies_item = &mut Self::from_proxies();
profiles::profiles_append_item_safe(proxies_item).await?;
proxies = proxies_item.uid.clone();
}
if groups.is_none() {
let groups_item = &mut Self::from_groups()?;
let groups_item = &mut Self::from_groups();
profiles::profiles_append_item_safe(groups_item).await?;
groups = groups_item.uid.clone();
}
@@ -227,7 +223,7 @@ impl PrfItem {
})
}
pub async fn from_url(
pub(crate) async fn from_url(
url: &str,
name: Option<&String>,
desc: Option<&String>,
@@ -257,7 +253,7 @@ impl PrfItem {
let url = fix_dirty_url(url)?;
let resp = match NetworkManager::new()
.get_with_interrupt(
.get(
url.as_str(),
proxy_type,
Some(timeout),
@@ -349,7 +345,7 @@ impl PrfItem {
let name = name
.map(|s| s.to_owned())
.unwrap_or_else(|| filename.map(|s| s.into()).unwrap_or_else(|| "Remote File".into()));
let data = resp.text_with_charset()?;
let data = resp.text();
let data = data.trim_start_matches('\u{feff}');
@@ -360,27 +356,27 @@ impl PrfItem {
}
if merge.is_none() {
let merge_item = &mut Self::from_merge(None)?;
let merge_item = &mut Self::from_merge(None);
profiles::profiles_append_item_safe(merge_item).await?;
merge = merge_item.uid.clone();
}
if script.is_none() {
let script_item = &mut Self::from_script(None)?;
let script_item = &mut Self::from_script(None);
profiles::profiles_append_item_safe(script_item).await?;
script = script_item.uid.clone();
}
if rules.is_none() {
let rules_item = &mut Self::from_rules()?;
let rules_item = &mut Self::from_rules();
profiles::profiles_append_item_safe(rules_item).await?;
rules = rules_item.uid.clone();
}
if proxies.is_none() {
let proxies_item = &mut Self::from_proxies()?;
let proxies_item = &mut Self::from_proxies();
profiles::profiles_append_item_safe(proxies_item).await?;
proxies = proxies_item.uid.clone();
}
if groups.is_none() {
let groups_item = &mut Self::from_groups()?;
let groups_item = &mut Self::from_groups();
profiles::profiles_append_item_safe(groups_item).await?;
groups = groups_item.uid.clone();
}
@@ -410,7 +406,7 @@ impl PrfItem {
})
}
pub fn from_merge(uid: Option<String>) -> Result<Self> {
pub(super) fn from_merge(uid: Option<String>) -> Self {
let (id, template) = if let Some(uid) = uid {
(uid, tmpl::ITEM_MERGE.into())
} else {
@@ -418,76 +414,76 @@ impl PrfItem {
};
let file = format!("{id}.yaml").into();
Ok(Self {
Self {
uid: Some(id),
itype: Some("merge".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(template),
..Default::default()
})
}
}
pub fn from_script(uid: Option<String>) -> Result<Self> {
pub(super) fn from_script(uid: Option<String>) -> Self {
let id = if let Some(uid) = uid {
uid
} else {
help::get_uid("s").into()
};
let file = format!("{id}.js").into(); // js ext
Ok(Self {
Self {
uid: Some(id),
itype: Some("script".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(tmpl::ITEM_SCRIPT.into()),
..Default::default()
})
}
}
pub fn from_rules() -> Result<Self> {
fn from_rules() -> Self {
let uid = help::get_uid("r").into();
let file = format!("{uid}.yaml").into(); // yaml ext
Ok(Self {
Self {
uid: Some(uid),
itype: Some("rules".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(tmpl::ITEM_RULES.into()),
..Default::default()
})
}
}
pub fn from_proxies() -> Result<Self> {
fn from_proxies() -> Self {
let uid = help::get_uid("p").into();
let file = format!("{uid}.yaml").into(); // yaml ext
Ok(Self {
Self {
uid: Some(uid),
itype: Some("proxies".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(tmpl::ITEM_PROXIES.into()),
..Default::default()
})
}
}
pub fn from_groups() -> Result<Self> {
fn from_groups() -> Self {
let uid = help::get_uid("g").into();
let file = format!("{uid}.yaml").into(); // yaml ext
Ok(Self {
Self {
uid: Some(uid),
itype: Some("groups".into()),
file: Some(file),
updated: Some(chrono::Local::now().timestamp() as usize),
file_data: Some(tmpl::ITEM_GROUPS.into()),
..Default::default()
})
}
}
pub async fn read_file(&self) -> Result<String> {
pub(crate) async fn read_file(&self) -> Result<String> {
let file = self
.file
.as_ref()
@@ -498,37 +494,26 @@ impl PrfItem {
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
Ok(content.into())
}
pub async fn save_file(&self, data: String) -> Result<()> {
let file = self
.file
.as_ref()
.ok_or_else(|| anyhow::anyhow!("could not find the file"))?;
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(path, data.as_bytes())
.await
.context("failed to save the file")
}
}
impl PrfItem {
pub fn current_merge(&self) -> Option<&String> {
pub(crate) fn current_merge(&self) -> Option<&String> {
self.option.as_ref().and_then(|o| o.merge.as_ref())
}
pub fn current_script(&self) -> Option<&String> {
pub(crate) fn current_script(&self) -> Option<&String> {
self.option.as_ref().and_then(|o| o.script.as_ref())
}
pub fn current_rules(&self) -> Option<&String> {
pub(crate) fn current_rules(&self) -> Option<&String> {
self.option.as_ref().and_then(|o| o.rules.as_ref())
}
pub fn current_proxies(&self) -> Option<&String> {
pub(crate) fn current_proxies(&self) -> Option<&String> {
self.option.as_ref().and_then(|o| o.proxies.as_ref())
}
pub fn current_groups(&self) -> Option<&String> {
pub(crate) fn current_groups(&self) -> Option<&String> {
self.option.as_ref().and_then(|o| o.groups.as_ref())
}
}
+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"));
-5
View File
@@ -16,11 +16,6 @@ pub struct IRuntime {
}
impl IRuntime {
#[inline]
pub fn new() -> Self {
Self::default()
}
#[inline]
pub fn patch_config(&mut self, patch: &Mapping) {
let config = if let Some(config) = self.config.as_mut() {
+4 -5
View File
@@ -1,6 +1,7 @@
use crate::config::Config;
use crate::{
config::{DEFAULT_PAC, deserialize_encrypted, serialize_encrypted},
constants::network,
utils::{dirs, help},
};
use anyhow::Result;
@@ -265,7 +266,7 @@ impl IVerge {
help::save_yaml(&config_path, &config, Some("# Clash Verge Config")).await?;
logging!(info, Type::Config, "配置文件修正完成,需要重新加载配置");
Self::reload_config_after_fix(config).await?;
Self::reload_config_after_fix(config).await;
} else {
logging!(info, Type::Config, "clash_core配置验证通过: {:?}", config.clash_core);
}
@@ -273,7 +274,7 @@ impl IVerge {
Ok(())
}
async fn reload_config_after_fix(updated_config: Self) -> Result<()> {
async fn reload_config_after_fix(updated_config: Self) {
logging!(
info,
Type::Config,
@@ -286,8 +287,6 @@ impl IVerge {
*d = updated_config;
});
config_draft.apply();
Ok(())
}
pub fn get_valid_clash_core(&self) -> String {
@@ -357,7 +356,7 @@ impl IVerge {
verge_tproxy_port: Some(7896),
#[cfg(target_os = "linux")]
verge_tproxy_enabled: Some(false),
verge_mixed_port: Some(7897),
verge_mixed_port: Some(network::ports::DEFAULT_MIXED),
verge_socks_port: Some(7898),
verge_socks_enabled: Some(false),
verge_port: Some(7899),