Compare commits

..
Author SHA1 Message Date
Tunglies 6f2f8404db test(task): start only keys the queue returned in the queue tests
Two queue tests called `start` on an armed key that `next_expired` had not returned, which the documented contract rules out. They now let the key expire first and take it from the queue.
2026-12-06 16:03:28 +08:00
Tunglies f67916952b docs(task): state the queue contract precisely
The doc comments of apply, start and interval left open what a changed interval does to a running timer, which keys start accepts, and whether a running key still reports its interval. State the behaviour the code kept from the original scheduler.
2026-12-06 16:03:28 +08:00
Tunglies 725c5941d0 test(task): tell the first delay from the interval after a change
The case used a plan whose first delay equalled its interval, so re-arming at the full interval passed as well. In production the first delay is the remaining time and the interval is the full period, so the test now uses different values.
2026-12-06 16:03:28 +08:00
Tunglies 80aad98358 test(config-render): cover the edges mutation testing found untested
The moved rules kept these changes undetected: a string provider DNS field being ignored or an empty one counted, a wider or empty gap after short-id disturbing the quoting, an unchanged scalar beside a numeric short-id rejecting the quoted result, and quoting leaking outside the fake-ip-filter block or at a deeper indentation. Each new test fails under its mutant and passes against the unchanged code.
2026-12-06 16:03:27 +08:00
Tunglies 91e091daec test(task): pin that a changed interval adds no fire while a run is in flight
Mutation testing showed the suite could not tell whether apply arms an extra queue entry for a running key whose interval changed. The test now advances past the new first delay during the run and expects nothing to fire, then exactly one expiry after the run reports back. The idle case also asserts that the reset timer does not fire at once.
2026-12-06 16:03:27 +08:00
Tunglies 41f7ffc558 refactor(config): move DNS and tunnel rules into clash-verge-config-render
override_source, needs_public_dns and sanitize_tunnels_proxy are pure rules over a rendered Mapping; the app keeps the DNS override state, IPC and file access.
2026-12-06 16:03:27 +08:00
Tunglies e2c06e4946 test(task): prove a retired timer is dropped and a changed interval reschedules 2026-12-06 16:03:27 +08:00
Tunglies c8356adfe5 refactor(config): move Mihomo YAML fidelity rules into clash-verge-config-render
Short-id-safe YAML parsing and the export quoting of fake-ip-filter wildcards are Mihomo output rules without app dependencies. They now live beside the other Mihomo YAML rules, and the app calls them from the parse and export entry points. The plain serializer re-export is replaced by serde_yaml_ng::to_string at its five call sites.
2026-12-06 16:03:27 +08:00
Tunglies 46449cf380 refactor(task): move the keyed timer queue into clash-verge-task
The timer scheduler in the app kept its own queue bookkeeping: when a key is due, that a run in flight cannot start a second one, that a key removed mid-run is dropped once it reports back, and that a finished run waits a whole interval. Move that bookkeeping into clash-verge-task as KeyedTimers, so the rules run and are tested without the desktop app. The app keeps the schedule, the logging and the update tasks.
2026-12-06 10:31:20 +08:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> fc6503c88d chore(deps): update dependency pnpm to v12.26.0 (#8844)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-05 14:23:38 +00:00
❤是纱雾酱哟~andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 96e8e7aa4d chore(deps): update dependency knip to v6.51.1 (#8843)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-05 14:23:09 +00:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 61e2c29707 build(deps): bump minimatch (#8837)
Bumps the npm_and_yarn group with 1 update in the / directory: [minimatch](https://github.com/isaacs/minimatch).


Updates `minimatch` from 11.0.9 to 11.0.10
- [Release notes](https://github.com/isaacs/minimatch/releases)
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v11.0.9...v11.0.10)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 11.0.10
  dependency-type: indirect
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-12-05 13:04:14 +00:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
33aa7ebfab chore(deps): update agentic workflows to v1.4.8 (#8836)
Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-12-05 12:55:06 +00:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 3a0c41c81d chore(deps): update rust crate tauri-plugin-wdio-webdriver to v2.0.0-next.1 (#8839)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-05 09:45:17 +00:00
Tunglies 1cf135d952 chore(deps): update tauri plugin 2026-12-05 15:50:48 +08:00
renovate[bot]andrenovate[bot] <29139614+renovate[bot]@users.noreply.github.com> 9c5be9c8a3 chore(deps): update dependency knip to v6.51.0 (#8835)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-05 07:21:50 +00:00
renovate[bot]renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>❤是纱雾酱哟~
b3669671a7 chore(deps): update github/gh-aw-actions action to v1.4.6 (#8831)
Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
2026-12-04 17:55:43 +00:00
Jeferson Araujo 327f1f103c fix(i18n): clarify the subscription website action in Portuguese (#8824) 2026-12-04 08:49:58 +00:00
59 changed files with 2343 additions and 1592 deletions
+1 -1
View File
@@ -5,7 +5,7 @@
"features": {
"ghcr.io/devcontainers/features/node:2": {
"version": "26.14.0",
"pnpmVersion": "12.25.1"
"pnpmVersion": "12.26.0"
},
"ghcr.io/devcontainers/features/rust:1": {
"version": "1.100.1",
+32 -7
View File
@@ -5,10 +5,10 @@
"version": "v9.0.0",
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
},
"github/gh-aw-actions/setup@v1.4.5": {
"github/gh-aw-actions/setup@v1.4.8": {
"repo": "github/gh-aw-actions/setup",
"version": "v1.4.5",
"sha": "a83eaf07e756a15e65f669eb32d00787cf5a2569"
"version": "v1.4.8",
"sha": "77d9990c6365a3aec005be071518ac236abafce5"
}
},
"containers": {
@@ -57,6 +57,11 @@
"digest": "sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.22@sha256:f5829ed92ec390e9c88c9d393556a16f0442c124c0d6b9c713e7544cb0efa5ad"
},
"ghcr.io/github/gh-aw-firewall/agent:0.29.23": {
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.23",
"digest": "sha256:eadd6294db82f613ec5be5a5c281c7ca9860aed389b4ce9cd61a7e635d156709",
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.23@sha256:eadd6294db82f613ec5be5a5c281c7ca9860aed389b4ce9cd61a7e635d156709"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13",
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
@@ -102,6 +107,11 @@
"digest": "sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.22@sha256:02149f4ed8b9c0bae954932745f2d16e8c5bd2b37adec5f788344806cd063dca"
},
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.23": {
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.23",
"digest": "sha256:d108c634a496c11cc62f579b0e05ef47295e91ae97cfeec9ae6b9798dfdc0347",
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.23@sha256:d108c634a496c11cc62f579b0e05ef47295e91ae97cfeec9ae6b9798dfdc0347"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.11",
"digest": "sha256:97782bc0d8ff7f80f19ae2fdc5e1668517aa732a6fa077e64b8d3919238496d2",
@@ -127,6 +137,11 @@
"digest": "sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.22@sha256:7b8ef50c5221824a425fbfabafb50767c5a4e6b0197a0fce6085fd9f7e97b5b7"
},
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.23": {
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.23",
"digest": "sha256:6f2f20fd32a507c687756664bdfc6a4e3fb49d75e6b3c6422c9e6542c35f9d06",
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.23@sha256:6f2f20fd32a507c687756664bdfc6a4e3fb49d75e6b3c6422c9e6542c35f9d06"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.14": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
@@ -147,6 +162,11 @@
"digest": "sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.22@sha256:b4253735af3ab47c17bcdfaf86e91b541581e1338d3d9ead512a12ebd3f146fb"
},
"ghcr.io/github/gh-aw-firewall/router:0.29.23": {
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.23",
"digest": "sha256:a606beb60fca03f05594911f3ada916f7ca4fd0342707c192b94710383dd5b66",
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.23@sha256:a606beb60fca03f05594911f3ada916f7ca4fd0342707c192b94710383dd5b66"
},
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
@@ -192,10 +212,15 @@
"digest": "sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.22@sha256:cf4dd8944eb5b389adcf49f42de0e884f46e07d63afc5824543e7c9ab8ddb882"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.16": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.16",
"digest": "sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.16@sha256:cd50cfae3acce5985985aee3964902c9358dcc809f1b68b8168cfe29b761b059"
"ghcr.io/github/gh-aw-firewall/squid:0.29.23": {
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.23",
"digest": "sha256:b19f240211cbdeee913165252b91078a5dd1118c25292365ef5dea343adcc6f2",
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.23@sha256:b19f240211cbdeee913165252b91078a5dd1118c25292365ef5dea343adcc6f2"
},
"ghcr.io/github/gh-aw-mcpg:v0.5.17": {
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.17",
"digest": "sha256:729e3f7660f5111f89141e4f1797b3a96020cbcd581978482fb072e78e69a343",
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.17@sha256:729e3f7660f5111f89141e4f1797b3a96020cbcd581978482fb072e78e69a343"
},
"ghcr.io/github/gh-aw-node": {
"image": "ghcr.io/github/gh-aw-node",
+8 -8
View File
@@ -265,6 +265,14 @@ jobs:
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: Release ${{ env.TAG_CHANNEL }} Version
run: pnpm release-version autobuild-latest
- name: 'Setup for linux'
run: |-
sudo ls -lR /etc/apt/
@@ -309,14 +317,6 @@ jobs:
gcc-arm-linux-gnueabihf \
g++-arm-linux-gnueabihf
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: Release ${{ env.TAG_CHANNEL }} Version
run: pnpm release-version autobuild-latest
- name: Tauri Build for Linux
run: |
export PKG_CONFIG_ALLOW_CROSS=1
+2 -2
View File
@@ -31,9 +31,9 @@ jobs:
with:
persist-credentials: false
- name: Install gh-aw extension
uses: github/gh-aw-actions/setup-cli@a83eaf07e756a15e65f669eb32d00787cf5a2569 # v1.4.5
uses: github/gh-aw-actions/setup-cli@77d9990c6365a3aec005be071518ac236abafce5 # v1.4.8
with:
version: v1.4.5
version: v1.4.8
- name: Install Rust Stable
uses: dtolnay/rust-toolchain@stable
with:
+8 -8
View File
@@ -107,14 +107,6 @@ jobs:
node-version: '26.14.0'
cache: 'pnpm'
- name: Add Rust Target
if: github.event.inputs[matrix.input] == 'true'
run: |
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
rustup target list --installed
echo "Rust target ${{ matrix.target }} installed."
- name: Pnpm install and check
if: github.event.inputs[matrix.input] == 'true'
run: |
@@ -125,6 +117,14 @@ jobs:
if: github.event.inputs[matrix.input] == 'true'
run: pnpm release-version ${{ env.TAG_NAME }}
- name: Add Rust Target
if: github.event.inputs[matrix.input] == 'true'
run: |
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
rustup target list --installed
echo "Rust target ${{ matrix.target }} installed."
- name: Tauri build
if: github.event.inputs[matrix.input] == 'true'
uses: tauri-apps/tauri-action@v1
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+5 -5
View File
@@ -333,6 +333,11 @@ jobs:
node-version: '26.14.0'
cache: 'pnpm'
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: 'Setup for linux'
run: |-
sudo ls -lR /etc/apt/
@@ -377,11 +382,6 @@ jobs:
gcc-arm-linux-gnueabihf \
g++-arm-linux-gnueabihf
- name: Pnpm install and check
run: |
pnpm i
pnpm run prebuild ${{ matrix.target }}
- name: Build for Linux
run: |
export PKG_CONFIG_ALLOW_CROSS=1
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -1,3 +1,3 @@
nodejs 26.14.0
pnpm 12.25.1
pnpm 12.26.0
rust 1.100.1
Generated
+25 -8
View File
@@ -1152,7 +1152,6 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml_ng",
"sha2 0.11.2",
"socket2",
"specta",
"specta-typescript",
@@ -1207,6 +1206,7 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml_ng",
"sha2 0.11.2",
"tokio",
"tristr",
]
@@ -1338,12 +1338,13 @@ dependencies = [
"futures",
"parking_lot 0.13.0",
"tokio",
"tokio-util",
]
[[package]]
name = "clash_verge_service_ipc"
version = "2.8.3"
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?rev=4129b4c08fbb003b11d0d9103236753d6aee717f#4129b4c08fbb003b11d0d9103236753d6aee717f"
version = "2.8.2"
source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?branch=main#3e06ff153e9cb19ae20e0a61f861b371d3f7b2aa"
dependencies = [
"anyhow",
"kode-bridge",
@@ -2177,7 +2178,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users 0.5.2",
"windows-sys 0.61.2",
"windows-sys 0.101.0",
]
[[package]]
@@ -3995,9 +3996,9 @@ dependencies = [
[[package]]
name = "kode-bridge"
version = "0.6.1"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e125a6b7f2e7ce5d560ce9517083e27549345a6492ca68194cd96b42e3b27acb"
checksum = "b17456ae84ba9c0da0f189bf00d13019805b89563ba846cd15ccd8c4bd6a2713"
dependencies = [
"bytes",
"futures",
@@ -4005,6 +4006,7 @@ dependencies = [
"httparse",
"libc",
"parking_lot 0.13.0",
"path-tree",
"pin-project-lite",
"rand 0.10.2",
"serde",
@@ -5156,6 +5158,15 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"
[[package]]
name = "path-tree"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a97453bc21a968f722df730bfe11bd08745cb50d1300b0df2bda131dece136"
dependencies = [
"smallvec",
]
[[package]]
name = "pathsearch"
version = "0.2.0"
@@ -7730,8 +7741,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-wdio-webdriver"
version = "2.0.0-next.0"
source = "git+https://github.com/Tunglies/desktop-mobile.git?rev=2745082c7f487c5e0c9568000b5a7ac24234d6e4#2745082c7f487c5e0c9568000b5a7ac24234d6e4"
version = "2.0.0-next.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c8f77d878b62d0f908dfa22698a149b0b1b2f9ff91d325a2d2bc9b961be9f51"
dependencies = [
"async-trait",
"axum",
@@ -10518,3 +10530,8 @@ dependencies = [
name = "muda"
version = "0.20.0"
source = "git+https://github.com/wonfen/muda.git?rev=547de49352791653fbdfa785f20f3c7ece8468e2#547de49352791653fbdfa785f20f3c7ece8468e2"
[[patch.unused]]
name = "tauri-plugin-wdio-webdriver"
version = "2.0.0-next.0"
source = "git+https://github.com/Tunglies/desktop-mobile.git?rev=2745082c7f487c5e0c9568000b5a7ac24234d6e4#2745082c7f487c5e0c9568000b5a7ac24234d6e4"
+2 -1
View File
@@ -74,7 +74,7 @@ clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" }
clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" }
clash-verge-profile = { path = "crates/clash-verge-profile" }
clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" }
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", rev = "4129b4c08fbb003b11d0d9103236753d6aee717f", version = "2.8.3", default-features = false }
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", default-features = false }
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
tracing = "0.1.44"
@@ -99,6 +99,7 @@ tokio = { version = "1.54.1", features = [
] }
flexi_logger = "0.32.0"
log = "0.4.35"
tokio-util = { version = "0.7.20", features = ["time"] }
reqwest = { version = "0.13.5", features = [
"json",
"cookies",
-2
View File
@@ -23,7 +23,6 @@
GitHub, so they never reach users. -->
## v2.6.0
- 升级至 2.6.x 后,可在应用内重装或卸载旧版服务;使用服务模式需安装随附的服务
- **Mihomo 内核升级至 v1.19.34**
<details>
@@ -50,7 +49,6 @@
**🖥️ Windows**
- 修复 Windows 服务启动失败后自动切换内核,现显示原因并等待用户选择
- 修复 Windows 普通用户因权限不足无法开启「开机自启」
**🍎 macOS**
@@ -9,6 +9,7 @@ log = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
sha2 = { workspace = true }
tristr = { workspace = true }
[dev-dependencies]
+132
View File
@@ -0,0 +1,132 @@
use serde_yaml_ng::{Mapping, Value};
use sha2::{Digest as _, Sha256};
use tristr::alias::String;
const PROVIDER_DNS_FIELDS: [&str; 3] = [
"proxy-server-nameserver",
"proxy-server-nameserver-policy",
"nameserver-policy",
];
pub fn override_source(profile_uid: &str, config: &Mapping) -> Result<Option<String>, serde_json::Error> {
let Some(dns) = config.get("dns").and_then(Value::as_mapping) else {
return Ok(None);
};
let fields: Mapping = PROVIDER_DNS_FIELDS
.iter()
.filter_map(|key| {
let value = dns.get(*key)?;
let nonempty = match value {
Value::Sequence(values) => !values.is_empty(),
Value::Mapping(values) => !values.is_empty(),
Value::String(value) => !value.trim().is_empty(),
_ => false,
};
nonempty.then(|| (Value::from(*key), value.clone()))
})
.collect();
if fields.is_empty() {
return Ok(None);
}
let mut canonical = serde_json::to_value(fields)?;
canonical.sort_all_objects();
let mut digest = Sha256::new();
digest.update(profile_uid.as_bytes());
digest.update([0]);
digest.update(serde_json::to_vec(&canonical)?);
Ok(Some(hex_encode(&digest.finalize()).into()))
}
fn hex_encode(bytes: &[u8]) -> std::string::String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = std::string::String::with_capacity(bytes.len() * 2);
for &byte in bytes {
out.push(HEX[usize::from(byte >> 4)] as char);
out.push(HEX[usize::from(byte & 0x0f)] as char);
}
out
}
// Without the placeholder, a LAN resolver is reached outside TUN and fake-ip is bypassed.
pub fn needs_public_dns(config: &Mapping) -> bool {
let section = |name: &str| config.get(name).and_then(Value::as_mapping);
let enabled = |name: &str| {
section(name)
.and_then(|map| map.get("enable"))
.and_then(Value::as_bool)
.unwrap_or(false)
};
enabled("tun")
&& enabled("dns")
&& section("dns")
.and_then(|dns| dns.get("enhanced-mode"))
.and_then(Value::as_str)
== Some("fake-ip")
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::{needs_public_dns, override_source};
use serde_yaml_ng::Mapping;
fn mapping(yaml: &str) -> Mapping {
serde_yaml_ng::from_str(yaml).expect("valid fixture")
}
#[test]
fn override_source_detects_each_original_field_but_not_empty_placeholders() -> Result<(), serde_json::Error> {
for field in [
"proxy-server-nameserver: [https://doh.pub/dns-query]",
"proxy-server-nameserver-policy: {'www.yournode.com': '114.114.114.114'}",
"nameserver-policy: {'+.quandao.com': ['https://doh.dohcore.com:2096/dns-query/#skip-cert-verify=true']}",
] {
assert!(override_source("profile", &mapping(&format!("dns: {{{field}}}")))?.is_some());
assert!(override_source("profile", &mapping(field))?.is_none());
}
for yaml in [
"{}",
"dns: {nameserver: [1.1.1.1]}",
"dns: {proxy-server-nameserver: [], proxy-server-nameserver-policy: null, nameserver-policy: {}}",
] {
assert!(override_source("profile", &mapping(yaml))?.is_none());
}
Ok(())
}
#[test]
fn override_source_ignores_order_and_key_order_but_not_the_profile() -> Result<(), serde_json::Error> {
let a = mapping("dns:\n nameserver-policy:\n a.example: 1.1.1.1\n b.example: [8.8.8.8]\n");
let b = mapping("dns:\n nameserver-policy:\n b.example: [8.8.8.8]\n a.example: 1.1.1.1\n port: 7890\n");
assert_eq!(override_source("one", &a)?, override_source("one", &b)?);
assert_ne!(override_source("one", &a)?, override_source("two", &a)?);
assert!(override_source("one", &a)?.is_some());
Ok(())
}
#[test]
fn fake_ip_under_tun_with_dns_needs_public_dns() {
assert!(needs_public_dns(&mapping(
"tun: {enable: true}\ndns: {enable: true, enhanced-mode: fake-ip}"
)));
assert!(!needs_public_dns(&mapping(
"tun: {enable: true}\ndns: {enable: true, enhanced-mode: redir-host}"
)));
assert!(!needs_public_dns(&mapping(
"dns: {enable: true, enhanced-mode: fake-ip}"
)));
assert!(!needs_public_dns(&mapping(
"tun: {enable: true}\ndns: {enable: false, enhanced-mode: fake-ip}"
)));
}
#[test]
fn override_source_accepts_a_string_field_only_when_it_has_content() -> Result<(), serde_json::Error> {
let config = mapping("dns: {proxy-server-nameserver: ' 1.1.1.1 '}");
assert!(override_source("profile", &config)?.is_some());
let config = mapping("dns: {nameserver-policy: ' '}");
assert!(override_source("profile", &config)?.is_none());
Ok(())
}
}
@@ -1,10 +1,16 @@
mod dns;
mod field;
mod merge;
mod script;
mod seq;
mod tun;
mod tunnels;
mod yaml;
pub use dns::{needs_public_dns, override_source};
pub use seq::SeqMap;
pub use tunnels::sanitize_tunnels_proxy;
pub use yaml::{parse_short_id_safe, serialize_for_export};
use self::{
field::{lowercase_config_keys, use_lowercase, use_sort},
@@ -0,0 +1,120 @@
use serde_yaml_ng::{Mapping, Value};
use std::collections::HashSet;
use tristr::alias::String;
pub fn sanitize_tunnels_proxy(config: &mut Mapping) {
if !config
.get("tunnels")
.and_then(|v| v.as_sequence())
.is_some_and(|t| tunnels_need_validation(t))
{
return;
}
let mut valid: HashSet<String> = HashSet::with_capacity(64);
collect_names(config, "proxies", &mut valid);
collect_names(config, "proxy-groups", &mut valid);
valid.insert("DIRECT".into());
valid.insert("REJECT".into());
let Some(tunnels) = config.get_mut("tunnels").and_then(|v| v.as_sequence_mut()) else {
return;
};
for item in tunnels {
let Some(tunnel) = item.as_mapping_mut() else { continue };
let Some(proxy_name) = tunnel.get("proxy").and_then(|v| v.as_str()) else {
continue;
};
if proxy_name == "DIRECT" || proxy_name == "REJECT" {
continue;
}
if !valid.contains(proxy_name) {
tunnel.remove("proxy");
}
}
}
fn tunnels_need_validation(tunnels: &[Value]) -> bool {
tunnels.iter().any(|item| {
item.as_mapping()
.and_then(|t| t.get("proxy"))
.and_then(|p| p.as_str())
.is_some_and(|name| name != "DIRECT" && name != "REJECT")
})
}
fn collect_names(config: &Mapping, list_key: &str, out: &mut HashSet<String>) {
let Some(Value::Sequence(seq)) = config.get(list_key) else {
return;
};
for item in seq {
let Value::Mapping(map) = item else {
continue;
};
if let Some(Value::String(n)) = map.get("name")
&& !n.is_empty()
{
out.insert(n.into());
}
}
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::sanitize_tunnels_proxy;
use serde_yaml_ng::Mapping;
fn mapping(yaml: &str) -> Mapping {
serde_yaml_ng::from_str(yaml).expect("valid fixture")
}
#[test]
fn tunnels_reference_only_existing_proxies_or_builtin_names() {
let mut config = mapping(
"proxies: [{name: a}]\nproxy-groups: [{name: b}]\ntunnels: [{proxy: a}, {proxy: b}, {proxy: DIRECT}, {proxy: REJECT}, {proxy: missing}]",
);
sanitize_tunnels_proxy(&mut config);
let tunnels = config["tunnels"].as_sequence().expect("sequence");
assert_eq!(tunnels[0]["proxy"], "a");
assert_eq!(tunnels[1]["proxy"], "b");
assert_eq!(tunnels[3]["proxy"], "REJECT");
assert!(tunnels[4].get("proxy").is_none());
}
#[test]
fn non_string_proxy_fields_are_left_alone() {
let mut config = mapping("proxies: [{name: a}]\ntunnels: [{proxy: 1}, {proxy: true}, {proxy: [a]}]");
sanitize_tunnels_proxy(&mut config);
assert_eq!(config["tunnels"][0]["proxy"], 1);
assert_eq!(config["tunnels"][1]["proxy"], true);
assert!(config["tunnels"][2]["proxy"].is_sequence());
}
#[test]
fn tunnels_without_named_proxies_are_left_alone() {
let mut config = mapping("proxies: [{name: a}]\ntunnels: [{proxy: DIRECT}, {network: [tcp]}]");
sanitize_tunnels_proxy(&mut config);
assert_eq!(
config["tunnels"],
mapping("tunnels: [{proxy: DIRECT}, {network: [tcp]}]")["tunnels"]
);
}
#[test]
fn names_come_only_from_mapping_items_with_non_empty_string_name() {
let mut config = mapping(
"proxies: [{name: ''}, 7, {name: a}]\nproxy-groups: not-a-list\ntunnels: [7, {proxy: a}, {proxy: ''}]",
);
sanitize_tunnels_proxy(&mut config);
assert_eq!(config["tunnels"][0], 7);
assert_eq!(config["tunnels"][1]["proxy"], "a");
assert!(config["tunnels"][2].get("proxy").is_none());
}
}
@@ -0,0 +1,262 @@
use clash_verge_logging::{Type, logging};
use serde::Serialize;
use serde_yaml_ng::Value;
use std::path::Path;
/// A float like `1234e123` loses its hex text, so retry with short-ids quoted and keep that only if nothing else changed.
pub fn parse_short_id_safe(yaml: &str, path: &Path) -> serde_yaml_ng::Result<Value> {
let value = serde_yaml_ng::from_str::<Value>(yaml)?;
if !has_numeric_short_id(&value) {
return Ok(value);
}
match serde_yaml_ng::from_str::<Value>(&quote_short_ids(yaml)) {
Ok(quoted) if same_except_short_id(&value, &quoted) => Ok(quoted),
_ => {
logging!(warn, Type::Config, "kept numeric short-id in {}", path.display());
Ok(value)
}
}
}
fn quote_short_ids(yaml: &str) -> String {
let mut quoted = String::with_capacity(yaml.len());
let mut rest = yaml;
while let Some((head, tail)) = rest.split_once("short-id:") {
let (gap, value) = tail.split_at(tail.len() - tail.trim_start_matches([' ', '\t']).len());
let (id, after) = value.split_at(value.bytes().take_while(u8::is_ascii_hexdigit).count());
quoted.push_str(head);
quoted.push_str("short-id:");
quoted.push_str(gap);
if !id.is_empty() && (after.is_empty() || after.starts_with([' ', '\t', '\r', '\n', ',', '}'])) {
quoted.push('"');
quoted.push_str(id);
quoted.push('"');
} else {
quoted.push_str(id);
}
rest = after;
}
quoted.push_str(rest);
quoted
}
fn has_numeric_short_id(value: &Value) -> bool {
match value {
Value::Mapping(map) => map
.iter()
.any(|(key, value)| (is_short_id(key) && matches!(value, Value::Number(_))) || has_numeric_short_id(value)),
Value::Sequence(seq) => seq.iter().any(has_numeric_short_id),
_ => false,
}
}
fn same_except_short_id(old: &Value, new: &Value) -> bool {
match (old, new) {
(Value::Mapping(old), Value::Mapping(new)) => {
old.len() == new.len()
&& old.iter().zip(new).all(|((key, old), (new_key, new))| {
key == new_key
&& (same_except_short_id(old, new)
|| (is_short_id(key) && matches!((old, new), (Value::Number(_), Value::String(_)))))
})
}
(Value::Sequence(old), Value::Sequence(new)) => {
old.len() == new.len() && old.iter().zip(new).all(|(old, new)| same_except_short_id(old, new))
}
_ => old == new,
}
}
fn is_short_id(key: &Value) -> bool {
key.as_str() == Some("short-id")
}
pub fn serialize_for_export<T: Serialize>(data: &T) -> serde_yaml_ng::Result<String> {
Ok(quote_fake_ip_filter_wildcards(&serde_yaml_ng::to_string(data)?))
}
fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
let mut result = String::with_capacity(yaml.len());
let mut in_fake_ip_filter = false;
let mut fake_ip_filter_indent = 0;
for line in yaml.lines() {
let indent = line.len() - line.trim_start_matches(' ').len();
let trimmed = &line[indent..];
if in_fake_ip_filter && indent <= fake_ip_filter_indent && !trimmed.starts_with("- ") {
in_fake_ip_filter = false;
}
if !in_fake_ip_filter && trimmed == "fake-ip-filter:" {
in_fake_ip_filter = true;
fake_ip_filter_indent = indent;
}
if in_fake_ip_filter
&& indent >= fake_ip_filter_indent
&& let Some(item) = trimmed.strip_prefix("- ")
&& needs_quotes(item)
{
result.push_str(&line[..indent + 2]);
push_quoted(&mut result, item);
} else {
result.push_str(line);
}
result.push('\n');
}
result
}
fn needs_quotes(item: &str) -> bool {
!item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.']))
}
fn push_quoted(output: &mut String, item: &str) {
output.push('\'');
for (index, part) in item.split('\'').enumerate() {
if index != 0 {
output.push_str("''");
}
output.push_str(part);
}
output.push('\'');
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::{parse_short_id_safe, serialize_for_export};
use serde_yaml_ng::Value;
use std::path::Path;
fn roundtrip(input: &str) -> Value {
let value: Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
let output = serialize_for_export(&value).expect("yaml should serialize");
let reparsed: Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse");
assert_eq!(reparsed, value);
reparsed
}
#[test]
fn quotes_fake_ip_filter_wildcards_without_changing_values() {
let input = r#"
dns:
fake-ip-filter:
- "*.lan"
- "+.market.xiaomi.com"
- ".example.com"
- "time.*.com"
- "plain.example.com"
"#;
roundtrip(input);
let value: Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
let output = serialize_for_export(&value).expect("yaml should serialize");
assert!(output.contains("- '*.lan'"));
assert!(output.contains("- '+.market.xiaomi.com'"));
assert!(output.contains("- '.example.com'"));
assert!(output.contains("- 'time.*.com'"));
assert!(output.contains("- plain.example.com"));
}
#[test]
fn nested_multiline_strings_roundtrip() {
roundtrip(
r"
items:
- name: demo
desc: |
line1
line2
",
);
}
#[test]
fn short_id_quoting_changing_other_values_is_dropped() {
let profile = "\
proxies:
- name: a
reality-opts:
short-id: 1234e123
note: |
short-id: 1234e123
";
let today = serde_yaml_ng::from_str::<Value>(profile).expect("profile should parse");
let value = parse_short_id_safe(profile, Path::new("profile.yaml")).expect("profile should parse");
assert_eq!(value, today);
}
#[test]
fn numeric_short_ids_parse_as_text() {
let value =
parse_short_id_safe("tunnels: [{short-id: 1234e123}, {short-id: 0e5}]", Path::new("p.yaml")).expect("yaml");
let tunnels = value["tunnels"].as_sequence().expect("sequence");
assert_eq!(tunnels[0]["short-id"], Value::String("1234e123".into()));
assert_eq!(tunnels[1]["short-id"], Value::String("0e5".into()));
}
#[test]
fn already_quoted_short_ids_are_left_alone() {
let yaml = "tunnels: [{short-id: \"1234e123\"}]";
assert_eq!(
parse_short_id_safe(yaml, Path::new("p.yaml")).expect("yaml"),
serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")
);
}
#[test]
fn crlf_yaml_still_gets_quoted_wildcards_and_roundtrips() {
let yaml =
"dns:\r\n fake-ip-filter:\r\n - '*.lan'\r\n - +.market.xiaomi.com\r\n - plain.example.com\r\n";
let out = serialize_for_export(&serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")).expect("yaml");
assert_eq!(roundtrip(&out), roundtrip(yaml));
assert!(out.contains("'+.market.xiaomi.com'"));
}
#[test]
fn unchanged_scalars_beside_a_numeric_short_id_keep_the_quoted_result() {
let value = parse_short_id_safe(
"proxies:\n - name: a\n reality-opts:\n short-id: 1234e123\n",
Path::new("profile.yaml"),
)
.expect("profile should parse");
let proxy = &value["proxies"].as_sequence().expect("sequence")[0];
assert_eq!(proxy["name"], Value::String("a".into()));
assert_eq!(proxy["reality-opts"]["short-id"], Value::String("1234e123".into()));
}
#[test]
fn wider_whitespace_and_empty_short_ids_do_not_disturb_the_quoting() {
let value = parse_short_id_safe(
"tunnels:\n - short-id: 1234e123\n - short-id:\t\n - short-id: 0e5\n",
Path::new("p.yaml"),
)
.expect("yaml");
let tunnels = value["tunnels"].as_sequence().expect("sequence");
assert_eq!(tunnels[0]["short-id"], Value::String("1234e123".into()));
assert_eq!(tunnels[1]["short-id"], Value::Null);
assert_eq!(tunnels[2]["short-id"], Value::String("0e5".into()));
}
#[test]
fn wildcards_outside_fake_ip_filter_are_left_alone() {
let yaml = "\ndns:\n fake-ip-filter:\n - .example.com\n fake-ip-filter-mode: blacklist\nsniffer:\n skip-domain:\n - +.push.apple.com\n";
let out = serialize_for_export(&serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")).expect("yaml");
assert_eq!(roundtrip(&out), roundtrip(yaml));
assert!(out.contains(" - '.example.com'\n"), "{out}");
assert!(out.contains(" - +.push.apple.com\n"), "{out}");
}
#[test]
fn quoting_follows_the_block_indentation() {
let yaml = "\nwrap:\n dns:\n fake-ip-filter:\n - +.market.xiaomi.com\n";
let out = serialize_for_export(&serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")).expect("yaml");
assert!(out.contains(" - '+.market.xiaomi.com'\n"), "{out}");
}
}
+1
View File
@@ -8,6 +8,7 @@ publish = false
futures = { workspace = true }
parking_lot = { workspace = true }
tokio = { workspace = true }
tokio-util = { workspace = true }
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
+1
View File
@@ -3,4 +3,5 @@
pub mod countdown;
pub mod retry;
pub mod scheduled_task;
pub mod timers;
pub mod watch_task;
+179
View File
@@ -0,0 +1,179 @@
//! Keyed timers whose runs never overlap per key.
use futures::StreamExt as _;
use std::{borrow::Borrow, collections::HashMap, hash::Hash, time::Duration};
use tokio_util::time::{DelayQueue, delay_queue::Key};
/// When a timer fires.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimerPlan {
/// Delay until the first fire, or until the next fire after the interval changed.
pub first_delay: Duration,
/// Delay from one finished run to the next fire.
pub interval: Duration,
}
/// What applying a schedule changed, removals first.
#[derive(Debug, PartialEq, Eq)]
pub enum TimerChange<K> {
/// Removed while its run was in flight; dropped once the run reports back.
Retired(K),
Removed(K),
Added(K),
Updated(K),
}
struct TaskState {
key: Option<Key>,
interval: Duration,
running: bool,
/// Disabled mid-update. Entry outlives removal so re-enabling reuses the `running` guard
/// instead of building a fresh state that would fire a second update at zero delay.
retired: bool,
}
/// One timer per key. A key whose run is in flight does not fire again until it reports back.
pub struct KeyedTimers<K> {
queue: DelayQueue<K>,
tasks: HashMap<K, TaskState>,
}
impl<K: Eq + Hash + Clone> Default for KeyedTimers<K> {
fn default() -> Self {
Self::new()
}
}
impl<K: Eq + Hash + Clone> KeyedTimers<K> {
pub fn new() -> Self {
Self {
queue: DelayQueue::new(),
tasks: HashMap::new(),
}
}
/// Forgets every timer; a run still in flight reports back to nothing.
pub fn clear(&mut self) {
self.queue = DelayQueue::new();
self.tasks.clear();
}
/// Replaces the schedule. Timers that stay keep their next fire unless their interval
/// changed: an idle timer then restarts from the new plan's `first_delay`, while one whose
/// run is in flight is re-armed with the new interval by `finish`.
pub fn apply(&mut self, schedule: HashMap<K, TimerPlan>) -> Vec<TimerChange<K>> {
let Self { queue, tasks } = self;
let mut changes = Vec::new();
tasks.retain(|key, state| {
if schedule.contains_key(key) {
return true;
}
if let Some(entry) = state.key.take() {
queue.remove(&entry);
}
if state.running {
state.retired = true;
changes.push(TimerChange::Retired(key.clone()));
return true;
}
changes.push(TimerChange::Removed(key.clone()));
false
});
for (key, plan) in schedule {
match tasks.get_mut(&key) {
None => {
let entry = queue.insert(key.clone(), plan.first_delay);
tasks.insert(
key.clone(),
TaskState {
key: Some(entry),
interval: plan.interval,
running: false,
retired: false,
},
);
changes.push(TimerChange::Added(key));
}
Some(state) => {
// Re-enabled before retirement took effect; finish re-arms it.
state.retired = false;
if state.interval == plan.interval {
continue;
}
state.interval = plan.interval;
if let Some(entry) = state.key.as_ref() {
queue.reset(entry, plan.first_delay);
} else if !state.running {
state.key = Some(queue.insert(key.clone(), plan.first_delay));
}
changes.push(TimerChange::Updated(key));
}
}
}
changes
}
/// Resolves with the next due key, or `None` once the queue is empty.
pub async fn next_expired(&mut self) -> Option<K> {
self.queue.next().await.map(|expired| expired.into_inner())
}
/// Marks the key running; `false` when the key is unknown or a run is already in flight.
/// Only a key that `next_expired` returned may be started: starting any other key forgets
/// its queue handle and leaves the entry armed.
pub fn start(&mut self, key: &K) -> bool {
let Some(state) = self.tasks.get_mut(key) else {
return false;
};
state.key = None;
if state.running {
return false;
}
state.running = true;
true
}
/// Reports that the run finished and re-arms the timer. Returns `true` when the timer was
/// retired meanwhile and is now dropped.
pub fn finish(&mut self, key: &K) -> bool {
let Some(state) = self.tasks.get_mut(key) else {
return false;
};
state.running = false;
if state.retired {
self.tasks.remove(key);
return true;
}
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
// counting from it would retry at zero delay and spin.
state.key = Some(self.queue.insert(key.clone(), state.interval));
false
}
/// The interval of a timer that is not retired, running or not; `None` for an unknown or
/// retired key. Takes any borrowed form of the key, so a `&str` lookup needs no owned key.
pub fn interval<Q>(&self, key: &Q) -> Option<Duration>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.tasks
.get(key)
.filter(|state| !state.retired)
.map(|state| state.interval)
}
}
+225
View File
@@ -0,0 +1,225 @@
use clash_verge_task::timers::{KeyedTimers, TimerChange, TimerPlan};
use std::{collections::HashMap, task::Poll, time::Duration};
const MINUTE: Duration = Duration::from_secs(60);
const fn plan(first_delay: Duration, interval: Duration) -> TimerPlan {
TimerPlan { first_delay, interval }
}
/// Polled, not awaited: a not-yet-due entry would park the test on the paused clock.
async fn take_expired(timers: &mut KeyedTimers<String>) -> Option<String> {
match futures::poll!(Box::pin(timers.next_expired())) {
Poll::Ready(Some(key)) => Some(key),
_ => None,
}
}
/// Empty queue reports `Ready(None)`, not `Pending`, so both count as "nothing due".
async fn nothing_due(timers: &mut KeyedTimers<String>) -> bool {
matches!(
futures::poll!(Box::pin(timers.next_expired())),
Poll::Pending | Poll::Ready(None)
)
}
#[tokio::test(start_paused = true)]
async fn queue_fires_at_the_remaining_time_then_waits_a_whole_interval() {
let mut timers = KeyedTimers::new();
// 1439min into a 1440min interval: due in a minute, not a day.
timers.apply(HashMap::from([("remote".to_owned(), plan(MINUTE, 1440 * MINUTE))]));
tokio::time::advance(Duration::from_secs(61)).await;
assert_eq!(
take_expired(&mut timers).await.as_deref(),
Some("remote"),
"the raised interval must fire one minute in, not a full day in"
);
// After it reports back, the next one is a whole interval away.
assert!(timers.start(&"remote".to_owned()));
assert!(!timers.finish(&"remote".to_owned()));
tokio::time::advance(Duration::from_secs(1439 * 60)).await;
assert!(
nothing_due(&mut timers).await,
"a finished task waits the whole interval, not the remainder of the old one"
);
tokio::time::advance(Duration::from_secs(120)).await;
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("remote"));
}
#[tokio::test(start_paused = true)]
async fn disabling_a_profile_mid_update_cannot_start_a_second_one() {
let mut timers = KeyedTimers::new();
// Overdue: every re-insert would land at zero delay.
let overdue = || plan(Duration::ZERO, 60 * MINUTE);
timers.apply(HashMap::from([("local".to_owned(), overdue())]));
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("local"));
assert!(timers.start(&"local".to_owned()));
// Toggled off then on while the run is still in flight.
assert_eq!(
timers.apply(HashMap::new()),
vec![TimerChange::Retired("local".to_owned())]
);
assert!(
timers
.apply(HashMap::from([("local".to_owned(), overdue())]))
.is_empty(),
"the entry must survive the toggle so the in-flight run is still accounted for"
);
assert!(
!timers.start(&"local".to_owned()),
"a second run while the first is in flight is refused"
);
assert!(
nothing_due(&mut timers).await,
"re-enabling must not queue a second run alongside the one already going"
);
// Original run reports back, re-arms exactly once.
assert!(!timers.finish(&"local".to_owned()));
tokio::time::advance(Duration::from_secs(3601)).await;
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("local"));
assert!(nothing_due(&mut timers).await, "exactly one key, no orphan");
}
#[tokio::test(start_paused = true)]
async fn a_profile_disabled_mid_update_is_dropped_when_it_reports_back() {
let mut timers = KeyedTimers::new();
timers.apply(HashMap::from([("local".to_owned(), plan(Duration::ZERO, 60 * MINUTE))]));
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("local"));
assert!(timers.start(&"local".to_owned()));
assert_eq!(
timers.apply(HashMap::new()),
vec![TimerChange::Retired("local".to_owned())]
);
assert_eq!(timers.interval("local"), None, "a retired timer reports no deadline");
assert!(
timers.finish(&"local".to_owned()),
"a task retired mid-update must not outlive the update"
);
assert_eq!(timers.interval(&"local".to_owned()), None);
tokio::time::advance(Duration::from_secs(7200)).await;
assert!(nothing_due(&mut timers).await, "and must never be scheduled again");
// Re-enabling starts from scratch; a leftover entry would report no change.
assert_eq!(
timers.apply(HashMap::from([("local".to_owned(), plan(Duration::ZERO, 60 * MINUTE))])),
vec![TimerChange::Added("local".to_owned())]
);
}
#[tokio::test(start_paused = true)]
async fn an_idle_timer_with_a_changed_interval_fires_after_the_new_first_delay() {
let mut timers = KeyedTimers::new();
timers.apply(HashMap::from([("a".to_owned(), plan(60 * MINUTE, 60 * MINUTE))]));
assert_eq!(
timers.apply(HashMap::from([("a".to_owned(), plan(MINUTE, 90 * MINUTE))])),
vec![TimerChange::Updated("a".to_owned())]
);
assert!(nothing_due(&mut timers).await, "a changed timer does not fire at once");
tokio::time::advance(MINUTE).await;
assert_eq!(
take_expired(&mut timers).await.as_deref(),
Some("a"),
"the old fire time an hour out must not survive the change"
);
assert!(nothing_due(&mut timers).await);
}
#[tokio::test(start_paused = true)]
async fn apply_reports_removals_first_and_reenable_changes_nothing() {
let mut timers = KeyedTimers::new();
timers.apply(HashMap::from([
("a".to_owned(), plan(MINUTE, MINUTE)),
("b".to_owned(), plan(MINUTE, 2 * MINUTE)),
("c".to_owned(), plan(10 * MINUTE, 3 * MINUTE)),
]));
let mut tail = timers.apply(HashMap::from([
("a".to_owned(), plan(2 * MINUTE, 2 * MINUTE)),
("c".to_owned(), plan(10 * MINUTE, 3 * MINUTE)),
("d".to_owned(), plan(4 * MINUTE, MINUTE)),
]));
assert_eq!(tail.remove(0), TimerChange::Removed("b".to_owned()));
assert_eq!(tail.len(), 2); // HashMap order decides which of these comes first
assert!(tail.contains(&TimerChange::Added("d".to_owned())));
assert!(tail.contains(&TimerChange::Updated("a".to_owned())));
tokio::time::advance(2 * MINUTE).await;
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
assert!(timers.start(&"a".to_owned()));
let retired = timers.apply(HashMap::from([("c".to_owned(), plan(10 * MINUTE, 3 * MINUTE))]));
assert_eq!(retired.len(), 2, "the running key is retired and the idle one removed");
assert!(retired.contains(&TimerChange::Retired("a".to_owned())));
assert!(retired.contains(&TimerChange::Removed("d".to_owned())));
assert!(
timers
.apply(HashMap::from([
("a".to_owned(), plan(2 * MINUTE, 2 * MINUTE)),
("c".to_owned(), plan(10 * MINUTE, 3 * MINUTE)),
]))
.is_empty()
);
assert!(!timers.finish(&"a".to_owned()));
assert_eq!(timers.interval(&"a".to_owned()), Some(2 * MINUTE));
}
#[tokio::test(start_paused = true)]
async fn interval_queries_answer_before_initialization() {
let mut timers = KeyedTimers::new();
timers.apply(HashMap::from([("a".to_owned(), plan(MINUTE, MINUTE))]));
assert_eq!(timers.interval(&"a".to_owned()), Some(MINUTE));
assert_eq!(timers.interval("a"), Some(MINUTE));
assert_eq!(timers.interval("b"), None);
assert_eq!(timers.apply(HashMap::new()), vec![TimerChange::Removed("a".to_owned())]);
assert_eq!(timers.interval("a"), None);
assert!(nothing_due(&mut timers).await);
}
#[tokio::test(start_paused = true)]
async fn finishing_an_unknown_or_cleared_key_does_nothing() {
let mut timers = KeyedTimers::new();
assert!(!timers.finish(&"missing".to_owned()));
timers.apply(HashMap::from([("a".to_owned(), plan(MINUTE, MINUTE))]));
tokio::time::advance(MINUTE).await;
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
assert!(timers.start(&"a".to_owned()));
timers.clear();
assert!(!timers.finish(&"a".to_owned()));
assert_eq!(timers.interval(&"a".to_owned()), None);
tokio::time::advance(24 * 60 * MINUTE).await;
assert!(nothing_due(&mut timers).await);
}
#[tokio::test(start_paused = true)]
async fn an_interval_changed_during_a_run_is_reported_and_used_on_finish() {
let mut timers = KeyedTimers::new();
timers.apply(HashMap::from([("a".to_owned(), plan(Duration::ZERO, MINUTE))]));
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
assert!(timers.start(&"a".to_owned()));
assert_eq!(
timers.apply(HashMap::from([("a".to_owned(), plan(5 * MINUTE, 5 * MINUTE))])),
vec![TimerChange::Updated("a".to_owned())]
);
assert!(nothing_due(&mut timers).await);
assert_eq!(timers.interval(&"a".to_owned()), Some(5 * MINUTE));
// The new plan's first delay is not a fire time while the run is still in flight.
tokio::time::advance(5 * MINUTE).await;
assert!(
nothing_due(&mut timers).await,
"a changed interval must not queue a second run beside the one in flight"
);
assert!(!timers.finish(&"a".to_owned()));
tokio::time::advance(5 * MINUTE - Duration::from_secs(1)).await;
assert!(nothing_due(&mut timers).await);
tokio::time::advance(Duration::from_secs(1)).await;
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
assert!(nothing_due(&mut timers).await, "exactly one run after the change");
}
+5 -5
View File
@@ -49,9 +49,9 @@
"@tanstack/react-virtual": "^3.14.13",
"@tauri-apps/api": "2.13.0",
"@tauri-apps/plugin-clipboard-manager": "2.5.0",
"@tauri-apps/plugin-dialog": "2.8.4",
"@tauri-apps/plugin-fs": "2.7.1",
"@tauri-apps/plugin-http": "2.9.0",
"@tauri-apps/plugin-dialog": "2.9.0",
"@tauri-apps/plugin-fs": "2.8.0",
"@tauri-apps/plugin-http": "2.10.0",
"@tauri-apps/plugin-opener": "2.7.3",
"@tauri-apps/plugin-updater": "2.14.1",
"ahooks": "^3.10.0",
@@ -110,7 +110,7 @@
"https-proxy-agent": "^9.1.0",
"husky": "^9.1.7",
"jiti": "^2.7.0",
"knip": "6.49.0",
"knip": "6.51.1",
"lint-staged": "^17.5.1",
"sass": "^1.104.1",
"tar": "^8.0.0",
@@ -132,5 +132,5 @@
]
},
"type": "module",
"packageManager": "pnpm@12.25.1"
"packageManager": "pnpm@12.26.0"
}
+189 -181
View File
@@ -7,172 +7,172 @@ importers:
configDependencies: {}
packageManagerDependencies:
pnpm:
specifier: 12.25.1
version: 12.25.1
specifier: 12.26.0
version: 12.26.0
packages:
'@pnpm/exe.android-arm64@12.25.1':
resolution: {integrity: sha512-QHXIyWMsuntq05xq9twYS6upQZS2TYeJIfmBWDFw1Xyi8XQxiaD06DSTWwZYjR38GwOP/dveeMC2jk2Y68IAAg==}
'@pnpm/exe.android-arm64@12.26.0':
resolution: {integrity: sha512-OY1jWzRb3IfN1Z5+IyILgc9LW7M0z5PGGnqrSS3g5f28Eu1g1eKEVlS8wtBfpn4isxtmmYD8xCIfwXZNpdvsbw==}
cpu: [arm64]
os: [android]
'@pnpm/exe.android-x64@12.25.1':
resolution: {integrity: sha512-bOJZTzi5c0MrI8xn6qU+0QzYu3gHMUtwLxb8ZRzuk/by7u6XhGXpn+gfppw7BF3te+rxpqK/mSR2PXb40d/7kg==}
'@pnpm/exe.android-x64@12.26.0':
resolution: {integrity: sha512-RisG0x6N4iJ0GQ+48BjY83F9vrySNTOzVxvh0r5WMpDZZwvCVLVXYNvuiy/kbLT6Qdeyc6P2JWgWr6wFshY94Q==}
cpu: [x64]
os: [android]
'@pnpm/exe.darwin-arm64@12.25.1':
resolution: {integrity: sha512-NXG2kaXA7ui3T7aznhAmG8AwWZ/BmKkxqT9DIIQJ0jU1jLKkRhGce1gbyJ+RAeGKx0HcRHAJbRi38lcHgpCteA==}
'@pnpm/exe.darwin-arm64@12.26.0':
resolution: {integrity: sha512-pk0zRMEYZUf63PSn9sc9IQ8tLixHRpAGem34qyKAYtTKELcbufQ2X271MlS6EJbGiciFC21Wea3h3wWBra1vHQ==}
cpu: [arm64]
os: [darwin]
'@pnpm/exe.darwin-x64@12.25.1':
resolution: {integrity: sha512-cDnnUeocsg6ESvgjxTs9az5SUt9MEaINaMKGzAEqrfFMCRvaYgkC+0Ct7eYb/41i9WYPvd9DFv8H29LHECwcVA==}
'@pnpm/exe.darwin-x64@12.26.0':
resolution: {integrity: sha512-anyxq5Ew6iNpXYu2h+jW5WeZMPX/kv7TbHLm9k4rnRIb50MNJJfmaoTEKAdDUrO+ny9I2aF5pN/05RuzWPhdbQ==}
cpu: [x64]
os: [darwin]
'@pnpm/exe.freebsd-x64@12.25.1':
resolution: {integrity: sha512-LEDM+BE5BdYEetfEHKSD9f5IhOWmMAHix9bMqhds6dn3cMICNQeJZQaoimwUDeVVAR8yMtvaDwRZGuWXOq5gJw==}
'@pnpm/exe.freebsd-x64@12.26.0':
resolution: {integrity: sha512-IY70n6CTJv3Dv/pez7irOjAFaWWe+vzKqVbiPRnpEGCheIMwc/58as+jnYeRKlCqmyTncTaVRMhXj/JSUvhJFA==}
cpu: [x64]
os: [freebsd]
'@pnpm/exe.linux-arm64-musl@12.25.1':
resolution: {integrity: sha512-LtURUp1sJoS0ENQtKLk+oTI7oSlcEDHl3SOxxS8AUD/FTmP1AM1htwYwxi+91J+MTinOYqcUFrgb1f87Zn1Vfw==}
'@pnpm/exe.linux-arm64-musl@12.26.0':
resolution: {integrity: sha512-46GKcquLpXDdeE3SwEf9yg76fETb6EdA0k62+nGvJZTS4gzpSGn9Bkf956KusALiJvD+NFhyRn9dE5U+xH0XyA==}
cpu: [arm64]
os: [linux]
libc: [musl]
'@pnpm/exe.linux-arm64@12.25.1':
resolution: {integrity: sha512-55Ni6+zebnL2zdvKq23tZCEWbtPSMKeQ1MwJAwqDqS/VjD/Z6hT0BlJSTFvHKUgrWOBxnH501iTIyQgLVD+Cfw==}
'@pnpm/exe.linux-arm64@12.26.0':
resolution: {integrity: sha512-UrKGXpcTmvm7S8nEMCcJk0nRq/GtuJU+bhYaXtjQ/9nKT9HEINmMLEZJeli9wfgfgr+cWP1hv4SPhgZAOERX/w==}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-loong64@12.25.1':
resolution: {integrity: sha512-52Fzal3IdcqsJ1kChNZC00JoFcwA9tDem/qTuZxpeJcc0KTALXTI5U/LbVF1+OXBfn72ADjS0Hxewkng7Q1iBA==}
'@pnpm/exe.linux-loong64@12.26.0':
resolution: {integrity: sha512-88idddQ+WUIjGX6ypUqci9ZQuDtDGkEyn76FiCYv1p1gtDj5IpuVDYahmOd2cUwyyXZFXs/UklpTjE4fOPLTTA==}
cpu: [loong64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-ppc64@12.25.1':
resolution: {integrity: sha512-x3b9VQyrmHi1IIejDGqZWrdmgbtTV/qgE3Sca0NVYmY6gT1cAvkKFq6tQvHJEgeEdny7hGKl+1sk6YkKRs1Sfg==}
'@pnpm/exe.linux-ppc64@12.26.0':
resolution: {integrity: sha512-viCV1LiKWKRKG0OXJV0Sgw6kQ5mm2LpAb2oymCSOP6ASM/AY8yBNYCQP9m9kToI7ajhxRNxqG3YZpuSuxs9/3A==}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-riscv64@12.25.1':
resolution: {integrity: sha512-lPQ5PjYog/N07VsOBEZr661GgZ7y39wQLRCviHcL4RfpMBpe4XeJKK3W7YKl9NJz6+5/nzMYYfTcvZPFLWuMvA==}
'@pnpm/exe.linux-riscv64@12.26.0':
resolution: {integrity: sha512-8t9RG7Hratl//OFCTYSsRWhykfnlMt+yYmpyr9waaZE9rl9YEJjjn4/OH+H3QxkhrAMfJI0DFdw1yWTXQ3CUfw==}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-s390x@12.25.1':
resolution: {integrity: sha512-5kdJeOXns1O/PYqdR2Zk/0ci/0mCz1LhaJDIA6NiqNdgFxwCC6ufRTBiu9u4FB/F2MWBLPDtyHxwzpcbBFCP9Q==}
'@pnpm/exe.linux-s390x@12.26.0':
resolution: {integrity: sha512-dnYk5INg16EfkVIP8+SxznEFmtvAHeZZ/bZauUMKUTicSqzq+9gaNZerNaqMImgcn7RwLRQBgq+YO9mWEDTeSw==}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@pnpm/exe.linux-x64-musl@12.25.1':
resolution: {integrity: sha512-GRsFj54bSmdhceZwrA+zReMfGJw6X6qpC4pJh6iLaUcy3p0fG7A7Zqr70AKmtzvW1Zm2VGkeeIzja6QSkN09Vw==}
'@pnpm/exe.linux-x64-musl@12.26.0':
resolution: {integrity: sha512-erYpcj7GU3NU7++XkszdcCmYSXfED7GqyNJB5Rsfy1vdkO3r82GnAbATibVNITHeLIeJWqcw2Ayf3G2QEiTJKg==}
cpu: [x64]
os: [linux]
libc: [musl]
'@pnpm/exe.linux-x64@12.25.1':
resolution: {integrity: sha512-Db2T6CtSNO8hjG6FISkOaZ2PW/OpynoXcT+jWEh44xDgSBt68rgbjGIbzjXSKJ+vH2mkoUxaUZCcLLusBVqelw==}
'@pnpm/exe.linux-x64@12.26.0':
resolution: {integrity: sha512-MZiMSTkC8buH3EGfkDootc2WvE/5tUzXhrM6hVcCgDWS7WbU7AefjLAp7hEjBw74E88JXglp7d+A0BSbRt91yA==}
cpu: [x64]
os: [linux]
libc: [glibc]
'@pnpm/exe.netbsd-x64@12.25.1':
resolution: {integrity: sha512-2hU5yNM/C8FT5eqbrNzB+0yGw/SS3oMJ1afk8pXEDsGU4vWdiiWxSqQ0kM8GHIvCDa/qRyw9ns98XWu5KZxxiA==}
'@pnpm/exe.netbsd-x64@12.26.0':
resolution: {integrity: sha512-ujMZzueds7rfEMDbvexTaLpFTLBdU01H79yMN28RXfnyLb9rDe8uMGLq2QsvuCfFBL21riaEdK7Yolv93/y5aQ==}
cpu: [x64]
os: [netbsd]
'@pnpm/exe.win32-arm64@12.25.1':
resolution: {integrity: sha512-v7YduE+TgEid1AiIThVBmYBnF0dj6vtk3ymcCkcM5FvanAM8MXoZhSiQYayQruh8xDwTXf5n8Zgn1OOi8WtqDg==}
'@pnpm/exe.win32-arm64@12.26.0':
resolution: {integrity: sha512-CeNctRVkKRRVGGwJ3Nb9hoyh0P/+ULMBmLsfXUw6AE17hEH0kVSiwdbnZqgy7G0EhYmEuIRAEIUnwRUSX377Vw==}
cpu: [arm64]
os: [win32]
'@pnpm/exe.win32-x64@12.25.1':
resolution: {integrity: sha512-cMfLsOE4zxSYBZYWyK1tr6BvCKVDyC81CnZg953t/6MEL592D8gk0eGdHQilEcd+yO+o6Ey1W9LLQdjl7pglsQ==}
'@pnpm/exe.win32-x64@12.26.0':
resolution: {integrity: sha512-p0x3aUOh+4BHLQvvE8DTpCzOYWe9tWdbiqtUwljCSfkXk/OeWTKDlCqzTd3rxAsZhDQkTIULWeMitJZqkWGt6g==}
cpu: [x64]
os: [win32]
pnpm@12.25.1:
resolution: {integrity: sha512-psZ31wNNPXmvE28z2zPNbUEz1z+lZaBr1kqPCW0lN92HoI1o4Y/zd3cf9RwY4uwxvgO0RnDrGeJBiQ6uOu0Bag==}
pnpm@12.26.0:
resolution: {integrity: sha512-W05eCOcD3LyL/gkedH0c9ws0Sdlto5E3sFDLSQTz6qTOPPnkX7CaMpCmTwPY6LNw+VuQ75qTf9APs5+DNINFqQ==}
engines: {node: '>=18'}
hasBin: true
snapshots:
'@pnpm/exe.android-arm64@12.25.1':
'@pnpm/exe.android-arm64@12.26.0':
optional: true
'@pnpm/exe.android-x64@12.25.1':
'@pnpm/exe.android-x64@12.26.0':
optional: true
'@pnpm/exe.darwin-arm64@12.25.1':
'@pnpm/exe.darwin-arm64@12.26.0':
optional: true
'@pnpm/exe.darwin-x64@12.25.1':
'@pnpm/exe.darwin-x64@12.26.0':
optional: true
'@pnpm/exe.freebsd-x64@12.25.1':
'@pnpm/exe.freebsd-x64@12.26.0':
optional: true
'@pnpm/exe.linux-arm64-musl@12.25.1':
'@pnpm/exe.linux-arm64-musl@12.26.0':
optional: true
'@pnpm/exe.linux-arm64@12.25.1':
'@pnpm/exe.linux-arm64@12.26.0':
optional: true
'@pnpm/exe.linux-loong64@12.25.1':
'@pnpm/exe.linux-loong64@12.26.0':
optional: true
'@pnpm/exe.linux-ppc64@12.25.1':
'@pnpm/exe.linux-ppc64@12.26.0':
optional: true
'@pnpm/exe.linux-riscv64@12.25.1':
'@pnpm/exe.linux-riscv64@12.26.0':
optional: true
'@pnpm/exe.linux-s390x@12.25.1':
'@pnpm/exe.linux-s390x@12.26.0':
optional: true
'@pnpm/exe.linux-x64-musl@12.25.1':
'@pnpm/exe.linux-x64-musl@12.26.0':
optional: true
'@pnpm/exe.linux-x64@12.25.1':
'@pnpm/exe.linux-x64@12.26.0':
optional: true
'@pnpm/exe.netbsd-x64@12.25.1':
'@pnpm/exe.netbsd-x64@12.26.0':
optional: true
'@pnpm/exe.win32-arm64@12.25.1':
'@pnpm/exe.win32-arm64@12.26.0':
optional: true
'@pnpm/exe.win32-x64@12.25.1':
'@pnpm/exe.win32-x64@12.26.0':
optional: true
pnpm@12.25.1:
pnpm@12.26.0:
optionalDependencies:
'@pnpm/exe.android-arm64': 12.25.1
'@pnpm/exe.android-x64': 12.25.1
'@pnpm/exe.darwin-arm64': 12.25.1
'@pnpm/exe.darwin-x64': 12.25.1
'@pnpm/exe.freebsd-x64': 12.25.1
'@pnpm/exe.linux-arm64': 12.25.1
'@pnpm/exe.linux-arm64-musl': 12.25.1
'@pnpm/exe.linux-loong64': 12.25.1
'@pnpm/exe.linux-ppc64': 12.25.1
'@pnpm/exe.linux-riscv64': 12.25.1
'@pnpm/exe.linux-s390x': 12.25.1
'@pnpm/exe.linux-x64': 12.25.1
'@pnpm/exe.linux-x64-musl': 12.25.1
'@pnpm/exe.netbsd-x64': 12.25.1
'@pnpm/exe.win32-arm64': 12.25.1
'@pnpm/exe.win32-x64': 12.25.1
'@pnpm/exe.android-arm64': 12.26.0
'@pnpm/exe.android-x64': 12.26.0
'@pnpm/exe.darwin-arm64': 12.26.0
'@pnpm/exe.darwin-x64': 12.26.0
'@pnpm/exe.freebsd-x64': 12.26.0
'@pnpm/exe.linux-arm64': 12.26.0
'@pnpm/exe.linux-arm64-musl': 12.26.0
'@pnpm/exe.linux-loong64': 12.26.0
'@pnpm/exe.linux-ppc64': 12.26.0
'@pnpm/exe.linux-riscv64': 12.26.0
'@pnpm/exe.linux-s390x': 12.26.0
'@pnpm/exe.linux-x64': 12.26.0
'@pnpm/exe.linux-x64-musl': 12.26.0
'@pnpm/exe.netbsd-x64': 12.26.0
'@pnpm/exe.win32-arm64': 12.26.0
'@pnpm/exe.win32-x64': 12.26.0
---
lockfileVersion: '9.0'
@@ -225,14 +225,14 @@ importers:
specifier: 2.5.0
version: 2.5.0
'@tauri-apps/plugin-dialog':
specifier: 2.8.4
version: 2.8.4
'@tauri-apps/plugin-fs':
specifier: 2.7.1
version: 2.7.1
'@tauri-apps/plugin-http':
specifier: 2.9.0
version: 2.9.0
'@tauri-apps/plugin-fs':
specifier: 2.8.0
version: 2.8.0
'@tauri-apps/plugin-http':
specifier: 2.10.0
version: 2.10.0
'@tauri-apps/plugin-opener':
specifier: 2.7.3
version: 2.7.3
@@ -403,8 +403,8 @@ importers:
specifier: ^2.7.0
version: 2.7.0
knip:
specifier: 6.49.0
version: 6.49.0
specifier: 6.51.1
version: 6.51.1
lint-staged:
specifier: ^17.5.1
version: 17.5.1
@@ -1412,124 +1412,124 @@ packages:
'@octokit/types@18.0.0':
resolution: {integrity: sha512-l6bAF43PNxkJp6g+W4PjoUSSkxHomXw2nOum5CTftJz1NlV3vu93NImgOYtLf6CbBUb5j+fiuzW0PPQ5JTSvZA==}
'@oxc-parser/binding-android-arm-eabi@0.160.0':
resolution: {integrity: sha512-IGhHufQ5uRhivrpzCcUJ92Mj4kYyFVhghaWk9hgZP/b+7WxdzdhFqBbH+PwEcfssDdIW10YHXcFvWib3kMX4Zg==}
'@oxc-parser/binding-android-arm-eabi@0.161.0':
resolution: {integrity: sha512-7rZxHs0ZndC5wp8OAooueAJp+qMjycAvhGerKMg8Kc3y2x7pdvqJ6m9YxIwZ/cao0/w9R5/HL63zRMWrL7+PYQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [android]
'@oxc-parser/binding-android-arm64@0.160.0':
resolution: {integrity: sha512-VxqVDFdTJG/QrJJ5pc/JIocKExtxCGcKf9qBsjIMS2VymVnHNdDu58d35pkgxIMFhxJ92YD79+66SBv86GXfCw==}
'@oxc-parser/binding-android-arm64@0.161.0':
resolution: {integrity: sha512-v8cNS3rcfFCbWBstttbhi784bMIqdGB3r8+LxHEM5umHR2XkQWiaOX7I/0lnUHF1f5zLSlA818sqg7TKFBn0Wg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
'@oxc-parser/binding-darwin-arm64@0.160.0':
resolution: {integrity: sha512-W5ULJkX2YAZAi6h2gkWCZCq1Ws5ZTIejBXjQP3tdf/UOeJaNQes4Vo5659/szYrFoBTef+WWcOU4HaY3TT4OYQ==}
'@oxc-parser/binding-darwin-arm64@0.161.0':
resolution: {integrity: sha512-m06qAJmRZfG2wIDZIunFmsf4E1CqzbEO54Gdll4bf9ahUOpL6JcnJHe/TRH3jbWJSJwc6ddxVyDI16N+oxhhoQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
'@oxc-parser/binding-darwin-x64@0.160.0':
resolution: {integrity: sha512-NNV6qakT/DX8SLqpe/gJ2ab2yDVJ+y6DKdJrbyTAdkpMjTP1KljiUxtAwoKVlHVPqfGMFPpSHIU9yL3FAWG/3w==}
'@oxc-parser/binding-darwin-x64@0.161.0':
resolution: {integrity: sha512-sxeOif3jV42oXbi2ruVjE7Z/vH3ifxUqbLvDdp4EjOj7R/6ADMelvj39Ra845uYR7akzZAF1AUu/8VdOmPociw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
'@oxc-parser/binding-freebsd-x64@0.160.0':
resolution: {integrity: sha512-P1Ay7bTnFJarHefoBOOrzZ8ynRluk0w92p/+PwkAYgg38Fh5Z2eQN2slzYqODyNQRDd2YrdecLV038V6KmqfXw==}
'@oxc-parser/binding-freebsd-x64@0.161.0':
resolution: {integrity: sha512-z2BzdDvFOFZ9GD58+cW/+wX76BU2vhzxpt8CHtcvlWT1O9CTuy3tuJAQbrvNCae89JbAzNG1RCvTTr8X7qSeEg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
'@oxc-parser/binding-linux-arm-gnueabihf@0.160.0':
resolution: {integrity: sha512-jw16rzFMeyaGRTVoHTiKAe5qHa6T5v54GX0TGoAvbEskN+hQcK0pZQ+pi5n3yGZ7b1+vTF2eBuqQP98mgcd6XA==}
'@oxc-parser/binding-linux-arm-gnueabihf@0.161.0':
resolution: {integrity: sha512-nTcaamp9wEgYcfW5IJP2sMJhyf74x5kvVGFVCr35e+7ieJsjL+Gat/zqg+CtWsluEVAbqQ8A6MC8WyXkhz0a0w==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
'@oxc-parser/binding-linux-arm-musleabihf@0.160.0':
resolution: {integrity: sha512-B55bnJn8XMC8NDBbEsL6Za2ZuFx6RIG49GMSlHYfpIc2pWQ6sbJRwarP+iKXnPgpJ1N7wfOAotMp58NUYjzQaQ==}
'@oxc-parser/binding-linux-arm-musleabihf@0.161.0':
resolution: {integrity: sha512-+/FA+S20pxKPmo9oXjCf6JXrs3/mzC4iUYI+bDJQt/4jYGeqrbI89wI2k5v3fOUdVHyjPfT6C6GIH6eoch63Hw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
'@oxc-parser/binding-linux-arm64-gnu@0.160.0':
resolution: {integrity: sha512-YKVHxONDpWXTPfilLv2MKvaI7VbYnKHARr5wJ3KKKGk0OkauDc0tVFyZlKFwIy9+br46fh8AjTVCnz6+9gKxVA==}
'@oxc-parser/binding-linux-arm64-gnu@0.161.0':
resolution: {integrity: sha512-mqNTntheFrojC2pEb+D9IdyZ5wHyFojljrG/x2uG2MnAiKGE7UUcIKUUHR1MRl9hq0uonEt/NG3UiIuUzdY+Ww==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@oxc-parser/binding-linux-arm64-musl@0.160.0':
resolution: {integrity: sha512-uiVA0AemCVB3+oZ3JmjQCSEqiGIgl+o3+bLqORIfviJbyYlVUChoRh6cVbyyDG6zm4fW0RtQIdKq3fVYuNTA3Q==}
'@oxc-parser/binding-linux-arm64-musl@0.161.0':
resolution: {integrity: sha512-pxicq28qXK4lZvascRUuRC0okky2Zo4fCX0X/Iv7UynmkronmpmDVvD6Sn6Uhuv7ZyhiS1sSU8mRrvuLq6P3UQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
'@oxc-parser/binding-linux-ppc64-gnu@0.160.0':
resolution: {integrity: sha512-h/tr4lWGdRXs4rUktl84Z0CprQhdDlxN4D82/cCcoKr0Kb4TEIJriXZVqHPznp12/uBWcV+BiihUBPbeyZm1KQ==}
'@oxc-parser/binding-linux-ppc64-gnu@0.161.0':
resolution: {integrity: sha512-jNXHd8V/QR/bDRIxuR4R/9Ivvk6sIy2lKmxAt4Ieilye2bXtaBqoOCME2BVFB+TwliMb9vMXM5F9Vt8z9l6DAg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
'@oxc-parser/binding-linux-riscv64-gnu@0.160.0':
resolution: {integrity: sha512-bA/Ba24KZYxorIUBHF2NbXM0OVY24xowGu4L0YBzpXhivt+ks1z8BT/c+BYGSfdFFqWrfNkC5TJjQGWdRkUHWQ==}
'@oxc-parser/binding-linux-riscv64-gnu@0.161.0':
resolution: {integrity: sha512-DrOazxIhCet2iIhQRtbZbT2qlVb/uVNf77IDWbArqW0qtudtz0tGMPPMyUD7UUmxChl8H9Mg9tSqJfM1Li2PeA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@oxc-parser/binding-linux-riscv64-musl@0.160.0':
resolution: {integrity: sha512-1uI9RghjO7/JQzkL9M/EDnG0Egy5z4v3k5TCUbPESZVUawHEmC52MMnCLe7f2CjMtiLjsm879CnO2HkRtsECNA==}
'@oxc-parser/binding-linux-riscv64-musl@0.161.0':
resolution: {integrity: sha512-HTjh2FpM6qOp+4kYfsxeU76idnLy4ReVR07mBfOH1usyWm8fk7vf8mZA/Qawd88lu3VFmoiHof+t6mAgSFBAvg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [riscv64]
os: [linux]
libc: [musl]
'@oxc-parser/binding-linux-s390x-gnu@0.160.0':
resolution: {integrity: sha512-1gaVKLXjT+UML8w8ypK93KUJurvUUmegqgQ/7qijDNpGCuogmTOIu0KgsYqL2hH//amY3AtfQhTTMlw9l363wA==}
'@oxc-parser/binding-linux-s390x-gnu@0.161.0':
resolution: {integrity: sha512-pmj+3FQhHMRhdJcgdkeOqZ1Gj9B2WqvWuPvESj2qfJSEnLbTcJ/hyq3/WWJvEyGe7tf/Jn8R+etrsrxEhg9a+g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
'@oxc-parser/binding-linux-x64-gnu@0.160.0':
resolution: {integrity: sha512-v44/JCrzpIof2jAJwF9W1j9l7mZKEaKihd8vBECBaNyIPcOiO4dtkeGX51MxnGmrJbsltdvTJb60VXLyMyAD2w==}
'@oxc-parser/binding-linux-x64-gnu@0.161.0':
resolution: {integrity: sha512-ON0kPWLOJx9eS9439MjARiYqiI8GsbqV6QMYpNZiFy/Qbv8C6ZOksI5FIQNBT9tkd/29bk12HlqGaAPNwN8Vgg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
'@oxc-parser/binding-linux-x64-musl@0.160.0':
resolution: {integrity: sha512-NOT9x+x27Aitn+z6PggidaeHiKOpbglRXwzcHg+3VqbMT7nv/C3fnXKeVESy4o0u3Yb3mEocwPrtzlT5O53JSA==}
'@oxc-parser/binding-linux-x64-musl@0.161.0':
resolution: {integrity: sha512-dD+mCEBAeD9CledlhuO1Sbrh7l/0CAt/qH+ZMZY7ASTV/K7wkuUm+U5bRmiZcV3VqRD51uDkDvI7BVdims7EqQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
'@oxc-parser/binding-openharmony-arm64@0.160.0':
resolution: {integrity: sha512-kXFdUqEkbB1E66dfqu7sk65w0CaDVp+uPeJ4eOacxBuVgKk/poy+b8/XpFfV443UNB8LUUvzgTzyWLxDQte2Dw==}
'@oxc-parser/binding-openharmony-arm64@0.161.0':
resolution: {integrity: sha512-kvDtrs7WonODzo+/RGHlUoB6RjZqiyz0NiVvMKAD1uAKwiIt6cViCoyWpGSG8yeroiP+j9CUqplGxeEPasayZg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
'@oxc-parser/binding-win32-arm64-msvc@0.160.0':
resolution: {integrity: sha512-tzYHz6BOwmKCY2c8txeV06CkMzwEVQhFwug8OR75q2UVRMfksf9yD5UBjAeauPEiFhzNogg1RRyk8UZ0bjMXvg==}
'@oxc-parser/binding-win32-arm64-msvc@0.161.0':
resolution: {integrity: sha512-FVsENeErPX95cc/zZ//iOIOlUO7EjlrmhZBUTaYo5vDTI10zuuSXelcFwCHv9FHpRoQ94yDp73NQo02Uc6m8rg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
'@oxc-parser/binding-win32-ia32-msvc@0.160.0':
resolution: {integrity: sha512-vyYZ4gcWUPuPANDj66eBnZ7+CFzUU0pzX28a5armxejWxM7onM3awHkM4PB/al8eEZ3MH8l0AprX/1jXrfGh7Q==}
'@oxc-parser/binding-win32-ia32-msvc@0.161.0':
resolution: {integrity: sha512-45YlP50q9WxwIX24S+NYeeNCI+QSZ+Yj86xzYAKMFmeq4vLMp/jCGY/G3mOvCiAr+U4r38DB31bn86OCH7Xa1g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ia32]
os: [win32]
'@oxc-parser/binding-win32-x64-msvc@0.160.0':
resolution: {integrity: sha512-KvENUAjmLfLBJBTF9yQ2wb5/DH41+FPM45oM7NMTgW0R3kN49NUj314SaDqqqkba+4cNTBt8NA2Ux5dekZB68w==}
'@oxc-parser/binding-win32-x64-msvc@0.161.0':
resolution: {integrity: sha512-XbGwtNTFWtTn6s5O+PQgDlht4JSfcdb35LVI4Dx5qug92C1r9KcFd/gy1/w9Z3w/+UyGp8Fnl8Y5dYLNHrtGTQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
@@ -1537,8 +1537,8 @@ packages:
'@oxc-project/types@0.156.0':
resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
'@oxc-project/types@0.160.0':
resolution: {integrity: sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==}
'@oxc-project/types@0.161.0':
resolution: {integrity: sha512-9vJdwWhmlmA/bqykS4fdREI7aDvCjoYucXAB8ARsIZWFLx/1NeNXhTPgQab6ZuDp99exJXBlY1mY/oJf7rXYqg==}
'@oxc-resolver/binding-android-arm-eabi@11.24.2':
resolution: {integrity: sha512-y09e0L0SRI2OA2tUIrjBgoV3eH5hvUKXNkJqXmNo5V2WxIjyC7I7aJfRLMEVpA8yi95f90gFDvO0VMgrDw+vwA==}
@@ -2004,14 +2004,14 @@ packages:
'@tauri-apps/plugin-clipboard-manager@2.5.0':
resolution: {integrity: sha512-dibUy1nKURYDXRMvjNk4deAbTZ5jPQ8wCE4nolt5xniryWgXQ4sK2GkFXoXlHbRdPzfZptZj95BRLfalA7m/2Q==}
'@tauri-apps/plugin-dialog@2.8.4':
resolution: {integrity: sha512-+6ZOiXenOaxXwb8qCbBPdT2jX2cFPaVVHGIskrpmJLpmWj+qKRTD6X/z9x7hTdSQn7NedcoXCkWGej4a7dC4lw==}
'@tauri-apps/plugin-dialog@2.9.0':
resolution: {integrity: sha512-2IMHbcnBGurmEEe88uPd3/okUZdL9RgAkQem7N1lNWDnegsnQufHyeu79sIm+A20GeN34jZlxj5KEckAQIWk6w==}
'@tauri-apps/plugin-fs@2.7.1':
resolution: {integrity: sha512-4TBVjpi/q8PuNzjpkAc2iBGXMTLjOrAyfTiiOL8ORaJCZJRG3tjzmQ4sqs2CMG75FvLyRkOkERfP7AyY4iBNwQ==}
'@tauri-apps/plugin-fs@2.8.0':
resolution: {integrity: sha512-CapOJxFvXx9hguQ0dOERgoHlpy6RwmEqafXZHWULWCkxYWSLmJOjLt5WZtyirbpMQVDWhYdHQUH4jSUoJ3oOow==}
'@tauri-apps/plugin-http@2.9.0':
resolution: {integrity: sha512-q3HTsbyFk3E9H4slJr+egd6KdRF2Fn4BoZFGI3ZHb7PBT9snlsOOlZC5L4Q1+AlDDd6OHdf/KTM6DNUJ0RNMEQ==}
'@tauri-apps/plugin-http@2.10.0':
resolution: {integrity: sha512-lC6LnFUwwfbxKX6Hd+T0AlCozvHdchuleB9Nze/hhtH9ByUplAK/1rgOvxGtbc7yeCaOD8hq9YsdPKItTZJo9g==}
'@tauri-apps/plugin-opener@2.7.3':
resolution: {integrity: sha512-Nm+v7vLBCDzYZxrmCJhpMgtPsPsKt5myMs7SMU/aBjPOmAFI1RrHfhMz7t5KlxjMOzRcelyNq1/j0pmC9SmBVA==}
@@ -2963,6 +2963,10 @@ packages:
resolution: {integrity: sha512-cezEd/DTyyht9cvSSURyygXPfy04GtWO/5e6ZPvH7fCtjKz9PYOmuawphw1Ctd1f6C+5JypXfGD7ahNMXvevBA==}
engines: {node: '>=18'}
globster@1.0.1:
resolution: {integrity: sha512-vQKXkjX2W/gG5tm4ONpQTQe/7kDnij4Zb7M+QD7px80jVo9xZLwep2jz3UuYvY18WrsJkzKPGafp1nvwshe/0w==}
engines: {node: ^20.19.0 || >=22.12.0}
gopd@1.2.0:
resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
engines: {node: '>= 0.4'}
@@ -3161,8 +3165,8 @@ packages:
keyv@5.6.0:
resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==}
knip@6.49.0:
resolution: {integrity: sha512-8Gf4R0xcJx1NdNKfr6gOGgSVBE1flB+KHPKPybDTKJ/hPtnswxyFE7Zpsk71kBvzAKReezakbe3DbQ0qAT4vzA==}
knip@6.51.1:
resolution: {integrity: sha512-708u8ARC50tYA/dwMrLFWwD7LeD/FQOX7uO8p2Ms9pY0xHSUtpinClv5laFTPj9dig1uHOrHKNAexOA6bADl0w==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@@ -3400,8 +3404,8 @@ packages:
resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
engines: {node: '>= 0.6'}
minimatch@11.0.9:
resolution: {integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==}
minimatch@11.0.10:
resolution: {integrity: sha512-L3/cjhQ5E6lft0VCp/2mO3Ic74RnutKy3rz7iGwp/6w1hKcO262g2rbfacFyw6eBig5OdI0nu5PpuA0/WQs9Tw==}
engines: {node: 20 || >=22}
monaco-editor@0.58.0:
@@ -3472,8 +3476,8 @@ packages:
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'}
oxc-parser@0.160.0:
resolution: {integrity: sha512-IIc9PydmdnTcH1hucWCHfTUbAuHWPDEs8+WlmW7td3jJnaYrbzvPQgcc99FEJc0gURrVU8EskpAr2VMyJ8VbzA==}
oxc-parser@0.161.0:
resolution: {integrity: sha512-l1gf4O5aRXIAcrxqknUJMWH+qVTG9v2AeBNrHz7EDxn8ncoZa/1qy/6Wy8M8EGngcZrxK4Jt00kIH3yebLWiGA==}
engines: {node: ^20.19.0 || >=22.12.0}
oxc-resolver@11.24.2:
@@ -5147,7 +5151,7 @@ snapshots:
dependencies:
'@eslint/object-schema': 3.0.5
debug: 4.4.3
minimatch: 11.0.9
minimatch: 11.0.10
transitivePeerDependencies:
- supports-color
@@ -5392,66 +5396,66 @@ snapshots:
dependencies:
'@octokit/openapi-types': 29.0.1
'@oxc-parser/binding-android-arm-eabi@0.160.0':
'@oxc-parser/binding-android-arm-eabi@0.161.0':
optional: true
'@oxc-parser/binding-android-arm64@0.160.0':
'@oxc-parser/binding-android-arm64@0.161.0':
optional: true
'@oxc-parser/binding-darwin-arm64@0.160.0':
'@oxc-parser/binding-darwin-arm64@0.161.0':
optional: true
'@oxc-parser/binding-darwin-x64@0.160.0':
'@oxc-parser/binding-darwin-x64@0.161.0':
optional: true
'@oxc-parser/binding-freebsd-x64@0.160.0':
'@oxc-parser/binding-freebsd-x64@0.161.0':
optional: true
'@oxc-parser/binding-linux-arm-gnueabihf@0.160.0':
'@oxc-parser/binding-linux-arm-gnueabihf@0.161.0':
optional: true
'@oxc-parser/binding-linux-arm-musleabihf@0.160.0':
'@oxc-parser/binding-linux-arm-musleabihf@0.161.0':
optional: true
'@oxc-parser/binding-linux-arm64-gnu@0.160.0':
'@oxc-parser/binding-linux-arm64-gnu@0.161.0':
optional: true
'@oxc-parser/binding-linux-arm64-musl@0.160.0':
'@oxc-parser/binding-linux-arm64-musl@0.161.0':
optional: true
'@oxc-parser/binding-linux-ppc64-gnu@0.160.0':
'@oxc-parser/binding-linux-ppc64-gnu@0.161.0':
optional: true
'@oxc-parser/binding-linux-riscv64-gnu@0.160.0':
'@oxc-parser/binding-linux-riscv64-gnu@0.161.0':
optional: true
'@oxc-parser/binding-linux-riscv64-musl@0.160.0':
'@oxc-parser/binding-linux-riscv64-musl@0.161.0':
optional: true
'@oxc-parser/binding-linux-s390x-gnu@0.160.0':
'@oxc-parser/binding-linux-s390x-gnu@0.161.0':
optional: true
'@oxc-parser/binding-linux-x64-gnu@0.160.0':
'@oxc-parser/binding-linux-x64-gnu@0.161.0':
optional: true
'@oxc-parser/binding-linux-x64-musl@0.160.0':
'@oxc-parser/binding-linux-x64-musl@0.161.0':
optional: true
'@oxc-parser/binding-openharmony-arm64@0.160.0':
'@oxc-parser/binding-openharmony-arm64@0.161.0':
optional: true
'@oxc-parser/binding-win32-arm64-msvc@0.160.0':
'@oxc-parser/binding-win32-arm64-msvc@0.161.0':
optional: true
'@oxc-parser/binding-win32-ia32-msvc@0.160.0':
'@oxc-parser/binding-win32-ia32-msvc@0.161.0':
optional: true
'@oxc-parser/binding-win32-x64-msvc@0.160.0':
'@oxc-parser/binding-win32-x64-msvc@0.161.0':
optional: true
'@oxc-project/types@0.156.0': {}
'@oxc-project/types@0.160.0': {}
'@oxc-project/types@0.161.0': {}
'@oxc-resolver/binding-android-arm-eabi@11.24.2':
optional: true
@@ -5763,15 +5767,15 @@ snapshots:
dependencies:
'@tauri-apps/api': 2.13.0
'@tauri-apps/plugin-dialog@2.8.4':
'@tauri-apps/plugin-dialog@2.9.0':
dependencies:
'@tauri-apps/api': 2.13.0
'@tauri-apps/plugin-fs@2.7.1':
'@tauri-apps/plugin-fs@2.8.0':
dependencies:
'@tauri-apps/api': 2.13.0
'@tauri-apps/plugin-http@2.9.0':
'@tauri-apps/plugin-http@2.10.0':
dependencies:
'@tauri-apps/api': 2.13.0
@@ -5945,7 +5949,7 @@ snapshots:
'@typescript-eslint/types': 8.74.0
'@typescript-eslint/visitor-keys': 8.74.0
debug: 4.4.3
minimatch: 11.0.9
minimatch: 11.0.10
semver: 7.8.5
tinyglobby: 0.2.17
ts-api-utils: 2.5.0(typescript@6.0.3)
@@ -6441,7 +6445,7 @@ snapshots:
eslint: 10.16.0(jiti@2.7.0)
eslint-import-context: 0.1.9(unrs-resolver@1.12.2)
is-glob: 4.0.3
minimatch: 11.0.9
minimatch: 11.0.10
semver: 7.8.5
stable-hash-x: 0.2.0
unrs-resolver: 1.12.2
@@ -6630,7 +6634,7 @@ snapshots:
imurmurhash: 0.1.4
is-glob: 4.0.3
json-stable-stringify-without-jsonify: 1.0.1
minimatch: 11.0.9
minimatch: 11.0.10
natural-compare: 1.4.0
optionator: 0.9.4
optionalDependencies:
@@ -6774,6 +6778,10 @@ snapshots:
globals@17.12.0: {}
globster@1.0.1:
dependencies:
picomatch: 4.0.7
gopd@1.2.0: {}
has-symbols@1.1.0: {}
@@ -6991,17 +6999,17 @@ snapshots:
dependencies:
'@keyv/serialize': 1.1.1
knip@6.49.0:
knip@6.51.1:
dependencies:
formatly: 0.12.3
get-tsconfig: 4.14.3
globster: 1.0.1
jiti: 2.7.0
oxc-parser: 0.160.0
oxc-parser: 0.161.0
oxc-resolver: 11.24.2
picomatch: 4.0.7
smol-toml: 1.9.1
strip-json-comments: 5.0.3
tinyglobby: 0.2.17
unbash: 6.0.5
yaml: 2.9.1
transitivePeerDependencies:
@@ -7350,7 +7358,7 @@ snapshots:
dependencies:
mime-db: 1.52.0
minimatch@11.0.9:
minimatch@11.0.10:
dependencies:
'@isaacs/nonrecursive-glob-match': 1.1.0
brace-expansion: 5.0.12
@@ -7429,29 +7437,29 @@ snapshots:
type-check: 0.4.0
word-wrap: 1.2.5
oxc-parser@0.160.0:
oxc-parser@0.161.0:
dependencies:
'@oxc-project/types': 0.160.0
'@oxc-project/types': 0.161.0
optionalDependencies:
'@oxc-parser/binding-android-arm-eabi': 0.160.0
'@oxc-parser/binding-android-arm64': 0.160.0
'@oxc-parser/binding-darwin-arm64': 0.160.0
'@oxc-parser/binding-darwin-x64': 0.160.0
'@oxc-parser/binding-freebsd-x64': 0.160.0
'@oxc-parser/binding-linux-arm-gnueabihf': 0.160.0
'@oxc-parser/binding-linux-arm-musleabihf': 0.160.0
'@oxc-parser/binding-linux-arm64-gnu': 0.160.0
'@oxc-parser/binding-linux-arm64-musl': 0.160.0
'@oxc-parser/binding-linux-ppc64-gnu': 0.160.0
'@oxc-parser/binding-linux-riscv64-gnu': 0.160.0
'@oxc-parser/binding-linux-riscv64-musl': 0.160.0
'@oxc-parser/binding-linux-s390x-gnu': 0.160.0
'@oxc-parser/binding-linux-x64-gnu': 0.160.0
'@oxc-parser/binding-linux-x64-musl': 0.160.0
'@oxc-parser/binding-openharmony-arm64': 0.160.0
'@oxc-parser/binding-win32-arm64-msvc': 0.160.0
'@oxc-parser/binding-win32-ia32-msvc': 0.160.0
'@oxc-parser/binding-win32-x64-msvc': 0.160.0
'@oxc-parser/binding-android-arm-eabi': 0.161.0
'@oxc-parser/binding-android-arm64': 0.161.0
'@oxc-parser/binding-darwin-arm64': 0.161.0
'@oxc-parser/binding-darwin-x64': 0.161.0
'@oxc-parser/binding-freebsd-x64': 0.161.0
'@oxc-parser/binding-linux-arm-gnueabihf': 0.161.0
'@oxc-parser/binding-linux-arm-musleabihf': 0.161.0
'@oxc-parser/binding-linux-arm64-gnu': 0.161.0
'@oxc-parser/binding-linux-arm64-musl': 0.161.0
'@oxc-parser/binding-linux-ppc64-gnu': 0.161.0
'@oxc-parser/binding-linux-riscv64-gnu': 0.161.0
'@oxc-parser/binding-linux-riscv64-musl': 0.161.0
'@oxc-parser/binding-linux-s390x-gnu': 0.161.0
'@oxc-parser/binding-linux-x64-gnu': 0.161.0
'@oxc-parser/binding-linux-x64-musl': 0.161.0
'@oxc-parser/binding-openharmony-arm64': 0.161.0
'@oxc-parser/binding-win32-arm64-msvc': 0.161.0
'@oxc-parser/binding-win32-ia32-msvc': 0.161.0
'@oxc-parser/binding-win32-x64-msvc': 0.161.0
oxc-resolver@11.24.2:
optionalDependencies:
+17 -20
View File
@@ -9,7 +9,7 @@ import AdmZip from 'adm-zip'
import { HttpsProxyAgent } from 'https-proxy-agent'
import { extract } from 'tar'
import { resolveServiceBundle as serviceBundleFromMetadata } from './service-release.mjs'
import { resolveServiceRelease } from './service-release.mjs'
import { log_debug, log_error, log_info, log_success } from './utils.mjs'
/** Prepares platform resources, caching versions and unchanged files unless `--force` is used. */
@@ -581,30 +581,23 @@ async function resolveServiceBundle() {
}
})
const metadata = JSON.parse(
execFileSync(
'cargo',
[
'metadata',
'--locked',
'--format-version',
'1',
'--filter-platform',
SIDECAR_HOST,
],
{ cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 },
),
const cargoManifest = await fsp.readFile(
path.join(cwd, 'src-tauri', 'Cargo.toml'),
'utf8',
)
const bundle = serviceBundleFromMetadata(metadata, SIDECAR_HOST, platform)
if (bundle.manifest) {
const serviceDependency = cargoManifest
.split(/\r?\n/)
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
const sourcePath = serviceDependency?.match(/\bpath\s*=\s*"([^"]+)"/)?.[1]
if (sourcePath) {
const manifest = path.resolve(cwd, 'src-tauri', sourcePath, 'Cargo.toml')
const targetDirectory = path.join(cwd, 'target', 'bundled-service')
execFileSync(
'cargo',
[
'build',
'--locked',
'--manifest-path',
bundle.manifest,
manifest,
'--target-dir',
targetDirectory,
'--target',
@@ -612,7 +605,7 @@ async function resolveServiceBundle() {
'--release',
'--features',
'standalone,client',
...SERVICE_BINARIES.flatMap((name) => ['--bin', name]),
'--bins',
],
{ stdio: 'inherit' },
)
@@ -627,7 +620,11 @@ async function resolveServiceBundle() {
}
return
}
const { archiveFile, downloadURL } = bundle
const { archiveFile, downloadURL } = resolveServiceRelease(
cargoManifest,
SIDECAR_HOST,
platform,
)
const tempDir = path.join(TEMP_DIR, 'clash-verge-service-ipc')
const tempArchive = path.join(tempDir, archiveFile)
+10 -23
View File
@@ -1,35 +1,22 @@
const SERVICE_URL_PREFIX =
'https://github.com/clash-verge-rev/clash-verge-service-ipc/releases/download'
export function resolveServiceBundle(metadata, host, platform) {
const app = metadata.packages.find(
(pkg) =>
pkg.name === 'clash-verge' && metadata.workspace_members.includes(pkg.id),
)
const dependency = app?.dependencies.find(
(dep) => dep.name === 'clash_verge_service_ipc',
)
const edge = metadata.resolve.nodes
.find((node) => node.id === app?.id)
?.deps.find((dep) => dep.name === 'clash_verge_service_ipc')
const service = metadata.packages.find((pkg) => pkg.id === edge?.pkg)
if (!service || !dependency) {
throw new Error('Cargo did not resolve the desktop IPC client dependency')
}
if (!service.source || new URL(service.source).searchParams.has('rev')) {
return { manifest: service.manifest_path }
}
const declared = dependency.req.replace(/^[=^]/, '')
if (declared !== service.version) {
export function resolveServiceRelease(cargoManifest, host, platform) {
const dependency = cargoManifest
.split(/\r?\n/)
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
const packageVersion = dependency?.match(/\bversion\s*=\s*"([^"]+)"/)?.[1]
if (!packageVersion) {
throw new Error(
`Service release version ${declared} differs from the resolved IPC client ${service.version}`,
'clash_verge_service_ipc dependency must declare an inline version',
)
}
const version = `v${declared}`
const version = `v${packageVersion}`
const archiveExt = platform === 'win32' ? 'zip' : 'tar.gz'
const archiveFile = `clash-verge-service-ipc-${version}-${host}.${archiveExt}`
return {
version,
archiveFile,
downloadURL: `${SERVICE_URL_PREFIX}/${version}/${archiveFile}`,
}
+2 -3
View File
@@ -86,7 +86,6 @@ flate2 = "1.1.11"
reqwest_dav = "0.4.0"
aes-gcm = { version = "0.11.1" }
base64 = "0.23.1"
sha2 = { workspace = true }
getrandom = "0.4.3"
futures = { workspace = true }
gethostname = "1.1.0"
@@ -104,7 +103,7 @@ rustls = { version = "0.23.47", features = ["ring"] }
webpki-roots = "1.0.12"
dark-light = "3.0.0"
bytes = "1.12.2"
tokio-util = { version = "0.7.20", features = ["time"] }
tokio-util = { workspace = true }
specta = { workspace = true, features = ["derive", "function", "serde_json"] }
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
specta-typescript = "=0.0.13"
@@ -122,7 +121,7 @@ clash-verge-signal = { workspace = true }
rfd = { version = "0.18.0", default-features = false, features = ["common-controls-v6"] }
[target.'cfg(target_os = "macos")'.dependencies]
tauri-plugin-wdio-webdriver = { version = "=2.0.0-next.0", optional = true }
tauri-plugin-wdio-webdriver = { version = "=2.0.0-next.1", optional = true }
objc2 = "0.6.5"
objc2-foundation = { version = "0.3.2", features = [
"NSString",
+2 -2
View File
@@ -4,7 +4,7 @@ use crate::feat;
use crate::utils::dirs;
use crate::{
cmd::StringifyErr as _,
config::{ClashInfo, Config, mihomo_yaml, profiles::save_committed_profiles},
config::{ClashInfo, Config, profiles::save_committed_profiles},
constants,
core::{
CoreManager, handle,
@@ -132,7 +132,7 @@ pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult {
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
let yaml_str = mihomo_yaml::serialize_for_export(&dns_config.0).stringify_err()?;
let yaml_str = clash_verge_config_render::serialize_for_export(&dns_config.0).stringify_err()?;
fs::write(&dns_path, yaml_str).await.stringify_err()?;
logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
+5 -7
View File
@@ -1,9 +1,5 @@
use super::CmdResult;
use crate::{
cmd::StringifyErr as _,
config::{Config, mihomo_yaml},
core::CoreManager,
};
use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager};
use anyhow::{Context as _, anyhow};
use std::collections::HashMap;
use tristr::alias::String;
@@ -28,7 +24,9 @@ pub async fn get_runtime_yaml() -> CmdResult<std::string::String> {
let config = runtime.config.as_ref();
config
.ok_or_else(|| anyhow!("failed to parse config to yaml file"))
.and_then(|config| mihomo_yaml::serialize_for_export(config).context("failed to convert config to yaml"))
.and_then(|config| {
clash_verge_config_render::serialize_for_export(config).context("failed to convert config to yaml")
})
.stringify_err()
}
@@ -91,7 +89,7 @@ pub async fn get_runtime_proxy_chain_config(
config.insert("proxies".into(), proxies_chain);
mihomo_yaml::serialize_for_export(&config)
clash_verge_config_render::serialize_for_export(&config)
.context("YAML generation failed")
.stringify_err()
} else {
+140 -9
View File
@@ -8,7 +8,17 @@ use crate::{
},
};
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult {
#[derive(Debug, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(tag = "status", rename_all = "camelCase")]
pub enum ServiceInstallOutcome {
Installed,
#[cfg_attr(not(any(windows, test)), allow(dead_code))]
Sidecar {
reason: String,
},
}
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult<ServiceInstallOutcome> {
let manager = CoreManager::global();
let result = {
let _lifecycle = manager.lifecycle_lock.lock().await;
@@ -16,17 +26,63 @@ async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str)
&status,
ServiceStatus::ReinstallRequired | ServiceStatus::ForceReinstallRequired
) {
manager.maintain_service(status).await
} else {
SERVICE_MANAGER.handle_service_status(status).await
manager
.controlled_stop_core_inner()
.await
.map_err(|error| proxy_aware_coded_error(&error, error_code))?;
}
SERVICE_MANAGER.handle_service_status(status).await
};
result.map_err(|error| proxy_aware_coded_error(&error, error_code))
#[cfg(windows)]
return finish_service_installation(result, error_code, async |reason| {
manager.continue_with_sidecar(Some(reason)).await
})
.await;
#[cfg(not(windows))]
result
.map(|()| ServiceInstallOutcome::Installed)
.map_err(|error| proxy_aware_coded_error(&error, error_code))
}
#[cfg(any(windows, test))]
async fn finish_service_installation<Fallback>(
installation: anyhow::Result<()>,
error_code: &str,
fallback: Fallback,
) -> CmdResult<ServiceInstallOutcome>
where
Fallback: AsyncFnOnce(&str) -> anyhow::Result<()>,
{
let Err(error) = installation else {
return Ok(ServiceInstallOutcome::Installed);
};
let Some(failure) = error.downcast_ref::<clash_verge_service_ipc::management::InstallationVerificationError>()
else {
return Err(proxy_aware_coded_error(&error, error_code));
};
let reasons = failure
.status
.cores
.iter()
.filter_map(|core| match &core.availability {
clash_verge_service_ipc::CoreAvailability::Rejected { reason } => Some(format!("{}: {reason}", core.name)),
_ => None,
})
.collect::<Vec<_>>();
if reasons.is_empty() {
return Err(proxy_aware_coded_error(&error, error_code));
}
let reason = reasons.join("\n");
fallback(reason.as_str())
.await
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))?;
Ok(ServiceInstallOutcome::Sidecar { reason })
}
#[tauri::command]
#[specta::specta]
pub async fn install_service() -> CmdResult {
pub async fn install_service() -> CmdResult<ServiceInstallOutcome> {
execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await
}
@@ -41,13 +97,13 @@ pub async fn uninstall_service() -> CmdResult {
#[tauri::command]
#[specta::specta]
pub async fn reinstall_service() -> CmdResult {
pub async fn reinstall_service() -> CmdResult<ServiceInstallOutcome> {
execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await
}
#[tauri::command]
#[specta::specta]
pub async fn repair_service() -> CmdResult {
pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await
}
@@ -55,7 +111,7 @@ pub async fn repair_service() -> CmdResult {
#[specta::specta]
pub async fn continue_with_sidecar() -> CmdResult {
crate::core::CoreManager::global()
.continue_with_sidecar()
.continue_with_sidecar(None)
.await
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))
}
@@ -66,6 +122,12 @@ pub fn get_sidecar_failure() -> crate::core::notification::SidecarFailureSnapsho
crate::core::notification::sidecar_failure_snapshot()
}
#[tauri::command]
#[specta::specta]
pub fn take_service_fallback_notice() -> Option<crate::core::service::ServiceFallbackNotice> {
crate::core::service::take_service_fallback_notice()
}
#[tauri::command]
#[specta::specta]
pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> {
@@ -91,3 +153,72 @@ pub fn sync_runtime_providers() {
request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE);
}
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::{ServiceInstallOutcome, finish_service_installation};
use clash_verge_service_ipc::{
CoreAvailability, CoreInspection, InstallationStatus, ProtocolInfo, management::InstallationVerificationError,
};
use std::cell::Cell;
#[tokio::test]
async fn rejected_installation_reports_sidecar_only_after_successful_continuation() {
let reason = "core path C:\\ is writable by Everyone";
for (availability, fallback_ready) in [
(None, false),
(Some(CoreAvailability::Missing), false),
(Some(CoreAvailability::DigestMismatch), false),
(Some(CoreAvailability::Rejected { reason: reason.into() }), false),
(Some(CoreAvailability::Rejected { reason: reason.into() }), true),
] {
let fallback_called = Cell::new(false);
let rejected = matches!(&availability, Some(CoreAvailability::Rejected { .. }));
let error = match availability {
Some(availability) => anyhow::Error::new(InstallationVerificationError {
status: InstallationStatus {
service_sha256: String::new(),
protocol: ProtocolInfo::current(),
cores: vec![CoreInspection {
name: "verge-mihomo.exe".into(),
availability,
}],
core_busy: false,
},
}),
None => anyhow::anyhow!("{reason}"),
}
.context("install service failed");
let result = finish_service_installation(Err(error), "SERVICE_INSTALL_FAILED", async |_| {
fallback_called.set(true);
anyhow::ensure!(fallback_ready, "another core is running");
Ok(())
})
.await;
assert_eq!(fallback_called.get(), rejected);
if rejected && fallback_ready {
assert_eq!(
result,
Ok(ServiceInstallOutcome::Sidecar {
reason: format!("verge-mihomo.exe: {reason}")
})
);
} else {
let error = result.expect_err("an unavailable fallback must remain an error");
assert_eq!(
error.code.as_deref(),
Some(if rejected {
"SERVICE_SIDECAR_FAILED"
} else {
"SERVICE_INSTALL_FAILED"
})
);
if rejected {
assert!(error.detail.contains("another core is running"));
}
}
}
}
}
+1 -2
View File
@@ -1,4 +1,3 @@
use super::mihomo_yaml;
use crate::constants::{network, tun as tun_const};
use crate::utils::dirs::{path_to_str, sidecar_ipc_path};
use crate::utils::{dirs, help};
@@ -152,7 +151,7 @@ impl IClashTemp {
pub async fn save_config(&self) -> Result<()> {
let path = dirs::clash_path()?;
let yaml = mihomo_yaml::serialize(&self.0)?;
let yaml = serde_yaml_ng::to_string(&self.0)?;
help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await
}
+4 -67
View File
@@ -1,4 +1,4 @@
use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml};
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
use crate::core::notify::NoticeStatus;
use crate::{
config::{
@@ -20,11 +20,11 @@ use crate::{
};
use anyhow::{Result, anyhow};
use backon::{ExponentialBuilder, Retryable as _};
use clash_verge_config_render::sanitize_tunnels_proxy;
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_runtime_bundle::resolve_provider_path_conflicts;
use serde_yaml_ng::{Mapping, Value};
use std::{collections::HashSet, path::PathBuf};
use std::path::PathBuf;
use tokio::sync::{Mutex, MutexGuard, OnceCell};
use tokio::time::sleep;
use tristr::alias::String;
@@ -230,7 +230,7 @@ impl Config {
{
return Ok(std::sync::Arc::clone(cached));
}
let yaml_str = std::sync::Arc::new(mihomo_yaml::serialize(config)?);
let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?);
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
Ok(yaml_str)
})
@@ -321,66 +321,3 @@ impl Config {
logging!(info, Type::Config, "save all draft data finished");
}
}
fn sanitize_tunnels_proxy(config: &mut Mapping) {
if !config
.get("tunnels")
.and_then(|v| v.as_sequence())
.is_some_and(|t| tunnels_need_validation(t))
{
return;
}
let mut valid: HashSet<String> = HashSet::with_capacity(64);
collect_names(config, "proxies", &mut valid);
collect_names(config, "proxy-groups", &mut valid);
valid.insert("DIRECT".into());
valid.insert("REJECT".into());
let Some(tunnels) = config.get_mut("tunnels").and_then(|v| v.as_sequence_mut()) else {
return;
};
for item in tunnels {
let Some(tunnel) = item.as_mapping_mut() else { continue };
let Some(proxy_name) = tunnel.get("proxy").and_then(|v| v.as_str()) else {
continue;
};
if proxy_name == "DIRECT" || proxy_name == "REJECT" {
continue;
}
if !valid.contains(proxy_name) {
tunnel.remove("proxy");
}
}
}
fn tunnels_need_validation(tunnels: &[Value]) -> bool {
tunnels.iter().any(|item| {
item.as_mapping()
.and_then(|t| t.get("proxy"))
.and_then(|p| p.as_str())
.is_some_and(|name| name != "DIRECT" && name != "REJECT")
})
}
fn collect_names(config: &Mapping, list_key: &str, out: &mut HashSet<String>) {
let Some(Value::Sequence(seq)) = config.get(list_key) else {
return;
};
for item in seq {
let Value::Mapping(map) = item else {
continue;
};
if let Some(Value::String(n)) = map.get("name")
&& !n.is_empty()
{
out.insert(n.into());
}
}
}
+6 -64
View File
@@ -1,12 +1,9 @@
use crate::core::notify::NoticeStatus;
use crate::utils::help;
use anyhow::Result;
use clash_verge_draft::DraftTransaction;
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_task::scheduled_task::{self, CoalescingJob};
use serde::{Deserialize, Serialize};
use serde_yaml_ng::{Mapping, Value};
use sha2::{Digest as _, Sha256};
use std::sync::{
LazyLock,
atomic::{AtomicBool, Ordering},
@@ -22,42 +19,6 @@ pub(crate) fn take_dns_override_notice() -> bool {
PENDING_DNS_OVERRIDE_NOTICE.swap(false, Ordering::Relaxed)
}
const PROVIDER_DNS_FIELDS: [&str; 3] = [
"proxy-server-nameserver",
"proxy-server-nameserver-policy",
"nameserver-policy",
];
pub(crate) fn dns_override_source(profile_uid: &str, config: &Mapping) -> Result<Option<String>> {
let Some(dns) = config.get("dns").and_then(Value::as_mapping) else {
return Ok(None);
};
let fields: Mapping = PROVIDER_DNS_FIELDS
.iter()
.filter_map(|key| {
let value = dns.get(*key)?;
let nonempty = match value {
Value::Sequence(values) => !values.is_empty(),
Value::Mapping(values) => !values.is_empty(),
Value::String(value) => !value.trim().is_empty(),
_ => false,
};
nonempty.then(|| (Value::from(*key), value.clone()))
})
.collect();
if fields.is_empty() {
return Ok(None);
}
let mut canonical = serde_json::to_value(fields)?;
canonical.sort_all_objects();
let mut digest = Sha256::new();
digest.update(profile_uid.as_bytes());
digest.update([0]);
digest.update(serde_json::to_vec(&canonical)?);
Ok(Some(help::hex_encode(&digest.finalize()).into()))
}
#[derive(Debug, Clone)]
pub(crate) struct DnsOverrideState {
profile_uid: String,
@@ -167,46 +128,27 @@ impl Config {
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::{DnsOverrideState, ProfileDnsSettings, dns_override_source};
use super::{DnsOverrideState, ProfileDnsSettings};
use crate::config::IVerge;
use anyhow::Result;
use clash_verge_config_render::override_source;
use serde_yaml_ng::Mapping;
fn mapping(yaml: &str) -> Mapping {
serde_yaml_ng::from_str(yaml).expect("valid fixture")
}
#[test]
fn dns_override_detects_each_original_field_but_not_empty_placeholders() -> Result<()> {
for field in [
"proxy-server-nameserver: [https://doh.pub/dns-query]",
"proxy-server-nameserver-policy: {'www.yournode.com': '114.114.114.114'}",
"nameserver-policy: {'+.quandao.com': ['https://doh.dohcore.com:2096/dns-query/#skip-cert-verify=true']}",
] {
assert!(dns_override_source("profile", &mapping(&format!("dns: {{{field}}}")))?.is_some());
assert!(dns_override_source("profile", &mapping(field))?.is_none());
}
for yaml in [
"{}",
"dns: {nameserver: [1.1.1.1]}",
"dns: {proxy-server-nameserver: [], proxy-server-nameserver-policy: null, nameserver-policy: {}}",
] {
assert!(dns_override_source("profile", &mapping(yaml))?.is_none());
}
Ok(())
}
#[test]
fn dns_override_confirmation_survives_formatting_but_not_a_different_source() -> Result<()> {
let original = mapping("dns: {nameserver-policy: {a.example: 1.1.1.1, b.example: [8.8.8.8]}}");
let source = dns_override_source("one", &original)?;
let source = override_source("one", &original)?;
let reordered =
mapping("dns:\n nameserver-policy:\n b.example: [8.8.8.8]\n a.example: 1.1.1.1\nport: 7890");
assert_eq!(source, dns_override_source("one", &reordered)?);
assert_eq!(source, override_source("one", &reordered)?);
assert!(DnsOverrideState::new("one", source.clone(), true, source.clone()).enabled);
assert!(!DnsOverrideState::new("two", dns_override_source("two", &original)?, true, source.clone()).enabled);
assert!(!DnsOverrideState::new("two", override_source("two", &original)?, true, source.clone()).enabled);
let changed = mapping("dns: {nameserver-policy: {a.example: 9.9.9.9, b.example: [8.8.8.8]}}");
assert!(!DnsOverrideState::new("one", dns_override_source("one", &changed)?, true, source).enabled);
assert!(!DnsOverrideState::new("one", override_source("one", &changed)?, true, source).enabled);
Ok(())
}
-108
View File
@@ -1,108 +0,0 @@
use serde::Serialize;
use serde_yaml_ng::Result;
pub(crate) use serde_yaml_ng::to_string as serialize;
pub(crate) fn serialize_for_export<T: Serialize>(data: &T) -> Result<String> {
Ok(quote_fake_ip_filter_wildcards(&serialize(data)?))
}
fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
let mut result = String::with_capacity(yaml.len());
let mut in_fake_ip_filter = false;
let mut fake_ip_filter_indent = 0;
for line in yaml.lines() {
let indent = line.len() - line.trim_start_matches(' ').len();
let trimmed = &line[indent..];
if in_fake_ip_filter && indent <= fake_ip_filter_indent && !trimmed.starts_with("- ") {
in_fake_ip_filter = false;
}
if !in_fake_ip_filter && trimmed == "fake-ip-filter:" {
in_fake_ip_filter = true;
fake_ip_filter_indent = indent;
}
if in_fake_ip_filter
&& indent >= fake_ip_filter_indent
&& let Some(item) = trimmed.strip_prefix("- ")
&& needs_quotes(item)
{
result.push_str(&line[..indent + 2]);
push_quoted(&mut result, item);
} else {
result.push_str(line);
}
result.push('\n');
}
result
}
fn needs_quotes(item: &str) -> bool {
!item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.']))
}
fn push_quoted(output: &mut String, item: &str) {
output.push('\'');
for (index, part) in item.split('\'').enumerate() {
if index != 0 {
output.push_str("''");
}
output.push_str(part);
}
output.push('\'');
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::serialize_for_export;
fn roundtrip(input: &str) {
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
let output = serialize_for_export(&value).expect("yaml should serialize");
let reparsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse");
assert_eq!(reparsed, value);
}
#[test]
fn quotes_fake_ip_filter_wildcards_without_changing_values() {
let input = r#"
dns:
fake-ip-filter:
- "*.lan"
- "+.market.xiaomi.com"
- ".example.com"
- "time.*.com"
- "plain.example.com"
"#;
roundtrip(input);
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
let output = serialize_for_export(&value).expect("yaml should serialize");
assert!(output.contains("- '*.lan'"));
assert!(output.contains("- '+.market.xiaomi.com'"));
assert!(output.contains("- '.example.com'"));
assert!(output.contains("- 'time.*.com'"));
assert!(output.contains("- plain.example.com"));
}
#[test]
fn nested_multiline_strings_roundtrip() {
roundtrip(
r"
items:
- name: demo
desc: |
line1
line2
",
);
}
}
-1
View File
@@ -3,7 +3,6 @@ mod clash;
mod config;
pub(crate) mod dns;
mod encrypt;
pub(crate) mod mihomo_yaml;
mod mixed_port;
mod port;
mod prfitem;
+7 -7
View File
@@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
use crate::core::notify::NoticeStatus;
use crate::core::service::StageRequest;
use crate::{
config::{Config, IProfiles, mihomo_yaml, profiles::save_profiles, runtime::IRuntime},
config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime},
constants::timing,
core::{
handle,
@@ -88,8 +88,8 @@ fn plan_config_application(attempt: &StageAttempt) -> ConfigApplication {
}
}
async fn ask_to_stage(path: &std::path::Path, session: &clash_verge_service_ipc::OwnerSessionProof) -> StageAttempt {
match crate::core::service::stage_runtime_by_service(path, session).await {
async fn ask_to_stage(path: &std::path::Path) -> StageAttempt {
match crate::core::service::stage_runtime_by_service(path).await {
Ok(StageRequest::Answered(outcome)) => StageAttempt::Answered(outcome),
Ok(StageRequest::Refused { code, message }) => {
let message = message.into();
@@ -170,7 +170,7 @@ impl CoreManager {
}
});
let yaml = mihomo_yaml::serialize(clash_config)?;
let yaml = serde_yaml_ng::to_string(clash_config)?;
help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?;
handle::Handle::notice(status, message);
Ok(())
@@ -433,10 +433,10 @@ impl CoreManager {
}
async fn attempt_staging(&self, path: &std::path::Path) -> StageAttempt {
let Ok(session) = crate::core::service::active_service_session() else {
if !crate::core::service::active_service_supports_runtime_staging() {
return StageAttempt::Unsupported;
};
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path, &session)).await
}
stage_with_confirmation(timing::STAGE_CONFIRM_TIMEOUT, || ask_to_stage(path)).await
}
/// Reload the Core from `path`, and replace the Core if it will not take it.
+191 -84
View File
@@ -188,6 +188,48 @@ where
apply_proxy().await
}
#[cfg(any(target_os = "windows", test))]
async fn run_service_start_with_sidecar_fallback<Start, StartFuture, Check, CheckFuture, Fallback, FallbackFuture>(
start_service: Start,
confirm_idle: Check,
start_sidecar: Fallback,
record_unavailable: impl FnOnce(std::string::String),
) -> Result<()>
where
Start: FnOnce() -> StartFuture,
StartFuture: std::future::Future<Output = Result<()>>,
Check: FnOnce() -> CheckFuture,
CheckFuture: std::future::Future<Output = Result<()>>,
Fallback: FnOnce(anyhow::Error) -> FallbackFuture,
FallbackFuture: std::future::Future<Output = Result<()>>,
{
let Err(error) = start_service().await else {
return Ok(());
};
let refusal = error.downcast_ref::<crate::core::service::ServiceStartRefusal>();
let location_refused = refusal.is_some_and(|refusal| {
refusal.code == clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16
});
if refusal.is_some() && !location_refused {
return Err(error);
}
// A lost start response can hide a running core; the shared check must resolve occupancy.
if let Err(probe_error) = confirm_idle().await {
let error = error.context(format!("Sidecar fallback was not safe: {probe_error:#}"));
record_unavailable(format!("{error:#}"));
return Err(error);
}
logging!(
warn,
Type::Core,
"Service could not start the core; falling back to Sidecar: {error:#}"
);
let reason = format!("{error:#}");
start_sidecar(error)
.await
.map_err(|error| error.context(format!("Sidecar fallback failed after Service failure: {reason}")))
}
async fn run_sidecar_termination_transition<Clear, ClearFuture, Terminate, TerminateFuture>(
clear_proxy: Clear,
terminate_sidecar: Terminate,
@@ -266,16 +308,11 @@ where
restore_proxy().await
}
enum UninstallFailure {
Maintenance(anyhow::Error),
Sidecar(anyhow::Error),
}
async fn run_uninstall_transition<Uninstall, UninstallFuture, Prepare, PrepareFuture, Start, StartFuture>(
uninstall: Uninstall,
prepare_sidecar: Prepare,
start_sidecar: Start,
) -> Result<(), UninstallFailure>
) -> Result<()>
where
Uninstall: FnOnce() -> UninstallFuture,
UninstallFuture: std::future::Future<Output = Result<()>>,
@@ -284,12 +321,16 @@ where
Start: FnOnce() -> StartFuture,
StartFuture: std::future::Future<Output = Result<()>>,
{
uninstall().await.map_err(UninstallFailure::Maintenance)?;
prepare_sidecar().await.map_err(UninstallFailure::Sidecar)?;
start_sidecar().await.map_err(UninstallFailure::Sidecar)
uninstall().await?;
prepare_sidecar().await?;
start_sidecar().await
}
fn report_sidecar_failure(error: anyhow::Error) -> anyhow::Error {
fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error {
let error = match service_rejection {
Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
None => error,
};
// Proxy failures have their own pending state and recovery dialog.
if SysproxyFailure::from_chain(&error).is_none() {
crate::core::notification::record_sidecar_failure(format!("{error:#}").into());
@@ -327,11 +368,12 @@ impl CoreManager {
}
#[tracing::instrument(skip_all, level = "info", fields(status = tracing::field::Empty, tun_disabled = false, readiness_generation = tracing::field::Empty))]
pub async fn continue_with_sidecar(&self) -> Result<()> {
pub async fn continue_with_sidecar(&self, service_rejection: Option<&str>) -> Result<()> {
if !self.try_start_config_update() {
return Err(report_sidecar_failure(anyhow::anyhow!(
"configuration update is already running"
)));
return Err(report_sidecar_failure(
anyhow::anyhow!("configuration update is already running"),
service_rejection,
));
}
let _config_update = DropGuard::new((), |()| {
self.finish_config_update();
@@ -348,8 +390,11 @@ impl CoreManager {
if !can_allow_sidecar_for_session(&mode, &status) {
anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}");
}
#[cfg(target_os = "windows")]
if matches!(*mode, RunningMode::NotRunning) {
crate::core::service::release_service_core_for_sidecar().await?;
clash_verge_service_ipc::execution::check_sidecar_available()
.await
.map_err(super::state::explain_core_occupancy)?;
}
if !matches!(status, ServiceStatus::SidecarAllowed) {
SERVICE_MANAGER.allow_sidecar_for_session()?;
@@ -402,7 +447,7 @@ impl CoreManager {
Ok(())
}
.await;
result.map_err(report_sidecar_failure)
result.map_err(|error| report_sidecar_failure(error, service_rejection))
}
#[tracing::instrument(skip_all, level = "info", fields(readiness_generation = tracing::field::Empty))]
@@ -417,8 +462,14 @@ impl CoreManager {
let _config_write = Config::lock_config_write().await;
let _life = self.lifecycle_lock.lock().await;
self.controlled_stop_core_inner().await?;
let result = run_uninstall_transition(
|| self.maintain_service(ServiceStatus::UninstallRequired),
|| async {
SERVICE_MANAGER
.handle_service_status(ServiceStatus::UninstallRequired)
.await
},
|| async {
// Must be asked after the uninstall: until then the Service still makes TUN capable.
let tun_enabled = Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false);
@@ -444,55 +495,12 @@ impl CoreManager {
)
.await;
match result {
Ok(()) => Ok(()),
Err(UninstallFailure::Maintenance(error)) => Err(error),
Err(UninstallFailure::Sidecar(error)) => {
let error = match self.rollback_failed_sidecar_transition().await {
Ok(()) => error,
Err(cleanup) => proxy_control::rollback_failure(error, cleanup),
};
let error = report_sidecar_failure(error.context("Service uninstalled; Sidecar startup failed"));
logging!(warn, Type::Core, "{error:#}");
Ok(())
}
}
}
/// The caller holds the lifecycle lock across both preparation and the privileged operation.
pub(crate) async fn maintain_service(&self, status: ServiceStatus) -> Result<()> {
let mode = *self.get_running_mode();
let uninstall = matches!(status, ServiceStatus::UninstallRequired);
let legacy = (uninstall || mode == RunningMode::Service)
&& matches!(
tokio::time::timeout(std::time::Duration::from_secs(2), clash_verge_service_ipc::get_version()).await,
Ok(Ok(reply)) if reply.code == 0 && reply.data.as_ref().is_some_and(|info| {
info.protocol.epoch == 2 && info.protocol.revision > 0 && !info.build_version.is_empty()
})
);
if legacy && mode == RunningMode::Service {
// The helper stops the old daemon and checks its child under the service owner lock.
#[cfg(target_os = "macos")]
warn_if_guard_lingers(proxy_control::stop_guard().await);
#[cfg(not(target_os = "macos"))]
proxy_control::clear().await?;
} else {
self.controlled_stop_core_inner().await?;
}
if uninstall && !legacy {
crate::core::service::release_service_core_for_sidecar().await?;
}
SERVICE_MANAGER.handle_service_status(status).await?;
if legacy {
crate::core::service::discard_replaced_service_session();
if mode == RunningMode::Service {
// A repaired daemon can restore its core; this GUI must acquire a fresh session.
self.core_stopped();
#[cfg(target_os = "macos")]
if uninstall {
crate::utils::resolve::dns::sync_public_dns().await;
}
if let Err(error) = result {
if let Err(cleanup_error) = self.rollback_failed_sidecar_transition().await {
return Err(proxy_control::rollback_failure(error, cleanup_error)
.context("failed to clear the proxy before rolling back"));
}
return Err(error);
}
Ok(())
}
@@ -630,6 +638,8 @@ impl CoreManager {
self.rollback_failed_start().await;
#[cfg(target_os = "macos")]
crate::utils::resolve::dns::sync_public_dns().await;
#[cfg(target_os = "windows")]
self.try_sidecar_after_service_unavailable().await?;
return Ok(());
}
if Handle::global().is_exiting() {
@@ -638,15 +648,27 @@ impl CoreManager {
}
let result = match startup {
StartupDecision::Service => self.start_core_by_service().await.inspect_err(|error| {
if error
.downcast_ref::<crate::core::service::ServiceStartRefusal>()
.is_none()
StartupDecision::Service => {
#[cfg(target_os = "windows")]
{
crate::core::runstate::RUN_STATE
.observe(crate::core::runstate::ServiceHealth::Unavailable(format!("{error:#}")));
run_service_start_with_sidecar_fallback(
|| self.start_core_by_service(),
|| async {
clash_verge_service_ipc::execution::check_sidecar_available()
.await
.map_err(super::state::explain_core_occupancy)
},
|error| self.start_sidecar_after_service_failure(error),
|reason| {
crate::core::runstate::RUN_STATE
.observe(crate::core::runstate::ServiceHealth::Unavailable(reason));
},
)
.await
}
}),
#[cfg(not(target_os = "windows"))]
self.start_core_by_service().await
}
StartupDecision::Sidecar => self.start_core_by_sidecar().await,
StartupDecision::Wait => Ok(()),
};
@@ -662,6 +684,53 @@ impl CoreManager {
result
}
#[cfg(target_os = "windows")]
async fn try_sidecar_after_service_unavailable(&self) -> Result<()> {
use crate::core::runstate::{RUN_STATE, ServiceHealth};
let state = RUN_STATE.state();
if state.pending.is_some() || state.op_in_flight || Handle::global().is_exiting() {
return Ok(());
}
let reason = match state.health {
ServiceHealth::Unavailable(reason) => reason,
ServiceHealth::VersionMismatch => "registered service is unavailable or incompatible".to_owned(),
_ => return Ok(()),
};
if let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available()
.await
.map_err(super::state::explain_core_occupancy)
{
logging!(
warn,
Type::Core,
"Service unavailable ({reason}); Sidecar fallback withheld: {error:#}"
);
return Ok(());
}
self.start_sidecar_after_service_failure(anyhow::anyhow!(reason)).await
}
#[cfg(target_os = "windows")]
async fn start_sidecar_after_service_failure(&self, error: anyhow::Error) -> Result<()> {
use crate::core::runstate::RUN_STATE;
if Handle::global().is_exiting() {
return Err(error.context("application exited before Sidecar fallback"));
}
let reason = format!("{error:#}");
RUN_STATE.allow_sidecar_after_service_refusal(reason.clone())?;
logging!(warn, Type::Core, "Starting Sidecar with Service unavailable: {reason}");
let result = self.start_core_by_sidecar().await;
if result.is_err() {
SERVICE_MANAGER.withdraw_sidecar_allowance();
self.rollback_failed_start().await;
} else {
crate::core::service::notify_service_fallback(&reason);
}
result.map_err(|error| error.context(format!("Service failure before Sidecar startup: {reason}")))
}
#[tracing::instrument(skip_all, level = "info", fields(mode = ?*self.get_running_mode()))]
pub async fn stop_core(&self) -> Result<()> {
let _life = self.lifecycle_lock.lock().await;
@@ -777,6 +846,13 @@ impl CoreManager {
let is_admin = is_current_app_handle_admin(Handle::app_handle());
if !should_wait_for_service(tun_enabled, service_ready, is_admin) {
if tun_enabled && !service_ready && is_admin {
logging!(
info,
Type::Core,
"service unavailable while app is elevated; starting sidecar immediately"
);
}
return;
}
@@ -789,6 +865,8 @@ impl CoreManager {
return;
}
// Failing to become ready is not fatal here: the caller falls back to Sidecar, and a
// transient transport failure must not overwrite the last confirmed install state.
let attempts = (timing::SERVICE_WAIT_MAX.as_millis() / timing::SERVICE_WAIT_INTERVAL.as_millis()) as usize;
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
@@ -875,18 +953,7 @@ mod tests {
.and_then(|failed| steps.iter().position(|step| *step == failed).map(|index| index + 1))
.unwrap_or(steps.len());
assert_eq!(&*calls.lock(), &steps[..expected_len]);
assert!(
matches!(
(fail_at, result),
(None, Ok(()))
| (Some("uninstall"), Err(super::UninstallFailure::Maintenance(_)))
| (
Some("prepare-sidecar" | "start-sidecar"),
Err(super::UninstallFailure::Sidecar(_))
)
),
"wrong uninstall outcome for {fail_at:?}"
);
assert_eq!(result.is_err(), fail_at.is_some());
}
}
@@ -1343,6 +1410,46 @@ mod tests {
}
}
#[tokio::test]
async fn blocked_windows_fallback_records_failure_without_starting_sidecar() {
use crate::core::runstate::{FakeEnv, RunStateStore, ServiceHealth};
for idle in [false, true] {
let store = RunStateStore::new(FakeEnv::new());
store.observe(ServiceHealth::Ready);
let started = AtomicBool::new(false);
let result = super::run_service_start_with_sidecar_fallback(
|| async {
Err(crate::core::service::ServiceStartRefusal {
code: clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16,
core_path: "verge-mihomo.exe".into(),
message: "no administrator-approved copy is installed".into(),
}
.into())
},
|| async move {
anyhow::ensure!(idle, "another core is running");
Ok(())
},
|_| async {
started.store(true, Ordering::SeqCst);
Ok(())
},
|reason| store.observe(ServiceHealth::Unavailable(reason)),
)
.await;
assert_eq!(started.load(Ordering::SeqCst), idle);
assert_eq!(result.is_ok(), idle);
assert!(!store.state().sidecar_allowed);
if !idle {
assert!(store.state().service_needs_attention());
assert!(!store.state().service_usable());
assert!(result.is_err_and(|error| format!("{error:#}").contains("another core is running")));
}
}
}
#[test]
fn failed_service_install_can_continue_with_an_existing_sidecar() {
assert!(can_allow_sidecar_for_session(
+80 -113
View File
@@ -11,18 +11,30 @@ use crate::{
use anyhow::{Context as _, Result};
use clash_verge_logging::Type;
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
use futures::{FutureExt as _, future::Shared};
use futures::{
FutureExt as _,
future::{Map, Shared},
};
use log::Level;
use std::num::NonZeroUsize;
use std::path::Path;
use std::sync::Arc;
use tauri_plugin_mihomo::MihomoExt as _;
use tauri_plugin_shell::ShellExt as _;
use tauri_plugin_shell::process::CommandChild;
use tokio::sync::oneshot;
use tokio::task::{JoinError, JoinHandle};
pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
let detail = error.to_string();
if detail.starts_with("process verge-mihomo") && detail.ends_with("; refusing a second core") {
error.context(clash_verge_i18n::t!("core.alreadyRunning").into_owned())
} else {
error
}
}
#[cfg(target_os = "windows")]
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
use crate::config::mihomo_yaml;
use serde_yaml_ng::{Mapping, Value};
let mut config: Mapping = serde_yaml_ng::from_str(yaml)?;
@@ -35,7 +47,7 @@ fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
tun.as_mapping_mut()
.context("invalid Sidecar TUN configuration")?
.insert(Value::from("enable"), Value::Bool(false));
Ok(mihomo_yaml::serialize(&config)?)
Ok(serde_yaml_ng::to_string(&config)?)
}
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
@@ -133,10 +145,18 @@ fn should_clear_terminated_sidecar(
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
}
type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc<JoinError>>;
type SidecarExit = Shared<Map<JoinHandle<()>, ShareExitResult>>;
fn share_exit(exit: JoinHandle<()>) -> SidecarExit {
let share_error: ShareExitResult = |result| result.map_err(Arc::new);
exit.map(share_error).shared()
}
#[derive(Debug, Default)]
pub(super) struct SidecarSession {
process: Option<SidecarProcess>,
exit: Option<Shared<oneshot::Receiver<()>>>,
exit: Option<SidecarExit>,
}
#[derive(Debug)]
@@ -174,7 +194,10 @@ impl CoreManager {
#[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))]
pub(super) async fn start_core_by_sidecar(&self) -> Result<()> {
self.wait_for_sidecar_exit().await?;
service::require_service_core_released()?;
let execution = clash_verge_service_ipc::execution::reserve_sidecar()
.await
.inspect_err(service::record_residual_service)
.map_err(explain_core_occupancy)?;
self.core_stopped();
let sidecar_ipc = dirs::sidecar_ipc_path()?;
@@ -197,11 +220,13 @@ impl CoreManager {
#[cfg(unix)]
discard_unwritable_core_cache(&config_dir);
#[cfg(unix)]
let previous_mask = unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) };
let command = app_handle
.shell()
.sidecar(clash_core.as_str())
.map_err(|error| anyhow::anyhow!("failed to build sidecar command for core {clash_core:?}: {error:#}"))?;
let command = command.kill_on_drop(true).args([
let command = command.args([
"-d",
dirs::path_to_str(&config_dir)?,
"-f",
@@ -218,13 +243,6 @@ impl CoreManager {
"LISTEN_NAMEDPIPE_SDDL",
crate::core::owner_identity::current_user_pipe_sddl()?,
);
#[cfg(unix)]
let restore_mask = std::mem::DropGuard::new(
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) },
|mask| {
unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(mask) };
},
);
let (mut rx, child) = command.spawn().map_err(|error| {
anyhow::anyhow!(
"failed to start sidecar core {clash_core:?} with config {} and data directory {}: {error:#}",
@@ -232,10 +250,35 @@ impl CoreManager {
config_dir.display()
)
})?;
let (terminated, termination) = tokio::sync::oneshot::channel();
let exit = execution.release_after_exit(child.pid(), termination);
self.sidecar.lock().exit = Some(share_exit(exit));
#[cfg(target_os = "windows")]
let job = {
match create_and_assign_sidecar_job(child.pid()) {
Ok(job) => job,
Err(job_error) => {
let pid = child.pid();
let error = match child.kill() {
Ok(()) => job_error,
Err(kill_error) => anyhow::anyhow!(
"failed to configure Job Object for sidecar PID {pid}: \
{job_error:#}; failed to terminate child: {kill_error:#}"
),
};
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
return Err(error);
}
}
};
#[cfg(unix)]
drop(restore_mask);
let (terminated, termination) = oneshot::channel();
self.sidecar.lock().exit = Some(termination.shared());
unsafe {
tauri_plugin_clash_verge_sysinfo::libc::umask(previous_mask)
};
let pid = child.pid();
tracing::Span::current().record("pid", pid);
@@ -273,30 +316,6 @@ impl CoreManager {
}
});
#[cfg(target_os = "windows")]
let job = {
match create_and_assign_sidecar_job(child.pid()) {
Ok(job) => job,
Err(job_error) => {
let pid = child.pid();
let error = match child.kill() {
Ok(()) => {
self.sidecar.lock().exit.take();
job_error
}
Err(kill_error) => anyhow::anyhow!(
"failed to configure Job Object for sidecar PID {pid}: \
{job_error:#}; failed to terminate child: {kill_error:#}"
),
};
logging!(error, Type::Core, "Failed to start sidecar: {error:#}");
return Err(error);
}
}
};
let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async {
tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async {
handle::Handle::mihomo().get_version().await
@@ -310,10 +329,7 @@ impl CoreManager {
proxy_control::stop_guard().await;
self.core_stopped();
return match child.kill() {
Ok(()) => {
self.sidecar.lock().exit.take();
Err(readiness_error)
}
Ok(()) => Err(readiness_error),
Err(kill_error) => Err(anyhow::anyhow!(
"{readiness_error:#}; failed to terminate unready sidecar PID {pid}: {kill_error:#}"
)),
@@ -341,11 +357,8 @@ impl CoreManager {
#[cfg(target_os = "windows")]
drop(process.job);
match process.child.kill() {
Ok(()) => {
self.sidecar.lock().exit.take();
}
Err(error) => logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}"),
if let Err(error) = process.child.kill() {
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
}
}
let result = self.wait_for_sidecar_exit().await;
@@ -379,13 +392,12 @@ impl CoreManager {
#[tracing::instrument(skip_all, level = "info", fields(config_file = %config_file.display()))]
pub(super) async fn start_core_by_service_with_config(&self, config_file: &Path) -> Result<()> {
self.wait_for_sidecar_exit().await?;
let start = tokio::sync::OnceCell::new();
// 交接时等待 sidecar 释放 ext-controller 通道。
#[cfg(target_os = "windows")]
{
use crate::constants::timing;
retry_service_start(timing::SERVICE_START_RETRIES, timing::SERVICE_START_RETRY_DELAY, || {
service::run_core_by_service(config_file, &start)
service::run_core_by_service(config_file)
})
.await?;
self.mark_core_ready();
@@ -397,7 +409,7 @@ impl CoreManager {
#[cfg(not(target_os = "windows"))]
{
service::run_core_by_service(config_file, &start).await?;
service::run_core_by_service(config_file).await?;
self.mark_core_ready();
self.core_started(RunningMode::Service);
self.restore_selected_nodes().await;
@@ -543,6 +555,20 @@ mod readiness_tests {
time::Duration,
};
#[test]
fn core_occupancy_explanation_preserves_the_original_error() {
for detail in [
"process verge-mihomo remains after IPC failure; refusing a second core",
"process verge-mihomo-alpha.exe (PID 123) is still running; refusing a second core",
] {
let error = super::explain_core_occupancy(anyhow::anyhow!(detail));
assert_eq!(error.to_string(), clash_verge_i18n::t!("core.alreadyRunning"));
assert_eq!(error.root_cause().to_string(), detail);
}
let error = super::explain_core_occupancy(anyhow::anyhow!("could not inspect remaining cores"));
assert_eq!(error.to_string(), "could not inspect remaining cores");
}
#[tokio::test]
async fn sidecar_readiness_poll_is_bounded_and_accepts_a_real_api_response() -> anyhow::Result<()> {
let attempts = Arc::new(AtomicUsize::new(0));
@@ -703,65 +729,6 @@ mod tests {
Ok(())
}
#[test]
fn forced_parent_exit_releases_the_sidecar_job() -> Result<()> {
use std::io::{BufRead as _, BufReader, Write as _};
use std::os::windows::io::{AsRawHandle as _, FromRawHandle as _, OwnedHandle};
use windows_sys::Win32::{
Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT},
System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},
};
const HELPER: &str = "CVR_TEST_SIDECAR_JOB_PARENT";
if std::env::var_os(HELPER).is_some() {
let mut child = spawn_long_lived()?;
let _job = create_and_assign_sidecar_job(child.id()).inspect_err(|_| {
let _ = child.kill();
let _ = child.wait();
})?;
println!("\nSIDECAR_PID={}", child.id());
std::io::stdout().flush()?;
std::io::stdin().read_line(&mut String::new())?;
return Ok(());
}
let mut parent = std::mem::DropGuard::new(
Command::new(std::env::current_exe()?)
.args(["forced_parent_exit_releases_the_sidecar_job", "--nocapture"])
.env(HELPER, "1")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?,
|mut parent| {
let _ = parent.kill();
let _ = parent.wait();
},
);
let stdout = parent
.stdout
.take()
.ok_or_else(|| anyhow::anyhow!("missing helper stdout"))?;
let mut pid = None;
for line in BufReader::new(stdout).lines() {
if let Some(value) = line?.strip_prefix("SIDECAR_PID=") {
pid = Some(value.parse()?);
break;
}
}
let pid = pid.ok_or_else(|| anyhow::anyhow!("helper did not report its child"))?;
let raw = unsafe { OpenProcess(PROCESS_SYNCHRONIZE, 0, pid) };
anyhow::ensure!(!raw.is_null(), "could not open helper child {pid}");
let child = unsafe { OwnedHandle::from_raw_handle(raw) };
assert_eq!(unsafe { WaitForSingleObject(child.as_raw_handle(), 0) }, WAIT_TIMEOUT);
parent.kill()?;
parent.wait()?;
assert_eq!(
unsafe { WaitForSingleObject(child.as_raw_handle(), 5000) },
WAIT_OBJECT_0
);
Ok(())
}
#[test]
fn returns_err_for_invalid_pid() {
// Windows PIDs are multiples of four; this one is effectively impossible.
+6 -1
View File
@@ -19,6 +19,9 @@ pub enum NoticeStatus {
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")]
@@ -78,13 +81,14 @@ impl NoticeStatus {
/// test both derive their variant list from here; expected strings stay
/// hand-written in the test so renames cannot slip through.
#[cfg(test)]
pub const ALL: [Self; 32] = [
pub const ALL: [Self; 33] = [
Self::ImportSubUrlOk,
Self::ImportSubUrlError,
Self::SetConfigError,
Self::CoreStartError,
Self::ServiceCoreRepairRequired,
Self::ServiceCoreAppDataNotOwned,
Self::ServiceCoreSidecarFallback,
Self::DnsOverrideAutoDisabled,
Self::EnhanceDiscardedKeys,
Self::TunModeAutoDisabled,
@@ -128,6 +132,7 @@ mod tests {
"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",
+2 -2
View File
@@ -390,10 +390,10 @@ fn service_proxy_config(verge: &IVerge, mixed_port: u16, pac_port: u16) -> Resul
/// the write's, so it stays a failure.
fn service_apply_result(requested: &MacosProxyConfig, outcome: ProxyApplyOutcome) -> Result<()> {
match outcome {
ProxyApplyOutcome::Applied => Ok(()),
ProxyApplyOutcome::Applied | ProxyApplyOutcome::NotRequested => Ok(()),
// Direct fallback satisfies a disable request.
ProxyApplyOutcome::DirectFallback { .. } if matches!(requested, MacosProxyConfig::Disabled) => Ok(()),
// The service reports a missing network service as fallback before any OS write.
// Older helpers encode a failed service lookup as fallback even when no OS write occurred.
#[cfg(target_os = "macos")]
ProxyApplyOutcome::DirectFallback { message }
if message == sysproxy::Error::NoActiveNetworkService.to_string() =>
+10 -2
View File
@@ -67,9 +67,17 @@ impl RunStateEnv for RealEnv {
}
async fn trusted_install_evidence(&self) -> Result<bool> {
tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
let registered = tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
.await
.context("service registration probe did not finish")?
.context("service registration probe did not finish")??;
// A helper that outlived its registration is a broken Service, not an absent one.
#[cfg(unix)]
if !registered && let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available().await {
return Ok(error
.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>()
.is_some());
}
Ok(registered)
}
fn is_elevated(&self) -> bool {
+16 -1
View File
@@ -24,7 +24,7 @@ pub use env::FakeEnv;
pub use env::{RealEnv, RunStateEnv};
pub use health::{PendingAction, RunState, RunStateView, ServiceHealth};
pub use owner::{OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch};
pub use probe::{ServiceVersionCheck, ServiceVersionReply, classify_service_version_reply};
pub use probe::{CORE_REJECTED_PREFIX, ServiceVersionCheck, ServiceVersionReply, classify_service_version_reply};
use crate::core::manager::RunningMode;
use health::StoredService;
@@ -336,6 +336,21 @@ impl<E: RunStateEnv> RunStateStore<E> {
Ok(())
}
#[cfg(target_os = "windows")]
pub fn allow_sidecar_after_service_refusal(&self, reason: String) -> Result<()> {
let mut state = self.service.lock();
if state.operation_running || state.service.pending.is_some() {
bail!("cannot fall back while a service operation is pending");
}
// Publish the refusal and allowance together so it never asks the UI for a repair.
state.service.health = ServiceHealth::Unavailable(reason);
state.service.allow_sidecar();
state.bump();
drop(state);
self.announce();
Ok(())
}
/// Requests installation only for a confirmed absent Service.
pub fn require_install_for_session(&self) -> Result<()> {
let mut state = self.service.lock();
+166 -196
View File
@@ -1,7 +1,7 @@
use crate::core::notify::NoticeStatus;
use crate::utils::dirs;
use crate::{
config::{Config, mihomo_yaml, runtime::IRuntime},
config::{Config, runtime::IRuntime},
constants,
core::{
CoreManager,
@@ -10,8 +10,8 @@ use crate::{
owner_identity::current_owner_credentials,
proxy_control,
runstate::{
OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE, ReadyWaitError,
RunState, RunStateEnv, RunStateStore, ServiceHealth,
CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE,
ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth,
},
tray::Tray,
},
@@ -22,9 +22,9 @@ use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging};
use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of};
use clash_verge_service_ipc::{
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProxyApplyOutcome, RemoteProvider,
RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
StageRuntimeOutcome, StartClashRequest, WriterConfig,
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome,
RemoteProvider, RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode,
ServiceStatusSnapshot, StageRuntimeOutcome, StartClashRequest, WriterConfig,
};
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
use clash_verge_task::watch_task;
@@ -44,21 +44,45 @@ use std::{
use tokio::{sync::watch, time::Instant};
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
static PENDING_SERVICE_START: Mutex<Option<PendingServiceStart>> = Mutex::new(None);
static ACTIVE_SERVICE_SESSION: Mutex<Option<Arc<OwnerSessionProof>>> = Mutex::new(None);
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
static PENDING_SERVICE_FALLBACK_NOTICE: Mutex<Option<String>> = Mutex::new(None);
static PENDING_SERVICE_REPAIR_NOTICE: AtomicBool = AtomicBool::new(false);
static PENDING_SERVICE_OWNER_NOTICE: Mutex<Option<String>> = Mutex::new(None);
#[cfg(windows)]
/// Why the Service was unavailable when the core fell back to Sidecar.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, specta::Type)]
#[serde(tag = "kind", content = "reason", rename_all = "camelCase")]
pub enum ServiceFallbackNotice {
Unavailable,
CoreRejected(String),
NotAutoStarted,
}
/// The release installer registers AutoStart.
const SERVICE_NOT_AUTO_STARTED: &str = "the Windows service is stopped and no longer starts with Windows";
#[cfg(windows)]
pub(crate) fn is_not_auto_started(reason: &str) -> bool {
// Detection prefixes its own context to the reason.
reason.contains(SERVICE_NOT_AUTO_STARTED)
}
#[cfg(target_os = "windows")]
pub(crate) fn notify_service_fallback(reason: &str) {
*PENDING_SERVICE_FALLBACK_NOTICE.lock() = Some(reason.to_owned());
Handle::notice(NoticeStatus::ServiceCoreSidecarFallback, "");
}
pub(crate) fn take_service_fallback_notice() -> Option<ServiceFallbackNotice> {
let reason = PENDING_SERVICE_FALLBACK_NOTICE.lock().take()?;
Some(if reason.starts_with(CORE_REJECTED_PREFIX) {
ServiceFallbackNotice::CoreRejected(reason)
} else if is_not_auto_started(&reason) {
ServiceFallbackNotice::NotAutoStarted
} else {
ServiceFallbackNotice::Unavailable
})
}
pub(crate) fn take_service_repair_notice() -> bool {
PENDING_SERVICE_REPAIR_NOTICE.swap(false, Ordering::Relaxed)
}
@@ -76,27 +100,14 @@ fn app_data_owner_command(credentials: &OwnerCredentials) -> Option<String> {
Some(format!("sudo chown -R {uid}:{gid} '{path}'"))
}
/// Capabilities of the service session that owns the running Core.
/// They are discarded with that session rather than cached across service upgrades.
#[derive(Clone)]
struct PendingServiceStart {
token: String,
service_replaced: bool,
}
impl PendingServiceStart {
const fn new(token: String) -> Self {
Self {
token,
service_replaced: false,
}
}
const fn released_after_repair(&self, status: &ServiceStatusSnapshot) -> bool {
self.service_replaced
&& !status.is_active
&& status.active_generation.is_none()
&& status.core_pid.is_none()
&& !status.desired_core_should_be_running
}
struct ActiveServiceSession {
proof: Arc<OwnerSessionProof>,
supports_runtime_staging: bool,
supports_runtime_file_read: bool,
supports_runtime_geo_read: bool,
}
fn generate_service_session_token() -> Result<String> {
@@ -114,14 +125,89 @@ fn generate_service_session_token() -> Result<String> {
pub(crate) fn active_service_session() -> Result<Arc<OwnerSessionProof>> {
ACTIVE_SERVICE_SESSION
.lock()
.clone()
.as_ref()
.map(|session| Arc::clone(&session.proof))
.context("service owner session is not active")
}
/// Returns false unless the active service session explicitly supports in-place staging.
pub(crate) fn active_service_supports_runtime_staging() -> bool {
ACTIVE_SERVICE_SESSION
.lock()
.as_ref()
.is_some_and(|session| session.supports_runtime_staging)
}
pub(crate) fn active_service_supports_runtime_file_read() -> bool {
ACTIVE_SERVICE_SESSION
.lock()
.as_ref()
.is_some_and(|session| session.supports_runtime_file_read)
}
fn active_service_supports_runtime_geo_read() -> bool {
ACTIVE_SERVICE_SESSION
.lock()
.as_ref()
.is_some_and(|session| session.supports_runtime_geo_read)
}
pub(crate) fn clear_active_service_session() {
ACTIVE_SERVICE_SESSION.lock().take();
}
#[derive(Clone, Copy, Default)]
struct ServiceCapabilities {
runtime_staging: bool,
runtime_file_read: bool,
runtime_geo_read: bool,
}
impl ServiceCapabilities {
const fn of(info: &ProtocolInfo) -> Self {
Self {
runtime_staging: info.supports_runtime_staging(),
runtime_file_read: info.supports_runtime_file_read(),
runtime_geo_read: info.supports_runtime_geo_read(),
}
}
}
/// Failed capability probes must not block startup.
#[tracing::instrument(skip_all, level = "info", fields(supported = tracing::field::Empty))]
async fn probe_service_capabilities() -> ServiceCapabilities {
match clash_verge_service_ipc::get_version().await {
Ok(response) if response.code == 0 => {
let capabilities = response
.data
.as_ref()
.map_or_else(ServiceCapabilities::default, ServiceCapabilities::of);
tracing::Span::current().record("supported", capabilities.runtime_staging);
capabilities
}
Ok(response) => {
tracing::Span::current().record("supported", false);
logging!(
warn,
Type::Service,
"服务协议查询返回 {}: {};配置变更将走重启路径",
response.code,
response.message
);
ServiceCapabilities::default()
}
Err(error) => {
tracing::Span::current().record("supported", false);
logging!(
warn,
Type::Service,
"无法查询服务协议版本: {error:#};配置变更将走重启路径"
);
ServiceCapabilities::default()
}
}
}
fn session_matches_status(proof: &OwnerSessionProof, is_active: bool, active_generation: Option<u64>) -> bool {
is_active && active_generation == Some(proof.generation)
}
@@ -514,26 +600,7 @@ pub(crate) fn run_privileged_service_action(action: PendingAction) -> Result<()>
PendingAction::Reinstall => (reinstall_service, "reinstall service"),
PendingAction::ForceReinstall => (force_reinstall_service, "force reinstall service"),
};
tokio::task::block_in_place(|| {
let pending_token = match action {
PendingAction::Reinstall | PendingAction::ForceReinstall => PENDING_SERVICE_START
.lock()
.as_ref()
.map(|pending| pending.token.clone()),
PendingAction::Install | PendingAction::Uninstall => None,
};
operation().with_context(|| format!("{label} failed"))?;
// Full repair acquires the stopped-service guard before replacing the daemon.
if let Some(token) = pending_token
&& let Some(pending) = PENDING_SERVICE_START
.lock()
.as_mut()
.filter(|pending| pending.token == token)
{
pending.service_replaced = true;
}
Ok(())
})
tokio::task::block_in_place(operation).with_context(|| format!("{label} failed"))
}
/// Builds the same runtime bundle description for both service start and staging.
@@ -546,7 +613,7 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result<RuntimeBun
let bin_path = service_core_path(&clash_core, bin_ext)?;
let plan = collect_runtime_bundle(config_file).await?;
Ok(RuntimeBundle {
yaml: mihomo_yaml::serialize(&plan.config).context("failed to serialize service runtime config")?,
yaml: serde_yaml_ng::to_string(&plan.config).context("failed to serialize service runtime config")?,
assets: plan
.assets
.into_iter()
@@ -581,11 +648,12 @@ impl StageRequest {
}
/// Requests in-place staging. `Err` means no answer; refusals are returned for caller policy.
pub(super) async fn stage_runtime_by_service(config_file: &Path, session: &OwnerSessionProof) -> Result<StageRequest> {
pub(super) async fn stage_runtime_by_service(config_file: &Path) -> Result<StageRequest> {
let session = active_service_session()?;
let credentials = current_owner_credentials()?;
let runtime = collect_service_runtime_bundle(config_file).await?;
let response = clash_verge_service_ipc::stage_runtime(&credentials, session, &runtime)
let response = clash_verge_service_ipc::stage_runtime(&credentials, &session, &runtime)
.await
.context("无法连接到Clash Verge Service")?;
if response.code > 0 {
@@ -632,92 +700,27 @@ fn record_service_start_refusal<E: RunStateEnv>(
refusal.into()
}
pub(super) fn discard_replaced_service_session() {
cancel_owner_monitors();
PENDING_SERVICE_START.lock().take();
clear_active_service_session();
}
pub(super) fn require_service_core_released() -> Result<()> {
anyhow::ensure!(
PENDING_SERVICE_START.lock().is_none() && ACTIVE_SERVICE_SESSION.lock().is_none(),
"the previous Service core has not confirmed exit"
);
Ok(())
}
pub(super) async fn release_service_core_for_sidecar() -> Result<()> {
let pending = PENDING_SERVICE_START.lock().clone();
if pending.is_none() {
if active_service_session().is_ok() {
return stop_core_by_service().await;
}
if matches!(RUN_STATE.state().health, ServiceHealth::NotInstalled) {
return Ok(());
}
/// Sidecar stays blocked until a reinstall replaces the residual helper, so ask for repair.
pub(super) fn record_residual_service(error: &anyhow::Error) {
if let Some(residual) = error.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>() {
RUN_STATE.observe(ServiceHealth::Unavailable(residual.to_string()));
}
let credentials = current_owner_credentials()?;
let status = tokio::time::timeout(
Duration::from_secs(2),
clash_verge_service_ipc::get_status(&credentials),
)
.await
.context("timed out confirming the previous Service core exited")??;
anyhow::ensure!(status.code == 0, "Service status failed: {}", status.message);
let status = status.data.context("Service omitted owner status")?;
let Some(pending) = pending else {
anyhow::ensure!(
!status.is_active || (status.core_pid.is_none() && !status.desired_core_should_be_running),
"the Service is running or recovering this owner's core; stop it before switching"
);
return Ok(());
};
if pending.released_after_repair(&status) {
PENDING_SERVICE_START.lock().take();
clear_active_service_session();
return Ok(());
}
// A lost Start reply may have committed. Only its proposed token can stop that generation.
let generation = status
.active_generation
.context("the previous Service start has not confirmed exit; repair the Service before switching")?;
let stopped = clash_verge_service_ipc::stop_clash(
&credentials,
&OwnerSessionProof {
generation,
token: pending.token,
},
)
.await?;
anyhow::ensure!(
stopped.code == 0,
"could not confirm Service core exit: {}",
stopped.message
);
PENDING_SERVICE_START.lock().take();
clear_active_service_session();
Ok(())
}
/// 尝试使用服务启动core
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
async fn start_with_existing_service(
config_file: &Path,
start: &tokio::sync::OnceCell<StartClashRequest>,
) -> Result<()> {
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, staging = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()> {
clear_active_service_session();
let credentials = current_owner_credentials()?;
let request = start
.get_or_try_init(|| async {
Ok::<_, anyhow::Error>(StartClashRequest {
runtime: collect_service_runtime_bundle(config_file).await?,
proposed_session_token: generate_service_session_token()?,
})
})
.await?;
let previous = PENDING_SERVICE_START
.lock()
.replace(PendingServiceStart::new(request.proposed_session_token.clone()));
let response = match clash_verge_service_ipc::start_clash(&credentials, request).await {
let runtime = collect_service_runtime_bundle(config_file).await?;
let request = StartClashRequest {
runtime,
proposed_session_token: generate_service_session_token()?,
macos_proxy: None,
};
let response = match clash_verge_service_ipc::start_clash(&credentials, &request).await {
Ok(response) => response,
Err(error) => {
tracing::Span::current().record("outcome", "ipc-unreachable");
@@ -729,16 +732,6 @@ async fn start_with_existing_service(
if response.code > 0 {
tracing::Span::current().record("code", response.code);
tracing::Span::current().record("outcome", "refused");
if matches!(response.code,
code if code == ServiceErrorCode::InvalidInstallLocation as u16
|| code == ServiceErrorCode::InvalidRuntimeAsset as u16
|| code == ServiceErrorCode::AppDataRootNotOwned as u16
|| code == ServiceErrorCode::UnauthorizedOwner as u16
|| code == ServiceErrorCode::ProtocolMismatch as u16
|| code == ServiceErrorCode::ProxyClearFailed as u16
) {
*PENDING_SERVICE_START.lock() = previous;
}
let err_msg = response.message;
logging!(
error,
@@ -761,39 +754,43 @@ async fn start_with_existing_service(
&RUN_STATE,
ServiceStartRefusal {
code: response.code,
core_path: request.runtime.core_path.clone(),
core_path: request.runtime.core_path,
message: err_msg,
},
));
}
let result = response.data.context("Clash Verge Service 未返回会话信息")?;
tracing::Span::current().record("generation", result.generation);
*ACTIVE_SERVICE_SESSION.lock() = Some(Arc::new(OwnerSessionProof {
generation: result.generation,
token: request.proposed_session_token.clone(),
}));
tracing::Span::current().record("generation", result.session.generation);
let capabilities = probe_service_capabilities().await;
tracing::Span::current().record("staging", capabilities.runtime_staging);
*ACTIVE_SERVICE_SESSION.lock() = Some(ActiveServiceSession {
proof: Arc::new(OwnerSessionProof {
generation: result.session.generation,
token: request.proposed_session_token,
}),
supports_runtime_staging: capabilities.runtime_staging,
supports_runtime_file_read: capabilities.runtime_file_read,
supports_runtime_geo_read: capabilities.runtime_geo_read,
});
PENDING_SERVICE_START.lock().take();
// PAC follows the Running Mode; the caller opens it via `core_started(Service)`.
start_owner_monitor();
tracing::Span::current().record("outcome", "started");
PENDING_SERVICE_FALLBACK_NOTICE.lock().take();
PENDING_SERVICE_REPAIR_NOTICE.store(false, Ordering::Relaxed);
PENDING_SERVICE_OWNER_NOTICE.lock().take();
logging!(
info,
Type::Service,
"服务成功启动核心 (session generation {})",
result.generation
result.session.generation
);
Ok(())
}
// 以服务启动core
pub(super) async fn run_core_by_service(
config_file: &Path,
start: &tokio::sync::OnceCell<StartClashRequest>,
) -> Result<()> {
pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> {
SERVICE_MANAGER.refresh().await?;
let status = SERVICE_MANAGER.current().await;
@@ -802,7 +799,7 @@ pub(super) async fn run_core_by_service(
}
logging!(info, Type::Service, "服务已运行且版本匹配,直接使用");
start_with_existing_service(config_file, start).await
start_with_existing_service(config_file).await
}
async fn capture_generation_before<F, Fut, T>(generation: &AtomicU64, operation: F) -> (u64, T)
@@ -959,10 +956,11 @@ type ProviderLoadTimes = HashMap<(&'static str, String), Option<u64>>;
#[tracing::instrument(level = "info", fields(synced = tracing::field::Empty, pending = tracing::field::Empty))]
async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
let Ok(session) = active_service_session() else {
if !active_service_supports_runtime_file_read() {
return Ok(ProviderSync::default());
};
}
let credentials = current_owner_credentials()?;
let session = active_service_session()?;
let app_dir = dirs::app_home_dir()?;
let runtime = Config::runtime().await;
let mut outcome = ProviderSync::default();
@@ -1048,10 +1046,14 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
/// Pulls geo databases the service core rewrote, because validation reads the app dir.
pub(crate) async fn sync_runtime_geo_by_service() {
let Ok(session) = active_service_session() else {
if !active_service_supports_runtime_geo_read() {
return;
};
let (Ok(credentials), Ok(app_dir)) = (current_owner_credentials(), dirs::app_home_dir()) else {
}
let (Ok(credentials), Ok(session), Ok(app_dir)) = (
current_owner_credentials(),
active_service_session(),
dirs::app_home_dir(),
) else {
return;
};
for asset in GEO_ASSETS {
@@ -1639,7 +1641,7 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
ACTIVE_SERVICE_SESSION
.lock()
.as_ref()
.is_some_and(|session| session_matches_status(session, is_active, active_generation))
.is_some_and(|session| session_matches_status(&session.proof, is_active, active_generation))
}
fn cancel_owner_monitors() {
@@ -1707,11 +1709,6 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
if policy.reset_system_proxy {
clear_proxy_after_owner_loss().await;
}
if matches!(reason, OwnerRecoveryReason::TransportFailure)
&& let Ok(session) = active_service_session()
{
*PENDING_SERVICE_START.lock() = Some(PendingServiceStart::new(session.token.clone()));
}
clear_active_service_session();
CoreManager::global().core_stopped();
// A displaced Service may still run TUN for its new owner, and DNS settings are system-wide.
@@ -1998,33 +1995,6 @@ mod tests {
ServiceStatus::from_run_state(&store.settled().await)
}
#[test]
fn an_idle_snapshot_releases_an_ambiguous_start_only_after_repair() {
let mut pending = super::PendingServiceStart::new("lost-reply".into());
let mut status = clash_verge_service_ipc::ServiceStatusSnapshot {
is_active: false,
active_generation: None,
core_pid: None,
desired_core_should_be_running: false,
service_state: clash_verge_service_ipc::ServiceLifecycleState::Running,
core_started_at: None,
last_core_exit_reason: None,
restart_count: 0,
last_recovery_at: None,
desired_generation: 0,
desired_updated_at: 0,
desired_persistence_error: None,
};
assert!(!pending.released_after_repair(&status));
pending.service_replaced = true;
assert!(pending.released_after_repair(&status));
status.active_generation = Some(1);
assert!(!pending.released_after_repair(&status));
status.active_generation = None;
status.desired_core_should_be_running = true;
assert!(!pending.released_after_repair(&status));
}
#[test]
fn mismatched_active_generation_displaces_local_session() {
let proof = OwnerSessionProof {
+77 -292
View File
@@ -9,13 +9,13 @@ use anyhow::{Context as _, Result};
use clash_verge_draft::Draft;
use clash_verge_logging::{Type, logging, logging_error};
use clash_verge_profile::SubscriptionSchedule as TaskSchedule;
use futures::{FutureExt as _, StreamExt as _};
use clash_verge_task::timers::{KeyedTimers, TimerChange, TimerPlan};
use futures::FutureExt as _;
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
use tokio::{
sync::{mpsc, oneshot},
time::{sleep, timeout},
};
use tokio_util::time::{DelayQueue, delay_queue::Key};
use tristr::alias::String;
enum TimerCommand {
@@ -25,15 +25,6 @@ enum TimerCommand {
TaskFinished(String),
}
struct TaskState {
key: Option<Key>,
interval_minutes: u64,
running: bool,
/// Disabled mid-update. Entry outlives removal so re-enabling reuses the `running` guard
/// instead of building a fresh state that would fire a second update at zero delay.
retired: bool,
}
async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Finished, Completed, Output>(
update_started: Started,
update_profile: Update,
@@ -52,17 +43,6 @@ async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Fini
update_completed();
}
impl TaskState {
const fn new(key: Option<Key>, interval_minutes: u64) -> Self {
Self {
key,
interval_minutes,
running: false,
retired: false,
}
}
}
pub struct Timer {
command_tx: mpsc::UnboundedSender<TimerCommand>,
}
@@ -116,15 +96,15 @@ impl Timer {
command_tx: mpsc::UnboundedSender<TimerCommand>,
profiles: Draft<IProfiles>,
) {
let mut queue = DelayQueue::new();
let mut tasks = HashMap::new();
let mut timers = KeyedTimers::<String>::new();
let mut initialized = false;
loop {
tokio::select! {
Some(expired) = queue.next(), if initialized => {
let uid = expired.into_inner();
Self::run_expired_task(&mut tasks, uid, command_tx.clone());
Some(expired) = timers.next_expired(), if initialized => {
if timers.start(&expired) {
Self::spawn_update_task(expired, command_tx.clone());
}
}
command = command_rx.recv() => {
@@ -135,8 +115,8 @@ impl Timer {
// timestamps when the queue first becomes eligible to fire.
let profiles = profiles.data_arc();
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), true);
tasks.clear();
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
timers.clear();
Self::log_changes(&schedule, timers.apply(Self::plans(&schedule)));
initialized = true;
logging!(info, Type::Timer, "Timer initialization completed");
}
@@ -146,21 +126,20 @@ impl Timer {
let profiles = profiles.data_arc();
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), false);
if initialized {
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
Self::log_changes(&schedule, timers.apply(Self::plans(&schedule)));
} else {
tasks = schedule
.into_iter()
.map(|(uid, schedule)| (uid, TaskState::new(None, schedule.interval_minutes)))
.collect();
timers.apply(Self::plans(&schedule));
}
let _ = reply.send(());
}
Some(TimerCommand::NextUpdateTime(uid, reply)) => {
let next = Self::next_update_time(&tasks, &profiles.latest_arc(), &uid);
let next = Self::next_update_time(&timers, &profiles.latest_arc(), &uid);
let _ = reply.send(next);
}
Some(TimerCommand::TaskFinished(uid)) => {
Self::finish_task(&mut queue, &mut tasks, uid);
if timers.finish(&uid) {
logging!(debug, Type::Timer, "Dropped retired timer task now that its update finished: uid={uid}");
}
}
None => break,
}
@@ -169,128 +148,63 @@ impl Timer {
}
}
fn apply_timer_map(
queue: &mut DelayQueue<String>,
tasks: &mut HashMap<String, TaskState>,
new_map: HashMap<String, TaskSchedule>,
) {
tasks.retain(|uid, state| {
if new_map.contains_key(uid) {
return true;
}
if let Some(key) = state.key.take() {
queue.remove(&key);
}
if state.running {
state.retired = true;
logging!(
debug,
Type::Timer,
"Retiring timer task once its in-flight update reports back: uid={}",
uid
);
return true;
}
logging!(debug, Type::Timer, "Removed timer task for uid={}", uid);
false
});
for (uid, schedule) in new_map {
let Some(state) = tasks.get_mut(&uid) else {
Self::insert_task(queue, tasks, uid, &schedule);
continue;
};
// Re-enabled before retirement took effect; finish_task re-arms it.
state.retired = false;
if state.interval_minutes == schedule.interval_minutes {
continue;
}
Self::update_task_interval(queue, &uid, state, &schedule);
}
fn plans(schedule: &HashMap<String, TaskSchedule>) -> HashMap<String, TimerPlan> {
schedule
.iter()
.map(|(uid, schedule)| {
(
uid.clone(),
TimerPlan {
first_delay: schedule.first_delay,
interval: TaskSchedule::interval_duration(schedule.interval_minutes),
},
)
})
.collect()
}
fn insert_task(
queue: &mut DelayQueue<String>,
tasks: &mut HashMap<String, TaskState>,
uid: String,
schedule: &TaskSchedule,
) {
let key = Self::schedule_task(queue, &uid, schedule.first_delay);
logging!(
debug,
Type::Timer,
"Added timer task: uid={}, interval={}min, first fire in {}s",
uid,
schedule.interval_minutes,
schedule.first_delay.as_secs()
);
tasks.insert(uid, TaskState::new(Some(key), schedule.interval_minutes));
}
fn update_task_interval(queue: &mut DelayQueue<String>, uid: &str, state: &mut TaskState, schedule: &TaskSchedule) {
state.interval_minutes = schedule.interval_minutes;
if let Some(key) = state.key.as_ref() {
queue.reset(key, schedule.first_delay);
} else if !state.running {
state.key = Some(Self::schedule_task(queue, uid, schedule.first_delay));
fn log_changes(schedule: &HashMap<String, TaskSchedule>, changes: Vec<TimerChange<String>>) {
for change in changes {
match change {
TimerChange::Retired(uid) => {
logging!(
debug,
Type::Timer,
"Retiring timer task once its in-flight update reports back: uid={}",
uid
);
}
TimerChange::Removed(uid) => {
logging!(debug, Type::Timer, "Removed timer task for uid={}", uid);
}
TimerChange::Added(uid) => {
let Some(schedule) = schedule.get(&uid) else {
continue;
};
logging!(
debug,
Type::Timer,
"Added timer task: uid={}, interval={}min, first fire in {}s",
uid,
schedule.interval_minutes,
schedule.first_delay.as_secs()
);
}
TimerChange::Updated(uid) => {
let Some(schedule) = schedule.get(&uid) else {
continue;
};
logging!(
debug,
Type::Timer,
"Updated timer task interval: uid={}, interval={}min, next fire in {}s",
uid,
schedule.interval_minutes,
schedule.first_delay.as_secs()
);
}
}
}
logging!(
debug,
Type::Timer,
"Updated timer task interval: uid={}, interval={}min, next fire in {}s",
uid,
schedule.interval_minutes,
schedule.first_delay.as_secs()
);
}
fn run_expired_task(
tasks: &mut HashMap<String, TaskState>,
uid: String,
command_tx: mpsc::UnboundedSender<TimerCommand>,
) {
let Some(state) = tasks.get_mut(&uid) else {
return;
};
state.key = None;
if state.running {
return;
}
state.running = true;
Self::spawn_update_task(uid, command_tx);
}
fn finish_task(queue: &mut DelayQueue<String>, tasks: &mut HashMap<String, TaskState>, uid: String) {
let Some(state) = tasks.get_mut(&uid) else {
return;
};
state.running = false;
if state.retired {
tasks.remove(&uid);
logging!(
debug,
Type::Timer,
"Dropped retired timer task now that its update finished: uid={}",
uid
);
return;
}
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
// counting from it would retry at zero delay and spin.
let key = Self::schedule_task(queue, &uid, TaskSchedule::interval_duration(state.interval_minutes));
state.key = Some(key);
}
fn spawn_update_task(uid: String, command_tx: mpsc::UnboundedSender<TimerCommand>) {
@@ -302,10 +216,6 @@ impl Timer {
});
}
fn schedule_task(queue: &mut DelayQueue<String>, uid: &str, delay: Duration) -> Key {
queue.insert(String::from(uid), delay)
}
pub async fn get_next_update_time(&self, uid: &str) -> Option<i64> {
let (reply, result) = oneshot::channel();
self.command_tx
@@ -314,10 +224,15 @@ impl Timer {
result.await.ok().flatten()
}
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
let task = tasks.get(uid).filter(|task| !task.retired)?;
fn next_update_time(timers: &KeyedTimers<String>, profiles: &IProfiles, uid: &str) -> Option<i64> {
let updated = profiles.get_item(uid).ok()?.updated;
TaskSchedule::reported_deadline(task.interval_minutes, updated)
TaskSchedule::reported_deadline(Self::minutes(timers.interval(uid)?)?, updated)
}
/// A saturated interval is not a whole number of minutes, so the query stays unanswered as before.
const fn minutes(interval: Duration) -> Option<u64> {
let secs = interval.as_secs();
if secs.is_multiple_of(60) { Some(secs / 60) } else { None }
}
fn emit_update_event(uid: &str, is_start: bool) {
@@ -364,9 +279,7 @@ impl Timer {
mod tests {
use super::{TaskSchedule, Timer, run_timer_profile_update_transition};
use crate::config::{PrfItem, PrfOption};
use futures::StreamExt as _;
use parking_lot::Mutex;
use std::collections::HashMap;
use std::{
sync::{
Arc,
@@ -376,8 +289,6 @@ mod tests {
time::Duration,
};
use tokio::sync::Barrier;
use tokio_util::time::DelayQueue;
use tristr::alias::String;
struct CancellationProbe {
cancelled: Arc<AtomicBool>,
@@ -469,132 +380,6 @@ mod tests {
);
}
/// Polled, not awaited: a not-yet-due entry would park the test on the paused clock.
async fn take_expired(queue: &mut DelayQueue<String>) -> Option<String> {
match futures::poll!(Box::pin(queue.next())) {
Poll::Ready(Some(expired)) => Some(expired.into_inner()),
_ => None,
}
}
/// What `run_expired_task` does, minus spawning the real update.
fn mark_running(tasks: &mut HashMap<String, super::TaskState>, uid: &str) {
assert!(tasks.contains_key(uid), "task {uid} must exist before it can run");
if let Some(state) = tasks.get_mut(uid) {
state.key = None;
state.running = true;
}
}
/// Empty queue reports `Ready(None)`, not `Pending`, so both count as "nothing due".
async fn nothing_due(queue: &mut DelayQueue<String>) -> bool {
matches!(
futures::poll!(Box::pin(queue.next())),
Poll::Pending | Poll::Ready(None)
)
}
#[tokio::test(start_paused = true)]
async fn queue_fires_at_the_remaining_time_then_waits_a_whole_interval() {
const NOW: i64 = 1_700_000_000;
let mut queue = DelayQueue::new();
let mut tasks = HashMap::new();
// 1439min into a 1440min interval: due in a minute, not a day.
let mut map = HashMap::new();
map.insert(
String::from("uid"),
TaskSchedule::new(1440, Some((NOW - 1439 * 60) as usize), NOW),
);
Timer::apply_timer_map(&mut queue, &mut tasks, map);
tokio::time::advance(Duration::from_secs(61)).await;
assert_eq!(
take_expired(&mut queue).await.as_deref(),
Some("uid"),
"the raised interval must fire one minute in, not a full day in"
);
// After it reports back, the next one is a whole interval away.
mark_running(&mut tasks, "uid");
Timer::finish_task(&mut queue, &mut tasks, String::from("uid"));
tokio::time::advance(Duration::from_secs(1439 * 60)).await;
assert!(
nothing_due(&mut queue).await,
"a finished task waits the whole interval, not the remainder of the old one"
);
tokio::time::advance(Duration::from_secs(120)).await;
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
}
#[tokio::test(start_paused = true)]
async fn disabling_a_profile_mid_update_cannot_start_a_second_one() {
const NOW: i64 = 1_700_000_000;
let mut queue = DelayQueue::new();
let mut tasks = HashMap::new();
// Overdue: every re-insert would land at zero delay.
let schedule = || TaskSchedule::new(60, Some((NOW - 7200) as usize), NOW);
let mut map = HashMap::new();
map.insert(String::from("uid"), schedule());
Timer::apply_timer_map(&mut queue, &mut tasks, map);
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
mark_running(&mut tasks, "uid");
// Toggled off then on while the run is still in flight.
Timer::apply_timer_map(&mut queue, &mut tasks, HashMap::new());
let mut back_on = HashMap::new();
back_on.insert(String::from("uid"), schedule());
Timer::apply_timer_map(&mut queue, &mut tasks, back_on);
assert!(
tasks.get("uid").is_some_and(|state| state.running),
"the entry must survive the toggle so the in-flight run is still accounted for"
);
assert!(
nothing_due(&mut queue).await,
"re-enabling must not queue a second run alongside the one already going"
);
// Original run reports back, re-arms exactly once.
Timer::finish_task(&mut queue, &mut tasks, String::from("uid"));
tokio::time::advance(Duration::from_secs(3601)).await;
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
assert!(nothing_due(&mut queue).await, "exactly one key, no orphan");
}
#[tokio::test(start_paused = true)]
async fn a_profile_disabled_mid_update_is_dropped_when_it_reports_back() {
const NOW: i64 = 1_700_000_000;
let mut queue = DelayQueue::new();
let mut tasks = HashMap::new();
let mut map = HashMap::new();
map.insert(
String::from("uid"),
TaskSchedule::new(60, Some((NOW - 7200) as usize), NOW),
);
Timer::apply_timer_map(&mut queue, &mut tasks, map);
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
mark_running(&mut tasks, "uid");
Timer::apply_timer_map(&mut queue, &mut tasks, HashMap::new());
Timer::finish_task(&mut queue, &mut tasks, String::from("uid"));
assert!(
tasks.is_empty(),
"a task retired mid-update must not outlive the update"
);
tokio::time::advance(Duration::from_secs(7200)).await;
assert!(nothing_due(&mut queue).await, "and must never be scheduled again");
}
#[tokio::test(start_paused = true)]
async fn timer_profile_update_runs_past_former_deadline_and_pairs_events() -> anyhow::Result<()> {
let calls = Arc::new(Mutex::new(Vec::new()));
+3 -3
View File
@@ -1,7 +1,7 @@
mod chain;
use self::chain::load_chain_item;
use crate::config::dns::{DnsOverrideState, dns_override_source};
use crate::config::dns::DnsOverrideState;
use crate::core::handle::Handle;
use crate::core::notify::NoticeStatus;
use crate::utils::dirs;
@@ -12,7 +12,7 @@ use crate::{
};
use anyhow::{Context as _, Result};
use clash_verge_config_render::{
ChainItem, ChainType, RenderProfile, RenderSettings, RenderedConfig, ResultLog, SeqMap, render,
ChainItem, ChainType, RenderProfile, RenderSettings, RenderedConfig, ResultLog, SeqMap, override_source, render,
};
use parking_lot::Mutex;
use serde_yaml_ng::Mapping;
@@ -253,7 +253,7 @@ pub async fn render_runtime_config(
let profile = collect_profile_items(profiles).await?;
let dns_override = DnsOverrideState::new(
profile_uid,
dns_override_source(profile_uid, &profile.config)?,
override_source(profile_uid, &profile.config)?,
settings.enable_dns_settings,
settings.dns_override_confirmation,
);
+3 -2
View File
@@ -1,5 +1,6 @@
use crate::core::notify::{Refresh, announce};
use anyhow::{Result, ensure};
use clash_verge_config_render::override_source;
use clash_verge_draft::DraftTransaction;
use serde::Serialize;
use tristr::alias::String;
@@ -7,7 +8,7 @@ use tristr::alias::String;
use crate::{
config::{
Config,
dns::{ProfileDnsSettings, dns_override_source},
dns::ProfileDnsSettings,
profiles::{PROFILE_WRITE_LOCK, current_mapping},
},
constants::files::DNS_CONFIG,
@@ -34,7 +35,7 @@ pub async fn set_dns_override(
profiles.current.as_ref() == Some(&profile_uid),
"The active profile changed; retry the DNS setting"
);
let source = dns_override_source(
let source = override_source(
profiles.current.as_deref().unwrap_or_default(),
&current_mapping(&profiles).await?,
)?;
+1
View File
@@ -51,6 +51,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
cmd::apply_dns_config,
cmd::set_dns_override,
cmd::take_dns_override_notice,
cmd::take_service_fallback_notice,
cmd::get_core_startup_error,
cmd::take_service_repair_notice,
cmd::take_service_owner_notice,
+3 -97
View File
@@ -44,7 +44,7 @@ pub async fn read_mapping(path: &Path) -> Result<Mapping> {
}
fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
match parse_short_id_text(&yaml_str, &path) {
match clash_verge_config_render::parse_short_id_safe(&yaml_str, &path) {
Ok(mut val) => {
val.apply_merge()
.with_context(|| format!("failed to apply merge \"{}\"", path.display()))?;
@@ -65,74 +65,6 @@ fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
}
}
/// A float like `1234e123` loses its hex text, so retry with short-ids quoted and keep that only if nothing else changed.
fn parse_short_id_text(yaml: &str, path: &Path) -> serde_yaml_ng::Result<Value> {
let value = serde_yaml_ng::from_str::<Value>(yaml)?;
if !has_numeric_short_id(&value) {
return Ok(value);
}
match serde_yaml_ng::from_str::<Value>(&quote_short_ids(yaml)) {
Ok(quoted) if same_except_short_id(&value, &quoted) => Ok(quoted),
_ => {
logging!(warn, Type::Config, "kept numeric short-id in {}", path.display());
Ok(value)
}
}
}
fn quote_short_ids(yaml: &str) -> String {
let mut quoted = String::with_capacity(yaml.len());
let mut rest = yaml;
while let Some((head, tail)) = rest.split_once("short-id:") {
let (gap, value) = tail.split_at(tail.len() - tail.trim_start_matches([' ', '\t']).len());
let (id, after) = value.split_at(value.bytes().take_while(u8::is_ascii_hexdigit).count());
quoted.push_str(head);
quoted.push_str("short-id:");
quoted.push_str(gap);
if !id.is_empty() && (after.is_empty() || after.starts_with([' ', '\t', '\r', '\n', ',', '}'])) {
quoted.push('"');
quoted.push_str(id);
quoted.push('"');
} else {
quoted.push_str(id);
}
rest = after;
}
quoted.push_str(rest);
quoted
}
fn has_numeric_short_id(value: &Value) -> bool {
match value {
Value::Mapping(map) => map
.iter()
.any(|(key, value)| (is_short_id(key) && matches!(value, Value::Number(_))) || has_numeric_short_id(value)),
Value::Sequence(seq) => seq.iter().any(has_numeric_short_id),
_ => false,
}
}
fn same_except_short_id(old: &Value, new: &Value) -> bool {
match (old, new) {
(Value::Mapping(old), Value::Mapping(new)) => {
old.len() == new.len()
&& old.iter().zip(new).all(|((key, old), (new_key, new))| {
key == new_key
&& (same_except_short_id(old, new)
|| (is_short_id(key) && matches!((old, new), (Value::Number(_), Value::String(_)))))
})
}
(Value::Sequence(old), Value::Sequence(new)) => {
old.len() == new.len() && old.iter().zip(new).all(|(old, new)| same_except_short_id(old, new))
}
_ => old == new,
}
}
fn is_short_id(key: &Value) -> bool {
key.as_str() == Some("short-id")
}
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
@@ -211,16 +143,6 @@ pub fn get_uid(prefix: &str) -> String {
format!("{prefix}{id}")
}
pub fn hex_encode(bytes: &[u8]) -> String {
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut out = String::with_capacity(bytes.len() * 2);
for &byte in bytes {
out.push(HEX[usize::from(byte >> 4)] as char);
out.push(HEX[usize::from(byte & 0x0f)] as char);
}
out
}
/// Masks query values and token-like path segments for logging.
pub fn mask_url(url: &str) -> String {
let (path_part, query_part) = match url.find('?') {
@@ -380,9 +302,8 @@ pub fn snapshot_path(original_path: &Path) -> Result<PathBuf> {
#[cfg(test)]
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
mod tests {
use super::{parse_mapping, parse_short_id_text};
use serde_yaml_ng::Value;
use std::path::{Path, PathBuf};
use super::parse_mapping;
use std::path::PathBuf;
#[test]
fn plain_short_id_stays_text() {
@@ -398,19 +319,4 @@ proxies:
assert!(output.contains("short-id: '1234e123'"), "{output}");
assert!(output.contains("short-id: '0e5'"), "{output}");
}
#[test]
fn short_id_quoting_changing_other_values_is_dropped() {
let profile = "\
proxies:
- name: a
reality-opts:
short-id: 1234e123
note: |
short-id: 1234e123
";
let today = serde_yaml_ng::from_str::<Value>(profile).expect("profile should parse");
let value = parse_short_id_text(profile, Path::new("profile.yaml")).expect("profile should parse");
assert_eq!(value, today);
}
}
+6 -19
View File
@@ -1,6 +1,5 @@
use anyhow::{Context as _, bail, ensure};
use clash_verge_logging::{Type, logging};
use serde_yaml_ng::{Mapping, Value};
use std::{
io::Read as _,
os::unix::process::CommandExt as _,
@@ -24,23 +23,6 @@ fn dns_state_dir() -> anyhow::Result<PathBuf> {
Ok(dir)
}
// Without the placeholder, a LAN resolver is reached outside TUN and fake-ip is bypassed.
fn needs_public_dns(config: &Mapping) -> bool {
let section = |name: &str| config.get(name).and_then(Value::as_mapping);
let enabled = |name: &str| {
section(name)
.and_then(|map| map.get("enable"))
.and_then(Value::as_bool)
.unwrap_or(false)
};
enabled("tun")
&& enabled("dns")
&& section("dns")
.and_then(|dns| dns.get("enhanced-mode"))
.and_then(Value::as_str)
== Some("fake-ip")
}
/// Sets the placeholder DNS while the running config needs it, and restores the system DNS otherwise.
#[allow(
clippy::significant_drop_tightening,
@@ -59,7 +41,12 @@ pub async fn sync_public_dns() {
}
let core_running = !matches!(*CoreManager::global().get_running_mode(), RunningMode::NotRunning);
let runtime = Config::runtime().await.latest_arc();
if core_running && runtime.config.as_ref().is_some_and(needs_public_dns) {
if core_running
&& runtime
.config
.as_ref()
.is_some_and(clash_verge_config_render::needs_public_dns)
{
set_public_dns(guard).await;
} else {
let _ = unset_public_dns(guard).await;
@@ -60,20 +60,34 @@ it.each([
},
)
it('leaves the choice open when installation fails', async () => {
store.runState = { service: 'notInstalled', mode: 'NotRunning' } as RunState
const error = new Error('core path is writable by Everyone')
vi.mocked(installService).mockRejectedValue(error)
vi.mocked(getRuntimeState).mockResolvedValue(store.runState)
it('reports the permission refusal and finishes after installation falls back to Sidecar', async () => {
store.runState = {
service: 'notInstalled',
mode: 'NotRunning',
} as unknown as RunState
const reason = 'core path C:\\ is writable by Everyone'
vi.mocked(installService).mockResolvedValue({ status: 'sidecar', reason })
vi.mocked(getRuntimeState).mockResolvedValue({
service: 'unavailable',
mode: 'Sidecar',
sidecarAllowed: true,
serviceNeedsAttention: false,
} as RunState)
const dialog = ServiceMigrationDialog()
dialog.props.onOk()
await vi.waitFor(() => {
expect(showNotice.warning).toHaveBeenCalledWith(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason },
0,
)
})
ServiceMigrationDialog().props.onOk()
await vi.waitFor(() => expect(getRuntimeState).toHaveBeenCalled())
expect(showNotice.error).toHaveBeenCalledWith(
'layout.components.serviceMigration.errors.actionFailed',
error,
)
expect(restartCore).not.toHaveBeenCalled()
expect(vi.mocked(useState).mock.results[2].value[1]).not.toHaveBeenCalledWith(
expect(showNotice.error).not.toHaveBeenCalled()
expect(showNotice.success).not.toHaveBeenCalled()
expect(vi.mocked(useState).mock.results[2].value[1]).toHaveBeenLastCalledWith(
false,
)
})
@@ -9,6 +9,7 @@ import {
reinstallService,
repairService,
restartCore,
type ServiceInstallOutcome,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
@@ -69,26 +70,26 @@ export const ServiceMigrationDialog = () => {
const handleServiceAction = async () => {
setLoading(true)
setWorkflowIncomplete(true)
let installed = false
let outcome: ServiceInstallOutcome | undefined
try {
if (remedy === 'install') {
const result = await mutate(() => installService(), {
id: 'install-service',
errorNotice: false,
})
installed = result.ok
if (result.ok) outcome = result.value
} else if (remedy === 'repair') {
const result = await mutate(() => repairService(), {
id: 'repair-service',
errorNotice: false,
})
installed = result.ok
if (result.ok) outcome = result.value
} else {
const result = await mutate(() => reinstallService(), {
id: 'reinstall-service',
errorNotice: false,
})
installed = result.ok
if (result.ok) outcome = result.value
}
} catch (error) {
showNotice.error(
@@ -107,10 +108,21 @@ export const ServiceMigrationDialog = () => {
error,
)
}
if (!installed || !initialRefreshSucceeded) {
if (!outcome || !initialRefreshSucceeded) {
setLoading(false)
return
}
if (outcome.status === 'sidecar') {
setWorkflowIncomplete(false)
setLoading(false)
showNotice.warning(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason: outcome.reason },
0,
)
return
}
let restartSucceeded = false
try {
const result = await mutate(() => restartCore(), {
@@ -202,9 +214,6 @@ export const ServiceMigrationDialog = () => {
? 'layout.components.serviceMigration.message'
: 'layout.components.serviceMigration.unavailableMessage',
)}
{!showCheckingMessage && runState?.serviceUnavailableReason && (
<div>{runState.serviceUnavailableReason}</div>
)}
</Alert>
</BaseDialog>
)
@@ -11,6 +11,7 @@ import {
restartCore,
type FailedOperation,
type PendingFailure,
type ServiceInstallOutcome,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
@@ -22,6 +23,7 @@ import {
type ServiceRequestReason,
} from '@/services/service-request'
import { useAppReads } from '@/store/app-store-context'
import getSystem from '@/utils/get-system'
type Remedy = 'installAndRestart' | 'reinstallAndRestart' | 'restartOnly'
@@ -103,20 +105,30 @@ export const SysproxyPrivilegeDialog = () => {
const handleFix = async () => {
try {
let outcome: ServiceInstallOutcome | undefined
if (remedy === 'reinstallAndRestart') {
setStep('installing')
const result = await mutate(() => reinstallService(), {
id: 'reinstall-service',
errorNotice: false,
})
if (!result.ok) return
if (result.ok) outcome = result.value
} else if (remedy === 'installAndRestart') {
setStep('installing')
const result = await mutate(() => installService(), {
id: 'install-service',
errorNotice: false,
})
if (!result.ok) return
if (result.ok) outcome = result.value
}
if (outcome?.status === 'sidecar') {
showNotice.warning(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason: outcome.reason },
0,
)
close()
return
}
setStep('restarting')
await mutate(() => restartCore(), {
@@ -125,7 +137,14 @@ export const SysproxyPrivilegeDialog = () => {
})
const runState = await readRunState()
if (runState.mode === 'Service') {
const usingAdminFallback =
remedy !== 'reinstallAndRestart' &&
getSystem() === 'windows' &&
runState.mode === 'Sidecar' &&
runState.isAdmin &&
runState.sidecarAllowed &&
runState.service === 'unavailable'
if (runState.mode === 'Service' || usingAdminFallback) {
if (restoring !== undefined) {
setStep('applying')
await mutate(() => patchVergeConfig(restoring), {
@@ -133,13 +152,15 @@ export const SysproxyPrivilegeDialog = () => {
errorNotice: false,
})
}
showNotice.success(
remedy === 'reinstallAndRestart'
? 'layout.components.serviceMigration.success'
: restoring === undefined
? 'settings.sections.proxyControl.messages.installedCheckProxy'
: 'settings.sections.proxyControl.messages.installedProxyRestored',
)
if (!usingAdminFallback) {
showNotice.success(
remedy === 'reinstallAndRestart'
? 'layout.components.serviceMigration.success'
: restoring === undefined
? 'settings.sections.proxyControl.messages.installedCheckProxy'
: 'settings.sections.proxyControl.messages.installedProxyRestored',
)
}
close()
} else {
showNotice.error(
+8
View File
@@ -33,6 +33,14 @@ export const useServiceInstaller = () => {
'settings.statuses.clashService.installing',
)
if (!installResult.ok) return
if (installResult.value.status === 'sidecar') {
showNotice.warning(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason: installResult.value.reason },
0,
)
return
}
showNotice.success(
'settings.feedback.notifications.clashService.installSuccess',
)
+1 -1
View File
@@ -70,7 +70,7 @@
"chooseFile": "Escolher arquivo"
},
"menu": {
"home": "Início",
"home": "Site da assinatura",
"select": "Selecionar",
"shareQrCode": "Compartilhar QR Code",
"editInfo": "Editar informações",
+20 -3
View File
@@ -44,10 +44,12 @@ export const commands = {
getSidecarFailure: () =>
__TAURI_INVOKE<SidecarFailureSnapshot_Serialize>('get_sidecar_failure'),
entryLightweightMode: () => __TAURI_INVOKE<null>('entry_lightweight_mode'),
installService: () => __TAURI_INVOKE<null>('install_service'),
installService: () =>
__TAURI_INVOKE<ServiceInstallOutcome>('install_service'),
uninstallService: () => __TAURI_INVOKE<null>('uninstall_service'),
reinstallService: () => __TAURI_INVOKE<null>('reinstall_service'),
repairService: () => __TAURI_INVOKE<null>('repair_service'),
reinstallService: () =>
__TAURI_INVOKE<ServiceInstallOutcome>('reinstall_service'),
repairService: () => __TAURI_INVOKE<ServiceInstallOutcome>('repair_service'),
continueWithSidecar: () => __TAURI_INVOKE<null>('continue_with_sidecar'),
syncRuntimeProviders: () => __TAURI_INVOKE<void>('sync_runtime_providers'),
getClashInfo: () => __TAURI_INVOKE<ClashInfo_Serialize>('get_clash_info'),
@@ -97,6 +99,10 @@ export const commands = {
}),
takeDnsOverrideNotice: () =>
__TAURI_INVOKE<boolean>('take_dns_override_notice'),
takeServiceFallbackNotice: () =>
__TAURI_INVOKE<ServiceFallbackNotice | null>(
'take_service_fallback_notice',
),
getCoreStartupError: () =>
__TAURI_INVOKE<CoreFailure | null>('get_core_startup_error'),
takeServiceRepairNotice: () =>
@@ -621,6 +627,7 @@ export type NoticeStatus =
| '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'
@@ -1033,6 +1040,12 @@ export type SaveProxyPortsOutcome =
| { status: 'saved' }
| { status: 'conflict'; port: number; transport: ListenerTransport }
/** Why the Service was unavailable when the core fell back to Sidecar. */
export type ServiceFallbackNotice =
| { kind: 'unavailable' }
| { kind: 'coreRejected'; reason: string }
| { kind: 'notAutoStarted' }
export type ServiceHealthKind =
| 'unknown'
| 'ready'
@@ -1040,6 +1053,10 @@ export type ServiceHealthKind =
| 'versionMismatch'
| 'unavailable'
export type ServiceInstallOutcome =
| { status: 'installed' }
| { status: 'sidecar'; reason: string }
/** A removal has a revision too, so a delayed read cannot restore a resolved failure. */
export type SidecarFailureSnapshot =
| SidecarFailureSnapshot_Serialize
@@ -4,6 +4,7 @@ import {
type RunState,
getCoreStartupError,
takeDnsOverrideNotice,
takeServiceFallbackNotice,
takeServiceRepairNotice,
} from '@/services/cmds'
import { showNotice } from '@/services/notice-service'
@@ -23,6 +24,7 @@ vi.mock('@/services/cmds', () => ({
getPendingFailures: vi.fn().mockResolvedValue([]),
takeDiscardedKeysNotice: vi.fn().mockResolvedValue(null),
takeDnsOverrideNotice: vi.fn().mockResolvedValue(false),
takeServiceFallbackNotice: vi.fn().mockResolvedValue(null),
takeServiceRepairNotice: vi.fn().mockResolvedValue(false),
takeServiceOwnerNotice: vi.fn().mockResolvedValue(null),
}))
@@ -177,3 +179,22 @@ it('offers service reinstallation for a startup path refusal even before listene
reason: 'serviceLocationRefused',
})
})
it('explains a startup core rejection instead of the generic fallback notice', async () => {
const reason =
'approved core was rejected: core path "C:\\" has an untrusted write ACE'
vi.mocked(takeServiceFallbackNotice)
.mockResolvedValueOnce({ kind: 'coreRejected', reason })
.mockResolvedValue(null)
const bus = await mountBus()
bus.onSubscribed()
bus.handlers['verge://notice-message'](['service_core::sidecar_fallback', ''])
await flush()
expect(showNotice.warning).toHaveBeenCalledExactlyOnceWith(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason },
0,
)
})
+1
View File
@@ -92,6 +92,7 @@ export const createEventBus = (deps: BusHandlerDeps) => {
deps.readPendingFailures()
deps.handleNotice(['dns_override::auto_disabled', ''])
deps.handleNotice(['enhance::discarded_keys', ''])
deps.handleNotice(['service_core::sidecar_fallback', ''])
deps.handleNotice(['service_core::repair_required', ''])
deps.handleNotice(['service_core::app_data_not_owned', ''])
deps.handleNotice(['core_start::error', ''])
+5
View File
@@ -23,6 +23,7 @@ export type {
FailedOperation,
PendingFailure,
SidecarFailureSnapshot,
ServiceInstallOutcome,
ProxyPortSettings,
ListenerTransport,
ListenerProbe,
@@ -233,6 +234,10 @@ export async function takeDnsOverrideNotice() {
return commands.takeDnsOverrideNotice()
}
export async function takeServiceFallbackNotice() {
return commands.takeServiceFallbackNotice()
}
export async function getCoreStartupError() {
return commands.getCoreStartupError()
}
+25
View File
@@ -4,6 +4,7 @@ import {
getCoreStartupError,
takeDiscardedKeysNotice,
takeDnsOverrideNotice,
takeServiceFallbackNotice,
takeServiceOwnerNotice,
takeServiceRepairNotice,
} from '@/services/cmds'
@@ -110,6 +111,30 @@ const handlers: Record<
console.error('Failed to read the pending service owner notice', error)
})
},
'service_core::sidecar_fallback': () => {
void takeServiceFallbackNotice()
.then((notice) => {
if (notice?.kind === 'coreRejected') {
showNotice.warning(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason: notice.reason },
0,
)
} else if (notice?.kind === 'notAutoStarted') {
requestService({ reason: 'serviceNotAutoStarted' })
} else if (notice) {
showNotice.warning(
'settings.feedback.notifications.clashService.sidecarFallback',
)
}
})
.catch((error) => {
console.error(
'Failed to read the pending service fallback notice',
error,
)
})
},
'dns_override::auto_disabled': () => {
void takeDnsOverrideNotice()
.then((pending) => {