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
+2 -1
View File
@@ -1,6 +1,6 @@
use crate::{
config::{Config, IClashTemp, IProfiles, IVerge},
core::{CoreManager, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
@@ -58,6 +58,7 @@ async fn finalize_restored_verge_config(
*d = restored.clone();
});
verge_draft.apply();
auto_backup::publish_settings(&verge_draft.data_arc());
// Turn it off here; a failing core side effect below would otherwise skip this step.
if !restored.enable_system_proxy.unwrap_or_default() {
+31 -14
View File
@@ -21,24 +21,38 @@ pub(super) enum Effect {
pub(super) type Effects = BTreeSet<Effect>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum AfterCommit {
BackupSettings,
}
#[derive(Default)]
pub(super) struct EffectPlan {
pub(super) before_commit: Effects,
pub(super) after_commit: BTreeSet<AfterCommit>,
}
macro_rules! select_field {
($effects:ident, $field:ident, NoEffect) => { let _ = $field; };
($effects:ident, $field:ident, [$($effect:ident),*]) => {
if $field.is_some() { $effects.extend([$(Effect::$effect),*]); }
if $field.is_some() { $effects.before_commit.extend([$(Effect::$effect),*]); }
};
($effects:ident, $field:ident, (AfterCommit $effect:ident)) => {
if $field.is_some() { $effects.after_commit.insert(AfterCommit::$effect); }
};
($effects:ident, $field:ident, Tun) => {
select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]);
#[cfg(target_os = "linux")]
if *$field == Some(true) { $effects.insert(Effect::RestartCore); }
if *$field == Some(true) { $effects.before_commit.insert(Effect::RestartCore); }
};
}
macro_rules! verge_registry {
($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => {
pub(super) fn verge_effects(patch: &IVerge) -> Effects {
pub(super) fn verge_effects(patch: &IVerge) -> EffectPlan {
// No rest pattern: even fields omitted by serde must be classified at compile time.
let IVerge { $( $(#[$cfg])* $field, )* } = patch;
let mut effects = Effects::new();
let mut effects = EffectPlan::default();
$( $(#[$cfg])* { select_field!(effects, $field, $rule); } )*
effects
}
@@ -100,9 +114,9 @@ verge_registry! {
proxy_layout_column => NoEffect;
test_list => NoEffect;
auto_log_clean => NoEffect;
enable_auto_backup_schedule => NoEffect;
auto_backup_interval_hours => NoEffect;
auto_backup_on_change => NoEffect;
enable_auto_backup_schedule => (AfterCommit BackupSettings);
auto_backup_interval_hours => (AfterCommit BackupSettings);
auto_backup_on_change => (AfterCommit BackupSettings);
#[cfg(not(target_os = "windows"))]
verge_redir_port => [RestartCore];
#[cfg(not(target_os = "windows"))]
@@ -130,7 +144,7 @@ verge_registry! {
enable_external_controller => [RestartCore];
}
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> EffectPlan {
use clash_verge_logging::{Type, logging};
let mut effects = Effects::new();
for key in patch.keys() {
@@ -157,7 +171,10 @@ pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
if patch.is_empty() {
effects.insert(Effect::ClashConfig);
}
effects
EffectPlan {
before_commit: effects,
..Default::default()
}
}
#[cfg(test)]
@@ -172,7 +189,7 @@ mod tests {
#[test]
fn representative_verge_patches_map_to_frozen_effects() {
assert_eq!(verge_effects(&IVerge::default()), Effects::new());
assert_eq!(verge_effects(&IVerge::default()).before_commit, Effects::new());
let cases: [(IVerge, &[Effect]); 9] = [
(
@@ -216,7 +233,7 @@ mod tests {
];
for (patch, expected) in cases {
assert_eq!(
verge_effects(&patch),
verge_effects(&patch).before_commit,
expected.iter().copied().collect::<Effects>(),
"patch mapping drifted for {expected:?}"
);
@@ -225,7 +242,7 @@ mod tests {
let tun = verge_patch(|p| p.enable_tun_mode = Some(true));
#[cfg(target_os = "linux")]
assert_eq!(
verge_effects(&tun),
verge_effects(&tun).before_commit,
[
Effect::RestartCore,
Effect::ClashConfig,
@@ -238,7 +255,7 @@ mod tests {
);
#[cfg(not(target_os = "linux"))]
assert_eq!(
verge_effects(&tun),
verge_effects(&tun).before_commit,
[
Effect::ClashConfig,
Effect::TrayIcon,
@@ -281,7 +298,7 @@ mod tests {
];
for (patch, expected) in cases {
assert_eq!(
clash_effects(&patch),
clash_effects(&patch).before_commit,
expected.iter().copied().collect::<Effects>(),
"clash mapping drifted for {expected:?}"
);
+10 -6
View File
@@ -1,11 +1,11 @@
use super::effects::{Effect, Effects};
use super::effects::{AfterCommit, Effect, EffectPlan};
use crate::core::notify::{Refresh, announce};
use crate::{
config::{
Config, IVerge,
snapshot::{capture_config_files, restore_files},
},
core::auto_backup::AutoBackupManager,
core::auto_backup,
core::{
CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control,
tray,
@@ -108,7 +108,7 @@ async fn ensure_effect(
Ok(())
}
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: EffectPlan) -> Result<()> {
let manager = CoreManager::global();
let update = manager.claim_config_update(config_write)?;
let clash = Config::clash().await;
@@ -130,7 +130,7 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
Patch::Clash(patch) => clash.edit_draft(|draft| draft.patch_config(patch)),
}
let result: Result<()> = async {
for effect in effects.iter().copied() {
for effect in effects.before_commit.iter().copied() {
let result = Box::pin(ensure_effect(effect, verge_patch, manager, &update)).await;
if matches!(patch, Patch::Clash(_)) && matches!(effect, Effect::TrayMenu | Effect::TrayIcon) {
// Tray failures must not reject an applied Clash mode change.
@@ -166,10 +166,14 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
if patch.auto_check_update == Some(false) {
SilentUpdater::global().discard_pending().await;
}
if effects.contains(&Effect::ClashConfig) {
if effects.before_commit.contains(&Effect::ClashConfig) {
announce(Refresh::Clash);
}
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
for effect in effects.after_commit {
match effect {
AfterCommit::BackupSettings => auto_backup::publish_settings(&verge.data_arc()),
}
}
announce(Refresh::Verge);
}
Patch::Clash(_) => announce(Refresh::Clash),
+20 -2
View File
@@ -4,19 +4,37 @@ use crate::core::notify::NoticeStatus;
use std::{
mem::DropGuard,
sync::atomic::{AtomicBool, Ordering},
sync::{
LazyLock,
atomic::{AtomicBool, Ordering},
},
};
use clash_verge_logging::{Type, logging};
use clash_verge_task::scheduled_task::{self, CoalescingJob};
use crate::{
config::{Config, IVerge},
core::{handle::Handle, manager::RunningMode, runstate::RUN_STATE},
process::AsyncHandler,
};
/// Prevents recursive runtime disable writes.
static DISABLING_TUN: AtomicBool = AtomicBool::new(false);
static TUN_RECONCILE: LazyLock<CoalescingJob> = LazyLock::new(|| {
AsyncHandler::start_driver(scheduled_task::coalescing(reconcile_tun_availability, || {
logging!(error, Type::Core, "TUN reconciliation panicked");
}))
});
pub(crate) fn request_tun_reconciliation() {
// The internal disable can publish Run State as part of its own effects.
if !DISABLING_TUN.load(Ordering::Acquire) {
TUN_RECONCILE.request();
}
}
/// Turn TUN off when startup confirms the Service is absent, so the Core can start on Sidecar.
///
/// Runs before the runtime config is generated.
@@ -61,7 +79,7 @@ pub async fn reconcile_tun_availability() {
return;
}
// The flag coalesces newly spawned tasks while the config lock serializes writers.
// Suppress recursive requests while the config lock serializes writers.
DISABLING_TUN.store(true, Ordering::Release);
let _disabling_tun = DropGuard::new((), |()| {
DISABLING_TUN.store(false, Ordering::Release);
+1 -11
View File
@@ -304,17 +304,7 @@ async fn clean_session_ending_best_effort() -> CleanupResult {
#[cfg(target_os = "macos")]
pub async fn hide() {
use crate::core::lightweight::add_light_weight_timer;
let enable_auto_light_weight_mode = Config::verge()
.await
.data_arc()
.enable_auto_light_weight_mode
.unwrap_or(false);
if enable_auto_light_weight_mode {
add_light_weight_timer().await;
}
crate::core::lightweight::add_light_weight_timer().await;
if let Some(window) = WindowManager::get_main_window()
&& window.is_visible().unwrap_or(false)