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");
}