Files
clash-verge-rev/crates/clash-verge-proxy-view/src/lib.rs
T
Tunglies 06329c3337 refactor(backend): extract configuration and runtime capabilities (#8801)
* 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
2026-12-03 23:24:11 +00:00

521 lines
15 KiB
Rust

use std::collections::{BTreeMap, BTreeSet, HashMap};
use serde::Serialize;
use tristr::alias::String;
pub struct ProxyViewInput {
pub runtime_group_order: Vec<String>,
pub group_scopes: BTreeMap<String, GroupScope>,
pub proxies: HashMap<String, ProxySnapshot>,
pub providers: Option<BTreeMap<String, ProviderSnapshot>>,
}
pub struct ProxySnapshot {
pub name: String,
pub proxy_type: String,
pub all: Option<Vec<String>>,
pub fixed: Option<String>,
pub hidden: Option<bool>,
pub icon: Option<String>,
pub now: Option<String>,
pub test_url: Option<String>,
pub id: Option<String>,
pub history: Vec<DelayHistory>,
pub capabilities: ProxyCapabilities,
}
pub struct ProviderSnapshot {
pub vehicle_type: ProxyProviderVehicleType,
pub proxies: Vec<ProxySnapshot>,
pub updated_at: Option<String>,
pub subscription_info: Option<ProxySubscriptionInfo>,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
pub struct DelayHistory {
pub time: String,
pub delay: u16,
}
/// The providers a group draws from (Mihomo order) and its `exclude-type` entries.
pub struct GroupScope {
pub providers: Vec<String>,
pub exclude_types: Vec<String>,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ProxyViewV1 {
pub schema_version: u8,
pub order_source: ProxyViewOrderSource,
pub provider_state: ProxyViewProviderState,
pub global: Option<ProxyGroupView>,
pub direct: Option<String>,
pub groups: Vec<ProxyGroupView>,
pub records: BTreeMap<String, ProxyNodeView>,
pub standalone: Vec<String>,
pub providers: Vec<ProxyProviderView>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "lowercase")]
pub enum ProxyViewOrderSource {
Runtime,
Fallback,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "lowercase")]
pub enum ProxyViewProviderState {
Ready,
Unavailable,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
pub struct ProxyCapabilities {
pub udp: bool,
pub xudp: bool,
pub tfo: bool,
pub mptcp: bool,
pub smux: bool,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ProxyGroupView {
pub name: String,
#[serde(rename = "type")]
pub proxy_type: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub now: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub fixed: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hidden: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub test_url: Option<String>,
pub history: Vec<DelayHistory>,
#[serde(flatten)]
pub capabilities: ProxyCapabilities,
pub members: Vec<ProxyMemberRef>,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ProxyNodeView {
pub record_id: String,
pub name: String,
#[serde(rename = "type")]
pub proxy_type: String,
pub history: Vec<DelayHistory>,
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub hidden: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub test_url: Option<String>,
#[serde(flatten)]
pub capabilities: ProxyCapabilities,
pub source: ProxyNodeSource,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ProxyNodeSource {
Core {
#[serde(rename = "proxyName")]
proxy_name: String,
},
Provider {
#[serde(rename = "providerName")]
provider_name: String,
#[serde(rename = "proxyName")]
proxy_name: String,
},
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum ProxyMemberRef {
Group {
name: String,
},
Node {
name: String,
#[serde(rename = "recordId")]
record_id: String,
},
Unresolved {
name: String,
reason: ProxyMemberUnresolvedReason,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)]
pub enum ProxyMemberUnresolvedReason {
#[serde(rename = "missing")]
Missing,
#[serde(rename = "ambiguous")]
Ambiguous,
#[serde(rename = "provider-unavailable")]
ProviderUnavailable,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
#[serde(rename_all = "camelCase")]
pub struct ProxyProviderView {
pub name: String,
pub vehicle_type: ProxyProviderVehicleType,
#[serde(skip_serializing_if = "Option::is_none")]
pub updated_at: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub subscription_info: Option<ProxySubscriptionInfo>,
pub proxy_record_ids: Vec<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, specta::Type)]
pub enum ProxyProviderVehicleType {
#[serde(rename = "HTTP")]
Http,
#[serde(rename = "File")]
File,
#[serde(rename = "Inline")]
Inline,
}
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
pub struct ProxySubscriptionInfo {
pub upload: i64,
pub download: i64,
pub total: i64,
pub expire: i64,
}
/// Proxy name -> `(provider name, record id)` in provider order.
type ProviderCandidates = BTreeMap<String, Vec<(String, String)>>;
struct MemberResolver<'a> {
group_names: BTreeSet<String>,
group_scopes: &'a BTreeMap<String, GroupScope>,
records: &'a BTreeMap<String, ProxyNodeView>,
core_node_ids: &'a BTreeMap<String, String>,
provider_candidates: &'a ProviderCandidates,
provider_available: bool,
}
impl<'a> MemberResolver<'a> {
/// Same-name records in the order Mihomo lists them in `group`: `use` order, after `exclude-type`.
fn scoped_candidates(&self, group: &str, candidates: &'a [(String, String)]) -> Vec<&'a String> {
let Some(scope) = self.group_scopes.get(group) else {
return Vec::new();
};
scope
.providers
.iter()
.flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider))
.map(|(_, record_id)| record_id)
.filter(|record_id| {
scope.exclude_types.is_empty()
|| !self.records.get(*record_id).is_some_and(|node| {
scope
.exclude_types
.iter()
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
})
})
.collect()
}
fn resolve(
&self,
group: &str,
name: String,
seen: &mut BTreeMap<String, (usize, Vec<&'a String>)>,
) -> ProxyMemberRef {
if self.group_names.contains(&name) {
ProxyMemberRef::Group { name }
} else if let Some(record_id) = self.core_node_ids.get(&name) {
ProxyMemberRef::Node {
name,
record_id: record_id.clone(),
}
} else if !self.provider_available {
ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::ProviderUnavailable,
}
} else {
let candidates = self.provider_candidates.get(&name).map_or(&[][..], Vec::as_slice);
let record_id = match candidates {
[(_, record_id)] => Some(record_id),
[] => {
return ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::Missing,
};
}
_ => {
// The n-th occurrence in Mihomo's member list selects the n-th scoped candidate.
let (occurrence, scoped) = seen
.entry(name.clone())
.or_insert_with(|| (0, self.scoped_candidates(group, candidates)));
let record_id = scoped.get(*occurrence).or_else(|| scoped.first()).copied();
*occurrence += 1;
record_id
}
};
match record_id {
Some(record_id) => ProxyMemberRef::Node {
name,
record_id: record_id.clone(),
},
None => ProxyMemberRef::Unresolved {
name,
reason: ProxyMemberUnresolvedReason::Ambiguous,
},
}
}
}
}
impl ProxyViewInput {
pub fn into_view(self) -> ProxyViewV1 {
let Self {
runtime_group_order,
group_scopes,
proxies,
providers,
} = self;
let provider_state = if providers.is_some() {
ProxyViewProviderState::Ready
} else {
ProxyViewProviderState::Unavailable
};
let (mut core_groups, core_nodes) = partition_core(proxies);
let (mut records, core_node_ids) = build_core_records(core_nodes);
let (providers, provider_candidates) = build_provider_records(providers, &mut records);
let resolver = MemberResolver {
group_names: core_groups.keys().cloned().collect(),
group_scopes: &group_scopes,
records: &records,
core_node_ids: &core_node_ids,
provider_candidates: &provider_candidates,
provider_available: provider_state == ProxyViewProviderState::Ready,
};
let global = core_groups
.remove("GLOBAL")
.map(|proxy| build_group("GLOBAL".into(), proxy, &resolver));
let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver);
let direct = core_node_ids.get("DIRECT").cloned();
let standalone = build_standalone(&core_node_ids);
ProxyViewV1 {
schema_version: 1,
order_source,
provider_state,
global,
direct,
groups,
records,
standalone,
providers,
}
}
}
fn partition_core(
proxies: HashMap<String, ProxySnapshot>,
) -> (BTreeMap<String, ProxySnapshot>, BTreeMap<String, ProxySnapshot>) {
let mut groups = BTreeMap::new();
let mut nodes = BTreeMap::new();
for (name, proxy) in proxies {
if proxy.all.is_some() {
groups.insert(name, proxy);
} else {
nodes.insert(name, proxy);
}
}
(groups, nodes)
}
fn build_core_records(
core_nodes: BTreeMap<String, ProxySnapshot>,
) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) {
let mut records = BTreeMap::new();
let mut ids = BTreeMap::new();
for (index, (name, proxy)) in core_nodes.into_iter().enumerate() {
let record_id: String = format!("c:{index}").into();
ids.insert(name.clone(), record_id.clone());
records.insert(
record_id.clone(),
build_node(
record_id,
name.clone(),
proxy,
ProxyNodeSource::Core { proxy_name: name },
),
);
}
(records, ids)
}
fn build_provider_records(
providers: Option<BTreeMap<String, ProviderSnapshot>>,
records: &mut BTreeMap<String, ProxyNodeView>,
) -> (Vec<ProxyProviderView>, ProviderCandidates) {
let mut views = Vec::new();
let mut candidates = BTreeMap::new();
for (provider_name, provider) in providers.into_iter().flatten() {
let ProviderSnapshot {
vehicle_type,
proxies,
updated_at,
subscription_info,
} = provider;
let provider_index = views.len();
let mut proxy_record_ids = Vec::new();
for (member_index, proxy) in proxies.into_iter().enumerate() {
let record_id: String = format!("p:{provider_index}:{member_index}").into();
let proxy_name = proxy.name.clone();
let node_name = proxy.name.clone();
candidates
.entry(proxy_name.clone())
.or_insert_with(Vec::new)
.push((provider_name.clone(), record_id.clone()));
records.insert(
record_id.clone(),
build_node(
record_id.clone(),
node_name,
proxy,
ProxyNodeSource::Provider {
provider_name: provider_name.clone(),
proxy_name,
},
),
);
proxy_record_ids.push(record_id);
}
views.push(ProxyProviderView {
name: provider_name,
vehicle_type,
updated_at,
subscription_info,
proxy_record_ids,
});
}
(views, candidates)
}
fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>) -> ProxyGroupView {
let ProxySnapshot {
all,
fixed,
hidden,
icon,
now,
test_url,
history,
capabilities,
proxy_type,
..
} = proxy;
let mut seen = BTreeMap::new();
let members = all
.unwrap_or_default()
.into_iter()
.map(|member| resolver.resolve(&name, member, &mut seen))
.collect();
ProxyGroupView {
name,
proxy_type,
now,
fixed,
hidden,
icon,
test_url,
history,
capabilities,
members,
}
}
fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: ProxyNodeSource) -> ProxyNodeView {
let ProxySnapshot {
id,
hidden,
icon,
test_url,
history,
capabilities,
proxy_type,
..
} = proxy;
ProxyNodeView {
record_id,
name,
proxy_type,
history,
id,
hidden,
icon,
test_url,
capabilities,
source,
}
}
fn build_ordered_groups(
mut core_groups: BTreeMap<String, ProxySnapshot>,
runtime_group_order: Vec<String>,
resolver: &MemberResolver<'_>,
) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) {
let mut groups = Vec::with_capacity(core_groups.len());
for name in runtime_group_order {
if let Some(proxy) = core_groups.remove(&name) {
groups.push(build_group(name, proxy, resolver));
}
}
let order_source = if groups.is_empty() {
ProxyViewOrderSource::Fallback
} else {
ProxyViewOrderSource::Runtime
};
groups.extend(
core_groups
.into_iter()
.map(|(name, proxy)| build_group(name, proxy, resolver)),
);
(groups, order_source)
}
fn build_standalone(core_node_ids: &BTreeMap<String, String>) -> Vec<String> {
let mut standalone = ["DIRECT", "REJECT"]
.into_iter()
.filter_map(|name| core_node_ids.get(name).cloned())
.collect::<Vec<_>>();
standalone.extend(
core_node_ids
.iter()
.filter(|(name, _)| name.as_str() != "DIRECT" && name.as_str() != "REJECT")
.map(|(_, record_id)| record_id.clone()),
);
standalone
}