Compare commits

...
29 Commits
Author SHA1 Message Date
Tunglies c8a8d2034c refactor(deps): replace once_cell with std OnceLock and LazyLock 2026-10-01 14:34:20 +08:00
Tunglies f17ccdc227 refactor(core): replace macOS network monitor slot with armed latch 2026-10-01 14:34:19 +08:00
Tunglies 92303ce60d refactor(port): store startup block reason in a OnceLock 2026-10-01 14:34:19 +08:00
Tunglies ecd60d317a refactor(service): drop redundant provider sync serial lock 2026-10-01 14:34:19 +08:00
Tunglies c2b6c0378e refactor(port): fold startup-core-blocked flag into reason slot 2026-10-01 14:34:19 +08:00
Tunglies adbe3ffec4 refactor(notify): fold sequence counter into entries lock 2026-10-01 14:34:19 +08:00
Tunglies a146d78b9f refactor(updater): drop write-only pending_* slots 2026-10-01 14:34:19 +08:00
Tunglies 1552f8e2f9 fix(events): close run-state race and restore single error toasts
Self-review findings: the bus now re-reads the run-state snapshot in
onSubscribed so an event racing the store's initial read cannot leave a
stale snapshot (the ordering the old layout listener guaranteed), and the
patch hooks pass errorNotice:false so GuardState/page handlers remain the
only error toast, matching the pre-migration behavior.
2026-10-01 14:34:17 +08:00
Tunglies 70d1298bc9 docs: add frontend architecture guardrails for src
Layering rules for the contract flow: generated contract as the only
wire-typing source, event bus as the only listen/emit site, pure-reducer
store for event-derived state, the mutate funnel for user intent, and
invoke only in the services layer — each backed by the CI gates.
2026-10-01 14:34:17 +08:00
Tunglies 42ec30633b refactor(proxies): route proxy/home/misc commands through the mutate funnel
Ports mode switching (page and home card), chain runtime updates, node
selection with tray sync, selection recording, provider updates and
syncs, and lightweight-mode entry onto the funnel; every site keeps its
existing optimistic/revert and error-handling behavior.
2026-10-01 14:34:17 +08:00
Tunglies 4a6f0da237 refactor(profiles): route profile operations through the mutate funnel
Ports profile create/import/reorder/delete/update/patch/save-file and
enhance calls onto the funnel; retry and editor flows keep their own
error handling with errorNotice:false. Per-uid ids keep the update
worker pool concurrent under the funnel's in-flight dedupe.
2026-10-01 14:34:17 +08:00
Tunglies 3e91458799 refactor(settings): route settings-domain commands through the mutate funnel
Ports port saving, webdav/local backup operations, core change/restart/
upgrade, service install/uninstall/repair flows, the system-proxy toggle
queue, the DNS override toggle, and app lifecycle commands onto the single
funnel. Bespoke flows keep their own error handling via errorNotice:false;
simple flows gain the funnel's default error toast and revalidation.
2026-10-01 14:34:17 +08:00
Tunglies 763338dade feat(mutate): single funnel for user-intent commands and invoke gate
Adds src/services/mutate.ts: one path for optimistic apply, services-layer
invoke, Busy handling, failure rollback, and the error toast, with busy
bookkeeping mirrored into the app store. The patch hooks (verge, clash,
profiles) now route through it. Moves the remaining direct invokes
(unlock ×3, DNS ×4) into cmds.ts and turns on the invoke-only-in-services
architecture gate in CI.
2026-10-01 14:34:17 +08:00
Tunglies 5b53c32de1 refactor(notice): make the notice table exhaustive and drop dead wire entries
D5 cleanup, frontend and backend in one commit: removes the six
config_validate::* statuses that never receive a backend send and the
set_config::ok send (enum variants, golden list 41→34, send point in
restart_clash_core), their frontend handlers, and the five i18n keys only
those handlers used. The notice table is now typed as a Record over the
generated NoticeStatus union, so a status without a frontend entry fails
to compile. The info status (sent by the silent updater for breaking
change notices, previously dropped with a console warning) now shows an
info toast — the one deliberate behavior delta.
2026-10-01 14:34:17 +08:00
Tunglies 43cf001e68 feat(events): route all backend events through a single event bus and store
Adds src/services/bus (the only listen/emit site: one handler per contract
event plus the frontend-internal test-all event) and the React
context/reducer app store. Migrates the five scattered subscriptions
(layout events, pending failures, proxy refresh, profile update/timer,
test-all), deletes the old glue (events.ts, use-listen, use-layout-events,
LoadingCacheProvider), moves run state into the store, and adds an
architecture gate script wired into CI. Behavior is unchanged; the
run-state query's poll/focus safety net is preserved by the store
provider.
2026-10-01 14:34:17 +08:00
Tunglies 5bf0de0d0b feat(contract): export wire contract from backend and generate frontend types
Adds a zero-dependency `frontend-contract` bin that serializes the real
NoticeStatus variants and FrontendEvent payloads, scripts/gen-contract.mjs
which emits the committed src/services/contract.ts, and a CI job that
regenerates it and fails on a non-empty diff. events.ts now derives its
event map from the generated contract instead of hand-typed shapes.
2026-10-01 14:34:17 +08:00
Tunglies 96d68b057a chore(core): document watcher exit conditions 2026-10-01 14:34:16 +08:00
Tunglies 917d97f335 docs(backend): record dead wire contract entries 2026-10-01 14:34:16 +08:00
Tunglies 5364468ad4 test(feat): freeze representative effect registry mappings 2026-10-01 14:34:16 +08:00
Tunglies 866899593e ci(backend): add architecture ban gates 2026-10-01 14:34:16 +08:00
Tunglies 079414253e refactor(core): complete bounded service retry migration 2026-10-01 14:34:16 +08:00
Tunglies 6de4df8c9f refactor(core): coalesce burst refresh announcements 2026-10-01 14:34:16 +08:00
Tunglies 86605f197d docs: add src-tauri architecture guardrails 2026-10-01 14:34:16 +08:00
Tunglies 5375ce360f refactor(utils): migrate remaining bounded retry loops 2026-10-01 14:34:16 +08:00
Tunglies 9d1b400299 refactor(core): fold tray, hotkey, autostart updates into effect ensures 2026-10-01 14:34:16 +08:00
Tunglies 7aed7be2f1 refactor(core): derive refresh announcements from transaction commit 2026-10-01 14:34:16 +08:00
Tunglies 438f6f7461 refactor(feat): declarative effect registry for verge and clash patches 2026-10-01 14:34:16 +08:00
Tunglies edcd76f27d refactor(utils): unified retry and strategy-list helpers 2026-10-01 14:34:16 +08:00
Tunglies 7eb24d8c69 refactor(core): type notice statuses behind the frozen wire contract 2026-10-01 14:34:16 +08:00
149 changed files with 3973 additions and 1835 deletions
+26
View File
@@ -0,0 +1,26 @@
name: Backend Guardrails
on:
pull_request:
paths:
- "src-tauri/**"
- ".github/workflows/backend-guardrails.yml"
workflow_dispatch:
permissions:
contents: read
jobs:
banned-patterns:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- name: No Handle::refresh calls in feat
run: '! grep -rn "Handle::refresh" src-tauri/src/feat'
- name: No notice_message outside core/notify
run: '! grep -rn "notice_message(" src-tauri/src --include="*.rs" | grep -v "core/notify"'
- name: No manual update-flag chains
run: '! grep -rnE "determine_update_flags|UpdateFlags" src-tauri/src'
+79
View File
@@ -85,3 +85,82 @@ jobs:
- name: Run Knip - name: Run Knip
if: steps.check_frontend.outputs.frontend == 'true' if: steps.check_frontend.outputs.frontend == 'true'
run: pnpm knip:check run: pnpm knip:check
- name: Architecture gates (listen/emit only in the event bus, invoke only in services)
if: steps.check_frontend.outputs.frontend == 'true'
run: node scripts/check-architecture.mjs listen emit invoke
contract-parity:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v7
- name: Check contract inputs
id: check_inputs
uses: dorny/paths-filter@v4
with:
filters: |
contract:
- 'src/services/contract.ts'
- 'scripts/gen-contract.mjs'
- 'src-tauri/src/core/notify/**'
- 'src-tauri/src/bin/**'
- 'src-tauri/src/lib.rs'
- '.github/workflows/frontend-check.yml'
- name: Skip if contract inputs unchanged
if: steps.check_inputs.outputs.contract != 'true'
run: echo "No contract inputs changed, skipping parity check."
- name: Install Rust Stable
if: steps.check_inputs.outputs.contract == 'true'
uses: dtolnay/rust-toolchain@master
with:
toolchain: stable
- name: Rust Cache
if: steps.check_inputs.outputs.contract == 'true'
uses: Swatinem/rust-cache@v2
with:
prefix-key: 'v1-rust'
key: 'rust-shared-stable-ubuntu-22.04-x86_64-unknown-linux-gnu-contract'
workspaces: |
. -> target
cache-all-crates: true
cache-workspace-crates: true
- name: Install dependencies
if: steps.check_inputs.outputs.contract == 'true'
run: |
sudo apt-get update
sudo apt-get install -y libxslt1.1 libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev patchelf
- name: Install pnpm
if: steps.check_inputs.outputs.contract == 'true'
uses: pnpm/action-setup@v6
with:
run_install: false
- uses: actions/setup-node@v7
if: steps.check_inputs.outputs.contract == 'true'
with:
node-version: '24.21.0'
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
if: steps.check_inputs.outputs.contract == 'true'
- name: Provision sidecar placeholders for tauri-build
if: steps.check_inputs.outputs.contract == 'true'
run: |
mkdir -p src-tauri/sidecar src-tauri/resources dist
touch dist/index.html
for bin in clash-verge-service clash-verge-service-install clash-verge-service-uninstall verge-mihomo verge-mihomo-alpha; do
touch "src-tauri/sidecar/${bin}-x86_64-unknown-linux-gnu"
done
- name: Regenerate contract and require empty diff
if: steps.check_inputs.outputs.contract == 'true'
run: |
pnpm gen:contract
git diff --exit-code -- src/services/contract.ts
Generated
-1
View File
@@ -1114,7 +1114,6 @@ dependencies = [
"objc2", "objc2",
"objc2-app-kit", "objc2-app-kit",
"objc2-foundation", "objc2-foundation",
"once_cell",
"open", "open",
"parking_lot", "parking_lot",
"percent-encoding", "percent-encoding",
+2 -1
View File
@@ -17,7 +17,8 @@
"ignoreBinaries": ["rustc", "cc"], "ignoreBinaries": ["rustc", "cc"],
"ignoreDependencies": ["lint-staged"], "ignoreDependencies": ["lint-staged"],
"ignoreIssues": { "ignoreIssues": {
"src/types/generated/**": ["exports", "types"] "src/types/generated/**": ["exports", "types"],
"src/services/contract.ts": ["exports", "types"]
}, },
"cycles": { "cycles": {
"dynamicImports": true "dynamicImports": true
+2
View File
@@ -30,6 +30,8 @@
"i18n:check": "node scripts/cleanup-unused-i18n.mjs", "i18n:check": "node scripts/cleanup-unused-i18n.mjs",
"i18n:format": "node scripts/cleanup-unused-i18n.mjs --align --apply", "i18n:format": "node scripts/cleanup-unused-i18n.mjs --align --apply",
"i18n:types": "node scripts/generate-i18n-keys.mjs", "i18n:types": "node scripts/generate-i18n-keys.mjs",
"gen:contract": "node scripts/gen-contract.mjs",
"arch:check": "node scripts/check-architecture.mjs listen emit invoke",
"typecheck": "tsc --noEmit", "typecheck": "tsc --noEmit",
"test": "vitest run", "test": "vitest run",
"test:watch": "vitest", "test:watch": "vitest",
+84
View File
@@ -0,0 +1,84 @@
import fs from 'node:fs'
import path from 'node:path'
/**
* Architecture grep gates for the frontend contract flow. Select gates via
* argv:
*
* node scripts/check-architecture.mjs listen emit invoke
*
* - listen/emit: the Tauri event API may only be used under src/services/bus/**
* (the event bus). Detected as a bare `listen(`/`emit(` call (member calls
* like `this.emit(` are unrelated class methods) or as importing the name
* from '@tauri-apps/api/event'.
* - invoke: `invoke(` calls may exist only under src/services/**.
*/
const ROOT = path.resolve(import.meta.dirname, '..')
const SRC = path.join(ROOT, 'src')
const tauriEventImport = (name) =>
new RegExp(
`import\\s*\\{[^}]*\\b${name}\\b[^}]*\\}\\s*from\\s*'@tauri-apps/api/event'`,
)
const GATES = {
listen: {
patterns: [/(?<![.\w])listen\(/, tauriEventImport('listen')],
allowed: (file) => file.startsWith('src/services/bus/'),
description: 'Tauri listen outside the event bus (src/services/bus)',
},
emit: {
patterns: [/(?<![.\w])emit\(/, tauriEventImport('emit')],
allowed: (file) => file.startsWith('src/services/bus/'),
description: 'Tauri emit outside the event bus (src/services/bus)',
},
invoke: {
patterns: [/\binvoke\(/],
allowed: (file) => file.startsWith('src/services/'),
description: 'invoke( outside the services layer (src/services)',
},
}
const walk = (dir) => {
const entries = fs.readdirSync(dir, { withFileTypes: true })
return entries.flatMap((entry) => {
const full = path.join(dir, entry.name)
if (entry.isDirectory()) return walk(full)
return /\.(ts|tsx|js|jsx|mts|mjs)$/.test(entry.name) ? [full] : []
})
}
const selected = process.argv.slice(2)
if (selected.length === 0) {
console.error('usage: check-architecture.mjs <gate>... (listen|emit|invoke)')
process.exit(2)
}
let violations = 0
for (const gate of selected) {
const rule = GATES[gate]
if (!rule) {
console.error(`unknown gate: ${gate}`)
process.exit(2)
}
for (const file of walk(SRC)) {
const relative = path.relative(ROOT, file).replaceAll('\\', '/')
if (rule.allowed(relative)) continue
const lines = fs.readFileSync(file, 'utf8').split('\n')
lines.forEach((line, index) => {
if (rule.patterns.some((pattern) => pattern.test(line))) {
violations += 1
console.error(
`[arch] ${rule.description}: ${relative}:${index + 1}: ${line.trim()}`,
)
}
})
}
}
if (violations > 0) {
console.error(`[arch] ${violations} violation(s) found`)
process.exit(1)
}
console.log('[arch] no violations')
+91
View File
@@ -0,0 +1,91 @@
import { execFileSync } from 'node:child_process'
import fs from 'node:fs'
import path from 'node:path'
/**
* Regenerates src/services/contract.ts from the backend wire contract.
* Source of truth: `cargo run -p clash-verge --bin frontend-contract` inside
* src-tauri, which serializes the same enum variants and event payloads the
* app emits at runtime. CI reruns this and fails on a non-empty diff.
*/
const ROOT = path.resolve(import.meta.dirname, '..')
const OUT = path.join(ROOT, 'src/services/contract.ts')
const contract = JSON.parse(
execFileSync(
'cargo',
['run', '-p', 'clash-verge', '--bin', 'frontend-contract', '-q'],
{
cwd: path.join(ROOT, 'src-tauri'),
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
},
),
)
if (contract.version !== 1) {
throw new Error(`unsupported wire contract version: ${contract.version}`)
}
/** TS type per event, derived from the serialized sample payload's JSON shape. */
const payloadType = (name, sample) => {
if (sample === null) return 'null'
if (typeof sample === 'string') return 'string'
if (Array.isArray(sample)) {
if (name === 'verge://notice-message') return '[NoticeStatus, string]'
throw new Error(`unexpected array payload for ${name}`)
}
if (typeof sample === 'object') {
const keys = Object.keys(sample)
if (keys.length === 1 && keys[0] === 'uid') return '{ uid: string }'
if (name === 'verge://run-state-changed') return 'RunState'
throw new Error(`unexpected object payload for ${name}: ${keys.join(',')}`)
}
throw new Error(`unexpected payload for ${name}`)
}
const needsRunState = contract.events.some(
(e) => e.name === 'verge://run-state-changed',
)
if (!needsRunState)
throw new Error('run-state-changed event missing from contract')
const lines = []
lines.push(
'// @generated by scripts/gen-contract.mjs from the backend wire contract. DO NOT EDIT.',
)
lines.push('// Regen: pnpm gen:contract')
lines.push('')
lines.push("import type { RunState } from './cmds'")
lines.push('')
lines.push(
'/** Wire status strings from NoticeStatus; keep in sync via `pnpm gen:contract`. */',
)
lines.push('export type NoticeStatus =')
for (const status of contract.noticeStatuses) {
lines.push(` | ${JSON.stringify(status)}`)
}
lines.push('')
lines.push('/** Event name → payload type for every backend-emitted event. */')
lines.push('export interface VergeEventPayloads {')
for (const event of contract.events) {
const key = JSON.stringify(event.name)
lines.push(` ${key}: ${payloadType(event.name, event.sample)}`)
}
lines.push('}')
lines.push('')
const content = `${lines.join('\n')}\n`
fs.writeFileSync(OUT, content)
// Match the repo's biome style so CI parity (`git diff --exit-code`) is stable.
execFileSync(
process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm',
['exec', 'biome', 'format', '--write', path.relative(ROOT, OUT)],
{ cwd: ROOT, stdio: 'ignore' },
)
console.log(
`[gen-contract] wrote ${path.relative(ROOT, OUT)}: ${contract.events.length} events, ${contract.noticeStatuses.length} statuses`,
)
+38
View File
@@ -0,0 +1,38 @@
# Backend Architecture Guardrails
These rules supplement the repository's root `AGENTS.md`.
1. **Keep configuration ownership in `config`.** Configuration writes must use
its draft and persistence APIs. Patch orchestration must use
`feat/effects.rs` and `feat/executor.rs`; refresh notifications must use
`core::notify::announce` after successful persistence and commit. This keeps
failed transactions from publishing state. Independent transactions retain
their boundaries and announce via `after_commit`; runtime-only profile
activation announces after successful application. New cross-layer
exceptions require a rationale in the PR and an update to this file.
2. **Register every new `IVerge` field.** Add one row, including an explicit
`NoEffect` where appropriate, to the exhaustive registry and preserve its
platform attributes. Keep the serialized-field coverage test passing. Manual
field-to-flag chains hide missing effects and are forbidden. No exceptions.
3. **Use `utils::retry` for bounded retries.** Do not introduce handwritten retry
loops, including `loop` plus `sleep`; preserve attempt budgets, delays and
terminal errors. Permanent watchers are the exception and must document
their exit conditions. Traversal of distinct data or port candidates is not
a retry policy.
4. **Keep notifications typed.** Send notice statuses through `NoticeStatus` and
use `Arc<str>` for notice message payloads. Preserve the event names and
status strings pinned by the golden tests. Status additions or changes
require frontend and backend changes in the same PR and an updated golden
list; this protects the wire contract. No exceptions.
5. **Preserve lock order.** The order is `config_write` before
`config_update_in_progress` before `lifecycle_lock`. Patch callers must use
the executor's guarded claim instead of independently combining these locks;
this preserves Busy rejection and prevents inverted acquisition. Existing
lifecycle and independent port transactions keep their established locking
boundaries. A new lock requires registering its position in this rule before
introducing acquisition sites.
6. **Prefer reconciliation.** Express new effects as idempotent `ensure`
operations in `EFFECT_ORDER` so repeated application converges on the same
state. A trigger chain is an exception only with a code comment explaining
why the operation cannot be idempotent. Configuration rollback does not
authorize reverse OS effects.
-1
View File
@@ -66,7 +66,6 @@ dunce = "1.0.5"
nanoid = "0.5" nanoid = "0.5"
chrono = { workspace = true } chrono = { workspace = true }
boa_engine = "0.22.0" boa_engine = "0.22.0"
once_cell = { version = "1.21.4", features = ["parking_lot"] }
percent-encoding = "2.3.2" percent-encoding = "2.3.2"
reqwest = { workspace = true } reqwest = { workspace = true }
regex = { workspace = true } regex = { workspace = true }
+8
View File
@@ -0,0 +1,8 @@
//! Prints the frontend wire contract as JSON to stdout. Zero new dependencies:
//! the payload is derived from the same serializers the app uses at runtime.
//! Consumed by scripts/gen-contract.mjs; CI regenerates and diffs the committed
//! TypeScript artifact.
fn main() {
println!("{}", app_lib::frontend_wire_contract());
}
+4 -3
View File
@@ -1,4 +1,5 @@
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error}; use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
use crate::core::notify::NoticeStatus;
use crate::feat; use crate::feat;
use crate::utils::{dirs, yaml_emitter}; use crate::utils::{dirs, yaml_emitter};
use crate::{ use crate::{
@@ -56,14 +57,14 @@ pub async fn change_clash_core(clash_core: String) -> CmdResult<Option<CommandFa
match CoreManager::global().restart_core().await { match CoreManager::global().restart_core().await {
Ok(_) => { Ok(_) => {
handle::Handle::notice_message("config_core::change_success", clash_core); handle::Handle::notice(NoticeStatus::ConfigCoreChangeSuccess, clash_core.as_str());
handle::Handle::refresh_clash(); handle::Handle::refresh_clash();
Ok(None) Ok(None)
} }
Err(err) => { Err(err) => {
let failed = err.context("core changed but failed to restart"); let failed = err.context("core changed but failed to restart");
let error_msg: String = format!("{failed:#}").into(); let error_msg: String = format!("{failed:#}").into();
handle::Handle::notice_message("config_core::change_error", error_msg.clone()); handle::Handle::notice(NoticeStatus::ConfigCoreChangeError, error_msg.as_str());
logging!(error, Type::Core, "core changed but failed to restart: {error_msg}"); logging!(error, Type::Core, "core changed but failed to restart: {error_msg}");
Ok(Some(proxy_aware_coded_error(&failed, "CORE_CHANGE_FAILED"))) Ok(Some(proxy_aware_coded_error(&failed, "CORE_CHANGE_FAILED")))
} }
@@ -72,7 +73,7 @@ pub async fn change_clash_core(clash_core: String) -> CmdResult<Option<CommandFa
Err(err) => { Err(err) => {
let error_msg: String = format!("{err:#}").into(); let error_msg: String = format!("{err:#}").into();
logging!(error, Type::Core, "failed to change core: {error_msg}"); logging!(error, Type::Core, "failed to change core: {error_msg}");
handle::Handle::notice_message("config_core::change_error", error_msg); handle::Handle::notice(NoticeStatus::ConfigCoreChangeError, error_msg.as_str());
Ok(Some(proxy_aware_coded_error(&err, "CORE_CHANGE_FAILED"))) Ok(Some(proxy_aware_coded_error(&err, "CORE_CHANGE_FAILED")))
} }
} }
+1 -1
View File
@@ -1,4 +1,4 @@
use crate::module::lightweight; use crate::core::lightweight;
use super::CmdResult; use super::CmdResult;
+2 -1
View File
@@ -1,6 +1,7 @@
use super::{CmdResult, StringifyErr as _, WithErrorCode as _, coded_error}; use super::{CmdResult, StringifyErr as _, WithErrorCode as _, coded_error};
use crate::cmd::validate::{ValidationNoticeTarget, handle_validation_notice}; use crate::cmd::validate::{ValidationNoticeTarget, handle_validation_notice};
use crate::config::profiles; use crate::config::profiles;
use crate::core::notify::NoticeStatus;
use crate::utils::window_manager::WindowManager; use crate::utils::window_manager::WindowManager;
use crate::{ use crate::{
config::{ config::{
@@ -282,7 +283,7 @@ async fn handle_update_error<E: std::fmt::Display>(
logging!(warn, Type::Cmd, "更新过程发生错误: {}", e,); logging!(warn, Type::Cmd, "更新过程发生错误: {}", e,);
discard_and_restore(current_profile).await?; discard_and_restore(current_profile).await?;
let message: String = e.to_string().into(); let message: String = e.to_string().into();
handle::Handle::notice_message("config_validate::boot_error", message.clone()); handle::Handle::notice(NoticeStatus::ConfigValidateBootError, message.as_str());
Ok(ValidationOutcome::invalid_from_message(message)) Ok(ValidationOutcome::invalid_from_message(message))
} }
+1
View File
@@ -84,6 +84,7 @@ pub async fn sync_tray_proxy_selection() -> CmdResult<()> {
} }
async fn run_tray_sync_loop() { async fn run_tray_sync_loop() {
// Permanent watcher: keeps syncing until a pass finds no pending sync request.
loop { loop {
match Tray::global().update_menu().await { match Tray::global().update_menu().await {
Ok(_) => { Ok(_) => {
+1 -1
View File
@@ -3,11 +3,11 @@ use crate::{
cmd::StringifyErr as _, cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice}, cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, PrfItem}, config::{Config, IProfiles, PrfItem},
core::auto_backup::{AutoBackupManager, AutoBackupTrigger},
core::{ core::{
CoreManager, handle, CoreManager, handle,
validate::{CoreConfigValidator, ValidationOutcome}, validate::{CoreConfigValidator, ValidationOutcome},
}, },
module::auto_backup::{AutoBackupManager, AutoBackupTrigger},
utils::dirs, utils::dirs,
}; };
use clash_verge_logging::{Type, logging, logging_error}; use clash_verge_logging::{Type, logging, logging_error};
+17 -16
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use crate::core::{ use crate::core::{
handle, handle,
validate::{ValidationErrorKind, ValidationOutcome}, validate::{ValidationErrorKind, ValidationOutcome},
@@ -11,27 +12,27 @@ pub enum ValidationNoticeTarget {
Script, Script,
} }
const fn notice_key(kind: ValidationErrorKind, target: ValidationNoticeTarget) -> &'static str { const fn notice_key(kind: ValidationErrorKind, target: ValidationNoticeTarget) -> NoticeStatus {
match kind { match kind {
ValidationErrorKind::FileMissing => "config_validate::file_not_found", ValidationErrorKind::FileMissing => NoticeStatus::ConfigValidateFileNotFound,
ValidationErrorKind::FileRead => match target { ValidationErrorKind::FileRead => match target {
ValidationNoticeTarget::Script => "config_validate::script_error", ValidationNoticeTarget::Script => NoticeStatus::ConfigValidateScriptError,
_ => "config_validate::yaml_read_error", _ => NoticeStatus::ConfigValidateYamlReadError,
}, },
ValidationErrorKind::YamlSyntax => match target { ValidationErrorKind::YamlSyntax => match target {
ValidationNoticeTarget::Merge => "config_validate::merge_syntax_error", ValidationNoticeTarget::Merge => NoticeStatus::ConfigValidateMergeSyntaxError,
ValidationNoticeTarget::Script => "config_validate::script_error", ValidationNoticeTarget::Script => NoticeStatus::ConfigValidateScriptError,
ValidationNoticeTarget::Runtime => "config_validate::yaml_syntax_error", ValidationNoticeTarget::Runtime => NoticeStatus::ConfigValidateYamlSyntaxError,
}, },
ValidationErrorKind::YamlMapping => match target { ValidationErrorKind::YamlMapping => match target {
ValidationNoticeTarget::Merge => "config_validate::merge_mapping_error", ValidationNoticeTarget::Merge => NoticeStatus::ConfigValidateMergeMappingError,
ValidationNoticeTarget::Script => "config_validate::script_error", ValidationNoticeTarget::Script => NoticeStatus::ConfigValidateScriptError,
ValidationNoticeTarget::Runtime => "config_validate::yaml_mapping_error", ValidationNoticeTarget::Runtime => NoticeStatus::ConfigValidateYamlMappingError,
}, },
ValidationErrorKind::ScriptSyntax => "config_validate::script_syntax_error", ValidationErrorKind::ScriptSyntax => NoticeStatus::ConfigValidateScriptSyntaxError,
ValidationErrorKind::ScriptMissingMain => "config_validate::script_missing_main", ValidationErrorKind::ScriptMissingMain => NoticeStatus::ConfigValidateScriptMissingMain,
ValidationErrorKind::ProcessTerminated => "config_validate::process_terminated", ValidationErrorKind::ProcessTerminated => NoticeStatus::ConfigValidateProcessTerminated,
ValidationErrorKind::CoreRejected | ValidationErrorKind::Timeout => "config_validate::error", ValidationErrorKind::CoreRejected | ValidationErrorKind::Timeout => NoticeStatus::ConfigValidateError,
} }
} }
@@ -40,12 +41,12 @@ pub fn handle_validation_notice(outcome: &ValidationOutcome, target: ValidationN
ValidationOutcome::Invalid { kind, message } => { ValidationOutcome::Invalid { kind, message } => {
let status = notice_key(*kind, target); let status = notice_key(*kind, target);
logging!(warn, Type::Config, "{} 验证失败: {}", file_type, message); logging!(warn, Type::Config, "{} 验证失败: {}", file_type, message);
handle::Handle::notice_message(status, message.to_owned()); handle::Handle::notice(status, message.as_str());
} }
ValidationOutcome::Busy | ValidationOutcome::Skipped { .. } => { ValidationOutcome::Busy | ValidationOutcome::Skipped { .. } => {
let message = outcome.to_string(); let message = outcome.to_string();
logging!(warn, Type::Config, "{} 验证跳过: {}", file_type, message); logging!(warn, Type::Config, "{} 验证跳过: {}", file_type, message);
handle::Handle::notice_message("config_validate::error", message); handle::Handle::notice(NoticeStatus::ConfigValidateError, message.as_str());
} }
ValidationOutcome::Valid => {} ValidationOutcome::Valid => {}
} }
+17 -10
View File
@@ -1,4 +1,5 @@
use super::{IClashTemp, IProfiles, IVerge, MixedPort}; use super::{IClashTemp, IProfiles, IVerge, MixedPort};
use crate::core::notify::NoticeStatus;
use crate::{ use crate::{
config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime}, config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
constants::{files, timing}, constants::{files, timing},
@@ -69,6 +70,12 @@ impl Config {
CONFIG_WRITE_LOCK.lock().await CONFIG_WRITE_LOCK.lock().await
} }
pub(crate) fn try_lock_config_write() -> Result<MutexGuard<'static, ()>> {
CONFIG_WRITE_LOCK
.try_lock()
.map_err(|_| anyhow!("configuration update is already running"))
}
pub async fn init_config_before_window() -> Result<()> { pub async fn init_config_before_window() -> Result<()> {
Self::ensure_default_profile_items().await?; Self::ensure_default_profile_items().await?;
@@ -106,7 +113,7 @@ impl Config {
if let Some((msg_type, msg_content)) = validation_result { if let Some((msg_type, msg_content)) = validation_result {
sleep(timing::STARTUP_ERROR_DELAY).await; sleep(timing::STARTUP_ERROR_DELAY).await;
handle::Handle::notice_message(msg_type, msg_content); handle::Handle::notice(msg_type, msg_content.as_str());
} }
Self::runtime().await.apply(); Self::runtime().await.apply();
@@ -137,14 +144,14 @@ impl Config {
Ok(()) Ok(())
} }
async fn generate_and_validate() -> Result<Option<(&'static str, String)>> { async fn generate_and_validate() -> Result<Option<(NoticeStatus, String)>> {
if let Err(err) = Self::generate().await { if let Err(err) = Self::generate().await {
let error_msg: String = err.to_string().into(); let error_msg: String = err.to_string().into();
logging!(error, Type::Config, "生成运行时配置失败: {}", error_msg); logging!(error, Type::Config, "生成运行时配置失败: {}", error_msg);
CoreManager::global() CoreManager::global()
.use_default_config("config_validate::boot_error", &error_msg) .use_default_config(NoticeStatus::ConfigValidateBootError, &error_msg)
.await?; .await?;
return Ok(Some(("config_validate::boot_error", error_msg))); return Ok(Some((NoticeStatus::ConfigValidateBootError, error_msg)));
} }
logging!(debug, Type::Config, "生成运行时配置成功"); logging!(debug, Type::Config, "生成运行时配置成功");
@@ -171,25 +178,25 @@ impl Config {
error_msg error_msg
); );
CoreManager::global() CoreManager::global()
.use_default_config("config_validate::boot_error", &error_msg) .use_default_config(NoticeStatus::ConfigValidateBootError, &error_msg)
.await?; .await?;
Ok(Some(("config_validate::boot_error", error_msg))) Ok(Some((NoticeStatus::ConfigValidateBootError, error_msg)))
} }
Err(err) => { Err(err) => {
logging!(warn, Type::Config, "验证过程执行失败: {err:#}"); logging!(warn, Type::Config, "验证过程执行失败: {err:#}");
CoreManager::global() CoreManager::global()
.use_default_config("config_validate::process_terminated", "") .use_default_config(NoticeStatus::ConfigValidateProcessTerminated, "")
.await?; .await?;
Ok(Some(("config_validate::process_terminated", String::new()))) Ok(Some((NoticeStatus::ConfigValidateProcessTerminated, String::new())))
} }
} }
} else { } else {
let error_msg = config_result.err().map(|err| err.to_string()).unwrap_or_default(); let error_msg = config_result.err().map(|err| err.to_string()).unwrap_or_default();
logging!(warn, Type::Config, "生成配置文件失败,使用默认配置: {error_msg}"); logging!(warn, Type::Config, "生成配置文件失败,使用默认配置: {error_msg}");
CoreManager::global() CoreManager::global()
.use_default_config("config_validate::error", "") .use_default_config(NoticeStatus::ConfigValidateError, "")
.await?; .await?;
Ok(Some(("config_validate::error", String::new()))) Ok(Some((NoticeStatus::ConfigValidateError, String::new())))
} }
} }
+5 -3
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use anyhow::Result; use anyhow::Result;
use clash_verge_draft::DraftTransaction; use clash_verge_draft::DraftTransaction;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -138,12 +139,13 @@ impl Config {
} }
// The runtime is already committed; a disk failure cannot undo its effective settings. // The runtime is already committed; a disk failure cannot undo its effective settings.
transaction.commit(); transaction.commit();
Handle::refresh_verge();
if state.requested && !state.enabled { if state.requested && !state.enabled {
PENDING_DNS_OVERRIDE_NOTICE.store(true, Ordering::Relaxed); PENDING_DNS_OVERRIDE_NOTICE.store(true, Ordering::Relaxed);
Handle::notice_message("dns_override::auto_disabled", ""); Handle::notice(NoticeStatus::DnsOverrideAutoDisabled, "");
} }
verge.data_arc().save_file().await verge.data_arc().save_file().await?;
Handle::refresh_verge();
Ok(())
} }
} }
+9 -15
View File
@@ -1,4 +1,5 @@
use super::{Config, IClashTemp, IVerge, MixedPort}; use super::{Config, IClashTemp, IVerge, MixedPort};
use crate::core::notify::NoticeStatus;
use crate::{ use crate::{
constants::timing, constants::timing,
core::{ core::{
@@ -14,14 +15,13 @@ use crate::{
use anyhow::{Context as _, Result, anyhow, bail}; use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_draft::DraftTransaction; use clash_verge_draft::DraftTransaction;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use serde_yaml_ng::Value; use serde_yaml_ng::Value;
use std::{ use std::{
collections::HashSet, collections::HashSet,
net::SocketAddr, net::SocketAddr,
str::FromStr as _, str::FromStr as _,
sync::atomic::{AtomicBool, Ordering}, sync::{LazyLock, OnceLock},
}; };
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -30,9 +30,8 @@ struct MixedPortFallback {
current: u16, current: u16,
} }
static PENDING_FALLBACK_NOTICE: Lazy<Mutex<Option<MixedPortFallback>>> = Lazy::new(|| Mutex::new(None)); static PENDING_FALLBACK_NOTICE: LazyLock<Mutex<Option<MixedPortFallback>>> = LazyLock::new(|| Mutex::new(None));
static STARTUP_CORE_BLOCKED: AtomicBool = AtomicBool::new(false); static STARTUP_CORE_BLOCK_REASON: OnceLock<String> = OnceLock::new();
static STARTUP_CORE_BLOCK_REASON: Lazy<Mutex<Option<String>>> = Lazy::new(|| Mutex::new(None));
impl Config { impl Config {
pub(crate) async fn resolve_startup_mixed_port() -> Result<bool> { pub(crate) async fn resolve_startup_mixed_port() -> Result<bool> {
@@ -147,17 +146,12 @@ impl Config {
} }
pub(crate) fn block_startup_core(error: &anyhow::Error) { pub(crate) fn block_startup_core(error: &anyhow::Error) {
STARTUP_CORE_BLOCKED.store(true, Ordering::Release); let _ = STARTUP_CORE_BLOCK_REASON.set(error.to_string());
*STARTUP_CORE_BLOCK_REASON.lock() = Some(error.to_string());
report_fallback_error(error.to_string()); report_fallback_error(error.to_string());
} }
pub(crate) fn startup_core_block_reason() -> Option<String> { pub(crate) fn startup_core_block_reason() -> Option<String> {
if STARTUP_CORE_BLOCKED.load(Ordering::Acquire) { STARTUP_CORE_BLOCK_REASON.get().cloned()
STARTUP_CORE_BLOCK_REASON.lock().clone()
} else {
None
}
} }
pub(crate) fn notify_startup_mixed_port_fallback() { pub(crate) fn notify_startup_mixed_port_fallback() {
@@ -166,8 +160,8 @@ impl Config {
}; };
AsyncHandler::spawn(move || async move { AsyncHandler::spawn(move || async move {
tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await; tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await;
Handle::notice_message( Handle::notice(
"mixed_port::fallback", NoticeStatus::MixedPortFallback,
format!("{},{}", change.original, change.current), format!("{},{}", change.original, change.current),
); );
}); });
@@ -196,7 +190,7 @@ fn report_fallback_error(message: String) {
); );
AsyncHandler::spawn(move || async move { AsyncHandler::spawn(move || async move {
tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await; tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await;
Handle::notice_message("mixed_port::fallback_error", message); Handle::notice(NoticeStatus::MixedPortFallbackError, message);
}); });
} }
+155 -148
View File
@@ -2,6 +2,8 @@ use super::{
PrfOption, PrfOption,
prfitem::{PrfItem, PrfSelected, normalize_profile_home_url}, prfitem::{PrfItem, PrfSelected, normalize_profile_home_url},
}; };
use crate::core::notify::{Refresh, announce};
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
use crate::{ use crate::{
core::{handle, tray::Tray}, core::{handle, tray::Tray},
utils::{ utils::{
@@ -16,6 +18,7 @@ use parking_lot::Mutex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_yaml_ng::Mapping; use serde_yaml_ng::Mapping;
use smartstring::alias::String; use smartstring::alias::String;
use std::num::NonZeroUsize;
use std::{ use std::{
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
path::{Component, Path}, path::{Component, Path},
@@ -600,19 +603,21 @@ fn is_activation_current(generation: u64) -> bool {
} }
async fn fetch_proxies_with_timeout() -> Result<Proxies> { async fn fetch_proxies_with_timeout() -> Result<Proxies> {
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async { let interval = Duration::from_millis(500);
loop { let attempts =
match handle::Handle::mihomo().get_proxies().await { NonZeroUsize::MIN.saturating_add((MIHOMO_OPERATION_TIMEOUT.as_millis() / interval.as_millis()) as usize + 1);
Ok(proxies) => return proxies, tokio::time::timeout(
Err(err) => { MIHOMO_OPERATION_TIMEOUT,
logging!(debug, Type::Config, "mihomo proxies are not ready yet: {err:#}"); retry(RetryPolicy::fixed(attempts, interval), |_| async {
tokio::time::sleep(Duration::from_millis(500)).await; handle::Handle::mihomo().get_proxies().await.map_err(|error| {
} logging!(debug, Type::Config, "mihomo proxies are not ready yet: {error:#}");
} RetryError::Retry(error)
} })
}) }),
)
.await .await
.context("timed out while waiting for mihomo proxies") .context("timed out while waiting for mihomo proxies")?
.map_err(Into::into)
} }
async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> { async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> {
@@ -691,51 +696,58 @@ async fn update_tray_after_activation(generation: u64) {
} }
} }
async fn persist_selected_update<F, Fut>(supersede: bool, edit: F) -> Result<()>
where
F: FnOnce(IProfiles) -> Fut + Send,
Fut: std::future::Future<Output = Result<(IProfiles, bool)>> + Send,
{
let changed = Config::profiles().await.with_data_modify(edit).await?;
if changed {
if supersede {
supersede_selected_activation();
}
announce(Refresh::Profiles);
}
Ok(())
}
/// Records a backend-made selection so the next core start restores it. /// Records a backend-made selection so the next core start restores it.
pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result<()> { pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result<()> {
let group_name = String::from(group_name); let group_name = String::from(group_name);
let node = String::from(node); let node = String::from(node);
let recorded = Config::profiles() persist_selected_update(true, move |mut profiles| async move {
.await let Some(current) = profiles.current.clone() else {
.with_data_modify(move |mut profiles| async move { return Ok((profiles, false));
let Some(current) = profiles.current.clone() else { };
return Ok((profiles, false)); let Some(item) = profiles
}; .items
let Some(item) = profiles .as_mut()
.items .and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&current)))
.as_mut() else {
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&current))) return Ok((profiles, false));
else { };
return Ok((profiles, false));
};
let mut selected = item.selected.clone().unwrap_or_default(); let mut selected = item.selected.clone().unwrap_or_default();
match selected match selected
.iter_mut() .iter_mut()
.find(|entry| entry.name.as_ref() == Some(&group_name)) .find(|entry| entry.name.as_ref() == Some(&group_name))
{ {
Some(entry) => { Some(entry) => {
if entry.now.as_ref() == Some(&node) { if entry.now.as_ref() == Some(&node) {
return Ok((profiles, false)); return Ok((profiles, false));
}
entry.now = Some(node);
} }
None => selected.push(PrfSelected { entry.now = Some(node);
name: Some(group_name),
now: Some(node),
}),
} }
item.selected = Some(selected); None => selected.push(PrfSelected {
profiles.save_file().await?; name: Some(group_name),
Ok((profiles, true)) now: Some(node),
}) }),
.await?; }
item.selected = Some(selected);
if recorded { profiles.save_file().await?;
supersede_selected_activation(); Ok((profiles, true))
handle::Handle::refresh_profiles(); })
} .await
Ok(())
} }
fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bool { fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bool {
@@ -745,36 +757,28 @@ fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bo
} }
pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> { pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
let cleared = Config::profiles() persist_selected_update(true, move |mut profiles| async move {
.await let Some(current) = profiles.current.clone() else {
.with_data_modify(move |mut profiles| async move { return Ok((profiles, false));
let Some(current) = profiles.current.clone() else { };
return Ok((profiles, false)); let Some(item) = profiles
}; .items
let Some(item) = profiles .as_mut()
.items .and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&current)))
.as_mut() else {
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&current))) return Ok((profiles, false));
else { };
return Ok((profiles, false));
};
let mut selected = item.selected.clone().unwrap_or_default(); let mut selected = item.selected.clone().unwrap_or_default();
if !remove_selected_node(&mut selected, group_name) { if !remove_selected_node(&mut selected, group_name) {
return Ok((profiles, false)); return Ok((profiles, false));
} }
item.selected = (!selected.is_empty()).then_some(selected); item.selected = (!selected.is_empty()).then_some(selected);
profiles.save_file().await?; profiles.save_file().await?;
Ok((profiles, true)) Ok((profiles, true))
}) })
.await?; .await
if cleared {
supersede_selected_activation();
handle::Handle::refresh_profiles();
}
Ok(())
} }
async fn persist_reconciled_selected( async fn persist_reconciled_selected(
@@ -787,34 +791,27 @@ async fn persist_reconciled_selected(
return Ok(()); return Ok(());
} }
let profiles = Config::profiles().await;
let profile_uid = profile_uid.clone(); let profile_uid = profile_uid.clone();
let original_selected = original_selected.to_vec(); let original_selected = original_selected.to_vec();
let updated = profiles persist_selected_update(false, move |mut profiles| async move {
.with_data_modify(move |mut profiles| async move { if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) { return Ok((profiles, false));
return Ok((profiles, false)); }
}
let profile = profiles let profile = profiles
.items .items
.as_mut() .as_mut()
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&profile_uid))) .and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&profile_uid)))
.with_context(|| format!("failed to find the profile item \"uid:{profile_uid}\""))?; .with_context(|| format!("failed to find the profile item \"uid:{profile_uid}\""))?;
if profile.selected.as_deref().unwrap_or(&[]) != original_selected.as_slice() { if profile.selected.as_deref().unwrap_or(&[]) != original_selected.as_slice() {
return Ok((profiles, false)); return Ok((profiles, false));
} }
profile.selected = (!selected.is_empty()).then_some(selected); profile.selected = (!selected.is_empty()).then_some(selected);
profiles.save_file().await?; profiles.save_file().await?;
Ok((profiles, true)) Ok((profiles, true))
}) })
.await?; .await
if updated {
handle::Handle::refresh_profiles();
}
Ok(())
} }
/// Returns recorded selections whose groups have not reached the requested node. /// Returns recorded selections whose groups have not reached the requested node.
@@ -836,48 +833,58 @@ fn unsettled_selections(selected: &[PrfSelected], proxies: &Proxies) -> Vec<Stri
/// Retries selections while provider-backed groups finish loading. /// Retries selections while provider-backed groups finish loading.
async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut HashMap<String, String>, generation: u64) { async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut HashMap<String, String>, generation: u64) {
let deadline = Instant::now() + SELECTED_NODES_SETTLE_DEADLINE; let deadline = Instant::now() + SELECTED_NODES_SETTLE_DEADLINE;
loop { let attempts = NonZeroUsize::MIN.saturating_add(
tokio::time::sleep(SELECTED_NODES_SETTLE_INTERVAL).await; (SELECTED_NODES_SETTLE_DEADLINE.as_millis() / SELECTED_NODES_SETTLE_INTERVAL.as_millis()) as usize,
if !is_activation_current(generation) { );
return; tokio::time::sleep(SELECTED_NODES_SETTLE_INTERVAL).await;
} let _ = retry_with_state(
let Ok(snapshot) = fetch_proxies_with_timeout().await else { RetryPolicy::fixed(attempts, SELECTED_NODES_SETTLE_INTERVAL),
// Unreachable core: the deadline still applies, so this cannot spin forever. (selected, completed, generation, deadline),
if Instant::now() >= deadline { |state, _| {
return; Box::pin(async move {
} let (selected, completed, generation, deadline) = state;
continue; if !is_activation_current(*generation) {
}; return Ok(());
if !is_activation_current(generation) { }
return; let Ok(snapshot) = fetch_proxies_with_timeout().await else {
} return if Instant::now() >= *deadline {
Ok(())
let pending = unsettled_selections(selected, &snapshot); } else {
if pending.is_empty() { Err(RetryError::Retry(()))
return; };
} };
if Instant::now() >= deadline { if !is_activation_current(*generation) {
logging!( return Ok(());
warn, }
Type::Config, let pending = unsettled_selections(selected, &snapshot);
"gave up putting back {} selected node(s) the core never loaded: {}", if pending.is_empty() {
pending.len(), return Ok(());
pending.iter().map(String::as_str).collect::<Vec<_>>().join(", ") }
); if Instant::now() >= *deadline {
return; logging!(
} warn,
Type::Config,
let plan = reconcile_selected_nodes(selected, None, &snapshot); "gave up putting back {} selected node(s) the core never loaded: {}",
if apply_activations(&plan.activations, completed, generation) pending.len(),
.await pending.iter().map(String::as_str).collect::<Vec<_>>().join(", ")
.is_none() );
{ return Ok(());
return; }
} let plan = reconcile_selected_nodes(selected, None, &snapshot);
if is_activation_current(generation) { if apply_activations(&plan.activations, completed, *generation)
handle::Handle::refresh_clash(); .await
} .is_none()
} {
return Ok(());
}
if is_activation_current(*generation) {
announce(Refresh::Clash);
}
Err(RetryError::Retry(()))
})
},
)
.await;
} }
/// Releases the first-pass waiter even when restoration exits early. /// Releases the first-pass waiter even when restoration exits early.
@@ -920,7 +927,7 @@ async fn activate_selected_nodes_worker(
} }
if is_activation_current(generation) { if is_activation_current(generation) {
handle::Handle::refresh_clash(); announce(Refresh::Clash);
} }
let plan = if needs_confirmation { let plan = if needs_confirmation {
@@ -944,7 +951,7 @@ async fn activate_selected_nodes_worker(
return Ok(()); return Ok(());
}; };
if confirmed_activated_count > 0 && is_activation_current(generation) { if confirmed_activated_count > 0 && is_activation_current(generation) {
handle::Handle::refresh_clash(); announce(Refresh::Clash);
} }
confirmed_plan confirmed_plan
} else { } else {
@@ -1034,7 +1041,7 @@ fn activate_selected_nodes_with(repair: SelectionRepair) -> tokio::sync::oneshot
if selected.is_empty() { if selected.is_empty() {
if is_activation_current(generation) { if is_activation_current(generation) {
handle::Handle::refresh_clash(); announce(Refresh::Clash);
} }
return Ok(()); return Ok(());
} }
@@ -1046,7 +1053,7 @@ fn activate_selected_nodes_with(repair: SelectionRepair) -> tokio::sync::oneshot
if let Err(err) = result { if let Err(err) = result {
logging!(error, Type::Config, "failed to activate selected nodes: {err:#}"); logging!(error, Type::Config, "failed to activate selected nodes: {err:#}");
// The profile itself is already active even if node restoration failed. // The profile itself is already active even if node restoration failed.
handle::Handle::refresh_clash(); announce(Refresh::Clash);
} }
update_tray_after_activation(generation).await; update_tray_after_activation(generation).await;
logging!(debug, Type::Config, "activating selected nodes done!"); logging!(debug, Type::Config, "activating selected nodes done!");
+57
View File
@@ -0,0 +1,57 @@
use crate::{
config::{Config, IVerge},
core::{autostart, hotkey, lightweight, tray},
};
use anyhow::Result;
use futures::future::BoxFuture;
pub(crate) fn ensure_autostart(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { autostart::update_launch().await })
}
pub(crate) fn ensure_hotkey(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
if let Some(hotkeys) = &patch.hotkeys {
hotkey::Hotkey::global().update(hotkeys.to_owned()).await?;
}
Ok(())
})
}
pub(crate) fn ensure_tray_menu(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { tray::Tray::global().update_menu().await })
}
pub(crate) fn ensure_tray_icon(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
tray::Tray::global()
.update_icon(&Config::verge().await.latest_arc())
.await?;
#[cfg(target_os = "macos")]
if let Some(enabled) = patch.enable_tray_speed {
tray::Tray::global().update_speed_task(enabled);
}
#[cfg(not(target_os = "macos"))]
let _ = patch;
Ok(())
})
}
pub(crate) fn ensure_tray_tooltip(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { tray::Tray::global().update_tooltip().await })
}
pub(crate) fn ensure_tray_click(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move { tray::Tray::global().update_click_behavior().await })
}
pub(crate) fn ensure_lightweight(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
Box::pin(async move {
if patch.enable_auto_light_weight_mode.unwrap_or(false) {
lightweight::enable_auto_light_weight_mode().await;
} else {
lightweight::disable_auto_light_weight_mode();
}
Ok(())
})
}
@@ -7,8 +7,8 @@ use crate::{
use anyhow::Result; use anyhow::Result;
use chrono::Local; use chrono::Local;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use once_cell::sync::OnceCell;
use parking_lot::RwLock; use parking_lot::RwLock;
use std::sync::OnceLock;
use std::{ use std::{
path::PathBuf, path::PathBuf,
sync::{ sync::{
@@ -92,7 +92,7 @@ pub struct AutoBackupManager {
impl AutoBackupManager { impl AutoBackupManager {
pub fn global() -> &'static Self { pub fn global() -> &'static Self {
static INSTANCE: OnceCell<AutoBackupManager> = OnceCell::new(); static INSTANCE: OnceLock<AutoBackupManager> = OnceLock::new();
INSTANCE.get_or_init(|| { INSTANCE.get_or_init(|| {
let (tx, _rx) = watch::channel(AutoBackupSettings::default()); let (tx, _rx) = watch::channel(AutoBackupSettings::default());
Self { Self {
+2 -2
View File
@@ -4,9 +4,9 @@ use anyhow::Error;
use arc_swap::{ArcSwap, ArcSwapOption}; use arc_swap::{ArcSwap, ArcSwapOption};
use backon::{ConstantBuilder, Retryable as _}; use backon::{ConstantBuilder, Retryable as _};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use once_cell::sync::OnceCell;
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus}; use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
use smartstring::alias::String; use smartstring::alias::String;
use std::sync::OnceLock;
use std::{ use std::{
collections::HashMap, collections::HashMap,
env::{consts::OS, temp_dir}, env::{consts::OS, temp_dir},
@@ -58,7 +58,7 @@ pub struct WebDavClient {
impl WebDavClient { impl WebDavClient {
pub fn global() -> &'static Self { pub fn global() -> &'static Self {
static WEBDAV_CLIENT: OnceCell<WebDavClient> = OnceCell::new(); static WEBDAV_CLIENT: OnceLock<WebDavClient> = OnceLock::new();
WEBDAV_CLIENT.get_or_init(|| Self { WEBDAV_CLIENT.get_or_init(|| Self {
config: ArcSwapOption::new(None), config: ArcSwapOption::new(None),
clients: ArcSwap::new(Arc::new(HashMap::new())), clients: ArcSwap::new(Arc::new(HashMap::new())),
+4 -3
View File
@@ -1,8 +1,9 @@
use crate::core::notify::NoticeStatus;
use crate::process::AsyncHandler; use crate::process::AsyncHandler;
use crate::singleton; use crate::singleton;
use crate::utils::notification::{NotificationEvent, notify_event}; use crate::utils::notification::{NotificationEvent, notify_event};
use crate::utils::window_manager::WindowManager; use crate::utils::window_manager::WindowManager;
use crate::{config::Config, core::handle, feat, module::lightweight::entry_lightweight_mode}; use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_mode, feat};
use anyhow::{Result, bail}; use anyhow::{Result, bail};
use arc_swap::ArcSwap; use arc_swap::ArcSwap;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
@@ -177,7 +178,7 @@ impl Hotkey {
"Hotkey profile reactivation failed validation: {}", "Hotkey profile reactivation failed validation: {}",
message.as_str() message.as_str()
); );
handle::Handle::notice_message("reactivate_profiles::error", message); handle::Handle::notice(NoticeStatus::ReactivateProfilesError, message);
} }
Err(err) => { Err(err) => {
logging!( logging!(
@@ -186,7 +187,7 @@ impl Hotkey {
"Failed to reactivate subscriptions via hotkey: {}", "Failed to reactivate subscriptions via hotkey: {}",
err err
); );
handle::Handle::notice_message("reactivate_profiles::error", err.to_string()); handle::Handle::notice(NoticeStatus::ReactivateProfilesError, err.to_string());
} }
}); });
} }
+35 -3
View File
@@ -1,4 +1,5 @@
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode}; use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::core::notify::NoticeStatus;
use crate::core::service::StageRequest; use crate::core::service::StageRequest;
use crate::{ use crate::{
config::{Config, IProfiles, runtime::IRuntime}, config::{Config, IProfiles, runtime::IRuntime},
@@ -129,7 +130,31 @@ where
} }
impl CoreManager { impl CoreManager {
pub async fn use_default_config(&self, error_key: &str, error_msg: &str) -> Result<()> { pub(crate) fn claim_config_update(
&self,
_config_write: &tokio::sync::MutexGuard<'_, ()>,
) -> Result<ConfigUpdateGuard<'_>> {
if !self.try_start_config_update() {
anyhow::bail!("configuration update is already running");
}
Ok(ConfigUpdateGuard(self))
}
pub(crate) async fn update_config_in_patch(&self, _update: &ConfigUpdateGuard<'_>) -> Result<()> {
if handle::Handle::global().is_exiting() {
anyhow::bail!("application is exiting");
}
self.set_last_update(Instant::now());
Config::generate().await?;
let outcome = self.validate_and_apply_draft().await?;
if outcome.is_valid() {
Ok(())
} else {
Err(anyhow!("{outcome}"))
}
}
pub async fn use_default_config(&self, status: NoticeStatus, message: &str) -> Result<()> {
use crate::constants::files::RUNTIME_CONFIG; use crate::constants::files::RUNTIME_CONFIG;
let runtime_path = dirs::app_home_dir()?.join(RUNTIME_CONFIG); let runtime_path = dirs::app_home_dir()?.join(RUNTIME_CONFIG);
@@ -145,7 +170,7 @@ impl CoreManager {
}); });
help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?; help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
handle::Handle::notice_message(error_key, error_msg); handle::Handle::notice(status, message);
Ok(()) Ok(())
} }
@@ -299,6 +324,14 @@ impl CoreManager {
/// Validates and applies the caller's transaction, committing only on success. /// Validates and applies the caller's transaction, committing only on success.
async fn validate_and_apply(&self, transaction: DraftTransaction<'_>) -> Result<ValidationOutcome> { async fn validate_and_apply(&self, transaction: DraftTransaction<'_>) -> Result<ValidationOutcome> {
let outcome = self.validate_and_apply_draft().await?;
if outcome.is_valid() {
transaction.commit();
}
Ok(outcome)
}
async fn validate_and_apply_draft(&self) -> Result<ValidationOutcome> {
// One serialization feeds check and run files; the core never applies unvalidated bytes. // One serialization feeds check and run files; the core never applies unvalidated bytes.
let yaml = Config::runtime_config_yaml().await?; let yaml = Config::runtime_config_yaml().await?;
let outcome = CoreConfigValidator::global() let outcome = CoreConfigValidator::global()
@@ -310,7 +343,6 @@ impl CoreManager {
let run_path = Config::write_runtime_file(&yaml).await?; let run_path = Config::write_runtime_file(&yaml).await?;
self.apply_config(run_path).await?; self.apply_config(run_path).await?;
transaction.commit();
Ok(ValidationOutcome::Valid) Ok(ValidationOutcome::Valid)
} }
+13 -8
View File
@@ -840,29 +840,34 @@ impl CoreManager {
AsyncHandler::spawn(|| async move { AsyncHandler::spawn(|| async move {
let manager = Self::global(); let manager = Self::global();
let started = Instant::now(); let started = Instant::now();
loop { use crate::utils::retry::{RetryError, RetryPolicy, retry};
let attempts = std::num::NonZeroUsize::MIN.saturating_add(
(timing::SERVICE_HANDOFF_WINDOW.as_millis() / timing::SERVICE_HANDOFF_INTERVAL.as_millis()) as usize,
);
let _ = retry(RetryPolicy::fixed(attempts, std::time::Duration::ZERO), |_| async {
if started.elapsed() >= timing::SERVICE_HANDOFF_WINDOW { if started.elapsed() >= timing::SERVICE_HANDOFF_WINDOW {
logging!( logging!(
info, info,
Type::Core, Type::Core,
"service handoff window elapsed; staying in sidecar mode" "service handoff window elapsed; staying in sidecar mode"
); );
break; return Ok(());
} }
// The window is checked before waiting, including the final handoff attempt.
tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await; tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await;
if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) { if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) {
break; return Ok(());
} }
match manager.try_handoff_sidecar_to_service().await { match manager.try_handoff_sidecar_to_service().await {
HandoffOutcome::Done => break, HandoffOutcome::Done => Ok(()),
HandoffOutcome::Failed => { HandoffOutcome::Failed => {
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode"); logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
break; Ok(())
} }
HandoffOutcome::NotReady => {} HandoffOutcome::NotReady => Err(RetryError::Retry(())),
} }
} })
.await;
manager.handoff_watcher_running.store(false, Ordering::Release); manager.handoff_watcher_running.store(false, Ordering::Release);
}); });
} }
+46 -37
View File
@@ -1,11 +1,12 @@
mod config; mod config;
pub(crate) use config::ConfigUpdateGuard;
mod lifecycle; mod lifecycle;
mod state; mod state;
use anyhow::Result; use anyhow::Result;
use arc_swap::{ArcSwap, ArcSwapOption}; use arc_swap::{ArcSwap, ArcSwapOption};
use clash_verge_logging::{LogRing, Type, logging}; use clash_verge_logging::{LogRing, Type, logging};
use once_cell::sync::Lazy; use std::sync::LazyLock;
use std::{ use std::{
fmt, fmt,
sync::{ sync::{
@@ -21,7 +22,7 @@ use crate::singleton;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
use std::os::windows::io::OwnedHandle; use std::os::windows::io::OwnedHandle;
pub(crate) static CLASH_LOGGER: Lazy<Arc<LogRing>> = Lazy::new(|| Arc::new(LogRing::new())); pub(crate) static CLASH_LOGGER: LazyLock<Arc<LogRing>> = LazyLock::new(|| Arc::new(LogRing::new()));
tokio::task_local! { tokio::task_local! {
static PROFILE_SELECTIONS_PENDING_COMMIT: bool; static PROFILE_SELECTIONS_PENDING_COMMIT: bool;
@@ -284,48 +285,56 @@ impl CoreManager {
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}"); anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
} }
let mut retries = 0; use crate::utils::retry::{RetryError, RetryPolicy, retry};
loop { retry(
match self.start_core().await { RetryPolicy::fixed(
Ok(()) => { std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
crate::config::Config::notify_startup_mixed_port_fallback(); std::time::Duration::ZERO,
return Ok(!matches!(*self.get_running_mode(), RunningMode::NotRunning)); ),
} |retries| async move {
Err(start_error) if retries < MAX_PORT_FALLBACK_RETRIES => { match self.start_core().await {
if !matches!(*self.get_running_mode(), RunningMode::NotRunning) { Ok(()) => {
crate::config::Config::notify_startup_mixed_port_fallback(); crate::config::Config::notify_startup_mixed_port_fallback();
return Err(start_error); Ok(!matches!(*self.get_running_mode(), RunningMode::NotRunning))
} }
match crate::config::Config::resolve_startup_mixed_port().await { Err(start_error) if retries < MAX_PORT_FALLBACK_RETRIES => {
Ok(true) => { if !matches!(*self.get_running_mode(), RunningMode::NotRunning) {
retries += 1;
tracing::Span::current().record("retries", retries);
logging!(
warn,
Type::Core,
"Retrying core startup after mixed proxy port fallback ({}/{}): {start_error:#}",
retries,
MAX_PORT_FALLBACK_RETRIES
);
}
Ok(false) => {
crate::config::Config::notify_startup_mixed_port_fallback(); crate::config::Config::notify_startup_mixed_port_fallback();
return Err(start_error); return Err(RetryError::Stop(start_error));
} }
Err(fallback_error) => { match crate::config::Config::resolve_startup_mixed_port().await {
crate::config::Config::block_startup_core(&fallback_error); Ok(true) => {
return Err(start_error.context(format!( let retries = retries + 1;
"the mixed proxy port fallback did not rescue core startup: {fallback_error:#}" tracing::Span::current().record("retries", retries);
))); logging!(
warn,
Type::Core,
"Retrying core startup after mixed proxy port fallback ({}/{}): {start_error:#}",
retries,
MAX_PORT_FALLBACK_RETRIES
);
Err(RetryError::Retry(start_error))
}
Ok(false) => {
crate::config::Config::notify_startup_mixed_port_fallback();
Err(RetryError::Stop(start_error))
}
Err(fallback_error) => {
crate::config::Config::block_startup_core(&fallback_error);
Err(RetryError::Stop(start_error.context(format!(
"the mixed proxy port fallback did not rescue core startup: {fallback_error:#}"
))))
}
} }
} }
Err(error) => {
crate::config::Config::notify_startup_mixed_port_fallback();
Err(RetryError::Stop(error))
}
} }
Err(error) => { },
crate::config::Config::notify_startup_mixed_port_fallback(); )
return Err(error); .await
}
}
}
} }
} }
+30 -31
View File
@@ -1,6 +1,7 @@
#[cfg(test)] #[cfg(test)]
use super::claim_core_readiness_generation; use super::claim_core_readiness_generation;
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode}; use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::utils::retry::{RetryError, RetryPolicy, retry};
use crate::{ use crate::{
AsyncHandler, AsyncHandler,
config::Config, config::Config,
@@ -11,6 +12,7 @@ use crate::{
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use clash_verge_logging::Type; use clash_verge_logging::Type;
use log::Level; use log::Level;
use std::num::NonZeroUsize;
use std::path::Path; use std::path::Path;
use tauri_plugin_mihomo::MihomoExt as _; use tauri_plugin_mihomo::MihomoExt as _;
use tauri_plugin_shell::ShellExt as _; use tauri_plugin_shell::ShellExt as _;
@@ -41,14 +43,15 @@ async fn retry_service_start<Start, StartFuture>(
mut start: Start, mut start: Start,
) -> Result<()> ) -> Result<()>
where where
Start: FnMut() -> StartFuture, Start: FnMut() -> StartFuture + Send,
StartFuture: std::future::Future<Output = Result<()>>, StartFuture: std::future::Future<Output = Result<()>> + Send,
{ {
let mut last_error = None; let attempts = NonZeroUsize::new(attempts).ok_or_else(|| anyhow::anyhow!("service start failed"))?;
for attempt in 0..attempts { retry(RetryPolicy::fixed(attempts, retry_delay), |attempt| {
match start().await { // The Windows Service IPC future would otherwise inflate every enclosing lifecycle future.
Ok(()) => return Ok(()), let future = Box::pin(start());
Err(error) => { async move {
future.await.map_err(|error| {
logging!( logging!(
warn, warn,
Type::Core, Type::Core,
@@ -60,16 +63,14 @@ where
.downcast_ref::<service::ServiceStartRefusal>() .downcast_ref::<service::ServiceStartRefusal>()
.is_some_and(|refusal| service::StageRequest::is_about_the_bundle(refusal.code)) .is_some_and(|refusal| service::StageRequest::is_about_the_bundle(refusal.code))
{ {
return Err(error); RetryError::Stop(error)
} else {
RetryError::Retry(error)
} }
last_error = Some(error); })
if attempt + 1 < attempts {
tokio::time::sleep(retry_delay).await;
}
}
} }
} })
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("service start failed"))) .await
} }
impl CoreManager { impl CoreManager {
@@ -95,14 +96,16 @@ async fn poll_sidecar_readiness<F, Fut>(
mut probe: F, mut probe: F,
) -> Result<()> ) -> Result<()>
where where
F: FnMut() -> Fut, F: FnMut() -> Fut + Send,
Fut: std::future::Future<Output = Result<()>>, Fut: std::future::Future<Output = Result<()>> + Send,
{ {
let mut last_error = None; let attempts = NonZeroUsize::new(max_attempts)
for attempt in 0..max_attempts { .context("sidecar readiness was configured with no attempts")
match probe().await { .context("Mihomo API did not become ready")?;
Ok(()) => return Ok(()), retry(RetryPolicy::fixed(attempts, retry_delay), |attempt| {
Err(error) => { let future = probe();
async move {
future.await.map_err(|error| {
logging!( logging!(
debug, debug,
Type::Core, Type::Core,
@@ -110,16 +113,12 @@ where
attempt + 1, attempt + 1,
max_attempts max_attempts
); );
last_error = Some(error); RetryError::Retry(error)
} })
} }
if attempt + 1 < max_attempts { })
tokio::time::sleep(retry_delay).await; .await
} .context("Mihomo API did not become ready")
}
Err(last_error
.unwrap_or_else(|| anyhow::anyhow!("sidecar readiness was configured with no attempts"))
.context("Mihomo API did not become ready"))
} }
fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool { fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool {
+5 -2
View File
@@ -1,13 +1,15 @@
pub(crate) mod app_effects;
pub mod auto_backup;
pub mod autostart; pub mod autostart;
pub mod backup; pub mod backup;
pub mod handle;
pub mod hotkey; pub mod hotkey;
pub mod lightweight;
pub mod listener; pub mod listener;
pub mod logger; pub mod logger;
pub mod manager; pub mod manager;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub mod network_watch; pub mod network_watch;
pub mod notification; pub mod notify;
pub(crate) mod owner_identity; pub(crate) mod owner_identity;
pub mod proxy_control; pub mod proxy_control;
pub mod proxy_view; pub mod proxy_view;
@@ -22,3 +24,4 @@ pub mod validate;
pub mod win_uwp; pub mod win_uwp;
pub use self::{manager::CoreManager, timer::Timer, updater::SilentUpdater}; pub use self::{manager::CoreManager, timer::Timer, updater::SilentUpdater};
pub use notify::{handle, notification};
+11 -4
View File
@@ -5,13 +5,13 @@
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler}; use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use parking_lot::Mutex; use std::sync::atomic::{AtomicBool, Ordering};
use sysproxy::NetworkServiceMonitor; use sysproxy::NetworkServiceMonitor;
static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None); static ARMED: AtomicBool = AtomicBool::new(false);
pub fn is_armed() -> bool { pub fn is_armed() -> bool {
MONITOR.lock().is_some() ARMED.load(Ordering::Acquire)
} }
/// Subscribe to the primary IPv4 service on the main run loop. Armed on return, so a service /// Subscribe to the primary IPv4 service on the main run loop. Armed on return, so a service
@@ -21,7 +21,14 @@ pub fn start() {
AsyncHandler::spawn(reapply); AsyncHandler::spawn(reapply);
}) { }) {
Ok(monitor) => { Ok(monitor) => {
*MONITOR.lock() = Some(monitor); if ARMED
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return;
}
// Dropping the monitor stops network notifications, so it must outlive the call.
std::mem::forget(monitor);
logging!( logging!(
debug, debug,
Type::Core, Type::Core,
+139
View File
@@ -0,0 +1,139 @@
use super::{handle::Handle, notification::FrontendEvent};
use anyhow::Result;
use parking_lot::Mutex;
use std::{cell::RefCell, future::Future, time::Duration};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Refresh {
Clash,
Verge,
Profiles,
Proxies,
}
tokio::task_local! {
static PENDING: RefCell<Vec<Refresh>>;
}
const REFRESH_WINDOW: Duration = Duration::from_millis(20);
static BATCH: RefreshBatch = RefreshBatch(Mutex::new(Vec::new()));
#[derive(Default)]
struct RefreshBatch(Mutex<Vec<Refresh>>);
impl RefreshBatch {
fn enqueue(&self, refresh: Refresh) -> bool {
let mut pending = self.0.lock();
let start_window = pending.is_empty();
if !pending.contains(&refresh) {
pending.push(refresh);
}
start_window
}
async fn flush(&self, emit: impl Fn(Refresh)) {
// A fixed window bounds latency even under a continuous stream of refreshes.
tokio::time::sleep(REFRESH_WINDOW).await;
let refreshes = std::mem::take(&mut *self.0.lock());
for refresh in refreshes {
emit(refresh);
}
}
}
pub fn announce(refresh: Refresh) {
if PENDING.try_with(|pending| pending.borrow_mut().push(refresh)).is_err() && BATCH.enqueue(refresh) {
crate::AsyncHandler::spawn(|| BATCH.flush(emit));
}
}
fn emit(refresh: Refresh) {
Handle::send_event(match refresh {
Refresh::Clash => FrontendEvent::RefreshClash,
Refresh::Verge => FrontendEvent::RefreshVerge,
Refresh::Profiles => FrontendEvent::RefreshProfiles,
Refresh::Proxies => FrontendEvent::RefreshProxyConfig,
});
}
async fn collect_committed<T: Send>(operation: impl Future<Output = Result<T>> + Send) -> Result<(T, Vec<Refresh>)> {
PENDING
.scope(RefCell::new(Vec::new()), async {
let value = operation.await?;
let refreshes = PENDING.with(|pending| pending.take());
Ok((value, refreshes))
})
.await
}
pub async fn after_commit<T: Send>(operation: impl Future<Output = Result<T>> + Send) -> Result<T> {
let (value, refreshes) = collect_committed(operation).await?;
// Nested transactions hand their notifications to the outer transaction.
for refresh in refreshes {
announce(refresh);
}
Ok(value)
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn only_successful_transactions_publish_refreshes() -> Result<()> {
let (_, refreshes) = collect_committed(async {
announce(Refresh::Clash);
after_commit(async {
announce(Refresh::Verge);
Ok(())
})
.await?;
let failed = after_commit(async {
announce(Refresh::Profiles);
Err::<(), _>(anyhow::anyhow!("persistence failed"))
})
.await;
assert!(failed.is_err());
announce(Refresh::Clash);
Ok(())
})
.await?;
assert_eq!(refreshes, [Refresh::Clash, Refresh::Verge, Refresh::Clash]);
Ok(())
}
#[tokio::test]
async fn bursts_keep_each_refresh_kind_and_rearm_during_delivery() -> Result<()> {
let batch = RefreshBatch::default();
let delivered = Mutex::new(Vec::new());
assert!(batch.enqueue(Refresh::Clash));
for refresh in [Refresh::Verge, Refresh::Clash, Refresh::Profiles, Refresh::Proxies] {
assert!(!batch.enqueue(refresh));
}
tokio::time::timeout(Duration::from_secs(1), async {
batch
.flush(|refresh| {
delivered.lock().push(refresh);
if refresh == Refresh::Clash {
assert!(batch.enqueue(Refresh::Clash));
assert!(!batch.enqueue(Refresh::Clash));
}
})
.await;
batch.flush(|refresh| delivered.lock().push(refresh)).await;
})
.await?;
assert_eq!(
*delivered.lock(),
[
Refresh::Clash,
Refresh::Verge,
Refresh::Profiles,
Refresh::Proxies,
Refresh::Clash
]
);
assert!(batch.enqueue(Refresh::Verge));
Ok(())
}
}
@@ -1,6 +1,10 @@
use super::NoticeStatus;
use crate::{APP_HANDLE, singleton}; use crate::{APP_HANDLE, singleton};
use smartstring::alias::String; use smartstring::alias::String;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use tauri::AppHandle; use tauri::AppHandle;
use tauri_plugin_mihomo::{Mihomo, MihomoExt as _}; use tauri_plugin_mihomo::{Mihomo, MihomoExt as _};
@@ -36,19 +40,11 @@ impl Handle {
} }
pub fn refresh_clash() { pub fn refresh_clash() {
Self::send_event(FrontendEvent::RefreshClash); super::announce(super::Refresh::Clash);
} }
pub fn refresh_verge() { pub fn refresh_verge() {
Self::send_event(FrontendEvent::RefreshVerge); super::announce(super::Refresh::Verge);
}
pub fn refresh_profiles() {
Self::send_event(FrontendEvent::RefreshProfiles);
}
pub fn refresh_proxy_config() {
Self::send_event(FrontendEvent::RefreshProxyConfig);
} }
/// Push a Run State snapshot to the frontend. /// Push a Run State snapshot to the frontend.
@@ -80,13 +76,10 @@ impl Handle {
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid }); Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
} }
pub fn notice_message<S: AsRef<str>, M: Into<String>>(status: S, msg: M) { pub fn notice(status: NoticeStatus, message: impl Into<Arc<str>>) {
let status_str = status.as_ref();
let msg_str = msg.into();
Self::send_event(FrontendEvent::NoticeMessage { Self::send_event(FrontendEvent::NoticeMessage {
status: status_str, status,
message: msg_str, message: message.into(),
}); });
} }
@@ -102,7 +95,7 @@ impl Handle {
self.is_exiting.load(Ordering::Acquire) self.is_exiting.load(Ordering::Acquire)
} }
fn send_event(event: FrontendEvent) { pub(super) fn send_event(event: FrontendEvent) {
let handle = Self::global(); let handle = Self::global();
if handle.is_exiting() { if handle.is_exiting() {
return; return;
+174
View File
@@ -0,0 +1,174 @@
mod announce;
pub use announce::{Refresh, after_commit, announce};
pub mod desktop;
pub mod handle;
pub mod notification;
pub use notification::frontend_wire_contract;
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum NoticeStatus {
#[serde(rename = "info")]
Info,
#[serde(rename = "import_sub_url::ok")]
ImportSubUrlOk,
#[serde(rename = "import_sub_url::error")]
ImportSubUrlError,
#[serde(rename = "set_config::error")]
SetConfigError,
#[serde(rename = "core_start::error")]
CoreStartError,
#[serde(rename = "service_core::repair_required")]
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
ServiceCoreRepairRequired,
#[serde(rename = "service_core::app_data_not_owned")]
ServiceCoreAppDataNotOwned,
#[serde(rename = "service_core::sidecar_fallback")]
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
ServiceCoreSidecarFallback,
#[serde(rename = "dns_override::auto_disabled")]
DnsOverrideAutoDisabled,
#[serde(rename = "enhance::discarded_keys")]
EnhanceDiscardedKeys,
#[serde(rename = "tun_mode::auto_disabled")]
TunModeAutoDisabled,
#[serde(rename = "tun_mode::auto_disable_failed")]
TunModeAutoDisableFailed,
#[serde(rename = "app_restart::core_stop_failed")]
AppRestartCoreStopFailed,
#[serde(rename = "app_quit::core_stop_failed")]
AppQuitCoreStopFailed,
#[serde(rename = "update_with_clash_proxy")]
UpdateWithClashProxy,
#[serde(rename = "update_failed_even_with_clash")]
UpdateFailedEvenWithClash,
#[serde(rename = "reactivate_profiles::error")]
ReactivateProfilesError,
#[serde(rename = "update_failed")]
UpdateFailed,
#[serde(rename = "config_validate::boot_error")]
ConfigValidateBootError,
#[serde(rename = "config_validate::error")]
ConfigValidateError,
#[serde(rename = "config_validate::process_terminated")]
ConfigValidateProcessTerminated,
#[serde(rename = "config_validate::script_error")]
ConfigValidateScriptError,
#[serde(rename = "config_validate::script_syntax_error")]
ConfigValidateScriptSyntaxError,
#[serde(rename = "config_validate::script_missing_main")]
ConfigValidateScriptMissingMain,
#[serde(rename = "config_validate::file_not_found")]
ConfigValidateFileNotFound,
#[serde(rename = "config_validate::yaml_syntax_error")]
ConfigValidateYamlSyntaxError,
#[serde(rename = "config_validate::yaml_read_error")]
ConfigValidateYamlReadError,
#[serde(rename = "config_validate::yaml_mapping_error")]
ConfigValidateYamlMappingError,
#[serde(rename = "config_validate::merge_syntax_error")]
ConfigValidateMergeSyntaxError,
#[serde(rename = "config_validate::merge_mapping_error")]
ConfigValidateMergeMappingError,
#[serde(rename = "config_core::change_success")]
ConfigCoreChangeSuccess,
#[serde(rename = "config_core::change_error")]
ConfigCoreChangeError,
#[serde(rename = "mixed_port::fallback")]
MixedPortFallback,
#[serde(rename = "mixed_port::fallback_error")]
MixedPortFallbackError,
}
impl NoticeStatus {
/// Every variant in golden order. The wire-contract export and the golden
/// test both derive their variant list from here; expected strings stay
/// hand-written in the test so renames cannot slip through.
pub const ALL: [Self; 34] = [
Self::Info,
Self::ImportSubUrlOk,
Self::ImportSubUrlError,
Self::SetConfigError,
Self::CoreStartError,
Self::ServiceCoreRepairRequired,
Self::ServiceCoreAppDataNotOwned,
Self::ServiceCoreSidecarFallback,
Self::DnsOverrideAutoDisabled,
Self::EnhanceDiscardedKeys,
Self::TunModeAutoDisabled,
Self::TunModeAutoDisableFailed,
Self::AppRestartCoreStopFailed,
Self::AppQuitCoreStopFailed,
Self::UpdateWithClashProxy,
Self::UpdateFailedEvenWithClash,
Self::ReactivateProfilesError,
Self::UpdateFailed,
Self::ConfigValidateBootError,
Self::ConfigValidateError,
Self::ConfigValidateProcessTerminated,
Self::ConfigValidateScriptError,
Self::ConfigValidateScriptSyntaxError,
Self::ConfigValidateScriptMissingMain,
Self::ConfigValidateFileNotFound,
Self::ConfigValidateYamlSyntaxError,
Self::ConfigValidateYamlReadError,
Self::ConfigValidateYamlMappingError,
Self::ConfigValidateMergeSyntaxError,
Self::ConfigValidateMergeMappingError,
Self::ConfigCoreChangeSuccess,
Self::ConfigCoreChangeError,
Self::MixedPortFallback,
Self::MixedPortFallbackError,
];
}
#[cfg(test)]
mod tests {
use super::NoticeStatus;
#[test]
fn notice_status_wire_contract() -> Result<(), serde_json::Error> {
let statuses = NoticeStatus::ALL;
let expected = [
"info",
"import_sub_url::ok",
"import_sub_url::error",
"set_config::error",
"core_start::error",
"service_core::repair_required",
"service_core::app_data_not_owned",
"service_core::sidecar_fallback",
"dns_override::auto_disabled",
"enhance::discarded_keys",
"tun_mode::auto_disabled",
"tun_mode::auto_disable_failed",
"app_restart::core_stop_failed",
"app_quit::core_stop_failed",
"update_with_clash_proxy",
"update_failed_even_with_clash",
"reactivate_profiles::error",
"update_failed",
"config_validate::boot_error",
"config_validate::error",
"config_validate::process_terminated",
"config_validate::script_error",
"config_validate::script_syntax_error",
"config_validate::script_missing_main",
"config_validate::file_not_found",
"config_validate::yaml_syntax_error",
"config_validate::yaml_read_error",
"config_validate::yaml_mapping_error",
"config_validate::merge_syntax_error",
"config_validate::merge_mapping_error",
"config_core::change_success",
"config_core::change_error",
"mixed_port::fallback",
"mixed_port::fallback_error",
];
let actual: Vec<_> = statuses
.into_iter()
.map(serde_json::to_value)
.collect::<Result<_, _>>()?;
assert_eq!(actual, expected.map(serde_json::Value::from));
Ok(())
}
}
@@ -1,24 +1,22 @@
use super::NoticeStatus;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use serde_json::json; use serde_json::json;
use smartstring::alias::String; use smartstring::alias::String;
use std::{ use std::sync::Arc;
collections::HashMap, use std::sync::LazyLock;
future::Future, use std::{collections::HashMap, future::Future};
sync::atomic::{AtomicU64, Ordering},
};
use tauri::{AppHandle, Emitter as _, Manager as _, WebviewWindow}; use tauri::{AppHandle, Emitter as _, Manager as _, WebviewWindow};
#[derive(Debug)] #[derive(Debug, Clone)]
pub enum FrontendEvent<'a> { pub enum FrontendEvent<'a> {
RefreshClash, RefreshClash,
RefreshVerge, RefreshVerge,
RefreshProfiles, RefreshProfiles,
RefreshProxyConfig, RefreshProxyConfig,
NoticeMessage { NoticeMessage {
status: &'a str, status: NoticeStatus,
message: String, message: Arc<str>,
}, },
ProfileChanged { ProfileChanged {
current_profile_id: &'a String, current_profile_id: &'a String,
@@ -89,16 +87,23 @@ pub struct PendingFailure {
/// Non-destructive pending state, indexed by stable code. /// Non-destructive pending state, indexed by stable code.
#[derive(Debug, Default)] #[derive(Debug, Default)]
struct FailureTable { struct FailureTable {
entries: Mutex<HashMap<String, PendingFailure>>, entries: Mutex<FailureEntries>,
sequence: AtomicU64, }
#[derive(Debug, Default)]
struct FailureEntries {
map: HashMap<String, PendingFailure>,
sequence: u64,
} }
impl FailureTable { impl FailureTable {
fn record(&self, operation: FailedOperation, code: &str, detail: String) { fn record(&self, operation: FailedOperation, code: &str, detail: String) {
// Sequence assignment and replacement must share one ordering lock. // Sequence assignment and replacement must share one ordering lock.
let mut entries = self.entries.lock(); let mut entries = self.entries.lock();
entries.sequence = entries.sequence.wrapping_add(1);
// Preserve an unanswered request over a later restore. // Preserve an unanswered request over a later restore.
let operation = entries let operation = entries
.map
.get(code) .get(code)
.filter(|existing| existing.operation.outranks(operation)) .filter(|existing| existing.operation.outranks(operation))
.map_or(operation, |existing| existing.operation); .map_or(operation, |existing| existing.operation);
@@ -106,13 +111,13 @@ impl FailureTable {
code: code.into(), code: code.into(),
detail, detail,
operation, operation,
sequence: self.sequence.fetch_add(1, Ordering::AcqRel).wrapping_add(1), sequence: entries.sequence,
}; };
entries.insert(code.into(), failure); entries.map.insert(code.into(), failure);
} }
fn snapshot(&self) -> Vec<PendingFailure> { fn snapshot(&self) -> Vec<PendingFailure> {
let mut failures: Vec<PendingFailure> = self.entries.lock().values().cloned().collect(); let mut failures: Vec<PendingFailure> = self.entries.lock().map.values().cloned().collect();
failures.sort_by_key(|failure| failure.sequence); failures.sort_by_key(|failure| failure.sequence);
failures failures
} }
@@ -120,17 +125,21 @@ impl FailureTable {
/// Return whether a guard failure was retired. /// Return whether a guard failure was retired.
fn retire_guard(&self) -> bool { fn retire_guard(&self) -> bool {
let mut entries = self.entries.lock(); let mut entries = self.entries.lock();
let before = entries.len(); let before = entries.map.len();
entries.retain(|_, failure| failure.operation != FailedOperation::SystemProxyGuard); entries
before != entries.len() .map
.retain(|_, failure| failure.operation != FailedOperation::SystemProxyGuard);
before != entries.map.len()
} }
/// Return whether any proxy failure was retired. /// Return whether any proxy failure was retired.
fn retire_system_proxy(&self, asked: FailedOperation) -> bool { fn retire_system_proxy(&self, asked: FailedOperation) -> bool {
let mut entries = self.entries.lock(); let mut entries = self.entries.lock();
let before = entries.len(); let before = entries.map.len();
entries.retain(|_, failure| !failure.operation.retired_by_success_of(asked)); entries
before != entries.len() .map
.retain(|_, failure| !failure.operation.retired_by_success_of(asked));
before != entries.map.len()
} }
} }
@@ -229,7 +238,7 @@ pub fn what_was_asked() -> FailedOperation {
.unwrap_or(FailedOperation::SystemProxyRestore) .unwrap_or(FailedOperation::SystemProxyRestore)
} }
static PENDING_FAILURES: Lazy<FailureTable> = Lazy::new(FailureTable::default); static PENDING_FAILURES: LazyLock<FailureTable> = LazyLock::new(FailureTable::default);
pub fn record_failure(operation: FailedOperation, code: &str, detail: impl Into<String>) { pub fn record_failure(operation: FailedOperation, code: &str, detail: impl Into<String>) {
PENDING_FAILURES.record(operation, code, detail.into()); PENDING_FAILURES.record(operation, code, detail.into());
@@ -237,7 +246,7 @@ pub fn record_failure(operation: FailedOperation, code: &str, detail: impl Into<
} }
pub fn has_pending_failure(code: &str) -> bool { pub fn has_pending_failure(code: &str) -> bool {
PENDING_FAILURES.entries.lock().contains_key(code) PENDING_FAILURES.entries.lock().map.contains_key(code)
} }
/// Return unresolved failures oldest first without clearing them. /// Return unresolved failures oldest first without clearing them.
@@ -283,9 +292,10 @@ impl NotificationSystem {
FrontendEvent::RefreshVerge => ("verge://refresh-verge-config", Ok(json!("yes"))), FrontendEvent::RefreshVerge => ("verge://refresh-verge-config", Ok(json!("yes"))),
FrontendEvent::RefreshProfiles => ("verge://refresh-profiles", Ok(json!("yes"))), FrontendEvent::RefreshProfiles => ("verge://refresh-profiles", Ok(json!("yes"))),
FrontendEvent::RefreshProxyConfig => ("verge://refresh-proxy-config", Ok(serde_json::Value::Null)), FrontendEvent::RefreshProxyConfig => ("verge://refresh-proxy-config", Ok(serde_json::Value::Null)),
FrontendEvent::NoticeMessage { status, message } => { FrontendEvent::NoticeMessage { status, message } => (
("verge://notice-message", serde_json::to_value((status, message))) "verge://notice-message",
} serde_json::to_value((status, message.as_ref())),
),
FrontendEvent::ProfileChanged { current_profile_id } => ("profile-changed", Ok(json!(current_profile_id))), FrontendEvent::ProfileChanged { current_profile_id } => ("profile-changed", Ok(json!(current_profile_id))),
FrontendEvent::TimerUpdated { profile_index } => ("verge://timer-updated", Ok(json!(profile_index))), FrontendEvent::TimerUpdated { profile_index } => ("verge://timer-updated", Ok(json!(profile_index))),
FrontendEvent::ProfileUpdateStarted { uid } => ("profile-update-started", Ok(json!({ "uid": uid }))), FrontendEvent::ProfileUpdateStarted { uid } => ("profile-update-started", Ok(json!({ "uid": uid }))),
@@ -313,3 +323,106 @@ impl NotificationSystem {
} }
} }
} }
#[cfg(test)]
mod wire_tests {
use super::*;
#[test]
fn frontend_event_wire_contract() -> Result<(), serde_json::Error> {
let uid = String::from("profile");
for (event, name, payload) in super::sample_frontend_events(&uid) {
let (actual_name, actual_payload) = NotificationSystem::serialize_event(event);
assert_eq!(actual_name, name);
assert_eq!(actual_payload?, payload);
}
Ok(())
}
}
/// One sample per `FrontendEvent` variant, paired with its wire name and payload.
/// Shared by the wire golden test and the contract export so the two cannot drift.
fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
vec![
(
FrontendEvent::RefreshClash,
"verge://refresh-clash-config",
json!("yes"),
),
(
FrontendEvent::RefreshVerge,
"verge://refresh-verge-config",
json!("yes"),
),
(FrontendEvent::RefreshProfiles, "verge://refresh-profiles", json!("yes")),
(
FrontendEvent::RefreshProxyConfig,
"verge://refresh-proxy-config",
json!(null),
),
(
FrontendEvent::NoticeMessage {
status: NoticeStatus::Info,
message: Arc::from("ok"),
},
"verge://notice-message",
json!(["info", "ok"]),
),
(
FrontendEvent::TimerUpdated { profile_index: uid },
"verge://timer-updated",
json!("profile"),
),
(
FrontendEvent::RunStateChanged {
state: json!({"running": true}),
},
"verge://run-state-changed",
json!({"running": true}),
),
(
FrontendEvent::PendingFailuresChanged,
"verge://pending-failures-changed",
json!(null),
),
(
FrontendEvent::ProfileChanged {
current_profile_id: uid,
},
"profile-changed",
json!("profile"),
),
(
FrontendEvent::ProfileUpdateStarted { uid },
"profile-update-started",
json!({"uid": "profile"}),
),
(
FrontendEvent::ProfileUpdateCompleted { uid },
"profile-update-completed",
json!({"uid": "profile"}),
),
]
}
/// Machine-readable form of the frontend wire contract: every event name with a
/// serialized sample payload, plus every notice status string. The sample
/// payload's JSON shape (string / null / array / object) is what the frontend
/// generator maps to TypeScript types. `ThemeChanged` is a Tauri built-in
/// linux-only window event, not part of this contract.
pub fn frontend_wire_contract() -> serde_json::Value {
let uid = String::from("sample");
let events: Vec<_> = sample_frontend_events(&uid)
.into_iter()
.map(|(event, _, _)| {
let (name, payload) = NotificationSystem::serialize_event(event);
json!({ "name": name, "sample": payload.unwrap_or(serde_json::Value::Null) })
})
.collect();
let statuses: Vec<_> = NoticeStatus::ALL
.iter()
// A unit variant with a string rename cannot fail to serialize.
.filter_map(|status| serde_json::to_value(status).ok())
.collect();
json!({ "version": 1, "events": events, "noticeStatuses": statuses })
}
+25 -16
View File
@@ -522,25 +522,34 @@ pub async fn clear() -> Result<()> {
/// A failed system call is usually a transient RPC hiccup, so give it a few tries. /// A failed system call is usually a transient RPC hiccup, so give it a few tries.
async fn clear_with_retry() -> Result<()> { async fn clear_with_retry() -> Result<()> {
for attempt in 1..CLEAR_ATTEMPTS { use crate::utils::retry::{RetryError, RetryPolicy, retry};
match clear_inner().await { retry(
Err(error) RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
CLEAR_RETRY_DELAY,
),
|attempt| async move {
clear_inner().await.map_err(|error| {
if matches!( if matches!(
SysproxyFailure::from_chain(&error), SysproxyFailure::from_chain(&error),
Some(SysproxyFailure::SystemCallFailed) Some(SysproxyFailure::SystemCallFailed)
) => ) {
{ if attempt + 1 < CLEAR_ATTEMPTS as usize {
logging!( logging!(
warn, warn,
Type::Core, Type::Core,
"clearing the system proxy failed (attempt {attempt}/{CLEAR_ATTEMPTS}); retrying: {error:#}" "clearing the system proxy failed (attempt {}/{CLEAR_ATTEMPTS}); retrying: {error:#}",
); attempt + 1
tokio::time::sleep(CLEAR_RETRY_DELAY).await; );
} }
other => return other, RetryError::Retry(error)
} } else {
} RetryError::Stop(error)
clear_inner().await }
})
},
)
.await
} }
#[tracing::instrument(skip_all, level = "info", fields(route = tracing::field::Empty))] #[tracing::instrument(skip_all, level = "info", fields(route = tracing::field::Empty))]
+15 -14
View File
@@ -19,8 +19,8 @@ use std::{
use anyhow::{Context as _, Result, bail}; use anyhow::{Context as _, Result, bail};
use arc_swap::ArcSwap; use arc_swap::ArcSwap;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::LazyLock;
use tokio::sync::Notify; use tokio::sync::Notify;
#[cfg(test)] #[cfg(test)]
@@ -35,7 +35,7 @@ use health::StoredService;
use probe::{CurrentServiceProbe, classify_service_health, probe_outcome}; use probe::{CurrentServiceProbe, classify_service_health, probe_outcome};
/// The process-wide Run State, observing the real machine. /// The process-wide Run State, observing the real machine.
pub static RUN_STATE: Lazy<RunStateStore<RealEnv>> = Lazy::new(|| RunStateStore::new(RealEnv)); pub static RUN_STATE: LazyLock<RunStateStore<RealEnv>> = LazyLock::new(|| RunStateStore::new(RealEnv));
/// Distinguishes silence from a reply that updated Service health with a rejection. /// Distinguishes silence from a reply that updated Service health with a rejection.
#[derive(Debug)] #[derive(Debug)]
@@ -130,20 +130,21 @@ impl<E: RunStateEnv> RunStateStore<E> {
/// Retries transport failures but stops at the first readable reply, including a rejection. /// 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> { pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
let mut last_error = None; use crate::utils::retry::{RetryError, RetryPolicy, retry};
for attempt in 0..attempts { let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| {
ReadyWaitError::Unreachable(anyhow::anyhow!(
"service readiness wait was configured with no attempts"
))
})?;
retry(RetryPolicy::fixed(attempts, interval), |_| async {
match self.env.probe_service_version().await { match self.env.probe_service_version().await {
Ok(reply) => return self.record_reply(&reply).map_err(ReadyWaitError::Rejected), Ok(reply) => self
Err(error) => last_error = Some(error), .record_reply(&reply)
.map_err(|error| RetryError::Stop(ReadyWaitError::Rejected(error))),
Err(error) => Err(RetryError::Retry(ReadyWaitError::Unreachable(error))),
} }
if attempt + 1 < attempts { })
tokio::time::sleep(interval).await; .await
}
}
Err(ReadyWaitError::Unreachable(last_error.unwrap_or_else(|| {
anyhow::anyhow!("service readiness wait was configured with no attempts")
})))
} }
fn record_reply(&self, reply: &ServiceVersionReply) -> Result<RunState> { fn record_reply(&self, reply: &ServiceVersionReply) -> Result<RunState> {
+110 -85
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use crate::utils::dirs; use crate::utils::dirs;
use crate::{ use crate::{
config::{Config, runtime::IRuntime}, config::{Config, runtime::IRuntime},
@@ -25,8 +26,8 @@ use clash_verge_service_ipc::{
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
StageRuntimeOutcome, StartClashRequest, WriterConfig, StageRuntimeOutcome, StartClashRequest, WriterConfig,
}; };
use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::sync::LazyLock;
use std::{ use std::{
collections::HashMap, collections::HashMap,
env::current_exe, env::current_exe,
@@ -38,7 +39,7 @@ use std::{
}; };
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0); static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
static ACTIVE_SERVICE_SESSION: Lazy<Mutex<Option<ActiveServiceSession>>> = Lazy::new(|| Mutex::new(None)); static ACTIVE_SERVICE_SESSION: LazyLock<Mutex<Option<ActiveServiceSession>>> = LazyLock::new(|| Mutex::new(None));
static PENDING_SERVICE_FALLBACK_NOTICE: AtomicBool = AtomicBool::new(false); static PENDING_SERVICE_FALLBACK_NOTICE: AtomicBool = AtomicBool::new(false);
static PENDING_SERVICE_REPAIR_NOTICE: AtomicBool = AtomicBool::new(false); static PENDING_SERVICE_REPAIR_NOTICE: AtomicBool = AtomicBool::new(false);
static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None); static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
@@ -46,7 +47,7 @@ static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub(crate) fn notify_service_fallback() { pub(crate) fn notify_service_fallback() {
PENDING_SERVICE_FALLBACK_NOTICE.store(true, Ordering::Relaxed); PENDING_SERVICE_FALLBACK_NOTICE.store(true, Ordering::Relaxed);
Handle::notice_message("service_core::sidecar_fallback", ""); Handle::notice(NoticeStatus::ServiceCoreSidecarFallback, "");
} }
pub(crate) fn take_service_fallback_notice() -> bool { pub(crate) fn take_service_fallback_notice() -> bool {
@@ -314,35 +315,40 @@ static SERVICE_CORE_STAGING_GENERATION: AtomicU64 = AtomicU64::new(0);
#[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))] #[cfg(any(all(target_os = "macos", feature = "verge-dev"), test))]
fn create_service_core_staging_file(directory: &Path, core_name: &std::ffi::OsStr) -> Result<(PathBuf, std::fs::File)> { fn create_service_core_staging_file(directory: &Path, core_name: &std::ffi::OsStr) -> Result<(PathBuf, std::fs::File)> {
for _ in 0..32 { use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
let generation = SERVICE_CORE_STAGING_GENERATION.fetch_add(1, Ordering::Relaxed); retry_sync(
let temporary_name = format!( RetryPolicy::fixed(
".{}.{}.{generation}.tmp", std::num::NonZeroUsize::MIN.saturating_add(31),
core_name.to_string_lossy(), std::time::Duration::ZERO,
std::process::id() ),
); |_| {
let temporary_path = directory.join(temporary_name); let generation = SERVICE_CORE_STAGING_GENERATION.fetch_add(1, Ordering::Relaxed);
match std::fs::OpenOptions::new() let temporary_name = format!(
.write(true) ".{}.{}.{generation}.tmp",
.create_new(true) core_name.to_string_lossy(),
.open(&temporary_path) std::process::id()
{ );
Ok(file) => return Ok((temporary_path, file)), let temporary_path = directory.join(temporary_name);
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} match std::fs::OpenOptions::new()
Err(error) => { .write(true)
return Err(error).with_context(|| { .create_new(true)
.open(&temporary_path)
{
Ok(file) => Ok((temporary_path, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
Err(RetryError::Retry(anyhow::anyhow!(
"failed to create a unique temporary development Service core in {}",
directory.display()
)))
}
Err(error) => Err(RetryError::Stop(anyhow::Error::from(error).context({
format!( format!(
"failed to create temporary development Service core {}", "failed to create temporary development Service core {}",
temporary_path.display() temporary_path.display()
) )
}); }))),
} }
} },
}
bail!(
"failed to create a unique temporary development Service core in {}",
directory.display()
) )
} }
@@ -886,11 +892,11 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
if response.code == ServiceErrorCode::InvalidInstallLocation as u16 { if response.code == ServiceErrorCode::InvalidInstallLocation as u16 {
PENDING_SERVICE_REPAIR_NOTICE.store(true, Ordering::Relaxed); PENDING_SERVICE_REPAIR_NOTICE.store(true, Ordering::Relaxed);
Handle::notice_message("service_core::repair_required", ""); Handle::notice(NoticeStatus::ServiceCoreRepairRequired, "");
} }
if response.code == ServiceErrorCode::AppDataRootNotOwned as u16 { if response.code == ServiceErrorCode::AppDataRootNotOwned as u16 {
*PENDING_SERVICE_OWNER_NOTICE.lock() = app_data_owner_command(&credentials); *PENDING_SERVICE_OWNER_NOTICE.lock() = app_data_owner_command(&credentials);
Handle::notice_message("service_core::app_data_not_owned", ""); Handle::notice(NoticeStatus::ServiceCoreAppDataNotOwned, "");
} }
start_owner_monitor(); start_owner_monitor();
return Err(record_service_start_refusal( return Err(record_service_start_refusal(
@@ -1002,7 +1008,6 @@ fn decode_hex(encoded: &str) -> Result<Vec<u8>> {
} }
static PROVIDER_SYNC_QUEUED: AtomicBool = AtomicBool::new(false); static PROVIDER_SYNC_QUEUED: AtomicBool = AtomicBool::new(false);
static PROVIDER_SYNC_SERIAL: Lazy<tokio::sync::Mutex<()>> = Lazy::new(|| tokio::sync::Mutex::new(()));
static SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0); static SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4; const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4;
const CONTENT_COMPARE_CHUNK: usize = 64 * 1024; const CONTENT_COMPARE_CHUNK: usize = 64 * 1024;
@@ -1013,38 +1018,44 @@ pub(crate) fn request_runtime_provider_sync(delay: Duration) {
} }
AsyncHandler::spawn(move || async move { AsyncHandler::spawn(move || async move {
tokio::time::sleep(delay).await; tokio::time::sleep(delay).await;
for attempt in 1..=RUNTIME_PROVIDER_SYNC_ATTEMPTS { use crate::utils::retry::{RetryError, RetryPolicy, retry};
let outcome = { let _ = retry(
let _serial = PROVIDER_SYNC_SERIAL.lock().await; RetryPolicy::fixed(
std::num::NonZeroUsize::MIN.saturating_add((RUNTIME_PROVIDER_SYNC_ATTEMPTS - 1) as usize),
constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY,
),
|index| async move {
let attempt = index as u32 + 1;
if attempt == 1 { if attempt == 1 {
PROVIDER_SYNC_QUEUED.store(false, Ordering::Release); PROVIDER_SYNC_QUEUED.store(false, Ordering::Release);
} }
sync_runtime_providers_by_service().await let outcome = sync_runtime_providers_by_service().await;
}; match outcome {
match outcome { Ok(ProviderSync { pending: 0, .. }) => Ok(()),
Ok(ProviderSync { pending: 0, .. }) => return, Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => { logging!(
logging!( info,
info, Type::Service,
Type::Service, "{pending} provider caches are not ready yet; retrying"
"{pending} provider caches are not ready yet; retrying" );
); Err(RetryError::Retry(()))
}
Ok(ProviderSync { pending, .. }) => {
logging!(warn, Type::Service, "{pending} provider caches were not synced");
Ok(())
}
Err(error) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
Ok(())
}
} }
Ok(ProviderSync { pending, .. }) => { },
logging!(warn, Type::Service, "{pending} provider caches were not synced"); )
return; .await;
}
Err(error) => {
logging!(
warn,
Type::Service,
"failed to sync provider caches from the service: {error:#}"
);
return;
}
}
tokio::time::sleep(constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY).await;
}
}); });
} }
@@ -1352,21 +1363,29 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> {
.file_name() .file_name()
.map(|name| name.to_string_lossy()) .map(|name| name.to_string_lossy())
.unwrap_or_default(); .unwrap_or_default();
for _ in 0..8 { use crate::utils::retry::{RetryError, RetryPolicy, retry};
let sequence = SYNC_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed); retry(
let temp = target.with_file_name(format!(".{name}.sync-{}-{sequence}.tmp", std::process::id())); RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
match tokio::fs::OpenOptions::new() |_| async {
.write(true) let sequence = SYNC_TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed);
.create_new(true) let temp = target.with_file_name(format!(".{name}.sync-{}-{sequence}.tmp", std::process::id()));
.open(&temp) match tokio::fs::OpenOptions::new()
.await .write(true)
{ .create_new(true)
Ok(file) => return Ok((temp, file)), .open(&temp)
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} .await
Err(error) => return Err(error).with_context(|| format!("failed to create {}", temp.display())), {
} Ok(file) => Ok((temp, file)),
} Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Err(RetryError::Retry(
bail!("no free temporary name beside {}", target.display()) anyhow::anyhow!("no free temporary name beside {}", target.display()),
)),
Err(error) => Err(RetryError::Stop(
anyhow::anyhow!(error).context(format!("failed to create {}", temp.display())),
)),
}
},
)
.await
} }
async fn same_contents(temp: &Path, target: &Path) -> bool { async fn same_contents(temp: &Path, target: &Path) -> bool {
@@ -1610,7 +1629,7 @@ fn report_service_core_stopped(status: &ServiceStatusSnapshot) {
); );
logging!(error, Type::Service, "service core stopped: {detail}"); logging!(error, Type::Service, "service core stopped: {detail}");
CoreManager::global().record_startup_error(CoreFailure::ServiceCoreStopped(detail)); CoreManager::global().record_startup_error(CoreFailure::ServiceCoreStopped(detail));
Handle::notice_message("core_start::error", ""); Handle::notice(NoticeStatus::CoreStartError, "");
} }
/// Samples ownership, treating every unusable reply as unreadable. /// Samples ownership, treating every unusable reply as unreadable.
@@ -1733,22 +1752,28 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
} }
async fn clear_proxy_after_owner_loss() { async fn clear_proxy_after_owner_loss() {
let mut last_error = None; use crate::utils::retry::{RetryError, RetryPolicy, retry};
for attempt in 1..=3 { let result = retry(
match proxy_control::clear().await { RetryPolicy::fixed(
Ok(()) => return, std::num::NonZeroUsize::MIN.saturating_add(2),
Err(error) => { Duration::from_millis(100),
),
|index| async move {
let attempt = index + 1;
proxy_control::clear().await.map_err(|error| {
logging!( logging!(
warn, warn,
Type::Service, Type::Service,
"proxy clear attempt {attempt}/3 after owner loss failed: {error:#}" "proxy clear attempt {attempt}/3 after owner loss failed: {error:#}"
); );
last_error = Some(error); RetryError::Retry(error)
tokio::time::sleep(Duration::from_millis(100)).await; })
} },
} )
} .await;
if let Some(error) = last_error { if let Err(error) = result {
// The existing recovery path also waits after its final failed clear.
tokio::time::sleep(Duration::from_millis(100)).await;
logging!( logging!(
error, error,
Type::Service, Type::Service,
+2 -2
View File
@@ -1,14 +1,14 @@
use crate::config::{IProfilePreview, IVerge}; use crate::config::{IProfilePreview, IVerge};
use crate::core::lightweight;
use crate::core::tray::menu_def::TrayAction; use crate::core::tray::menu_def::TrayAction;
use crate::module::lightweight;
use crate::process::AsyncHandler; use crate::process::AsyncHandler;
use crate::singleton; use crate::singleton;
use crate::utils::window_manager::WindowManager; use crate::utils::window_manager::WindowManager;
use crate::{ use crate::{
Type, cmd, Type, cmd,
config::Config, config::Config,
core::lightweight::is_in_lightweight_mode,
feat, logging, feat, logging,
module::lightweight::is_in_lightweight_mode,
utils::{dirs::find_target_icons, help}, utils::{dirs::find_target_icons, help},
}; };
use clash_verge_limiter::{Limiter, SystemClock, SystemLimiter}; use clash_verge_limiter::{Limiter, SystemClock, SystemLimiter};
+12 -19
View File
@@ -2,19 +2,15 @@ use crate::{config::Config, singleton, utils::dirs};
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use chrono::Utc; use chrono::Utc;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
path::PathBuf, path::PathBuf,
sync::atomic::{AtomicBool, Ordering}, sync::atomic::{AtomicBool, Ordering},
}; };
use tauri_plugin_updater::{Update, UpdaterExt as _}; use tauri_plugin_updater::UpdaterExt as _;
pub struct SilentUpdater { pub struct SilentUpdater {
update_ready: AtomicBool, update_ready: AtomicBool,
pending_bytes: RwLock<Option<Vec<u8>>>,
pending_update: RwLock<Option<Update>>,
pending_version: RwLock<Option<String>>,
} }
singleton!(SilentUpdater, SILENT_UPDATER); singleton!(SilentUpdater, SILENT_UPDATER);
@@ -23,9 +19,6 @@ impl SilentUpdater {
const fn new() -> Self { const fn new() -> Self {
Self { Self {
update_ready: AtomicBool::new(false), update_ready: AtomicBool::new(false),
pending_bytes: RwLock::new(None),
pending_update: RwLock::new(None),
pending_version: RwLock::new(None),
} }
} }
@@ -388,12 +381,14 @@ impl SilentUpdater {
// The new webview may not accept evaluation immediately. // The new webview may not accept evaluation immediately.
std::thread::spawn(move || { std::thread::spawn(move || {
for i in 0..10 { use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
std::thread::sleep(std::time::Duration::from_millis(100 * (i + 1))); let _ = retry_sync(
if window.eval(&js).is_ok() { RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(9), std::time::Duration::ZERO),
return; |index| {
} std::thread::sleep(std::time::Duration::from_millis(100 * (index as u64 + 1)));
} window.eval(&js).map_err(RetryError::Retry)
},
);
}); });
logging!(info, Type::System, "Update splash window shown"); logging!(info, Type::System, "Update splash window shown");
@@ -447,8 +442,8 @@ impl SilentUpdater {
Type::System, Type::System,
"Silent updater: breaking change detected in v{version}, notifying frontend" "Silent updater: breaking change detected in v{version}, notifying frontend"
); );
super::handle::Handle::notice_message( super::handle::Handle::notice(
"info", super::notify::NoticeStatus::Info,
format!("New version v{version} contains breaking changes. Please update manually."), format!("New version v{version} contains breaking changes. Please update manually."),
); );
return Ok(()); return Ok(());
@@ -474,9 +469,6 @@ impl SilentUpdater {
logging!(warn, Type::System, "Silent updater: failed to write cache: {e:#}"); logging!(warn, Type::System, "Silent updater: failed to write cache: {e:#}");
} }
*self.pending_bytes.write() = Some(bytes);
*self.pending_update.write() = Some(update);
*self.pending_version.write() = Some(version.clone());
self.update_ready.store(true, Ordering::Release); self.update_ready.store(true, Ordering::Release);
logging!( logging!(
@@ -488,6 +480,7 @@ impl SilentUpdater {
} }
pub async fn start_background_check(&self, app_handle: tauri::AppHandle) { pub async fn start_background_check(&self, app_handle: tauri::AppHandle) {
// Permanent watcher: daily update cycles for the lifetime of the app.
logging!(info, Type::System, "Silent updater: background task started"); logging!(info, Type::System, "Silent updater: background task started");
tokio::time::sleep(std::time::Duration::from_secs(10)).await; tokio::time::sleep(std::time::Duration::from_secs(10)).await;
+2 -1
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
mod chain; mod chain;
pub mod field; pub mod field;
mod merge; mod merge;
@@ -436,7 +437,7 @@ fn notify_discarded_keys(keys: Vec<String>) {
drop(notice); drop(notice);
if should_notify { if should_notify {
Handle::notice_message("enhance::discarded_keys", ""); Handle::notice(NoticeStatus::EnhanceDiscardedKeys, "");
} }
} }
+9 -8
View File
@@ -1,3 +1,5 @@
use crate::core::notify::NoticeStatus;
use crate::core::notify::{Refresh, announce};
use crate::{ use crate::{
config::{Config, MixedPort}, config::{Config, MixedPort},
core::{CoreManager, handle, tray}, core::{CoreManager, handle, tray},
@@ -7,13 +9,13 @@ use crate::{
}; };
use bytes::BytesMut; use bytes::BytesMut;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use serde_yaml_ng::{Mapping, Value}; use serde_yaml_ng::{Mapping, Value};
use smartstring::alias::String; use smartstring::alias::String;
use std::sync::Arc; use std::sync::Arc;
use std::sync::LazyLock;
#[allow(clippy::expect_used)] #[allow(clippy::expect_used)]
static TLS_CONFIG: Lazy<Arc<rustls::ClientConfig>> = Lazy::new(|| { static TLS_CONFIG: LazyLock<Arc<rustls::ClientConfig>> = LazyLock::new(|| {
let root_store = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); let root_store = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
let config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) let config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions() .with_safe_default_protocol_versions()
@@ -26,11 +28,10 @@ static TLS_CONFIG: Lazy<Arc<rustls::ClientConfig>> = Lazy::new(|| {
pub async fn restart_clash_core() { pub async fn restart_clash_core() {
match CoreManager::global().restart_core().await { match CoreManager::global().restart_core().await {
Ok(_) => { Ok(_) => {
handle::Handle::refresh_clash(); announce(Refresh::Clash);
handle::Handle::notice_message("set_config::ok", "ok");
} }
Err(err) => { Err(err) => {
handle::Handle::notice_message("set_config::error", format!("{err:#}")); handle::Handle::notice(NoticeStatus::SetConfigError, format!("{err:#}"));
logging!(error, Type::Core, "restart core failed: {err:#}"); logging!(error, Type::Core, "restart core failed: {err:#}");
} }
} }
@@ -53,8 +54,8 @@ pub async fn restart_app() {
if !cleanup_result.core_stopped { if !cleanup_result.core_stopped {
handle::Handle::global().clear_is_exiting(); handle::Handle::global().clear_is_exiting();
handle::Handle::notice_message( handle::Handle::notice(
"app_restart::core_stop_failed", NoticeStatus::AppRestartCoreStopFailed,
cleanup_result.stop_error.unwrap_or_default(), cleanup_result.stop_error.unwrap_or_default(),
); );
return; return;
@@ -95,7 +96,7 @@ pub async fn change_clash_mode(mode: String) -> Result<(), String> {
let clash_data = clash.data_arc(); let clash_data = clash.data_arc();
if clash_data.save_config().await.is_ok() { if clash_data.save_config().await.is_ok() {
handle::Handle::refresh_clash(); announce(Refresh::Clash);
tray::Tray::global().update_menu_and_icon().await; tray::Tray::global().update_menu_and_icon().await;
} }
+19 -295
View File
@@ -1,279 +1,17 @@
use crate::{ use crate::config::{Config, IVerge};
config::{Config, IVerge},
core::{CoreManager, autostart, handle, hotkey, logger, proxy_control, tray},
module::{auto_backup::AutoBackupManager, lightweight},
};
use anyhow::Result; use anyhow::Result;
use bitflags::bitflags; use clash_verge_draft::SharedDraft;
use clash_verge_draft::{DraftTransaction, SharedDraft};
use clash_verge_logging::{Type, logging, logging_error};
use serde_yaml_ng::Mapping; use serde_yaml_ng::Mapping;
use tokio::sync::MutexGuard; use tokio::sync::MutexGuard;
/// Patch Clash configuration
pub async fn patch_clash(patch: &Mapping) -> Result<()> { pub async fn patch_clash(patch: &Mapping) -> Result<()> {
Config::clash().await.edit_draft(|d| d.patch_config(patch)); let config_write = Config::try_lock_config_write()?;
super::executor::apply(
let res = { &config_write,
// 激活订阅 super::executor::Patch::Clash(patch),
if patch.get("secret").is_some() || patch.get("external-controller").is_some() { super::effects::clash_effects(patch),
Config::generate().await?; )
CoreManager::global().restart_core().await?; .await
} else if patch.get("allow-lan").is_some() {
CoreManager::global().update_config_checked().await?;
} else {
if patch.get("mode").is_some() {
tray::Tray::global().update_menu_and_icon().await;
}
CoreManager::global().update_config_checked().await?;
}
handle::Handle::refresh_clash();
<Result<()>>::Ok(())
};
match res {
Ok(()) => {
Config::clash().await.apply();
// 分离数据获取和异步调用
let clash_data = Config::clash().await.data_arc();
clash_data.save_config().await?;
Ok(())
}
Err(err) => {
Config::clash().await.discard();
Err(err)
}
}
}
// Define update flags as bitflags for better performance
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct UpdateFlags: u16 {
const RESTART_CORE = 1 << 0;
const CLASH_CONFIG = 1 << 1;
const VERGE_CONFIG = 1 << 2;
const LAUNCH = 1 << 3;
const SYS_PROXY = 1 << 4;
const SYSTRAY_ICON = 1 << 5;
const HOTKEY = 1 << 6;
const SYSTRAY_MENU = 1 << 7;
const SYSTRAY_TOOLTIP = 1 << 8;
const SYSTRAY_CLICK_BEHAVIOR = 1 << 9;
const LIGHT_WEIGHT = 1 << 10;
const LANGUAGE = 1 << 11;
const LOG_LEVEL = 1 << 12;
const LOG_FILE = 1 << 13;
const GROUP_SYS_TRAY = Self::SYSTRAY_MENU.bits()
| Self::SYSTRAY_TOOLTIP.bits()
| Self::SYSTRAY_ICON.bits();
}
}
fn determine_update_flags(patch: &IVerge) -> UpdateFlags {
let tun_mode = patch.enable_tun_mode;
let auto_launch = patch.enable_auto_launch;
let system_proxy = patch.enable_system_proxy;
let pac = patch.proxy_auto_config;
let pac_content = &patch.pac_file_content;
let proxy_bypass = &patch.system_proxy_bypass;
let language = &patch.language;
let mixed_port = patch.verge_mixed_port;
#[cfg(target_os = "macos")]
let tray_icon = &patch.tray_icon;
#[cfg(not(target_os = "macos"))]
let tray_icon: Option<String> = None;
let common_tray_icon = patch.common_tray_icon;
let sysproxy_tray_icon = patch.sysproxy_tray_icon;
let tun_tray_icon = patch.tun_tray_icon;
#[cfg(not(target_os = "windows"))]
let redir_enabled = patch.verge_redir_enabled;
#[cfg(not(target_os = "windows"))]
let redir_port = patch.verge_redir_port;
#[cfg(target_os = "linux")]
let tproxy_enabled = patch.verge_tproxy_enabled;
#[cfg(target_os = "linux")]
let tproxy_port = patch.verge_tproxy_port;
let socks_enabled = patch.verge_socks_enabled;
let socks_port = patch.verge_socks_port;
let http_enabled = patch.verge_http_enabled;
let http_port = patch.verge_port;
#[cfg(target_os = "macos")]
let enable_tray_speed = patch.enable_tray_speed;
#[cfg(not(target_os = "macos"))]
let enable_tray_speed: Option<bool> = None;
// let enable_tray_icon = patch.enable_tray_icon;
let enable_global_hotkey = patch.enable_global_hotkey;
let tray_event = &patch.tray_event;
let home_cards = patch.home_cards.as_ref();
let enable_auto_light_weight = patch.enable_auto_light_weight_mode;
let enable_external_controller = patch.enable_external_controller;
let tray_proxy_groups_display_mode = &patch.tray_proxy_groups_display_mode;
let tray_inline_outbound_modes = patch.tray_inline_outbound_modes;
let enable_proxy_guard = patch.enable_proxy_guard;
let proxy_guard_duration = patch.proxy_guard_duration;
let log_level = &patch.app_log_level;
let log_max_size = patch.app_log_max_size;
let log_max_count = patch.app_log_max_count;
#[cfg(target_os = "windows")]
let restart_core_needed = socks_enabled.is_some()
|| http_enabled.is_some()
|| socks_port.is_some()
|| http_port.is_some()
|| mixed_port.is_some()
|| enable_external_controller.is_some();
#[cfg(not(target_os = "windows"))]
let mut restart_core_needed = socks_enabled.is_some()
|| http_enabled.is_some()
|| socks_port.is_some()
|| http_port.is_some()
|| mixed_port.is_some()
|| enable_external_controller.is_some();
#[cfg(not(target_os = "windows"))]
{
restart_core_needed |= redir_enabled.is_some() || redir_port.is_some();
}
#[cfg(target_os = "linux")]
{
restart_core_needed |= tproxy_enabled.is_some() || tproxy_port.is_some();
restart_core_needed |= tun_mode == Some(true);
}
let mut update_flags = UpdateFlags::empty();
if restart_core_needed {
update_flags.insert(UpdateFlags::RESTART_CORE);
}
if tun_mode.is_some() {
update_flags.insert(UpdateFlags::CLASH_CONFIG | UpdateFlags::GROUP_SYS_TRAY);
}
if enable_global_hotkey.is_some() || home_cards.is_some() {
update_flags.insert(UpdateFlags::VERGE_CONFIG);
}
if auto_launch.is_some() {
update_flags.insert(UpdateFlags::LAUNCH);
}
if system_proxy.is_some() {
update_flags.insert(UpdateFlags::SYS_PROXY | UpdateFlags::GROUP_SYS_TRAY);
}
if proxy_bypass.is_some()
|| pac_content.is_some()
|| pac.is_some()
|| enable_proxy_guard.is_some()
|| proxy_guard_duration.is_some()
{
update_flags.insert(UpdateFlags::SYS_PROXY);
}
if language.is_some() {
update_flags.insert(UpdateFlags::LANGUAGE | UpdateFlags::SYSTRAY_MENU | UpdateFlags::SYSTRAY_TOOLTIP);
}
if common_tray_icon.is_some()
|| sysproxy_tray_icon.is_some()
|| tun_tray_icon.is_some()
|| tray_icon.is_some()
|| enable_tray_speed.is_some()
{
update_flags.insert(UpdateFlags::SYSTRAY_ICON);
}
if patch.hotkeys.is_some() {
update_flags.insert(UpdateFlags::HOTKEY | UpdateFlags::SYSTRAY_MENU);
}
if tray_event.is_some() {
update_flags.insert(UpdateFlags::SYSTRAY_CLICK_BEHAVIOR);
}
if enable_auto_light_weight.is_some() {
update_flags.insert(UpdateFlags::LIGHT_WEIGHT);
}
if tray_proxy_groups_display_mode.is_some() {
update_flags.insert(UpdateFlags::SYSTRAY_MENU);
}
if log_level.is_some() {
update_flags.insert(UpdateFlags::LOG_LEVEL);
}
if log_max_size.is_some() || log_max_count.is_some() {
update_flags.insert(UpdateFlags::LOG_FILE);
}
if tray_inline_outbound_modes.is_some() {
update_flags.insert(UpdateFlags::SYSTRAY_MENU);
}
update_flags
}
#[allow(clippy::cognitive_complexity)]
async fn process_terminated_flags(update_flags: UpdateFlags, patch: &IVerge) -> Result<()> {
// Process updates based on flags
if update_flags.contains(UpdateFlags::RESTART_CORE) {
Config::generate().await?;
CoreManager::global().restart_core().await?;
}
if update_flags.contains(UpdateFlags::CLASH_CONFIG) {
CoreManager::global().update_config_checked().await?;
handle::Handle::refresh_clash();
}
if update_flags.contains(UpdateFlags::LAUNCH) {
autostart::update_launch().await?;
}
if update_flags.contains(UpdateFlags::LANGUAGE)
&& let Some(language) = &patch.language
{
clash_verge_i18n::set_locale(language.as_str());
}
if update_flags.contains(UpdateFlags::SYS_PROXY) {
let manager = CoreManager::global();
let _lifecycle = manager.lifecycle_lock.lock().await;
// Turning it off only writes OS state, so it must stay available while the Core is down.
if Config::verge()
.await
.latest_arc()
.enable_system_proxy
.unwrap_or_default()
{
manager.apply_proxy_after_start().await?;
} else {
proxy_control::apply().await?;
proxy_control::refresh_guard().await?;
}
}
if update_flags.contains(UpdateFlags::HOTKEY)
&& let Some(hotkeys) = &patch.hotkeys
{
hotkey::Hotkey::global().update(hotkeys.to_owned()).await?;
}
if update_flags.contains(UpdateFlags::SYSTRAY_MENU) {
tray::Tray::global().update_menu().await?;
}
if update_flags.contains(UpdateFlags::SYSTRAY_ICON) {
tray::Tray::global()
.update_icon(&Config::verge().await.latest_arc())
.await?;
#[cfg(target_os = "macos")]
if patch.enable_tray_speed.is_some() {
tray::Tray::global().update_speed_task(patch.enable_tray_speed.unwrap_or(false));
}
}
if update_flags.contains(UpdateFlags::SYSTRAY_TOOLTIP) {
tray::Tray::global().update_tooltip().await?;
}
if update_flags.contains(UpdateFlags::SYSTRAY_CLICK_BEHAVIOR) {
tray::Tray::global().update_click_behavior().await?;
}
if update_flags.contains(UpdateFlags::LIGHT_WEIGHT) {
if patch.enable_auto_light_weight_mode.unwrap_or(false) {
lightweight::enable_auto_light_weight_mode().await;
} else {
lightweight::disable_auto_light_weight_mode();
}
}
if update_flags.contains(UpdateFlags::LOG_LEVEL) {
logger::Logger::global().update_log_level(patch.get_log_level())?;
}
if update_flags.contains(UpdateFlags::LOG_FILE) {
let log_max_size = patch.app_log_max_size.unwrap_or(128);
let log_max_count = patch.app_log_max_count.unwrap_or(8);
logger::update_log_config(log_max_size, log_max_count).await?;
}
Ok(())
} }
/// Apply a patch, then reconcile TUN when its setting changes. /// Apply a patch, then reconcile TUN when its setting changes.
@@ -289,7 +27,7 @@ pub async fn patch_verge(patch: &IVerge, not_save_file: bool) -> Result<()> {
/// Apply a patch without post-update reconciliation. /// Apply a patch without post-update reconciliation.
pub(super) async fn apply_verge_patch(patch: &IVerge, not_save_file: bool) -> Result<()> { pub(super) async fn apply_verge_patch(patch: &IVerge, not_save_file: bool) -> Result<()> {
let config_write = Config::lock_config_write().await; let config_write = Config::try_lock_config_write()?;
apply_verge_patch_locked(&config_write, patch, not_save_file).await apply_verge_patch_locked(&config_write, patch, not_save_file).await
} }
@@ -300,29 +38,15 @@ pub(super) async fn apply_verge_patch_locked(
patch: &IVerge, patch: &IVerge,
not_save_file: bool, not_save_file: bool,
) -> Result<()> { ) -> Result<()> {
let verge = Config::verge().await; super::executor::apply(
// Hold the claim across side effects so concurrent transactions cannot share this draft. _config_write,
let transaction = DraftTransaction::begin(vec![&verge])?; super::executor::Patch::Verge {
verge.edit_draft(|d| d.patch_config(patch)); patch,
persist: !not_save_file,
let update_flags = determine_update_flags(patch); },
logging!(debug, Type::Setup, "Determined update flags: {:?}", update_flags); super::effects::verge_effects(patch),
// A failed patch rolls back to what the user already had; it never invents a value for them. )
process_terminated_flags(update_flags, patch).await?; .await
transaction.commit();
announce_verge_change();
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
if !not_save_file {
// 分离数据获取和异步调用
let verge_data = verge.data_arc();
verge_data.save_file().await?;
}
Ok(())
}
fn announce_verge_change() {
handle::Handle::refresh_verge();
} }
pub async fn fetch_verge_config() -> Result<SharedDraft<IVerge>> { pub async fn fetch_verge_config() -> Result<SharedDraft<IVerge>> {
+23 -16
View File
@@ -359,24 +359,31 @@ fn stage_core(target: &Path, package: &[u8], version: &str) -> Result<StagedCore
} }
fn create_staging_file(directory: &Path, core_name: &OsStr) -> Result<(PathBuf, File)> { fn create_staging_file(directory: &Path, core_name: &OsStr) -> Result<(PathBuf, File)> {
for _ in 0..32 { use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
let generation = STAGING_GENERATION.fetch_add(1, Ordering::Relaxed); retry_sync(
let path = directory.join(format!( RetryPolicy::fixed(
".{}.{}.{generation}.tmp", std::num::NonZeroUsize::MIN.saturating_add(31),
core_name.to_string_lossy(), std::time::Duration::ZERO,
std::process::id() ),
)); |_| {
let generation = STAGING_GENERATION.fetch_add(1, Ordering::Relaxed);
let path = directory.join(format!(
".{}.{}.{generation}.tmp",
core_name.to_string_lossy(),
std::process::id()
));
match File::options().write(true).create_new(true).open(&path) { match File::options().write(true).create_new(true).open(&path) {
Ok(file) => return Ok((path, file)), Ok(file) => Ok((path, file)),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Err(RetryError::Retry(
Err(error) => { anyhow::anyhow!("failed to create a unique staging file in {}", directory.display()),
return Err(error).with_context(|| format!("failed to create {}", path.display())); )),
Err(error) => Err(RetryError::Stop(
anyhow::Error::from(error).context(format!("failed to create {}", path.display())),
)),
} }
} },
} )
bail!("failed to create a unique staging file in {}", directory.display())
} }
#[cfg(windows)] #[cfg(windows)]
+12 -3
View File
@@ -1,3 +1,4 @@
use crate::core::notify::{Refresh, announce};
use anyhow::{Result, ensure}; use anyhow::{Result, ensure};
use clash_verge_draft::DraftTransaction; use clash_verge_draft::DraftTransaction;
use serde::Serialize; use serde::Serialize;
@@ -10,7 +11,7 @@ use crate::{
profiles::PROFILE_WRITE_LOCK, profiles::PROFILE_WRITE_LOCK,
}, },
constants::files::DNS_CONFIG, constants::files::DNS_CONFIG,
core::{CoreManager, handle::Handle}, core::CoreManager,
utils::dirs, utils::dirs,
}; };
@@ -25,6 +26,14 @@ pub async fn set_dns_override(
profile_uid: String, profile_uid: String,
enabled: bool, enabled: bool,
confirmation: Option<String>, confirmation: Option<String>,
) -> Result<DnsOverrideOutcome> {
crate::core::notify::after_commit(Box::pin(set_dns_override_inner(profile_uid, enabled, confirmation))).await
}
async fn set_dns_override_inner(
profile_uid: String,
enabled: bool,
confirmation: Option<String>,
) -> Result<DnsOverrideOutcome> { ) -> Result<DnsOverrideOutcome> {
let _profile_write = PROFILE_WRITE_LOCK.lock().await; let _profile_write = PROFILE_WRITE_LOCK.lock().await;
let _config_write = Config::lock_config_write().await; let _config_write = Config::lock_config_write().await;
@@ -74,8 +83,8 @@ pub async fn set_dns_override(
} }
transaction.commit(); transaction.commit();
Handle::refresh_verge();
Handle::refresh_clash();
verge.data_arc().save_file().await?; verge.data_arc().save_file().await?;
announce(Refresh::Verge);
announce(Refresh::Clash);
Ok(outcome) Ok(outcome)
} }
+296
View File
@@ -0,0 +1,296 @@
use crate::config::IVerge;
use std::collections::BTreeSet;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum Effect {
RestartCore,
ClashConfig,
VergeConfig,
Autostart,
SystemProxy,
TrayIcon,
Hotkey,
TrayMenu,
TrayTooltip,
TrayClick,
Lightweight,
Language,
LogLevel,
LogFile,
}
pub(super) type Effects = BTreeSet<Effect>;
macro_rules! select_field {
($effects:ident, $field:ident, NoEffect) => { let _ = $field; };
($effects:ident, $field:ident, [$($effect:ident),*]) => {
if $field.is_some() { $effects.extend([$(Effect::$effect),*]); }
};
($effects:ident, $field:ident, Tun) => {
select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]);
#[cfg(target_os = "linux")]
if *$field == Some(true) { $effects.insert(Effect::RestartCore); }
};
}
macro_rules! verge_registry {
($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => {
pub(super) fn verge_effects(patch: &IVerge) -> Effects {
// No rest pattern: even fields omitted by serde must be classified at compile time.
let IVerge { $( $(#[$cfg])* $field, )* } = patch;
let mut effects = Effects::new();
$( $(#[$cfg])* { select_field!(effects, $field, $rule); } )*
effects
}
#[cfg(test)]
const VERGE_FIELDS: &[&str] = &[ $( $(#[$cfg])* stringify!($field), )* ];
};
}
verge_registry! {
app_log_level => [LogLevel];
app_log_max_size => [LogFile];
app_log_max_count => [LogFile];
language => [Language, TrayMenu, TrayTooltip];
theme_mode => NoEffect;
tray_event => [TrayClick];
env_type => NoEffect;
start_page => NoEffect;
startup_script => NoEffect;
traffic_graph => NoEffect;
enable_memory_usage => NoEffect;
enable_group_icon => NoEffect;
pause_render_traffic_stats_on_blur => NoEffect;
common_tray_icon => [TrayIcon];
#[cfg(target_os = "macos")]
tray_icon => [TrayIcon];
menu_icon => NoEffect;
menu_order => NoEffect;
proxy_group_tools_position => NoEffect;
notice_position => NoEffect;
collapse_navbar => NoEffect;
sysproxy_tray_icon => [TrayIcon];
tun_tray_icon => [TrayIcon];
enable_tun_mode => Tun;
enable_auto_launch => [Autostart];
enable_silent_start => NoEffect;
enable_system_proxy => [SystemProxy, TrayMenu, TrayTooltip, TrayIcon];
enable_proxy_guard => [SystemProxy];
enable_bypass_check => NoEffect;
enable_dns_settings => NoEffect;
profile_dns_settings => NoEffect;
use_default_bypass => NoEffect;
system_proxy_bypass => [SystemProxy];
proxy_guard_duration => [SystemProxy];
proxy_auto_config => [SystemProxy];
pac_file_content => [SystemProxy];
proxy_host => NoEffect;
theme_setting => NoEffect;
web_ui_list => NoEffect;
clash_core => NoEffect;
hotkeys => [Hotkey, TrayMenu];
enable_global_hotkey => [VergeConfig];
home_cards => [VergeConfig];
auto_close_connection => NoEffect;
auto_check_update => NoEffect;
default_latency_test => NoEffect;
default_latency_timeout => NoEffect;
enable_auto_delay_detection => NoEffect;
auto_delay_detection_interval_minutes => NoEffect;
enable_builtin_enhanced => NoEffect;
proxy_layout_column => NoEffect;
test_list => NoEffect;
auto_log_clean => NoEffect;
enable_auto_backup_schedule => NoEffect;
auto_backup_interval_hours => NoEffect;
auto_backup_on_change => NoEffect;
#[cfg(not(target_os = "windows"))]
verge_redir_port => [RestartCore];
#[cfg(not(target_os = "windows"))]
verge_redir_enabled => [RestartCore];
#[cfg(target_os = "linux")]
verge_tproxy_port => [RestartCore];
#[cfg(target_os = "linux")]
verge_tproxy_enabled => [RestartCore];
verge_mixed_port => [RestartCore];
verge_socks_port => [RestartCore];
verge_socks_enabled => [RestartCore];
verge_port => [RestartCore];
verge_http_enabled => [RestartCore];
webdav_url => NoEffect;
webdav_username => NoEffect;
webdav_password => NoEffect;
#[cfg(target_os = "macos")]
enable_tray_speed => [TrayIcon];
tray_proxy_groups_display_mode => [TrayMenu];
tray_inline_outbound_modes => [TrayMenu];
enable_auto_light_weight_mode => [Lightweight];
auto_light_weight_minutes => NoEffect;
enable_hover_jump_navigator => NoEffect;
hover_jump_navigator_delay => NoEffect;
enable_external_controller => [RestartCore];
}
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
use clash_verge_logging::{Type, logging};
let mut effects = Effects::new();
for key in patch.keys() {
effects.extend(match key.as_str() {
Some("secret" | "external-controller") => &[Effect::RestartCore][..],
Some("allow-lan") => &[Effect::ClashConfig][..],
Some("mode") => &[Effect::ClashConfig, Effect::TrayMenu, Effect::TrayIcon][..],
_ => {
logging!(
warn,
Type::Config,
"Unregistered Clash configuration key {key:?}; reloading configuration"
);
&[Effect::ClashConfig][..]
}
});
}
// These branches were exclusive: restart supersedes reload, and allow-lan precedes mode.
if effects.contains(&Effect::RestartCore) {
effects.retain(|effect| *effect == Effect::RestartCore);
} else if patch.contains_key("allow-lan") {
effects.retain(|effect| *effect == Effect::ClashConfig);
}
if patch.is_empty() {
effects.insert(Effect::ClashConfig);
}
effects
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_serialized_verge_field_is_registered() -> Result<(), serde_json::Error> {
let fields: std::collections::BTreeMap<String, serde_json::Value> =
serde_json::from_value(serde_json::to_value(IVerge::default())?)?;
for field in fields.keys() {
assert!(VERGE_FIELDS.contains(&field.as_str()), "unregistered field: {field}");
}
let unique: BTreeSet<_> = VERGE_FIELDS.iter().collect();
assert_eq!(unique.len(), VERGE_FIELDS.len());
Ok(())
}
fn verge_patch(mutate: impl FnOnce(&mut IVerge)) -> IVerge {
let mut patch = IVerge::default();
mutate(&mut patch);
patch
}
#[test]
fn representative_verge_patches_map_to_frozen_effects() {
assert_eq!(verge_effects(&IVerge::default()), Effects::new());
let cases: [(IVerge, &[Effect]); 7] = [
(
verge_patch(|p| p.verge_mixed_port = Some(27899)),
&[Effect::RestartCore],
),
(
verge_patch(|p| p.language = Some("zh".into())),
&[Effect::TrayMenu, Effect::TrayTooltip, Effect::Language],
),
(
verge_patch(|p| p.hotkeys = Some(vec!["CmdOrCtrl+K".into()])),
&[Effect::Hotkey, Effect::TrayMenu],
),
(
verge_patch(|p| p.enable_system_proxy = Some(true)),
&[
Effect::SystemProxy,
Effect::TrayIcon,
Effect::TrayMenu,
Effect::TrayTooltip,
],
),
(
verge_patch(|p| p.system_proxy_bypass = Some("localhost".into())),
&[Effect::SystemProxy],
),
(
verge_patch(|p| p.tray_event = Some("show_main_window".into())),
&[Effect::TrayClick],
),
(verge_patch(|p| p.theme_mode = Some("dark".into())), &[]),
];
for (patch, expected) in cases {
assert_eq!(
verge_effects(&patch),
expected.iter().copied().collect::<Effects>(),
"patch mapping drifted for {expected:?}"
);
}
let tun = verge_patch(|p| p.enable_tun_mode = Some(true));
#[cfg(target_os = "linux")]
assert_eq!(
verge_effects(&tun),
[
Effect::RestartCore,
Effect::ClashConfig,
Effect::TrayIcon,
Effect::TrayMenu,
Effect::TrayTooltip,
]
.into_iter()
.collect::<Effects>()
);
#[cfg(not(target_os = "linux"))]
assert_eq!(
verge_effects(&tun),
[
Effect::ClashConfig,
Effect::TrayIcon,
Effect::TrayMenu,
Effect::TrayTooltip,
]
.into_iter()
.collect::<Effects>()
);
}
fn clash_mapping(pairs: &[(&str, &str)]) -> serde_yaml_ng::Mapping {
let mut mapping = serde_yaml_ng::Mapping::new();
for (key, value) in pairs {
mapping.insert((*key).into(), (*value).into());
}
mapping
}
#[test]
fn clash_keys_map_to_frozen_effects() {
let cases: [(serde_yaml_ng::Mapping, &[Effect]); 7] = [
(clash_mapping(&[]), &[Effect::ClashConfig]),
(clash_mapping(&[("secret", "s")]), &[Effect::RestartCore]),
(
clash_mapping(&[("mode", "rule")]),
&[Effect::ClashConfig, Effect::TrayIcon, Effect::TrayMenu],
),
(clash_mapping(&[("allow-lan", "true")]), &[Effect::ClashConfig]),
(clash_mapping(&[("not-a-known-key", "1")]), &[Effect::ClashConfig]),
// Restart supersedes reload; allow-lan precedes mode.
(
clash_mapping(&[("secret", "s"), ("mode", "rule")]),
&[Effect::RestartCore],
),
(
clash_mapping(&[("allow-lan", "true"), ("mode", "rule")]),
&[Effect::ClashConfig],
),
];
for (patch, expected) in cases {
assert_eq!(
clash_effects(&patch),
expected.iter().copied().collect::<Effects>(),
"clash mapping drifted for {expected:?}"
);
}
}
}
+195
View File
@@ -0,0 +1,195 @@
use super::effects::{Effect, Effects};
use crate::core::notify::{Refresh, announce};
use crate::{
config::{
Config, IVerge,
snapshot::{capture_config_files, restore_files},
},
core::auto_backup::AutoBackupManager,
core::{CoreManager, logger, manager::ConfigUpdateGuard, proxy_control},
};
use anyhow::Result;
use clash_verge_draft::DraftTransaction;
use clash_verge_logging::{Type, logging_error};
use futures::future::BoxFuture;
use serde_yaml_ng::Mapping;
use tokio::sync::MutexGuard;
pub(super) enum Patch<'a> {
Verge { patch: &'a IVerge, persist: bool },
Clash(&'a Mapping),
}
struct EffectContext<'a> {
patch: &'a IVerge,
manager: &'a CoreManager,
update: &'a ConfigUpdateGuard<'a>,
}
type Ensure = for<'a> fn(&'a EffectContext<'_>) -> BoxFuture<'a, Result<()>>;
const EFFECT_ORDER: &[(Effect, Ensure)] = &[
(Effect::RestartCore, ensure_restart),
(Effect::ClashConfig, ensure_clash),
(Effect::VergeConfig, ensure_verge),
(Effect::Autostart, ensure_autostart),
(Effect::Language, ensure_language),
(Effect::SystemProxy, ensure_system_proxy),
(Effect::Hotkey, ensure_hotkey),
(Effect::TrayMenu, ensure_tray_menu),
(Effect::TrayIcon, ensure_tray_icon),
(Effect::TrayTooltip, ensure_tray_tooltip),
(Effect::TrayClick, ensure_tray_click),
(Effect::Lightweight, ensure_lightweight),
(Effect::LogLevel, ensure_log_level),
(Effect::LogFile, ensure_log_file),
];
macro_rules! ensure {
($name:ident, $ctx:ident, $body:block) => {
fn $name<'a>($ctx: &'a EffectContext<'_>) -> BoxFuture<'a, Result<()>> {
Box::pin(async move $body)
}
};
}
ensure!(ensure_restart, ctx, {
Config::generate().await?;
ctx.manager.restart_core_during_config_update().await
});
ensure!(ensure_clash, ctx, {
ctx.manager.update_config_in_patch(ctx.update).await?;
announce(Refresh::Clash);
Ok(())
});
ensure!(ensure_verge, _ctx, { Ok(()) });
ensure!(ensure_autostart, ctx, {
crate::core::app_effects::ensure_autostart(ctx.patch).await
});
ensure!(ensure_language, ctx, {
if let Some(language) = &ctx.patch.language {
clash_verge_i18n::set_locale(language.as_str());
}
Ok(())
});
ensure!(ensure_system_proxy, ctx, {
let _lifecycle = ctx.manager.lifecycle_lock.lock().await;
// Disabling only writes OS state and must remain available when the Core is stopped.
if Config::verge()
.await
.latest_arc()
.enable_system_proxy
.unwrap_or_default()
{
ctx.manager.apply_proxy_after_start().await
} else {
proxy_control::apply().await?;
proxy_control::refresh_guard().await
}
});
ensure!(ensure_hotkey, ctx, {
crate::core::app_effects::ensure_hotkey(ctx.patch).await
});
ensure!(ensure_tray_menu, ctx, {
crate::core::app_effects::ensure_tray_menu(ctx.patch).await
});
ensure!(ensure_tray_icon, ctx, {
crate::core::app_effects::ensure_tray_icon(ctx.patch).await
});
ensure!(ensure_tray_tooltip, ctx, {
crate::core::app_effects::ensure_tray_tooltip(ctx.patch).await
});
ensure!(ensure_tray_click, ctx, {
crate::core::app_effects::ensure_tray_click(ctx.patch).await
});
ensure!(ensure_lightweight, ctx, {
crate::core::app_effects::ensure_lightweight(ctx.patch).await
});
ensure!(ensure_log_level, ctx, {
logger::Logger::global().update_log_level(ctx.patch.get_log_level())
});
ensure!(ensure_log_file, ctx, {
logger::update_log_config(
ctx.patch.app_log_max_size.unwrap_or(128),
ctx.patch.app_log_max_count.unwrap_or(8),
)
.await
});
async fn apply_inner(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
let manager = CoreManager::global();
let update = manager.claim_config_update(config_write)?;
let clash = Config::clash().await;
let verge = Config::verge().await;
let runtime = Config::runtime().await;
let transaction = match patch {
Patch::Verge { .. } => DraftTransaction::begin(vec![&verge, &runtime])?,
Patch::Clash(_) => DraftTransaction::begin(vec![&clash, &runtime])?,
};
let snapshots = capture_config_files().await?;
let empty = IVerge::default();
let context = EffectContext {
patch: match &patch {
Patch::Verge { patch, .. } => patch,
Patch::Clash(_) => &empty,
},
manager,
update: &update,
};
match &patch {
Patch::Verge { patch, .. } => verge.edit_draft(|draft| draft.patch_config(patch)),
Patch::Clash(patch) => clash.edit_draft(|draft| draft.patch_config(patch)),
}
let result: Result<()> = async {
for (effect, ensure) in EFFECT_ORDER {
if effects.contains(effect) {
ensure(&context).await?;
}
}
match patch {
Patch::Verge { persist: true, .. } => verge.latest_arc().save_file().await?,
Patch::Verge { persist: false, .. } => {}
Patch::Clash(_) => clash.latest_arc().save_config().await?,
}
Ok(())
}
.await;
if let Err(error) = result {
transaction.rollback();
return match restore_files(&snapshots).await {
Ok(()) => Err(error),
Err(rollback_error) => Err(proxy_control::rollback_failure(error, rollback_error)),
};
}
transaction.commit();
match patch {
Patch::Verge { .. } => {
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
announce(Refresh::Verge);
}
Patch::Clash(_) => announce(Refresh::Clash),
}
Ok(())
}
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
crate::core::notify::after_commit(apply_inner(config_write, patch, effects)).await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn config_claim_is_exclusive_and_released_on_drop() -> Result<()> {
let write_lock = tokio::sync::Mutex::new(());
let write = write_lock.lock().await;
let manager = CoreManager::default();
let first = manager.claim_config_update(&write)?;
assert!(manager.claim_config_update(&write).is_err());
drop(first);
assert!(manager.claim_config_update(&write).is_ok());
drop(write);
Ok(())
}
}
+8 -4
View File
@@ -1,3 +1,4 @@
use crate::core::notify::{Refresh, announce};
use crate::{ use crate::{
config::{ config::{
Config, MixedPort, Config, MixedPort,
@@ -5,7 +6,6 @@ use crate::{
}, },
core::{ core::{
CoreManager, CoreManager,
handle::Handle,
listener::{ listener::{
ListenerProbe, ListenerProbeOutcome, ProxyPortSettings, SaveProxyPortsOutcome, ListenerProbe, ListenerProbeOutcome, ProxyPortSettings, SaveProxyPortsOutcome,
probe_listener as probe_listener_sync, probe_proxy_port_change, probe_listener as probe_listener_sync, probe_proxy_port_change,
@@ -27,8 +27,12 @@ pub async fn probe_listener(request: ListenerProbe) -> Result<ListenerProbeOutco
.context("listener probe task failed") .context("listener probe task failed")
} }
#[allow(clippy::cognitive_complexity)]
pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPortsOutcome> { pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPortsOutcome> {
crate::core::notify::after_commit(Box::pin(save_proxy_ports_inner(settings))).await
}
#[allow(clippy::cognitive_complexity)]
async fn save_proxy_ports_inner(settings: ProxyPortSettings) -> Result<SaveProxyPortsOutcome> {
settings.validate()?; settings.validate()?;
let _config_write = Config::lock_config_write().await; let _config_write = Config::lock_config_write().await;
let manager = CoreManager::global(); let manager = CoreManager::global();
@@ -126,8 +130,8 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
transaction.commit(); transaction.commit();
// The save landed, so the port the app had borrowed is now irrelevant. // The save landed, so the port the app had borrowed is now irrelevant.
let _ = ScopeGuard::into_inner(borrowed_port); let _ = ScopeGuard::into_inner(borrowed_port);
Handle::refresh_clash(); announce(Refresh::Clash);
Handle::refresh_verge(); announce(Refresh::Verge);
logging!(info, Type::Config, "Proxy port configuration applied and persisted"); logging!(info, Type::Config, "Proxy port configuration applied and persisted");
Ok(SaveProxyPortsOutcome::Saved) Ok(SaveProxyPortsOutcome::Saved)
} }
+2
View File
@@ -3,6 +3,8 @@ mod clash;
mod config; mod config;
mod core_upgrade; mod core_upgrade;
mod dns; mod dns;
mod effects;
mod executor;
mod icon; mod icon;
mod listener; mod listener;
mod profile; mod profile;
+74 -56
View File
@@ -1,3 +1,5 @@
use crate::core::notify::NoticeStatus;
use crate::core::notify::{Refresh, announce};
use crate::{ use crate::{
cmd, cmd,
config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe}, config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe},
@@ -43,7 +45,7 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str) {
{ {
Ok(_) => { Ok(_) => {
record_switched_node(group_name, proxy_name).await; record_switched_node(group_name, proxy_name).await;
handle::Handle::refresh_proxy_config(); announce(Refresh::Proxies);
let _ = tray::Tray::global().update_menu().await; let _ = tray::Tray::global().update_menu().await;
return; return;
} }
@@ -100,7 +102,7 @@ async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result
} }
} }
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty))] #[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
async fn perform_profile_update( async fn perform_profile_update(
uid: &String, uid: &String,
url: &String, url: &String,
@@ -108,7 +110,7 @@ async fn perform_profile_update(
option: Option<&PrfOption>, option: Option<&PrfOption>,
is_mannual_trigger: bool, is_mannual_trigger: bool,
) -> Result<()> { ) -> Result<()> {
let mut merged_opt = PrfOption::merge(opt, option); let merged_opt = PrfOption::merge(opt, option);
let profiles = Config::profiles().await; let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc(); let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc let profile_name = profiles_arc
@@ -117,66 +119,82 @@ async fn perform_profile_update(
.and_then(|item| item.name.clone()) .and_then(|item| item.name.clone())
.unwrap_or_else(|| String::from("UnKnown Profile")); .unwrap_or_else(|| String::from("UnKnown Profile"));
match PrfItem::from_url(url, None, None, merged_opt.as_ref()).await { #[derive(Clone, Copy)]
Ok(mut item) => { enum Strategy {
logging!(info, Type::Config, "[订阅更新] 更新订阅配置成功"); Configured,
profiles_update_item_safe(uid, &mut item).await?; Clash,
return Ok(()); System,
}
Err(err) => {
logging!(
warn,
Type::Config,
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
mask_err(&format!("{err:#}"))
);
}
} }
merged_opt.get_or_insert_with(PrfOption::default).self_proxy = Some(true); let result =
merged_opt.get_or_insert_with(PrfOption::default).with_proxy = Some(false); crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| {
let mut options = merged_opt.clone();
match PrfItem::from_url(url, None, None, merged_opt.as_ref()).await { async move {
Ok(mut item) => { let (name, success, failure) = match strategy {
logging!(info, Type::Config, "[订阅更新] 使用 Clash代理 更新订阅配置成功"); Strategy::Configured => (
"configured",
"[订阅更新] 更新订阅配置成功",
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
),
Strategy::Clash => (
"clash",
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
),
Strategy::System => (
"system",
"[订阅更新] 使用 系统代理 更新订阅配置成功",
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
),
};
match strategy {
Strategy::Configured => {}
Strategy::Clash | Strategy::System => {
let option = options.get_or_insert_with(PrfOption::default);
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
option.with_proxy = Some(matches!(strategy, Strategy::System));
}
}
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = PrfItem::from_url(url, None, None, options.as_ref()).await;
let elapsed_field = match strategy {
Strategy::Configured => "configured_elapsed",
Strategy::Clash => "clash_elapsed",
Strategy::System => "system_elapsed",
};
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
match &result {
Ok(_) => logging!(info, Type::Config, "{success}"),
Err(error) => logging!(
warn,
Type::Config,
"{}",
failure.replace("{}", &mask_err(&format!("{error:#}")))
),
}
result
}
})
.await;
let last_err = match result {
Ok((strategy, mut item)) => {
// A persistence error must not replay a successful download with another transport.
profiles_update_item_safe(uid, &mut item).await?; profiles_update_item_safe(uid, &mut item).await?;
handle::Handle::notice_message("update_with_clash_proxy", profile_name); if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
}
return Ok(()); return Ok(());
} }
Err(err) => { Err(error) => error,
logging!(
warn,
Type::Config,
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
mask_err(&format!("{err:#}"))
);
}
}
merged_opt.get_or_insert_with(PrfOption::default).self_proxy = Some(false);
merged_opt.get_or_insert_with(PrfOption::default).with_proxy = Some(true);
let last_err = match PrfItem::from_url(url, None, None, merged_opt.as_ref()).await {
Ok(mut item) => {
logging!(info, Type::Config, "[订阅更新] 使用 系统代理 更新订阅配置成功");
profiles_update_item_safe(uid, &mut item).await?;
handle::Handle::notice_message("update_with_clash_proxy", profile_name);
return Ok(());
}
Err(err) => {
logging!(
warn,
Type::Config,
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
mask_err(&format!("{err:#}"))
);
err
}
}; };
let last_err = mask_err(&last_err.to_string()); let last_err = mask_err(&last_err.to_string());
if is_mannual_trigger { if is_mannual_trigger {
handle::Handle::notice_message("update_failed_even_with_clash", format!("{profile_name} - {last_err}")); handle::Handle::notice(
NoticeStatus::UpdateFailedEvenWithClash,
format!("{profile_name} - {last_err}"),
);
} }
bail!(last_err) bail!(last_err)
} }
@@ -201,7 +219,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
match CoreManager::global().update_config_with_force(is_mannual_trigger).await { match CoreManager::global().update_config_with_force(is_mannual_trigger).await {
Ok(outcome) if outcome.is_valid() => { Ok(outcome) if outcome.is_valid() => {
logging_error!(Type::Config, Config::sync_dns_override().await); logging_error!(Type::Config, Config::sync_dns_override().await);
handle::Handle::refresh_clash(); announce(Refresh::Clash);
} }
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => { Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => {
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome); logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
@@ -218,7 +236,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
message message
}; };
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message); logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
handle::Handle::notice_message("update_failed", &message); handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
bail!(message); bail!(message);
} }
} }
+2 -1
View File
@@ -1,3 +1,4 @@
use crate::core::notify::{Refresh, announce};
use crate::{ use crate::{
config::{Config, IVerge, MixedPort}, config::{Config, IVerge, MixedPort},
core::{ core::{
@@ -83,7 +84,7 @@ pub async fn toggle_tun_mode(not_save_file: Option<bool>) -> bool {
.await .await
{ {
Ok(_) => { Ok(_) => {
handle::Handle::refresh_verge(); announce(Refresh::Verge);
// Reconciliation may immediately disable unavailable TUN; report the resulting state. // Reconciliation may immediately disable unavailable TUN; report the resulting state.
Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false) Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
} }
+4 -2
View File
@@ -1,5 +1,7 @@
//! Reconciles TUN with current Core and Service availability. //! Reconciles TUN with current Core and Service availability.
use crate::core::notify::NoticeStatus;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
@@ -75,10 +77,10 @@ pub async fn reconcile_tun_availability() {
// Skip recursive reconciliation for this internal patch. // Skip recursive reconciliation for this internal patch.
match super::apply_verge_patch_locked(&config_write, &patch, false).await { match super::apply_verge_patch_locked(&config_write, &patch, false).await {
Ok(()) => Handle::notice_message("tun_mode::auto_disabled", ""), Ok(()) => Handle::notice(NoticeStatus::TunModeAutoDisabled, ""),
Err(error) => { Err(error) => {
logging!(error, Type::Core, "failed to turn TUN mode off: {error:#}"); logging!(error, Type::Core, "failed to turn TUN mode off: {error:#}");
Handle::notice_message("tun_mode::auto_disable_failed", ""); Handle::notice(NoticeStatus::TunModeAutoDisableFailed, "");
} }
} }
} }
+5 -4
View File
@@ -1,6 +1,7 @@
use crate::config::Config; use crate::config::Config;
use crate::core::lightweight;
use crate::core::notify::NoticeStatus;
use crate::core::{CoreManager, handle}; use crate::core::{CoreManager, handle};
use crate::module::lightweight;
use crate::utils; use crate::utils;
use crate::utils::window_manager::WindowManager; use crate::utils::window_manager::WindowManager;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
@@ -128,8 +129,8 @@ pub async fn quit() -> clash_verge_signal::ShutdownOutcome {
if should_abort_exit_after_cleanup(cleanup_result.core_stopped) { if should_abort_exit_after_cleanup(cleanup_result.core_stopped) {
handle::Handle::global().clear_is_exiting(); handle::Handle::global().clear_is_exiting();
handle::Handle::notice_message( handle::Handle::notice(
"app_quit::core_stop_failed", NoticeStatus::AppQuitCoreStopFailed,
cleanup_result.stop_error.unwrap_or_default(), cleanup_result.stop_error.unwrap_or_default(),
); );
return clash_verge_signal::ShutdownOutcome::Canceled; return clash_verge_signal::ShutdownOutcome::Canceled;
@@ -230,7 +231,7 @@ pub async fn clean_session_ending_best_effort() -> CleanupResult {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub async fn hide() { pub async fn hide() {
use crate::module::lightweight::add_light_weight_timer; use crate::core::lightweight::add_light_weight_timer;
let enable_auto_light_weight_mode = Config::verge() let enable_auto_light_weight_mode = Config::verge()
.await .await
+8 -5
View File
@@ -7,7 +7,6 @@ mod constants;
mod core; mod core;
mod enhance; mod enhance;
mod feat; mod feat;
mod module;
mod process; mod process;
pub mod utils; pub mod utils;
@@ -19,13 +18,17 @@ use crate::{
}; };
use anyhow::Result; use anyhow::Result;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use once_cell::sync::OnceCell; use std::sync::OnceLock;
use tauri::{AppHandle, Manager as _}; use tauri::{AppHandle, Manager as _};
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use tauri_plugin_autostart::MacosLauncher; use tauri_plugin_autostart::MacosLauncher;
use tauri_plugin_deep_link::DeepLinkExt as _; use tauri_plugin_deep_link::DeepLinkExt as _;
pub static APP_HANDLE: OnceCell<AppHandle> = OnceCell::new(); pub static APP_HANDLE: OnceLock<AppHandle> = OnceLock::new();
// Re-exported for src/bin/frontend-contract.rs; the wire contract stays owned
// by core::notify.
pub use crate::core::notify::frontend_wire_contract;
/// Application initialization helper functions /// Application initialization helper functions
mod app_init { mod app_init {
use super::*; use super::*;
@@ -333,7 +336,7 @@ pub fn run() -> std::process::ExitCode {
mod event_handlers { mod event_handlers {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
use crate::module::lightweight; use crate::core::lightweight;
use crate::utils::window_manager::WindowManager; use crate::utils::window_manager::WindowManager;
use crate::{ use crate::{
config::Config, config::Config,
@@ -488,7 +491,7 @@ pub fn run() -> std::process::ExitCode {
}), }),
#[allow(unused_variables)] #[allow(unused_variables)]
tauri::RunEvent::ExitRequested { api, code, .. } => { tauri::RunEvent::ExitRequested { api, code, .. } => {
if module::lightweight::is_in_lightweight_mode() && !handle::Handle::global().is_exiting() { if core::lightweight::is_in_lightweight_mode() && !handle::Handle::global().is_exiting() {
api.prevent_exit(); api.prevent_exit();
} else if code.is_none() { } else if code.is_none() {
api.prevent_exit(); api.prevent_exit();
-2
View File
@@ -1,2 +0,0 @@
pub mod auto_backup;
pub mod lightweight;
+2 -1
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use crate::{config::with_encryption, process::AsyncHandler}; use crate::{config::with_encryption, process::AsyncHandler};
use anyhow::{Context as _, Result, anyhow, bail}; use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
@@ -58,7 +59,7 @@ fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
let error_msg = format!("YAML syntax error in {}: {}", path.display(), err); let error_msg = format!("YAML syntax error in {}: {}", path.display(), err);
logging!(error, Type::Config, "{}", error_msg); logging!(error, Type::Config, "{}", error_msg);
crate::core::handle::Handle::notice_message("config_validate::yaml_syntax_error", &error_msg); crate::core::handle::Handle::notice(NoticeStatus::ConfigValidateYamlSyntaxError, error_msg.as_str());
bail!("YAML syntax error: {}", err) bail!("YAML syntax error: {}", err)
} }
+53 -36
View File
@@ -109,44 +109,61 @@ fn current_user_home() -> anyhow::Result<PathBuf> {
} }
.max(1024); .max(1024);
loop { use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
if buffer_size > MAX_BUFFER_SIZE { retry_sync(
anyhow::bail!("effective-user home lookup exceeded the maximum buffer size"); RetryPolicy::fixed(
} std::num::NonZeroUsize::MIN.saturating_add(11),
std::time::Duration::ZERO,
),
|_| {
if buffer_size > MAX_BUFFER_SIZE {
return Err(RetryError::Stop(anyhow::anyhow!(
"effective-user home lookup exceeded the maximum buffer size"
)));
}
let mut passwd = std::mem::MaybeUninit::<libc::passwd>::zeroed(); let mut passwd = std::mem::MaybeUninit::<libc::passwd>::zeroed();
let mut result = std::ptr::null_mut(); let mut result = std::ptr::null_mut();
let mut buffer = vec![0_u8; buffer_size]; let mut buffer = vec![0_u8; buffer_size];
let code = unsafe { let code = unsafe {
libc::getpwuid_r( libc::getpwuid_r(
uid, uid,
passwd.as_mut_ptr(), passwd.as_mut_ptr(),
buffer.as_mut_ptr().cast(), buffer.as_mut_ptr().cast(),
buffer.len(), buffer.len(),
&mut result, &mut result,
) )
}; };
if code == libc::ERANGE { if code == libc::ERANGE {
buffer_size = buffer_size.saturating_mul(2); buffer_size = buffer_size.saturating_mul(2);
continue; return Err(RetryError::Retry(anyhow::anyhow!(
} "effective-user home lookup exceeded the maximum buffer size"
if code != 0 { )));
return Err(std::io::Error::from_raw_os_error(code).into()); }
} if code != 0 {
if result.is_null() { return Err(RetryError::Stop(std::io::Error::from_raw_os_error(code).into()));
anyhow::bail!("effective user {uid} has no password database entry"); }
} if result.is_null() {
return Err(RetryError::Stop(anyhow::anyhow!(
"effective user {uid} has no password database entry"
)));
}
let passwd = unsafe { passwd.assume_init() }; let passwd = unsafe { passwd.assume_init() };
if passwd.pw_dir.is_null() { if passwd.pw_dir.is_null() {
anyhow::bail!("effective user {uid} has no home directory"); return Err(RetryError::Stop(anyhow::anyhow!(
} "effective user {uid} has no home directory"
let home = unsafe { CStr::from_ptr(passwd.pw_dir) }; )));
if home.to_bytes().is_empty() { }
anyhow::bail!("effective user {uid} has an empty home directory"); let home = unsafe { CStr::from_ptr(passwd.pw_dir) };
} if home.to_bytes().is_empty() {
return Ok(PathBuf::from(std::ffi::OsStr::from_bytes(home.to_bytes()))); return Err(RetryError::Stop(anyhow::anyhow!(
} "effective user {uid} has an empty home directory"
)));
}
Ok(PathBuf::from(std::ffi::OsStr::from_bytes(home.to_bytes())))
},
)
} }
pub const fn move_decision( pub const fn move_decision(
+2 -1
View File
@@ -8,9 +8,10 @@ pub mod linux;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub mod macos_launch_guard; pub mod macos_launch_guard;
pub(crate) mod network; pub(crate) mod network;
pub mod notification; pub use crate::core::notify::desktop as notification;
pub mod port; pub mod port;
pub mod resolve; pub mod resolve;
pub mod retry;
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
pub mod schtasks; pub mod schtasks;
pub mod server; pub mod server;
+3 -2
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use anyhow::Result; use anyhow::Result;
@@ -13,8 +14,8 @@ use crate::{
service::{SERVICE_MANAGER, ServiceManager}, service::{SERVICE_MANAGER, ServiceManager},
tray::Tray, tray::Tray,
}, },
core::{auto_backup::AutoBackupManager, lightweight::auto_lightweight_boot},
feat, feat,
module::{auto_backup::AutoBackupManager, lightweight::auto_lightweight_boot},
process::AsyncHandler, process::AsyncHandler,
utils::{init, server, window_manager::WindowManager}, utils::{init, server, window_manager::WindowManager},
}; };
@@ -223,7 +224,7 @@ async fn init_core_manager() -> bool {
Err(error) => { Err(error) => {
logging!(error, Type::Setup, "core manager initialization failed: {error:#}"); logging!(error, Type::Setup, "core manager initialization failed: {error:#}");
CoreManager::global().record_startup_error(CoreFailure::StartFailed(format!("{error:#}"))); CoreManager::global().record_startup_error(CoreFailure::StartFailed(format!("{error:#}")));
Handle::notice_message("core_start::error", ""); Handle::notice(NoticeStatus::CoreStartError, "");
false false
} }
} }
+8 -7
View File
@@ -1,3 +1,4 @@
use crate::core::notify::NoticeStatus;
use anyhow::Result; use anyhow::Result;
use percent_encoding::percent_decode_str; use percent_encoding::percent_decode_str;
use smartstring::alias::String; use smartstring::alias::String;
@@ -93,18 +94,18 @@ async fn import_subscription(url: &str, name: Option<&String>) {
if let Err(e) = profiles::profiles_append_item_safe(&mut item).await { if let Err(e) = profiles::profiles_append_item_safe(&mut item).await {
logging!(error, Type::Config, "failed to import subscription url: {:?}", e); logging!(error, Type::Config, "failed to import subscription url: {:?}", e);
Config::profiles().await.discard(); Config::profiles().await.discard();
handle::Handle::notice_message("import_sub_url::error", e.to_string()); handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
return; return;
} }
if let Err(e) = profiles::profiles_save_file_safe().await { if let Err(e) = profiles::profiles_save_file_safe().await {
logging!(error, Type::Config, "failed to save imported subscription: {e:#}"); logging!(error, Type::Config, "failed to save imported subscription: {e:#}");
handle::Handle::notice_message("import_sub_url::error", e.to_string()); handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
return; return;
} }
logging_error!(Type::Timer, Timer::global().refresh().await); logging_error!(Type::Timer, Timer::global().refresh().await);
handle::Handle::notice_message( handle::Handle::notice(
"import_sub_url::ok", NoticeStatus::ImportSubUrlOk,
"", // 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。 "", // 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。
); );
@@ -116,7 +117,7 @@ async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option<PrfItem>
Ok(item) => Some(item), Ok(item) => Some(item),
Err(e) => { Err(e) => {
logging!(error, Type::Config, "failed to parse profile from url: {:?}", e); logging!(error, Type::Config, "failed to parse profile from url: {:?}", e);
handle::Handle::notice_message("import_sub_url::error", e.to_string()); handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string());
None None
} }
} }
@@ -149,11 +150,11 @@ async fn refresh_core_config() {
Ok(outcome) => { Ok(outcome) => {
let message = outcome.to_string(); let message = outcome.to_string();
logging!(warn, Type::Config, "Apply config failed: {}", message); logging!(warn, Type::Config, "Apply config failed: {}", message);
handle::Handle::notice_message("config_validate::error", message); handle::Handle::notice(NoticeStatus::ConfigValidateError, message);
} }
Err(err) => { Err(err) => {
logging!(error, Type::Config, "Apply config error: {err:#}"); logging!(error, Type::Config, "Apply config error: {err:#}");
handle::Handle::notice_message("update_failed", format!("{err}")); handle::Handle::notice(NoticeStatus::UpdateFailed, format!("{err}"));
} }
} }
} }
+237
View File
@@ -0,0 +1,237 @@
use backon::{BackoffBuilder as _, ExponentialBackoff, ExponentialBuilder};
use std::{future::Future, num::NonZeroUsize, time::Duration};
#[derive(Clone, Copy, Debug)]
pub enum Backoff {
Fixed(Duration),
#[allow(dead_code)]
Exponential {
base: Duration,
cap: Duration,
},
}
#[derive(Clone, Copy, Debug)]
pub struct RetryPolicy {
pub attempts: NonZeroUsize,
pub backoff: Backoff,
pub jitter: bool,
}
impl RetryPolicy {
pub const fn fixed(attempts: NonZeroUsize, delay: Duration) -> Self {
Self {
attempts,
backoff: Backoff::Fixed(delay),
jitter: false,
}
}
fn delays(self) -> ExponentialBackoff {
let (base, cap, factor) = match self.backoff {
Backoff::Fixed(delay) => (delay, delay, 1.0),
Backoff::Exponential { base, cap } => (base, cap, 2.0),
};
let mut builder = ExponentialBuilder::default()
.with_min_delay(base)
.with_max_delay(cap)
.with_factor(factor)
.with_max_times(self.attempts.get() - 1);
if self.jitter {
builder = builder.with_jitter();
}
builder.build()
}
}
pub enum RetryError<E> {
Retry(E),
Stop(E),
}
pub async fn retry<T: Send, E: Send, Fut: Future<Output = Result<T, RetryError<E>>> + Send>(
policy: RetryPolicy,
mut operation: impl FnMut(usize) -> Fut + Send,
) -> Result<T, E> {
let mut result = operation(0).await;
for (index, delay) in policy.delays().enumerate() {
match result {
Ok(_) | Err(RetryError::Stop(_)) => break,
Err(RetryError::Retry(_)) => {
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
}
}
result = operation(index + 1).await;
}
result.map_err(|error| match error {
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
}
pub async fn try_strategies<
S: Copy + Send,
T: Send,
E: Send,
Fut: Future<Output = Result<T, E>> + Send,
const N: usize,
>(
first: S,
rest: [S; N],
mut operation: impl FnMut(S) -> Fut + Send,
) -> Result<(S, T), E> {
retry(
RetryPolicy {
attempts: NonZeroUsize::MIN.saturating_add(N),
backoff: Backoff::Fixed(Duration::ZERO),
jitter: false,
},
move |attempt| {
let strategy = if attempt == 0 { first } else { rest[attempt - 1] };
let future = operation(strategy);
async move { future.await.map(|value| (strategy, value)).map_err(RetryError::Retry) }
},
)
.await
}
pub async fn retry_with_state<S: Send, T: Send, E: Send>(
policy: RetryPolicy,
mut state: S,
mut operation: impl for<'a> FnMut(&'a mut S, usize) -> futures::future::BoxFuture<'a, Result<T, RetryError<E>>> + Send,
) -> Result<T, E> {
let mut result = operation(&mut state, 0).await;
for (index, delay) in policy.delays().enumerate() {
match result {
Ok(_) | Err(RetryError::Stop(_)) => break,
Err(RetryError::Retry(_)) => {
if !delay.is_zero() {
tokio::time::sleep(delay).await;
}
}
}
result = operation(&mut state, index + 1).await;
}
result.map_err(|error| match error {
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
}
pub fn retry_sync<T, E>(
policy: RetryPolicy,
mut operation: impl FnMut(usize) -> Result<T, RetryError<E>>,
) -> Result<T, E> {
let mut result = operation(0);
for (index, delay) in policy.delays().enumerate() {
match result {
Ok(_) | Err(RetryError::Stop(_)) => break,
Err(RetryError::Retry(_)) => {
if !delay.is_zero() {
std::thread::sleep(delay);
}
}
}
result = operation(index + 1);
}
result.map_err(|error| match error {
RetryError::Retry(error) | RetryError::Stop(error) => error,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn retries_stop_at_success_terminal_error_or_attempt_limit() {
let policy = RetryPolicy {
attempts: NonZeroUsize::MIN.saturating_add(2),
backoff: Backoff::Fixed(Duration::ZERO),
jitter: false,
};
let mut calls = 0;
let success = retry(policy, |attempt| {
calls += 1;
async move {
if attempt == 1 {
Ok(7)
} else {
Err(RetryError::Retry(attempt))
}
}
})
.await;
assert_eq!((success, calls), (Ok(7), 2));
calls = 0;
let stopped = retry(policy, |_| {
calls += 1;
async move { Err::<(), _>(RetryError::Stop("terminal")) }
})
.await;
assert_eq!((stopped, calls), (Err("terminal"), 1));
calls = 0;
let exhausted = retry(policy, |attempt| {
calls += 1;
async move { Err::<(), _>(RetryError::Retry(attempt)) }
})
.await;
assert_eq!((exhausted, calls), (Err(2), 3));
}
#[tokio::test]
async fn strategies_preserve_order_and_the_last_failure() {
let mut visited = Vec::new();
let result = try_strategies("direct", ["clash", "system"], |strategy| {
visited.push(strategy);
async move { Err::<(), _>(strategy) }
})
.await;
assert_eq!(result, Err("system"));
assert_eq!(visited, ["direct", "clash", "system"]);
}
#[tokio::test]
async fn stateful_and_sync_retries_preserve_progress_and_stop() {
let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), Duration::ZERO);
let result = retry_with_state(policy, Vec::new(), |visited, attempt| {
Box::pin(async move {
visited.push(attempt);
if visited.len() == 3 {
Ok(visited.clone())
} else {
Err(RetryError::Retry(()))
}
})
})
.await;
assert_eq!(result, Ok(vec![0, 1, 2]));
let mut visited = Vec::new();
let result = retry_sync(policy, |attempt| {
visited.push(attempt);
if attempt == 1 {
Err::<(), _>(RetryError::Stop("terminal"))
} else {
Err(RetryError::Retry("retry"))
}
});
assert_eq!(result, Err("terminal"));
assert_eq!(visited, [0, 1]);
}
#[test]
fn backoff_keeps_the_attempt_budget_and_exponential_cap() {
let policy = RetryPolicy {
attempts: NonZeroUsize::MIN.saturating_add(4),
backoff: Backoff::Exponential {
base: Duration::from_millis(10),
cap: Duration::from_millis(25),
},
jitter: false,
};
assert_eq!(
policy.delays().collect::<Vec<_>>(),
[10, 20, 25, 25].map(Duration::from_millis)
);
}
}
+33 -21
View File
@@ -1,18 +1,18 @@
use super::resolve; use super::resolve;
use crate::{ use crate::{
config::{Config, DEFAULT_PAC, MixedPort}, config::{Config, DEFAULT_PAC, MixedPort},
module::lightweight, core::lightweight,
process::AsyncHandler, process::AsyncHandler,
utils::{dirs, window_manager::WindowManager}, utils::{dirs, window_manager::WindowManager},
}; };
use anyhow::{Context as _, Result, bail}; use anyhow::{Context as _, Result, bail};
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use once_cell::sync::OnceCell;
use parking_lot::Mutex; use parking_lot::Mutex;
use reqwest::ClientBuilder; use reqwest::ClientBuilder;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::io::{Read as _, Write as _}; use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration; use std::time::Duration;
use tokio::sync::oneshot; use tokio::sync::oneshot;
@@ -33,9 +33,9 @@ struct InstanceRecord {
token: String, token: String,
} }
static SHUTDOWN_SENDER: OnceCell<Mutex<Option<oneshot::Sender<()>>>> = OnceCell::new(); static SHUTDOWN_SENDER: OnceLock<Mutex<Option<oneshot::Sender<()>>>> = OnceLock::new();
static EMBEDDED_PORT: OnceCell<u16> = OnceCell::new(); static EMBEDDED_PORT: OnceLock<u16> = OnceLock::new();
static INSTANCE_LOCK: OnceCell<std::fs::File> = OnceCell::new(); static INSTANCE_LOCK: OnceLock<std::fs::File> = OnceLock::new();
const PAC_INITIAL_AVAILABLE: bool = false; const PAC_INITIAL_AVAILABLE: bool = false;
static PAC_AVAILABLE: AtomicBool = AtomicBool::new(PAC_INITIAL_AVAILABLE); static PAC_AVAILABLE: AtomicBool = AtomicBool::new(PAC_INITIAL_AVAILABLE);
static COMMANDS_READY: AtomicBool = AtomicBool::new(false); static COMMANDS_READY: AtomicBool = AtomicBool::new(false);
@@ -54,22 +54,34 @@ pub async fn check_singleton() -> Result<SingletonDisposition> {
.context("failed to initialize singleton lock")?; .context("failed to initialize singleton lock")?;
if !try_lock_instance(&lock).context("failed to acquire singleton lock")? { if !try_lock_instance(&lock).context("failed to acquire singleton lock")? {
let deadline = std::time::Instant::now() + Duration::from_secs(20); let deadline = std::time::Instant::now() + Duration::from_secs(20);
loop { use crate::utils::retry::{RetryError, RetryPolicy, retry};
if std::time::Instant::now() >= deadline { let secondary = retry(
bail!("another app instance is starting"); RetryPolicy::fixed(
} std::num::NonZeroUsize::MIN.saturating_add(400),
// A restarting instance releases this lock only after spawning this Duration::from_millis(50),
// process, and its embedded server is already down, so waiting on ),
// the notify probe alone can never promote this instance. |_| async {
if try_lock_instance(&lock).context("failed to acquire singleton lock")? { if std::time::Instant::now() >= deadline {
break; return Err(RetryError::Stop(anyhow::anyhow!("another app instance is starting")));
} }
if let Ok(record) = read_instance_record(&record_path) // A restarting primary releases the lock after spawning us, with its server down.
&& notify_existing_instance(&record).await if try_lock_instance(&lock)
{ .context("failed to acquire singleton lock")
return Ok(SingletonDisposition::Secondary); .map_err(RetryError::Stop)?
} {
tokio::time::sleep(Duration::from_millis(50)).await; return Ok(false);
}
if let Ok(record) = read_instance_record(&record_path)
&& notify_existing_instance(&record).await
{
return Ok(true);
}
Err(RetryError::Retry(anyhow::anyhow!("another app instance is starting")))
},
)
.await?;
if secondary {
return Ok(SingletonDisposition::Secondary);
} }
} }
+1 -1
View File
@@ -1,4 +1,4 @@
/// Implements `global()` using the supplied `OnceCell` static. /// Implements `global()` using the supplied `OnceLock` static.
#[macro_export] #[macro_export]
macro_rules! singleton { macro_rules! singleton {
($struct_name:ty, $instance_name:ident) => { ($struct_name:ty, $instance_name:ident) => {
+2 -2
View File
@@ -1,8 +1,8 @@
use crate::{core::handle, utils::resolve::window::build_new_window}; use crate::{core::handle, utils::resolve::window::build_new_window};
use clash_verge_limiter::Limiter; use clash_verge_limiter::Limiter;
use clash_verge_logging::{Type, logging}; use clash_verge_logging::{Type, logging};
use once_cell::sync::Lazy;
use std::pin::Pin; use std::pin::Pin;
use std::sync::LazyLock;
use std::time::Duration; use std::time::Duration;
use tauri::{Manager as _, WebviewWindow, Wry}; use tauri::{Manager as _, WebviewWindow, Wry};
@@ -26,7 +26,7 @@ pub enum WindowState {
} }
const WINDOW_OPERATION_DEBOUNCE_MS: u64 = 625; const WINDOW_OPERATION_DEBOUNCE_MS: u64 = 625;
static WINDOW_OPERATION_LIMITER: Lazy<Limiter> = Lazy::new(|| { static WINDOW_OPERATION_LIMITER: LazyLock<Limiter> = LazyLock::new(|| {
Limiter::new( Limiter::new(
Duration::from_millis(WINDOW_OPERATION_DEBOUNCE_MS), Duration::from_millis(WINDOW_OPERATION_DEBOUNCE_MS),
clash_verge_limiter::SystemClock, clash_verge_limiter::SystemClock,
+36
View File
@@ -0,0 +1,36 @@
# Frontend Architecture Guardrails
These rules supplement the repository's root `AGENTS.md`. They define the
layering introduced by the frontend contract flow; violating any of them is
rework, not a review note.
1. **Contract is generated, never hand-typed.** Event names, payload shapes,
and the `NoticeStatus` union come from `src/services/contract.ts`
(`@generated`). Regenerate with `pnpm gen:contract` after changing the
backend wire contract, and commit the result; CI regenerates and fails on
a diff. Adding a backend status requires updating the exhaustive notice
table (`src/services/notice-handlers.ts`) in the same PR — the
`Record<NoticeStatus, …>` type enforces it. No exceptions.
2. **`listen(`/`emit(` live only in the event bus.** All Tauri event
subscriptions and emissions go through `src/services/bus/`, which mounts
exactly once at the layout root and registers exactly one handler per
event name. Components and pages never touch `@tauri-apps/api/event`.
Window-lifecycle helpers that do not use the event-module API may stay
with their owning component.
3. **Event-derived state lives in the app store.** Cross-component state
produced by events is written only through pure reducer actions dispatched
by the bus or the funnel (`src/store/`). Handlers may perform documented
side effects (SWR revalidation, notices) but must not write store state
directly. New event-consumed state needs a reducer action first, not a
local `useState` in a page.
4. **User intent funnels through `mutate`.** Every mutating backend command
call goes through `src/services/mutate.ts` — components, hooks, and
dialogs included. Give each intent a stable `id`; express optimistic
writes as `optimistic`/`rollback` and success refreshes as `revalidate`/
`onFulfilled`. Flows with bespoke error UX keep it via `errorNotice:
false`; suppressing both the funnel's and the site's handling is a bug.
5. **`invoke(` lives only in services.** Backend commands are wrapped in
`src/services/cmds.ts`; mihomo-plugin mutations are governed by rule 4.
Pages and components import the wrapper, never `@tauri-apps/api/core`. CI
greps for this and rule 2 (`node scripts/check-architecture.mjs listen
emit invoke` must stay clean).
+5 -1
View File
@@ -16,6 +16,7 @@ import {
useCoreDataStatus, useCoreDataStatus,
} from '@/providers/app-data-context' } from '@/providers/app-data-context'
import { patchClashMode } from '@/services/cmds' import { patchClashMode } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { setCacheData } from '@/services/query-client' import { setCacheData } from '@/services/query-client'
import type { TranslationKey } from '@/types/generated/i18n-keys' import type { TranslationKey } from '@/types/generated/i18n-keys'
@@ -90,7 +91,10 @@ export const ClashModeCard = () => {
setOptimisticMode(mode) setOptimisticMode(mode)
try { try {
await patchClashMode(mode) await mutate(() => patchClashMode(mode), {
id: 'patch-clash-mode',
errorNotice: false,
})
} catch (error) { } catch (error) {
setOptimisticMode(null) setOptimisticMode(null)
showNotice.error(error) showNotice.error(error)
+5 -1
View File
@@ -26,6 +26,7 @@ import { useNavigate } from 'react-router'
import { useAppRefreshers } from '@/providers/app-data-context' import { useAppRefreshers } from '@/providers/app-data-context'
import { updateProfile } from '@/services/cmds' import { updateProfile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { isValidUrl } from '@/utils/network' import { isValidUrl } from '@/utils/network'
import { openExternalUrl } from '@/utils/open-external-url' import { openExternalUrl } from '@/utils/open-external-url'
@@ -297,7 +298,10 @@ export const HomeProfileCard = ({
setUpdating(true) setUpdating(true)
try { try {
await updateProfile(current.uid, current.option) await mutate(() => updateProfile(current.uid, current.option), {
id: `update-profile:${current.uid}`,
errorNotice: false,
})
onProfileUpdated?.() onProfileUpdated?.()
// 刷新首页数据 // 刷新首页数据
+2 -2
View File
@@ -6,7 +6,6 @@ import {
import { isSortable } from '@dnd-kit/react/sortable' import { isSortable } from '@dnd-kit/react/sortable'
import { Add, NetworkCheck } from '@mui/icons-material' import { Add, NetworkCheck } from '@mui/icons-material'
import { Box, IconButton, Tooltip, alpha, styled } from '@mui/material' import { Box, IconButton, Tooltip, alpha, styled } from '@mui/material'
import { emit } from '@tauri-apps/api/event'
import { nanoid } from 'nanoid' import { nanoid } from 'nanoid'
import { useEffect, useRef, useMemo, useCallback } from 'react' import { useEffect, useRef, useMemo, useCallback } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
@@ -20,6 +19,7 @@ import { SortableItem } from '@/components/base'
import { TestItem } from '@/components/test/test-item' import { TestItem } from '@/components/test/test-item'
import { TestViewer, type TestViewerRef } from '@/components/test/test-viewer' import { TestViewer, type TestViewerRef } from '@/components/test/test-viewer'
import { useVerge } from '@/hooks/use-verge' import { useVerge } from '@/hooks/use-verge'
import { emitTestAll } from '@/services/bus'
import { EnhancedCard } from './enhanced-card' import { EnhancedCard } from './enhanced-card'
@@ -178,7 +178,7 @@ export const TestCard = () => {
) )
const handleTestAll = useCallback(() => { const handleTestAll = useCallback(() => {
emit('verge://test-all') emitTestAll()
}, []) }, [])
const handleCreateTest = useCallback(() => { const handleCreateTest = useCallback(() => {
@@ -8,18 +8,24 @@ import {
type RunState, type RunState,
} from '@/services/cmds' } from '@/services/cmds'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { useQuery } from '@/services/query-client'
import { ServiceMigrationDialog } from './service-migration-dialog' import { ServiceMigrationDialog } from './service-migration-dialog'
const store = vi.hoisted(() => ({
dispatch: vi.fn(),
runState: null as RunState | null,
}))
vi.mock('react', () => ({ useState: vi.fn() })) vi.mock('react', () => ({ useState: vi.fn() }))
vi.mock('react-i18next', () => ({ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }), useTranslation: () => ({ t: (key: string) => key }),
})) }))
vi.mock('@mui/material', () => ({ Alert: 'div' })) vi.mock('@mui/material', () => ({ Alert: 'div' }))
vi.mock('@/components/base', () => ({ BaseDialog: 'dialog' })) vi.mock('@/components/base', () => ({ BaseDialog: 'dialog' }))
vi.mock('@/hooks/use-visibility', () => ({ useVisibility: () => true })) vi.mock('@/store/app-store-context', () => ({
vi.mock('@/hooks/use-system-state', () => ({ runStateQueryKey: ['state'] })) useAppDispatch: () => store.dispatch,
useRunState: () => store.runState,
}))
vi.mock('@/services/cmds', () => ({ vi.mock('@/services/cmds', () => ({
getRuntimeState: vi.fn(), getRuntimeState: vi.fn(),
installService: vi.fn(), installService: vi.fn(),
@@ -28,13 +34,10 @@ vi.mock('@/services/cmds', () => ({
vi.mock('@/services/notice-service', () => ({ vi.mock('@/services/notice-service', () => ({
showNotice: { warning: vi.fn(), error: vi.fn(), success: vi.fn() }, showNotice: { warning: vi.fn(), error: vi.fn(), success: vi.fn() },
})) }))
vi.mock('@/services/query-client', () => ({
useQuery: vi.fn(),
setCacheData: vi.fn(),
}))
beforeEach(() => { beforeEach(() => {
vi.clearAllMocks() vi.clearAllMocks()
store.runState = null
vi.mocked(useState) vi.mocked(useState)
.mockReturnValueOnce([false, vi.fn()]) .mockReturnValueOnce([false, vi.fn()])
.mockReturnValueOnce([false, vi.fn()]) .mockReturnValueOnce([false, vi.fn()])
@@ -50,9 +53,7 @@ it.each([
] satisfies Partial<RunState>[])( ] satisfies Partial<RunState>[])(
'does not offer Sidecar continuation from %j', 'does not offer Sidecar continuation from %j',
(state) => { (state) => {
vi.mocked(useQuery).mockReturnValue({ data: state } as ReturnType< store.runState = state as unknown as RunState
typeof useQuery
>)
const dialog = ServiceMigrationDialog() const dialog = ServiceMigrationDialog()
expect(dialog.props.open).toBe(true) expect(dialog.props.open).toBe(true)
expect(dialog.props.disableCancel).toBe(true) expect(dialog.props.disableCancel).toBe(true)
@@ -60,9 +61,10 @@ it.each([
) )
it('reports the permission refusal and finishes after installation falls back to Sidecar', async () => { it('reports the permission refusal and finishes after installation falls back to Sidecar', async () => {
vi.mocked(useQuery).mockReturnValue({ store.runState = {
data: { service: 'notInstalled', mode: 'NotRunning' }, service: 'notInstalled',
} as ReturnType<typeof useQuery>) mode: 'NotRunning',
} as unknown as RunState
const reason = 'core path C:\\ is writable by Everyone' const reason = 'core path C:\\ is writable by Everyone'
vi.mocked(installService).mockResolvedValue({ status: 'sidecar', reason }) vi.mocked(installService).mockResolvedValue({ status: 'sidecar', reason })
vi.mocked(getRuntimeState).mockResolvedValue({ vi.mocked(getRuntimeState).mockResolvedValue({
@@ -98,9 +100,7 @@ it.each([
] satisfies Partial<RunState>[])( ] satisfies Partial<RunState>[])(
'offers Sidecar continuation from %j', 'offers Sidecar continuation from %j',
(state) => { (state) => {
vi.mocked(useQuery).mockReturnValue({ data: state } as ReturnType< store.runState = state as unknown as RunState
typeof useQuery
>)
expect(ServiceMigrationDialog().props.disableCancel).toBe(false) expect(ServiceMigrationDialog().props.disableCancel).toBe(false)
}, },
) )
@@ -3,8 +3,6 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { BaseDialog } from '@/components/base' import { BaseDialog } from '@/components/base'
import { runStateQueryKey } from '@/hooks/use-system-state'
import { useVisibility } from '@/hooks/use-visibility'
import { import {
continueWithSidecar, continueWithSidecar,
getRuntimeState, getRuntimeState,
@@ -12,25 +10,19 @@ import {
reinstallService, reinstallService,
repairService, repairService,
restartCore, restartCore,
type RunState,
type ServiceInstallOutcome, type ServiceInstallOutcome,
} from '@/services/cmds' } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { setCacheData, useQuery } from '@/services/query-client' import { useAppDispatch, useRunState } from '@/store/app-store-context'
export const ServiceMigrationDialog = () => { export const ServiceMigrationDialog = () => {
const { t } = useTranslation() const { t } = useTranslation()
const pageVisible = useVisibility()
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [stateRefreshFailed, setStateRefreshFailed] = useState(false) const [stateRefreshFailed, setStateRefreshFailed] = useState(false)
const [workflowIncomplete, setWorkflowIncomplete] = useState(false) const [workflowIncomplete, setWorkflowIncomplete] = useState(false)
const { data: runState } = useQuery({ const dispatch = useAppDispatch()
queryKey: runStateQueryKey, const runState = useRunState()
queryFn: getRuntimeState,
enabled: true,
retry: 1,
refetchInterval: pageVisible ? 30000 : false,
})
// Whether the service needs a decision is derived once, in Rust, and travels with the // Whether the service needs a decision is derived once, in Rust, and travels with the
// snapshot; a failed refresh is treated as needing one, since we cannot tell otherwise. // snapshot; a failed refresh is treated as needing one, since we cannot tell otherwise.
const needsDecision = const needsDecision =
@@ -64,11 +56,11 @@ export const ServiceMigrationDialog = () => {
runState.service === 'unavailable')), runState.service === 'unavailable')),
) )
// One cache entry to refresh, so there is nothing left to keep coherent by hand. // One store entry to refresh, so there is nothing left to keep coherent by hand.
const refreshRunState = async () => { const refreshRunState = async () => {
try { try {
const data = await getRuntimeState() const data = await getRuntimeState()
await setCacheData<RunState>(runStateQueryKey, data) dispatch({ type: 'runState/loaded', runState: data })
setStateRefreshFailed(false) setStateRefreshFailed(false)
return data return data
} catch (error) { } catch (error) {
@@ -83,11 +75,23 @@ export const ServiceMigrationDialog = () => {
let outcome: ServiceInstallOutcome | undefined let outcome: ServiceInstallOutcome | undefined
try { try {
if (remedy === 'install') { if (remedy === 'install') {
outcome = await installService() const result = await mutate(() => installService(), {
id: 'install-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
} else if (remedy === 'repair') { } else if (remedy === 'repair') {
outcome = await repairService() const result = await mutate(() => repairService(), {
id: 'repair-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
} else { } else {
outcome = await reinstallService() const result = await mutate(() => reinstallService(), {
id: 'reinstall-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
} }
} catch (error) { } catch (error) {
showNotice.error( showNotice.error(
@@ -123,8 +127,11 @@ export const ServiceMigrationDialog = () => {
let restartSucceeded = false let restartSucceeded = false
try { try {
await restartCore() const result = await mutate(() => restartCore(), {
restartSucceeded = true id: 'restart-core',
errorNotice: false,
})
restartSucceeded = result.ok
} catch (error) { } catch (error) {
showNotice.error( showNotice.error(
'layout.components.serviceMigration.errors.restartFailed', 'layout.components.serviceMigration.errors.restartFailed',
@@ -154,7 +161,10 @@ export const ServiceMigrationDialog = () => {
setWorkflowIncomplete(true) setWorkflowIncomplete(true)
let startupError: unknown let startupError: unknown
try { try {
await continueWithSidecar() await mutate(() => continueWithSidecar(), {
id: 'continue-with-sidecar',
errorNotice: false,
})
} catch (error) { } catch (error) {
startupError = error startupError = error
} }
@@ -14,6 +14,7 @@ import {
type PendingFailure, type PendingFailure,
type ServiceInstallOutcome, type ServiceInstallOutcome,
} from '@/services/cmds' } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { import {
clearServiceRequest, clearServiceRequest,
@@ -103,10 +104,18 @@ export const SysproxyPrivilegeDialog = () => {
let outcome: ServiceInstallOutcome | undefined let outcome: ServiceInstallOutcome | undefined
if (remedy === 'reinstallAndRestart') { if (remedy === 'reinstallAndRestart') {
setStep('installing') setStep('installing')
outcome = await reinstallService() const result = await mutate(() => reinstallService(), {
id: 'reinstall-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
} else if (remedy === 'installAndRestart') { } else if (remedy === 'installAndRestart') {
setStep('installing') setStep('installing')
outcome = await installService() const result = await mutate(() => installService(), {
id: 'install-service',
errorNotice: false,
})
if (result.ok) outcome = result.value
} }
if (outcome?.status === 'sidecar') { if (outcome?.status === 'sidecar') {
showNotice.warning( showNotice.warning(
@@ -118,7 +127,10 @@ export const SysproxyPrivilegeDialog = () => {
return return
} }
setStep('restarting') setStep('restarting')
await restartCore() await mutate(() => restartCore(), {
id: 'restart-core',
errorNotice: false,
})
const runState = await getRuntimeState() const runState = await getRuntimeState()
const usingAdminFallback = const usingAdminFallback =
@@ -131,7 +143,10 @@ export const SysproxyPrivilegeDialog = () => {
if (runState.mode === 'Service' || usingAdminFallback) { if (runState.mode === 'Service' || usingAdminFallback) {
if (restoring !== undefined) { if (restoring !== undefined) {
setStep('applying') setStep('applying')
await patchVergeConfig(restoring) await mutate(() => patchVergeConfig(restoring), {
id: 'sysproxy-privilege-restore',
errorNotice: false,
})
} }
if (!usingAdminFallback) { if (!usingAdminFallback) {
showNotice.success( showNotice.success(
@@ -42,6 +42,7 @@ import {
readProfileFile, readProfileFile,
saveProfileFile, saveProfileFile,
} from '@/services/cmds' } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { useThemeMode } from '@/services/states' import { useThemeMode } from '@/services/states'
import type { TranslationKey } from '@/types/generated/i18n-keys' import type { TranslationKey } from '@/types/generated/i18n-keys'
@@ -472,7 +473,11 @@ export const GroupsEditorViewer = (props: Props) => {
setCurrData(nextData) setCurrData(nextData)
} }
if (!(await saveProfileFile(property, nextData))) { const result = await mutate(() => saveProfileFile(property, nextData), {
id: `save-profile-file:${property}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await fetchContent() await fetchContent()
onClose() onClose()
return return
+35 -18
View File
@@ -39,8 +39,12 @@ import {
updateProfile, updateProfile,
viewProfile, viewProfile,
} from '@/services/cmds' } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { useLoadingCache, useSetLoadingCache } from '@/services/states' import {
useProfileLoadingCache,
useSetProfileLoading,
} from '@/store/app-store-context'
import type { TranslationKey } from '@/types/generated/i18n-keys' import type { TranslationKey } from '@/types/generated/i18n-keys'
import { debugLog } from '@/utils/debug' import { debugLog } from '@/utils/debug'
import { isValidUrl } from '@/utils/network' import { isValidUrl } from '@/utils/network'
@@ -105,8 +109,8 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const { t } = useTranslation() const { t } = useTranslation()
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null) const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null)
const [position, setPosition] = useState({ left: 0, top: 0 }) const [position, setPosition] = useState({ left: 0, top: 0 })
const loadingCache = useLoadingCache() const loadingCache = useProfileLoadingCache()
const setLoadingCache = useSetLoadingCache() const setProfileLoading = useSetProfileLoading()
const [showNextUpdate, setShowNextUpdate] = useState(false) const [showNextUpdate, setShowNextUpdate] = useState(false)
const showNextUpdateRef = useRef(false) const showNextUpdateRef = useRef(false)
@@ -116,17 +120,9 @@ const ProfileItemBase = (props: ProfileItemProps) => {
) )
const setLoading = useCallback( const setLoading = useCallback(
(loading: boolean) => { (loading: boolean) => {
setLoadingCache((cache) => { setProfileLoading([itemData.uid], loading)
const next = new Set(cache)
if (loading) {
next.add(itemData.uid)
} else {
next.delete(itemData.uid)
}
return next
})
}, },
[itemData.uid, setLoadingCache], [itemData.uid, setProfileLoading],
) )
const { uid, name = 'Profile', extra, updated = 0, option } = itemData const { uid, name = 'Profile', extra, updated = 0, option } = itemData
@@ -374,7 +370,10 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const onOpenFile = useLockFn(async () => { const onOpenFile = useLockFn(async () => {
setAnchorEl(null) setAnchorEl(null)
try { try {
await viewProfile(itemData.uid) await mutate(() => viewProfile(itemData.uid), {
id: 'view-profile',
errorNotice: false,
})
} catch (err) { } catch (err) {
showNotice.error(err) showNotice.error(err)
} }
@@ -403,7 +402,10 @@ const ProfileItemBase = (props: ProfileItemProps) => {
try { try {
const payload = Object.keys(option).length > 0 ? option : undefined const payload = Object.keys(option).length > 0 ? option : undefined
await updateProfile(itemData.uid, payload) await mutate(() => updateProfile(itemData.uid, payload), {
id: `update-profile:${itemData.uid}`,
errorNotice: false,
})
void mutateProfiles() void mutateProfiles()
} catch { } catch {
@@ -591,7 +593,11 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const handleSaveProfileDocument = useLockFn(async () => { const handleSaveProfileDocument = useLockFn(async () => {
const currentValue = profileDocument.value const currentValue = profileDocument.value
if (!(await saveProfileFile(uid, currentValue))) { const result = await mutate(() => saveProfileFile(uid, currentValue), {
id: `save-profile-file:${uid}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await profileDocument.reload() await profileDocument.reload()
return return
} }
@@ -602,7 +608,11 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const handleSaveMergeDocument = useLockFn(async () => { const handleSaveMergeDocument = useLockFn(async () => {
const mergeUid = option?.merge ?? '' const mergeUid = option?.merge ?? ''
const currentValue = mergeDocument.value const currentValue = mergeDocument.value
if (!(await saveProfileFile(mergeUid, currentValue))) { const result = await mutate(() => saveProfileFile(mergeUid, currentValue), {
id: `save-profile-file:${mergeUid}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await mergeDocument.reload() await mergeDocument.reload()
return return
} }
@@ -613,7 +623,14 @@ const ProfileItemBase = (props: ProfileItemProps) => {
const handleSaveScriptDocument = useLockFn(async () => { const handleSaveScriptDocument = useLockFn(async () => {
const scriptUid = option?.script ?? '' const scriptUid = option?.script ?? ''
const currentValue = scriptDocument.value const currentValue = scriptDocument.value
if (!(await saveProfileFile(scriptUid, currentValue))) { const result = await mutate(
() => saveProfileFile(scriptUid, currentValue),
{
id: `save-profile-file:${scriptUid}`,
errorNotice: false,
},
)
if (!(result.ok && result.value === true)) {
await scriptDocument.reload() await scriptDocument.reload()
return return
} }
+10 -2
View File
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next'
import { EditorViewer } from '@/components/profile/editor-viewer' import { EditorViewer } from '@/components/profile/editor-viewer'
import { useEditorDocument } from '@/hooks/use-editor-document' import { useEditorDocument } from '@/hooks/use-editor-document'
import { viewProfile, readProfileFile, saveProfileFile } from '@/services/cmds' import { viewProfile, readProfileFile, saveProfileFile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { EnhanceHint } from './enhance-hint' import { EnhanceHint } from './enhance-hint'
@@ -63,7 +64,10 @@ export const ProfileMore = (props: Props) => {
const onOpenFile = useLockFn(async () => { const onOpenFile = useLockFn(async () => {
setAnchorEl(null) setAnchorEl(null)
try { try {
await viewProfile(id) await mutate(() => viewProfile(id), {
id: 'view-profile',
errorNotice: false,
})
} catch (err) { } catch (err) {
showNotice.error(err) showNotice.error(err)
} }
@@ -96,7 +100,11 @@ export const ProfileMore = (props: Props) => {
const handleSave = useLockFn(async () => { const handleSave = useLockFn(async () => {
const currentValue = document.value const currentValue = document.value
if (!(await saveProfileFile(id, currentValue))) { const result = await mutate(() => saveProfileFile(id, currentValue), {
id: `save-profile-file:${id}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await document.reload() await document.reload()
return return
} }
+35 -7
View File
@@ -17,6 +17,7 @@ import { useTranslation } from 'react-i18next'
import { BaseDialog, Switch } from '@/components/base' import { BaseDialog, Switch } from '@/components/base'
import { useProfiles } from '@/hooks/use-profiles' import { useProfiles } from '@/hooks/use-profiles'
import { createProfile, patchProfile } from '@/services/cmds' import { createProfile, patchProfile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { version } from '@root/package.json' import { version } from '@root/package.json'
@@ -128,26 +129,38 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
if (!isRemote) { if (!isRemote) {
if (openType === 'new') { if (openType === 'new') {
await createProfile(item, fileDataRef.current) await mutate(() => createProfile(item, fileDataRef.current), {
id: 'create-profile',
errorNotice: false,
})
} else { } else {
if (!form.uid) { if (!form.uid) {
throw new Error( throw new Error(
t('profiles.modals.profileForm.errors.uidMissing'), t('profiles.modals.profileForm.errors.uidMissing'),
) )
} }
await patchProfile(form.uid, item) await mutate(() => patchProfile(form.uid, item), {
id: 'patch-profile',
errorNotice: false,
})
} }
} else { } else {
try { try {
if (openType === 'new') { if (openType === 'new') {
await createProfile(item, fileDataRef.current) await mutate(() => createProfile(item, fileDataRef.current), {
id: 'create-profile',
errorNotice: false,
})
} else { } else {
if (!form.uid) { if (!form.uid) {
throw new Error( throw new Error(
t('profiles.modals.profileForm.errors.uidMissing'), t('profiles.modals.profileForm.errors.uidMissing'),
) )
} }
await patchProfile(form.uid, item) await mutate(() => patchProfile(form.uid, item), {
id: 'patch-profile',
errorNotice: false,
})
} }
} catch { } catch {
showNotice.info( showNotice.info(
@@ -164,16 +177,31 @@ export function ProfileViewer({ onChange, ref }: ProfileViewerProps) {
} }
if (openType === 'new') { if (openType === 'new') {
await createProfile(retryItem, fileDataRef.current) await mutate(
() => createProfile(retryItem, fileDataRef.current),
{
id: 'create-profile',
errorNotice: false,
},
)
} else { } else {
if (!form.uid) { if (!form.uid) {
throw new Error( throw new Error(
t('profiles.modals.profileForm.errors.uidMissing'), t('profiles.modals.profileForm.errors.uidMissing'),
) )
} }
await patchProfile(form.uid, retryItem) await mutate(() => patchProfile(form.uid, retryItem), {
id: 'patch-profile',
errorNotice: false,
})
await patchProfile(form.uid, { option: originalOptions }) await mutate(
() => patchProfile(form.uid, { option: originalOptions }),
{
id: 'patch-profile',
errorNotice: false,
},
)
} }
showNotice.success( showNotice.success(
@@ -30,6 +30,7 @@ import { useTranslation } from 'react-i18next'
import { BaseSearchBox, MonacoEditor } from '@/components/base' import { BaseSearchBox, MonacoEditor } from '@/components/base'
import { ProxyItem } from '@/components/profile/proxy-item' import { ProxyItem } from '@/components/profile/proxy-item'
import { readProfileFile, saveProfileFile } from '@/services/cmds' import { readProfileFile, saveProfileFile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { useThemeMode } from '@/services/states' import { useThemeMode } from '@/services/states'
import type { MonacoEditorInstance } from '@/types/monaco' import type { MonacoEditorInstance } from '@/types/monaco'
@@ -329,7 +330,11 @@ export const ProxiesEditorViewer = (props: Props) => {
const handleSave = useLockFn(async () => { const handleSave = useLockFn(async () => {
try { try {
if (!(await saveProfileFile(property, currData))) { const result = await mutate(() => saveProfileFile(property, currData), {
id: `save-profile-file:${property}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await fetchContent() await fetchContent()
onClose() onClose()
return return
@@ -32,6 +32,7 @@ import { useTranslation } from 'react-i18next'
import { BaseSearchBox, MonacoEditor, Switch } from '@/components/base' import { BaseSearchBox, MonacoEditor, Switch } from '@/components/base'
import { RuleItem } from '@/components/profile/rule-item' import { RuleItem } from '@/components/profile/rule-item'
import { readProfileFile, saveProfileFile } from '@/services/cmds' import { readProfileFile, saveProfileFile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { useThemeMode } from '@/services/states' import { useThemeMode } from '@/services/states'
import type { TranslationKey } from '@/types/generated/i18n-keys' import type { TranslationKey } from '@/types/generated/i18n-keys'
@@ -570,7 +571,11 @@ export const RulesEditorViewer = (props: Props) => {
const handleSave = useLockFn(async () => { const handleSave = useLockFn(async () => {
try { try {
if (!(await saveProfileFile(property, currData))) { const result = await mutate(() => saveProfileFile(property, currData), {
id: `save-profile-file:${property}`,
errorNotice: false,
})
if (!(result.ok && result.value === true)) {
await fetchContent() await fetchContent()
onClose() onClose()
return return
+17 -4
View File
@@ -24,6 +24,7 @@ import { updateProxyProvider } from 'tauri-plugin-mihomo-api'
import { useAppRefreshers, useProxiesData } from '@/providers/app-data-context' import { useAppRefreshers, useProxiesData } from '@/providers/app-data-context'
import { syncRuntimeProviders } from '@/services/cmds' import { syncRuntimeProviders } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import parseTraffic from '@/utils/parse-traffic' import parseTraffic from '@/utils/parse-traffic'
@@ -57,10 +58,16 @@ export const ProviderButton = () => {
try { try {
setUpdating((prev) => ({ ...prev, [name]: true })) setUpdating((prev) => ({ ...prev, [name]: true }))
await updateProxyProvider(name) await mutate(() => updateProxyProvider(name), {
id: `update-proxy-provider-${name}`,
errorNotice: false,
})
await refreshProxy() await refreshProxy()
void syncRuntimeProviders() void mutate(() => syncRuntimeProviders(), {
id: 'sync-runtime-providers',
errorNotice: false,
})
showNotice.success( showNotice.success(
'proxies.feedback.notifications.provider.updateSuccess', 'proxies.feedback.notifications.provider.updateSuccess',
@@ -97,7 +104,10 @@ export const ProviderButton = () => {
for (const name of allProviders) { for (const name of allProviders) {
try { try {
await updateProxyProvider(name) await mutate(() => updateProxyProvider(name), {
id: `update-proxy-provider-${name}`,
errorNotice: false,
})
setUpdating((prev) => ({ ...prev, [name]: false })) setUpdating((prev) => ({ ...prev, [name]: false }))
} catch (err) { } catch (err) {
console.error(`更新 ${name} 失败`, err) console.error(`更新 ${name} 失败`, err)
@@ -105,7 +115,10 @@ export const ProviderButton = () => {
} }
await refreshProxy() await refreshProxy()
void syncRuntimeProviders() void mutate(() => syncRuntimeProviders(), {
id: 'sync-runtime-providers',
errorNotice: false,
})
showNotice.success('proxies.feedback.notifications.provider.allUpdated') showNotice.success('proxies.feedback.notifications.provider.allUpdated')
} catch (err) { } catch (err) {
+36 -7
View File
@@ -45,6 +45,7 @@ import { useRuntimeConfig } from '@/hooks/use-clash'
import { useRecordSelection } from '@/hooks/use-record-selection' import { useRecordSelection } from '@/hooks/use-record-selection'
import { useAppRefreshers, useProxiesData } from '@/providers/app-data-context' import { useAppRefreshers, useProxiesData } from '@/providers/app-data-context'
import { updateProxyChainConfigInRuntime } from '@/services/cmds' import { updateProxyChainConfigInRuntime } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { import {
selectGlobalChainNodes, selectGlobalChainNodes,
selectRuleChainMembers, selectRuleChainMembers,
@@ -444,7 +445,10 @@ export const ProxyChain = ({
if (isConnected) { if (isConnected) {
setIsConnecting(true) setIsConnecting(true)
try { try {
await updateProxyChainConfigInRuntime(null) await mutate(() => updateProxyChainConfigInRuntime(null), {
id: 'update-proxy-chain-runtime',
errorNotice: false,
})
const targetGroup = const targetGroup =
mode === 'global' mode === 'global'
@@ -453,12 +457,22 @@ export const ProxyChain = ({
if (targetGroup) { if (targetGroup) {
try { try {
await selectNodeForGroup(targetGroup, 'DIRECT') await mutate(() => selectNodeForGroup(targetGroup, 'DIRECT'), {
id: 'select-proxy-node',
errorNotice: false,
})
recordSelection(targetGroup, 'DIRECT') recordSelection(targetGroup, 'DIRECT')
} catch { } catch {
if (currentProxyChain.length >= 1) { if (currentProxyChain.length >= 1) {
try { try {
await selectNodeForGroup(targetGroup, currentProxyChain[0].name) await mutate(
() =>
selectNodeForGroup(targetGroup, currentProxyChain[0].name),
{
id: 'select-proxy-node',
errorNotice: false,
},
)
recordSelection(targetGroup, currentProxyChain[0].name) recordSelection(targetGroup, currentProxyChain[0].name)
} catch { } catch {
// ignore // ignore
@@ -471,7 +485,10 @@ export const ProxyChain = ({
localStorage.removeItem('proxy-chain-exit-node') localStorage.removeItem('proxy-chain-exit-node')
localStorage.removeItem('proxy-chain-items') localStorage.removeItem('proxy-chain-items')
await closeAllConnections() await mutate(() => closeAllConnections(), {
id: 'close-all-connections',
errorNotice: false,
})
await refreshProxy() await refreshProxy()
onUpdateChain([]) onUpdateChain([])
@@ -502,7 +519,10 @@ export const ProxyChain = ({
// 第一步:保存链式代理配置 // 第一步:保存链式代理配置
const chainProxies = currentProxyChain.map((node) => node.name) const chainProxies = currentProxyChain.map((node) => node.name)
debugLog('Saving chain config:', chainProxies) debugLog('Saving chain config:', chainProxies)
await updateProxyChainConfigInRuntime(chainProxies) await mutate(() => updateProxyChainConfigInRuntime(chainProxies), {
id: 'update-proxy-chain-runtime',
errorNotice: false,
})
debugLog('Chain configuration saved successfully') debugLog('Chain configuration saved successfully')
// 第二步:连接到代理链的最后一个节点 // 第二步:连接到代理链的最后一个节点
@@ -516,7 +536,13 @@ export const ProxyChain = ({
const targetGroup = mode === 'global' ? 'GLOBAL' : selectedGroup const targetGroup = mode === 'global' ? 'GLOBAL' : selectedGroup
await selectNodeForGroup(targetGroup || 'GLOBAL', lastNode.name) await mutate(
() => selectNodeForGroup(targetGroup || 'GLOBAL', lastNode.name),
{
id: 'select-proxy-node',
errorNotice: false,
},
)
// The chain moves the group like any other selection, so the profile has to learn about // The chain moves the group like any other selection, so the profile has to learn about
// it: what the profile holds is what gets re-applied the next time the core starts. // it: what the profile holds is what gets re-applied the next time the core starts.
recordSelection(targetGroup || 'GLOBAL', lastNode.name) recordSelection(targetGroup || 'GLOBAL', lastNode.name)
@@ -593,7 +619,10 @@ export const ProxyChain = ({
<IconButton <IconButton
size="small" size="small"
onClick={() => { onClick={() => {
updateProxyChainConfigInRuntime(null) mutate(() => updateProxyChainConfigInRuntime(null), {
id: 'update-proxy-chain-runtime',
errorNotice: false,
})
localStorage.removeItem('proxy-chain-group') localStorage.removeItem('proxy-chain-group')
localStorage.removeItem('proxy-chain-exit-node') localStorage.removeItem('proxy-chain-exit-node')
localStorage.removeItem('proxy-chain-items') localStorage.removeItem('proxy-chain-items')
+7 -7
View File
@@ -4,11 +4,10 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router' import { useNavigate } from 'react-router'
import { runStateQueryKey } from '@/hooks/use-system-state' import { useSystemState } from '@/hooks/use-system-state'
import { useAppRefreshers } from '@/providers/app-data-context' import { useAppRefreshers } from '@/providers/app-data-context'
import { openLogsDir, restartCore } from '@/services/cmds' import { openLogsDir, restartCore } from '@/services/cmds'
import { showNotice } from '@/services/notice-service' import { mutate } from '@/services/mutate'
import { revalidateQuery } from '@/services/query-client'
import type { ProxyEmptyStateReason } from './proxy-empty-state-model' import type { ProxyEmptyStateReason } from './proxy-empty-state-model'
@@ -20,15 +19,16 @@ export const ProxyEmptyState = ({ reason }: Props) => {
const { t } = useTranslation() const { t } = useTranslation()
const navigate = useNavigate() const navigate = useNavigate()
const { refreshProxy } = useAppRefreshers() const { refreshProxy } = useAppRefreshers()
const { mutateSystemState } = useSystemState()
const [isRestarting, setIsRestarting] = useState(false) const [isRestarting, setIsRestarting] = useState(false)
const handleRestart = useLockFn(async () => { const handleRestart = useLockFn(async () => {
setIsRestarting(true) setIsRestarting(true)
try { try {
await restartCore() await mutate(() => restartCore(), { id: 'restart-core' })
await Promise.all([refreshProxy(), revalidateQuery(runStateQueryKey)]) await Promise.all([refreshProxy(), mutateSystemState()])
} catch (error) { } catch {
showNotice.error(error) // the funnel already notified
} finally { } finally {
setIsRestarting(false) setIsRestarting(false)
} }
+5 -1
View File
@@ -24,6 +24,7 @@ import { useTranslation } from 'react-i18next'
import { useProxiesData } from '@/providers/app-data-context' import { useProxiesData } from '@/providers/app-data-context'
import { updateProxyChainConfigInRuntime } from '@/services/cmds' import { updateProxyChainConfigInRuntime } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { import {
isInteractableMember, isInteractableMember,
type ProxyGroupView, type ProxyGroupView,
@@ -404,7 +405,10 @@ export function ProxyGroupsChain(props: ProxyGroupsChainProps) {
handleGroupMenuClose() handleGroupMenuClose()
if (mode === 'rule') { if (mode === 'rule') {
updateProxyChainConfigInRuntime(null) mutate(() => updateProxyChainConfigInRuntime(null), {
id: 'update-proxy-chain-runtime',
errorNotice: false,
})
localStorage.removeItem('proxy-chain-group') localStorage.removeItem('proxy-chain-group')
localStorage.removeItem('proxy-chain-exit-node') localStorage.removeItem('proxy-chain-exit-node')
localStorage.removeItem('proxy-chain-items') localStorage.removeItem('proxy-chain-items')
+17 -4
View File
@@ -23,6 +23,7 @@ import { updateRuleProvider } from 'tauri-plugin-mihomo-api'
import { useAppRefreshers, useRulesData } from '@/providers/app-data-context' import { useAppRefreshers, useRulesData } from '@/providers/app-data-context'
import { syncRuntimeProviders } from '@/services/cmds' import { syncRuntimeProviders } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
const TypeBox = styled(Box)<{ component?: React.ElementType }>(({ theme }) => ({ const TypeBox = styled(Box)<{ component?: React.ElementType }>(({ theme }) => ({
@@ -50,11 +51,17 @@ export const ProviderButton = () => {
try { try {
setUpdating((prev) => ({ ...prev, [name]: true })) setUpdating((prev) => ({ ...prev, [name]: true }))
await updateRuleProvider(name) await mutate(() => updateRuleProvider(name), {
id: `update-rule-provider-${name}`,
errorNotice: false,
})
await refreshRules() await refreshRules()
await refreshRuleProviders() await refreshRuleProviders()
void syncRuntimeProviders() void mutate(() => syncRuntimeProviders(), {
id: 'sync-runtime-providers',
errorNotice: false,
})
showNotice.success( showNotice.success(
'rules.feedback.notifications.provider.updateSuccess', 'rules.feedback.notifications.provider.updateSuccess',
@@ -91,7 +98,10 @@ export const ProviderButton = () => {
for (const name of allProviders) { for (const name of allProviders) {
try { try {
await updateRuleProvider(name) await mutate(() => updateRuleProvider(name), {
id: `update-rule-provider-${name}`,
errorNotice: false,
})
setUpdating((prev) => ({ ...prev, [name]: false })) setUpdating((prev) => ({ ...prev, [name]: false }))
} catch (err) { } catch (err) {
console.error(`更新 ${name} 失败`, err) console.error(`更新 ${name} 失败`, err)
@@ -100,7 +110,10 @@ export const ProviderButton = () => {
await refreshRules() await refreshRules()
await refreshRuleProviders() await refreshRuleProviders()
void syncRuntimeProviders() void mutate(() => syncRuntimeProviders(), {
id: 'sync-runtime-providers',
errorNotice: false,
})
showNotice.success('rules.feedback.notifications.provider.allUpdated') showNotice.success('rules.feedback.notifications.provider.allUpdated')
} catch (err) { } catch (err) {
@@ -15,6 +15,7 @@ import { useTranslation } from 'react-i18next'
import { useVerge } from '@/hooks/use-verge' import { useVerge } from '@/hooks/use-verge'
import { saveWebdavConfig, createWebdavBackup } from '@/services/cmds' import { saveWebdavConfig, createWebdavBackup } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { errorDetail, showNotice } from '@/services/notice-service' import { errorDetail, showNotice } from '@/services/notice-service'
import { import {
buildWebdavSignature, buildWebdavSignature,
@@ -119,7 +120,13 @@ export const BackupConfigViewer = memo(
try { try {
setLoading(true) setLoading(true)
await saveWebdavConfig(trimmedUrl, trimmedUsername, data.password) await mutate(
() => saveWebdavConfig(trimmedUrl, trimmedUsername, data.password),
{
id: 'save-webdav-config',
errorNotice: false,
},
)
await mutateVerge( await mutateVerge(
(current) => (current) =>
current current
@@ -156,7 +163,10 @@ export const BackupConfigViewer = memo(
try { try {
setLoading(true) setLoading(true)
await createWebdavBackup().then(async () => { await mutate(() => createWebdavBackup(), {
id: 'create-webdav-backup',
errorNotice: false,
}).then(async () => {
showNotice.success('settings.modals.backup.messages.backupCreated') showNotice.success('settings.modals.backup.messages.backupCreated')
await onBackupSuccess() await onBackupSuccess()
}) })
@@ -35,6 +35,7 @@ import {
restoreLocalBackup, restoreLocalBackup,
restoreWebDavBackup, restoreWebDavBackup,
} from '@/services/cmds' } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { import {
buildWebdavSignature, buildWebdavSignature,
@@ -228,17 +229,29 @@ export const BackupHistoryViewer = ({
try { try {
if (action === 'delete') { if (action === 'delete') {
if (actionIsLocal) { if (actionIsLocal) {
await deleteLocalBackup(filename) await mutate(() => deleteLocalBackup(filename), {
id: 'delete-local-backup',
errorNotice: false,
})
} else { } else {
await deleteWebdavBackup(filename) await mutate(() => deleteWebdavBackup(filename), {
id: 'delete-webdav-backup',
errorNotice: false,
})
} }
setPendingConfirmation(null) setPendingConfirmation(null)
await fetchRows() await fetchRows()
} else { } else {
if (actionIsLocal) { if (actionIsLocal) {
await restoreLocalBackup(filename) await mutate(() => restoreLocalBackup(filename), {
id: 'restore-local-backup',
errorNotice: false,
})
} else { } else {
await restoreWebDavBackup(filename) await mutate(() => restoreWebDavBackup(filename), {
id: 'restore-webdav-backup',
errorNotice: false,
})
} }
setPendingConfirmation(null) setPendingConfirmation(null)
showNotice.success('settings.modals.backup.messages.restoreSuccess') showNotice.success('settings.modals.backup.messages.restoreSuccess')
@@ -265,8 +278,11 @@ export const BackupHistoryViewer = ({
const savePath = await save({ defaultPath: filename }) const savePath = await save({ defaultPath: filename })
if (!savePath || Array.isArray(savePath)) return if (!savePath || Array.isArray(savePath)) return
try { try {
await exportLocalBackup(filename, savePath) await mutate(() => exportLocalBackup(filename, savePath), {
showNotice.success('settings.modals.backup.messages.localBackupExported') id: 'export-local-backup',
errorNotice: false,
successNotice: 'settings.modals.backup.messages.localBackupExported',
})
} catch (ignoreError: unknown) { } catch (ignoreError: unknown) {
showNotice.error( showNotice.error(
'settings.modals.backup.messages.localBackupExportFailed', 'settings.modals.backup.messages.localBackupExportFailed',
+17 -7
View File
@@ -19,6 +19,7 @@ import {
createWebdavBackup, createWebdavBackup,
importLocalBackup, importLocalBackup,
} from '@/services/cmds' } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { errorDetail, showNotice } from '@/services/notice-service' import { errorDetail, showNotice } from '@/services/notice-service'
import { buildWebdavSignature, setWebdavStatus } from '@/services/webdav-status' import { buildWebdavSignature, setWebdavStatus } from '@/services/webdav-status'
@@ -55,12 +56,18 @@ export function BackupViewer({ ref }: { ref?: Ref<DialogRef> }) {
try { try {
setBusyAction(target) setBusyAction(target)
if (target === 'local') { if (target === 'local') {
await createLocalBackup() await mutate(() => createLocalBackup(), {
showNotice.success('settings.modals.backup.messages.localBackupCreated') id: 'create-local-backup',
errorNotice: false,
successNotice: 'settings.modals.backup.messages.localBackupCreated',
})
} else { } else {
await createWebdavBackup() await mutate(() => createWebdavBackup(), {
showNotice.success('settings.modals.backup.messages.backupCreated') id: 'create-webdav-backup',
setWebdavStatus(webdavSignature, 'ready') errorNotice: false,
successNotice: 'settings.modals.backup.messages.backupCreated',
onFulfilled: () => setWebdavStatus(webdavSignature, 'ready'),
})
} }
} catch (error) { } catch (error) {
console.error(error) console.error(error)
@@ -86,8 +93,11 @@ export function BackupViewer({ ref }: { ref?: Ref<DialogRef> }) {
if (!selected || Array.isArray(selected)) return if (!selected || Array.isArray(selected)) return
try { try {
setLocalImporting(true) setLocalImporting(true)
await importLocalBackup(selected) await mutate(() => importLocalBackup(selected), {
showNotice.success('settings.modals.backup.messages.localBackupImported') id: 'import-local-backup',
errorNotice: false,
successNotice: 'settings.modals.backup.messages.localBackupImported',
})
openHistory('local') openHistory('local')
} catch (error) { } catch (error) {
console.error(error) console.error(error)
@@ -21,6 +21,7 @@ import { BaseDialog, DialogRef } from '@/components/base'
import { useClash, useClashInfo } from '@/hooks/use-clash' import { useClash, useClashInfo } from '@/hooks/use-clash'
import { useVerge } from '@/hooks/use-verge' import { useVerge } from '@/hooks/use-verge'
import { changeClashCore, restartCore, upgradeClashCore } from '@/services/cmds' import { changeClashCore, restartCore, upgradeClashCore } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
const VALID_CORE = [ const VALID_CORE = [
@@ -60,8 +61,16 @@ export function ClashCoreViewer({ ref }: { ref?: Ref<DialogRef> }) {
try { try {
setChangingCore(core) setChangingCore(core)
closeAllConnections() void mutate(() => closeAllConnections(), {
const errorMsg = await changeClashCore(core) id: 'close-all-connections',
errorNotice: false,
})
const result = await mutate(() => changeClashCore(core), {
id: 'change-clash-core',
errorNotice: false,
})
if (!result.ok) return
const errorMsg = result.value
if (errorMsg) { if (errorMsg) {
showNotice.error(errorMsg) showNotice.error(errorMsg)
@@ -83,28 +92,33 @@ export function ClashCoreViewer({ ref }: { ref?: Ref<DialogRef> }) {
const onRestart = useLockFn(async () => { const onRestart = useLockFn(async () => {
try { try {
setRestarting(true) setRestarting(true)
await restartCore() await mutate(() => restartCore(), {
showNotice.success( id: 'restart-core',
t('settings.feedback.notifications.clash.restartSuccess'), successNotice: t(
) 'settings.feedback.notifications.clash.restartSuccess',
),
})
setRestarting(false) setRestarting(false)
} catch (err) { } catch {
setRestarting(false) setRestarting(false)
showNotice.error(err)
} }
}) })
const onUpgrade = useLockFn(async () => { const onUpgrade = useLockFn(async () => {
try { try {
setUpgrading(true) setUpgrading(true)
const report = await upgradeClashCore() await mutate(() => upgradeClashCore(), {
showNotice.success( id: 'upgrade-clash-core',
report.upgraded onFulfilled: (report) => {
? t('settings.feedback.notifications.clash.versionUpdated') showNotice.success(
: t('settings.feedback.notifications.clash.alreadyLatestVersion'), report.upgraded
) ? t('settings.feedback.notifications.clash.versionUpdated')
} catch (err) { : t('settings.feedback.notifications.clash.alreadyLatestVersion'),
showNotice.error(err) )
},
})
} catch {
// the funnel already notified
} finally { } finally {
setUpgrading(false) setUpgrading(false)
} }
@@ -15,7 +15,8 @@ import { useTranslation } from 'react-i18next'
import { BaseDialog, Switch } from '@/components/base' import { BaseDialog, Switch } from '@/components/base'
import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port' import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
import { useVerge } from '@/hooks/use-verge' import { useVerge } from '@/hooks/use-verge'
import { saveProxyPorts } from '@/services/cmds' import { saveProxyPorts, type ProxyPortSettings } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import getSystem from '@/utils/get-system' import getSystem from '@/utils/get-system'
@@ -57,22 +58,31 @@ export const ClashPortViewer = forwardRef<ClashPortViewerRef>((_, ref) => {
) )
// 添加保存请求,防止GUI卡死 // 添加保存请求,防止GUI卡死
const { loading, runAsync: saveSettings } = useRequest(saveProxyPorts, { const { loading, runAsync: saveSettings } = useRequest(
manual: true, async (settings: ProxyPortSettings) =>
onSuccess: (outcome) => { mutate(() => saveProxyPorts(settings), {
if (outcome.status === 'conflict') { id: 'save-proxy-ports',
showNotice.error('settings.modals.clashPort.messages.portInUse', { errorNotice: false,
port: outcome.port, }),
}) {
return manual: true,
} onSuccess: (result) => {
setOpen(false) if (!result.ok) return
showNotice.success('settings.modals.clashPort.messages.saved') const outcome = result.value
if (outcome.status === 'conflict') {
showNotice.error('settings.modals.clashPort.messages.portInUse', {
port: outcome.port,
})
return
}
setOpen(false)
showNotice.success('settings.modals.clashPort.messages.saved')
},
onError: (error) => {
showNotice.error('settings.modals.clashPort.messages.saveFailed', error)
},
}, },
onError: (error) => { )
showNotice.error('settings.modals.clashPort.messages.saveFailed', error)
},
})
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
open: () => { open: () => {
+10 -11
View File
@@ -13,7 +13,6 @@ import {
TextField, TextField,
Typography, Typography,
} from '@mui/material' } from '@mui/material'
import { invoke } from '@tauri-apps/api/core'
import { useLockFn } from 'ahooks' import { useLockFn } from 'ahooks'
import * as yaml from 'js-yaml' import * as yaml from 'js-yaml'
import type { Ref } from 'react' import type { Ref } from 'react'
@@ -36,6 +35,12 @@ import {
import { useClash } from '@/hooks/use-clash' import { useClash } from '@/hooks/use-clash'
import { useProfiles } from '@/hooks/use-profiles' import { useProfiles } from '@/hooks/use-profiles'
import { useVerge } from '@/hooks/use-verge' import { useVerge } from '@/hooks/use-verge'
import {
applyDnsConfig,
getDnsConfigContent,
saveDnsConfig,
validateDnsConfig,
} from '@/services/cmds'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { useThemeMode } from '@/services/states' import { useThemeMode } from '@/services/states'
import type { MonacoEditorInstance } from '@/types/monaco' import type { MonacoEditorInstance } from '@/types/monaco'
@@ -465,10 +470,7 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
const initDnsConfig = useCallback(async () => { const initDnsConfig = useCallback(async () => {
try { try {
const dnsConfig = await invoke<string | null>( const dnsConfig = await getDnsConfigContent()
'get_dns_config_content',
{},
)
if (dnsConfig !== null) { if (dnsConfig !== null) {
const config = yaml.load(dnsConfig) as any const config = yaml.load(dnsConfig) as any
@@ -517,12 +519,9 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
config = parsedConfig as Record<string, any> config = parsedConfig as Record<string, any>
} }
await invoke('save_dns_config', { dnsConfig: config }) await saveDnsConfig(config)
const validation = await invoke<ValidationOutcome>( const validation = await validateDnsConfig()
'validate_dns_config',
{},
)
if (validation.status !== 'valid') { if (validation.status !== 'valid') {
const errorMsg = const errorMsg =
@@ -559,7 +558,7 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
} }
if (dnsEnabled) { if (dnsEnabled) {
await invoke('apply_dns_config', { apply: true }) await applyDnsConfig(true)
mutateClash() mutateClash()
} }
@@ -7,6 +7,7 @@ import { useTranslation } from 'react-i18next'
import { BaseDialog, Switch } from '@/components/base' import { BaseDialog, Switch } from '@/components/base'
import { useClash } from '@/hooks/use-clash' import { useClash } from '@/hooks/use-clash'
import { restartCore } from '@/services/cmds' import { restartCore } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
// Development origins must never be persisted into production configuration. // Development origins must never be persisted into production configuration.
@@ -135,7 +136,10 @@ export const HeaderConfiguration = forwardRef<ClashHeaderConfigingRef>(
), ),
}, },
}) })
await restartCore() await mutate(() => restartCore(), {
id: 'restart-core',
errorNotice: false,
})
await mutateClash() await mutateClash()
}, },
{ {
@@ -14,6 +14,7 @@ import { useTranslation } from 'react-i18next'
import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base' import { BaseDialog, DialogRef, Switch, TooltipIcon } from '@/components/base'
import { useVerge } from '@/hooks/use-verge' import { useVerge } from '@/hooks/use-verge'
import { entry_lightweight_mode } from '@/services/cmds' import { entry_lightweight_mode } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
export function LiteModeViewer({ ref }: { ref?: Ref<DialogRef> }) { export function LiteModeViewer({ ref }: { ref?: Ref<DialogRef> }) {
@@ -72,7 +73,12 @@ export function LiteModeViewer({ ref }: { ref?: Ref<DialogRef> }) {
color: 'primary.main', color: 'primary.main',
'&:hover': { textDecoration: 'underline' }, '&:hover': { textDecoration: 'underline' },
}} }}
onClick={async () => await entry_lightweight_mode()} onClick={async () =>
await mutate(() => entry_lightweight_mode(), {
id: 'entry-lightweight-mode',
errorNotice: false,
})
}
> >
{t('shared.actions.enable')} {t('shared.actions.enable')}
</Typography> </Typography>
+5 -1
View File
@@ -21,6 +21,7 @@ import {
} from '@/components/base' } from '@/components/base'
import { useClash } from '@/hooks/use-clash' import { useClash } from '@/hooks/use-clash'
import { enhanceProfiles } from '@/services/cmds' import { enhanceProfiles } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import getSystem from '@/utils/get-system' import getSystem from '@/utils/get-system'
import { areValidIpCidrs } from '@/utils/network' import { areValidIpCidrs } from '@/utils/network'
@@ -129,7 +130,10 @@ export function TunViewer({ ref }: { ref?: Ref<DialogRef> }) {
) )
setOpen(false) setOpen(false)
showNotice.success('settings.modals.tun.messages.applied') showNotice.success('settings.modals.tun.messages.applied')
void enhanceProfiles().catch((err: any) => { void mutate(() => enhanceProfiles(), {
id: 'enhance-profiles',
errorNotice: false,
}).catch((err: any) => {
showNotice.error(err) showNotice.error(err)
}) })
} catch (err: any) { } catch (err: any) {
@@ -16,6 +16,7 @@ import type { Options as ReactMarkdownOptions } from 'react-markdown'
import { BaseDialog, DialogRef } from '@/components/base' import { BaseDialog, DialogRef } from '@/components/base'
import { useUpdate } from '@/hooks/use-update' import { useUpdate } from '@/hooks/use-update'
import { restartApp } from '@/services/cmds' import { restartApp } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { useSetUpdateState, useUpdateState } from '@/services/states' import { useSetUpdateState, useUpdateState } from '@/services/states'
import { openExternalUrl } from '@/utils/open-external-url' import { openExternalUrl } from '@/utils/open-external-url'
@@ -270,8 +271,14 @@ export function UpdateViewer({ ref }: { ref?: Ref<DialogRef> }) {
} }
try { try {
await updateInfo.downloadAndInstall(onDownloadEvent) await mutate(() => updateInfo.downloadAndInstall(onDownloadEvent), {
await restartApp() id: 'install-app-update',
errorNotice: false,
})
await mutate(() => restartApp(), {
id: 'restart-app',
errorNotice: false,
})
} catch (err: any) { } catch (err: any) {
showNotice.error(err) showNotice.error(err)
} finally { } finally {
+14 -2
View File
@@ -12,6 +12,7 @@ import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
import { useProfiles } from '@/hooks/use-profiles' import { useProfiles } from '@/hooks/use-profiles'
import { useVerge } from '@/hooks/use-verge' import { useVerge } from '@/hooks/use-verge'
import { invoke_uwp_tool, setDnsOverride } from '@/services/cmds' import { invoke_uwp_tool, setDnsOverride } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import getSystem from '@/utils/get-system' import getSystem from '@/utils/get-system'
@@ -74,7 +75,10 @@ const SettingClash = ({ onError }: Props) => {
} }
const onUpdateGeo = async () => { const onUpdateGeo = async () => {
try { try {
await updateGeo() await mutate(() => updateGeo(), {
id: 'update-geo',
errorNotice: false,
})
showNotice.success('settings.feedback.notifications.clash.geoDataUpdated') showNotice.success('settings.feedback.notifications.clash.geoDataUpdated')
} catch (err: any) { } catch (err: any) {
showNotice.error(err) showNotice.error(err)
@@ -90,7 +94,15 @@ const SettingClash = ({ onError }: Props) => {
if (!profileUid) return if (!profileUid) return
setDnsUpdating(true) setDnsUpdating(true)
try { try {
const outcome = await setDnsOverride(profileUid, enable, confirmation) const result = await mutate(
() => setDnsOverride(profileUid, enable, confirmation),
{
id: 'set-dns-override',
errorNotice: false,
},
)
if (!result.ok) return
const outcome = result.value
if (outcome.status === 'confirmation_required') { if (outcome.status === 'confirmation_required') {
setDnsConfirmation({ profileUid, source: outcome.source }) setDnsConfirmation({ profileUid, source: outcome.source })
} else { } else {
@@ -13,6 +13,7 @@ import {
openDevTools, openDevTools,
openLogsDir, openLogsDir,
} from '@/services/cmds' } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { checkUpdateSafe as checkUpdate } from '@/services/update' import { checkUpdateSafe as checkUpdate } from '@/services/update'
import { version } from '@root/package.json' import { version } from '@root/package.json'
@@ -61,7 +62,10 @@ const SettingVergeAdvanced = ({ onError: _ }: Props) => {
} }
const onExportDiagnosticInfo = useCallback(async () => { const onExportDiagnosticInfo = useCallback(async () => {
await exportDiagnosticInfo() await mutate(() => exportDiagnosticInfo(), {
id: 'export-diagnostic-info',
errorNotice: false,
})
showNotice.success('shared.feedback.notifications.common.copySuccess', 1000) showNotice.success('shared.feedback.notifications.common.copySuccess', 1000)
}, []) }, [])
@@ -128,7 +132,12 @@ const SettingVergeAdvanced = ({ onError: _ }: Props) => {
/> />
<SettingItem <SettingItem
onClick={openDevTools} onClick={() => {
void mutate(() => openDevTools(), {
id: 'open-devtools',
errorNotice: false,
}).catch(() => {})
}}
label={t('settings.components.verge.advanced.fields.openDevTools')} label={t('settings.components.verge.advanced.fields.openDevTools')}
/> />
@@ -145,7 +154,10 @@ const SettingVergeAdvanced = ({ onError: _ }: Props) => {
<SettingItem <SettingItem
onClick={() => { onClick={() => {
exitApp() void mutate(() => exitApp(), {
id: 'exit-app',
errorNotice: false,
}).catch(() => {})
}} }}
label={t('settings.components.verge.advanced.fields.exit')} label={t('settings.components.verge.advanced.fields.exit')}
/> />
+15 -6
View File
@@ -1,15 +1,15 @@
import { LanguageRounded } from '@mui/icons-material' import { LanguageRounded } from '@mui/icons-material'
import { Box, Divider, MenuItem, Menu, styled, alpha } from '@mui/material' import { Box, Divider, MenuItem, Menu, styled, alpha } from '@mui/material'
import { useLockFn } from 'ahooks' import { useLockFn } from 'ahooks'
import { useCallback, useEffect, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { BaseLoading } from '@/components/base' import { BaseLoading } from '@/components/base'
import { useIconCache } from '@/hooks/use-icon-cache' import { useIconCache } from '@/hooks/use-icon-cache'
import { cmdTestDelay } from '@/services/cmds' import { cmdTestDelay } from '@/services/cmds'
import delayManager from '@/services/delay' import delayManager from '@/services/delay'
import { subscribeVergeEvents } from '@/services/events'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
import { useTestAllCounter } from '@/store/app-store-context'
import { TestBox } from './test-box' import { TestBox } from './test-box'
@@ -52,10 +52,19 @@ export const TestItem = ({ itemData, onEdit, onDelete: removeTest }: Props) => {
{ label: t('shared.actions.delete'), handler: onDelete }, { label: t('shared.actions.delete'), handler: onDelete },
] ]
useEffect( // Store bump replaces the per-item event subscription; skip the initial
() => subscribeVergeEvents({ 'verge://test-all': () => onDelay() }), // mount value and call through a ref so url changes do not re-trigger tests.
[url, onDelay], const testAllCounter = useTestAllCounter()
) const onDelayRef = useRef(onDelay)
onDelayRef.current = onDelay
const mountedRef = useRef(false)
useEffect(() => {
if (!mountedRef.current) {
mountedRef.current = true
return
}
void onDelayRef.current()
}, [testAllCounter])
return ( return (
<Box> <Box>
+11 -5
View File
@@ -8,6 +8,7 @@ import {
getRuntimeConfig, getRuntimeConfig,
patchClashConfig, patchClashConfig,
} from '@/services/cmds' } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { import {
revalidateQuery, revalidateQuery,
setCacheData, setCacheData,
@@ -104,8 +105,11 @@ export const useClash = () => {
} }
const patchClash = useLockFn(async (patch: Partial<IConfigData>) => { const patchClash = useLockFn(async (patch: Partial<IConfigData>) => {
await patchClashConfig(patch) await mutate(() => patchClashConfig(patch), {
mutateClash() id: 'patch-clash-config',
revalidate: [['getRuntimeConfig']],
errorNotice: false,
})
}) })
const version = versionData?.meta const version = versionData?.meta
@@ -132,9 +136,11 @@ export const useClashInfo = () => {
validatePorts(patch) validatePorts(patch)
await patchClashConfig(patch) await mutate(() => patchClashConfig(patch), {
mutateInfo() id: 'patch-clash-info',
revalidateQuery(['getClashConfig']) revalidate: [['getClashInfo'], ['getClashConfig']],
errorNotice: false,
})
}) })
const invalidateClashConfig = () => revalidateQuery(['getClashConfig']) const invalidateClashConfig = () => revalidateQuery(['getClashConfig'])
-15
View File
@@ -1,15 +0,0 @@
import { listen, EventCallback } from '@tauri-apps/api/event'
import { useCallback } from 'react'
export const useListen = () => {
const addListener = useCallback(
async <T>(eventName: string, handler: EventCallback<T>) => {
return await listen(eventName, handler)
},
[],
)
return {
addListener,
}
}
+18 -15
View File
@@ -1,18 +1,12 @@
import { useCallback, useRef } from 'react' import { useCallback, useRef } from 'react'
import { getProfiles, patchProfile, patchProfilesConfig } from '@/services/cmds' import { getProfiles, patchProfile, patchProfilesConfig } from '@/services/cmds'
import { import { mutate } from '@/services/mutate'
fetchCacheData, import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client'
revalidateQuery,
setCacheData,
useQuery,
} from '@/services/query-client'
import { debugLog } from '@/utils/debug' import { debugLog } from '@/utils/debug'
const profilesQueryKey = ['getProfiles'] as const const profilesQueryKey = ['getProfiles'] as const
export const revalidateProfiles = () => revalidateQuery(profilesQueryKey)
export const fetchProfilesIntoCache = () => export const fetchProfilesIntoCache = () =>
fetchCacheData(profilesQueryKey, getProfiles) fetchCacheData(profilesQueryKey, getProfiles)
@@ -49,16 +43,25 @@ export const useProfiles = () => {
const patchProfiles = useCallback( const patchProfiles = useCallback(
async (value: Partial<IProfilesConfig>) => { async (value: Partial<IProfilesConfig>) => {
try { try {
const outcome = await patchProfilesConfig(value) const result = await mutate(() => patchProfilesConfig(value), {
id: 'patch-profiles-config',
onFulfilled: (outcome) => {
if (outcome.status === 'valid') {
void setCacheData<IProfilesConfig>(profilesQueryKey, (current) =>
current ? { ...current, ...value } : current,
)
}
},
})
if (outcome.status === 'valid') { if (!result.ok) {
await setCacheData<IProfilesConfig>(profilesQueryKey, (current) => // Backend Busy keeps local state untouched, as before.
current ? { ...current, ...value } : current, return result.value ?? { status: 'busy' }
) }
} else if (outcome.status !== 'busy') { const outcome = result.value
if (outcome.status !== 'valid' && outcome.status !== 'busy') {
await mutateProfiles() await mutateProfiles()
} }
return outcome return outcome
} catch (error) { } catch (error) {
await mutateProfiles() await mutateProfiles()
+13 -3
View File
@@ -12,6 +12,7 @@ import {
} from '@/hooks/use-record-selection' } from '@/hooks/use-record-selection'
import { useVerge } from '@/hooks/use-verge' import { useVerge } from '@/hooks/use-verge'
import { syncTrayProxySelection } from '@/services/cmds' import { syncTrayProxySelection } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { debugLog } from '@/utils/debug' import { debugLog } from '@/utils/debug'
// 缓存连接清理 // 缓存连接清理
@@ -58,7 +59,10 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
// 切换节点 // 切换节点
const syncTraySelection = useCallback(() => { const syncTraySelection = useCallback(() => {
syncTrayProxySelection().catch((error) => { mutate(() => syncTrayProxySelection(), {
id: 'sync-tray-selection',
errorNotice: false,
}).catch((error) => {
console.error('[ProxySelection] 托盘状态同步失败:', error) console.error('[ProxySelection] 托盘状态同步失败:', error)
}) })
}, []) }, [])
@@ -75,9 +79,15 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
try { try {
if (isFixedProxy) { if (isFixedProxy) {
await unfixedProxy(groupName) await mutate(() => unfixedProxy(groupName), {
id: 'select-proxy-node',
errorNotice: false,
})
} else { } else {
await selectNodeForGroup(groupName, proxyName) await mutate(() => selectNodeForGroup(groupName, proxyName), {
id: 'select-proxy-node',
errorNotice: false,
})
} }
onSuccess?.() onSuccess?.()
syncTraySelection() syncTraySelection()

Some files were not shown because too many files have changed in this diff Show More