Files
clash-verge-rev/src-tauri/src/config/profiles.rs
T
Tunglies e31c01894a 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.
2026-11-30 18:44:12 +08:00

1353 lines
47 KiB
Rust

use super::{PrfItem, PrfOption, PrfSelected, patch_opt_field, prfitem::build_profile};
use crate::core::notify::{Refresh, announce};
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
use crate::{
core::{handle, tray::Tray},
process::AsyncHandler,
utils::{
dirs::{self, PathBufExec as _},
help,
},
};
use anyhow::{Context as _, Result, bail};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging};
pub use clash_verge_profile::{IProfilePreview, IProfiles};
use clash_verge_subscription::normalize_profile_home_url;
use futures::FutureExt as _;
use serde_yaml_ng::Mapping;
use std::num::NonZeroUsize;
use std::{
collections::{HashMap, HashSet},
panic::AssertUnwindSafe,
path::{Component, Path},
sync::OnceLock,
time::{Duration, Instant},
};
use tauri_plugin_mihomo::models::{Proxies, ProxyType};
use tokio::{
fs,
sync::{oneshot, watch},
};
use tristr::alias::String;
pub(crate) static PROFILE_WRITE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
static SELECTED_ACTIVATION: OnceLock<watch::Sender<SelectedActivation>> = OnceLock::new();
// The plugin already limits the request/response phase to 5 seconds. This outer timeout also covers
// lock acquisition, connection-pool waiting, and local-socket connection establishment.
const MIHOMO_OPERATION_TIMEOUT: Duration = Duration::from_secs(10);
const SELECTED_NODES_RECHECK_DELAY: Duration = Duration::from_secs(1);
/// Bounds retries while provider-backed groups finish loading.
const SELECTED_NODES_SETTLE_DEADLINE: Duration = Duration::from_secs(30);
/// How often a restore looks again while waiting for those groups.
const SELECTED_NODES_SETTLE_INTERVAL: Duration = Duration::from_secs(1);
/// Bounds startup waiting; remaining selections continue restoring in the background.
const SELECTED_NODES_FIRST_PASS_BUDGET: Duration = Duration::from_secs(3);
pub(crate) async fn cleanup_profile_files(files: Vec<String>) {
let Ok(dir) = dirs::app_profiles_dir() else {
return;
};
for file in files {
let path = dir.join(file.as_str());
if let Err(error) = path.remove_if_exists().await {
logging!(
warn,
Type::Config,
"Failed to remove deleted profile file {}: {error:#}",
path.display()
);
}
}
}
pub(crate) async fn load_profiles() -> IProfiles {
let path = match dirs::profiles_path() {
Ok(p) => p,
Err(err) => {
logging!(error, Type::Config, "failed to get profiles path: {err:#}");
return IProfiles::default();
}
};
match help::read_yaml::<IProfiles>(&path).await {
Ok(mut profiles) => {
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
for item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d").into());
}
if item.itype.as_deref() == Some("remote") {
item.option
.get_or_insert_with(PrfOption::default)
.allow_auto_update
.get_or_insert(true);
}
if item
.home
.as_deref()
.is_some_and(|home| normalize_profile_home_url(home).is_none())
{
item.home = None;
home_changed = true;
}
}
if home_changed && let Err(err) = save_profiles(&profiles).await {
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
}
profiles
}
Err(err) => {
logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}");
IProfiles::default()
}
}
}
pub(crate) async fn save_profiles(profiles: &IProfiles) -> Result<()> {
help::save_yaml(
&dirs::profiles_path()?,
profiles,
Some("# Profiles Config for Clash Verge"),
)
.await
}
async fn append_item(profiles: &mut IProfiles, item: &mut PrfItem) -> Result<()> {
if item.uid.is_none() {
bail!("the uid should not be null");
}
if let Some(file_data) = item.file_data.take() {
if item.file.is_none() {
bail!("the file should not be null");
}
let file = item
.file
.clone()
.ok_or_else(|| anyhow::anyhow!("file field is required when file_data is provided"))?;
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, file_data.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
}
profiles.append_item(item);
Ok(())
}
async fn patch_item(profiles: &mut IProfiles, uid: &str, item: &PrfItem) -> Result<()> {
if let Some(file) = &item.file {
validate_profile_file(file)?;
}
let mut items = profiles.items.take().unwrap_or_default();
for each in items.iter_mut() {
if each.uid.as_deref() == Some(uid) {
patch_opt_field!(each, item, itype);
patch_opt_field!(each, item, name);
patch_opt_field!(each, item, desc);
patch_opt_field!(each, item, file);
patch_opt_field!(each, item, url);
patch_opt_field!(each, item, selected);
patch_opt_field!(each, item, extra);
patch_opt_field!(each, item, updated);
patch_opt_field!(each, item, option);
profiles.items = Some(items);
return save_profiles(profiles).await;
}
}
profiles.items = Some(items);
bail!("failed to find the profile item \"uid:{uid}\"")
}
fn validate_profile_file(file: &str) -> Result<()> {
let mut components = Path::new(file).components();
if file.is_empty()
|| file.contains('/')
|| file.contains('\\')
|| !matches!(
(components.next(), components.next()),
(Some(Component::Normal(_)), None)
)
{
bail!("profile file must be a single filename");
}
Ok(())
}
/// Updates fields returned by a remote profile refresh.
async fn update_item(profiles: &mut IProfiles, uid: &str, item: &mut PrfItem) -> Result<()> {
if profiles.items.is_none() {
profiles.items = Some(vec![]);
}
let _ = profiles.get_item(uid)?;
if let Some(items) = profiles.items.as_mut() {
for each in items.iter_mut() {
if each.uid.as_deref() == Some(uid) {
each.extra = item.extra;
each.updated = item.updated;
each.home = item.home.to_owned();
each.option = PrfOption::merge(each.option.as_ref(), item.option.as_ref());
if let Some(file_data) = item.file_data.take() {
let file = each.file.take();
let file =
file.unwrap_or_else(|| item.file.take().unwrap_or_else(|| format!("{}.yaml", uid).into()));
each.file = Some(file.clone());
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, file_data.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
}
break;
}
}
}
save_profiles(profiles).await
}
/// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone.
/// Returns how many changed so the caller can skip a pointless write.
pub(crate) fn raise_short_update_intervals(profiles: &mut IProfiles, min_minutes: u64) -> usize {
let mut raised = 0;
for item in profiles.items.iter_mut().flatten() {
let Some(option) = item.option.as_mut() else {
continue;
};
if option
.update_interval
.is_some_and(|interval| (1..min_minutes).contains(&interval))
{
option.update_interval = Some(min_minutes);
raised += 1;
}
}
raised
}
pub(crate) async fn current_mapping(profiles: &IProfiles) -> Result<Mapping> {
match (profiles.current.as_ref(), profiles.items.as_ref()) {
(Some(current), Some(items)) => {
if let Some(item) = items.iter().find(|e| e.uid.as_ref() == Some(current)) {
let file_path = match item.file.as_ref() {
Some(file) => dirs::app_profiles_dir()?.join(file.as_str()),
None => bail!("failed to get the file field"),
};
return help::read_mapping(&file_path).await;
}
bail!("failed to find the current profile \"uid:{current}\"");
}
_ => Ok(Mapping::new()),
}
}
// These helpers serialize asynchronous operations against committed profile data.
use crate::config::Config;
pub(crate) async fn profiles_append_item_with_filedata_safe(item: &PrfItem, file_data: Option<String>) -> Result<()> {
let item = &mut build_profile(item, file_data).await?;
profiles_append_item_safe(item).await
}
/// Applies `edit` to the committed profiles; commits only when the edit succeeds.
async fn with_profiles_edit<F, Fut>(edit: F) -> Result<()>
where
F: FnOnce(IProfiles) -> Fut + Send,
Fut: std::future::Future<Output = Result<IProfiles>> + Send,
{
Config::profiles()
.await
.with_data_modify(|profiles| async move {
let profiles = edit(profiles).await?;
Ok((profiles, ()))
})
.await
}
pub(crate) async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()> {
let profiles = Config::profiles().await;
profiles_append_item_to_safe(&profiles, item).await
}
pub(super) async fn profiles_append_item_to_safe(profiles: &Draft<IProfiles>, item: &mut PrfItem) -> Result<()> {
profiles
.with_data_modify(|mut profiles| async move {
append_item(&mut profiles, item).await?;
Ok((profiles, ()))
})
.await
}
pub(crate) async fn profiles_patch_item_safe(index: &str, item: &PrfItem) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
patch_item(&mut profiles, index, item).await?;
Ok(profiles)
})
.await
}
pub(crate) async fn profiles_reorder_safe(active_id: &str, over_id: &str) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
if profiles.reorder(active_id, over_id) {
save_profiles(&profiles).await?;
}
Ok(profiles)
})
.await
}
pub(crate) async fn profiles_save_file_safe() -> Result<()> {
with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await
}
pub(crate) async fn profiles_update_item_safe(index: &str, item: &mut PrfItem) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
update_item(&mut profiles, index, item).await?;
Ok(profiles)
})
.await
}
#[derive(Debug, PartialEq, Eq)]
struct SelectedNodesPlan {
selected: Vec<PrfSelected>,
activations: Vec<(String, String)>,
repaired_count: usize,
}
fn node_is_available(available_nodes: &[std::string::String], node: &str) -> bool {
available_nodes.iter().any(|available| available == node)
}
fn selected_nodes_need_confirmation(selected: &[PrfSelected], proxies: &Proxies) -> bool {
selected.iter().any(|selected_item| {
let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else {
return false;
};
let Some(group) = proxies.proxies.get(group_name.as_str()) else {
return true;
};
let Some(available_nodes) = group.all.as_deref().filter(|nodes| !nodes.is_empty()) else {
return true;
};
!node_is_available(available_nodes, node)
})
}
fn reconcile_selected_nodes(
selected: &[PrfSelected],
previous: Option<&Proxies>,
proxies: &Proxies,
) -> SelectedNodesPlan {
let mut plan = SelectedNodesPlan {
selected: Vec::with_capacity(selected.len()),
activations: Vec::new(),
repaired_count: 0,
};
let mut seen_groups = HashSet::new();
let mut unique_selected = selected
.iter()
.rev()
.filter(|item| item.name.as_ref().is_some_and(|name| seen_groups.insert(name.clone())))
.collect::<Vec<_>>();
unique_selected.reverse();
plan.repaired_count += selected.len() - unique_selected.len();
for selected_item in unique_selected {
let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else {
plan.repaired_count += 1;
continue;
};
let Some(group) = proxies.proxies.get(group_name.as_str()) else {
if previous.is_some_and(|snapshot| !snapshot.proxies.contains_key(group_name.as_str())) {
plan.repaired_count += 1;
} else {
plan.selected.push(selected_item.clone());
}
continue;
};
let Some(available_nodes) = group.all.as_deref().filter(|nodes| !nodes.is_empty()) else {
// Provider-backed groups can be temporarily incomplete immediately after a reload.
plan.selected.push(selected_item.clone());
continue;
};
let is_selectable_group = matches!(
&group.proxy_type,
ProxyType::Selector | ProxyType::URLTest | ProxyType::Fallback | ProxyType::LoadBalance
);
if !is_selectable_group {
let preferred_node = group
.now
.as_deref()
.filter(|current| node_is_available(available_nodes, current))
.or_else(|| node_is_available(available_nodes, node).then_some(node.as_str()));
if let Some(preferred_node) = preferred_node {
if preferred_node != node.as_str() {
plan.repaired_count += 1;
}
plan.selected.push(PrfSelected {
name: Some(group_name.clone()),
now: Some(preferred_node.into()),
});
} else {
plan.repaired_count += 1;
}
continue;
}
if node_is_available(available_nodes, node) {
plan.selected.push(selected_item.clone());
if group.now.as_deref() != Some(node.as_str()) {
plan.activations.push((group_name.clone(), node.clone()));
}
continue;
}
let missing_was_confirmed = previous
.and_then(|snapshot| snapshot.proxies.get(group_name.as_str()))
.and_then(|group| group.all.as_deref())
.filter(|nodes| !nodes.is_empty())
.is_some_and(|nodes| !node_is_available(nodes, node));
if !missing_was_confirmed {
plan.selected.push(selected_item.clone());
continue;
}
plan.repaired_count += 1;
if let Some(current_node) = group
.now
.as_deref()
.filter(|current| node_is_available(available_nodes, current))
{
plan.selected.push(PrfSelected {
name: Some(group_name.clone()),
now: Some(current_node.into()),
});
}
}
plan
}
/// Cancels restoration so it cannot overwrite a newer selection or profile snapshot.
pub(crate) fn supersede_selected_activation() {
if let Some(inbox) = SELECTED_ACTIVATION.get() {
inbox.send_modify(|state| state.replace(None));
}
}
fn is_activation_current(generation: u64) -> bool {
SELECTED_ACTIVATION
.get()
.is_some_and(|inbox| inbox.borrow().generation == generation)
}
async fn fetch_proxies_with_timeout() -> Result<Proxies> {
let interval = Duration::from_millis(500);
let attempts =
NonZeroUsize::MIN.saturating_add((MIHOMO_OPERATION_TIMEOUT.as_millis() / interval.as_millis()) as usize + 1);
tokio::time::timeout(
MIHOMO_OPERATION_TIMEOUT,
retry(RetryPolicy::fixed(attempts, interval), |_| async {
handle::Handle::mihomo().get_proxies().await.map_err(|error| {
logging!(debug, Type::Config, "mihomo proxies are not ready yet: {error:#}");
RetryError::Retry(error)
})
}),
)
.await
.context("timed out while waiting for mihomo proxies")?
.map_err(Into::into)
}
async fn select_node_with_timeout(group_name: &str, node: &str) -> Result<()> {
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
handle::Handle::mihomo().select_node_for_group(group_name, node).await
})
.await
.with_context(|| format!("timed out while selecting node [{node}] for group [{group_name}]"))?
.with_context(|| format!("failed to select node [{node}] for group [{group_name}]"))
}
// mihomo lists these first in GLOBAL, so an unpicked GLOBAL starts on DIRECT.
const GLOBAL_BUILTINS: [&str; 2] = ["DIRECT", "REJECT"];
/// GLOBAL's first visible group, else its first node, while GLOBAL is still on a built-in.
fn global_exit_target(proxies: &Proxies) -> Option<&str> {
let global = proxies.proxies.get("GLOBAL")?;
if !global.now.as_deref().is_some_and(|now| GLOBAL_BUILTINS.contains(&now)) {
return None;
}
let members = global.all.as_deref()?;
let is_visible_group = |name: &str| {
proxies.proxies.get(name).is_some_and(|proxy| {
proxy.hidden != Some(true)
&& matches!(
proxy.proxy_type,
ProxyType::Selector | ProxyType::URLTest | ProxyType::Fallback | ProxyType::LoadBalance
)
})
};
members
.iter()
.find(|name| is_visible_group(name))
.or_else(|| members.iter().find(|name| !GLOBAL_BUILTINS.contains(&name.as_str())))
.map(|name| name.as_str())
}
/// Moves GLOBAL off a built-in unless the profile records any GLOBAL choice.
pub(crate) async fn leave_default_global_exit() -> Result<()> {
leave_default_global_exit_if(|| true).await
}
async fn leave_default_global_exit_if(is_current: impl FnOnce() -> bool) -> Result<()> {
let profiles = Config::profiles().await.data_arc();
let has_record = profiles
.current
.as_ref()
.and_then(|current| profiles.get_item(current).ok())
.and_then(|item| item.selected.as_deref())
.is_some_and(|selected| selected.iter().any(|item| item.name.as_deref() == Some("GLOBAL")));
if has_record {
return Ok(());
}
let snapshot = fetch_proxies_with_timeout().await?;
let Some(target) = global_exit_target(&snapshot).filter(|_| is_current()) else {
return Ok(());
};
select_node_with_timeout(&String::from("GLOBAL"), &String::from(target)).await?;
logging!(info, Type::Config, "moved GLOBAL off its built-in default to {target}");
Ok(())
}
fn remaining_activations(
activations: &[(String, String)],
completed: &HashMap<String, String>,
) -> Vec<(String, String)> {
activations
.iter()
.filter(|(group_name, node)| completed.get(group_name) != Some(node))
.cloned()
.collect()
}
async fn apply_activations(
activations: &[(String, String)],
completed: &mut HashMap<String, String>,
generation: u64,
) -> Option<usize> {
let mut activated_count = 0;
for (group_name, node) in remaining_activations(activations, completed) {
if !is_activation_current(generation) {
return None;
}
match select_node_with_timeout(&group_name, &node).await {
Ok(()) => {
if !is_activation_current(generation) {
return None;
}
logging!(
info,
Type::Config,
"Selected node for proxy: {group_name}, node: {node}"
);
completed.insert(group_name, node);
activated_count += 1;
}
Err(err) => logging!(error, Type::Config, "{err:#}"),
}
if !is_activation_current(generation) {
return None;
}
}
Some(activated_count)
}
async fn update_tray_after_activation(generation: u64) {
if !is_activation_current(generation) {
return;
}
if let Err(err) = Tray::global().update_tooltip().await {
logging!(
warn,
Type::Config,
"failed to update tray tooltip after profile switch: {err:#}"
);
}
if !is_activation_current(generation) {
return;
}
if let Err(err) = Tray::global().update_menu().await {
logging!(
warn,
Type::Config,
"failed to update tray menu after profile switch: {err:#}"
);
}
}
async fn persist_selected_update<F, Fut>(supersede: bool, edit: F) -> Result<()>
where
F: FnOnce(IProfiles) -> Fut + Send,
Fut: std::future::Future<Output = Result<(IProfiles, bool)>> + Send,
{
let changed = Config::profiles().await.with_data_modify(edit).await?;
if changed {
if supersede {
supersede_selected_activation();
}
announce(Refresh::Profiles);
}
Ok(())
}
fn current_item_mut(profiles: &mut IProfiles) -> Option<&mut PrfItem> {
let current = profiles.current.clone()?;
profiles
.items
.as_mut()?
.iter_mut()
.find(|item| item.uid.as_ref() == Some(&current))
}
/// Records a backend-made selection so the next core start restores it.
pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result<()> {
persist_selected_update(true, move |mut profiles| async move {
let Some(item) = current_item_mut(&mut profiles) else {
return Ok((profiles, false));
};
let selected = item.selected.get_or_insert_with(Vec::new);
match selected
.iter_mut()
.find(|entry| entry.name.as_deref() == Some(group_name))
{
Some(entry) => {
if entry.now.as_deref() == Some(node) {
return Ok((profiles, false));
}
entry.now = Some(node.into());
}
None => selected.push(PrfSelected {
name: Some(group_name.into()),
now: Some(node.into()),
}),
}
save_profiles(&profiles).await?;
Ok((profiles, true))
})
.await
}
fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bool {
let original_len = selected.len();
selected.retain(|entry| entry.name.as_deref() != Some(group_name));
selected.len() != original_len
}
pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
persist_selected_update(true, move |mut profiles| async move {
let Some(item) = current_item_mut(&mut profiles) else {
return Ok((profiles, false));
};
let Some(mut selected) = item.selected.take() else {
return Ok((profiles, false));
};
if !remove_selected_node(&mut selected, group_name) {
item.selected = Some(selected);
return Ok((profiles, false));
}
if !selected.is_empty() {
item.selected = Some(selected);
}
save_profiles(&profiles).await?;
Ok((profiles, true))
})
.await
}
async fn persist_reconciled_selected(
profile_uid: &str,
original_selected: &[PrfSelected],
selected: Vec<PrfSelected>,
generation: u64,
) -> Result<()> {
if !is_activation_current(generation) {
return Ok(());
}
persist_selected_update(false, move |mut profiles| async move {
if !is_activation_current(generation) || profiles.current.as_deref() != Some(profile_uid) {
return Ok((profiles, false));
}
let profile = profiles
.items
.as_mut()
.and_then(|items| items.iter_mut().find(|item| item.uid.as_deref() == Some(profile_uid)))
.with_context(|| format!("failed to find the profile item \"uid:{profile_uid}\""))?;
if profile.selected.as_deref().unwrap_or(&[]) != original_selected {
return Ok((profiles, false));
}
profile.selected = (!selected.is_empty()).then_some(selected);
save_profiles(&profiles).await?;
Ok((profiles, true))
})
.await
}
/// Returns recorded selections whose groups have not reached the requested node.
fn unsettled_selections(selected: &[PrfSelected], proxies: &Proxies) -> Vec<String> {
selected
.iter()
.filter_map(|item| {
let (Some(group_name), Some(node)) = (&item.name, &item.now) else {
return None;
};
match proxies.proxies.get(group_name.as_str()) {
Some(group) if group.now.as_deref() == Some(node.as_str()) => None,
_ => Some(group_name.clone()),
}
})
.collect()
}
/// Retries selections while provider-backed groups finish loading.
async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut HashMap<String, String>, generation: u64) {
let deadline = Instant::now() + SELECTED_NODES_SETTLE_DEADLINE;
let attempts = NonZeroUsize::MIN.saturating_add(
(SELECTED_NODES_SETTLE_DEADLINE.as_millis() / SELECTED_NODES_SETTLE_INTERVAL.as_millis()) as usize,
);
tokio::time::sleep(SELECTED_NODES_SETTLE_INTERVAL).await;
let _ = retry_with_state(
RetryPolicy::fixed(attempts, SELECTED_NODES_SETTLE_INTERVAL),
(selected, completed, generation, deadline),
|state, _| {
Box::pin(async move {
let (selected, completed, generation, deadline) = state;
if !is_activation_current(*generation) {
return Ok(());
}
let Ok(snapshot) = fetch_proxies_with_timeout().await else {
return if Instant::now() >= *deadline {
Ok(())
} else {
Err(RetryError::Retry(()))
};
};
if !is_activation_current(*generation) {
return Ok(());
}
let pending = unsettled_selections(selected, &snapshot);
if pending.is_empty() {
return Ok(());
}
if Instant::now() >= *deadline {
logging!(
warn,
Type::Config,
"gave up putting back {} selected node(s) the core never loaded: {}",
pending.len(),
pending.iter().map(String::as_str).collect::<Vec<_>>().join(", ")
);
return Ok(());
}
let plan = reconcile_selected_nodes(selected, None, &snapshot);
if apply_activations(&plan.activations, completed, *generation)
.await
.is_none()
{
return Ok(());
}
if is_activation_current(*generation) {
announce(Refresh::Clash);
}
Err(RetryError::Retry(()))
})
},
)
.await;
}
async fn activate_selected_nodes_worker(
profile_uid: String,
selected: Vec<PrfSelected>,
generation: u64,
request: ActivationRequest,
) -> Result<()> {
let first_snapshot = fetch_proxies_with_timeout().await?;
if !is_activation_current(generation) {
return Ok(());
}
let needs_confirmation = selected_nodes_need_confirmation(&selected, &first_snapshot);
let immediate_plan = reconcile_selected_nodes(&selected, None, &first_snapshot);
logging!(
debug,
Type::Config,
"immediate selected nodes activation plan: {immediate_plan:?}"
);
let mut completed_activations = HashMap::new();
if apply_activations(&immediate_plan.activations, &mut completed_activations, generation)
.await
.is_none()
{
return Ok(());
}
if is_activation_current(generation) {
announce(Refresh::Clash);
}
let plan = if needs_confirmation {
tokio::time::sleep(SELECTED_NODES_RECHECK_DELAY).await;
if !is_activation_current(generation) {
return Ok(());
}
let second_snapshot = fetch_proxies_with_timeout().await?;
if !is_activation_current(generation) {
return Ok(());
}
let confirmed_plan = reconcile_selected_nodes(&selected, Some(&first_snapshot), &second_snapshot);
logging!(
debug,
Type::Config,
"confirmed selected nodes activation plan: {confirmed_plan:?}"
);
let Some(confirmed_activated_count) =
apply_activations(&confirmed_plan.activations, &mut completed_activations, generation).await
else {
return Ok(());
};
if confirmed_activated_count > 0 && is_activation_current(generation) {
announce(Refresh::Clash);
}
confirmed_plan
} else {
immediate_plan
};
if !is_activation_current(generation) {
return Ok(());
}
if let ActivationRequest::Restore(first_pass) = request {
// Remaining selections depend on provider loading and continue in the background.
let _ = first_pass.send(());
settle_pending_selections(&selected, &mut completed_activations, generation).await;
return Ok(());
}
if plan.repaired_count > 0 && is_activation_current(generation) {
logging!(
info,
Type::Config,
"repairing {} invalid selected node record(s) for profile {profile_uid}",
plan.repaired_count
);
persist_reconciled_selected(&profile_uid, &selected, plan.selected, generation).await?;
}
Ok(())
}
enum ActivationRequest {
/// Prune records after a fully loaded profile switch.
Prune,
/// Preserve records at startup and release the first-pass waiter on early exit.
Restore(oneshot::Sender<()>),
}
#[derive(Default)]
struct SelectedActivation {
generation: u64,
pending: Option<ActivationRequest>,
}
impl SelectedActivation {
fn replace(&mut self, request: Option<ActivationRequest>) {
self.generation = self.generation.wrapping_add(1);
self.pending = request;
}
}
pub(crate) fn activate_selected_nodes() {
submit_selected_activation(ActivationRequest::Prune);
}
/// Restores available selections before the system proxy points at the core, then retries the rest.
pub(crate) async fn restore_selected_nodes() {
let (first_pass, done) = oneshot::channel();
submit_selected_activation(ActivationRequest::Restore(first_pass));
if tokio::time::timeout(SELECTED_NODES_FIRST_PASS_BUDGET, done)
.await
.is_err()
{
logging!(
warn,
Type::Config,
"starting without having put the selected nodes back yet; still trying"
);
}
}
fn submit_selected_activation(request: ActivationRequest) {
logging!(debug, Type::Config, "starting activating selected nodes");
let inbox = SELECTED_ACTIVATION.get_or_init(|| {
let (inbox, changes) = watch::channel(SelectedActivation::default());
let worker_inbox = inbox.clone();
AsyncHandler::spawn(move || run_selected_activation(worker_inbox, changes));
inbox
});
inbox.send_modify(|state| state.replace(Some(request)));
}
async fn run_selected_activation(
inbox: watch::Sender<SelectedActivation>,
mut changes: watch::Receiver<SelectedActivation>,
) {
while changes.changed().await.is_ok() {
let mut activation = None;
inbox.send_if_modified(|state| {
activation = state.pending.take().map(|request| (state.generation, request));
// Taking the request leaves the active generation unchanged.
false
});
if let Some((generation, request)) = activation
&& AssertUnwindSafe(activate_selected_request(generation, request))
.catch_unwind()
.await
.is_err()
{
logging!(error, Type::Config, "selected nodes activation panicked");
}
}
}
async fn activate_selected_request(generation: u64, request: ActivationRequest) {
if !is_activation_current(generation) {
return;
}
let result = async {
// A draft may be a profile switch that has not passed validation yet.
let profiles = Config::profiles().await.data_arc();
let current = profiles.current.clone().context("no current profile running")?;
let selected = profiles
.get_item(&current)
.context("failed to get current profile")?
.selected
.clone()
.unwrap_or_default();
if Config::clash().await.latest_arc().get_mode().as_deref() == Some("global")
&& is_activation_current(generation)
&& let Err(err) = leave_default_global_exit_if(|| is_activation_current(generation)).await
{
logging!(warn, Type::Config, "failed to move GLOBAL off its default: {err:#}");
}
if !is_activation_current(generation) {
return Ok(());
}
if selected.is_empty() {
announce(Refresh::Clash);
return Ok(());
}
activate_selected_nodes_worker(current, selected, generation, request).await
}
.await;
if is_activation_current(generation) {
if let Err(err) = result {
logging!(error, Type::Config, "failed to activate selected nodes: {err:#}");
// The profile itself is already active even if node restoration failed.
announce(Refresh::Clash);
}
update_tray_after_activation(generation).await;
logging!(debug, Type::Config, "activating selected nodes done!");
}
}
#[cfg(test)]
mod tests {
use super::*;
use tauri_plugin_mihomo::models::Proxy;
fn interval_item(uid: &str, update_interval: Option<u64>) -> PrfItem {
PrfItem {
uid: Some(uid.into()),
itype: Some("remote".into()),
option: Some(PrfOption {
update_interval,
..PrfOption::default()
}),
..PrfItem::default()
}
}
#[test]
fn raising_intervals_only_touches_those_scheduled_too_often() {
let mut profiles = IProfiles {
current: None,
items: Some(vec![
interval_item("too-often", Some(60)),
interval_item("just-under", Some(1439)),
interval_item("at-floor", Some(1440)),
interval_item("relaxed", Some(4320)),
// raising these would switch auto-update on
interval_item("disabled-by-zero", Some(0)),
interval_item("disabled-by-absence", None),
PrfItem {
uid: Some("no-option".into()),
option: None,
..PrfItem::default()
},
]),
};
assert_eq!(raise_short_update_intervals(&mut profiles, 1440), 2);
let intervals: Vec<Option<u64>> = profiles
.items
.iter()
.flatten()
.map(|item| item.option.as_ref().and_then(|o| o.update_interval))
.collect();
assert_eq!(
intervals,
vec![Some(1440), Some(1440), Some(1440), Some(4320), Some(0), None, None]
);
assert_eq!(
raise_short_update_intervals(&mut profiles, 1440),
0,
"a second pass must be a no-op, so re-running the migration cannot churn the file"
);
}
fn selected(group: &str, node: &str) -> PrfSelected {
PrfSelected {
name: Some(group.into()),
now: Some(node.into()),
}
}
#[test]
fn removes_only_the_requested_group_selection() {
let mut selections = vec![selected("Proxy", "Node A"), selected("Fallback", "Node B")];
assert!(remove_selected_node(&mut selections, "Proxy"));
assert_eq!(selections, vec![selected("Fallback", "Node B")]);
}
#[test]
fn removing_a_missing_group_is_idempotent() {
let mut selections = vec![selected("Proxy", "Node A")];
assert!(!remove_selected_node(&mut selections, "Missing"));
assert_eq!(selections, vec![selected("Proxy", "Node A")]);
}
fn proxies(groups: Vec<(&str, &[&str], Option<&str>)>) -> Proxies {
Proxies {
proxies: groups
.into_iter()
.map(|(name, all, now)| {
(
name.to_owned(),
Proxy {
name: name.to_owned(),
all: Some(all.iter().map(|node| (*node).to_owned()).collect()),
now: now.map(str::to_owned),
proxy_type: ProxyType::Selector,
..Proxy::default()
},
)
})
.collect::<HashMap<_, _>>(),
}
}
#[test]
fn a_group_the_core_has_not_loaded_is_still_unsettled() {
// The regression this pins. A provider-backed group is present but empty until its
// provider loads, which on a cold start is exactly when restoring runs. Reconciling
// produces no activation for it, so a restore that stopped after one re-check reported
// success having left the group on the first entry of its `proxies:` list.
let saved = vec![selected("provider-group", "saved")];
let unloaded = proxies(vec![("provider-group", &[], None)]);
assert!(
reconcile_selected_nodes(&saved, Some(&unloaded), &unloaded)
.activations
.is_empty(),
"nothing can be activated while the group is empty"
);
assert_eq!(
unsettled_selections(&saved, &unloaded),
vec![String::from("provider-group")],
"so the restore must keep looking rather than call it done"
);
}
#[test]
fn a_group_the_core_is_already_on_is_settled() {
let saved = vec![selected("Proxy", "Node A")];
let loaded = proxies(vec![("Proxy", &["Node A", "Node B"], Some("Node A"))]);
assert!(
unsettled_selections(&saved, &loaded).is_empty(),
"a group already on its node needs nothing, even though it produces no activation"
);
}
#[test]
fn a_group_on_the_wrong_node_is_unsettled() {
// Covers a `select` that failed transiently: the group is loaded, the node exists, and
// the core is simply not on it. Retrying is the only thing that fixes that.
let saved = vec![selected("Proxy", "Node A")];
let wrong = proxies(vec![("Proxy", &["Node A", "Node B"], Some("Node B"))]);
assert_eq!(unsettled_selections(&saved, &wrong), vec![String::from("Proxy")]);
}
#[test]
fn a_record_without_a_group_or_node_is_not_waited_on() {
// A malformed record cannot be satisfied by waiting, and holding the settle loop open
// for it would delay giving up on everything else.
let malformed = vec![
PrfSelected {
name: Some("Proxy".into()),
now: None,
},
PrfSelected {
name: None,
now: Some("Node A".into()),
},
];
assert!(unsettled_selections(&malformed, &proxies(vec![])).is_empty());
}
#[test]
fn a_group_missing_from_both_snapshots_is_dropped_from_the_records() {
// This is the pruning a profile switch wants and a core start must not do: the record is
// gone from the plan, and `persist_reconciled_selected` writes the plan back. Pinned here
// because it is why `ActivationRequest` distinguishes these cases — the predicate is right, the question is
// only who is entitled to act on it.
let saved = vec![selected("provider-group", "saved")];
let empty = proxies(vec![]);
let plan = reconcile_selected_nodes(&saved, Some(&empty), &empty);
assert!(
plan.selected.is_empty(),
"a group absent from both looks invalid, so the record is dropped"
);
assert_eq!(plan.repaired_count, 1, "and dropping it counts as a repair");
}
#[test]
fn a_group_missing_from_only_the_second_snapshot_is_kept() {
// Absent once is not evidence: only a group that was already absent when the first
// snapshot was taken is treated as gone.
let saved = vec![selected("provider-group", "saved")];
let had_it = proxies(vec![("provider-group", &["saved"], Some("saved"))]);
let lost_it = proxies(vec![]);
let plan = reconcile_selected_nodes(&saved, Some(&had_it), &lost_it);
assert_eq!(plan.selected, saved);
assert_eq!(plan.repaired_count, 0);
}
#[test]
fn replacement_releases_a_pending_first_pass_and_invalidates_its_generation() {
let mut activation = SelectedActivation::default();
let (first_pass, mut done) = oneshot::channel();
activation.replace(Some(ActivationRequest::Restore(first_pass)));
let generation = activation.generation;
activation.replace(None);
assert_ne!(activation.generation, generation);
assert!(matches!(done.try_recv(), Err(oneshot::error::TryRecvError::Closed)));
}
#[test]
fn keeps_valid_selection_and_activates_when_needed() {
let saved = vec![selected("group", "saved")];
let plan = reconcile_selected_nodes(
&saved,
None,
&proxies(vec![("group", &["current", "saved"], Some("current"))]),
);
assert_eq!(plan.selected, saved);
assert_eq!(plan.activations, vec![("group".into(), "saved".into())]);
assert_eq!(plan.repaired_count, 0);
}
#[test]
fn replaces_missing_node_with_valid_current_node() {
let snapshot = proxies(vec![("group", &["current"], Some("current"))]);
let plan = reconcile_selected_nodes(&[selected("group", "renamed-node")], Some(&snapshot), &snapshot);
assert_eq!(plan.selected, vec![selected("group", "current")]);
assert!(plan.activations.is_empty());
assert_eq!(plan.repaired_count, 1);
}
#[test]
fn validates_membership_in_group_not_global_existence() {
let snapshot = proxies(vec![
("group", &["current"], Some("current")),
("other-node", &[], None),
]);
let plan = reconcile_selected_nodes(&[selected("group", "other-node")], Some(&snapshot), &snapshot);
assert_eq!(plan.selected, vec![selected("group", "current")]);
assert!(plan.activations.is_empty());
assert_eq!(plan.repaired_count, 1);
}
#[test]
fn does_not_activate_non_selectable_groups() {
let snapshot = Proxies {
proxies: HashMap::from([(
"group".to_owned(),
Proxy {
name: "group".to_owned(),
all: Some(vec!["current".to_owned(), "saved".to_owned()]),
now: Some("current".to_owned()),
proxy_type: ProxyType::Direct,
..Proxy::default()
},
)]),
};
let plan = reconcile_selected_nodes(&[selected("group", "saved")], None, &snapshot);
assert_eq!(plan.selected, vec![selected("group", "current")]);
assert!(plan.activations.is_empty());
assert_eq!(plan.repaired_count, 1);
}
#[test]
fn removes_selection_when_group_or_fallback_is_invalid() {
let snapshot = proxies(vec![("group", &["valid"], Some("invalid-current"))]);
let plan = reconcile_selected_nodes(
&[
selected("missing-group", "node"),
selected("group", "missing-node"),
PrfSelected::default(),
],
Some(&snapshot),
&snapshot,
);
assert!(plan.selected.is_empty());
assert!(plan.activations.is_empty());
assert_eq!(plan.repaired_count, 3);
}
#[test]
fn preserves_selection_until_missing_node_is_confirmed() {
let saved = vec![selected("group", "saved")];
let incomplete = proxies(vec![("group", &[], None)]);
let complete = proxies(vec![("group", &["current"], Some("current"))]);
let incomplete_plan = reconcile_selected_nodes(&saved, None, &incomplete);
let one_snapshot_plan = reconcile_selected_nodes(&saved, None, &complete);
assert_eq!(incomplete_plan.selected, saved);
assert_eq!(incomplete_plan.repaired_count, 0);
assert_eq!(one_snapshot_plan.selected, saved);
assert_eq!(one_snapshot_plan.repaired_count, 0);
}
#[test]
fn recovers_when_group_appears_in_second_snapshot() {
let saved = vec![selected("group", "saved")];
let incomplete = Proxies::default();
let complete = proxies(vec![("group", &["current", "saved"], Some("current"))]);
let plan = reconcile_selected_nodes(&saved, Some(&incomplete), &complete);
assert_eq!(plan.selected, saved);
assert_eq!(plan.activations, vec![("group".into(), "saved".into())]);
assert_eq!(plan.repaired_count, 0);
}
#[test]
fn keeps_last_selection_for_duplicate_group_entries() {
let saved = vec![selected("group", "old"), selected("group", "new")];
let snapshot = proxies(vec![("group", &["old", "new"], Some("old"))]);
let plan = reconcile_selected_nodes(&saved, None, &snapshot);
assert_eq!(plan.selected, vec![selected("group", "new")]);
assert_eq!(plan.activations, vec![("group".into(), "new".into())]);
assert_eq!(plan.repaired_count, 1);
}
#[test]
fn activates_valid_nodes_before_confirming_invalid_records() {
let saved = vec![selected("valid-group", "saved"), selected("stale-group", "missing")];
let first_snapshot = proxies(vec![
("valid-group", &["current", "saved"], Some("current")),
("stale-group", &["fallback"], Some("fallback")),
]);
assert!(selected_nodes_need_confirmation(&saved, &first_snapshot));
let immediate_plan = reconcile_selected_nodes(&saved, None, &first_snapshot);
assert_eq!(immediate_plan.selected, saved);
assert_eq!(immediate_plan.activations, vec![("valid-group".into(), "saved".into())]);
assert_eq!(immediate_plan.repaired_count, 0);
}
#[test]
fn skips_only_activations_that_already_succeeded() {
let activations = vec![
("first-group".into(), "saved".into()),
("second-group".into(), "new".into()),
("first-group".into(), "replacement".into()),
];
let completed = HashMap::from([("first-group".into(), "saved".into())]);
assert_eq!(
remaining_activations(&activations, &completed),
vec![
("second-group".into(), "new".into()),
("first-group".into(), "replacement".into()),
]
);
}
}