mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-04 21:30:06 +08:00
chore(storage): sync the runtime branch with dev
This commit is contained in:
Generated
-1
@@ -1284,7 +1284,6 @@ dependencies = [
|
||||
"boa_engine",
|
||||
"clash-verge-logging",
|
||||
"log",
|
||||
"parking_lot 0.13.0",
|
||||
"serde_json",
|
||||
"serde_yaml_ng",
|
||||
"tokio",
|
||||
|
||||
@@ -68,8 +68,8 @@ pub fn use_sort(mut config: Mapping) -> Mapping {
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn use_keys<'a>(config: &'a Mapping) -> impl Iterator<Item = String> + 'a {
|
||||
config.iter().filter_map(|(key, _)| key.as_str()).map(|s: &str| {
|
||||
pub(super) fn lowercase_config_keys(config: &Mapping) -> impl Iterator<Item = String> {
|
||||
config.keys().filter_map(Value::as_str).map(|s: &str| {
|
||||
let mut s: String = s.into();
|
||||
s.make_ascii_lowercase();
|
||||
s
|
||||
|
||||
@@ -4,11 +4,10 @@ mod script;
|
||||
mod seq;
|
||||
mod tun;
|
||||
|
||||
pub use field::use_keys;
|
||||
pub use seq::SeqMap;
|
||||
|
||||
use self::{
|
||||
field::{use_lowercase, use_sort},
|
||||
field::{lowercase_config_keys, use_lowercase, use_sort},
|
||||
merge::use_merge,
|
||||
script::use_script,
|
||||
seq::use_seq,
|
||||
@@ -80,17 +79,17 @@ pub struct RenderedConfig {
|
||||
pub discarded_keys: Vec<String>,
|
||||
}
|
||||
|
||||
async fn process_override_items<Fut: Future<Output = ScriptOutcome> + Send>(
|
||||
async fn apply_merge_and_script<Fut: Future<Output = ScriptOutcome> + Send>(
|
||||
mut config: Mapping,
|
||||
mut exists_keys: Vec<String>,
|
||||
mut result_map: HashMap<String, ResultLog>,
|
||||
profile_keys: &mut HashSet<String>,
|
||||
chain_logs: &mut HashMap<String, ResultLog>,
|
||||
(merge_item, script_item): (Arc<ChainItem>, Arc<ChainItem>),
|
||||
profile_name: &str,
|
||||
authoritative: &AuthoritativeFields,
|
||||
execute_script: &(impl Fn(String, serde_json::Value, String) -> Fut + Sync),
|
||||
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
||||
) -> Mapping {
|
||||
if let ChainType::Merge(merge) = &merge_item.data {
|
||||
exists_keys.extend(use_keys(merge));
|
||||
profile_keys.extend(lowercase_config_keys(merge));
|
||||
let before = authoritative.current(&config);
|
||||
config = use_merge(merge.clone(), config);
|
||||
let notes: ResultLog = authoritative
|
||||
@@ -99,7 +98,7 @@ async fn process_override_items<Fut: Future<Output = ScriptOutcome> + Send>(
|
||||
.map(discarded_note)
|
||||
.collect();
|
||||
if !notes.is_empty() {
|
||||
result_map.entry(merge_item.uid.clone()).or_default().extend(notes);
|
||||
chain_logs.entry(merge_item.uid.clone()).or_default().extend(notes);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,7 +106,7 @@ async fn process_override_items<Fut: Future<Output = ScriptOutcome> + Send>(
|
||||
let before = authoritative.current(&config);
|
||||
let (res_config, changed_keys, mut logs) =
|
||||
use_script(script.clone(), config, profile_name.into(), execute_script).await;
|
||||
exists_keys.extend(changed_keys);
|
||||
profile_keys.extend(changed_keys);
|
||||
config = res_config;
|
||||
logs.extend(
|
||||
authoritative
|
||||
@@ -115,13 +114,13 @@ async fn process_override_items<Fut: Future<Output = ScriptOutcome> + Send>(
|
||||
.into_iter()
|
||||
.map(discarded_note),
|
||||
);
|
||||
result_map.insert(script_item.uid.clone(), logs);
|
||||
chain_logs.insert(script_item.uid.clone(), logs);
|
||||
}
|
||||
|
||||
(config, exists_keys, result_map)
|
||||
config
|
||||
}
|
||||
|
||||
fn process_seq_items(
|
||||
fn apply_sequence_overrides(
|
||||
mut config: Mapping,
|
||||
rules_item: Arc<ChainItem>,
|
||||
proxies_item: Arc<ChainItem>,
|
||||
@@ -653,20 +652,14 @@ pub async fn render<Fut: Future<Output = ScriptOutcome> + Send>(
|
||||
#[cfg(target_os = "linux")]
|
||||
tproxy_enabled,
|
||||
} = settings;
|
||||
let config = profile.config;
|
||||
let merge_item = profile.merge_item;
|
||||
let script_item = profile.script_item;
|
||||
let rules_item = profile.rules_item;
|
||||
let proxies_item = profile.proxies_item;
|
||||
let groups_item = profile.groups_item;
|
||||
let global_merge = profile.global_merge;
|
||||
let global_script = profile.global_script;
|
||||
let profile_name = profile.profile_name;
|
||||
|
||||
let result_map = HashMap::new();
|
||||
|
||||
let config = process_seq_items(config, rules_item, proxies_item, groups_item);
|
||||
let exists_keys = use_keys(&config).collect::<Vec<_>>();
|
||||
let config = apply_sequence_overrides(
|
||||
profile.config,
|
||||
profile.rules_item,
|
||||
profile.proxies_item,
|
||||
profile.groups_item,
|
||||
);
|
||||
let mut profile_keys = lowercase_config_keys(&config).collect();
|
||||
let mut chain_logs = HashMap::new();
|
||||
let gui_tun_keys = gui_tun_keys(&clash_config);
|
||||
|
||||
let config = merge_default_config(
|
||||
@@ -683,34 +676,28 @@ pub async fn render<Fut: Future<Output = ScriptOutcome> + Send>(
|
||||
|
||||
let config = apply_builtin_scripts(config, enable_builtin);
|
||||
let config = use_tun(config, enable_tun);
|
||||
let (config, dns_settings) = match dns_config {
|
||||
let (mut config, dns_settings) = match dns_config {
|
||||
Some(dns_config) => merge_dns_config(config, dns_config),
|
||||
None => (config, Mapping::new()),
|
||||
};
|
||||
|
||||
let authoritative = AuthoritativeFields::capture(&config, &gui_tun_keys, dns_settings);
|
||||
|
||||
let (config, exists_keys, result_map) = process_override_items(
|
||||
config,
|
||||
exists_keys,
|
||||
result_map,
|
||||
(global_merge, global_script),
|
||||
profile_name.as_str(),
|
||||
&authoritative,
|
||||
&execute_script,
|
||||
)
|
||||
.await;
|
||||
|
||||
let (config, exists_keys, result_map) = process_override_items(
|
||||
config,
|
||||
exists_keys,
|
||||
result_map,
|
||||
(merge_item, script_item),
|
||||
profile_name.as_str(),
|
||||
&authoritative,
|
||||
&execute_script,
|
||||
)
|
||||
.await;
|
||||
for overrides in [
|
||||
(profile.global_merge, profile.global_script),
|
||||
(profile.merge_item, profile.script_item),
|
||||
] {
|
||||
config = apply_merge_and_script(
|
||||
config,
|
||||
&mut profile_keys,
|
||||
&mut chain_logs,
|
||||
overrides,
|
||||
&profile.profile_name,
|
||||
&authoritative,
|
||||
&execute_script,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
let discarded_keys = authoritative.overridden(&authoritative.fingerprints, &authoritative.current(&config));
|
||||
let config = authoritative.enforce(config);
|
||||
@@ -722,8 +709,8 @@ pub async fn render<Fut: Future<Output = ScriptOutcome> + Send>(
|
||||
|
||||
RenderedConfig {
|
||||
config,
|
||||
exists_keys: exists_keys.into_iter().collect(),
|
||||
logs: result_map,
|
||||
exists_keys: profile_keys,
|
||||
logs: chain_logs,
|
||||
discarded_keys,
|
||||
}
|
||||
}
|
||||
@@ -1185,10 +1172,10 @@ mod authoritative_field_tests {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
AuthoritativeFields, ChainItem, ChainType, Mapping, ScriptOutcome, String, cleanup_proxy_groups,
|
||||
ensure_lan_bind_address, process_override_items, use_keys,
|
||||
AuthoritativeFields, ChainItem, ChainType, Mapping, ScriptOutcome, String, apply_merge_and_script,
|
||||
cleanup_proxy_groups, ensure_lan_bind_address, lowercase_config_keys,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::future::{Ready, ready};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -1237,10 +1224,12 @@ hosts: {script.example: "192.0.2.4"}"#;
|
||||
})
|
||||
};
|
||||
let profile_name = "test-profile";
|
||||
let (config, keys, logs) = process_override_items(
|
||||
let mut keys = HashSet::new();
|
||||
let mut logs = HashMap::new();
|
||||
let config = apply_merge_and_script(
|
||||
config,
|
||||
vec![],
|
||||
HashMap::new(),
|
||||
&mut keys,
|
||||
&mut logs,
|
||||
(
|
||||
merge_item("global-merge"),
|
||||
Arc::new(ChainItem {
|
||||
@@ -1253,10 +1242,10 @@ hosts: {script.example: "192.0.2.4"}"#;
|
||||
&apply_script_fixture,
|
||||
)
|
||||
.await;
|
||||
let (config, _, logs) = process_override_items(
|
||||
let config = apply_merge_and_script(
|
||||
config,
|
||||
keys,
|
||||
logs,
|
||||
&mut keys,
|
||||
&mut logs,
|
||||
(
|
||||
merge_item("profile-merge"),
|
||||
Arc::new(ChainItem {
|
||||
@@ -1299,7 +1288,7 @@ hosts: {script.example: "192.0.2.4"}"#;
|
||||
r"{global-merge-wins: other, global-script-wins: other, profile-merge-wins: other,
|
||||
profile-script-wins: other, nested: {winner: other}, dns: {enable: true}, tun: {enable: true}}",
|
||||
);
|
||||
let exists_keys = use_keys(&config).collect();
|
||||
let mut exists_keys = lowercase_config_keys(&config).collect();
|
||||
config.insert("application-only".into(), true.into());
|
||||
|
||||
let global_merge = Arc::new(ChainItem {
|
||||
@@ -1332,20 +1321,21 @@ hosts: {script.example: "192.0.2.4"}"#;
|
||||
|
||||
let profile_name = "test-profile";
|
||||
let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());
|
||||
let (config, exists_keys, result_map) = process_override_items(
|
||||
let mut logs = HashMap::new();
|
||||
let config = apply_merge_and_script(
|
||||
config,
|
||||
exists_keys,
|
||||
HashMap::new(),
|
||||
&mut exists_keys,
|
||||
&mut logs,
|
||||
(global_merge, global_script),
|
||||
profile_name,
|
||||
&authoritative,
|
||||
&apply_script_fixture,
|
||||
)
|
||||
.await;
|
||||
let (config, exists_keys, _) = process_override_items(
|
||||
let config = apply_merge_and_script(
|
||||
config,
|
||||
exists_keys,
|
||||
result_map,
|
||||
&mut exists_keys,
|
||||
&mut logs,
|
||||
(profile_merge, profile_script),
|
||||
profile_name,
|
||||
&authoritative,
|
||||
@@ -1365,7 +1355,7 @@ hosts: {script.example: "192.0.2.4"}"#;
|
||||
.and_then(serde_yaml_ng::Value::as_str),
|
||||
Some("profile-script")
|
||||
);
|
||||
assert!(!exists_keys.contains(&"application-only".into()));
|
||||
assert!(!exists_keys.contains("application-only"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -10,14 +10,12 @@ pub struct SeqMap {
|
||||
pub delete: Vec<String>,
|
||||
}
|
||||
|
||||
fn collect_proxy_names(seq: &Sequence) -> Vec<TriStr> {
|
||||
seq.iter()
|
||||
.filter_map(|item| match item {
|
||||
Value::Mapping(map) => map.get("name").and_then(Value::as_str).map(TriStr::from),
|
||||
Value::String(name) => Some(TriStr::from(name.as_str())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
fn proxy_name(proxy: &Value) -> Option<&str> {
|
||||
match proxy {
|
||||
Value::Mapping(proxy) => proxy.get("name").and_then(Value::as_str),
|
||||
Value::String(name) => Some(name),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_selector_group(group_map: &Mapping) -> bool {
|
||||
@@ -35,41 +33,30 @@ pub fn use_seq(seq: SeqMap, mut config: Mapping, field: &str) -> Mapping {
|
||||
} = seq;
|
||||
|
||||
let added_proxy_names = if field == "proxies" {
|
||||
let mut names = collect_proxy_names(&prepend);
|
||||
names.extend(collect_proxy_names(&append));
|
||||
let mut seen = HashSet::new();
|
||||
names
|
||||
.into_iter()
|
||||
.filter(|name| seen.insert(name.clone()))
|
||||
.collect::<Vec<TriStr>>()
|
||||
prepend
|
||||
.iter()
|
||||
.chain(&append)
|
||||
.filter_map(proxy_name)
|
||||
.map(TriStr::from)
|
||||
.collect::<Vec<_>>()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let mut updated_items = Sequence::new();
|
||||
updated_items.extend(prepend);
|
||||
|
||||
let mut updated_items = prepend;
|
||||
if let Some(Value::Sequence(existing_items)) = config.remove(field) {
|
||||
// Filter out deleted items
|
||||
let kept_items: Sequence = existing_items
|
||||
.into_iter()
|
||||
.filter(|item| {
|
||||
if let Value::String(s) = item {
|
||||
!delete.contains(s)
|
||||
} else if let Value::Mapping(m) = item {
|
||||
if let Some(Value::String(name)) = m.get("name") {
|
||||
!delete.contains(name)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
updated_items.extend(kept_items);
|
||||
updated_items.extend(existing_items.into_iter().filter(|item| {
|
||||
let name = match item {
|
||||
Value::String(name) => Some(name),
|
||||
Value::Mapping(mapping) => match mapping.get("name") {
|
||||
Some(Value::String(name)) => Some(name),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
name.is_none_or(|name| !delete.contains(name))
|
||||
}));
|
||||
}
|
||||
|
||||
updated_items.extend(append);
|
||||
config.insert(Value::String(field.into()), Value::Sequence(updated_items));
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ edition = "2024"
|
||||
boa_engine = { workspace = true }
|
||||
clash-verge-logging = { workspace = true }
|
||||
log = { workspace = true }
|
||||
parking_lot = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml_ng = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use boa_engine::{Context, JsString, JsValue, Source, js_string, native_function::NativeFunction, property::Attribute};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use parking_lot::Mutex;
|
||||
use serde_yaml_ng::Mapping;
|
||||
use std::sync::Arc;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
use tristr::alias::String;
|
||||
|
||||
const MAX_OUTPUTS: usize = 1000;
|
||||
@@ -66,13 +66,10 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
|
||||
.runtime_limits_mut()
|
||||
.set_loop_iteration_limit(MAX_LOOP_ITERATIONS);
|
||||
|
||||
let outputs = Arc::new(Mutex::new(vec![]));
|
||||
let total_size = Arc::new(Mutex::new(0usize));
|
||||
|
||||
let outputs_clone = Arc::clone(&outputs);
|
||||
let total_size_clone = Arc::clone(&total_size);
|
||||
|
||||
let take_logs = || std::mem::take(&mut *outputs.lock());
|
||||
let logs = Rc::new(RefCell::new(Vec::new()));
|
||||
let console_logs = Rc::clone(&logs);
|
||||
let logged_bytes = Cell::new(0);
|
||||
let take_logs = || logs.take();
|
||||
let bail = |reason: std::string::String| (Err(reason), take_logs());
|
||||
|
||||
let _ = context.register_global_builtin_callable("__verge_log__".into(), 2, unsafe {
|
||||
@@ -93,22 +90,21 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
|
||||
boa_engine::JsError::from_opaque(JsString::from("Failed to convert data to string").into())
|
||||
})?;
|
||||
|
||||
if outputs_clone.lock().len() >= MAX_OUTPUTS {
|
||||
let mut entries = console_logs.borrow_mut();
|
||||
if entries.len() >= MAX_OUTPUTS {
|
||||
return Err(boa_engine::JsError::from_opaque(
|
||||
JsString::from("Maximum number of log outputs exceeded").into(),
|
||||
));
|
||||
}
|
||||
|
||||
let mut size = total_size_clone.lock();
|
||||
let new_size = *size + level.len() + data.len();
|
||||
let new_size = logged_bytes.get() + level.len() + data.len();
|
||||
if new_size > MAX_OUTPUT_SIZE {
|
||||
return Err(boa_engine::JsError::from_opaque(
|
||||
JsString::from("Maximum output size exceeded").into(),
|
||||
));
|
||||
}
|
||||
*size = new_size;
|
||||
drop(size);
|
||||
outputs_clone.lock().push((level.into(), data.into()));
|
||||
logged_bytes.set(new_size);
|
||||
entries.push((level.into(), data.into()));
|
||||
Ok(JsValue::undefined())
|
||||
})
|
||||
});
|
||||
@@ -132,15 +128,15 @@ fn eval_script(script: &str, config_json: &serde_json::Value, name: &String) ->
|
||||
return bail(format!("failed to bind config for script: {err}"));
|
||||
}
|
||||
|
||||
let safe_name = escape_js_string_for_single_quote(name);
|
||||
if safe_name.len() > 1024 {
|
||||
let escaped_profile_name = escape_js_string_for_single_quote(name);
|
||||
if escaped_profile_name.len() > 1024 {
|
||||
return bail("Name parameter too long".to_owned());
|
||||
}
|
||||
|
||||
let code = format!(
|
||||
r"try{{
|
||||
{script};
|
||||
main(globalThis.__verge_config__,'{safe_name}')
|
||||
main(globalThis.__verge_config__,'{escaped_profile_name}')
|
||||
}} catch(err) {{
|
||||
`__error_flag__ ${{err.toString()}}`
|
||||
}}"
|
||||
@@ -234,7 +230,18 @@ fn escape_js_string_for_single_quote(s: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{MainDeclaration, validate};
|
||||
use super::{MainDeclaration, eval_script, validate};
|
||||
|
||||
#[test]
|
||||
fn console_entries_survive_a_script_error() {
|
||||
let (result, logs) = eval_script(
|
||||
"function main() { console.log(1); console.warn(2); throw Error(); }",
|
||||
&serde_json::json!({}),
|
||||
&"profile".into(),
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert_eq!(logs, [("log".into(), "1".into()), ("warn".into(), "2".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_distinguishes_missing_main_from_evaluation_failure() {
|
||||
|
||||
@@ -7,7 +7,7 @@ pub struct ProxyViewInput {
|
||||
pub runtime_group_order: Vec<String>,
|
||||
pub group_scopes: BTreeMap<String, GroupScope>,
|
||||
pub proxies: HashMap<String, ProxySnapshot>,
|
||||
pub providers: Option<HashMap<String, ProviderSnapshot>>,
|
||||
pub providers: Option<BTreeMap<String, ProviderSnapshot>>,
|
||||
}
|
||||
|
||||
pub struct ProxySnapshot {
|
||||
@@ -43,8 +43,6 @@ pub struct GroupScope {
|
||||
pub exclude_types: Vec<String>,
|
||||
}
|
||||
|
||||
pub struct ProxyViewBuilder;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProxyViewV1 {
|
||||
@@ -265,14 +263,14 @@ impl<'a> MemberResolver<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
impl ProxyViewBuilder {
|
||||
pub fn build(input: ProxyViewInput) -> ProxyViewV1 {
|
||||
let ProxyViewInput {
|
||||
impl ProxyViewInput {
|
||||
pub fn into_view(self) -> ProxyViewV1 {
|
||||
let Self {
|
||||
runtime_group_order,
|
||||
group_scopes,
|
||||
proxies,
|
||||
providers,
|
||||
} = input;
|
||||
} = self;
|
||||
let provider_state = if providers.is_some() {
|
||||
ProxyViewProviderState::Ready
|
||||
} else {
|
||||
@@ -352,14 +350,13 @@ fn build_core_records(
|
||||
}
|
||||
|
||||
fn build_provider_records(
|
||||
providers: Option<HashMap<String, ProviderSnapshot>>,
|
||||
providers: Option<BTreeMap<String, ProviderSnapshot>>,
|
||||
records: &mut BTreeMap<String, ProxyNodeView>,
|
||||
) -> (Vec<ProxyProviderView>, ProviderCandidates) {
|
||||
let providers = providers.map_or_default(|providers| providers.into_iter().collect::<BTreeMap<_, _>>());
|
||||
let mut views = Vec::new();
|
||||
let mut candidates = BTreeMap::new();
|
||||
|
||||
for (provider_name, provider) in providers {
|
||||
for (provider_name, provider) in providers.into_iter().flatten() {
|
||||
let ProviderSnapshot {
|
||||
vehicle_type,
|
||||
proxies,
|
||||
|
||||
@@ -9,6 +9,8 @@ use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Component, Path, PathBuf, Prefix};
|
||||
use tristr::TriStr;
|
||||
|
||||
const PROVIDER_SECTIONS: [&str; 2] = ["proxy-providers", "rule-providers"];
|
||||
|
||||
pub const GEO_ASSETS: &[&str] = &[
|
||||
"Country.mmdb",
|
||||
"ASN.mmdb",
|
||||
@@ -59,7 +61,7 @@ pub fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<R
|
||||
let config_root = std::fs::canonicalize(config_root)?;
|
||||
let mut destinations = HashSet::new();
|
||||
let mut remote_providers = Vec::new();
|
||||
for section in ["proxy-providers", "rule-providers"] {
|
||||
for section in PROVIDER_SECTIONS {
|
||||
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
|
||||
continue;
|
||||
};
|
||||
@@ -88,7 +90,7 @@ pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path)
|
||||
let config_root = std::fs::canonicalize(config_root)?;
|
||||
let mut paths = BTreeMap::<TriStr, ProviderPathOwners>::new();
|
||||
let mut reserved: HashSet<TriStr> = GEO_ASSETS.iter().copied().map(TriStr::from).collect();
|
||||
for section in ["proxy-providers", "rule-providers"] {
|
||||
for section in PROVIDER_SECTIONS {
|
||||
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
|
||||
continue;
|
||||
};
|
||||
@@ -172,22 +174,16 @@ fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<Runtim
|
||||
let mut destinations = HashSet::new();
|
||||
let mut remote_providers = Vec::new();
|
||||
|
||||
collect_provider_assets(
|
||||
&mut config,
|
||||
"proxy-providers",
|
||||
&config_root,
|
||||
&mut destinations,
|
||||
&mut assets,
|
||||
&mut remote_providers,
|
||||
)?;
|
||||
collect_provider_assets(
|
||||
&mut config,
|
||||
"rule-providers",
|
||||
&config_root,
|
||||
&mut destinations,
|
||||
&mut assets,
|
||||
&mut remote_providers,
|
||||
)?;
|
||||
for section in PROVIDER_SECTIONS {
|
||||
collect_provider_assets(
|
||||
&mut config,
|
||||
section,
|
||||
&config_root,
|
||||
&mut destinations,
|
||||
&mut assets,
|
||||
&mut remote_providers,
|
||||
)?;
|
||||
}
|
||||
collect_ssh_private_keys(&mut config, &config_root, &mut destinations, &mut assets);
|
||||
for filename in GEO_ASSETS {
|
||||
let source = config_root.join(filename);
|
||||
|
||||
@@ -2,10 +2,6 @@ use serde_yaml_ng::{Mapping, Value};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use tristr::alias::String;
|
||||
|
||||
use clash_verge_config_render::use_keys;
|
||||
|
||||
const PATCH_CONFIG_INNER: [&str; 5] = ["allow-lan", "ipv6", "log-level", "unified-delay", "tunnels"];
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct IRuntime {
|
||||
pub config: Option<Mapping>,
|
||||
@@ -17,39 +13,6 @@ pub struct IRuntime {
|
||||
}
|
||||
|
||||
impl IRuntime {
|
||||
#[inline]
|
||||
pub fn patch_config(&mut self, patch: &Mapping) {
|
||||
let config = if let Some(config) = self.config.as_mut() {
|
||||
config
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
|
||||
for key in PATCH_CONFIG_INNER.iter() {
|
||||
if let Some(value) = patch.get(key) {
|
||||
config.insert((*key).into(), value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let Some(patch_tun) = patch.get("tun") else {
|
||||
return;
|
||||
};
|
||||
|
||||
let tun_key = Value::from("tun");
|
||||
if !matches!(config.get(&tun_key), Some(Value::Mapping(_))) {
|
||||
config.insert(tun_key.clone(), Value::Mapping(Mapping::new()));
|
||||
}
|
||||
|
||||
if let (Some(patch_tun_mapping), Some(Value::Mapping(tun))) = (patch_tun.as_mapping(), config.get_mut(&tun_key))
|
||||
{
|
||||
for key in use_keys(patch_tun_mapping) {
|
||||
if let Some(value) = patch_tun_mapping.get(key.as_str()) {
|
||||
tun.insert(Value::from(key.as_str()), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds `dialer-proxy` links from an ordered proxy chain, or removes them for `None`.
|
||||
#[inline]
|
||||
pub fn update_proxy_chain_config(&mut self, proxy_chain_config: Option<Value>) {
|
||||
|
||||
@@ -18,56 +18,45 @@ struct CachedChain {
|
||||
|
||||
static CHAIN_CACHE: LazyLock<Mutex<HashMap<PathBuf, CachedChain>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
// Helper trait to allow async conversion
|
||||
pub trait AsyncChainItemFrom {
|
||||
async fn from_async(item: &PrfItem) -> Option<Arc<ChainItem>>;
|
||||
}
|
||||
pub(super) async fn load_chain_item(item: &PrfItem) -> Option<Arc<ChainItem>> {
|
||||
let itype = item.itype.as_ref()?.as_str();
|
||||
let file = item.file.as_ref()?;
|
||||
let path = dirs::app_profiles_dir().ok()?.join(file.as_str());
|
||||
|
||||
impl AsyncChainItemFrom for Option<Arc<ChainItem>> {
|
||||
async fn from_async(item: &PrfItem) -> Self {
|
||||
let itype = item.itype.as_ref()?.as_str();
|
||||
let file = item.file.clone()?;
|
||||
let uid = item.uid.clone().unwrap_or_else(|| "".into());
|
||||
let path = dirs::app_profiles_dir().ok()?.join(file.as_str());
|
||||
|
||||
let meta = fs::metadata(&path).await.ok()?;
|
||||
let (mtime, len) = (meta.modified().ok()?, meta.len());
|
||||
if let Some(cached) = CHAIN_CACHE.lock().get(&path)
|
||||
&& cached.mtime == mtime
|
||||
&& cached.len == len
|
||||
{
|
||||
return Some(Arc::clone(&cached.item));
|
||||
}
|
||||
|
||||
let loaded = Arc::new(match itype {
|
||||
"script" => Some(ChainItem {
|
||||
uid,
|
||||
data: ChainType::Script(fs::read_to_string(&path).await.ok()?.as_str().into()),
|
||||
}),
|
||||
"merge" => Some(ChainItem {
|
||||
uid,
|
||||
data: ChainType::Merge(help::read_mapping(&path).await.ok()?),
|
||||
}),
|
||||
"rules" | "proxies" | "groups" => {
|
||||
let seq_map = help::read_yaml::<SeqMap>(&path).await.ok()?;
|
||||
let data = match itype {
|
||||
"rules" => ChainType::Rules(seq_map),
|
||||
"proxies" => ChainType::Proxies(seq_map),
|
||||
_ => ChainType::Groups(seq_map),
|
||||
};
|
||||
Some(ChainItem { uid, data })
|
||||
}
|
||||
_ => None,
|
||||
}?);
|
||||
|
||||
CHAIN_CACHE.lock().insert(
|
||||
path,
|
||||
CachedChain {
|
||||
mtime,
|
||||
len,
|
||||
item: Arc::clone(&loaded),
|
||||
},
|
||||
);
|
||||
Some(loaded)
|
||||
let meta = fs::metadata(&path).await.ok()?;
|
||||
let (mtime, len) = (meta.modified().ok()?, meta.len());
|
||||
if let Some(cached) = CHAIN_CACHE.lock().get(&path)
|
||||
&& cached.mtime == mtime
|
||||
&& cached.len == len
|
||||
{
|
||||
return Some(Arc::clone(&cached.item));
|
||||
}
|
||||
|
||||
let data = match itype {
|
||||
"script" => ChainType::Script(fs::read_to_string(&path).await.ok()?.into()),
|
||||
"merge" => ChainType::Merge(help::read_mapping(&path).await.ok()?),
|
||||
"rules" | "proxies" | "groups" => {
|
||||
let seq_map = help::read_yaml::<SeqMap>(&path).await.ok()?;
|
||||
match itype {
|
||||
"rules" => ChainType::Rules(seq_map),
|
||||
"proxies" => ChainType::Proxies(seq_map),
|
||||
_ => ChainType::Groups(seq_map),
|
||||
}
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let loaded = Arc::new(ChainItem {
|
||||
uid: item.uid.clone().unwrap_or_default(),
|
||||
data,
|
||||
});
|
||||
|
||||
CHAIN_CACHE.lock().insert(
|
||||
path,
|
||||
CachedChain {
|
||||
mtime,
|
||||
len,
|
||||
item: Arc::clone(&loaded),
|
||||
},
|
||||
);
|
||||
Some(loaded)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
mod chain;
|
||||
|
||||
use self::chain::AsyncChainItemFrom as _;
|
||||
use self::chain::load_chain_item;
|
||||
use crate::config::dns::{DnsOverrideState, dns_override_source};
|
||||
use crate::core::handle::Handle;
|
||||
use crate::core::notify::NoticeStatus;
|
||||
@@ -67,9 +67,7 @@ async fn chain_item_or_default(
|
||||
default_item: impl FnOnce() -> Arc<ChainItem>,
|
||||
) -> Arc<ChainItem> {
|
||||
if let Some(item) = item {
|
||||
<Option<Arc<ChainItem>>>::from_async(item)
|
||||
.await
|
||||
.unwrap_or_else(default_item)
|
||||
load_chain_item(item).await.unwrap_or_else(default_item)
|
||||
} else {
|
||||
default_item()
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ mod groups;
|
||||
|
||||
use clash_verge_proxy_view::{
|
||||
DelayHistory, ProviderSnapshot, ProxyCapabilities, ProxyProviderVehicleType, ProxySnapshot, ProxySubscriptionInfo,
|
||||
ProxyViewBuilder, ProxyViewInput, ProxyViewV1,
|
||||
ProxyViewInput, ProxyViewV1,
|
||||
};
|
||||
use serde_yaml_ng::Mapping;
|
||||
use std::future::Future;
|
||||
@@ -20,7 +20,7 @@ pub(crate) async fn load_proxy_view(
|
||||
let (proxies, providers) = tokio::join!(proxies, providers);
|
||||
let proxies = proxies?;
|
||||
|
||||
Ok(ProxyViewBuilder::build(ProxyViewInput {
|
||||
Ok(ProxyViewInput {
|
||||
runtime_group_order,
|
||||
group_scopes,
|
||||
proxies: proxies
|
||||
@@ -35,7 +35,8 @@ pub(crate) async fn load_proxy_view(
|
||||
.filter_map(|(name, provider)| provider_snapshot(provider).map(|snapshot| (name.into(), snapshot)))
|
||||
.collect()
|
||||
}),
|
||||
}))
|
||||
}
|
||||
.into_view())
|
||||
}
|
||||
|
||||
fn proxy_snapshot(proxy: Proxy) -> ProxySnapshot {
|
||||
@@ -106,11 +107,14 @@ mod tests {
|
||||
"proxy-providers: {z: {}, a: {}}\n\
|
||||
proxy-groups:\n\
|
||||
- {name: GLOBAL}\n\
|
||||
- {name: Select, use: [a]}\n\
|
||||
- {name: Another}\n\
|
||||
- {name: Select, use: [a], include-all-providers: true, exclude-type: Direct}",
|
||||
)?;
|
||||
let proxies = r#"{"proxies":{
|
||||
"GLOBAL":{"type":"Selector","all":["Select"]},
|
||||
"Select":{"type":"Selector","all":["shared"]}
|
||||
"Select":{"type":"Selector","all":["shared"]},
|
||||
"Another":{"type":"Selector","all":[]}
|
||||
}}"#;
|
||||
let providers = serde_json::from_str(
|
||||
r#"{"providers":{
|
||||
@@ -137,7 +141,8 @@ mod tests {
|
||||
view.global.as_ref().map(|global| global.members.as_slice()),
|
||||
Some([ProxyMemberRef::Group { name: "Select".into() }].as_slice())
|
||||
);
|
||||
assert_eq!(view.groups.len(), 1);
|
||||
assert_eq!(view.groups.len(), 2);
|
||||
assert_eq!(view.groups[1].name.as_str(), "Another");
|
||||
assert_eq!(view.groups[0].name.as_str(), "Select");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,81 +1,61 @@
|
||||
use clash_verge_proxy_view::GroupScope;
|
||||
use serde_yaml_ng::Mapping;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::collections::BTreeMap;
|
||||
use tristr::alias::String as ViewString;
|
||||
|
||||
fn runtime_group_order(config: Option<&Mapping>) -> Vec<ViewString> {
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
config
|
||||
.and_then(|config| config.get("proxy-groups"))
|
||||
.and_then(|groups| groups.as_sequence())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|group| group.get("name"))
|
||||
.filter_map(|name| name.as_str())
|
||||
.filter(|name| !name.is_empty() && *name != "GLOBAL")
|
||||
.filter(|name| seen.insert(*name))
|
||||
.map(ViewString::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Mirrors Mihomo: `include-all`/`include-all-providers` replace `use` with every provider, sorted.
|
||||
fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<ViewString, GroupScope> {
|
||||
let Some(config) = config else {
|
||||
return BTreeMap::new();
|
||||
pub(super) fn runtime_groups(config: Option<&Mapping>) -> (Vec<ViewString>, BTreeMap<ViewString, GroupScope>) {
|
||||
let mut order = Vec::new();
|
||||
let mut scopes = BTreeMap::new();
|
||||
let Some(config) = config else { return (order, scopes) };
|
||||
let Some(groups) = config.get("proxy-groups").and_then(|groups| groups.as_sequence()) else {
|
||||
return (order, scopes);
|
||||
};
|
||||
let mut all_providers = None;
|
||||
let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true);
|
||||
|
||||
config
|
||||
.get("proxy-groups")
|
||||
.and_then(|groups| groups.as_sequence())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|group| group.as_mapping())
|
||||
.filter_map(|group| {
|
||||
let name = ViewString::from(group.get("name")?.as_str()?);
|
||||
let providers = if flag(group, "include-all") || flag(group, "include-all-providers") {
|
||||
all_providers
|
||||
.get_or_insert_with(|| {
|
||||
let mut names = config
|
||||
.get("proxy-providers")
|
||||
.and_then(|providers| providers.as_mapping())
|
||||
.into_iter()
|
||||
.flat_map(|providers| providers.keys())
|
||||
.filter_map(|name| name.as_str())
|
||||
.map(ViewString::from)
|
||||
.collect::<Vec<_>>();
|
||||
names.sort();
|
||||
names
|
||||
})
|
||||
.clone()
|
||||
} else {
|
||||
group
|
||||
.get("use")
|
||||
.and_then(|providers| providers.as_sequence())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|provider| provider.as_str())
|
||||
.map(ViewString::from)
|
||||
.collect()
|
||||
};
|
||||
let exclude_types = group
|
||||
.get("exclude-type")
|
||||
.and_then(|types| types.as_str())
|
||||
.filter(|types| !types.is_empty())
|
||||
.map_or_default(|types| types.split('|').map(ViewString::from).collect());
|
||||
Some((
|
||||
name,
|
||||
GroupScope {
|
||||
providers,
|
||||
exclude_types,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn runtime_groups(config: Option<&Mapping>) -> (Vec<ViewString>, BTreeMap<ViewString, GroupScope>) {
|
||||
(runtime_group_order(config), runtime_group_scopes(config))
|
||||
for group in groups.iter().filter_map(|group| group.as_mapping()) {
|
||||
let Some(name) = group.get("name").and_then(|name| name.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
let name = ViewString::from(name);
|
||||
// Mihomo sorts all providers when either flag replaces the explicit use list.
|
||||
let providers = if flag(group, "include-all") || flag(group, "include-all-providers") {
|
||||
all_providers
|
||||
.get_or_insert_with(|| {
|
||||
let mut names = config
|
||||
.get("proxy-providers")
|
||||
.and_then(|providers| providers.as_mapping())
|
||||
.into_iter()
|
||||
.flat_map(|providers| providers.keys())
|
||||
.filter_map(|name| name.as_str())
|
||||
.map(ViewString::from)
|
||||
.collect::<Vec<_>>();
|
||||
names.sort();
|
||||
names
|
||||
})
|
||||
.clone()
|
||||
} else {
|
||||
group
|
||||
.get("use")
|
||||
.and_then(|providers| providers.as_sequence())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|provider| provider.as_str())
|
||||
.map(ViewString::from)
|
||||
.collect()
|
||||
};
|
||||
let exclude_types = group
|
||||
.get("exclude-type")
|
||||
.and_then(|types| types.as_str())
|
||||
.filter(|types| !types.is_empty())
|
||||
.map_or_default(|types| types.split('|').map(ViewString::from).collect());
|
||||
let scope = GroupScope {
|
||||
providers,
|
||||
exclude_types,
|
||||
};
|
||||
if scopes.insert(name.clone(), scope).is_none() && !name.is_empty() && name != "GLOBAL" {
|
||||
order.push(name);
|
||||
}
|
||||
}
|
||||
(order, scopes)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user