refactor(backend): share single-owner drivers for background tasks (#8759)

* docs(backend): define background task ownership

* refactor(backend): give background operations single task owners

* test(backend): remove actor migration regression cases

* docs(changelog): drop backend actor migration entry

* refactor(backend): extract workspace task drivers

* fix(timer): omit profile identifier from panic log

* docs(backend): define workspace crate boundaries

* refactor(lightweight): use the task countdown driver

* refactor(lightweight): name countdown callbacks

* refactor(task): simplify driver startup and coalescing requests

* refactor(core): bind service handoff to the sidecar generation

* refactor(tun): coalesce background run state reconciliation

* refactor(core): own sidecar exit resources in one session

* refactor(core): remove automatic Windows service handoff

* refactor(task): simplify coalescing job signals

* refactor(runstate): keep operation status with service state

* refactor(dns): coalesce background override synchronization

* refactor(sysproxy): own the local guard under its operation lock

* fix(tray): read menu settings at publication

* fix(dns): retain script lock across caller cancellation

* refactor(profiles): own selected node restoration in one task

* refactor(timer): own subscription schedules in the scheduler

* test(timer): remove the added application test

* fix(service): renew provider sync retry budget on refresh
This commit is contained in:
Tunglies
2026-11-29 00:42:52 +00:00
committed by GitHub
parent 9724aa6d4d
commit 929bb6a0a1
37 changed files with 1671 additions and 1291 deletions
+126 -103
View File
@@ -6,6 +6,7 @@ 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,
@@ -14,27 +15,27 @@ use crate::{
use anyhow::{Context as _, Result, bail};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use futures::FutureExt as _;
use serde::{Deserialize, Serialize};
use serde_yaml_ng::Mapping;
use std::num::NonZeroUsize;
use std::{
collections::{HashMap, HashSet},
panic::AssertUnwindSafe,
path::{Component, Path},
sync::{
LazyLock,
atomic::{AtomicU64, Ordering},
},
sync::OnceLock,
time::{Duration, Instant},
};
use tauri_plugin_mihomo::models::{Proxies, ProxyType};
use tokio::{fs, task::JoinHandle};
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 ACTIVATE_SELECTED_TASK: LazyLock<Mutex<Option<JoinHandle<()>>>> = LazyLock::new(|| Mutex::new(None));
static ACTIVATE_SELECTED_GENERATION: AtomicU64 = AtomicU64::new(0);
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.
@@ -579,11 +580,15 @@ fn reconcile_selected_nodes(
/// Cancels restoration so it cannot overwrite a newer selection or profile snapshot.
pub(crate) fn supersede_selected_activation() {
ACTIVATE_SELECTED_GENERATION.fetch_add(1, Ordering::AcqRel);
if let Some(inbox) = SELECTED_ACTIVATION.get() {
inbox.send_modify(|state| state.replace(None));
}
}
fn is_activation_current(generation: u64) -> bool {
ACTIVATE_SELECTED_GENERATION.load(Ordering::Acquire) == generation
SELECTED_ACTIVATION
.get()
.is_some_and(|inbox| inbox.borrow().generation == generation)
}
async fn fetch_proxies_with_timeout() -> Result<Proxies> {
@@ -641,6 +646,10 @@ fn global_exit_target(proxies: &Proxies) -> Option<&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
@@ -652,7 +661,7 @@ pub(crate) async fn leave_default_global_exit() -> Result<()> {
return Ok(());
}
let snapshot = fetch_proxies_with_timeout().await?;
let Some(target) = global_exit_target(&snapshot) else {
let Some(target) = global_exit_target(&snapshot).filter(|_| is_current()) else {
return Ok(());
};
select_node_with_timeout(&String::from("GLOBAL"), &String::from(target)).await?;
@@ -913,23 +922,11 @@ async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut Has
.await;
}
/// Releases the first-pass waiter even when restoration exits early.
struct FirstPassSignal(Option<tokio::sync::oneshot::Sender<()>>);
impl FirstPassSignal {
fn notify(&mut self) {
if let Some(sender) = self.0.take() {
let _ = sender.send(());
}
}
}
async fn activate_selected_nodes_worker(
profile_uid: String,
selected: Vec<PrfSelected>,
generation: u64,
repair: SelectionRepair,
mut first_pass_done: FirstPassSignal,
request: ActivationRequest,
) -> Result<()> {
let first_snapshot = fetch_proxies_with_timeout().await?;
if !is_activation_current(generation) {
@@ -987,9 +984,9 @@ async fn activate_selected_nodes_worker(
return Ok(());
}
if repair == SelectionRepair::KeepRecords {
if let ActivationRequest::Restore(first_pass) = request {
// Remaining selections depend on provider loading and continue in the background.
first_pass_done.notify();
let _ = first_pass.send(());
settle_pending_selections(&selected, &mut completed_activations, generation).await;
return Ok(());
}
@@ -1007,25 +1004,35 @@ async fn activate_selected_nodes_worker(
Ok(())
}
/// Whether an activation may also prune the records it cannot match.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum SelectionRepair {
enum ActivationRequest {
/// Prune records after a fully loaded profile switch.
Prune,
/// Preserve records during startup while provider-backed groups may still be absent.
KeepRecords,
/// 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() {
// The first-pass signal is for callers that wait; a profile switch does not, and dropping
// the receiver simply makes the send a no-op.
drop(activate_selected_nodes_with(SelectionRepair::Prune));
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 = activate_selected_nodes_with(SelectionRepair::KeepRecords);
if tokio::time::timeout(SELECTED_NODES_FIRST_PASS_BUDGET, first_pass)
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()
{
@@ -1037,63 +1044,82 @@ pub(crate) async fn restore_selected_nodes() {
}
}
fn activate_selected_nodes_with(repair: SelectionRepair) -> tokio::sync::oneshot::Receiver<()> {
fn submit_selected_activation(request: ActivationRequest) {
logging!(debug, Type::Config, "starting activating selected nodes");
let mut active_task = ACTIVATE_SELECTED_TASK.lock();
let generation = ACTIVATE_SELECTED_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;
let previous_task = active_task.take();
let (first_pass_sender, first_pass_done) = tokio::sync::oneshot::channel();
let handle = tokio::spawn(async move {
// Dropping this releases the startup waiter on every early exit.
let first_pass = FirstPassSignal(Some(first_pass_sender));
if let Some(previous_task) = previous_task {
let _ = previous_task.await;
}
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")
&& let Err(err) = leave_default_global_exit().await
{
logging!(warn, Type::Config, "failed to move GLOBAL off its default: {err:#}");
}
if selected.is_empty() {
if is_activation_current(generation) {
announce(Refresh::Clash);
}
return Ok(());
}
activate_selected_nodes_worker(current, selected, generation, repair, first_pass).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!");
}
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
});
*active_task = Some(handle);
drop(active_task);
first_pass_done
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)]
@@ -1331,7 +1357,7 @@ mod tests {
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 `SelectionRepair` exists — the predicate is right, the question is
// 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![]);
@@ -1360,19 +1386,16 @@ mod tests {
}
#[test]
fn superseding_an_activation_makes_the_one_in_flight_stand_down() {
// What a selection made during a start relies on: the restore that is still polling the
// core has to notice it has been overtaken, or it will push the older node back.
let generation = ACTIVATE_SELECTED_GENERATION.load(Ordering::Acquire) + 1;
ACTIVATE_SELECTED_GENERATION.store(generation, Ordering::Release);
assert!(is_activation_current(generation));
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;
supersede_selected_activation();
activation.replace(None);
assert!(
!is_activation_current(generation),
"an activation that has been overtaken must stop before it puts anything"
);
assert_ne!(activation.generation, generation);
assert!(matches!(done.try_recv(), Err(oneshot::error::TryRecvError::Closed)));
}
#[test]