refactor: streamline SWR configuration and improve error handling in AppDataProvider

This commit is contained in:
xmk23333
2025-10-21 17:51:12 +08:00
parent bafe2ae164
commit 0e933597f5
18 changed files with 1139 additions and 1383 deletions

View File

@@ -47,30 +47,32 @@ impl IClashTemp {
}
pub fn template() -> Self {
use crate::constants::{network, tun as tun_const};
let mut map = Mapping::new();
let mut tun = Mapping::new();
let mut tun_config = Mapping::new();
let mut cors_map = Mapping::new();
tun.insert("enable".into(), false.into());
#[cfg(target_os = "linux")]
tun.insert("stack".into(), "mixed".into());
#[cfg(not(target_os = "linux"))]
tun.insert("stack".into(), "gvisor".into());
tun.insert("auto-route".into(), true.into());
tun.insert("strict-route".into(), false.into());
tun.insert("auto-detect-interface".into(), true.into());
tun.insert("dns-hijack".into(), vec!["any:53"].into());
tun_config.insert("enable".into(), false.into());
tun_config.insert("stack".into(), tun_const::DEFAULT_STACK.into());
tun_config.insert("auto-route".into(), true.into());
tun_config.insert("strict-route".into(), false.into());
tun_config.insert("auto-detect-interface".into(), true.into());
tun_config.insert("dns-hijack".into(), tun_const::DNS_HIJACK.into());
#[cfg(not(target_os = "windows"))]
map.insert("redir-port".into(), 7895.into());
map.insert("redir-port".into(), network::ports::DEFAULT_REDIR.into());
#[cfg(target_os = "linux")]
map.insert("tproxy-port".into(), 7896.into());
map.insert("mixed-port".into(), 7897.into());
map.insert("socks-port".into(), 7898.into());
map.insert("port".into(), 7899.into());
map.insert("tproxy-port".into(), network::ports::DEFAULT_TPROXY.into());
map.insert("mixed-port".into(), network::ports::DEFAULT_MIXED.into());
map.insert("socks-port".into(), network::ports::DEFAULT_SOCKS.into());
map.insert("port".into(), network::ports::DEFAULT_HTTP.into());
map.insert("log-level".into(), "info".into());
map.insert("allow-lan".into(), false.into());
map.insert("ipv6".into(), true.into());
map.insert("mode".into(), "rule".into());
map.insert("external-controller".into(), "127.0.0.1:9097".into());
map.insert("external-controller".into(), network::DEFAULT_EXTERNAL_CONTROLLER.into());
#[cfg(unix)]
map.insert(
"external-controller-unix".into(),
@@ -81,9 +83,9 @@ impl IClashTemp {
"external-controller-pipe".into(),
Self::guard_external_controller_ipc().into(),
);
map.insert("tun".into(), tun_config.into());
cors_map.insert("allow-private-network".into(), true.into());
cors_map.insert(
"allow-origins".into(),
cors_map.insert("allow-origins".into(),
vec![
"tauri://localhost",
"http://tauri.localhost",
@@ -97,7 +99,6 @@ impl IClashTemp {
.into(),
);
map.insert("secret".into(), "set-your-secret".into());
map.insert("tun".into(), tun.into());
map.insert("external-controller-cors".into(), cors_map.into());
map.insert("unified-delay".into(), true.into());
Self(map)
@@ -325,8 +326,8 @@ impl IClashTemp {
.ok()
.and_then(|path| path_to_str(&path).ok().map(|s| s.into()))
.unwrap_or_else(|| {
log::error!(target: "app", "Failed to get IPC path, using default");
"127.0.0.1:9090".into()
log::error!(target: "app", "Failed to get IPC path");
crate::constants::network::DEFAULT_EXTERNAL_CONTROLLER.into()
})
}
}

View File

@@ -1,6 +1,7 @@
use super::{IClashTemp, IProfiles, IRuntime, IVerge};
use crate::{
config::{PrfItem, profiles_append_item_safe},
constants::{files, timing},
core::{CoreManager, handle, validate::CoreConfigValidator},
enhance, logging,
utils::{Draft, dirs, help, logging::Type},
@@ -8,13 +9,9 @@ use crate::{
use anyhow::{Result, anyhow};
use backoff::{Error as BackoffError, ExponentialBackoff};
use std::path::PathBuf;
use std::time::Duration;
use tokio::sync::OnceCell;
use tokio::time::sleep;
pub const RUNTIME_CONFIG: &str = "clash-verge.yaml";
pub const CHECK_CONFIG: &str = "clash-verge-check.yaml";
pub struct Config {
clash_config: Draft<Box<IClashTemp>>,
verge_config: Draft<Box<IVerge>>,
@@ -123,20 +120,18 @@ impl Config {
Some(("config_validate::error", String::new()))
};
// 在单独的任务中发送通知
if let Some((msg_type, msg_content)) = validation_result {
sleep(Duration::from_secs(2)).await;
sleep(timing::STARTUP_ERROR_DELAY).await;
handle::Handle::notice_message(msg_type, &msg_content);
}
Ok(())
}
/// 将订阅丢到对应的文件中
pub async fn generate_file(typ: ConfigType) -> Result<PathBuf> {
let path = match typ {
ConfigType::Run => dirs::app_home_dir()?.join(RUNTIME_CONFIG),
ConfigType::Check => dirs::app_home_dir()?.join(CHECK_CONFIG),
ConfigType::Run => dirs::app_home_dir()?.join(files::RUNTIME_CONFIG),
ConfigType::Check => dirs::app_home_dir()?.join(files::CHECK_CONFIG),
};
let runtime = Config::runtime().await;
@@ -152,7 +147,6 @@ impl Config {
Ok(path)
}
/// 生成订阅存好
pub async fn generate() -> Result<()> {
let (config, exists_keys, logs) = enhance::enhance().await;
@@ -166,8 +160,6 @@ impl Config {
}
pub async fn verify_config_initialization() {
logging!(info, Type::Setup, "Verifying config initialization...");
let backoff_strategy = ExponentialBackoff {
initial_interval: std::time::Duration::from_millis(100),
max_interval: std::time::Duration::from_secs(2),
@@ -178,48 +170,15 @@ impl Config {
let operation = || async {
if Config::runtime().await.latest_ref().config.is_some() {
logging!(
info,
Type::Setup,
"Config initialization verified successfully"
);
return Ok::<(), BackoffError<anyhow::Error>>(());
}
logging!(
warn,
Type::Setup,
"Runtime config not found, attempting to regenerate..."
);
match Config::generate().await {
Ok(_) => {
logging!(info, Type::Setup, "Config successfully regenerated");
Ok(())
}
Err(e) => {
logging!(warn, Type::Setup, "Failed to generate config: {}", e);
Err(BackoffError::transient(e))
}
}
Config::generate().await
.map_err(BackoffError::transient)
};
match backoff::future::retry(backoff_strategy, operation).await {
Ok(_) => {
logging!(
info,
Type::Setup,
"Config initialization verified with backoff retry"
);
}
Err(e) => {
logging!(
error,
Type::Setup,
"Failed to verify config initialization after retries: {}",
e
);
}
if let Err(e) = backoff::future::retry(backoff_strategy, operation).await {
logging!(error, Type::Setup, "Config init verification failed: {}", e);
}
}
}

View File

@@ -513,13 +513,8 @@ impl IVerge {
patch!(enable_external_controller);
}
/// 在初始化前尝试拿到单例端口的值
pub fn get_singleton_port() -> u16 {
#[cfg(not(feature = "verge-dev"))]
const SERVER_PORT: u16 = 33331;
#[cfg(feature = "verge-dev")]
const SERVER_PORT: u16 = 11233;
SERVER_PORT
crate::constants::network::ports::SINGLETON_SERVER
}
/// 获取日志等级