mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-01 02:20:07 +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:
@@ -326,13 +326,6 @@ where
|
||||
start_sidecar().await
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
enum HandoffOutcome {
|
||||
NotReady,
|
||||
Done,
|
||||
Failed,
|
||||
}
|
||||
|
||||
fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error {
|
||||
let error = match service_rejection {
|
||||
Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
|
||||
@@ -688,11 +681,6 @@ impl CoreManager {
|
||||
return result;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
if matches!(*self.get_running_mode(), RunningMode::Sidecar) {
|
||||
self.spawn_service_handoff_watcher().await;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
@@ -883,167 +871,6 @@ impl CoreManager {
|
||||
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
|
||||
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn spawn_service_handoff_watcher(&self) {
|
||||
use crate::constants::timing;
|
||||
use crate::process::AsyncHandler;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Instant;
|
||||
|
||||
// An accepted Sidecar is the user's decision for this session, not a wait for the Service.
|
||||
let needs_service = Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|
||||
&& !crate::core::runstate::RUN_STATE.state().sidecar_allowed;
|
||||
if !needs_service {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.handoff_watcher_running.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service not ready at startup; sidecar active, watching for handoff"
|
||||
);
|
||||
|
||||
AsyncHandler::spawn(|| async move {
|
||||
let manager = Self::global();
|
||||
let started = Instant::now();
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
let attempts = std::num::NonZeroUsize::MIN.saturating_add(
|
||||
(timing::SERVICE_HANDOFF_WINDOW.as_millis() / timing::SERVICE_HANDOFF_INTERVAL.as_millis()) as usize,
|
||||
);
|
||||
let _ = retry(RetryPolicy::fixed(attempts, std::time::Duration::ZERO), |_| async {
|
||||
if started.elapsed() >= timing::SERVICE_HANDOFF_WINDOW {
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service handoff window elapsed; staying in sidecar mode"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
// The window is checked before waiting, including the final handoff attempt.
|
||||
tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await;
|
||||
if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) {
|
||||
return Ok(());
|
||||
}
|
||||
match manager.try_handoff_sidecar_to_service().await {
|
||||
HandoffOutcome::Done => Ok(()),
|
||||
HandoffOutcome::Failed => {
|
||||
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
|
||||
Ok(())
|
||||
}
|
||||
HandoffOutcome::NotReady => Err(RetryError::Retry(())),
|
||||
}
|
||||
})
|
||||
.await;
|
||||
manager.handoff_watcher_running.store(false, Ordering::Release);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn refresh_service_readiness_for_handoff() -> bool {
|
||||
if SERVICE_MANAGER.confirm_ready().await.is_err() {
|
||||
return false;
|
||||
}
|
||||
crate::core::runstate::RUN_STATE.state().service_usable()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tracing::instrument(skip_all, level = "debug", fields(outcome = tracing::field::Empty))]
|
||||
async fn try_handoff_sidecar_to_service(&self) -> HandoffOutcome {
|
||||
// Before probing: a probe reply records an observation, which clears sidecar_allowed.
|
||||
if crate::core::runstate::RUN_STATE.state().sidecar_allowed {
|
||||
return HandoffOutcome::Done;
|
||||
}
|
||||
if !Self::refresh_service_readiness_for_handoff().await {
|
||||
return HandoffOutcome::NotReady;
|
||||
}
|
||||
|
||||
if !self.try_start_config_update() {
|
||||
return HandoffOutcome::NotReady;
|
||||
}
|
||||
let _config_update = DropGuard::new((), |()| {
|
||||
self.finish_config_update();
|
||||
});
|
||||
|
||||
// Lock order is config then lifecycle.
|
||||
let _life = self.lifecycle_lock.lock().await;
|
||||
|
||||
if !matches!(*self.get_running_mode(), RunningMode::Sidecar)
|
||||
|| !Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|
||||
|| crate::core::runstate::RUN_STATE.state().sidecar_allowed
|
||||
{
|
||||
return HandoffOutcome::Done;
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service became ready; handing off from sidecar to service"
|
||||
);
|
||||
if let Err(error) = self.stop_sidecar_after_proxy_clear().await {
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"failed to clear proxy before sidecar handoff: {error:#}"
|
||||
);
|
||||
return HandoffOutcome::Failed;
|
||||
}
|
||||
|
||||
let service_result = run_ready_core_start_transition(
|
||||
|| self.start_core_by_service(),
|
||||
|| {
|
||||
matches!(*self.get_running_mode(), RunningMode::Service)
|
||||
&& self.current_core_readiness_generation().is_some()
|
||||
},
|
||||
|| self.apply_proxy_after_start(),
|
||||
)
|
||||
.await;
|
||||
let Err(service_error) = service_result else {
|
||||
logging!(info, Type::Core, "handoff to service mode succeeded");
|
||||
return HandoffOutcome::Done;
|
||||
};
|
||||
|
||||
logging!(error, Type::Core, "handoff to service failed: {service_error:#}");
|
||||
if let Err(cleanup_error) = self.controlled_stop_core_inner().await {
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"failed to stop service before sidecar fallback: {cleanup_error:#}"
|
||||
);
|
||||
return HandoffOutcome::Failed;
|
||||
}
|
||||
|
||||
let sidecar_result = run_ready_core_start_transition(
|
||||
|| self.start_core_by_sidecar(),
|
||||
|| {
|
||||
matches!(*self.get_running_mode(), RunningMode::Sidecar)
|
||||
&& self.current_core_readiness_generation().is_some()
|
||||
},
|
||||
|| self.apply_proxy_after_start(),
|
||||
)
|
||||
.await;
|
||||
if let Err(sidecar_error) = sidecar_result {
|
||||
logging!(error, Type::Core, "sidecar fallback failed: {sidecar_error:#}");
|
||||
if let Err(cleanup_error) = self.rollback_failed_sidecar_transition().await {
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"failed to clear proxy before sidecar rollback: {cleanup_error:#}"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"sidecar fallback became ready and restored proxy state"
|
||||
);
|
||||
}
|
||||
HandoffOutcome::Failed
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -4,8 +4,8 @@ mod lifecycle;
|
||||
mod state;
|
||||
|
||||
use anyhow::Result;
|
||||
use arc_swap::{ArcSwap, ArcSwapOption};
|
||||
use clash_verge_logging::{LogRing, Type, logging, logging_error};
|
||||
use arc_swap::ArcSwapOption;
|
||||
use clash_verge_logging::{LogRing, Type, logging};
|
||||
use std::{
|
||||
fmt,
|
||||
sync::{
|
||||
@@ -14,12 +14,9 @@ use std::{
|
||||
},
|
||||
time::Instant,
|
||||
};
|
||||
use tauri_plugin_shell::process::CommandChild;
|
||||
|
||||
use crate::core::runstate::{RUN_STATE, RealEnv, RunStateStore};
|
||||
use crate::singleton;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
|
||||
pub(crate) static CLASH_LOGGER: LazyLock<Arc<LogRing>> = LazyLock::new(|| Arc::new(LogRing::new()));
|
||||
|
||||
@@ -89,46 +86,26 @@ pub struct CoreManager {
|
||||
/// A reference rather than the global directly, so a test can supervise a Core without
|
||||
/// racing every other test for one process-wide Running Mode.
|
||||
run_state: &'static RunStateStore<RealEnv>,
|
||||
state: ArcSwap<State>,
|
||||
sidecar: parking_lot::Mutex<state::SidecarSession>,
|
||||
last_update: ArcSwapOption<Instant>,
|
||||
#[cfg(target_os = "windows")]
|
||||
job_handle: ArcSwapOption<OwnedHandle>,
|
||||
config_update_in_progress: AtomicBool,
|
||||
core_readiness_state: AtomicU64,
|
||||
startup_error: parking_lot::Mutex<Option<CoreFailure>>,
|
||||
sidecar_exit: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
// 串行化 start/stop/restart 和 sidecar→service 交接。
|
||||
// 锁序固定为 config_update_in_progress → lifecycle_lock。
|
||||
pub(crate) lifecycle_lock: tokio::sync::Mutex<()>,
|
||||
// sidecar→service 交接 watcher 单实例标志。
|
||||
#[cfg(target_os = "windows")]
|
||||
handoff_watcher_running: AtomicBool,
|
||||
}
|
||||
|
||||
/// Process-level state owned by `CoreManager`.
|
||||
///
|
||||
/// Running Mode deliberately does *not* live here — it belongs to `core::runstate`, which
|
||||
/// keeps it consistent with Service Health and derives PAC availability from it.
|
||||
#[derive(Debug, Default)]
|
||||
struct State {
|
||||
child_sidecar: ArcSwapOption<CommandChild>,
|
||||
}
|
||||
|
||||
impl Default for CoreManager {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
run_state: &RUN_STATE,
|
||||
state: ArcSwap::new(Arc::new(State::default())),
|
||||
sidecar: parking_lot::Mutex::default(),
|
||||
last_update: ArcSwapOption::new(None),
|
||||
#[cfg(target_os = "windows")]
|
||||
job_handle: ArcSwapOption::new(None),
|
||||
config_update_in_progress: AtomicBool::new(false),
|
||||
core_readiness_state: AtomicU64::new(0),
|
||||
startup_error: parking_lot::Mutex::new(None),
|
||||
sidecar_exit: tokio::sync::Mutex::new(None),
|
||||
lifecycle_lock: tokio::sync::Mutex::new(()),
|
||||
#[cfg(target_os = "windows")]
|
||||
handoff_watcher_running: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,18 +139,6 @@ impl CoreManager {
|
||||
self.startup_error.lock().clone()
|
||||
}
|
||||
|
||||
pub fn take_child_sidecar(&self) -> Option<CommandChild> {
|
||||
self.state
|
||||
.load()
|
||||
.child_sidecar
|
||||
.swap(None)
|
||||
.and_then(|arc| Arc::try_unwrap(arc).ok())
|
||||
}
|
||||
|
||||
pub fn get_running_sidecar_pid(&self) -> Option<u32> {
|
||||
self.state.load().child_sidecar.load_full().map(|child| child.pid())
|
||||
}
|
||||
|
||||
pub fn get_last_update(&self) -> Option<Arc<Instant>> {
|
||||
self.last_update.load_full()
|
||||
}
|
||||
@@ -218,11 +183,6 @@ impl CoreManager {
|
||||
self.run_state.core_start_settled();
|
||||
}
|
||||
|
||||
pub fn set_running_child_sidecar(&self, child: CommandChild) {
|
||||
let state = self.state.load();
|
||||
state.child_sidecar.store(Some(Arc::new(child)));
|
||||
}
|
||||
|
||||
fn mark_core_ready(&self) -> u64 {
|
||||
let mut current = self.core_readiness_state.load(Ordering::Acquire);
|
||||
loop {
|
||||
@@ -257,27 +217,14 @@ impl CoreManager {
|
||||
self.last_update.store(Some(Arc::new(time)));
|
||||
}
|
||||
|
||||
/// Replaces the Windows Job Object handle owned by the core manager
|
||||
///
|
||||
/// Passing `None` drops the current handle, which closes the Job Object
|
||||
/// and terminates its assigned processes due to `KILL_ON_JOB_CLOSE`.
|
||||
///
|
||||
/// This method is currently only used on Windows.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn set_job_handle(&self, handle: Option<OwnedHandle>) {
|
||||
self.job_handle.store(handle.map(Arc::new));
|
||||
}
|
||||
|
||||
pub(crate) fn try_start_config_update(&self) -> bool {
|
||||
!self.config_update_in_progress.swap(true, Ordering::AcqRel)
|
||||
}
|
||||
|
||||
pub(crate) fn finish_config_update(&self) {
|
||||
self.config_update_in_progress.store(false, Ordering::Release);
|
||||
// Spawned because the caller may still hold the config write lock this waits for.
|
||||
crate::process::AsyncHandler::spawn(|| async {
|
||||
logging_error!(Type::Config, crate::config::Config::sync_dns_override().await);
|
||||
});
|
||||
// The caller may still hold the config write lock that synchronization needs.
|
||||
crate::config::Config::request_dns_override_sync();
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(retries = 0))]
|
||||
|
||||
@@ -11,11 +11,18 @@ use crate::{
|
||||
};
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_logging::Type;
|
||||
use futures::{
|
||||
FutureExt as _,
|
||||
future::{Map, Shared},
|
||||
};
|
||||
use log::Level;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tauri_plugin_mihomo::MihomoExt as _;
|
||||
use tauri_plugin_shell::ShellExt as _;
|
||||
use tauri_plugin_shell::process::CommandChild;
|
||||
use tokio::task::{JoinError, JoinHandle};
|
||||
|
||||
pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
|
||||
let detail = error.to_string();
|
||||
@@ -130,8 +137,34 @@ where
|
||||
.context("Mihomo API did not become ready")
|
||||
}
|
||||
|
||||
fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool {
|
||||
matches!(running_mode, RunningMode::Sidecar) && current_pid == Some(terminated_pid)
|
||||
fn should_clear_terminated_sidecar(
|
||||
running_mode: &RunningMode,
|
||||
current_generation: Option<u64>,
|
||||
terminated_generation: u64,
|
||||
) -> bool {
|
||||
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
|
||||
}
|
||||
|
||||
type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc<JoinError>>;
|
||||
type SidecarExit = Shared<Map<JoinHandle<()>, ShareExitResult>>;
|
||||
|
||||
fn share_exit(exit: JoinHandle<()>) -> SidecarExit {
|
||||
let share_error: ShareExitResult = |result| result.map_err(Arc::new);
|
||||
exit.map(share_error).shared()
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct SidecarSession {
|
||||
process: Option<SidecarProcess>,
|
||||
exit: Option<SidecarExit>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SidecarProcess {
|
||||
generation: u64,
|
||||
child: CommandChild,
|
||||
#[cfg(target_os = "windows")]
|
||||
job: OwnedHandle,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -218,7 +251,8 @@ impl CoreManager {
|
||||
)
|
||||
})?;
|
||||
let (terminated, termination) = tokio::sync::oneshot::channel();
|
||||
*self.sidecar_exit.lock().await = Some(execution.release_after_exit(child.pid(), termination));
|
||||
let exit = execution.release_after_exit(child.pid(), termination);
|
||||
self.sidecar.lock().exit = Some(share_exit(exit));
|
||||
#[cfg(target_os = "windows")]
|
||||
let job = {
|
||||
match create_and_assign_sidecar_job(child.pid()) {
|
||||
@@ -274,7 +308,7 @@ impl CoreManager {
|
||||
};
|
||||
Logger::global().writer_sidecar_log(Level::Info, &message);
|
||||
CLASH_LOGGER.clear_logs();
|
||||
manager.clear_terminated_sidecar(pid).await;
|
||||
manager.clear_terminated_sidecar(core_readiness_generation).await;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
@@ -302,9 +336,12 @@ impl CoreManager {
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
self.set_job_handle(Some(job));
|
||||
self.set_running_child_sidecar(child);
|
||||
self.sidecar.lock().process = Some(SidecarProcess {
|
||||
generation: core_readiness_generation,
|
||||
child,
|
||||
#[cfg(target_os = "windows")]
|
||||
job,
|
||||
});
|
||||
self.core_started(RunningMode::Sidecar);
|
||||
self.restore_selected_nodes().await;
|
||||
|
||||
@@ -314,18 +351,13 @@ impl CoreManager {
|
||||
/// Terminates the sidecar after its caller has successfully cleared the
|
||||
/// system proxy.
|
||||
pub(super) async fn stop_core_by_sidecar_unprepared(&self) -> Result<()> {
|
||||
if let Some(child) = self.take_child_sidecar() {
|
||||
let pid = child.pid();
|
||||
|
||||
let process = self.sidecar.lock().process.take();
|
||||
if let Some(process) = process {
|
||||
let pid = process.child.pid();
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// Setting the job handle to None clears the stored handle and
|
||||
// closes the previous Windows job handle in `set_job_handle`.
|
||||
self.set_job_handle(None);
|
||||
let _ = pid;
|
||||
}
|
||||
drop(process.job);
|
||||
|
||||
if let Err(error) = child.kill() {
|
||||
if let Err(error) = process.child.kill() {
|
||||
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
|
||||
}
|
||||
}
|
||||
@@ -335,15 +367,15 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
async fn wait_for_sidecar_exit(&self) -> Result<()> {
|
||||
let mut exit = self.sidecar_exit.lock().await;
|
||||
if let Some(task) = exit.as_mut() {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), task)
|
||||
// The lifecycle lock serializes callers. Keep a receipt in the session across timeouts.
|
||||
let exit = self.sidecar.lock().exit.clone();
|
||||
if let Some(exit) = exit {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), exit)
|
||||
.await
|
||||
.context("Sidecar has not exited; core handoff is blocked")?
|
||||
.context("Sidecar exit monitoring failed")?;
|
||||
exit.take();
|
||||
self.sidecar.lock().exit.take();
|
||||
}
|
||||
drop(exit);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -392,15 +424,17 @@ impl CoreManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn clear_terminated_sidecar(&self, terminated_pid: u32) {
|
||||
async fn clear_terminated_sidecar(&self, terminated_generation: u64) {
|
||||
let _life = self.lifecycle_lock.lock().await;
|
||||
if !should_clear_terminated_sidecar(&self.get_running_mode(), self.get_running_sidecar_pid(), terminated_pid) {
|
||||
return;
|
||||
}
|
||||
|
||||
let _ = self.take_child_sidecar();
|
||||
#[cfg(target_os = "windows")]
|
||||
self.set_job_handle(None);
|
||||
let process = {
|
||||
let mut session = self.sidecar.lock();
|
||||
let current = session.process.as_ref().map(|process| process.generation);
|
||||
if !should_clear_terminated_sidecar(&self.get_running_mode(), current, terminated_generation) {
|
||||
return;
|
||||
}
|
||||
session.process.take()
|
||||
};
|
||||
drop(process);
|
||||
proxy_control::stop_guard().await;
|
||||
self.core_stopped();
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
Reference in New Issue
Block a user