mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-06 23:00:15 +08:00
* chore(clippy): scope crate lint policy Keep panic-on-error lints at application target roots and scope signal dependencies to Linux. * docs(agents): define Rust backend architecture boundaries Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation. * refactor(draft): type async publication conflicts Return typed conflicts for async Draft edits. Release the lock and edit permit before converting the error, and exercise overlapping updates. * refactor(logging): use typed logger errors Expose crate-owned logger errors and preserve the underlying error sources. * refactor(subscription): extract response decoding Keep HTTP and persistence in the app. Decode response metadata and framing in the crate, and fall back when the server filename is invalid. * refactor(profile): extract profile models and index rules Move profile models and index rules into the crate, preserving serialization and returning a typed missing-profile error. * refactor(profile): separate subscription refresh and scheduling policy Separate download and scheduling policy from the subscription use case while retaining the existing write path. * refactor(subscription): decode deep links in the subscription crate * refactor(profile): extract selected node recovery rules * docs(agents): define dependencies between capability crates * refactor(task): move retry primitives into the task crate * refactor(backup): extract backup ZIP writing * refactor(subscription): keep profile writes outside proxy fallback * refactor(runtime-bundle): extract runtime bundle planning Plan provider destinations and assets in the crate. Adapt the plan to the Service wire format at the call site. * perf(runtime-bundle): share destination strings with tristr Share destination storage within bundle planning and preserve the Service wire strings and provider readback. * refactor(profile): extract script validation and execution Share the Boa validation and execution API while preserving the save-side timeout and diagnostics. * refactor(config): extract configuration renderer Render from inputs supplied by the app, reuse the script crate, and preserve the default template fast path. * refactor(proxy): extract proxy view and its use case Project the Mihomo snapshot into the existing IPC DTO and move use-case orchestration out of the command. * refactor(config): inject the profile script executor * refactor(config): centralize Mihomo YAML output * perf(runtime-bundle): read remote providers from borrowed configuration * chore(clippy): scope crate lint policy Keep panic-on-error lints at application target roots and scope signal dependencies to Linux. * docs(agents): define Rust backend architecture boundaries Document which layer owns Rust capabilities, fallible inputs, background work, and crate validation. * refactor(draft): type async publication conflicts Return typed conflicts for async Draft edits. Release the lock and edit permit before converting the error, and exercise overlapping updates. * refactor(logging): use typed logger errors Expose crate-owned logger errors and preserve the underlying error sources. * refactor(subscription): extract response decoding Keep HTTP and persistence in the app. Decode response metadata and framing in the crate, and fall back when the server filename is invalid. * refactor(profile): extract profile models and index rules Move profile models and index rules into the crate, preserving serialization and returning a typed missing-profile error. * refactor(profile): separate subscription refresh and scheduling policy Separate download and scheduling policy from the subscription use case while retaining the existing write path. * refactor(subscription): decode deep links in the subscription crate * refactor(profile): extract selected node recovery rules * docs(agents): define dependencies between capability crates * refactor(task): move retry primitives into the task crate * refactor(backup): extract backup ZIP writing * refactor(subscription): keep profile writes outside proxy fallback * fix(profile): preserve delays for future update timestamps * fix(subscription): preserve filenames from response headers and URL paths * fix(subscription): separate deep link parameters from nested URLs * refactor(profile): look up the refresh target once * refactor(subscription): pass the proxy directly to each download * refactor(profile): build companion options in one place * refactor(profile): remove companions from the deleted profile * style(profile): keep profile fields together * refactor(profile): name index operations after what they change * refactor(profile): call the core reload directly * refactor(backup): move archive validation to the restore change * refactor(config): name the runtime rendering step * refactor(config): remove the unused runtime patch API * refactor(config): accumulate profile keys and logs during rendering * refactor(config): load cached chain items directly * refactor(script): keep console state local to evaluation * refactor(proxy): read group order and scope in one pass * refactor(config): reuse sequence storage when applying profile edits * refactor(proxy): collect provider snapshots in display order * refactor(proxy): build the view from its input * refactor(runtime-bundle): share provider section order * fix(config): fill blank IPv6 fake IP ranges in TUN mode * fix(config): keep runtime field sorting stable * perf(config): reuse profile sequence storage during rendering * fix(script): check the evaluated profile entry point * fix(script): support runtime console methods during validation * perf(script): count integer digits without formatting JSON * perf(proxy): resolve unique members without building scope caches * fix(runtime-bundle): reject mixed owners of a provider path * perf(runtime-bundle): reuse the normalized destination buffer * fix(script): reject oversized names before escaping
277 lines
8.6 KiB
Rust
277 lines
8.6 KiB
Rust
mod chain;
|
|
|
|
use self::chain::load_chain_item;
|
|
use crate::config::dns::{DnsOverrideState, dns_override_source};
|
|
use crate::core::handle::Handle;
|
|
use crate::core::notify::NoticeStatus;
|
|
use crate::utils::dirs;
|
|
use crate::{
|
|
config::{Config, IProfiles, IVerge, PrfItem, profiles::current_mapping},
|
|
constants,
|
|
utils::tmpl,
|
|
};
|
|
use anyhow::{Context as _, Result};
|
|
use clash_verge_config_render::{
|
|
ChainItem, ChainType, RenderProfile, RenderSettings, RenderedConfig, ResultLog, SeqMap, render,
|
|
};
|
|
use parking_lot::Mutex;
|
|
use serde_yaml_ng::Mapping;
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::sync::Arc;
|
|
use tokio::fs;
|
|
use tristr::alias::String;
|
|
|
|
struct ConfigValues {
|
|
render: RenderSettings,
|
|
enable_dns_settings: bool,
|
|
dns_override_confirmation: Option<String>,
|
|
}
|
|
|
|
fn default_profile() -> RenderProfile {
|
|
RenderProfile {
|
|
config: Default::default(),
|
|
profile_name: Default::default(),
|
|
merge_item: Arc::new(ChainItem {
|
|
uid: "".into(),
|
|
data: ChainType::Merge(Mapping::new()),
|
|
}),
|
|
script_item: Arc::new(ChainItem {
|
|
uid: "".into(),
|
|
data: ChainType::Script(tmpl::ITEM_SCRIPT.into()),
|
|
}),
|
|
rules_item: Arc::new(ChainItem {
|
|
uid: "".into(),
|
|
data: ChainType::Rules(SeqMap::default()),
|
|
}),
|
|
proxies_item: Arc::new(ChainItem {
|
|
uid: "".into(),
|
|
data: ChainType::Proxies(SeqMap::default()),
|
|
}),
|
|
groups_item: Arc::new(ChainItem {
|
|
uid: "".into(),
|
|
data: ChainType::Groups(SeqMap::default()),
|
|
}),
|
|
global_merge: Arc::new(ChainItem {
|
|
uid: "Merge".into(),
|
|
data: ChainType::Merge(Mapping::new()),
|
|
}),
|
|
global_script: Arc::new(ChainItem {
|
|
uid: "Script".into(),
|
|
data: ChainType::Script(tmpl::ITEM_SCRIPT.into()),
|
|
}),
|
|
}
|
|
}
|
|
|
|
async fn chain_item_or_default(
|
|
item: Option<&PrfItem>,
|
|
default_item: impl FnOnce() -> Arc<ChainItem>,
|
|
) -> Arc<ChainItem> {
|
|
if let Some(item) = item {
|
|
load_chain_item(item).await.unwrap_or_else(default_item)
|
|
} else {
|
|
default_item()
|
|
}
|
|
}
|
|
|
|
async fn get_config_values(profile_uid: &str) -> ConfigValues {
|
|
let clash = Config::clash().await;
|
|
let clash_arc = clash.latest_arc();
|
|
let clash_config = clash_arc.0.clone();
|
|
drop(clash_arc);
|
|
drop(clash);
|
|
|
|
let verge = Config::verge().await;
|
|
|
|
let verge_arc = verge.latest_arc();
|
|
let IVerge {
|
|
ref enable_tun_mode,
|
|
ref enable_builtin_enhanced,
|
|
ref verge_socks_enabled,
|
|
ref verge_http_enabled,
|
|
ref enable_external_controller,
|
|
..
|
|
} = **verge_arc;
|
|
let enable_external_controller = enable_external_controller.unwrap_or(false);
|
|
let dns_settings = verge_arc.dns_settings_for(profile_uid);
|
|
let dns_override_confirmation = dns_settings.confirmation;
|
|
|
|
let (enable_tun, enable_builtin, socks_enabled, http_enabled, enable_dns_settings) = (
|
|
enable_tun_mode.unwrap_or(false),
|
|
enable_builtin_enhanced.unwrap_or(true),
|
|
verge_socks_enabled.unwrap_or(false),
|
|
verge_http_enabled.unwrap_or(false),
|
|
dns_settings.enabled,
|
|
);
|
|
|
|
#[cfg(not(target_os = "windows"))]
|
|
let redir_enabled = verge_arc.verge_redir_enabled.unwrap_or(false);
|
|
|
|
#[cfg(target_os = "linux")]
|
|
let tproxy_enabled = verge_arc.verge_tproxy_enabled.unwrap_or(false);
|
|
|
|
drop(verge_arc);
|
|
drop(verge);
|
|
|
|
ConfigValues {
|
|
render: RenderSettings {
|
|
clash_config,
|
|
enable_tun,
|
|
enable_builtin,
|
|
socks_enabled,
|
|
http_enabled,
|
|
enable_external_controller,
|
|
#[cfg(not(target_os = "windows"))]
|
|
redir_enabled,
|
|
#[cfg(target_os = "linux")]
|
|
tproxy_enabled,
|
|
},
|
|
enable_dns_settings,
|
|
dns_override_confirmation,
|
|
}
|
|
}
|
|
|
|
#[allow(clippy::cognitive_complexity)]
|
|
async fn collect_profile_items(profiles: &IProfiles) -> Result<RenderProfile> {
|
|
let current_profile_uid = match profiles.current.clone() {
|
|
Some(uid) => uid,
|
|
None => return Ok(default_profile()),
|
|
};
|
|
|
|
let current = current_mapping(profiles)
|
|
.await
|
|
.with_context(|| format!("failed to read current profile \"{current_profile_uid}\""))?;
|
|
|
|
let current_item = match profiles.get_item(¤t_profile_uid) {
|
|
Ok(item) => item,
|
|
Err(err) => {
|
|
return Err(err).with_context(|| format!("failed to get current profile \"{current_profile_uid}\""));
|
|
}
|
|
};
|
|
|
|
let merge_uid = current_item.current_merge().cloned().unwrap_or_else(|| "Merge".into());
|
|
let script_uid = current_item
|
|
.current_script()
|
|
.cloned()
|
|
.unwrap_or_else(|| "Script".into());
|
|
let rules_uid = current_item.current_rules().cloned().unwrap_or_else(|| "Rules".into());
|
|
let proxies_uid = current_item
|
|
.current_proxies()
|
|
.cloned()
|
|
.unwrap_or_else(|| "Proxies".into());
|
|
let groups_uid = current_item
|
|
.current_groups()
|
|
.cloned()
|
|
.unwrap_or_else(|| "Groups".into());
|
|
|
|
let name = current_item.name.clone().unwrap_or_default();
|
|
|
|
let RenderProfile {
|
|
merge_item: default_merge,
|
|
script_item: default_script,
|
|
rules_item: default_rules,
|
|
proxies_item: default_proxies,
|
|
groups_item: default_groups,
|
|
global_merge: default_global_merge,
|
|
global_script: default_global_script,
|
|
..
|
|
} = default_profile();
|
|
|
|
let (merge_item, script_item, rules_item, proxies_item, groups_item, global_merge, global_script) = tokio::join!(
|
|
chain_item_or_default(profiles.get_item(&merge_uid).ok(), || default_merge,),
|
|
chain_item_or_default(profiles.get_item(&script_uid).ok(), || default_script,),
|
|
chain_item_or_default(profiles.get_item(&rules_uid).ok(), || default_rules,),
|
|
chain_item_or_default(profiles.get_item(&proxies_uid).ok(), || default_proxies,),
|
|
chain_item_or_default(profiles.get_item(&groups_uid).ok(), || default_groups,),
|
|
chain_item_or_default(profiles.get_item("Merge").ok(), || default_global_merge,),
|
|
chain_item_or_default(profiles.get_item("Script").ok(), || default_global_script,),
|
|
);
|
|
|
|
Ok(RenderProfile {
|
|
config: current,
|
|
merge_item,
|
|
script_item,
|
|
rules_item,
|
|
proxies_item,
|
|
groups_item,
|
|
global_merge,
|
|
global_script,
|
|
profile_name: name,
|
|
})
|
|
}
|
|
|
|
struct DiscardedKeysNotice {
|
|
pending: Option<String>,
|
|
last: Vec<String>,
|
|
}
|
|
|
|
static DISCARDED_KEYS_NOTICE: Mutex<DiscardedKeysNotice> = Mutex::new(DiscardedKeysNotice {
|
|
pending: None,
|
|
last: Vec::new(),
|
|
});
|
|
|
|
pub(crate) fn take_discarded_keys_notice() -> Option<String> {
|
|
DISCARDED_KEYS_NOTICE.lock().pending.take()
|
|
}
|
|
|
|
/// One notice per distinct set, so regenerations with unchanged extensions stay quiet.
|
|
fn notify_discarded_keys(keys: Vec<String>) {
|
|
let mut notice = DISCARDED_KEYS_NOTICE.lock();
|
|
if notice.last == keys {
|
|
return;
|
|
}
|
|
let should_notify = !keys.is_empty();
|
|
if should_notify {
|
|
notice.pending = Some(keys.join(", ").into());
|
|
}
|
|
notice.last = keys;
|
|
drop(notice);
|
|
|
|
if should_notify {
|
|
Handle::notice(NoticeStatus::EnhanceDiscardedKeys, "");
|
|
}
|
|
}
|
|
|
|
async fn read_dns_settings(enabled: bool) -> Option<Mapping> {
|
|
if !enabled {
|
|
return None;
|
|
}
|
|
|
|
let dns_path = dirs::app_home_dir().ok()?.join(constants::files::DNS_CONFIG);
|
|
if !dns_path.exists() {
|
|
return None;
|
|
}
|
|
let yaml = fs::read_to_string(&dns_path).await.ok()?;
|
|
serde_yaml_ng::from_str(&yaml).ok()
|
|
}
|
|
|
|
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
|
|
pub async fn render_runtime_config(
|
|
profiles: &IProfiles,
|
|
) -> Result<(Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState)> {
|
|
let profile_uid = profiles.current.as_deref().unwrap_or_default();
|
|
let settings = get_config_values(profile_uid).await;
|
|
let profile = collect_profile_items(profiles).await?;
|
|
let dns_override = DnsOverrideState::new(
|
|
profile_uid,
|
|
dns_override_source(profile_uid, &profile.config)?,
|
|
settings.enable_dns_settings,
|
|
settings.dns_override_confirmation,
|
|
);
|
|
let dns_config = read_dns_settings(dns_override.enabled).await;
|
|
let RenderedConfig {
|
|
config,
|
|
exists_keys,
|
|
logs,
|
|
discarded_keys,
|
|
} = render(
|
|
profile,
|
|
settings.render,
|
|
dns_config,
|
|
clash_verge_profile_script::execute,
|
|
)
|
|
.await;
|
|
notify_discarded_keys(discarded_keys);
|
|
|
|
Ok((config, exists_keys, logs, dns_override))
|
|
}
|