mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-02 19:50:21 +08:00
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:
@@ -6,13 +6,9 @@ use crate::{
|
||||
};
|
||||
use anyhow::Result;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use parking_lot::RwLock;
|
||||
use std::{
|
||||
mem::DropGuard,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
use sysproxy::{Autoproxy, GuardMonitor, GuardType, Sysproxy};
|
||||
@@ -243,18 +239,16 @@ async fn current_os_proxy_state(sys: Sysproxy, auto: Autoproxy) -> OsProxyState
|
||||
pub(crate) struct Sysopt {
|
||||
// Owns the proxy target pair; every reader and writer goes through this lock.
|
||||
proxy_state_lock: TokioMutex<(Sysproxy, Autoproxy)>,
|
||||
guard_operation_lock: TokioMutex<()>,
|
||||
reset_sysproxy: AtomicBool,
|
||||
guard: Arc<RwLock<GuardMonitor>>,
|
||||
guard: TokioMutex<GuardMonitor>,
|
||||
}
|
||||
|
||||
impl Default for Sysopt {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
proxy_state_lock: TokioMutex::new((Sysproxy::default(), Autoproxy::default())),
|
||||
guard_operation_lock: TokioMutex::new(()),
|
||||
reset_sysproxy: AtomicBool::new(false),
|
||||
guard: Arc::new(RwLock::new(GuardMonitor::new(GuardType::None, Duration::from_secs(30)))),
|
||||
guard: TokioMutex::new(GuardMonitor::new(GuardType::None, Duration::from_secs(30))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -295,14 +289,9 @@ impl Sysopt {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn access_guard(&self) -> Arc<RwLock<GuardMonitor>> {
|
||||
Arc::clone(&self.guard)
|
||||
}
|
||||
|
||||
/// Stop the guard and return whether it drained.
|
||||
async fn stop_proxy_guard_locked(&self) -> bool {
|
||||
// Drop the parking_lot read guard before awaiting.
|
||||
let idle = self.access_guard().read().shutdown();
|
||||
async fn drain_guard(guard: &GuardMonitor) -> bool {
|
||||
let idle = guard.shutdown();
|
||||
let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await;
|
||||
if !drained {
|
||||
logging!(
|
||||
@@ -316,23 +305,23 @@ impl Sysopt {
|
||||
|
||||
/// Stop the guard before handing OS proxy ownership elsewhere.
|
||||
pub(super) async fn stop_proxy_guard(&self) -> bool {
|
||||
let _operation = self.guard_operation_lock.lock().await;
|
||||
self.stop_proxy_guard_locked().await
|
||||
let guard = self.guard.lock().await;
|
||||
Self::drain_guard(&guard).await
|
||||
}
|
||||
|
||||
/// Reconcile guard state with configuration and report success.
|
||||
pub(super) async fn refresh_guard(&self) -> bool {
|
||||
logging!(info, Type::Core, "Refreshing system proxy guard...");
|
||||
let verge = Config::verge().await.latest_arc();
|
||||
let _operation = self.guard_operation_lock.lock().await;
|
||||
let mut guard = self.guard.lock().await;
|
||||
if !verge.enable_system_proxy.unwrap_or_default() {
|
||||
logging!(info, Type::Core, "System proxy is disabled.");
|
||||
let _drained = self.stop_proxy_guard_locked().await;
|
||||
let _drained = Self::drain_guard(&guard).await;
|
||||
return true;
|
||||
}
|
||||
if !verge.enable_proxy_guard.unwrap_or_default() {
|
||||
logging!(info, Type::Core, "System proxy guard is disabled.");
|
||||
let _drained = self.stop_proxy_guard_locked().await;
|
||||
let _drained = Self::drain_guard(&guard).await;
|
||||
return true;
|
||||
}
|
||||
logging!(
|
||||
@@ -341,52 +330,27 @@ impl Sysopt {
|
||||
"Updating system proxy with duration: {} seconds",
|
||||
verge.proxy_guard_duration.unwrap_or(30)
|
||||
);
|
||||
{
|
||||
let guard = self.access_guard();
|
||||
guard
|
||||
.write()
|
||||
.set_interval(Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30)));
|
||||
}
|
||||
guard.set_interval(Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30)));
|
||||
logging!(info, Type::Core, "Starting system proxy guard...");
|
||||
{
|
||||
let guard = self.access_guard();
|
||||
if !guard.read().start() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"the system proxy guard refused to start; a previous run has not finished"
|
||||
);
|
||||
}
|
||||
if !guard.start() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"the system proxy guard refused to start; a previous run has not finished"
|
||||
);
|
||||
}
|
||||
while self.access_guard().read().get_state().is_pendding() {
|
||||
while guard.get_state().is_pendding() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
// `start()` false may also mean a guard was already running.
|
||||
!self.access_guard().read().get_state().is_stopped()
|
||||
}
|
||||
|
||||
/// Recover OS and guard state after a failed write.
|
||||
async fn recover_from_failed_write(
|
||||
&self,
|
||||
error: anyhow::Error,
|
||||
earlier_step_completed: bool,
|
||||
guard_was_running: bool,
|
||||
off: (Sysproxy, Autoproxy),
|
||||
) -> anyhow::Error {
|
||||
recover_from_failed_write(
|
||||
error,
|
||||
earlier_step_completed,
|
||||
|state| self.recover_guard_after_failure(state, guard_was_running),
|
||||
|| disable_all_proxies(off.0, off.1),
|
||||
)
|
||||
.await
|
||||
!guard.get_state().is_stopped()
|
||||
}
|
||||
|
||||
/// Reconcile the guard with the authoritative state.
|
||||
fn recover_guard_after_failure(&self, state: AuthoritativeState, was_running: bool) {
|
||||
fn recover_guard_after_failure(guard: &mut GuardMonitor, state: AuthoritativeState, was_running: bool) {
|
||||
match state {
|
||||
AuthoritativeState::Unchanged if was_running => {
|
||||
let restarted = self.access_guard().read().start();
|
||||
let restarted = guard.start();
|
||||
if !restarted {
|
||||
logging!(
|
||||
warn,
|
||||
@@ -397,7 +361,7 @@ impl Sysopt {
|
||||
}
|
||||
AuthoritativeState::Unchanged => {}
|
||||
AuthoritativeState::Unknown => {
|
||||
self.access_guard().write().set_guard_type(GuardType::None);
|
||||
guard.set_guard_type(GuardType::None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -465,11 +429,11 @@ impl Sysopt {
|
||||
(sys.clone(), auto.clone(), guard_type)
|
||||
};
|
||||
|
||||
let _guard_operation = self.guard_operation_lock.lock().await;
|
||||
let mut guard = self.guard.lock().await;
|
||||
|
||||
// Drain the guard before any OS read or write.
|
||||
let guard_was_running = !self.access_guard().read().get_state().is_stopped();
|
||||
let idle = self.access_guard().read().shutdown();
|
||||
let guard_was_running = !guard.get_state().is_stopped();
|
||||
let idle = guard.shutdown();
|
||||
let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await;
|
||||
|
||||
// A slow guard does not stop the write, but it does make the OS read untrustworthy.
|
||||
@@ -477,7 +441,7 @@ impl Sysopt {
|
||||
&& drained
|
||||
&& current_os_proxy_state(sys.clone(), auto.clone()).await == OsProxyState::AlreadyApplied
|
||||
{
|
||||
self.access_guard().write().set_guard_type(guard_type);
|
||||
guard.set_guard_type(guard_type);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -508,24 +472,25 @@ impl Sysopt {
|
||||
})
|
||||
.await;
|
||||
|
||||
match applied {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err((earlier_step_completed, error))) => {
|
||||
return Err(self
|
||||
.recover_from_failed_write(error, earlier_step_completed, guard_was_running, compensation)
|
||||
.await);
|
||||
let (earlier_step_completed, error) = match applied {
|
||||
Ok(Ok(())) => {
|
||||
guard.set_guard_type(guard_type);
|
||||
return Ok(());
|
||||
}
|
||||
Err(join_error) => {
|
||||
let error = anyhow::Error::from(join_error).context("the system proxy write task did not finish");
|
||||
return Err(self
|
||||
.recover_from_failed_write(error, false, guard_was_running, compensation)
|
||||
.await);
|
||||
}
|
||||
}
|
||||
Ok(Err(failure)) => failure,
|
||||
Err(error) => (
|
||||
false,
|
||||
anyhow::Error::from(error).context("the system proxy write task did not finish"),
|
||||
),
|
||||
};
|
||||
|
||||
// Never point the guard at a target that failed to reach the OS.
|
||||
self.access_guard().write().set_guard_type(guard_type);
|
||||
Ok(())
|
||||
Err(recover_from_failed_write(
|
||||
error,
|
||||
earlier_step_completed,
|
||||
|state| Self::recover_guard_after_failure(&mut guard, state, guard_was_running),
|
||||
|| disable_all_proxies(compensation.0, compensation.1),
|
||||
)
|
||||
.await)
|
||||
}
|
||||
|
||||
/// reset the sysproxy
|
||||
@@ -545,8 +510,8 @@ impl Sysopt {
|
||||
self.reset_sysproxy.store(false, Ordering::SeqCst);
|
||||
});
|
||||
let mut proxy_state = self.proxy_state_lock.lock().await;
|
||||
let _guard_operation = self.guard_operation_lock.lock().await;
|
||||
let drained = self.stop_proxy_guard_locked().await;
|
||||
let guard = self.guard.lock().await;
|
||||
let drained = Self::drain_guard(&guard).await;
|
||||
|
||||
// 直接关闭所有代理
|
||||
let (sys, auto) = {
|
||||
@@ -567,7 +532,7 @@ impl Sysopt {
|
||||
disable_until_the_last_write_is_ours(
|
||||
drained,
|
||||
|| disable_all_proxies(sys.clone(), auto.clone()),
|
||||
|| self.stop_proxy_guard_locked(),
|
||||
|| Self::drain_guard(&guard),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user