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:
@@ -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