chore: trim excessive comments

This commit is contained in:
wonfen
2026-08-19 07:27:43 +08:00
parent 42b91b6294
commit 807f9a206d
103 changed files with 293 additions and 2517 deletions
+20 -94
View File
@@ -22,36 +22,23 @@ use std::{
};
use tauri_plugin_mihomo::Error as MihomoError;
/// What came back from asking the Service to stage a runtime.
///
/// Separated from the decision below so the decision stays a pure function of it. The variants are
/// the four ways an attempt can end, and what distinguishes them is how much they let us conclude:
/// a refusal is the Service's verdict on this bundle, while silence says nothing at all.
/// A staging result separated from the policy that acts on it.
#[derive(Debug, Clone, PartialEq, Eq)]
enum StageAttempt {
/// The Service that owns the running Core predates staging.
Unsupported,
/// The Service answered, and its answer was a refusal about the bundle itself — the kind a
/// fresh start would run into again, because it would materialise the same bundle.
/// Restarting would present the same rejected bundle.
RefusedTheBundle(String),
/// The Service answered with a refusal about something other than the bundle: the session, the
/// protocol, the request. Starting is how several of those get resolved, so it is not a reason
/// to leave the Core where it is.
/// A new service session may resolve this refusal.
RefusedForAnotherReason(String),
/// The request did not come back. The Service is authoritative about its own runtime, so
/// without an answer nothing may be assumed about what it did or did not write.
/// The service may have staged the bundle without delivering its reply.
Unanswered(String),
Answered(StageRuntimeOutcome),
}
/// How the Core should be made to pick up a configuration.
#[derive(Debug, PartialEq, Eq)]
enum ConfigApplication {
/// Point the running Core at this path.
ReloadFrom(String),
/// Stop the Core and start it again from a freshly materialised runtime.
ReplaceCore,
/// Leave the Core alone and report why the configuration cannot be applied.
Fail(String),
}
@@ -63,21 +50,8 @@ impl Drop for ConfigUpdateGuard<'_> {
}
}
/// Decide how to apply a configuration, given how staging went.
///
/// Two branches avoid replacing the Core, for opposite reasons. One is success. The other is a
/// refusal *about the bundle*: the Service inspected it and would not take it, and a fresh start
/// materialises the same bundle — so it would fail the same way, having stopped a Core that was
/// working.
///
/// The distinction matters more than it looks. A refusal about the session is not a refusal about
/// the bundle: starting proposes a new session rather than presenting the old one, and the restart
/// path is also what notices that ownership was lost and clears the system proxy. Treating every
/// non-zero code alike would skip that.
///
/// Everything else — an older Service, a request that never came back, or a Service that asked to
/// be restarted — replaces the Core, which is what this did before staging existed and what the
/// Service guarantees is still safe after every way of declining.
/// Avoids replacing a working core only when the service staged successfully or rejected the
/// bundle itself; session-level failures may be repaired by replacement.
fn plan_config_application(attempt: &StageAttempt) -> ConfigApplication {
match attempt {
StageAttempt::Answered(StageRuntimeOutcome::Staged { config_path }) => {
@@ -112,7 +86,6 @@ fn plan_config_application(attempt: &StageAttempt) -> ConfigApplication {
}
}
/// One round trip to the Service, classified but not judged.
async fn ask_to_stage(path: &std::path::Path) -> StageAttempt {
match crate::core::service::stage_runtime_by_service(path).await {
Ok(StageRequest::Answered(outcome)) => StageAttempt::Answered(outcome),
@@ -128,21 +101,8 @@ async fn ask_to_stage(path: &std::path::Path) -> StageAttempt {
}
}
/// Ask once, and ask again only when the first attempt came back silent.
///
/// Silence is the one answer that has to be resolved rather than acted on. The Service commits the
/// generation before it replies, so a reply that never arrives can leave `config.yaml` already
/// replaced while this side concludes nothing happened — and the Service restarts a Core that dies
/// later from exactly that file. Treating silence as "nothing happened" is therefore a guess, and
/// the expensive half of it is silent: the Core keeps running the previous configuration until
/// something restarts it, and then it does not.
///
/// Asking again is cheap precisely where it matters. Staging plans against the manifest it wrote,
/// so a bundle that already landed copies nothing and answers in milliseconds; and because the
/// Service holds its lifecycle lock for the whole operation, a second ask that overtakes a first
/// one still in flight waits for it rather than interleaving with it. `confirm_within` is what
/// keeps that wait from being the caller's problem — past it, the answer has stopped being worth
/// more than the fallback, which is where a second silence goes anyway.
/// Confirms one silent request because the service may commit before its reply is lost.
/// Re-staging an already committed bundle is idempotent and bounded by `confirm_within`.
async fn stage_with_confirmation<Ask, Fut>(confirm_within: Duration, ask: Ask) -> StageAttempt
where
Ask: Fn() -> Fut,
@@ -326,10 +286,7 @@ impl CoreManager {
self.validate_and_apply(transaction).await
}
/// Validate the staged Runtime Config and hand it to the Core, committing only if both work.
///
/// Takes the transaction rather than opening one, so it covers the staging its callers did.
/// Every way out of here other than the last line rolls that staging back.
/// Validates and applies the caller's transaction, committing only on success.
async fn validate_and_apply(&self, transaction: DraftTransaction<'_>) -> Result<ValidationOutcome> {
let outcome = CoreConfigValidator::global().validate_config_outcome().await?;
if !outcome.is_valid() {
@@ -342,15 +299,7 @@ impl CoreManager {
Ok(ValidationOutcome::Valid)
}
/// Hand the generated configuration to the Core.
///
/// Says nothing about drafts: whether the staged Runtime Config is kept follows from
/// whether this succeeded, and the caller's transaction decides that.
///
/// Both modes have the same shape — put the configuration where the Core can read it, ask the
/// Core to reload, restart it if that did not work. Only the first step differs: in Sidecar
/// mode the Core already reads the app's own directory, while in Service mode the Service has
/// to materialise the configuration into the directory it started the Core in.
/// Applies a generated configuration through the active core owner.
async fn apply_config(&self, path: PathBuf) -> Result<()> {
if matches!(*self.get_running_mode(), RunningMode::Service) {
let _lifecycle = self.lifecycle_lock.lock().await;
@@ -364,18 +313,12 @@ impl CoreManager {
self.reload_or_restart(path).await
}
/// Apply a configuration in Service mode, staging it in place when that is possible.
///
/// Every way of not staging leads to the same place it always led: stop the Core and start it
/// again from a freshly materialised runtime. That is what makes declining safe — the Service
/// leaves the runtime it could not stage exactly as the running Core left it.
///
/// Applies through the service, replacing the core when in-place staging is unavailable.
/// Caller must hold `lifecycle_lock`.
async fn apply_config_by_service(&self, path: &std::path::Path) -> Result<()> {
match plan_config_application(&self.attempt_staging(path).await) {
ConfigApplication::Fail(message) => {
// The Service looked at this bundle and would not take it. Replacing the Core would
// hand it the same bundle, so the outage would buy nothing.
// Replacement would hand the service the same rejected bundle.
logging!(
warn,
Type::Core,
@@ -402,7 +345,6 @@ impl CoreManager {
Ok(())
}
/// Ask the Service to stage the runtime, reporting the attempt rather than judging it.
async fn attempt_staging(&self, path: &std::path::Path) -> StageAttempt {
if !crate::core::service::active_service_supports_runtime_staging() {
return StageAttempt::Unsupported;
@@ -466,12 +408,7 @@ mod tests {
);
}
/// Wrap a rejection as the answer the Service would have sent.
///
/// The `match` is the point, not the wrapping: it is exhaustive, so a new way for the Service
/// to decline cannot be added upstream without this failing to compile — which is what sends
/// whoever adds it to the test below to say what it should lead to. `CoreRestarted` reached
/// production without one, and inherited its verdict silently.
/// Exhaustively maps every service rejection into the policy under test.
fn declined(reason: StageRejection) -> StageAttempt {
match &reason {
StageRejection::CoreNotRunning
@@ -490,9 +427,7 @@ mod tests {
StageRejection::RuntimeUnwritable {
detail: "held open".to_owned(),
},
// The service's own watchdog can restart the core mid-staging, which leaves the
// generation holding a mixture no manifest describes. Rebuilding it from nothing is
// the only answer that does not guess at what is in there.
// A watchdog restart mid-staging can leave a generation that no manifest describes.
StageRejection::CoreRestarted,
] {
assert_eq!(
@@ -514,9 +449,7 @@ mod tests {
#[test]
fn a_refusal_about_the_bundle_leaves_the_core_alone() {
// Replacing the core would materialise the same bundle the Service just rejected, so the
// outage buys nothing: the configuration update fails either way, and this way the user's
// proxy is still working when it does.
// Keep the working core when replacement would present the same rejected bundle.
assert_eq!(
plan_config_application(&StageAttempt::RefusedTheBundle("runtime asset is unavailable".into())),
ConfigApplication::Fail("runtime asset is unavailable".into())
@@ -525,9 +458,7 @@ mod tests {
#[test]
fn a_refusal_about_anything_else_still_replaces_the_core() {
// A stale session is the case that matters: starting proposes a new one, so it is the cure
// rather than a repeat of the failure — and the restart path is also what notices ownership
// was lost and clears the system proxy.
// A new session can repair stale ownership and clear the inherited system proxy.
assert_eq!(
plan_config_application(&StageAttempt::RefusedForAnotherReason("owner session is stale".into())),
ConfigApplication::ReplaceCore
@@ -559,8 +490,7 @@ mod tests {
#[test]
fn a_request_that_never_came_back_makes_the_core_be_replaced() {
// Not knowing what the service did is the one case where reloading would be a guess: the
// staged path might not exist, or might hold the previous configuration.
// Silence gives no trustworthy path to reload.
assert_eq!(
plan_config_application(&StageAttempt::Unanswered("connection reset".into())),
ConfigApplication::ReplaceCore
@@ -569,8 +499,7 @@ mod tests {
#[tokio::test]
async fn an_answer_is_taken_at_its_word_and_not_asked_for_twice() {
// Staging is only idempotent in what it writes, not in what it costs: a second ask after a
// perfectly good answer would re-send the whole bundle for nothing.
// Do not pay for a confirmation after a conclusive answer.
for answer in [
staged(),
StageAttempt::Answered(StageRuntimeOutcome::RestartRequired {
@@ -593,9 +522,7 @@ mod tests {
#[tokio::test]
async fn silence_is_resolved_by_asking_again_rather_than_assumed() {
// The case this exists for: the service committed the generation and the reply was lost.
// Asking again reaches a service that has already done the work, so the second answer is
// the truth the first one failed to deliver — and it keeps the core off the replace path.
// Confirm a committed generation whose first reply was lost.
let asks = Cell::new(0);
let outcome = stage_with_confirmation(CONFIRM_WITHIN, || {
asks.set(asks.get() + 1);
@@ -639,8 +566,7 @@ mod tests {
#[tokio::test(start_paused = true)]
async fn a_second_ask_that_keeps_working_is_not_waited_out() {
// A service still copying assets is why the deadline exists: the answer would be worth
// having, but not at the cost of leaving the user's configuration unapplied indefinitely.
// Do not wait indefinitely for a service still copying assets.
let asks = Cell::new(0);
let started = tokio::time::Instant::now();
let outcome = stage_with_confirmation(CONFIRM_WITHIN, || async {
+2 -33
View File
@@ -24,15 +24,12 @@ enum StartupDecision {
Wait,
}
/// Proxy action captured before a controlled stop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ProxyStopIntent {
Clear,
/// Let the service overwrite the inherited proxy state.
HandOverToService,
}
/// Select whether a controlled stop clears or hands over proxy state.
const fn proxy_stop_intent(is_macos: bool, running_mode: RunningMode, decision: StartupDecision) -> ProxyStopIntent {
match (is_macos, running_mode, decision) {
(true, RunningMode::Sidecar, StartupDecision::Service) => ProxyStopIntent::HandOverToService,
@@ -280,14 +277,10 @@ where
start_sidecar().await
}
/// sidecar→service 交接结果
#[cfg(target_os = "windows")]
enum HandoffOutcome {
/// 服务尚未就绪
NotReady,
/// 已完成或无需交接
Done,
/// 交接失败并已回退
Failed,
}
@@ -408,7 +401,6 @@ impl CoreManager {
run_sidecar_termination_transition(proxy_control::clear, || self.stop_core_by_sidecar_unprepared()).await
}
/// Replaces a Service-owned core while the caller holds `lifecycle_lock`.
pub(super) async fn replace_service_core_with_config(&self, config_file: &Path) -> Result<()> {
run_service_config_replacement_transition(
cfg!(target_os = "macos"),
@@ -457,14 +449,11 @@ impl CoreManager {
Ok(())
}
/// 调用者须已持有 `lifecycle_lock`。
async fn start_core_inner(&self) -> Result<()> {
// 退出中不再启动新内核。
if Handle::global().is_exiting() {
return Ok(());
}
// 已有内核运行时保持幂等,重启请走 restart_core。
if !matches!(*self.get_running_mode(), RunningMode::NotRunning) {
logging!(
info,
@@ -479,7 +468,6 @@ impl CoreManager {
self.rollback_failed_start().await;
return Ok(());
}
// 等待服务期间可能进入退出;未真正启动时回滚状态。
if Handle::global().is_exiting() {
self.core_stopped();
return Ok(());
@@ -491,15 +479,12 @@ impl CoreManager {
StartupDecision::Wait => Ok(()),
};
// No startup failure may leave a locally reported running mode. PAC is
// still fail-closed, and any service owner monitor will exit after this
// transition instead of treating an unconfirmed core as running.
// A failed start must not leave a locally reported running mode.
if result.is_err() {
self.rollback_failed_start().await;
return result;
}
// 回退 sidecar 后,后台等待服务就绪再交接
#[cfg(target_os = "windows")]
if matches!(*self.get_running_mode(), RunningMode::Sidecar) {
self.spawn_service_handoff_watcher().await;
@@ -513,12 +498,10 @@ impl CoreManager {
self.controlled_stop_core_inner().await
}
/// 调用者须已持有 `lifecycle_lock`。
pub(crate) async fn controlled_stop_core_inner(&self) -> Result<()> {
self.controlled_stop_core_with_intent(ProxyStopIntent::Clear).await
}
/// 调用者须已持有 `lifecycle_lock`。
async fn controlled_stop_core_with_intent(&self, proxy_intent: ProxyStopIntent) -> Result<()> {
let running_mode = *self.get_running_mode();
run_controlled_stop_transition(
@@ -532,7 +515,6 @@ impl CoreManager {
.await
}
/// Capture handoff intent before stopping; startup state may change afterward.
async fn proxy_stop_intent(&self) -> ProxyStopIntent {
let running_mode = *self.get_running_mode();
if !cfg!(target_os = "macos") || !matches!(running_mode, RunningMode::Sidecar) {
@@ -541,7 +523,6 @@ impl CoreManager {
proxy_stop_intent(cfg!(target_os = "macos"), running_mode, self.prepare_startup().await)
}
/// 调用者须已持有 `lifecycle_lock`,且已完成受控代理清理。
async fn stop_core_unprepared_inner(&self) -> Result<()> {
CLASH_LOGGER.clear_logs().await;
match *self.get_running_mode() {
@@ -565,7 +546,6 @@ impl CoreManager {
}
pub(crate) async fn restart_core_during_config_update(&self) -> Result<()> {
// 持锁覆盖 stop+start,避免生命周期操作插入。
let _life = self.lifecycle_lock.lock().await;
logging!(info, Type::Core, "Restarting core");
let proxy_intent = self.proxy_stop_intent().await;
@@ -583,7 +563,6 @@ impl CoreManager {
.await
}
/// Switch the core binary and reload configuration.
pub async fn change_core(&self, clash_core: &String) -> Result<()> {
if !IVerge::VALID_CLASH_CORES.contains(&clash_core.as_str()) {
anyhow::bail!("invalid clash core: {clash_core}");
@@ -644,7 +623,6 @@ impl CoreManager {
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
}
/// 在窗口内等待服务就绪,再从 sidecar 交接到 service
#[cfg(target_os = "windows")]
async fn spawn_service_handoff_watcher(&self) {
use crate::constants::timing;
@@ -652,14 +630,12 @@ impl CoreManager {
use std::sync::atomic::Ordering;
use std::time::Instant;
// 仅 TUN 模式需要服务交接
let needs_service = Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
&& !Config::tun_suppressed_for_session();
if !needs_service {
return;
}
// 单实例,避免并发交接
if self.handoff_watcher_running.swap(true, Ordering::AcqRel) {
return;
}
@@ -684,14 +660,11 @@ impl CoreManager {
}
tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await;
// 模式已变更时退出
if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) {
break;
}
match manager.try_handoff_sidecar_to_service().await {
// 已交接或无需交接
HandoffOutcome::Done => break,
// 已回退 sidecar,停止重试
HandoffOutcome::Failed => {
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
break;
@@ -705,21 +678,18 @@ impl CoreManager {
#[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()
}
/// 服务就绪后停止 sidecar,再以 service 重启内核
#[cfg(target_os = "windows")]
async fn try_handoff_sidecar_to_service(&self) -> HandoffOutcome {
if !Self::refresh_service_readiness_for_handoff().await {
return HandoffOutcome::NotReady;
}
// 先抢 config 锁;失败则让位给正在进行的更新。
if !self.try_start_config_update() {
return HandoffOutcome::NotReady;
}
@@ -727,10 +697,9 @@ impl CoreManager {
self.finish_config_update();
}
// 再取 lifecycle 锁;锁序固定为 config→lifecycle。
// Lock order is config then lifecycle.
let _life = self.lifecycle_lock.lock().await;
// 持锁后复检运行模式和 TUN 状态
if !matches!(*self.get_running_mode(), RunningMode::Sidecar)
|| !Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|| Config::tun_suppressed_for_session()
+4 -25
View File
@@ -20,22 +20,8 @@ use tauri_plugin_shell::ShellExt as _;
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
impl CoreManager {
/// A core process is up: put back the node selections the user made.
///
/// mihomo restores these itself, from the `cache.db` it keeps in the directory it was started
/// against — but only when `profile.store-selected` is on and that file survived, and neither
/// is something the app can assume. The setting comes from a merge template a user is free to
/// replace, and a service older than the durable runtime generation hands every start a
/// directory nothing has ever run in. The app holds the same selections in the profile, so it
/// is the one that can say for certain.
///
/// Awaited, and deliberately here rather than beside the proxy: the caller enables the system
/// proxy as soon as the start returns, and pointing it at a core still on the first entry of
/// every group is what this exists to prevent. The wait is bounded — what cannot be put back
/// yet keeps being retried in the background — so a core that will not answer delays a start
/// instead of blocking it.
///
/// Repeat calls supersede each other, so every start path may call this without coordinating.
/// Restores profile selections before callers enable the system proxy.
/// The bounded first pass continues in the background, and later calls supersede earlier ones.
async fn restore_selected_nodes(&self) {
if PROFILE_SELECTIONS_PENDING_COMMIT
.try_with(|pending| *pending)
@@ -469,8 +455,7 @@ mod tests {
time::{Duration, Instant},
};
// 起一个长命子进程用于验证 Job Object 的生命周期绑定。
// 直接使用 System32 下的 ping.exe,避免 cmd 中间层。
// Use ping directly as a long-lived process without a cmd.exe intermediary.
fn spawn_long_lived() -> Result<Child> {
let child = Command::new("ping")
.args(["-n", "999", "127.0.0.1"])
@@ -480,7 +465,6 @@ mod tests {
Ok(child)
}
// 在超时内轮询子进程是否退出,返回是否已退出。
fn wait_until_exited(child: &mut Child, timeout: Duration) -> Result<bool> {
let deadline = Instant::now() + timeout;
loop {
@@ -494,21 +478,17 @@ mod tests {
}
}
// 成功路径:进程被分配进 Job Object 后仍存活;drop Job 句柄触发
// KILL_ON_JOB_CLOSE,进程应在超时内被 OS 终止。
#[test]
fn job_kills_child_on_handle_drop() -> Result<()> {
let mut child = spawn_long_lived()?;
let job = create_and_assign_sidecar_job(child.id())?;
// 分配后进程应仍在运行。
assert!(
child.try_wait()?.is_none(),
"child should still be running after being assigned to the job"
);
// 关闭 Job 句柄,OS 应连带终止其成员进程。
drop(job);
assert!(
@@ -519,10 +499,9 @@ mod tests {
Ok(())
}
// 失败路径:对一个不存在的 PID 调用时 OpenProcess 应失败,函数返回 Err。
#[test]
fn returns_err_for_invalid_pid() {
// PID 必须为 4 的倍数且极不可能存在;0xFFFF_FFFC 对应不到真实进程。
// Windows PIDs are multiples of four; this one is effectively impossible.
let result = create_and_assign_sidecar_job(0xFFFF_FFFC);
assert!(result.is_err(), "expected Err for a non-existent PID");
}
-16
View File
@@ -41,7 +41,6 @@ pub enum SysproxyFailure {
}
impl SysproxyFailure {
/// Stable frontend error code.
#[inline]
pub const fn code(&self) -> &'static str {
match self {
@@ -52,7 +51,6 @@ impl SysproxyFailure {
}
}
/// Find a classification using `anyhow`'s context-aware downcast.
#[inline]
pub fn from_chain(error: &anyhow::Error) -> Option<&Self> {
error.downcast_ref::<Self>()
@@ -83,7 +81,6 @@ impl std::error::Error for SysproxyFailure {}
pub struct SystemProxyStateUnknown;
impl SystemProxyStateUnknown {
/// Whether this marker appears in the error chain.
#[inline]
pub fn is_in(error: &anyhow::Error) -> bool {
error.downcast_ref::<Self>().is_some()
@@ -98,7 +95,6 @@ impl std::fmt::Display for SystemProxyStateUnknown {
impl std::error::Error for SystemProxyStateUnknown {}
/// Whether the error carries a frontend-mappable classification.
#[inline]
fn carries_a_mappable_code(error: &anyhow::Error) -> bool {
SysproxyFailure::from_chain(error).is_some()
@@ -120,7 +116,6 @@ pub fn rollback_failure(caused_by: anyhow::Error, rollback: anyhow::Error) -> an
combined
}
/// Classify local macOS proxy failures without replacing their source chain.
fn classify_local_failure(error: anyhow::Error) -> anyhow::Error {
if !was_refused_locally(&error) {
return error;
@@ -128,7 +123,6 @@ fn classify_local_failure(error: anyhow::Error) -> anyhow::Error {
error.context(SysproxyFailure::PrivilegeRequired)
}
/// Whether macOS refused a local proxy write.
fn was_refused_locally(error: &anyhow::Error) -> bool {
cfg!(target_os = "macos")
&& error.chain().any(|cause| {
@@ -141,7 +135,6 @@ fn was_refused_locally(error: &anyhow::Error) -> bool {
/// Distinguish a misplaced sidecar from a missing privileged service.
async fn classify_local_apply_failure(error: anyhow::Error) -> anyhow::Error {
// Preserve any existing, more specific classification.
if SysproxyFailure::from_chain(&error).is_some() || !was_refused_locally(&error) {
return error;
}
@@ -153,7 +146,6 @@ async fn classify_local_apply_failure(error: anyhow::Error) -> anyhow::Error {
error.context(refusal_classification(probed))
}
/// Bound the diagnostic service probe.
const SERVICE_PROBE_TIMEOUT: Duration = Duration::from_secs(2);
/// Classify a refusal from a fresh service probe only.
@@ -206,7 +198,6 @@ impl ServiceProxyOperations {
self.run_service_operation(operation).await
}
/// Invalidate the guard generation and wait for cancellation.
async fn cancel_and_drain<F, Fut, T>(&self, cancel: F) -> (u64, T)
where
F: FnOnce() -> Fut,
@@ -217,7 +208,6 @@ impl ServiceProxyOperations {
(generation, cancelled)
}
/// Record under the operation lock only for the current guard generation.
async fn record_if_current<Record>(&self, captured_generation: u64, record: Record) -> bool
where
Record: FnOnce() -> bool,
@@ -339,12 +329,10 @@ async fn current_service_proxy_config(verge: &IVerge) -> Result<MacosProxyConfig
if verge.proxy_auto_config.unwrap_or_default() {
return service_proxy_config(verge, 0, server::embedded_server_port()?);
}
// Configured: this builds the proxy settings handed to the service alongside a start.
let mixed_port = MixedPort::desired().await;
service_proxy_config(verge, mixed_port, 0)
}
/// Return whether a classified failure remains pending.
pub fn is_reportable(error: &anyhow::Error) -> bool {
is_reportable_given(error, notification::has_pending_failure)
}
@@ -549,10 +537,8 @@ pub async fn refresh_guard() -> Result<()> {
Ok(())
}
/// Consecutive failures allowed before the guard stops.
const GUARD_FAILURES_BEFORE_STOPPING: u32 = 3;
/// Report that the current guard stopped.
async fn report_guard_stopped(captured_generation: u64, error: &anyhow::Error) {
let stopped = anyhow::Error::new(SysproxyFailure::GuardStopped {
detail: format!("{error:#}"),
@@ -569,7 +555,6 @@ async fn report_guard_stopped(captured_generation: u64, error: &anyhow::Error) {
}
}
/// Stop the local guard and report whether it drained.
pub async fn stop_guard() -> bool {
SERVICE_PROXY_OPERATIONS
.cancel_and_drain(|| Sysopt::global().stop_proxy_guard())
@@ -593,7 +578,6 @@ mod tests {
use std::task::Poll;
use tokio::sync::Barrier;
/// Proxy state maintained by a running guard.
fn guarded_proxy() -> MacosProxyConfig {
MacosProxyConfig::Global {
host: "127.0.0.1".to_owned(),
+6 -52
View File
@@ -1,9 +1,4 @@
//! The seam between Run State and the machine it observes.
//!
//! Two adapters satisfy it: [`RealEnv`] talks to the Service over IPC and to the platform's
//! service registry, [`FakeEnv`] replays scripted answers. Because the store is generic over
//! this trait rather than reaching for globals, the state machine can be exercised without
//! a running app, an installed Service, or elevation.
//! Adapters between Run State and the real or scripted machine it observes.
use anyhow::{Context as _, Result};
@@ -12,41 +7,21 @@ use super::probe::ServiceVersionReply;
/// Everything Run State needs from outside itself.
pub trait RunStateEnv: Send + Sync + 'static {
/// Ask the Service which protocol it speaks. Fails when it cannot be reached at all.
fn probe_service_version(&self) -> impl Future<Output = Result<ServiceVersionReply>> + Send;
/// Whether the platform's service registry has a trusted record of an installation.
///
/// Fails when the registry itself could not be inspected, which is different from
/// "no installation" and is treated as unavailable rather than not-installed.
///
/// Async so blocking systemd and Windows SCM checks can run off the runtime workers.
/// Returns an error when installation evidence cannot be inspected, not when it is absent.
fn trusted_install_evidence(&self) -> impl Future<Output = Result<bool>> + Send;
/// Whether this app process is running elevated.
fn is_elevated(&self) -> bool;
/// Open or close the local PAC endpoint.
///
/// Derived from the Running Mode, never set independently: a PAC script that points at a
/// proxy port nothing is listening on is worse than no PAC at all.
/// Keeps the PAC endpoint derived from Running Mode.
fn set_pac_available(&self, available: bool);
/// Publish the Run State to observers outside the store.
///
/// Two of them today: the diagnostic snapshot, which reports the Running Mode, and the
/// frontend, which gets the whole thing pushed rather than polling for it.
fn publish(&self, state: &RunState);
/// Carry out a privileged operation against the Service.
///
/// Blocking and platform-specific — SCM, systemd, launchd, elevation prompts — which is
/// exactly why it sits behind the seam: the state machine around it can then be exercised
/// without installing anything.
fn run_privileged(&self, action: PendingAction) -> Result<()>;
}
/// The production adapter: real IPC, real platform registry, real elevation check.
#[derive(Debug, Default, Clone, Copy)]
pub struct RealEnv;
@@ -67,9 +42,7 @@ impl RunStateEnv for RealEnv {
}
fn is_elevated(&self) -> bool {
// Deliberately non-panicking, unlike `Handle::app_handle()`: Run State is read from
// startup paths that run before the app handle exists, and "not yet known" must
// degrade to "not elevated" rather than abort the process.
// Startup may read Run State before the app handle exists; fail closed instead of panicking.
crate::APP_HANDLE
.get()
.is_some_and(tauri_plugin_clash_verge_sysinfo::is_current_app_handle_admin)
@@ -80,17 +53,11 @@ impl RunStateEnv for RealEnv {
}
fn publish(&self, state: &RunState) {
// Reconciling capability is a reaction to the new state, not part of publishing it, so
// it is spawned: a transition must not wait on a config write it triggered. It is also
// spawned *before* the app-handle gate below, because a Core that stops and starts
// before the app handle exists still needs reconciling; the task re-reads the Run
// State itself rather than closing over this snapshot.
// Reconciliation must run before the app handle exists and must not block this transition.
crate::process::AsyncHandler::spawn(|| async {
crate::feat::reconcile_tun_availability().await;
});
// Non-panicking for the same reason as `is_elevated`: the Core can stop and start
// before the app handle exists, and a missed notification is better than an abort.
let Some(app_handle) = crate::APP_HANDLE.get() else {
return;
};
@@ -115,10 +82,7 @@ mod fake {
use super::{PendingAction, RunState, RunStateEnv, ServiceVersionReply};
use crate::core::manager::RunningMode;
/// A scripted stand-in for the machine.
///
/// Defaults to the least capable environment — no Service, no elevation — so a test only
/// has to say what it needs. Outbound effects are recorded rather than performed.
/// A fail-closed scripted machine that records outbound effects.
#[derive(Debug)]
pub struct FakeEnv {
version_replies: Mutex<Vec<Result<ServiceVersionReply, String>>>,
@@ -152,7 +116,6 @@ mod fake {
Self::default()
}
/// An installed, reachable, protocol-compatible Service.
#[must_use]
pub fn service_ready(self) -> Self {
self.with_evidence(true).always_replying(Ok(ServiceVersionReply {
@@ -162,7 +125,6 @@ mod fake {
}))
}
/// An installed Service that answers with an incompatible protocol.
#[must_use]
pub fn service_version_mismatch(self) -> Self {
self.with_evidence(true).always_replying(Ok(ServiceVersionReply {
@@ -172,14 +134,12 @@ mod fake {
}))
}
/// Registered with the platform but not answering.
#[must_use]
pub fn service_unreachable(self) -> Self {
self.with_evidence(true)
.always_replying(Err("ipc transport refused".to_owned()))
}
/// The platform registry itself could not be inspected.
#[must_use]
pub fn evidence_unavailable(mut self) -> Self {
self.evidence = Err("registry probe failed".to_owned());
@@ -210,38 +170,32 @@ mod fake {
self.replying(vec![reply])
}
/// How many times the Service was probed — asserts that retries actually retried.
#[must_use]
pub fn probe_count(&self) -> usize {
*self.probe_count.lock()
}
/// The last PAC availability the store asked for, or `None` if it never asked.
#[must_use]
pub fn pac_available(&self) -> Option<bool> {
*self.pac_available.lock()
}
/// Every Running Mode published outward, in order.
#[must_use]
pub fn published_modes(&self) -> Vec<RunningMode> {
self.published.lock().iter().map(|state| state.mode).collect()
}
/// Every Run State published outward, in order.
#[must_use]
pub fn published(&self) -> Vec<RunState> {
self.published.lock().clone()
}
/// Make every privileged operation fail with `reason`.
#[must_use]
pub fn privileged_operations_fail(self, reason: &str) -> Self {
*self.privileged_outcome.lock() = Err(reason.to_owned());
self
}
/// Every privileged operation actually attempted, in order.
#[must_use]
pub fn privileged_actions(&self) -> Vec<PendingAction> {
self.privileged_actions.lock().clone()
+2 -21
View File
@@ -3,19 +3,13 @@
use crate::core::manager::RunningMode;
/// Last observed Service state.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum ServiceHealth {
/// Not probed yet.
#[default]
Unknown,
/// Installed, reachable, and speaking a compatible protocol.
Ready,
/// No trusted installation evidence on this machine.
NotInstalled,
/// Installed but speaking an incompatible protocol; needs reinstall.
VersionMismatch,
/// Installed but unusable, with the reason we recorded.
Unavailable(String),
}
@@ -38,7 +32,6 @@ impl ServiceHealth {
}
}
/// Requested privileged Service operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PendingAction {
@@ -48,7 +41,6 @@ pub enum PendingAction {
ForceReinstall,
}
/// Snapshot used for Core availability decisions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunState {
pub health: ServiceHealth,
@@ -61,26 +53,22 @@ pub struct RunState {
}
impl RunState {
/// Whether the last probe observed a ready Service; ignores in-flight operations.
#[must_use]
pub const fn service_ready(&self) -> bool {
matches!(self.health, ServiceHealth::Ready)
}
/// Whether the Service is ready and not mid-operation.
#[must_use]
pub const fn service_usable(&self) -> bool {
self.service_ready() && !self.op_in_flight
}
/// Whether elevation or a usable Service can support TUN.
#[must_use]
pub const fn tun_capable(&self) -> bool {
self.is_admin || self.service_usable()
}
/// Whether the user must resolve a pending request or a present-but-unusable Service.
/// In-flight, absent, and accepted-Sidecar states need no decision.
/// In-flight, absent, and accepted-Sidecar states require no user decision.
#[must_use]
pub const fn service_needs_attention(&self) -> bool {
if self.op_in_flight {
@@ -98,7 +86,6 @@ impl RunState {
)
}
/// Whether enabled TUN is certainly unusable and may be disabled.
/// Unknown, in-flight, and attention-required states are inconclusive.
#[must_use]
pub const fn tun_should_be_disabled(&self, tun_enabled: bool) -> bool {
@@ -108,14 +95,12 @@ impl RunState {
!matches!(self.health, ServiceHealth::Unknown) && !self.op_in_flight && !self.service_needs_attention()
}
/// Whether startup must suppress TUN for a confirmed absent Service.
/// Present-but-broken Services remain in the repair flow.
/// Present-but-broken services remain in the repair flow rather than suppressing TUN.
#[must_use]
pub const fn startup_tun_should_be_disabled(&self, tun_enabled: bool) -> bool {
matches!(self.health, ServiceHealth::NotInstalled) && self.tun_should_be_disabled(tun_enabled)
}
/// Frontend view with derived availability decisions.
#[must_use]
pub fn to_view(&self) -> RunStateView {
RunStateView {
@@ -133,7 +118,6 @@ impl RunState {
}
}
/// Frontend Run State.
#[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RunStateView {
@@ -159,20 +143,17 @@ pub(super) struct StoredService {
}
impl StoredService {
/// Record an observation, clearing any request it answers.
pub fn observe(&mut self, health: ServiceHealth) {
self.health = health;
self.pending = None;
self.sidecar_allowed = false;
}
/// Record a requested privileged operation, preserving the last observation.
pub const fn request(&mut self, action: PendingAction) {
self.pending = Some(action);
self.sidecar_allowed = false;
}
/// Record that the user accepted Sidecar for this session.
pub const fn allow_sidecar(&mut self) {
self.pending = None;
self.sidecar_allowed = true;
+25 -134
View File
@@ -1,15 +1,7 @@
//! Run State — the single answer to "how is the Core running, and what backs it".
//! The single answer to how the Core runs and what backs it.
//!
//! This module owns Service Health, Running Mode, Pending Action and the privileged-operation
//! lock. It deliberately does **not** own starting, stopping or restarting the Core — those
//! stay in `CoreManager`, which reports transitions in and reads snapshots back. Merging the
//! two would leave no point at which the state is consistent, since a snapshot taken
//! mid-restart would describe a transition rather than a state.
//!
//! Reads come in three flavours that differ only in *freshness* — [`RunStateStore::state`]
//! (cached), [`RunStateStore::settled`] (waits for any in-flight operation) and
//! [`RunStateStore::probe`] (forces live IPC). What the answer *means* is decided by methods
//! on [`RunState`], so no caller writes its own availability formula.
//! Core lifecycle stays in `CoreManager`; this module owns its state, service health, pending
//! actions, and the privileged-operation lock. Reads differ only in freshness.
mod env;
mod health;
@@ -45,11 +37,7 @@ use probe::{CurrentServiceProbe, classify_service_health, probe_outcome};
/// The process-wide Run State, observing the real machine.
pub static RUN_STATE: Lazy<RunStateStore<RealEnv>> = Lazy::new(|| RunStateStore::new(RealEnv));
/// Why a wait for Service readiness ended without a ready Service.
///
/// The two are not interchangeable: an unreachable Service told us nothing, so the caller
/// decides whether silence means unavailable; a rejected one already updated health and must
/// not have that verdict overwritten with a vaguer one.
/// Distinguishes silence from a reply that updated Service health with a rejection.
#[derive(Debug)]
pub enum ReadyWaitError {
/// No readable reply within the attempts budget.
@@ -66,11 +54,7 @@ impl std::fmt::Display for ReadyWaitError {
}
}
/// The service-owned state together with the counters that version it.
///
/// They share one lock so a reader can never see a change without its version bump.
/// `generation` tracks visible changes; `observation` also tracks assertions that invalidate
/// older health probes without changing visible state.
/// Service state and revisions share one lock so observations cannot overtake their version bump.
#[derive(Debug, Default)]
struct VersionedService {
service: StoredService,
@@ -79,13 +63,11 @@ struct VersionedService {
}
impl VersionedService {
/// Record a visible change and invalidate older health probes.
const fn bump(&mut self) {
self.generation = self.generation.wrapping_add(1);
self.observation = self.observation.wrapping_add(1);
}
/// Reserve a revision that invalidates older health probes.
const fn next_observation(&mut self) -> u64 {
self.observation = self.observation.wrapping_add(1);
self.observation
@@ -113,33 +95,19 @@ impl<E: RunStateEnv> RunStateStore<E> {
}
}
// ─────────────────────────── reads: freshness only ───────────────────────────
/// The last known Run State, without waiting and without probing.
///
/// May be stale while a privileged operation is in flight — the snapshot says so via
/// [`RunState::op_in_flight`], and [`RunState::service_usable`] accounts for it.
/// It reports when a privileged operation may make the snapshot stale.
pub fn state(&self) -> RunState {
let service = self.service.lock().service.clone();
self.snapshot(service)
}
/// The Run State once any in-flight privileged operation has finished.
///
/// The snapshot is the decision, not a separate check before it. Reading the slot twice —
/// once to decide whether to wait, once to build the snapshot — leaves a window in which an
/// operation claims it, and the snapshot then *describes* that operation instead of waiting
/// for it. `prepare_startup` reads this: it would see a requested install as a reason not to
/// start, where waiting would have told it whether the install worked.
/// Returns one snapshot taken after any operation visible in that snapshot has settled.
pub async fn settled(&self) -> RunState {
loop {
let notified = self.operation_done.notified();
tokio::pin!(notified);
// Register as a waiter *before* reading the state. `notify_waiters` wakes only
// those already registered and leaves no permit behind, so without this an
// operation finishing between the read and the await is a wakeup lost for good
// — and this future would then wait for some unrelated later operation, or
// forever.
// Register before reading; `notify_waiters` leaves no permit for late waiters.
notified.as_mut().enable();
let state = self.state();
@@ -150,11 +118,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
}
}
/// Probe the Service now, record what came back, and return the fresh Run State.
///
/// A *transport* failure is not an observation: the Service may simply be restarting, so
/// the last confirmed health survives and the caller decides whether to retry. Only a
/// reply we could read and reject updates health.
/// Records readable replies; transport failures preserve the last confirmed health.
pub async fn probe(&self) -> Result<RunState> {
let reply = self
.env
@@ -164,11 +128,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
self.record_reply(&reply)
}
/// Probe until the Service answers, giving it `attempts` tries `interval` apart.
///
/// Only an unreachable Service is worth retrying. A reply we could read is the Service's
/// answer — retrying an incompatible version twenty times would just delay telling the
/// user to reinstall — so the wait ends on the first readable reply either way.
/// Retries transport failures but stops at the first readable reply, including a rejection.
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
let mut last_error = None;
for attempt in 0..attempts {
@@ -186,7 +146,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
})))
}
/// Record a readable reply as an observation, and report whether it was acceptable.
fn record_reply(&self, reply: &ServiceVersionReply) -> Result<RunState> {
match classify_service_version_reply(reply) {
ServiceVersionCheck::Ready => {
@@ -200,10 +159,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
}
}
/// Work out the Service's health from scratch: platform evidence first, then a live probe.
///
/// Platform evidence that cannot be inspected is *unavailable*, not *absent* — assuming
/// "not installed" there would offer the user an install that is already there.
/// Detects health from platform evidence and then live IPC; unknown evidence is not absence.
pub async fn detect_service_health(&self) -> ServiceHealth {
let has_marker = match self.env.trusted_install_evidence().await {
Ok(exists) => exists,
@@ -234,26 +190,18 @@ impl<E: RunStateEnv> RunStateStore<E> {
}
}
// ─────────────────────────── writes ───────────────────────────
/// Probe and record Service health unless a newer observation arrived first.
///
/// Reserving before I/O prevents slower probes from overwriting later observations, including
/// assertions that leave visible state unchanged. Returns the health that remains recorded.
/// Records detected health unless a newer observation arrived during I/O.
pub async fn observe_current_health(&self) -> ServiceHealth {
let reservation = self.reserve_health_observation();
let health = self.detect_service_health().await;
self.commit_reserved_observation(health, reservation)
}
/// Reserve the revision for a health probe.
fn reserve_health_observation(&self) -> u64 {
self.service.lock().next_observation()
}
/// Commit `health` only if `reservation` is still latest; otherwise return the newer health.
///
/// The comparison and write share one lock. A successful commit reuses its reserved revision.
/// Commits only the latest reserved observation.
fn commit_reserved_observation(&self, health: ServiceHealth, reservation: u64) -> ServiceHealth {
let mut state = self.service.lock();
if state.observation != reservation {
@@ -276,7 +224,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
health
}
/// Record an observation about the Service, clearing any request it answers.
pub fn observe(&self, health: ServiceHealth) {
let mut state = self.service.lock();
if state.service.health == health && state.service.pending.is_none() && !state.service.sidecar_allowed {
@@ -290,11 +237,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
self.announce();
}
/// Record an authorised privileged operation and return whether it displaced the session's
/// Sidecar allowance.
///
/// Reading and clearing the allowance in one transition lets the caller safely restore it if
/// the operation fails.
/// Records an action and returns the Sidecar allowance it displaced for possible rollback.
pub fn request_action(&self, action: PendingAction) -> bool {
let mut state = self.service.lock();
let displaced = state.service.sidecar_allowed;
@@ -310,9 +253,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
displaced
}
/// Accept Sidecar for the rest of this app session without any eligibility check.
///
/// For builds and paths where Sidecar is the decided outcome rather than a fallback.
/// Accepts Sidecar when it is the predetermined outcome rather than a fallback.
pub fn accept_sidecar(&self) {
let mut state = self.service.lock();
if state.service.sidecar_allowed && state.service.pending.is_none() {
@@ -326,10 +267,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
self.announce();
}
/// Restore a displaced Sidecar allowance unless one already exists or the Service is ready.
///
/// The check and update are atomic so a restored allowance cannot shadow a newly ready
/// Service. Returns whether the allowance was restored.
/// Atomically restores an allowance unless Sidecar is already allowed or the Service is ready.
pub fn restore_sidecar_allowance(&self) -> bool {
let mut state = self.service.lock();
if state.service.sidecar_allowed {
@@ -348,9 +286,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
true
}
/// Revoke an allowance after Sidecar startup fails without changing Service health.
///
/// Returns whether the allowance was revoked.
/// Revokes a failed Sidecar allowance without changing Service health.
pub fn withdraw_sidecar_allowance(&self) -> bool {
let mut state = self.service.lock();
if !state.service.sidecar_allowed {
@@ -363,10 +299,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
true
}
/// Accept Sidecar for the rest of this app session.
///
/// Rejected while an operation is in flight, or from a state where the Service is
/// already usable or is mid-privileged-operation other than an install.
/// Accepts Sidecar only while the Service is unusable and no conflicting operation is active.
pub fn allow_sidecar_for_session(&self) -> Result<()> {
let mut state = self.service.lock();
if self.operation_running.load(Ordering::Acquire) {
@@ -390,10 +323,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
Ok(())
}
/// Require the Service to be installed before the Core starts, when it is simply absent.
///
/// A no-op from any other state, mirroring the rule that an already-requested or
/// already-usable Service must not be downgraded to "needs installing".
/// Requests installation only for a confirmed absent Service.
pub fn require_install_for_session(&self) -> Result<()> {
let mut state = self.service.lock();
if self.operation_running.load(Ordering::Acquire) {
@@ -414,11 +344,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
Ok(())
}
/// Carry out a privileged operation and record what it did to the Service.
///
/// A successful uninstall records an absent Service. Other successes rely on the caller's
/// readiness check. Failures re-probe the Service so the request is retired and health
/// reflects the machine's current state.
/// Runs an operation, recording uninstall success or re-probing after failure.
pub async fn perform(&self, action: PendingAction) -> Result<()> {
let outcome = self.env.run_privileged(action);
match &outcome {
@@ -436,56 +362,32 @@ impl<E: RunStateEnv> RunStateStore<E> {
outcome
}
// ─────────────────────────── running mode ───────────────────────────
/// The Running Mode, shared so hot callers such as the tray do not allocate.
pub fn mode_arc(&self) -> Arc<RunningMode> {
Arc::clone(&self.mode.load())
}
/// The Core is now running, and serving, in `mode`.
pub fn core_started(&self, mode: RunningMode) {
self.enter_mode(mode);
}
/// The Core is no longer running.
pub fn core_stopped(&self) {
self.enter_mode(RunningMode::NotRunning);
}
/// A start attempt is under way: the Core is not serving yet, whatever the mode says.
///
/// Closes the PAC endpoint without disturbing the Running Mode, so a handover cannot
/// hand out a PAC script for a proxy port that is between owners.
///
/// Every caller must pair this with [`Self::core_start_settled`]. A start attempt that
/// never happens — a candidate rejected before anything was stopped — otherwise leaves PAC
/// closed for a Core that is still serving, and nothing else would ever reopen it: PAC is
/// re-derived only when the Running Mode changes, and that is exactly what did not happen.
/// Closes PAC during a start or handover without changing the last running mode.
/// Every call must be paired with [`Self::core_start_settled`].
pub fn core_starting(&self) {
self.env.set_pac_available(false);
}
/// The start attempt is over, however it ended: PAC goes back to following the Running Mode.
///
/// Idempotent and safe on every path, because it re-derives rather than restores. After a
/// start that succeeded the mode is already running and this confirms PAC open; after one
/// that was abandoned the mode never moved and this reopens PAC for the Core that kept
/// serving; after one that failed and stopped the Core the mode says NotRunning and PAC
/// stays shut.
/// Idempotently re-derives PAC availability after a start attempt settles.
pub fn core_start_settled(&self) {
let running = !matches!(**self.mode.load(), RunningMode::NotRunning);
self.env.set_pac_available(running);
}
/// Move to `mode` and re-derive everything that follows from it.
///
/// PAC availability and the outward mirror are derived here and nowhere else, so they
/// cannot drift from the Running Mode the way ten hand-paired call sites could.
///
/// PAC closes *before* the mode changes and opens *after*, so whatever a concurrent
/// reader catches mid-transition is the closed state: being refused a PAC script beats
/// being handed one that points at a proxy port between owners.
/// Moves to `mode`, closing PAC before the transition and reopening it only afterward.
fn enter_mode(&self, mode: RunningMode) {
let running = !matches!(mode, RunningMode::NotRunning);
if !running {
@@ -498,8 +400,6 @@ impl<E: RunStateEnv> RunStateStore<E> {
self.announce();
}
// ─────────────────────────── privileged operations ───────────────────────────
/// Claim the privileged-operation slot, releasing it when the guard drops.
///
/// Only one privileged operation may be in flight; [`Self::settled`] waits on this.
@@ -514,31 +414,22 @@ impl<E: RunStateEnv> RunStateStore<E> {
Ok(OperationGuard { store: self })
}
/// Whether a privileged operation is in flight right now.
///
/// Production code reads this through [`RunState::op_in_flight`]; this accessor exists for
/// tests that assert on the slot without taking a snapshot.
#[cfg(test)]
pub fn operation_in_flight(&self) -> bool {
self.operation_running.load(Ordering::Acquire)
}
/// The environment this store observes, so tests can assert on the effects it recorded.
#[cfg(test)]
pub const fn env(&self) -> &E {
&self.env
}
/// Bumped on every state change; lets tests assert that a no-op really was a no-op.
#[cfg(test)]
pub fn generation_count(&self) -> u64 {
self.service.lock().generation
}
/// Tell the outside world the Run State moved.
///
/// Called after every mutation and never while the state lock is held, so a publisher that
/// reads back the state cannot deadlock against the writer that triggered it.
/// Publishes after dropping the state lock so observers may safely read it back.
fn announce(&self) {
self.env.publish(&self.state());
}
+5 -25
View File
@@ -1,20 +1,8 @@
//! Deciding when the Service has stopped being ours.
//!
//! While the Core runs under the Service, the app polls the Service for owner status. Three
//! things can go wrong — we cannot read a reply, the Service says someone else owns it, or it
//! answers but describes a Core that is gone — and each needs a different response. This is
//! the decision, separated from the polling and from the recovery it triggers.
//!
//! Recovery *actions* deliberately live with the Core lifecycle rather than here: this module
//! decides that the Service can no longer be trusted, and `CoreManager` is what tears the Core
//! down in response.
//! Classifies service ownership samples; `CoreManager` performs any recovery it requests.
use clash_verge_service_ipc::ServiceLifecycleState;
/// How many consecutive bad samples we tolerate before acting.
///
/// Service restarts and slow status calls are normal; acting on the first one would tear down
/// a working proxy for a blip.
/// Tolerates transient service restarts and slow status calls.
const SUSTAINED_SAMPLES: u8 = 3;
/// Why the app stopped trusting the Service that was running its Core.
@@ -49,11 +37,7 @@ pub enum OwnerSample {
pub enum OwnerStep {
/// Nothing is wrong, or not wrong for long enough yet.
Continue,
/// Unreadable for long enough that it might be real. Check whether the Core's own endpoint
/// still answers, then report back via [`OwnerWatch::resolve_transport`].
///
/// A Service we cannot reach while the Core is still serving is a broken status channel,
/// not a lost Core — tearing down the proxy there would be the cure causing the disease.
/// Check the Core endpoint before treating a sustained status-channel failure as lost ownership.
VerifyTransport,
/// Stop trusting the Service and recover.
Recover(OwnerRecoveryReason),
@@ -75,8 +59,7 @@ impl OwnerWatch {
}
}
/// Whether this sample warrants a log line: only the moment a run becomes sustained, so a
/// permanently broken Service does not fill the log at the poll interval.
/// True only when a failure first becomes sustained, to avoid repeated logs.
#[must_use]
pub const fn just_became_sustained(&self) -> bool {
self.unreadable_samples == SUSTAINED_SAMPLES
@@ -120,10 +103,7 @@ impl OwnerWatch {
}
}
/// Report what the transport check found after [`OwnerStep::VerifyTransport`].
///
/// If the Core's own endpoint still answers, only the status channel is broken: the run is
/// reset so the next stretch of silence has to earn its own verdict.
/// Resets the failure run when only the status channel is unavailable.
pub const fn resolve_transport(&mut self, owner_endpoint_available: bool) -> OwnerStep {
if owner_endpoint_available {
self.unreadable_samples = 0;
+7 -32
View File
@@ -61,13 +61,8 @@ pub(crate) async fn collect_runtime_bundle(config_file: &Path, core_path: &Path)
})
}
/// Rewrite one provider section's paths to service-side destinations, and record what each
/// destination is going to hold.
///
/// The two outputs are not the same thing. `assets` are files the app owns and the service copies;
/// `remote_providers` are files the *core* downloads, which the service never writes and only
/// needs to recognise — a download cache is reusable exactly while the url that produced it is
/// unchanged, and the service has no other way to tell.
/// Rewrites provider paths and records copied assets separately from core-downloaded providers.
/// Remote URLs let the service decide whether a core download cache remains reusable.
fn collect_provider_assets(
config: &mut Value,
section: &str,
@@ -91,28 +86,13 @@ fn collect_provider_assets(
let Some(raw_path) = provider.get("path").and_then(Value::as_str) else {
continue;
};
// The Core decides what a provider is by its `type`, so anything else here would disagree
// with it. Keying off the presence of a `url` used to do that: a `file` provider carrying
// a stray `url` was treated as remote, its local file left uncopied, and the Core then
// could not find what the rewritten path pointed at.
//
// Disagreeing the other way is just as bad, though, and it is why neither branch may fail
// the whole bundle over one odd provider. Measured against mihomo v1.19.26: it accepts a
// `http` provider with no url, an `inline` provider carrying both a url and a path that
// does not exist, and a `file` provider whose path is missing. Refusing any of those here
// would turn a configuration the Core is willing to load into one that cannot be applied
// at all — including at start, since this is where a Service-mode start gets its bundle.
// A provider we cannot classify keeps its path unrewritten and is simply not declared.
// Match mihomo's `type` classification and leave malformed-but-accepted providers untouched.
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http");
let url = provider.get("url").and_then(Value::as_str).map(str::to_owned);
let destination = match (is_remote, url) {
(true, Some(url)) => {
let destination = provider_destination(config_root, raw_path)?;
// Remote providers take their destination out of circulation as much as local ones
// do: the Service refuses a bundle where one path is claimed both by a file it must
// copy and by a file the Core downloads, because the two would overwrite each
// other. Two providers naming the same file *and* the same source are not that —
// they are one file with two names for it, which the Service folds.
// Reserve remote destinations too; copied and downloaded files must not collide.
match remote_providers
.iter()
.find(|declared| declared.destination == destination)
@@ -281,9 +261,7 @@ mod tests {
);
assert!(bundle.assets.iter().any(|asset| asset.destination == "Country.mmdb"));
assert!(!bundle.assets.iter().any(|asset| asset.destination.contains("remote")));
// A remote provider is not copied, but it must still be declared: the Service decides
// whether the Core's download cache is reusable by comparing the url that produced it,
// and an undeclared provider is one it can only ever discard.
// Remote declarations preserve service-side cache reuse.
assert_eq!(
bundle
.remote_providers
@@ -305,9 +283,7 @@ mod tests {
#[tokio::test]
async fn two_names_for_one_remote_file_are_folded_rather_than_refused() -> anyhow::Result<()> {
// The Service folds an identical repeat, so refusing it here would block a configuration
// mihomo itself accepts — and this is also where a Service-mode *start* gets its bundle,
// so the refusal would stop the core coming up at all.
// Identical repeats are one service-side file and are safe to fold.
let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root)?;
@@ -351,8 +327,7 @@ mod tests {
#[tokio::test]
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle() -> anyhow::Result<()> {
// Measured against mihomo v1.19.26: it accepts a `http` provider with no url, and a
// non-http provider whose path does not exist. Neither may stop the rest being materialised.
// Odd providers accepted by mihomo must not block the rest of the bundle.
let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root)?;
+17 -70
View File
@@ -39,12 +39,8 @@ use std::{
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
static ACTIVE_SERVICE_SESSION: Lazy<Mutex<Option<ActiveServiceSession>>> = Lazy::new(|| Mutex::new(None));
/// The Service session that owns the running Core, and what that Service can do.
///
/// The capability is learned once, when the Core is started, and discarded with the session
/// rather than cached globally — it describes *the Service instance that owns this Core*, which
/// is the only scope where it is safe to act on. A Service upgraded underneath a running Core
/// does not silently gain abilities the Core it owns was not started under.
/// Capabilities of the service session that owns the running Core.
/// They are discarded with that session rather than cached across service upgrades.
#[derive(Clone)]
struct ActiveServiceSession {
proof: OwnerSessionProof,
@@ -65,10 +61,7 @@ pub(crate) fn active_service_session() -> Result<OwnerSessionProof> {
.context("service owner session is not active")
}
/// Whether the Service that started the running Core can stage a runtime in place.
///
/// False for every reason that is not "yes": no session, an older Service, or a protocol query
/// that did not come back. All of them mean the same thing to the caller — take the slow path.
/// Returns false unless the active service session explicitly supports in-place staging.
pub(crate) fn active_service_supports_runtime_staging() -> bool {
ACTIVE_SERVICE_SESSION
.lock()
@@ -80,10 +73,7 @@ pub(crate) fn clear_active_service_session() {
ACTIVE_SERVICE_SESSION.lock().take();
}
/// Ask the Service whether it speaks the staging half of the protocol.
///
/// A failure here is not a failure to start: it only costs the fast path, so it is reported as
/// "no" and logged rather than propagated.
/// Probes staging support without failing startup when the fast path is unavailable.
async fn probe_runtime_staging_support() -> bool {
match clash_verge_service_ipc::get_version().await {
Ok(response) if response.code == 0 => response
@@ -130,11 +120,7 @@ pub enum ServiceStatus {
}
impl ServiceStatus {
/// Flatten a Run State snapshot into the legacy single-slot status.
///
/// Precedence mirrors what the single slot used to hold: a requested action shadows an
/// accepted Sidecar, which shadows the last observation. Kept until the frontend seam
/// moves to `RunState` wholesale.
/// Flattens Run State using legacy precedence: action, Sidecar allowance, then health.
fn from_run_state(state: &RunState) -> Self {
if let Some(action) = state.pending {
return match action {
@@ -240,11 +226,7 @@ pub(crate) fn trusted_service_evidence() -> Result<bool> {
macos_service_install_marker_exists().context("failed to inspect launchd service registration")
}
/// Legacy façade over [`RUN_STATE`].
///
/// Holds no state of its own: Service Health, the requested action and the privileged-operation
/// lock all live in `core::runstate`. This type survives only so that existing call sites keep
/// compiling while the seam moves; it is retired once they read `RunState` directly.
/// Stateless legacy façade over [`RUN_STATE`] retained for existing call sites.
pub struct ServiceManager;
#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))]
@@ -812,9 +794,7 @@ fn force_reinstall_service() -> Result<()> {
})
}
/// Dispatch a privileged operation to the platform implementation.
///
/// Blocking work, so it is handed to a blocking thread: the caller is async.
/// Dispatches a privileged platform operation on a blocking thread.
pub(crate) fn run_privileged_service_action(action: PendingAction) -> Result<()> {
let (operation, label): (fn() -> Result<()>, &'static str) = match action {
PendingAction::Install => (install_service, "install service"),
@@ -825,11 +805,7 @@ pub(crate) fn run_privileged_service_action(action: PendingAction) -> Result<()>
tokio::task::block_in_place(operation).with_context(|| format!("{label} failed"))
}
/// Describe what the Service should hold, for the Core binary this app would start.
///
/// Shared by starting and staging so the two cannot disagree about the binary or about how the
/// configuration's provider paths are rewritten — a staged bundle naming a different core is
/// exactly what makes the Service refuse to stage.
/// Builds the same runtime bundle description for both service start and staging.
async fn collect_service_runtime_bundle(config_file: &Path) -> Result<RuntimeBundle> {
let verge_config = Config::verge().await;
let clash_core = verge_config.latest_arc().get_valid_clash_core();
@@ -840,13 +816,7 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result<RuntimeBun
collect_runtime_bundle(config_file, &bin_path).await
}
/// What asking the Service to stage a runtime produced.
///
/// A refusal carries its code because only some refusals say anything about starting. "This bundle
/// names an asset I will not accept" does: a fresh start materialises the same bundle and is
/// refused the same way, so stopping a working Core would add an outage to a failure that already
/// happened. "You do not own this Core" does not — `start_clash` proposes a new session rather than
/// presenting the old one, so starting is exactly how that gets resolved.
/// A staging response whose refusal code tells callers whether a fresh start can help.
pub(super) enum StageRequest {
Refused { code: u16, message: CompactString },
Answered(StageRuntimeOutcome),
@@ -859,11 +829,7 @@ impl StageRequest {
}
}
/// Have the Service make the running Core's runtime match `config_file`, without restarting it.
///
/// `Err` means the request did not get an answer. A refusal, and `RestartRequired`, both come back
/// as `Ok`: neither is a failure of this function, and only the caller can decide what to do about
/// them.
/// Requests in-place staging. `Err` means no answer; refusals are returned for caller policy.
pub(super) async fn stage_runtime_by_service(config_file: &Path) -> Result<StageRequest> {
let session = active_service_session()?;
let credentials = current_owner_credentials()?;
@@ -1141,10 +1107,7 @@ fn start_owner_monitor() {
});
}
/// Ask the Service who owns it, flattening every unusable answer into one sample.
///
/// A transport error, an error code and an empty payload are the same thing to the watch:
/// we did not learn anything. Only the log line distinguishes them.
/// Samples ownership, treating every unusable reply as unreadable.
async fn read_owner_sample() -> OwnerSample {
let response = match current_owner_credentials() {
Ok(credentials) => clash_verge_service_ipc::get_status(&credentials).await,
@@ -1270,11 +1233,8 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
}
}
/// Wait for a freshly installed or repaired Service to answer.
///
/// Silence for the whole budget *is* an observation here — the Service had its window and
/// never spoke — unlike a single failed probe. A readable but rejected reply already recorded
/// its own verdict, which must not be flattened into "unavailable".
/// Waits for a repaired service, preserving readable rejection details but classifying sustained
/// silence as unavailable.
async fn wait_for_service_ipc() -> Result<()> {
const CONTEXT: &str = "service IPC did not become available";
let config = ServiceManager::config();
@@ -1354,9 +1314,7 @@ impl ServiceManager {
}
async fn apply_service_status(&self, status: ServiceStatus) -> Result<()> {
// Derived from the caller's own argument, not read back out of the store: an
// observation racing in between would clear the pending action and silently turn a
// user-authorised install into a no-op.
// Use the caller's action; a racing observation may clear the stored pending action.
let Some(action) = requested_action(&status) else {
self.set_status(status.clone());
return report_non_actionable_status(status);
@@ -1377,9 +1335,7 @@ impl ServiceManager {
}
}
/// Run the full action workflow and restore the session's previous Sidecar allowance on failure.
///
/// This includes the readiness wait: an action has not landed until the Service responds.
/// Runs through readiness and restores a displaced Sidecar allowance on failure.
async fn run_action_restoring_sidecar<E: RunStateEnv>(
store: &RunStateStore<E>,
was_allowed: bool,
@@ -1428,11 +1384,7 @@ fn report_non_actionable_status(status: ServiceStatus) -> Result<()> {
Ok(())
}
/// Run a privileged operation while holding the Run State operation slot.
///
/// The slot is released — and `settled` waiters woken — before `post_operation` runs, so a
/// post-operation refresh such as the tray menu observes the final state rather than a
/// state still flagged as in-flight.
/// Releases the Run State operation slot before post-operation observers refresh.
async fn run_operation_and_then<E, Post, PostFuture>(
store: &RunStateStore<E>,
operation: impl Future<Output = Result<()>>,
@@ -1451,12 +1403,7 @@ where
post_operation().await
}
/// Apply a legacy single-slot status to a Run State, splitting it back into observation and
/// request. The inverse of [`ServiceStatus::from_run_state`].
/// The privileged operation a status is asking for, if any.
///
/// A pure function of the status so that a caller can decide what to run without reading the
/// store back and racing an observation.
/// Maps a legacy status to its requested action without racing a store reread.
const fn requested_action(status: &ServiceStatus) -> Option<PendingAction> {
match status {
ServiceStatus::InstallRequired => Some(PendingAction::Install),
-22
View File
@@ -156,7 +156,6 @@ impl Tray {
logging!(info, Type::Tray, "System tray created successfully");
}
Err(e) => {
// Don't return error, let application continue running without tray
logging!(
warn,
Type::Tray,
@@ -167,7 +166,6 @@ impl Tray {
Ok(())
}
/// 更新托盘点击行为
pub async fn update_click_behavior(&self) -> Result<()> {
if handle::Handle::global().is_exiting() {
logging!(debug, Type::Tray, "应用正在退出,跳过托盘点击行为更新");
@@ -187,7 +185,6 @@ impl Tray {
Ok(())
}
/// 更新托盘菜单
pub async fn update_menu(&self) -> Result<()> {
if handle::Handle::global().is_exiting() {
logging!(debug, Type::Tray, "应用正在退出,跳过托盘菜单更新");
@@ -245,7 +242,6 @@ impl Tray {
Ok(())
}
/// 更新托盘图标
pub async fn update_icon(&self, verge: &IVerge) -> Result<()> {
if handle::Handle::global().is_exiting() {
logging!(debug, Type::Tray, "应用正在退出,跳过托盘图标更新");
@@ -278,7 +274,6 @@ impl Tray {
Ok(())
}
/// 更新托盘提示
pub async fn update_tooltip(&self) -> Result<()> {
if handle::Handle::global().is_exiting() {
logging!(debug, Type::Tray, "应用正在退出,跳过托盘提示更新");
@@ -309,7 +304,6 @@ impl Tray {
}
}
// Get localized strings before using them
let sys_proxy_text = clash_verge_i18n::t!("tray.tooltip.systemProxy");
let tun_text = clash_verge_i18n::t!("tray.tooltip.tun");
let profile_text = clash_verge_i18n::t!("tray.tooltip.profile");
@@ -413,7 +407,6 @@ impl Tray {
allow
}
/// 根据配置统一更新托盘速率采集任务状态(macOS)
#[cfg(target_os = "macos")]
pub fn update_speed_task(&self, enable_tray_speed: bool) {
self.speed_controller.update_task(enable_tray_speed);
@@ -476,7 +469,6 @@ fn create_subcreate_proxy_menu_item(
// TODO: 应用启动时,内核还未启动完全,无法获取代理节点信息
if let Some(proxy_nodes_data) = proxy_nodes_data {
for (group_name, group_data) in proxy_nodes_data.proxies.iter() {
// Filter groups based on mode and hidden flag
let should_show = match proxy_mode {
"global" => group_name == "GLOBAL",
_ => group_name != "GLOBAL",
@@ -492,14 +484,12 @@ fn create_subcreate_proxy_menu_item(
let now_proxy = group_data.now.as_deref().unwrap_or_default();
// Create proxy items
let group_items: Vec<CheckMenuItem<Wry>> = all_proxies
.iter()
.filter_map(|proxy_str| {
let is_selected = *proxy_str == now_proxy;
let item_id = format!("proxy_{}_{}", group_name, proxy_str);
// Get delay for display
let delay_text = proxy_nodes_data
.proxies
.get(proxy_str)
@@ -565,7 +555,6 @@ fn create_proxy_menu_item(
proxy_submenus: Vec<Submenu<Wry>>,
proxies_text: &str,
) -> Result<ProxyMenuItem> {
// 创建代理主菜单
let (proxies_submenu, inline_proxy_items) = if show_proxy_groups_inline {
(
None,
@@ -660,9 +649,7 @@ async fn create_tray_menu(
let profile_menu_items: Vec<CheckMenuItem<Wry>> = create_profile_menu_item(app_handle, profiles_preview)?;
// Pre-fetch all localized strings
let texts = MenuTexts::new();
// Convert to references only when needed
let profile_menu_items_refs: Vec<&dyn IsMenuItem<Wry>> = profile_menu_items
.iter()
.map(|item| item as &dyn IsMenuItem<Wry>)
@@ -842,7 +829,6 @@ async fn create_tray_menu(
let separator = &PredefinedMenuItem::separator(app_handle)?;
// 动态构建菜单项
let mut menu_items: Vec<&dyn IsMenuItem<Wry>> = vec![open_window, separator];
if show_outbound_modes_inline {
@@ -857,7 +843,6 @@ async fn create_tray_menu(
menu_items.extend_from_slice(&[separator, profiles]);
// 如果有代理节点,添加代理节点菜单
match tray_proxy_groups_display_mode {
"default" => {
menu_items.extend(proxies_menu.iter().map(|item| item as &dyn IsMenuItem<_>));
@@ -898,7 +883,6 @@ fn on_tray_icon_event(_tray_icon: &TrayIcon, tray_event: TrayIconEvent) {
..
} = tray_event
{
// 添加防抖检查,防止快速连击
#[allow(clippy::use_self)]
if !Tray::global().should_handle_tray_click() {
return;
@@ -942,12 +926,10 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
AsyncHandler::spawn(|| async move {
match event.id.as_ref() {
mode @ (MenuIds::RULE_MODE | MenuIds::GLOBAL_MODE | MenuIds::DIRECT_MODE) => {
// Removing the the "tray_" prefix and "_mode" suffix
if let Some(stripped) = mode.strip_prefix("tray_")
&& let Some(final_mode) = stripped.strip_suffix("_mode")
{
logging!(info, Type::ProxyMode, "Switch Proxy Mode To: {}", final_mode);
// 错误已在 change_clash_mode 内部记录,此处显式忽略返回值
let _ = feat::change_clash_mode(final_mode.into()).await;
}
}
@@ -1004,7 +986,6 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
feat::toggle_proxy_profile(profile_index.into()).await;
}
id if id.starts_with("proxy_") => {
// proxy_{group_name}_{proxy_name}
let rest = match id.strip_prefix("proxy_") {
Some(r) => r,
None => return,
@@ -1019,8 +1000,5 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
logging!(debug, Type::Tray, "Unhandled tray menu event: {:?}", event.id);
}
}
// We dont expected to refresh tray state here
// as the inner handle function (SHOULD) already takes care of it
});
}
+2 -12
View File
@@ -8,12 +8,9 @@ use std::time::Duration;
use tauri::async_runtime::JoinHandle;
use tauri_plugin_mihomo::models::WsConnectionId;
/// 托盘速率流异常后的重连间隔。
const TRAY_SPEED_RETRY_DELAY: Duration = Duration::from_secs(1);
/// 托盘速率流在此时间内收不到有效数据时,触发重连并降级到 0/0。
const TRAY_SPEED_STALE_TIMEOUT: Duration = Duration::from_secs(5);
/// macOS 托盘速率任务控制器。
#[derive(Clone)]
pub struct TraySpeedController {
speed_task: Arc<Mutex<Option<JoinHandle<()>>>>,
@@ -42,13 +39,11 @@ impl TraySpeedController {
}
}
/// 启动托盘速率采集后台任务(基于 `/traffic` WebSocket 流)。
fn start_task(&self) {
if handle::Handle::global().is_exiting() {
return;
}
// 关键步骤:托盘不可用时不启动速率任务,避免无效连接重试。
if !Self::has_main_tray() {
logging!(warn, Type::Tray, "托盘不可用,跳过启动托盘速率任务");
return;
@@ -111,7 +106,7 @@ impl TraySpeedController {
break;
}
// Stale 分支在内层 loop 中已重置为 0/0;此处兜底 Closed 分支(流被远端关闭)。
// `Stale` already reset the display; this covers remote close.
Self::apply_tray_speed(0, 0);
tokio::time::sleep(TRAY_SPEED_RETRY_DELAY).await;
}
@@ -122,17 +117,12 @@ impl TraySpeedController {
*guard = Some(task);
}
/// 停止托盘速率采集后台任务并清除速率显示。
fn stop_task(&self) {
// 取出任务句柄,与 speed_connection_id 一同传入清理任务。
let task = self.speed_task.lock().take();
let speed_connection_id = Arc::clone(&self.speed_connection_id);
AsyncHandler::spawn(move || async move {
// 关键步骤:先等待 abort 完成,再断开 WebSocket 连接。
// 若直接 abort 后立即 disconnect,任务可能已通过 take 取走 connection_id
// 但尚未完成断开,导致 connection_id 丢失、连接泄漏。
// await task handle 可保证原任务已退出,connection_id 不再被占用。
// Await abort before disconnect so the task cannot consume and lose the connection ID.
if let Some(task) = task {
task.abort();
let _ = task.await;
+10 -53
View File
@@ -34,8 +34,6 @@ impl SilentUpdater {
}
}
// ─── Disk Cache ───────────────────────────────────────────────────────────────
#[derive(Serialize, Deserialize)]
struct UpdateCacheMeta {
version: String,
@@ -95,10 +93,7 @@ impl SilentUpdater {
}
}
// ─── Version Comparison ───────────────────────────────────────────────────────
/// Returns true if version `a` <= version `b` using semver-like comparison.
/// Strips leading 'v', splits on '.', handles pre-release suffixes.
/// Compares numeric version components after stripping `v` and prerelease suffixes.
fn version_lte(a: &str, b: &str) -> bool {
let parse = |v: &str| -> Vec<u64> {
v.trim_start_matches('v')
@@ -127,12 +122,7 @@ fn version_lte(a: &str, b: &str) -> bool {
true // equal
}
/// Map the app's resolved UI language code to an NSIS installer language ID.
///
/// The Windows installer only ships SimpChinese, English and Russian
/// (`tauri.windows.conf.json` `nsis.languages`). Languages without a matching
/// NSIS translation fall back to English; Traditional Chinese ("zhtw") is
/// mapped to SimpChinese so Chinese users don't get an English installer.
/// Maps UI language to one of the three NSIS translations, defaulting to English.
#[cfg(target_os = "windows")]
fn nsis_language_id(app_language: &str) -> &'static str {
match app_language {
@@ -142,12 +132,8 @@ fn nsis_language_id(app_language: &str) -> &'static str {
}
}
// ─── Startup Install & Cache Management ─────────────────────────────────────
impl SilentUpdater {
/// Called at app startup. If a cached update exists and is newer than the current version,
/// attempt to install it immediately (before the main app initializes).
/// Returns true if install was triggered (app should relaunch), false otherwise.
/// Installs a newer cached update before normal startup, if the user confirms.
pub async fn try_install_on_startup(&self, app_handle: &tauri::AppHandle) -> bool {
let current_version = env!("CARGO_PKG_VERSION");
@@ -178,14 +164,12 @@ impl SilentUpdater {
current_version
);
// Ask user for confirmation — they can skip and use the app normally.
// The cache is preserved so next launch will ask again.
// Preserve the cache when skipped so the next launch asks again.
if !Self::ask_user_to_install(app_handle, cached_version).await {
logging!(info, Type::System, "User skipped update install, starting normally");
return false;
}
// Read cached bytes
let bytes = match Self::read_cache_bytes() {
Ok(b) => b,
Err(e) => {
@@ -199,14 +183,8 @@ impl SilentUpdater {
}
};
// Need a fresh Update object from the server to call install().
// This is a lightweight HTTP request (< 1s), not a re-download.
//
// The updater is built with the app's current language forwarded as
// `/LANG=<NSIS-lang-id>`. On Windows the NSIS installer parses this in
// `.onInit` (see `packages/windows/installer.nsi`) and sets `$LANGUAGE`
// directly, skipping its language-selection dialog so the update starts
// without prompting. Other platforms don't run an installer.
// Refresh metadata without re-downloading. Windows receives `/LANG` to suppress the
// NSIS language dialog; see `packages/windows/installer.nsi`.
let updater_builder = app_handle.updater_builder();
#[cfg(target_os = "windows")]
let updater_builder = {
@@ -245,8 +223,7 @@ impl SilentUpdater {
}
};
// Verify the server's version matches the cached version.
// If server now has a newer version, our cached bytes are stale.
// A changed server version invalidates the cached bytes.
if update.version != *cached_version {
logging!(
info,
@@ -262,11 +239,9 @@ impl SilentUpdater {
let version = update.version.clone();
logging!(info, Type::System, "Installing cached update v{version} at startup...");
// Show splash window so user knows the app is updating, not frozen
Self::show_update_splash(app_handle, &version);
// install() is sync and may hang (known bug #2558), so run with a timeout.
// On Windows, NSIS takes over the process so install() may never return — that's OK.
// `install()` may hang (#2558); on Windows NSIS can take over without returning.
let install_result = tokio::task::spawn_blocking({
let bytes = bytes.clone();
let update = update.clone();
@@ -305,7 +280,6 @@ impl SilentUpdater {
}
};
// Close splash window if install failed and app continues normally
if !success {
Self::close_update_splash(app_handle);
}
@@ -314,11 +288,7 @@ impl SilentUpdater {
}
}
// ─── User Confirmation Dialog ────────────────────────────────────────────────
impl SilentUpdater {
/// Show a native dialog asking the user to install or skip the update.
/// Returns true if user chose to install, false if they chose to skip.
async fn ask_user_to_install(app_handle: &tauri::AppHandle, version: &str) -> bool {
use tauri_plugin_dialog::{DialogExt as _, MessageDialogButtons, MessageDialogKind};
@@ -343,12 +313,8 @@ impl SilentUpdater {
}
}
// ─── Update Splash Window ────────────────────────────────────────────────────
impl SilentUpdater {
/// Show a small centered splash window indicating update is being installed.
/// Injects HTML via eval() after window creation so it doesn't depend on any
/// external file in the bundle.
/// Uses injected HTML so the splash has no bundled-file dependency.
fn show_update_splash(app_handle: &tauri::AppHandle, version: &str) {
use tauri::{WebviewUrl, WebviewWindowBuilder};
@@ -405,7 +371,7 @@ impl SilentUpdater {
"#
);
// Retry eval a few times — the webview may not be ready immediately
// The new webview may not accept evaluation immediately.
std::thread::spawn(move || {
for i in 0..10 {
std::thread::sleep(std::time::Duration::from_millis(100 * (i + 1)));
@@ -418,7 +384,6 @@ impl SilentUpdater {
logging!(info, Type::System, "Update splash window shown");
}
/// Close the update splash window (e.g. after install failure).
fn close_update_splash(app_handle: &tauri::AppHandle) {
use tauri::Manager as _;
if let Some(window) = app_handle.get_webview_window("update-splash") {
@@ -428,8 +393,6 @@ impl SilentUpdater {
}
}
// ─── Background Check and Download ───────────────────────────────────────────
impl SilentUpdater {
async fn check_and_download(&self, app_handle: &tauri::AppHandle) -> Result<()> {
let is_portable = *dirs::PORTABLE_FLAG.get().unwrap_or(&false);
@@ -535,8 +498,6 @@ impl SilentUpdater {
mod tests {
use super::*;
// ─── version_lte tests ──────────────────────────────────────────────────
#[test]
fn test_version_equal() {
assert!(version_lte("2.4.7", "2.4.7"));
@@ -565,10 +526,8 @@ mod tests {
#[test]
fn test_version_with_prerelease() {
// "2.4.8-alpha" → numeric part is still "2.4.8"
assert!(version_lte("2.4.7", "2.4.8-alpha"));
assert!(version_lte("2.4.8-alpha", "2.4.8"));
// Both have same numeric part, so equal → true
assert!(version_lte("2.4.8-alpha", "2.4.8-beta"));
}
@@ -579,8 +538,6 @@ mod tests {
assert!(version_lte("2.4.0", "2.4"));
}
// ─── Cache metadata tests ───────────────────────────────────────────────
#[test]
fn test_cache_meta_serialize_roundtrip() {
let meta = UpdateCacheMeta {
+4 -33
View File
@@ -133,16 +133,13 @@ impl CoreConfigValidator {
}
impl CoreConfigValidator {
/// 检查文件是否为脚本文件
async fn is_script_file(path: &str) -> Result<bool> {
// 1. 先通过扩展名快速判断
if has_ext(path, "yaml") || has_ext(path, "yml") {
return Ok(false); // YAML文件不是脚本文件
return Ok(false);
} else if has_ext(path, "js") {
return Ok(true); // JS文件是脚本文件
return Ok(true);
}
// 2. 读取文件内容
let content = match fs::read_to_string(path).await {
Ok(content) => content,
Err(err) => {
@@ -151,13 +148,11 @@ impl CoreConfigValidator {
}
};
// 3. 检查是否存在明显的YAML特征
let has_yaml_features = content.contains(": ")
|| content.contains("#")
|| content.contains("---")
|| content.lines().any(|line| line.trim().starts_with("- "));
// 4. 检查是否存在明显的JS特征
let has_js_features = content.contains("function ")
|| content.contains("const ")
|| content.contains("let ")
@@ -168,16 +163,11 @@ impl CoreConfigValidator {
|| content.contains("export ")
|| content.contains("import ");
// 5. 决策逻辑
if has_yaml_features && !has_js_features {
// 只有YAML特征,没有JS特征
return Ok(false);
} else if has_js_features && !has_yaml_features {
// 只有JS特征,没有YAML特征
return Ok(true);
} else if has_yaml_features && has_js_features {
// 两种特征都有,需要更精细判断
// 优先检查是否有明确的JS结构特征
if content.contains("function main")
|| content.contains("module.exports")
|| content.contains("export default")
@@ -185,24 +175,21 @@ impl CoreConfigValidator {
return Ok(true);
}
// 检查冒号后是否有空格(YAML的典型特征)
let yaml_pattern_count = content.lines().filter(|line| line.contains(": ")).count();
if yaml_pattern_count > 2 {
return Ok(false); // 多个键值对格式,更可能是YAML
return Ok(false);
}
}
// 默认情况:无法确定时,假设为非脚本文件(更安全)
// Unknown files take the safer YAML validation path.
logging!(debug, Type::Validate, "无法确定文件类型,默认当作YAML处理: {}", path);
Ok(false)
}
/// 只进行文件语法检查,不进行完整验证
async fn validate_file_syntax_outcome(config_path: &str) -> Result<ValidationOutcome> {
logging!(info, Type::Validate, "开始检查文件: {}", config_path);
// 读取文件内容
let content = match fs::read_to_string(config_path).await {
Ok(content) => content,
Err(err) => {
@@ -211,7 +198,6 @@ impl CoreConfigValidator {
return Ok(ValidationOutcome::invalid_from_message(error_msg));
}
};
// 对YAML文件尝试解析,只检查语法正确性
logging!(info, Type::Validate, "进行YAML语法检查");
match serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&content) {
Ok(_) => {
@@ -226,9 +212,7 @@ impl CoreConfigValidator {
}
}
/// 验证脚本文件语法
async fn validate_script_file_outcome(path: &str) -> Result<ValidationOutcome> {
// 读取脚本内容
let content = match fs::read_to_string(path).await {
Ok(content) => content,
Err(err) => {
@@ -240,7 +224,6 @@ impl CoreConfigValidator {
logging!(debug, Type::Validate, "验证脚本文件: {}", path);
// 使用boa引擎进行基本语法检查
use boa_engine::{Context, Source};
let mut context = Context::default();
@@ -258,7 +241,6 @@ impl CoreConfigValidator {
Ok(_) => {
logging!(debug, Type::Validate, "脚本语法验证通过: {}", path);
// 检查脚本是否包含main函数
if !content.contains("function main")
&& !content.contains("const main")
&& !content.contains("let main")
@@ -278,12 +260,10 @@ impl CoreConfigValidator {
}
}
/// 验证指定的配置文件
pub async fn validate_config_file_outcome(
config_path: &str,
is_merge_file: Option<bool>,
) -> Result<ValidationOutcome> {
// 检查程序是否正在退出,如果是则跳过验证
if handle::Handle::global().is_exiting() {
logging!(info, Type::Core, "应用正在退出,跳过验证");
return Ok(ValidationOutcome::Skipped {
@@ -291,13 +271,11 @@ impl CoreConfigValidator {
});
}
// 检查文件是否存在
if !std::path::Path::new(config_path).exists() {
let error_msg: String = format!("File not found: {config_path}").into();
return Ok(ValidationOutcome::invalid_from_message(error_msg));
}
// 如果是合并文件且不是强制验证,执行语法检查但不进行完整验证
if is_merge_file.unwrap_or(false) {
logging!(info, Type::Validate, "检测到Merge文件,仅进行语法检查: {}", config_path);
return Self::validate_file_syntax_outcome(config_path).await;
@@ -306,7 +284,6 @@ impl CoreConfigValidator {
let is_script = match Self::is_script_file(config_path).await {
Ok(result) => result,
Err(err) => {
// 如果无法确定文件类型,尝试使用Clash内核验证
logging!(warn, Type::Validate, "无法确定文件类型: {}, 错误: {}", config_path, err);
return Self::validate_config_internal_outcome(config_path).await;
}
@@ -322,14 +299,11 @@ impl CoreConfigValidator {
return Self::validate_script_file_outcome(config_path).await;
}
// 对YAML配置文件使用Clash内核验证
logging!(info, Type::Validate, "使用Clash内核验证配置文件: {}", config_path);
Self::validate_config_internal_outcome(config_path).await
}
/// 内部验证配置文件的实现
async fn validate_config_internal_outcome(config_path: &str) -> Result<ValidationOutcome> {
// 检查程序是否正在退出,如果是则跳过验证
if handle::Handle::global().is_exiting() {
logging!(info, Type::Validate, "应用正在退出,跳过验证");
return Ok(ValidationOutcome::Skipped {
@@ -347,7 +321,6 @@ impl CoreConfigValidator {
let app_dir_str = dirs::path_to_str(&app_dir)?;
logging!(info, Type::Validate, "验证目录: {}", app_dir_str);
// 使用子进程运行clash验证配置
let command = app_handle.shell().sidecar(clash_core.as_str()).map_err(|error| {
anyhow::anyhow!("failed to build validation command for core {clash_core:?}: {error:#}")
})?;
@@ -363,7 +336,6 @@ impl CoreConfigValidator {
let stderr = &output.stderr;
let stdout = &output.stdout;
// 检查进程退出状态和错误输出
let error_keywords = ["FATA", "fatal", "Parse config error", "level=fatal"];
let has_error = !status.success() || contains_any_keyword(stderr, &error_keywords);
@@ -399,7 +371,6 @@ impl CoreConfigValidator {
}
}
/// 验证运行时配置
pub async fn validate_config_outcome(&self) -> Result<ValidationOutcome> {
if !self.try_start() {
logging!(info, Type::Validate, "验证已在进行中,跳过新的验证请求");