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
98 changed files with 1994 additions and 4267 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",
+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:
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
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
+10 -130
View File
@@ -98,12 +98,6 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
[[package]]
name = "ambient-authority"
version = "0.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
[[package]]
name = "android_system_properties"
version = "0.1.5"
@@ -913,48 +907,6 @@ dependencies = [
"serde_core",
]
[[package]]
name = "cap-fs-ext"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56ff379b70af8e08307a8f65e7040c7301cb4a572538ade16b4984f0da77847f"
dependencies = [
"cap-primitives",
"cap-std",
"io-lifetimes 3.0.2",
"windows-sys 0.61.2",
]
[[package]]
name = "cap-primitives"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
dependencies = [
"ambient-authority",
"fs-set-times",
"io-extras",
"io-lifetimes 3.0.2",
"ipnet",
"maybe-owned",
"rustix 1.1.4",
"rustix-linux-procfs",
"windows-sys 0.61.2",
"winx",
]
[[package]]
name = "cap-std"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8"
dependencies = [
"cap-primitives",
"io-extras",
"io-lifetimes 3.0.2",
"rustix 1.1.4",
]
[[package]]
name = "cargo-platform"
version = "0.3.3"
@@ -1165,7 +1117,6 @@ dependencies = [
"clash-verge-media-unlock",
"clash-verge-profile",
"clash-verge-profile-script",
"clash-verge-profile-store",
"clash-verge-proxy-view",
"clash-verge-runtime-bundle",
"clash-verge-signal",
@@ -1201,7 +1152,6 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml_ng",
"sha2 0.11.2",
"socket2",
"specta",
"specta-typescript",
@@ -1225,7 +1175,6 @@ dependencies = [
"tauri-plugin-wdio-webdriver",
"tauri-plugin-window-state",
"tauri-specta",
"tempfile",
"tokio",
"tokio-rustls",
"tokio-util",
@@ -1244,11 +1193,7 @@ dependencies = [
name = "clash-verge-backup-archive"
version = "0.1.0"
dependencies = [
"cap-fs-ext",
"cap-primitives",
"tempfile",
"thiserror 2.0.20",
"windows-sys 0.101.0",
"zip",
]
@@ -1261,6 +1206,7 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml_ng",
"sha2 0.11.2",
"tokio",
"tristr",
]
@@ -1342,20 +1288,6 @@ dependencies = [
"tristr",
]
[[package]]
name = "clash-verge-profile-store"
version = "0.1.0"
dependencies = [
"clash-verge-profile",
"serde",
"serde_json",
"serde_yaml_ng",
"sha2 0.11.2",
"tempfile",
"thiserror 2.0.20",
"windows-sys 0.61.2",
]
[[package]]
name = "clash-verge-proxy-view"
version = "0.1.0"
@@ -1406,6 +1338,7 @@ dependencies = [
"futures",
"parking_lot 0.13.0",
"tokio",
"tokio-util",
]
[[package]]
@@ -2691,17 +2624,6 @@ dependencies = [
"percent-encoding",
]
[[package]]
name = "fs-set-times"
version = "0.20.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7faf4684e58845f735514afb09ff7404ab7c26faf9f4d84dbc783a691256ee07"
dependencies = [
"io-lifetimes 2.0.4",
"rustix 1.1.4",
"windows-sys 0.101.0",
]
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -3773,28 +3695,6 @@ version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4275b20e6057cd7733fd8df8a5a31701e4fe44497dad0f3fa0e1c4fb971506be"
[[package]]
name = "io-extras"
version = "0.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "174362052ac8354d7e0c8be593872c476f204f83e6c4987d9ba760a3d801de26"
dependencies = [
"io-lifetimes 3.0.2",
"windows-sys 0.101.0",
]
[[package]]
name = "io-lifetimes"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
[[package]]
name = "io-lifetimes"
version = "3.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b28156deaa5fb6c0f06c23351eefb194a4bc8e3a0e934c3cb13ff8496aa30481"
[[package]]
name = "ipnet"
version = "2.12.0"
@@ -4389,12 +4289,6 @@ version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "maybe-owned"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
[[package]]
name = "md-5"
version = "0.10.6"
@@ -6314,16 +6208,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rustix-linux-procfs"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
dependencies = [
"once_cell",
"rustix 1.1.4",
]
[[package]]
name = "rustls"
version = "0.23.47"
@@ -7857,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",
@@ -10162,16 +10047,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "winx"
version = "0.36.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18e241e21bf0690cf99541caedf959c02c24f36f0bafec8f142ed4e6505ba774"
dependencies = [
"bitflags 2.13.2",
"windows-sys 0.101.0",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
@@ -10655,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"
+1 -3
View File
@@ -15,7 +15,6 @@ members = [
"crates/clash-verge-profile-script",
"crates/clash-verge-proxy-view",
"crates/clash-verge-profile",
"crates/clash-verge-profile-store",
"crates/clash-verge-backup-archive",
]
resolver = "2"
@@ -74,7 +73,6 @@ clash-verge-subscription = { path = "crates/clash-verge-subscription" }
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-profile-store = { path = "crates/clash-verge-profile-store" }
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", branch = "main", version = "2.8.2", default-features = false }
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
@@ -101,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",
@@ -115,7 +114,6 @@ tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849
serde_json = { version = "1.0.154" }
serde_yaml_ng = { version = "0.10.0" }
sha2 = "0.11.2"
tempfile = "3.27.0"
specta = "=2.0.0-rc.26"
socket2 = "0.6.5"
-4
View File
@@ -28,10 +28,6 @@
<details>
<summary><strong> 🐞 修复问题 </strong></summary>
- 优化本地与 WebDAV 备份恢复,复用已校验的文件,减少重复解压
- 修复订阅更新覆盖下载期间修改的设置,以及更新失败后遗留增强配置
- 修复手动更新订阅时错误提示缺失或重复,显示订阅名称和失败原因
- 优化订阅恢复失败提示,显示受影响的订阅名称
- 修复「外部控制器」复制成功的提示一闪而过
- 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位
- 修复检测更新后又发布新版时,应用内更新失败
@@ -4,14 +4,8 @@ version = "0.1.0"
edition = "2024"
[dependencies]
cap-primitives = "4.0.3"
cap-fs-ext = "4.0.3"
tempfile = { workspace = true }
thiserror = { workspace = true }
zip = { workspace = true }
[lints]
workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_System_SystemServices"] }
@@ -4,12 +4,4 @@ pub enum ArchiveError {
Zip(#[from] zip::result::ZipError),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("backup contains a symbolic link")]
Symlink,
#[error("backup contains an invalid path")]
InvalidPath,
#[error("archive contains profile recovery data")]
ReservedEntry,
#[error("backup entry length differs from its declared size")]
SizeMismatch,
}
+7 -141
View File
@@ -1,14 +1,9 @@
mod error;
mod staged;
pub use error::ArchiveError;
pub use staged::{InstallError, StagedBackup};
use std::{
io::{self, Read, Seek, Write},
path::{Component, Path},
};
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
use std::io::{Seek, Write};
use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};
pub struct BackupWriter<W: Write + Seek> {
zip: ZipWriter<W>,
@@ -24,7 +19,7 @@ impl<W: Write + Seek> BackupWriter<W> {
}
pub fn start_profile<'a>(&'a mut self, filename: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
self.start_file(&["profiles/", filename].concat())
self.start_file(&format!("profiles/{filename}"))
}
pub fn start_file<'a>(&'a mut self, name: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
@@ -37,148 +32,20 @@ impl<W: Write + Seek> BackupWriter<W> {
}
}
pub struct BackupArchive<R: Read + Seek> {
zip: ZipArchive<R>,
entries: Vec<staged::Entry>,
}
impl<R: Read + Seek> BackupArchive<R> {
/// Checks entry paths and lengths. Extract into staging to verify stored file checksums before restore.
pub fn open(source: R, reserved_names: &[&str]) -> Result<Self, ArchiveError> {
let mut zip = ZipArchive::new(source)?;
let mut entries = Vec::with_capacity(zip.len());
for index in 0..zip.len() {
let mut entry = zip.by_index(index)?;
if entry.is_symlink() {
return Err(ArchiveError::Symlink);
}
let path = entry.enclosed_name().ok_or(ArchiveError::InvalidPath)?;
for component in path.components() {
let Component::Normal(name) = component else {
continue;
};
let name = name.to_string_lossy();
if reserved_names
.iter()
.any(|reserved| name.eq_ignore_ascii_case(reserved))
{
return Err(ArchiveError::ReservedEntry);
}
}
// Extraction skips directory payloads and permits a decoded file shorter than its declared size.
let size = if entry.is_dir() || entry.compression() != CompressionMethod::Stored {
io::copy(&mut entry, &mut io::sink())?
} else {
entry.compressed_size()
};
entries.push(staged::Entry {
path,
directory: entry.is_dir(),
mode: entry.unix_mode(),
});
if size != entry.size() {
return Err(ArchiveError::SizeMismatch);
}
}
Ok(Self { zip, entries })
}
pub fn stage(mut self, home: &Path) -> Result<StagedBackup, ArchiveError> {
let files = tempfile::tempdir_in(home)?;
self.zip.extract(files.path())?;
Ok(StagedBackup {
files,
entries: self.entries,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
use std::io::{Cursor, Read as _};
use zip::ZipArchive;
#[test]
fn rejects_entries_shorter_than_their_declared_size() -> Result<(), ArchiveError> {
for name in ["profiles/example.yaml", "profiles/"] {
for method in [CompressionMethod::Stored, CompressionMethod::Deflated] {
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.start_file(name, SimpleFileOptions::default().compression_method(method))?;
writer.write_all(b"abc")?;
let mut bytes = writer.finish()?.into_inner();
let directory = ZipArchive::new(Cursor::new(&bytes))?.central_directory_start() as usize;
// Both ZIP headers agree on a size one byte larger than the actual payload.
bytes[22..26].copy_from_slice(&4u32.to_le_bytes());
bytes[directory + 24..directory + 28].copy_from_slice(&4u32.to_le_bytes());
assert!(
BackupArchive::open(Cursor::new(bytes), &[]).is_err(),
"{name} {method:?}"
);
}
}
Ok(())
}
#[cfg(unix)]
#[test]
fn installs_restricted_entries_and_preserves_omitted_files() -> Result<(), Box<dyn std::error::Error>> {
use std::{fs, os::unix::fs::PermissionsExt as _};
let home = tempfile::tempdir()?;
let implicit = home.path().join("implicit");
fs::create_dir(&implicit)?;
std::os::unix::fs::symlink("implicit", home.path().join("link"))?;
fs::set_permissions(&implicit, fs::Permissions::from_mode(0o750))?;
fs::write(implicit.join("omitted"), "keep")?;
fs::write(implicit.join("replace"), "old")?;
fs::hard_link(implicit.join("replace"), implicit.join("peer"))?;
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.add_directory("private/", SimpleFileOptions::default().unix_permissions(0))?;
writer.start_file("private/body", SimpleFileOptions::default().unix_permissions(0o200))?;
writer.write_all(b"restricted")?;
writer.start_file("link/replace", SimpleFileOptions::default())?;
writer.write_all(b"new")?;
let staged = BackupArchive::open(writer.finish()?, &[])?.stage(home.path())?;
staged.install(home.path())?;
let private = home.path().join("private");
assert_eq!(fs::metadata(&private)?.permissions().mode() & 0o777, 0);
fs::set_permissions(&private, fs::Permissions::from_mode(0o700))?;
assert_eq!(fs::metadata(private.join("body"))?.permissions().mode() & 0o777, 0o200);
fs::set_permissions(private.join("body"), fs::Permissions::from_mode(0o600))?;
assert_eq!(fs::read(private.join("body"))?, b"restricted");
assert_eq!(fs::read(implicit.join("replace"))?, b"new");
assert_eq!(fs::read(implicit.join("peer"))?, b"old");
assert_eq!(fs::read(implicit.join("omitted"))?, b"keep");
assert_eq!(fs::metadata(implicit)?.permissions().mode() & 0o777, 0o750);
Ok(())
}
#[test]
fn classifies_install_failure_by_preceding_live_changes() -> Result<(), Box<dyn std::error::Error>> {
for partial in [false, true] {
let home = tempfile::tempdir()?;
std::fs::create_dir(home.path().join("conflict"))?;
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
if partial {
writer.start_file("first", SimpleFileOptions::default())?;
writer.write_all(b"installed")?;
}
writer.start_file("conflict", SimpleFileOptions::default())?;
let staged = BackupArchive::open(writer.finish()?, &[])?.stage(home.path())?;
let error = staged.install(home.path()).unwrap_err();
assert_eq!(error.live_changed, partial);
assert_eq!(home.path().join("first").exists(), partial);
}
Ok(())
}
#[test]
fn writes_and_validates_the_backup_layout() -> Result<(), ArchiveError> {
fn writes_the_backup_layout() -> Result<(), ArchiveError> {
let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?;
writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?;
writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?;
let source = writer.finish()?;
let mut zip = ZipArchive::new(source.clone())?;
let mut zip = ZipArchive::new(source)?;
assert_eq!(zip.len(), 3);
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
let profile_time = {
@@ -193,7 +60,6 @@ mod tests {
let index = zip.by_index(2)?;
assert_eq!(index.name()?, "profiles.yaml");
assert_eq!(index.last_modified(), profile_time);
BackupArchive::open(source, &[".profile-refresh", ".profile-refresh.lock"])?;
Ok(())
}
}
@@ -1,458 +0,0 @@
use cap_fs_ext::{MetadataExt as _, OpenOptionsFollowExt as _, OpenOptionsMaybeDirExt as _, OpenOptionsSyncExt as _};
use cap_primitives::fs as cap;
use std::{
collections::BTreeMap,
fs::{self, File},
io::{self, ErrorKind},
path::{Component, Path, PathBuf},
};
pub(super) struct Entry {
pub path: PathBuf,
pub directory: bool,
pub mode: Option<u32>,
}
#[derive(Debug, thiserror::Error)]
#[error("{source}")]
pub struct InstallError {
pub live_changed: bool,
#[source]
source: io::Error,
}
pub struct StagedBackup {
pub(super) files: tempfile::TempDir,
pub(super) entries: Vec<Entry>,
}
impl StagedBackup {
pub fn path(&self) -> &Path {
self.files.path()
}
pub fn install(self, destination: &Path) -> Result<(), InstallError> {
let mut live_changed = false;
self.install_files(destination, &mut live_changed)
.map_err(|source| InstallError { live_changed, source })
}
fn install_files(&self, destination: &Path, changed: &mut bool) -> io::Result<()> {
let destination = destination.canonicalize()?;
let staging = self.path().canonicalize()?;
let staged_dir = cap::open_ambient_dir(&staging, cap_primitives::ambient_authority())?;
let staged_dir = cap::Metadata::from_file(&staged_dir)?;
let root = cap::open_ambient_dir(&destination, cap_primitives::ambient_authority())?;
let mut modes = BTreeMap::new();
for entry in &self.entries {
if entry.path.as_os_str().is_empty() {
continue;
}
let relative = resolve(&destination, &entry.path, &staging, &mut 40, true)?;
if relative.as_os_str().is_empty() {
return Err(invalid_target());
}
let parent = open_dirs(
&root,
relative.parent().ok_or_else(invalid_target)?,
&staged_dir,
changed,
)?;
let name = Path::new(relative.file_name().ok_or_else(invalid_target)?);
if entry.directory {
open_child_dir(&parent.dir, name, &staged_dir, changed)?;
} else {
let source = staging.join(&entry.path);
copy_file(&staging, &source, &parent.dir, name, entry.mode, changed)?;
}
#[cfg(windows)]
let mode = fs::metadata(staging.join(&entry.path))?
.permissions()
.readonly()
.then_some(0o444);
#[cfg(not(windows))]
let mode = entry.mode;
if let Some(mode) = mode {
modes.insert(relative, mode);
} else if !entry.directory {
modes.remove(&relative);
}
}
for (path, mode) in modes.into_iter().rev() {
let parent = open_dirs(&root, path.parent().ok_or_else(invalid_target)?, &staged_dir, changed)?;
let name = Path::new(path.file_name().ok_or_else(invalid_target)?);
set_mode(&parent.dir, name, mode)?;
*changed = true;
}
Ok(())
}
}
fn invalid_target() -> io::Error {
io::Error::new(ErrorKind::PermissionDenied, "invalid backup installation target")
}
fn relative_link<'a>(home: &Path, target: &'a Path) -> io::Result<&'a Path> {
if let Ok(relative) = target.strip_prefix(home) {
return Ok(relative);
}
#[cfg(windows)]
{
use std::path::Prefix;
let volume = |prefix| match prefix {
Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => Prefix::Disk(drive.to_ascii_uppercase()),
Prefix::VerbatimUNC(server, share) => Prefix::UNC(server, share),
other => other,
};
let mut home = home.components();
let mut target = target.components();
if let (Some(Component::Prefix(base)), Some(Component::Prefix(link))) = (home.next(), target.next())
&& volume(base.kind()) == volume(link.kind())
{
return target
.as_path()
.strip_prefix(home.as_path())
.map_err(|_| invalid_target());
}
}
Err(invalid_target())
}
// Resolve existing links within the home, then reopen the resolved components without following links.
// A file entry replaces its leaf link only after its target has passed the same containment check.
fn resolve(home: &Path, path: &Path, staging: &Path, hops: &mut u8, keep_leaf: bool) -> io::Result<PathBuf> {
let mut out = PathBuf::new();
let mut components = path.components().peekable();
let mut missing = false;
while let Some(component) = components.next() {
match component {
Component::Normal(name) => out.push(name),
Component::CurDir => continue,
Component::ParentDir if !missing && out.pop() => continue,
_ => return Err(invalid_target()),
}
let full = home.join(&out);
if full.starts_with(staging) {
return Err(invalid_target());
}
match fs::symlink_metadata(&full) {
Ok(meta) if meta.is_symlink() => {
*hops = hops.checked_sub(1).ok_or_else(invalid_target)?;
let link = fs::read_link(&full)?;
let target = if link.is_absolute() {
relative_link(home, &link)?.to_owned()
} else {
out.parent().ok_or_else(invalid_target)?.join(link)
};
let checked = resolve(home, &target, staging, hops, false)?;
if !keep_leaf || components.peek().is_some() {
missing |= !home.join(&checked).try_exists()?;
out = checked;
}
}
Ok(_) => {}
Err(err) if err.kind() == ErrorKind::NotFound => missing = true,
Err(err) => return Err(err),
}
}
Ok(out)
}
struct PinnedDir {
dir: File,
#[cfg(windows)]
ancestors: Vec<File>,
}
fn is_staging_directory(dir: &File, staging: &cap::Metadata) -> io::Result<bool> {
let meta = cap::Metadata::from_file(dir)?;
Ok(meta.dev() == staging.dev() && meta.ino() == staging.ino())
}
fn open_dirs(root: &File, path: &Path, staging: &cap::Metadata, changed: &mut bool) -> io::Result<PinnedDir> {
let mut parent = PinnedDir {
dir: root.try_clone()?,
#[cfg(windows)]
ancestors: Vec::new(),
};
for component in path.components() {
let Component::Normal(name) = component else {
return Err(invalid_target());
};
let child = open_child_dir(&parent.dir, Path::new(name), staging, changed)?;
#[cfg(windows)]
parent.ancestors.push(parent.dir);
parent.dir = child;
}
Ok(parent)
}
fn open_child_dir(parent: &File, name: &Path, staging: &cap::Metadata, changed: &mut bool) -> io::Result<File> {
#[cfg(unix)]
let options = cap::DirBuilderExt::mode(&mut cap::DirOptions::new(), 0o700).clone();
#[cfg(not(unix))]
let options = cap::DirOptions::new();
match cap::create_dir(parent, name, &options) {
Ok(()) => *changed = true,
Err(error) if error.kind() == ErrorKind::AlreadyExists => {}
#[cfg(windows)]
Err(error)
if error.kind() == ErrorKind::PermissionDenied
&& cap::stat(parent, name, cap::FollowSymlinks::No).is_ok() => {}
Err(error) => return Err(error),
}
#[cfg(windows)]
{
use cap::OpenOptionsExt as _;
use windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ;
let mut opts = cap::OpenOptions::new();
opts.read(true)
.maybe_dir(true)
.follow(cap::FollowSymlinks::No)
.share_mode(FILE_SHARE_READ);
let dir = cap::open(parent, name, &opts)?;
let meta = dir.metadata()?;
check_storage_filter(&dir)?;
if !meta.is_dir() || is_staging_directory(&dir, staging)? {
return Err(invalid_target());
}
Ok(dir)
}
#[cfg(not(windows))]
{
let dir = cap::open_dir_nofollow(parent, name)?;
if is_staging_directory(&dir, staging)? {
return Err(invalid_target());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
let mode = dir.metadata()?.permissions().mode();
if mode & 0o700 != 0o700 {
cap::set_permissions(&dir, Path::new("."), cap::PermissionsExt::from_mode(mode | 0o700))?;
*changed = true;
}
}
Ok(dir)
}
}
fn open_source(staging: &Path, source: &Path) -> io::Result<File> {
match File::open(source) {
#[cfg(unix)]
Err(error) if error.kind() == ErrorKind::PermissionDenied => {
use std::os::unix::fs::PermissionsExt as _;
// Staging has the final archive modes, including unreadable files and directories.
let mut path = staging.to_owned();
for component in source.strip_prefix(staging).map_err(|_| invalid_target())?.components() {
path.push(component);
let meta = path.symlink_metadata()?;
let needed = if meta.is_dir() { 0o700 } else { 0o400 };
let mode = meta.permissions().mode();
if mode & needed != needed {
fs::set_permissions(&path, fs::Permissions::from_mode(mode | needed))?;
}
}
File::open(source)
}
result => {
let _ = staging;
result
}
}
}
fn copy_file(
staging: &Path,
source: &Path,
parent: &File,
name: &Path,
mode: Option<u32>,
changed: &mut bool,
) -> io::Result<()> {
let mut input = open_source(staging, source)?;
let mut options = cap::OpenOptions::new();
options.write(true).follow(cap::FollowSymlinks::No).nonblock(true);
#[cfg(windows)]
cap::OpenOptionsExt::share_mode(&mut options, windows_sys::Win32::Storage::FileSystem::FILE_SHARE_READ);
#[cfg(unix)]
cap::OpenOptionsExt::mode(&mut options, if mode.is_some() { 0o600 } else { 0o666 });
#[cfg(not(unix))]
let _ = mode;
match cap::stat(parent, name, cap::FollowSymlinks::No) {
Ok(metadata) => {
let replace = metadata.is_symlink() || metadata.is_file() && metadata.nlink() > 1;
#[cfg(windows)]
let replace = {
let mut replace = replace;
use windows_sys::Win32::Storage::FileSystem::{
FILE_ATTRIBUTE_OFFLINE, FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS, FILE_ATTRIBUTE_RECALL_ON_OPEN,
FILE_ATTRIBUTE_REPARSE_POINT, FILE_READ_ATTRIBUTES,
};
let attrs = cap::MetadataExt::file_attributes(&metadata);
if !metadata.is_symlink() && attrs & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
let mut query = cap::OpenOptions::new();
cap::OpenOptionsExt::access_mode(&mut query, FILE_READ_ATTRIBUTES);
let pinned = cap::open(parent, name, query.follow(cap::FollowSymlinks::No))?;
check_storage_filter(&pinned)?;
replace |= attrs
& (FILE_ATTRIBUTE_OFFLINE
| FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS
| FILE_ATTRIBUTE_RECALL_ON_OPEN)
!= 0;
}
replace
};
if replace {
#[cfg(windows)]
if cap::MetadataExt::file_attributes(&metadata)
& windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_DIRECTORY
!= 0
{
cap::remove_dir(parent, name)?;
} else {
cap::remove_file(parent, name)?;
}
#[cfg(not(windows))]
cap::remove_file(parent, name)?;
*changed = true;
} else if !metadata.is_file() {
return Err(invalid_target());
}
}
Err(error) if error.kind() == ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
let mut output = match cap::open(parent, name, &options) {
Err(error) if error.kind() == ErrorKind::NotFound => {
let file = cap::open(parent, name, options.create_new(true))?;
*changed = true;
file
}
result => result?,
};
let meta = cap::Metadata::from_file(&output)?;
if !meta.is_file() || meta.nlink() != 1 {
return Err(invalid_target());
}
#[cfg(windows)]
check_storage_filter(&output)?;
output.set_len(0)?;
*changed = true;
io::copy(&mut input, &mut output)?;
output.set_modified(input.metadata()?.modified()?)?;
Ok(())
}
fn set_mode(parent: &File, name: &Path, mode: u32) -> io::Result<()> {
let mut options = cap::OpenOptions::new();
options
.read(true)
.follow(cap::FollowSymlinks::No)
.maybe_dir(true)
.nonblock(true);
#[cfg(windows)]
{
use windows_sys::Win32::Storage::FileSystem::{FILE_READ_ATTRIBUTES, FILE_SHARE_READ, FILE_WRITE_ATTRIBUTES};
cap::OpenOptionsExt::access_mode(&mut options, FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES);
cap::OpenOptionsExt::share_mode(&mut options, FILE_SHARE_READ);
}
let file = match cap::open(parent, name, &options) {
#[cfg(unix)]
Err(error) if error.kind() == ErrorKind::PermissionDenied => {
cap::open(parent, name, options.read(false).write(true))?
}
result => result?,
};
let meta = cap::Metadata::from_file(&file)?;
if !(meta.is_dir() || meta.is_file() && meta.nlink() == 1) {
return Err(invalid_target());
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
file.set_permissions(fs::Permissions::from_mode(mode))
}
#[cfg(windows)]
{
check_storage_filter(&file)?;
let mut permissions = file.metadata()?.permissions();
permissions.set_readonly(mode & 0o222 == 0);
file.set_permissions(permissions)
}
}
#[cfg(windows)]
fn check_storage_filter(file: &File) -> io::Result<()> {
use std::os::windows::{fs::MetadataExt as _, io::AsRawHandle as _};
use windows_sys::Win32::{
Storage::FileSystem::{
FILE_ATTRIBUTE_REPARSE_POINT, FILE_ATTRIBUTE_TAG_INFO, FileAttributeTagInfo, GetFileInformationByHandleEx,
},
System::SystemServices::{
IO_REPARSE_TAG_CLOUD, IO_REPARSE_TAG_CLOUD_MASK, IO_REPARSE_TAG_DEDUP, IO_REPARSE_TAG_FILE_PLACEHOLDER,
IO_REPARSE_TAG_HSM, IO_REPARSE_TAG_HSM2, IO_REPARSE_TAG_ONEDRIVE, IO_REPARSE_TAG_SIS,
IO_REPARSE_TAG_STORAGE_SYNC, IO_REPARSE_TAG_WOF,
},
};
if file.metadata()?.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT == 0 {
return Ok(());
}
let mut info = FILE_ATTRIBUTE_TAG_INFO::default();
// Inspect the pinned object, so a pathname swap cannot change which filter is classified.
if unsafe {
GetFileInformationByHandleEx(
file.as_raw_handle(),
FileAttributeTagInfo,
(&raw mut info).cast(),
size_of::<FILE_ATTRIBUTE_TAG_INFO>() as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
let tag = info.ReparseTag;
if tag & !IO_REPARSE_TAG_CLOUD_MASK == IO_REPARSE_TAG_CLOUD
|| matches!(
tag,
IO_REPARSE_TAG_ONEDRIVE
| IO_REPARSE_TAG_FILE_PLACEHOLDER
| IO_REPARSE_TAG_WOF
| IO_REPARSE_TAG_DEDUP
| IO_REPARSE_TAG_STORAGE_SYNC
| 0x9000_0027
| IO_REPARSE_TAG_HSM2
| IO_REPARSE_TAG_HSM
| IO_REPARSE_TAG_SIS
| 0xC000_0014
)
{
Ok(())
} else {
Err(invalid_target())
}
}
#[cfg(all(test, windows))]
mod tests {
use super::*;
#[test]
fn absolute_links_may_use_an_ordinary_prefix_for_the_same_home() {
let drive = Path::new(r"\\?\C:\home");
let share = Path::new(r"\\?\UNC\server\share\home");
assert_eq!(
relative_link(drive, Path::new(r"c:\home\data")).ok(),
Some(Path::new("data"))
);
assert_eq!(
relative_link(share, Path::new(r"\\server\share\home\data")).ok(),
Some(Path::new("data"))
);
assert!(relative_link(drive, Path::new(r"D:\home\data")).is_err());
assert!(relative_link(share, Path::new(r"\\server\other\home\data")).is_err());
assert!(relative_link(drive, Path::new(r"C:\home-other\data")).is_err());
}
}
@@ -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}");
}
}
-3
View File
@@ -1,3 +0,0 @@
fn main() {
println!("cargo::rerun-if-changed=locales");
}
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: وكيل النظام
tun: TUN
profile: ملف تعريفي
profileRecovery:
named: يجب استعادة الاشتراك «{name}». راجع سجل التطبيق للاطلاع على التفاصيل.
unknown: يجب استعادة أحد الاشتراكات، لكن تعذّر تحديده. راجع سجل التطبيق للاطلاع على التفاصيل.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: Systemproxy
tun: TUN
profile: Profil
profileRecovery:
named: Das Abonnement „{name}“ muss wiederhergestellt werden. Details stehen im Anwendungsprotokoll.
unknown: Ein Abonnement muss wiederhergestellt werden, konnte aber nicht identifiziert werden. Details stehen im Anwendungsprotokoll.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: System Proxy
tun: TUN
profile: Profile
profileRecovery:
named: Subscription “{name}” needs recovery. See the application log for details.
unknown: Subscription recovery is required. The affected subscription could not be identified. See the application log for details.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: Proxy del sistema
tun: TUN
profile: Perfil
profileRecovery:
named: Hay que recuperar la suscripción «{name}». Consulta el registro de la aplicación para más detalles.
unknown: Hay que recuperar una suscripción, pero no se pudo identificar cuál. Consulta el registro de la aplicación para más detalles.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: پروکسی سیستم
tun: TUN
profile: پروفایل
profileRecovery:
named: اشتراک «{name}» باید بازیابی شود. برای جزئیات، گزارش برنامه را ببینید.
unknown: بازیابی اشتراک لازم است، اما اشتراک موردنظر شناسایی نشد. برای جزئیات، گزارش برنامه را ببینید.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: Proksi Sistem
tun: TUN
profile: Profil
profileRecovery:
named: Langganan “{name}” perlu dipulihkan. Lihat log aplikasi untuk detailnya.
unknown: Langganan perlu dipulihkan, tetapi langganan yang terdampak tidak dapat diidentifikasi. Lihat log aplikasi untuk detailnya.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: システムプロキシ
tun: TUN
profile: プロファイル
profileRecovery:
named: サブスクリプション「{name}」の復旧が必要です。詳細はアプリのログを確認してください。
unknown: サブスクリプションの復旧が必要ですが、対象を特定できません。詳細はアプリのログを確認してください。
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: 시스템 프록시
tun: TUN
profile: 프로필
profileRecovery:
named: “{name}” 구독을 복구해야 합니다. 자세한 내용은 앱 로그를 확인하세요.
unknown: 구독을 복구해야 하지만 해당 구독을 식별할 수 없습니다. 자세한 내용은 앱 로그를 확인하세요.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: Proxy do sistema
tun: TUN
profile: Perfil
profileRecovery:
named: É necessário recuperar a assinatura “{name}”. Consulte o registro do aplicativo para mais detalhes.
unknown: É necessário recuperar uma assinatura, mas não foi possível identificá-la. Consulte o registro do aplicativo para mais detalhes.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: Системный прокси
tun: TUN
profile: Профиль
profileRecovery:
named: Подписку «{name}» нужно восстановить. Подробности в журнале приложения.
unknown: Не удалось определить, какую подписку необходимо восстановить. Подробности в журнале приложения.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: Sistem Vekil'i
tun: TUN
profile: Profil
profileRecovery:
named: “{name}” aboneliğinin kurtarılması gerekiyor. Ayrıntılar için uygulama günlüğüne bakın.
unknown: Kurtarılması gereken abonelik belirlenemedi. Ayrıntılar için uygulama günlüğüne bakın.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: Системалы прокси
tun: TUN
profile: Профиль
profileRecovery:
named: «{name}» язылуын торгызырга кирәк. Тулырак мәгълүмат кушымта журналында.
unknown: Кайсы язылуны торгызырга кирәклеген билгеләп булмады. Тулырак мәгълүмат кушымта журналында.
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: 系统代理
tun: TUN
profile: 订阅
profileRecovery:
named: 订阅「{name}」需要恢复,详情请查看应用日志。
unknown: 订阅需要恢复,但无法识别受影响的订阅。详情请查看应用日志。
-3
View File
@@ -85,6 +85,3 @@ tray:
systemProxy: 系統代理
tun: 虛擬網路介面卡
profile: 訂閱
profileRecovery:
named: 訂閱「{name}」需要復原,詳情請查看應用程式記錄。
unknown: 訂閱需要復原,但無法識別受影響的訂閱。詳情請查看應用程式記錄。
@@ -1,28 +0,0 @@
[package]
name = "clash-verge-profile-store"
version = "0.1.0"
edition = "2024"
[features]
test-support = []
[dependencies]
thiserror = { workspace = true }
clash-verge-profile = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
serde_yaml_ng = { workspace = true }
sha2 = { workspace = true }
[lints]
workspace = true
[dev-dependencies]
tempfile = { workspace = true }
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61.2", features = [
"Win32_Foundation",
"Win32_Storage_FileSystem",
"Win32_System_WindowsProgramming",
] }
@@ -1,78 +0,0 @@
use std::{io, path::PathBuf};
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
#[error("could not recover subscription “{name}”: {source}")]
NamedRecovery { name: String, source: Box<Self> },
#[error(transparent)]
Io(#[from] io::Error),
#[error("{operation} {}", path.display())]
PathIo {
operation: &'static str,
path: PathBuf,
#[source]
source: io::Error,
},
#[error(transparent)]
IndexYaml(#[from] serde_yaml_ng::Error),
#[error(transparent)]
SerializeDecision(#[from] serde_json::Error),
#[error("invalid refresh decision")]
InvalidDecision(#[source] serde_json::Error),
#[error(transparent)]
ProfileNotFound(#[from] clash_verge_profile::ProfileNotFound),
#[error("index and body must share a filesystem")]
DifferentVolumes,
#[cfg(windows)]
#[error("profile recovery requires a supported NTFS volume")]
UnsupportedVolume,
#[error("profile UID is shared")]
SharedUid,
#[error("profile is missing from the on-disk index")]
ProfileMissingFromDisk,
#[error("profile source is ambiguous")]
AmbiguousProfile,
#[error("profile must be remote")]
NotRemote,
#[error("body filename changed")]
FilenameChanged,
#[error("body filename is shared")]
SharedFilename,
#[error("new body path already exists")]
ExistingBodyPath,
#[error("decision is oversized")]
OversizedDecision,
#[error("unknown refresh decision version")]
UnknownDecisionVersion,
#[error("refresh decision target does not match the staged index")]
DecisionTargetMismatch,
#[error("staged content checksum mismatch")]
StagedChecksumMismatch,
#[error("refresh marker is missing for an inconsistent pair")]
InconsistentUnmarkedPair,
#[error("journal is not a directory")]
InvalidJournal,
#[error("decision is not a regular file")]
InvalidDecisionFile,
#[error("invalid profile filename")]
InvalidFilename,
#[cfg(windows)]
#[error("invalid Windows profile filename")]
InvalidWindowsFilename,
#[error("missing profile filename")]
MissingFilename,
#[error("UID or filename is shared")]
SharedUidOrFilename,
#[error("profile body is hard linked")]
HardLinkedBody,
#[error("profile file has a filesystem alias")]
AliasedBody,
#[error("live content changed outside the refresh transaction: {}", .0.display())]
LiveContentChanged(PathBuf),
#[error("expected directory {}", .0.display())]
ExpectedDirectory(PathBuf),
#[error("expected regular file {}", .0.display())]
ExpectedRegularFile(PathBuf),
#[error("missing {}", .0.display())]
MissingFile(PathBuf),
}
-820
View File
@@ -1,820 +0,0 @@
//! Recoverable replacement of one subscription body and the profile index.
#![cfg(any(unix, windows))]
mod error;
mod platform;
pub use error::StoreError;
use clash_verge_profile::IProfiles;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use std::{
fs::{self, File, Permissions},
io::{self, Write as _},
path::{Path, PathBuf},
};
pub const RECOVERY_JOURNAL_NAME: &str = ".profile-refresh";
pub const RECOVERY_ENTRY_NAMES: &[&str] = &[RECOVERY_JOURNAL_NAME, RECOVERY_LOCK_NAME];
const RECOVERY_LOCK_NAME: &str = ".profile-refresh.lock";
const DECISION: &str = "decision";
const MAX_DECISION_BYTES: u64 = 4096;
const PROFILES: &str = "profiles";
const INDEX: &str = "profiles.yaml";
const BODY_NEXT: &str = "body.next";
const INDEX_NEXT: &str = "index.next";
const DECISION_NEXT: &str = "decision.next";
const DECISION_BUILDING: &str = "decision.building";
const APPLY: &str = "body.apply";
const MAX_COMPANIONS: usize = 5;
type Result<T> = std::result::Result<T, StoreError>;
type Checkpoint<'a> = dyn FnMut(&'static str) -> Result<()> + 'a;
#[derive(Debug)]
pub enum CommitOutcome {
Committed,
CommittedCleanupPending(StoreError),
Retryable(StoreError),
RetryCleanupFailed(StoreError),
NeedsRecovery(StoreError),
}
enum InstallOutcome {
Installed,
Reverted(StoreError),
}
pub struct Session {
root: PathBuf,
_lock: File,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Decision {
version: u32,
uid: String,
file: String,
old_body_digest: Option<[u8; 32]>,
old_index_digest: [u8; 32],
body_digest: [u8; 32],
index_digest: [u8; 32],
#[serde(default, skip_serializing_if = "Vec::is_empty")]
companions: Vec<Companion>,
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Companion {
uid: String,
digest: [u8; 32],
}
fn companion_file<'a>(profiles: &'a IProfiles, parent: &str, uid: &str) -> Result<&'a str> {
let item = profiles.get_item(uid)?;
let options = profiles
.get_item(parent)?
.option
.as_ref()
.ok_or(StoreError::DecisionTargetMismatch)?;
let reference = match item.itype.as_deref() {
Some("merge") => &options.merge,
Some("script") => &options.script,
Some("rules") => &options.rules,
Some("proxies") => &options.proxies,
Some("groups") => &options.groups,
_ => return Err(StoreError::DecisionTargetMismatch),
};
let file = item.file.as_deref().ok_or(StoreError::MissingFilename)?;
validate_filename(file)?;
if reference.as_deref() != Some(uid)
|| profiles
.items
.iter()
.flatten()
.filter(|other| other.uid.as_deref() == Some(uid) || other.file.as_deref() == Some(file))
.count()
!= 1
{
return Err(StoreError::DecisionTargetMismatch);
}
Ok(file)
}
impl Session {
pub fn open(root: &Path) -> Result<Self> {
Self::open_with_checkpoint(root, &mut |_| Ok(()))
}
#[cfg(feature = "test-support")]
#[doc(hidden)]
pub fn open_observed(root: &Path, checkpoint: &mut Checkpoint<'_>) -> Result<Self> {
Self::open_with_checkpoint(root, checkpoint)
}
fn open_with_checkpoint(root: &Path, checkpoint: &mut Checkpoint<'_>) -> Result<Self> {
let root = root.canonicalize()?;
let root_metadata = directory(&root)?;
let profiles = root.join(PROFILES);
let profile_metadata = directory(&profiles)?;
if platform::volume(&root, &root_metadata)? != platform::volume(&profiles, &profile_metadata)? {
return Err(StoreError::DifferentVolumes);
}
#[cfg(windows)]
if !platform::supports_redo(&root)? {
let source = StoreError::UnsupportedVolume;
return Err(match pending_refresh_name(&root) {
Some(name) => StoreError::NamedRecovery {
name,
source: Box::new(source),
},
None => source,
});
}
let lock = platform::open_lock(&root.join(RECOVERY_LOCK_NAME))?;
lock.lock()?;
let session = Self { root, _lock: lock };
session
.recover(checkpoint)
.map_err(|error| match refresh_name(&session.root) {
Some(name) => StoreError::NamedRecovery {
name,
source: Box::new(error),
},
None => error,
})?;
Ok(session)
}
fn journal(&self) -> PathBuf {
self.root.join(RECOVERY_JOURNAL_NAME)
}
#[cfg(feature = "test-support")]
#[doc(hidden)]
pub fn snapshot(&self, uid: &str) -> Result<(IProfiles, Vec<u8>)> {
let profiles = serde_yaml_ng::from_slice(&fs::read(self.root.join(INDEX))?)?;
let file = body_filename(&profiles, uid)?;
let body = fs::read(self.root.join(PROFILES).join(file))?;
Ok((profiles, body))
}
pub fn commit_refresh(self, uid: &str, candidate: &IProfiles, body: &[u8]) -> CommitOutcome {
let outcome = self.commit_with_checkpoint(uid, candidate, body, &mut |_| Ok(()));
self.finish_commit(outcome)
}
fn finish_commit(&self, outcome: CommitOutcome) -> CommitOutcome {
match outcome {
CommitOutcome::Retryable(error) => match self.recover(&mut |_| Ok(())) {
Ok(()) => CommitOutcome::Retryable(error),
Err(cleanup) => CommitOutcome::RetryCleanupFailed(cleanup),
},
CommitOutcome::CommittedCleanupPending(error) => match self.recover(&mut |_| Ok(())) {
Ok(()) => CommitOutcome::Committed,
Err(_) => CommitOutcome::CommittedCleanupPending(error),
},
outcome => outcome,
}
}
#[cfg(feature = "test-support")]
#[doc(hidden)]
pub fn commit_observed(
self,
uid: &str,
candidate: &IProfiles,
body: &[u8],
checkpoint: &mut Checkpoint<'_>,
) -> CommitOutcome {
self.commit_with_checkpoint(uid, candidate, body, checkpoint)
}
fn commit_with_checkpoint(
&self,
uid: &str,
candidate: &IProfiles,
body: &[u8],
checkpoint: &mut Checkpoint<'_>,
) -> CommitOutcome {
let before = self.prepare(uid, candidate, body, checkpoint);
if let Err(error) = before {
return CommitOutcome::Retryable(error);
}
let journal = self.journal();
if let Err(error) = fs::hard_link(journal.join(DECISION_NEXT), journal.join(DECISION)) {
return CommitOutcome::Retryable(error.into());
}
let published = (|| {
checkpoint("decision-created")?;
platform::sync_dir(&journal)?;
checkpoint("decision-synced")?;
self.install(checkpoint)
})();
let installed = match published {
Ok(installed) => installed,
Err(error) => return CommitOutcome::NeedsRecovery(error),
};
match (installed, self.disarm_and_clean(checkpoint)) {
(InstallOutcome::Installed, Ok(())) => CommitOutcome::Committed,
(InstallOutcome::Installed, Err(error)) => CommitOutcome::CommittedCleanupPending(error),
(InstallOutcome::Reverted(rejection), Ok(())) => CommitOutcome::Retryable(rejection),
(InstallOutcome::Reverted(_), Err(error)) => CommitOutcome::NeedsRecovery(error),
}
}
fn prepare(&self, uid: &str, candidate: &IProfiles, body: &[u8], checkpoint: &mut Checkpoint<'_>) -> Result<()> {
// Check directory flush access before creating a Windows journal.
#[cfg(windows)]
{
platform::sync_dir(&self.root)?;
platform::sync_dir(&self.root.join(PROFILES))?;
}
let index_path = self.root.join(INDEX);
let old_index = fs::read(&index_path)?;
let current: IProfiles = serde_yaml_ng::from_slice(&old_index)?;
let file = body_filename(candidate, uid)?;
let mut exact = current
.items
.iter()
.flatten()
.filter(|item| item.uid.as_deref() == Some(uid));
let old_item = if let Some(item) = exact.next() {
if exact.next().is_some() {
return Err(StoreError::SharedUid);
}
item
} else {
// Loading an old index may assign a UID without rewriting the file.
let new_item = candidate.get_item(uid)?;
let mut legacy = current.items.iter().flatten().filter(|item| {
item.uid.is_none()
&& item.itype.as_deref() == Some("remote")
&& item.url == new_item.url
&& item.file.as_deref().is_none_or(|old| old == file)
});
let item = legacy.next().ok_or(StoreError::ProfileMissingFromDisk)?;
if legacy.next().is_some() {
return Err(StoreError::AmbiguousProfile);
}
item
};
if old_item.itype.as_deref() != Some("remote") {
return Err(StoreError::NotRemote);
}
if let Some(old_file) = old_item.file.as_deref()
&& old_file != file
{
return Err(StoreError::FilenameChanged);
}
if !current
.items
.iter()
.flatten()
.all(|item| std::ptr::eq(item, old_item) || item.file.as_deref() != Some(file))
{
return Err(StoreError::SharedFilename);
}
let profiles_dir = self.root.join(PROFILES);
let metadata = unshared_body(&profiles_dir, &current, file, 1)?;
unshared_body(&profiles_dir, candidate, file, 1)?;
let index_permissions = regular(&index_path)?.permissions();
let old_body_digest = optional_file_digest(&profiles_dir.join(file))?;
if old_item.file.is_none() && old_body_digest.is_some() {
return Err(StoreError::ExistingBodyPath);
}
let mut index = b"# Profiles Config for Clash Verge\n\n".to_vec();
serde_yaml_ng::to_writer(&mut index, candidate)?;
let mut companions = Vec::new();
let mut templates = Vec::new();
for item in candidate.items.iter().flatten() {
let Some(data) = &item.file_data else { continue };
let id = item.uid.as_deref().ok_or(StoreError::DecisionTargetMismatch)?;
let file = companion_file(candidate, uid, id)?;
if current
.items
.iter()
.flatten()
.any(|old| old.uid.as_deref() == Some(id) || old.file.as_deref() == Some(file))
|| optional_regular(&profiles_dir.join(file))?.is_some()
{
return Err(StoreError::ExistingBodyPath);
}
let bytes = data.as_bytes();
companions.push(Companion {
uid: id.to_owned(),
digest: Sha256::digest(bytes).into(),
});
templates.push(bytes);
}
if companions.len() > MAX_COMPANIONS {
return Err(StoreError::DecisionTargetMismatch);
}
let decision = Decision {
version: if companions.is_empty() { 1 } else { 2 },
companions,
uid: uid.into(),
file: file.into(),
old_body_digest,
old_index_digest: Sha256::digest(&old_index).into(),
body_digest: Sha256::digest(body).into(),
index_digest: Sha256::digest(&index).into(),
};
let decision = serde_json::to_vec(&decision)?;
if decision.len() as u64 > MAX_DECISION_BYTES {
return Err(StoreError::OversizedDecision);
}
let journal = self.journal();
platform::create_dir(&journal)?;
platform::sync_dir(&self.root)?;
checkpoint("journal-created")?;
write_new(&journal.join(BODY_NEXT), body, metadata.map(|meta| meta.permissions()))?;
checkpoint("body-staged")?;
for (slot, bytes) in templates.into_iter().enumerate() {
write_new(&journal.join(format!("companion.{slot}")), bytes, None)?;
}
write_new(&journal.join(INDEX_NEXT), &index, Some(index_permissions))?;
checkpoint("index-staged")?;
write_new(&journal.join(DECISION_BUILDING), &decision, None)?;
platform::replace(journal.join(DECISION_BUILDING), journal.join(DECISION_NEXT))?;
// A decision that survives interruption must only reference already-synced inputs.
platform::sync_dir(&journal)?;
checkpoint("prepared")
}
fn install(&self, checkpoint: &mut Checkpoint<'_>) -> Result<InstallOutcome> {
let journal = self.journal();
let decision = read_decision(&journal.join(DECISION))?;
let index_next = journal.join(INDEX_NEXT);
let (index, index_permissions) = verified(&index_next, decision.index_digest)?;
let candidate: IProfiles = serde_yaml_ng::from_slice(&index)?;
if body_filename(&candidate, &decision.uid)? != decision.file {
return Err(StoreError::DecisionTargetMismatch);
}
let profiles_dir = self.root.join(PROFILES);
let body_path = profiles_dir.join(&decision.file);
let index_path = self.root.join(INDEX);
let apply = journal.join(APPLY);
let body_installed = verify_live(&body_path, decision.old_body_digest, decision.body_digest)?;
let index_installed = verify_live(&index_path, Some(decision.old_index_digest), decision.index_digest)?;
let can_revert_new_body = decision.old_body_digest.is_none()
&& (!index_installed || decision.old_index_digest == decision.index_digest);
if !can_revert_new_body {
unshared_body(&profiles_dir, &candidate, &decision.file, 1)?;
}
let body_next = journal.join(BODY_NEXT);
if body_installed {
if file_digest(&body_next)? != decision.body_digest {
return Err(StoreError::StagedChecksumMismatch);
}
// Equality alone does not establish durability of a prior in-place edit.
platform::sync_file(&body_path)?;
} else {
remove_file_if_exists(&apply)?;
copy_verified(&body_next, &apply, decision.body_digest)?;
platform::replace(&apply, &body_path).map_err(|source| StoreError::PathIo {
operation: "replace",
path: body_path.clone(),
source,
})?;
}
checkpoint("body-replaced")?;
if can_revert_new_body {
// Native aliases of a missing file only resolve once the file exists.
let check = (|| {
unshared_body(&profiles_dir, &candidate, &decision.file, 1)?;
if !index_installed {
let (index, _) = verified(&index_path, decision.old_index_digest)?;
let current = serde_yaml_ng::from_slice(&index)?;
unshared_body(&profiles_dir, &current, &decision.file, 1)?;
}
Ok(())
})();
if let Err(error) = check {
match error {
StoreError::AliasedBody | StoreError::InvalidFilename => {}
#[cfg(windows)]
StoreError::InvalidWindowsFilename => {}
_ => return Err(error),
}
fs::remove_file(&body_path)?;
platform::sync_dir(&profiles_dir)?;
return Ok(InstallOutcome::Reverted(error));
}
}
let old_companion_index: Option<IProfiles> = if !index_installed && !decision.companions.is_empty() {
let (index, _) = verified(&index_path, decision.old_index_digest)?;
Some(serde_yaml_ng::from_slice(&index)?)
} else {
None
};
for (slot, companion) in decision.companions.iter().enumerate() {
let file = companion_file(&candidate, &decision.uid, &companion.uid)?;
let staged = journal.join(format!("companion.{slot}"));
if file_digest(&staged)? != companion.digest {
return Err(StoreError::StagedChecksumMismatch);
}
let target = profiles_dir.join(file);
match fs::hard_link(&staged, &target) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
if platform::file_identity(&target, &regular(&target)?)?
!= platform::file_identity(&staged, &regular(&staged)?)?
{
return Err(StoreError::LiveContentChanged(target));
}
}
Err(error) => return Err(error.into()),
}
unshared_body(&profiles_dir, &candidate, file, 2)?;
if let Some(old) = &old_companion_index {
unshared_body(&profiles_dir, old, file, 2)?;
}
checkpoint("companion-installed")?;
}
if index_installed {
platform::sync_file(&index_path)?;
} else {
// The body rename consumed the scratch file. Replay can discard it at either step.
remove_file_if_exists(&apply)?;
write_new(&apply, &index, Some(index_permissions))?;
platform::replace(&apply, &index_path).map_err(|source| StoreError::PathIo {
operation: "replace",
path: index_path,
source,
})?;
}
checkpoint("index-replaced")?;
platform::sync_dir(&profiles_dir)?;
checkpoint("body-synced")?;
platform::sync_dir(&self.root)?;
checkpoint("index-synced")?;
Ok(InstallOutcome::Installed)
}
fn disarm_and_clean(&self, checkpoint: &mut Checkpoint<'_>) -> Result<()> {
let journal = self.journal();
fs::remove_file(journal.join(DECISION))?;
checkpoint("decision-removed")?;
platform::sync_dir(&journal)?;
checkpoint("disarmed")?;
self.remove_journal()?;
checkpoint("journal-removed")
}
fn remove_journal(&self) -> Result<()> {
let journal = self.journal();
for name in [
DECISION_NEXT,
DECISION_BUILDING,
BODY_NEXT,
INDEX_NEXT,
APPLY,
"index.apply", // Older v1 journals used a separate scratch file for the index.
] {
remove_file_if_exists(&journal.join(name))?;
}
match fs::remove_dir(&journal) {
Err(error) if error.kind() == io::ErrorKind::DirectoryNotEmpty => {
for slot in 0..MAX_COMPANIONS {
remove_file_if_exists(&journal.join(format!("companion.{slot}")))?;
}
fs::remove_dir(&journal)?;
}
result => result?,
}
Ok(platform::sync_dir(&self.root)?)
}
fn check_unmarked_pair(&self, intent: &Decision) -> Result<()> {
let body = optional_file_digest(&self.root.join(PROFILES).join(&intent.file))?;
let index = file_digest(&self.root.join(INDEX))?;
let old_pair = body == intent.old_body_digest && index == intent.old_index_digest;
let new_pair = body == Some(intent.body_digest) && index == intent.index_digest;
if !old_pair && !new_pair {
return Err(StoreError::InconsistentUnmarkedPair);
}
if new_pair && !intent.companions.is_empty() {
let (bytes, _) = verified(&self.root.join(INDEX), intent.index_digest)?;
let candidate = serde_yaml_ng::from_slice(&bytes)?;
for companion in &intent.companions {
let file = companion_file(&candidate, &intent.uid, &companion.uid)?;
let path = self.root.join(PROFILES).join(file);
if optional_file_digest(&path)? != Some(companion.digest) {
return Err(StoreError::LiveContentChanged(path));
}
}
}
Ok(())
}
fn recover(&self, checkpoint: &mut Checkpoint<'_>) -> Result<()> {
let journal = self.journal();
match fs::symlink_metadata(&journal) {
Ok(metadata) => {
if !metadata.is_dir() || platform::is_reparse(&metadata) {
return Err(StoreError::InvalidJournal);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(error.into()),
}
match fs::symlink_metadata(journal.join(DECISION)) {
Ok(metadata) => {
if !metadata.is_file() || platform::is_reparse(&metadata) {
return Err(StoreError::InvalidDecisionFile);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
// A previous process may have unlinked the decision before its directory sync.
platform::sync_dir(&journal)?;
let intent = journal.join(DECISION_NEXT);
match fs::symlink_metadata(&intent) {
Ok(_) => self.check_unmarked_pair(&read_decision(&intent)?)?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
Err(error) => return Err(error.into()),
}
return self.remove_journal();
}
Err(error) => return Err(error.into()),
}
// A visible decision may have survived a process interruption before its directory sync.
platform::sync_dir(&journal)?;
self.install(checkpoint)?;
self.disarm_and_clean(checkpoint)
}
}
fn read_decision(path: &Path) -> Result<Decision> {
if regular(path)?.len() > MAX_DECISION_BYTES {
return Err(StoreError::OversizedDecision);
}
let decision: Decision = serde_json::from_slice(&fs::read(path)?).map_err(StoreError::InvalidDecision)?;
if !matches!(
(decision.version, decision.companions.len()),
(1, 0) | (2, 1..=MAX_COMPANIONS)
) {
return Err(StoreError::UnknownDecisionVersion);
}
validate_filename(&decision.file)?;
Ok(decision)
}
fn validate_filename(file: &str) -> Result<()> {
if file.is_empty()
|| matches!(file, "." | "..")
|| file.contains(['/', '\\', '\0'])
|| (cfg!(windows) && file.contains(':'))
{
return Err(StoreError::InvalidFilename);
}
#[cfg(windows)]
{
let stem = file
.split('.')
.next()
.unwrap_or_default()
.trim_end_matches(' ')
.to_ascii_uppercase();
let is_port_device = ["COM", "LPT"].iter().any(|prefix| {
stem.strip_prefix(prefix).is_some_and(|suffix| {
matches!(
suffix,
"1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
)
})
});
if file.ends_with([' ', '.'])
|| file.contains(['<', '>', '"', '|', '?', '*'])
|| file.bytes().any(|byte| byte < 32)
|| matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|| is_port_device
{
return Err(StoreError::InvalidWindowsFilename);
}
}
Ok(())
}
fn body_filename<'a>(profiles: &'a IProfiles, uid: &str) -> Result<&'a str> {
let item = profiles.get_item(uid)?;
if item.itype.as_deref() != Some("remote") {
return Err(StoreError::NotRemote);
}
let file = item.file.as_deref().ok_or(StoreError::MissingFilename)?;
validate_filename(file)?;
let owners = profiles
.items
.iter()
.flatten()
.filter(|item| item.uid.as_deref() == Some(uid) || item.file.as_deref() == Some(file))
.count();
if owners != 1 {
return Err(StoreError::SharedUidOrFilename);
}
Ok(file)
}
fn unshared_body(dir: &Path, profiles: &IProfiles, file: &str, expected_links: u64) -> Result<Option<fs::Metadata>> {
let mut path = dir.join(file);
let target = optional_regular(&path)?;
let identity = target
.as_ref()
.map(|metadata| platform::file_identity(&path, metadata))
.transpose()?;
if identity
.as_ref()
.is_some_and(|identity| identity.links != expected_links)
{
return Err(StoreError::HardLinkedBody);
}
for other in profiles.items.iter().flatten().filter_map(|item| item.file.as_deref()) {
if other == file {
continue;
}
// Other entries may use native filenames, but they must stay in this directory.
let mut components = Path::new(other).components();
if !matches!(
(components.next(), components.next()),
(Some(std::path::Component::Normal(name)), None) if name == other
) || other.contains('\0')
{
return Err(StoreError::InvalidFilename);
}
#[cfg(windows)]
validate_filename(other)?;
path.set_file_name(other);
match fs::metadata(&path) {
Ok(metadata) => {
if let Some(identity) = &identity
&& platform::file_identity(&path, &metadata)? == *identity
{
return Err(StoreError::AliasedBody);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => (),
Err(error) => return Err(error.into()),
}
}
Ok(target)
}
fn file_digest(path: &Path) -> Result<[u8; 32]> {
regular(path)?;
transfer_digest(File::open(path)?, io::sink())
}
fn optional_file_digest(path: &Path) -> Result<Option<[u8; 32]>> {
optional_regular(path)?
.map(|_| transfer_digest(File::open(path)?, io::sink()))
.transpose()
}
fn transfer_digest(mut input: impl io::Read, mut output: impl io::Write) -> Result<[u8; 32]> {
let mut digest = Sha256::new();
let mut buffer = [0; 16 * 1024];
loop {
let len = match input.read(&mut buffer) {
Ok(0) => return Ok(digest.finalize().into()),
Ok(len) => len,
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
Err(error) => return Err(error.into()),
};
digest.update(&buffer[..len]);
output.write_all(&buffer[..len])?;
}
}
fn copy_verified(from: &Path, to: &Path, expected: [u8; 32]) -> Result<()> {
let permissions = regular(from)?.permissions();
let mut output = platform::create_new(to)?;
let actual = transfer_digest(File::open(from)?, &mut output)?;
if actual != expected {
return Err(StoreError::StagedChecksumMismatch);
}
output.set_permissions(permissions)?;
output.sync_all()?;
Ok(())
}
fn verify_live(path: &Path, old: Option<[u8; 32]>, new: [u8; 32]) -> Result<bool> {
let actual = optional_file_digest(path)?;
if actual != old && actual != Some(new) {
return Err(StoreError::LiveContentChanged(path.to_owned()));
}
Ok(actual == Some(new))
}
fn verified(path: &Path, digest: [u8; 32]) -> Result<(Vec<u8>, Permissions)> {
let permissions = regular(path)?.permissions();
let bytes = fs::read(path)?;
let actual: [u8; 32] = Sha256::digest(&bytes).into();
if actual != digest {
return Err(StoreError::StagedChecksumMismatch);
}
Ok((bytes, permissions))
}
fn directory(path: &Path) -> Result<fs::Metadata> {
let metadata = fs::symlink_metadata(path).map_err(|source| StoreError::PathIo {
operation: "inspect",
path: path.to_owned(),
source,
})?;
if !metadata.is_dir() || platform::is_reparse(&metadata) {
return Err(StoreError::ExpectedDirectory(path.to_owned()));
}
Ok(metadata)
}
fn regular(path: &Path) -> Result<fs::Metadata> {
optional_regular(path)?.ok_or_else(|| StoreError::MissingFile(path.to_owned()))
}
fn optional_regular(path: &Path) -> Result<Option<fs::Metadata>> {
match fs::symlink_metadata(path) {
Ok(metadata) => {
if !metadata.is_file() || platform::is_reparse(&metadata) {
return Err(StoreError::ExpectedRegularFile(path.to_owned()));
}
Ok(Some(metadata))
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(source) => Err(StoreError::PathIo {
operation: "inspect",
path: path.to_owned(),
source,
}),
}
}
fn write_new(path: &Path, bytes: &[u8], permissions: Option<Permissions>) -> Result<()> {
let mut file = platform::create_new(path).map_err(|source| StoreError::PathIo {
operation: "create",
path: path.to_owned(),
source,
})?;
file.write_all(bytes)?;
if let Some(permissions) = permissions {
file.set_permissions(permissions)?;
}
file.sync_all()?;
Ok(())
}
fn remove_file_if_exists(path: &Path) -> Result<()> {
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
fn refresh_name(root: &Path) -> Option<String> {
let journal = root.join(RECOVERY_JOURNAL_NAME);
directory(&journal).ok()?;
let marker = match optional_regular(&journal.join(DECISION)).ok()? {
Some(_) => DECISION,
None => DECISION_NEXT,
};
let decision = read_decision(&journal.join(marker)).ok()?;
let (index, _) = verified(&journal.join(INDEX_NEXT), decision.index_digest).ok()?;
let profiles: IProfiles = serde_yaml_ng::from_slice(&index).ok()?;
if body_filename(&profiles, &decision.uid).ok()? != decision.file {
return None;
}
let item = profiles.get_item(&decision.uid).ok()?;
item.name
.as_deref()
.filter(|name| !name.trim().is_empty())
.map(str::to_owned)
}
/// Identifies a pending transaction when this build or volume cannot replay it.
#[cfg(windows)]
pub fn pending_refresh_name(root: &Path) -> Option<String> {
let lock = File::open(root.join(RECOVERY_LOCK_NAME)).ok()?;
lock.try_lock_shared().ok()?;
refresh_name(root)
}
/// Replays a saved decision before the application creates or loads its index.
pub fn recover_pending(root: &Path) -> Result<()> {
match fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
Ok(_) => Session::open(root).map(drop),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error.into()),
}
}
#[cfg(windows)]
pub fn supports_redo(root: &Path) -> Result<bool> {
Ok(platform::supports_redo(root)?)
}
@@ -1,209 +0,0 @@
#[cfg(windows)]
pub(crate) use native::supports_redo;
pub(crate) use native::{create_dir, create_new, file_identity, is_reparse, open_lock, sync_dir, sync_file, volume};
pub(crate) use std::fs::rename as replace;
pub(crate) struct FileIdentity {
volume: u64,
id: u64,
pub(crate) links: u64,
}
impl PartialEq for FileIdentity {
fn eq(&self, other: &Self) -> bool {
self.volume == other.volume && self.id == other.id
}
}
#[cfg(unix)]
mod native {
use super::FileIdentity;
use std::{
fs::{DirBuilder, File, Metadata, OpenOptions},
io,
os::unix::fs::{DirBuilderExt as _, MetadataExt as _, OpenOptionsExt as _},
path::Path,
};
#[expect(clippy::unnecessary_wraps, reason = "The corresponding Windows operation can fail")]
pub(crate) fn volume(_: &Path, metadata: &Metadata) -> io::Result<u64> {
Ok(metadata.dev())
}
#[expect(clippy::unnecessary_wraps, reason = "The corresponding Windows operation can fail")]
pub(crate) fn file_identity(_: &Path, metadata: &Metadata) -> io::Result<FileIdentity> {
Ok(FileIdentity {
volume: metadata.dev(),
id: metadata.ino(),
links: metadata.nlink(),
})
}
pub(crate) const fn is_reparse(_: &Metadata) -> bool {
false
}
pub(crate) fn create_dir(path: &Path) -> io::Result<()> {
DirBuilder::new().mode(0o700).create(path)
}
pub(crate) fn open_lock(path: &Path) -> io::Result<File> {
OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.mode(0o600)
.open(path)
}
pub(crate) fn create_new(path: &Path) -> io::Result<File> {
OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)
}
pub(crate) fn sync_dir(path: &Path) -> io::Result<()> {
File::open(path)?.sync_all()
}
pub(crate) fn sync_file(path: &Path) -> io::Result<()> {
File::open(path)?.sync_all()
}
}
#[cfg(windows)]
mod native {
use super::FileIdentity;
use std::{
fs::{self, File, Metadata, OpenOptions},
io,
os::windows::{
ffi::OsStrExt as _,
fs::{MetadataExt as _, OpenOptionsExt as _},
io::AsRawHandle as _,
},
path::Path,
};
use windows_sys::Win32::{
Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT, FILE_FLAG_BACKUP_SEMANTICS,
FILE_FLAG_OPEN_REPARSE_POINT, FILE_READ_ATTRIBUTES, GetDriveTypeW, GetFileInformationByHandle,
GetVolumeInformationByHandleW, GetVolumePathNameW,
},
System::WindowsProgramming::DRIVE_FIXED,
};
fn path_wide(path: &Path) -> io::Result<Vec<u16>> {
let mut wide: Vec<_> = path.as_os_str().encode_wide().collect();
if wide.contains(&0) {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "path contains a NUL"));
}
wide.push(0);
Ok(wide)
}
fn open_attributes(path: &Path) -> io::Result<File> {
// Follow a named alias for identity checks. Managed paths are separately checked with symlink_metadata.
OpenOptions::new()
.access_mode(FILE_READ_ATTRIBUTES)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
.open(path)
}
fn file_info(path: &Path) -> io::Result<BY_HANDLE_FILE_INFORMATION> {
let file = open_attributes(path)?;
let mut info = BY_HANDLE_FILE_INFORMATION::default();
// The output buffer and file handle remain valid for the call.
let ok = unsafe { GetFileInformationByHandle(file.as_raw_handle(), &raw mut info) };
if ok == 0 {
return Err(io::Error::last_os_error());
}
Ok(info)
}
pub(crate) fn volume(path: &Path, _: &Metadata) -> io::Result<u64> {
Ok(u64::from(file_info(path)?.dwVolumeSerialNumber))
}
pub(crate) fn file_identity(path: &Path, _: &Metadata) -> io::Result<FileIdentity> {
let info = file_info(path)?;
// The full NTFS file ID fits in 64 bits. ReFS is excluded by supports_redo.
Ok(FileIdentity {
volume: u64::from(info.dwVolumeSerialNumber),
id: (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
links: u64::from(info.nNumberOfLinks),
})
}
pub(crate) fn is_reparse(metadata: &Metadata) -> bool {
metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
}
pub(crate) fn supports_redo(root: &Path) -> io::Result<bool> {
let path = path_wide(root)?;
let mut volume = vec![0u16; 32_768];
// The input is NUL-terminated and the output buffer is writable for the stated length.
let ok = unsafe { GetVolumePathNameW(path.as_ptr(), volume.as_mut_ptr(), volume.len() as u32) };
if ok == 0 {
return Err(io::Error::last_os_error());
}
// GetVolumePathNameW returned a NUL-terminated volume root.
if unsafe { GetDriveTypeW(volume.as_ptr()) } != DRIVE_FIXED {
return Ok(false);
}
let file = open_attributes(root)?;
let mut filesystem = [0u16; 16];
// The handle remains live. Optional outputs are omitted, except for the writable filesystem buffer.
let ok = unsafe {
GetVolumeInformationByHandleW(
file.as_raw_handle(),
std::ptr::null_mut(),
0,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
filesystem.as_mut_ptr(),
filesystem.len() as u32,
)
};
if ok == 0 {
return Err(io::Error::last_os_error());
}
// MS-FSA 2.1.5.7 documents directory persistence on NTFS. Other filesystems can silently succeed.
Ok(filesystem.starts_with(&[u16::from(b'N'), u16::from(b'T'), u16::from(b'F'), u16::from(b'S'), 0]))
}
pub(crate) fn create_dir(path: &Path) -> io::Result<()> {
fs::create_dir(path)
}
pub(crate) fn open_lock(path: &Path) -> io::Result<File> {
OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)
}
pub(crate) fn create_new(path: &Path) -> io::Result<File> {
OpenOptions::new().write(true).create_new(true).open(path)
}
pub(crate) fn sync_dir(path: &Path) -> io::Result<()> {
OpenOptions::new()
.write(true)
.custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?
.sync_all()
}
pub(crate) fn sync_file(path: &Path) -> io::Result<()> {
OpenOptions::new()
.write(true)
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
.open(path)?
.sync_all()
}
}
@@ -1,175 +0,0 @@
#![cfg(any(unix, windows))]
use clash_verge_profile::IProfiles;
use clash_verge_profile_store::{CommitOutcome, Session};
use std::fs;
#[test]
fn refresh_creates_missing_body_for_legacy_index() -> Result<(), clash_verge_profile_store::StoreError> {
let dir = tempfile::tempdir()?;
let root = dir.path();
fs::create_dir(root.join("profiles"))?;
fs::write(
root.join("profiles.yaml"),
"items:\n- {type: remote, url: 'https://example.invalid/sub'}\n",
)?;
let candidate = serde_yaml_ng::from_str(
"items:\n- {uid: assigned, type: remote, url: 'https://example.invalid/sub', file: 'Rnew.yaml', updated: 42}\n",
)?;
let body = b"# preserve comments\nproxies: []\n";
let outcome = Session::open(root)?.commit_refresh("assigned", &candidate, body);
assert!(matches!(outcome, CommitOutcome::Committed), "{outcome:?}");
let index: IProfiles = serde_yaml_ng::from_slice(&fs::read(root.join("profiles.yaml"))?)?;
let stored_body = fs::read(root.join("profiles/Rnew.yaml"))?;
assert_eq!(index.get_item("assigned")?.updated, Some(42));
assert_eq!(index.get_item("assigned")?.file.as_deref(), Some("Rnew.yaml"));
assert_eq!(stored_body, body);
Ok(())
}
#[cfg(unix)]
#[test]
fn refresh_preserves_native_unix_filenames() -> Result<(), clash_verge_profile_store::StoreError> {
let dir = tempfile::tempdir()?;
let root = dir.path();
fs::create_dir(root.join("profiles"))?;
fs::write(root.join("profiles/remote:old.yaml"), b"old")?;
fs::write(root.join("profiles/office:old.yaml"), b"local")?;
let old = "items:\n- {uid: r, type: remote, file: 'remote:old.yaml', updated: 1}\n- {uid: l, type: local, file: 'office:old.yaml'}\n";
fs::write(root.join("profiles.yaml"), old)?;
let candidate = serde_yaml_ng::from_str(&old.replace("updated: 1", "updated: 2"))?;
let outcome = Session::open(root)?.commit_refresh("r", &candidate, b"new");
assert!(matches!(outcome, CommitOutcome::Committed), "{outcome:?}");
assert_eq!(fs::read(root.join("profiles/remote:old.yaml"))?, b"new");
assert_eq!(fs::read(root.join("profiles/office:old.yaml"))?, b"local");
Ok(())
}
#[test]
fn refresh_rejects_legacy_path_alias_before_creating_body() -> Result<(), clash_verge_profile_store::StoreError> {
let dir = tempfile::tempdir()?;
let root = dir.path();
fs::create_dir(root.join("profiles"))?;
let old = "items:\n- {uid: r, type: remote, file: r.yaml, updated: 1}\n- {uid: l, type: local, file: './r.yaml'}\n";
fs::write(root.join("profiles.yaml"), old)?;
let candidate = serde_yaml_ng::from_str(&old.replace("updated: 1", "updated: 2"))?;
let outcome = Session::open(root)?.commit_refresh("r", &candidate, b"new");
assert!(matches!(
outcome,
CommitOutcome::Retryable(clash_verge_profile_store::StoreError::InvalidFilename)
));
assert!(!root.join("profiles/r.yaml").exists());
assert!(!root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
Ok(())
}
#[cfg(all(unix, feature = "test-support"))]
#[test]
fn interrupted_creation_reverts_an_aliased_body() -> Result<(), clash_verge_profile_store::StoreError> {
let dir = tempfile::tempdir()?;
let root = dir.path();
fs::create_dir(root.join("profiles"))?;
std::os::unix::fs::symlink("r.yaml", root.join("profiles/alias.yaml"))?;
let old = "items:\n- {uid: r, type: remote, file: r.yaml, updated: 1}\n- {uid: l, type: local, file: alias.yaml}\n";
fs::write(root.join("profiles.yaml"), old)?;
let candidate = serde_yaml_ng::from_str(&old.replace("updated: 1", "updated: 2"))?;
let outcome = Session::open(root)?.commit_observed("r", &candidate, b"new", &mut |phase| {
if phase == "body-replaced" {
return Err(std::io::Error::other("interrupted after body replacement").into());
}
Ok(())
});
assert!(matches!(outcome, CommitOutcome::NeedsRecovery(_)), "{outcome:?}");
assert_eq!(fs::read(root.join("profiles/r.yaml"))?, b"new");
let session = Session::open(root)?;
assert!(!root.join("profiles/r.yaml").exists());
assert!(!root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
let outcome = session.commit_refresh("r", &candidate, b"new");
assert!(matches!(
outcome,
CommitOutcome::Retryable(clash_verge_profile_store::StoreError::AliasedBody)
));
Ok(())
}
#[cfg(feature = "test-support")]
#[test]
fn recovery_identifies_the_interrupted_subscription_from_its_verified_index()
-> Result<(), clash_verge_profile_store::StoreError> {
use clash_verge_profile_store::{StoreError, recover_pending};
let home = tempfile::tempdir()?;
let root = home.path();
fs::create_dir(root.join("profiles"))?;
let index = "current: other\nitems:\n- {uid: other, name: Home, type: remote, file: other.yaml}\n- {uid: opaque, name: 工作线路, type: remote, file: target.yaml}\n";
fs::write(root.join("profiles.yaml"), index)?;
let candidate = serde_yaml_ng::from_str(index)?;
let outcome = Session::open(root)?.commit_observed("opaque", &candidate, b"new", &mut |phase| {
if phase == "decision-created" {
return Err(std::io::Error::other("interrupted").into());
}
Ok(())
});
assert!(matches!(outcome, CommitOutcome::NeedsRecovery(_)));
fs::write(root.join("profiles/target.yaml"), b"changed outside the refresh")?;
let error = recover_pending(root).unwrap_err();
assert!(
matches!(error, StoreError::NamedRecovery { name, source } if name == "工作线路" && matches!(*source, StoreError::LiveContentChanged(_)))
);
let journal = root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME);
fs::write(journal.join("index.next"), index.replace("工作线路", "Wrong"))?;
assert!(matches!(recover_pending(root), Err(StoreError::StagedChecksumMismatch)));
Ok(())
}
#[cfg(feature = "test-support")]
#[test]
fn legacy_companions_follow_the_refresh_decision() -> Result<(), clash_verge_profile_store::StoreError> {
for phase in ["prepared", "companion-installed", "decision-removed"] {
let home = tempfile::tempdir()?;
let root = home.path();
let profiles = root.join("profiles");
fs::create_dir(&profiles)?;
let old = "items: [{uid: r, type: remote, file: r.yaml}]";
fs::write(root.join("profiles.yaml"), old)?;
fs::write(profiles.join("r.yaml"), b"old")?;
let mut candidate: IProfiles = serde_yaml_ng::from_str(
"items: [{uid: r, type: remote, file: r.yaml, option: {script: s}}, {uid: s, type: script, file: s.js}]",
)?;
candidate.get_item_mut("s")?.file_data = Some("template".into());
let result = Session::open(root)?.commit_observed("r", &candidate, b"new", &mut |checkpoint| {
if checkpoint == phase {
return Err(std::io::Error::other("interrupted").into());
}
Ok(())
});
if phase == "decision-removed" {
assert!(matches!(result, CommitOutcome::CommittedCleanupPending(_)));
fs::write(profiles.join("s.js"), b"edited")?;
assert!(clash_verge_profile_store::recover_pending(root).is_err());
assert_eq!(fs::read(profiles.join("s.js"))?, b"edited");
assert!(root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME).exists());
continue;
}
assert_eq!(fs::read_to_string(root.join("profiles.yaml"))?, old);
if phase == "prepared" {
assert!(matches!(result, CommitOutcome::Retryable(_)));
clash_verge_profile_store::recover_pending(root)?;
assert!(!profiles.join("s.js").exists());
assert_eq!(fs::read(profiles.join("r.yaml"))?, b"old");
} else {
assert!(matches!(result, CommitOutcome::NeedsRecovery(_)));
clash_verge_profile_store::recover_pending(root)?;
let stored: IProfiles = serde_yaml_ng::from_slice(&fs::read(root.join("profiles.yaml"))?)?;
assert_eq!(stored.get_item("s")?.file.as_deref(), Some("s.js"));
assert_eq!(fs::read(profiles.join("r.yaml"))?, b"new");
assert_eq!(fs::read(profiles.join("s.js"))?, b"template");
}
}
Ok(())
}
+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:
+3 -9
View File
@@ -22,7 +22,6 @@ tokio-trace = ["clash-verge-logging/tokio-trace"]
chrome-trace = ["clash-verge-logging/chrome-trace"]
clippy = ["tauri/test"]
perf-harness = ["dep:tauri-plugin-wdio-webdriver"]
profile-store-windows = []
[package.metadata.bundle]
identifier = "io.github.clash-verge-rev.clash-verge-rev"
@@ -31,7 +30,6 @@ identifier = "io.github.clash-verge-rev.clash-verge-rev"
tauri-build = { version = "2.8.0", features = [] }
[dependencies]
tempfile = { workspace = true }
clash-verge-draft = { workspace = true }
clash-verge-task = { workspace = true }
clash-verge-media-unlock = { workspace = true }
@@ -83,11 +81,11 @@ tauri-plugin-dialog = { version = "2.9.0", default-features = false, features =
tauri-plugin-fs = "2.8.0"
tauri-plugin-deep-link = "2.6.3"
tauri-plugin-window-state = "2.5.1"
zip = { workspace = true }
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"
@@ -105,14 +103,11 @@ 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"
[target.'cfg(any(unix, windows))'.dependencies]
clash-verge-profile-store = { workspace = true }
[target.'cfg(unix)'.dependencies]
libc = "0.2.191"
@@ -126,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",
@@ -150,7 +145,6 @@ objc2-app-kit = { version = "0.3.2", features = [
] }
[target.'cfg(windows)'.dependencies]
zip = { workspace = true }
deelevate = { workspace = true }
quick-xml = "0.42.0"
runas = "=1.2.0"
+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:?}");
+10 -27
View File
@@ -34,23 +34,10 @@ fn profile_import_error(err: &anyhow::Error) -> std::string::String {
format!("导入订阅失败: {err:#}")
}
fn profile_command_error(error: anyhow::Error, fallback: Option<&str>) -> super::CommandFailure {
if error.is::<crate::config::profile_storage::RecoveryRequired>() {
coded_error("PROFILE_RECOVERY_REQUIRED", format_args!("{error:#}"))
} else if let Some(code) = fallback {
coded_error(code, format_args!("{error:#}"))
} else {
super::CommandFailure::plain(error)
}
}
#[tauri::command]
#[specta::specta]
pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
let draft = Config::profiles().await;
let _guard = crate::config::profile_storage::read()
.await
.map_err(|error| profile_command_error(error, None))?;
let data = draft.data_arc();
Ok(data)
}
@@ -155,10 +142,13 @@ pub async fn create_profile(item: ProfileCreate, file_data: Option<std::string::
#[specta::specta]
pub async fn update_profile(index: std::string::String, option: Option<PrfOption>) -> CmdResult {
let index: String = index.into();
feat::update_profile(&index, option.as_ref(), true)
.await
.inspect_err(|e| logging!(error, Type::Cmd, "update profile failed: {e:#}"))
.map_err(|error| profile_command_error(error, Some("PROFILE_UPDATE_FAILED")))
match feat::update_profile(&index, option.as_ref(), true).await {
Ok(_) => Ok(()),
Err(e) => {
logging!(error, Type::Cmd, "update profile failed: {e:#}");
Err(coded_error("PROFILE_UPDATE_FAILED", e))
}
}
}
#[tauri::command]
@@ -166,11 +156,8 @@ pub async fn update_profile(index: std::string::String, option: Option<PrfOption
pub async fn delete_profile(index: std::string::String) -> CmdResult {
let index: String = index.into();
let profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
crate::config::profile_storage::check().stringify_err()?;
let profiles = Config::profiles().await;
let mut storage_guard = None;
let slot = &mut storage_guard;
let result = profiles
.with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move {
let original = candidate.clone();
@@ -189,13 +176,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
None
};
let current = candidate.current.clone();
*slot = Some(crate::config::profile_storage::write().await?);
cleanup_profile_files(plan.files).await;
Ok((candidate, Ok((should_update, current, guard))))
})
.await
.with_error_code("PROFILE_DELETE_FAILED")?;
drop(storage_guard);
let (should_update, current, config_update_guard) = match result {
Ok(result) => result,
Err(outcome) => {
@@ -228,9 +213,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
commit_current_profile(&Config::profiles().await, Some(prev_profile.clone()))
Config::profiles()
.await
.stringify_err()?;
.edit_draft(|d| d.patch_current(Some(prev_profile)));
Config::profiles().await.apply();
crate::process::AsyncHandler::spawn(|| async move {
if let Err(e) = save_committed_profiles().await {
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
@@ -404,7 +390,6 @@ pub async fn patch_profiles_config(profiles: ProfileSelection) -> CmdResult<Vali
CURRENT_SWITCHING_PROFILE.store(false, Ordering::Release);
});
let _profile_write_guard = PROFILE_WRITE_LOCK.lock().await;
crate::config::profile_storage::check().stringify_err()?;
let target_profile = profiles.current.as_ref();
@@ -472,7 +457,6 @@ pub async fn patch_profile(index: std::string::String, profile: ProfilePatch) ->
#[tauri::command]
#[specta::specta]
pub async fn view_profile(index: std::string::String) -> CmdResult {
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc();
let file = profiles_ref
@@ -498,7 +482,6 @@ pub async fn view_profile(index: std::string::String) -> CmdResult {
#[tauri::command]
#[specta::specta]
pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::string::String> {
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
let file = {
let profiles = Config::profiles().await;
let profiles_ref = profiles.latest_arc();
+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 {
+30 -33
View File
@@ -2,7 +2,7 @@ use super::CmdResult;
use crate::{
cmd::StringifyErr as _,
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
config::{Config, IProfiles, profile_storage, profiles::PROFILE_WRITE_LOCK, read_profile_item_file},
config::{Config, IProfiles, read_profile_item_file},
core::auto_backup::{self, AutoBackupTrigger},
core::{
CoreManager, handle,
@@ -34,9 +34,6 @@ pub async fn save_profile_file(
_ => None,
};
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
let profile_guard = profile_storage::write().await.stringify_err()?;
// 在异步操作前获取必要元数据并释放锁
let (rel_path, is_merge_file, is_script_file, affects_runtime) = {
let profiles = Config::profiles().await;
@@ -51,6 +48,7 @@ pub async fn save_profile_file(
let profiles_dir = dirs::app_profiles_dir().stringify_err()?;
let file_path = profiles_dir.join(rel_path.as_str());
let file_path_str = file_path.to_string_lossy().to_string();
// 读取原始内容(在释放profiles_guard后进行)
let original_existed = fs::try_exists(&file_path).await.map_err(|err| {
@@ -60,22 +58,24 @@ pub async fn save_profile_file(
))
})?;
let original_content = if original_existed {
Some(read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()?)
read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()?
} else {
None
String::new()
};
// 保存新的配置文件
fs::write(&file_path, &file_data).await.stringify_err()?;
drop(profile_guard);
let original = OriginalProfileFile {
content: original_content.as_deref(),
written: &file_data,
};
let changes_applied =
validate_and_apply_profile(&file_path, &original, is_merge_file, is_script_file, affects_runtime).await?;
let changes_applied = handle_saved_profile_file(
&file_path_str,
&file_path,
&original_content,
original_existed,
is_merge_file,
is_script_file,
affects_runtime,
)
.await?;
if changes_applied.is_valid()
&& let Some(trigger) = backup_trigger
@@ -86,18 +86,13 @@ pub async fn save_profile_file(
Ok(changes_applied)
}
struct OriginalProfileFile<'a> {
content: Option<&'a str>,
written: &'a str,
}
async fn restore_original(file_path: &std::path::Path, original: &OriginalProfileFile<'_>) -> CmdResult<()> {
let _guard = profile_storage::write().await.stringify_err()?;
if fs::read(file_path).await.stringify_err()? != original.written.as_bytes() {
return Err("profile file changed during validation".into());
}
if let Some(content) = original.content {
fs::write(file_path, content).await.stringify_err()
async fn restore_original(
file_path: &std::path::Path,
original_content: &str,
original_existed: bool,
) -> CmdResult<()> {
if original_existed {
fs::write(file_path, original_content).await.stringify_err()
} else {
fs::remove_file(file_path).await.stringify_err()
}
@@ -124,9 +119,11 @@ fn profile_affects_runtime(profiles: &IProfiles, index: &str) -> bool {
.contains(&index)
}
async fn validate_and_apply_profile(
async fn handle_saved_profile_file(
file_path_str: &str,
file_path: &std::path::Path,
original: &OriginalProfileFile<'_>,
original_content: &str,
original_existed: bool,
is_merge_file: bool,
is_script_file: bool,
affects_runtime: bool,
@@ -139,17 +136,17 @@ async fn validate_and_apply_profile(
(ValidationNoticeTarget::Runtime, "YAML配置文件")
};
match CoreConfigValidator::validate_config_file_outcome(&file_path.to_string_lossy(), Some(is_merge_file)).await {
match CoreConfigValidator::validate_config_file_outcome(file_path_str, Some(is_merge_file)).await {
Ok(outcome) if outcome.is_valid() => {}
Ok(outcome) => {
logging!(warn, Type::Config, "[cmd配置save] 文件验证失败: {}", outcome);
restore_original(file_path, original).await?;
restore_original(file_path, original_content, original_existed).await?;
handle_validation_notice(&outcome, target, file_type);
return Ok(outcome);
}
Err(e) => {
logging!(error, Type::Config, "[cmd配置save] 验证过程发生错误: {e:#}");
restore_original(file_path, original).await?;
restore_original(file_path, original_content, original_existed).await?;
return Err(e.to_string().into());
}
}
@@ -170,13 +167,13 @@ async fn validate_and_apply_profile(
}
Ok(outcome) => {
logging!(warn, Type::Config, "[cmd配置save] 运行时配置应用失败: {}", outcome);
restore_original(file_path, original).await?;
restore_original(file_path, original_content, original_existed).await?;
handle_validation_notice(&outcome, ValidationNoticeTarget::Runtime, "运行时配置");
Ok(outcome)
}
Err(err) => {
logging!(error, Type::Config, "[cmd配置save] 运行时配置应用错误: {err:#}");
restore_original(file_path, original).await?;
restore_original(file_path, original_content, original_existed).await?;
Err(err.to_string().into())
}
}
+3 -5
View File
@@ -22,12 +22,10 @@ pub async fn save_webdav_config(
webdav_password: Some(password),
..IVerge::default()
};
let _config_write = Config::lock_config_write().await;
let verge = Config::verge().await;
verge.edit_draft(|e| e.patch_config(&patch));
verge.apply();
Config::verge().await.edit_draft(|e| e.patch_config(&patch));
Config::verge().await.apply();
let verge_data = verge.data_arc();
let verge_data = Config::verge().await.data_arc();
verge_data.save_file().await.stringify_err()?;
core::backup::WebDavClient::global().reset();
Ok(())
+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
}
+10 -99
View File
@@ -1,10 +1,9 @@
use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml};
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
use crate::core::notify::NoticeStatus;
use crate::{
config::{
prfitem::{build_merge_profile, build_script_profile},
profile_storage,
profiles::{append_to_profile_index, load_profiles, save_profiles_unlocked},
profiles::{append_to_profile_index, load_profiles, save_profiles},
runtime::IRuntime,
},
constants::{files, timing},
@@ -21,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;
@@ -85,7 +84,6 @@ impl Config {
}
pub async fn init_config_before_window() -> Result<()> {
profile_storage::check()?;
Self::ensure_default_profile_items().await?;
let verge = Self::verge().await.latest_arc();
@@ -232,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)
})
@@ -247,24 +245,12 @@ impl Config {
}
pub async fn generate() -> Result<()> {
let profiles = Self::profiles().await;
let inputs = {
let _guard = profile_storage::read().await?;
enhance::collect_render_inputs(&profiles.latest_arc()).await?
};
Self::generate_from_inputs(inputs).await
let profiles = Self::profiles().await.latest_arc();
Self::generate_with_profiles(&profiles).await
}
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
let inputs = {
let _guard = profile_storage::read().await?;
enhance::collect_render_inputs(profiles).await?
};
Self::generate_from_inputs(inputs).await
}
async fn generate_from_inputs(inputs: enhance::ProfileRenderInputs) -> Result<()> {
let (mut config, exists_keys, logs, dns_override) = enhance::render_runtime_config(inputs).await;
let (mut config, exists_keys, logs, dns_override) = enhance::render_runtime_config(profiles).await?;
resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?;
sanitize_tunnels_proxy(&mut config);
@@ -327,86 +313,11 @@ impl Config {
let save_profiles_task = AsyncHandler::spawn(|| async {
let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await;
let profiles = Self::profiles().await;
let mut storage_guard = None;
let slot = &mut storage_guard;
let draft = &profiles;
let result = profiles
.with_data_modify(|_| async move {
*slot = Some(profile_storage::write().await?);
let candidate = (**draft.latest_arc()).clone();
let saved = save_profiles_unlocked(&candidate).await;
draft.discard();
Ok((candidate, saved))
})
.await;
drop(storage_guard);
logging_error!(Type::Config, result.and_then(std::convert::identity));
profiles.apply();
logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await);
});
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
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 -3
View File
@@ -3,11 +3,9 @@ mod clash;
mod config;
pub(crate) mod dns;
mod encrypt;
pub(crate) mod mihomo_yaml;
mod mixed_port;
mod port;
mod prfitem;
pub(crate) mod profile_storage;
pub mod profiles;
pub mod runtime;
pub(crate) mod snapshot;
@@ -15,7 +13,7 @@ mod verge;
pub(crate) use self::config::Config;
pub(crate) use self::prfitem::{
build_remote_profile, download_subscription, read_profile_item_file, subscription_proxy,
build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file, subscription_proxy,
};
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
+66 -61
View File
@@ -44,26 +44,15 @@ pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) ->
}
}
fn missing_companions(options: &mut PrfOption) -> Vec<PrfItem> {
let mut companions = Vec::new();
for (reference, build) in [
(&mut options.merge, (|| build_merge_profile(None)) as fn() -> PrfItem),
(&mut options.script, || build_script_profile(None)),
(&mut options.rules, from_rules),
(&mut options.proxies, from_proxies),
(&mut options.groups, from_groups),
] {
if reference.is_none() {
let item = build();
*reference = item.uid.clone();
companions.push(item);
}
}
companions
async fn append_companion_item(item: &mut PrfItem) -> Result<String> {
profiles::append_profile(item).await?;
item.uid
.clone()
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
}
fn creation_options(source: Option<&PrfOption>) -> PrfOption {
PrfOption {
async fn prepare_profile_options(source: Option<&PrfOption>) -> Result<PrfOption> {
let mut options = PrfOption {
update_interval: source.and_then(|options| options.update_interval),
merge: source.and_then(|options| options.merge.clone()),
script: source.and_then(|options| options.script.clone()),
@@ -71,14 +60,23 @@ fn creation_options(source: Option<&PrfOption>) -> PrfOption {
proxies: source.and_then(|options| options.proxies.clone()),
groups: source.and_then(|options| options.groups.clone()),
..PrfOption::default()
};
if options.merge.is_none() {
options.merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
}
}
async fn append_companions(companions: Vec<PrfItem>) -> Result<()> {
for mut item in companions {
profiles::append_profile(&mut item).await?;
if options.script.is_none() {
options.script = Some(append_companion_item(&mut build_script_profile(None)).await?);
}
Ok(())
if options.rules.is_none() {
options.rules = Some(append_companion_item(&mut from_rules()).await?);
}
if options.proxies.is_none() {
options.proxies = Some(append_companion_item(&mut from_proxies()).await?);
}
if options.groups.is_none() {
options.groups = Some(append_companion_item(&mut from_groups()).await?);
}
Ok(options)
}
async fn from_local(
@@ -89,8 +87,7 @@ async fn from_local(
) -> Result<PrfItem> {
let uid = help::get_uid("L").into();
let file = format!("{uid}.yaml").into();
let mut options = creation_options(option);
append_companions(missing_companions(&mut options)).await?;
let options = prepare_profile_options(option).await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("local".into()),
@@ -116,16 +113,12 @@ pub(crate) struct DownloadedSubscription {
body: String,
}
impl DownloadedSubscription {
pub(super) fn apply(self, item: &mut PrfItem) -> (String, Vec<PrfItem>) {
let option = item.option.get_or_insert_with(PrfOption::default);
option.update_interval = option.update_interval.or(self.update_interval_minutes);
option.allow_auto_update.get_or_insert(true);
item.home = self.home;
item.extra = self.extra;
item.updated = Some(chrono::Local::now().timestamp() as usize);
(self.body, missing_companions(option))
}
pub(crate) struct RemoteProfileRefresh {
pub(super) extra: Option<PrfExtra>,
pub(super) home: Option<String>,
pub(super) updated: usize,
pub(super) option: PrfOption,
pub(super) body: String,
}
pub(crate) async fn build_remote_profile(
@@ -142,22 +135,28 @@ pub(crate) async fn build_remote_profile(
.or_else(|| downloaded.suggested_name.take().map(Into::into))
.unwrap_or_else(|| "Remote File".into());
let url = downloaded.url.as_str().into();
let mut options = creation_options(option);
options.allow_auto_update = option.and_then(|value| value.allow_auto_update);
let mut item = PrfItem {
let RemoteProfileRefresh {
extra,
home,
updated,
option,
body,
} = prepare_remote_refresh(downloaded, option).await?;
Ok(PrfItem {
uid: Some(uid),
itype: Some("remote".into()),
name: Some(name),
desc: desc.cloned(),
file: Some(file),
url: Some(url),
option: Some(options),
..Default::default()
};
let (body, companions) = downloaded.apply(&mut item);
append_companions(companions).await?;
item.file_data = Some(body);
Ok(item)
selected: None,
extra,
option: Some(option),
home,
updated: Some(updated),
file_data: Some(body),
})
}
pub(crate) fn subscription_proxy(options: Option<&PrfOption>) -> ProxyType {
@@ -213,6 +212,22 @@ pub(crate) async fn download_subscription(
})
}
pub(crate) async fn prepare_remote_refresh(
downloaded: DownloadedSubscription,
option: Option<&PrfOption>,
) -> Result<RemoteProfileRefresh> {
let mut options = prepare_profile_options(option).await?;
options.update_interval = options.update_interval.or(downloaded.update_interval_minutes);
options.allow_auto_update = Some(option.and_then(|options| options.allow_auto_update).unwrap_or(true));
Ok(RemoteProfileRefresh {
extra: downloaded.extra,
home: downloaded.home,
updated: chrono::Local::now().timestamp() as usize,
option: options,
body: downloaded.body,
})
}
pub(super) fn build_merge_profile(uid: Option<String>) -> PrfItem {
let (id, template) = if let Some(uid) = uid {
(uid, tmpl::ITEM_MERGE.into())
@@ -365,14 +380,7 @@ mod tests {
..option
};
let downloaded = download_subscription(&url, Some(&refresh_option), ProxyType::None).await?;
let mut refresh = PrfItem {
option: Some(PrfOption {
groups: None,
..refresh_option.clone()
}),
..Default::default()
};
let (body, companions) = downloaded.apply(&mut refresh);
let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?;
server.await??;
assert_eq!(item.itype.as_deref(), Some("remote"));
assert_eq!(item.name.as_deref(), Some("remote.yaml"));
@@ -385,19 +393,16 @@ mod tests {
assert_eq!(fetched_option.update_interval, Some(0));
assert_eq!(fetched_option.allow_auto_update, Some(false));
assert_eq!(body.as_str(), BODY);
assert_eq!(refresh.body.as_str(), BODY);
assert_eq!(refresh.home, item.home);
let usage = refresh.extra.context("expected refresh usage")?;
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
assert_eq!(companions.len(), 1);
assert_eq!(companions[0].itype.as_deref(), Some("groups"));
assert_eq!(
refresh.option,
Some(PrfOption {
PrfOption {
update_interval: Some(120),
groups: companions[0].uid.clone(),
..refresh_option
})
..fetched_option
}
);
Ok(())
}
-342
View File
@@ -1,342 +0,0 @@
use anyhow::{Result, anyhow};
use clash_verge_logging::{Type, logging};
use clash_verge_profile_store::RECOVERY_JOURNAL_NAME;
use parking_lot::Mutex;
use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
static PROFILE_IO: RwLock<()> = RwLock::const_new(());
static BLOCKED: Mutex<Option<StorageBlock>> = Mutex::new(None);
enum StorageBlock {
Transaction(RecoveryRequired),
Restore(String),
}
#[derive(Clone, Debug)]
pub(crate) struct RecoveryRequired(Option<String>);
impl std::fmt::Display for RecoveryRequired {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&match self.0.as_deref() {
Some(name) => clash_verge_i18n::t!("profileRecovery.named", name = name),
None => clash_verge_i18n::t!("profileRecovery.unknown"),
})
}
}
impl std::error::Error for RecoveryRequired {}
pub(crate) fn check() -> Result<()> {
match BLOCKED.lock().as_ref() {
Some(StorageBlock::Transaction(recovery)) => Err(recovery.clone().into()),
Some(StorageBlock::Restore(reason)) => Err(anyhow!("Profile storage requires recovery before use: {reason}")),
None => Ok(()),
}
}
pub(crate) fn block(name: Option<&str>, error: &anyhow::Error) -> anyhow::Error {
logging!(error, Type::Config, "Profile recovery required: {error:#}");
let mut blocked = BLOCKED.lock();
if let Some(StorageBlock::Transaction(recovery)) = blocked.as_ref() {
return recovery.clone().into();
}
let recovery = RecoveryRequired(name.filter(|name| !name.trim().is_empty()).map(str::to_owned));
*blocked = Some(StorageBlock::Transaction(recovery.clone()));
drop(blocked);
recovery.into()
}
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
fn block_store(error: clash_verge_profile_store::StoreError) -> anyhow::Error {
match error {
clash_verge_profile_store::StoreError::NamedRecovery { name, source } => {
block(Some(&name), &anyhow::Error::from(*source))
}
error => block(None, &error.into()),
}
}
pub(crate) fn block_restore(error: &anyhow::Error) {
let mut blocked = BLOCKED.lock();
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
*blocked = Some(StorageBlock::Restore(format!("{error:#}")));
}
}
pub(crate) async fn write_for_restore() -> Result<(RwLockWriteGuard<'static, ()>, bool)> {
let guard = PROFILE_IO.write().await;
let retry = match BLOCKED.lock().as_ref() {
Some(StorageBlock::Transaction(reason)) => {
return Err(reason.clone().into());
}
Some(StorageBlock::Restore(_)) => true,
None => false,
};
Ok((guard, retry))
}
pub(crate) fn finish_restore(_guard: &RwLockWriteGuard<'_, ()>) {
let mut blocked = BLOCKED.lock();
if matches!(*blocked, Some(StorageBlock::Restore(_))) {
*blocked = None;
}
}
pub(crate) async fn read() -> Result<RwLockReadGuard<'static, ()>> {
let guard = PROFILE_IO.read().await;
check()?;
Ok(guard)
}
pub(crate) async fn write() -> Result<RwLockWriteGuard<'static, ()>> {
let guard = PROFILE_IO.write().await;
check()?;
Ok(guard)
}
pub(crate) async fn recover_at_startup() -> Result<()> {
let _guard = write().await?;
let root = crate::utils::dirs::app_home_dir().map_err(|error| block(None, &error))?;
if !journal_exists(&root).await.map_err(|error| block(None, &error))? {
return Ok(());
}
tokio::task::spawn_blocking(move || {
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
return clash_verge_profile_store::recover_pending(&root).map_err(block_store);
#[cfg(all(windows, not(feature = "profile-store-windows")))]
return Err(block(
clash_verge_profile_store::pending_refresh_name(&root).as_deref(),
&anyhow!("restore the pending profile transaction with redo support enabled"),
));
})
.await
.map_err(|error| block(None, &error.into()))?
}
async fn journal_exists(root: &std::path::Path) -> Result<bool> {
match tokio::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)).await {
Ok(_) => Ok(true),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
Err(error) => Err(error.into()),
}
}
pub(super) async fn commit_refresh(
uid: String,
candidate: super::IProfiles,
body: tristr::alias::String,
) -> Result<super::IProfiles> {
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
let mut candidate = commit_recoverable_refresh(uid, candidate, body).await?;
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
let mut candidate = {
write_legacy_refresh(&crate::utils::dirs::app_home_dir()?, &uid, &candidate, body.as_bytes()).await?;
candidate
};
for item in candidate.items.iter_mut().flatten() {
item.file_data = None;
}
Ok(candidate)
}
#[cfg(any(not(unix), test))]
async fn write_legacy_refresh(
root: &std::path::Path,
uid: &str,
candidate: &super::IProfiles,
body: &[u8],
) -> Result<()> {
use anyhow::Context as _;
let file = candidate
.get_item(uid)?
.file
.as_deref()
.context("missing profile filename")?;
let path = root.join(crate::utils::dirs::PROFILES_DIR).join(file);
let mut target = tokio::fs::File::create(path)
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
use tokio::io::AsyncWriteExt as _;
async {
target.write_all(body).await?;
target.flush().await
}
.await
.with_context(|| format!("profile body {file} may be incomplete; the index was not updated"))?;
drop(target);
let mut created = Vec::new();
let result: Result<()> = async {
for item in candidate.items.iter().flatten() {
let Some(data) = &item.file_data else { continue };
let name = item.file.as_deref().context("missing companion filename")?;
super::profiles::validate_profile_file(name)?;
let path = root.join(crate::utils::dirs::PROFILES_DIR).join(name);
let mut options = tokio::fs::OpenOptions::new();
options.create_new(true).write(true);
#[cfg(windows)]
{
use windows_sys::Win32::Storage::FileSystem::{DELETE, FILE_GENERIC_WRITE, FILE_SHARE_READ};
options
.access_mode(FILE_GENERIC_WRITE | DELETE)
.share_mode(FILE_SHARE_READ);
}
let mut file = options.open(&path).await?;
let written = async {
file.write_all(data.as_bytes()).await?;
file.flush().await
}
.await;
created.push((path, file));
written?;
}
super::profiles::save_profile_index(&root.join(crate::utils::dirs::PROFILE_YAML), candidate).await
}
.await;
if let Err(error) = result {
let mut error = error;
for (path, file) in created {
#[cfg(windows)]
let cleanup = {
use std::os::windows::io::AsRawHandle as _;
use windows_sys::Win32::Storage::FileSystem::{
FILE_DISPOSITION_INFO, FileDispositionInfo, SetFileInformationByHandle,
};
let disposition = FILE_DISPOSITION_INFO { DeleteFile: 1 };
// Remove only the file this refresh created, even if its parent has been renamed.
let deleted = unsafe {
SetFileInformationByHandle(
file.as_raw_handle(),
FileDispositionInfo,
(&raw const disposition).cast(),
std::mem::size_of::<FILE_DISPOSITION_INFO>() as u32,
)
};
if deleted == 0 {
Err(std::io::Error::last_os_error())
} else {
Ok(())
}
};
#[cfg(not(windows))]
let cleanup = {
drop(file);
tokio::fs::remove_file(&path).await
};
if let Err(cleanup) = cleanup {
error = error.context(format!("failed to clean up {}: {cleanup}", path.display()));
}
}
return Err(error)
.with_context(|| format!("profile body was written to {file}, but the index was not updated"));
}
Ok(())
}
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
async fn commit_recoverable_refresh(
uid: String,
candidate: super::IProfiles,
body: tristr::alias::String,
) -> Result<super::IProfiles> {
use clash_verge_profile_store::{CommitOutcome, Session};
let root = crate::utils::dirs::app_home_dir()?;
#[cfg(windows)]
{
let probe_root = root.clone();
let supported =
tokio::task::spawn_blocking(move || clash_verge_profile_store::supports_redo(&probe_root)).await??;
if !supported {
if journal_exists(&root).await? {
let error = anyhow!("Profile refresh journal requires a supported NTFS volume");
return Err(block(
clash_verge_profile_store::pending_refresh_name(&root).as_deref(),
&error,
));
}
write_legacy_refresh(&root, &uid, &candidate, body.as_bytes()).await?;
return Ok(candidate);
}
}
let result = tokio::task::spawn_blocking(move || {
let session = Session::open(&root).map_err(|error| {
match std::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
Err(status) if status.kind() == std::io::ErrorKind::NotFound => error.into(),
_ => block_store(error),
}
})?;
let item = candidate.get_item(&uid)?;
if let Some(file) = item.file.as_deref()
&& !file.contains(['/', '\\', '\0'])
&& (!cfg!(windows) || !file.contains(':'))
&& !matches!(file, "" | "." | "..")
{
let path = root.join("profiles").join(file);
match std::fs::symlink_metadata(&path) {
Ok(metadata) if metadata.is_file() => {
std::fs::OpenOptions::new().write(true).open(&path)?;
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error.into()),
}
}
match session.commit_refresh(&uid, &candidate, body.as_bytes()) {
CommitOutcome::Committed => Ok(candidate),
CommitOutcome::CommittedCleanupPending(error) => {
let _ = block(item.name.as_deref(), &error.into());
Ok(candidate)
}
CommitOutcome::Retryable(error) => {
Err(anyhow::Error::from(error).context("profile refresh stopped before commit"))
}
CommitOutcome::RetryCleanupFailed(error) => {
let error = anyhow::Error::from(error);
Err(block(item.name.as_deref(), &error).context("failed to discard the incomplete profile refresh"))
}
CommitOutcome::NeedsRecovery(error) => {
let error = anyhow::Error::from(error);
Err(block(item.name.as_deref(), &error))
}
}
})
.await;
match result {
Ok(result) => result,
Err(error) => {
let error = anyhow::Error::from(error).context("profile storage worker stopped unexpectedly");
Err(block(None, &error))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn recovery_message_identifies_the_subscription_in_the_active_language() {
let named = RecoveryRequired(Some("工作线路".into())).to_string();
assert!(named.contains("工作线路"));
let unknown = RecoveryRequired(None).to_string();
assert!(!unknown.contains("工作线路"));
assert_ne!(unknown, "profileRecovery.unknown");
}
#[tokio::test]
async fn legacy_refresh_reports_a_written_body_when_index_replace_fails() -> Result<()> {
let home = tempfile::tempdir()?;
let root = home.path();
std::fs::create_dir(root.join("profiles"))?;
std::fs::create_dir(root.join("profiles.yaml"))?;
let mut profiles: super::super::IProfiles =
serde_yaml_ng::from_str("items: [{uid: r, file: old.yaml}, {uid: s, type: script, file: s.js}]")?;
profiles.get_item_mut("s")?.file_data = Some("template".into());
let result = write_legacy_refresh(root, "r", &profiles, b"new body").await;
assert_eq!(std::fs::read(root.join("profiles/old.yaml"))?, b"new body");
assert!(result.unwrap_err().to_string().contains("body was written"));
assert!(!root.join("profiles/s.js").exists());
Ok(())
}
}
+69 -109
View File
@@ -1,7 +1,6 @@
use super::{
PrfItem, PrfOption, PrfSelected, patch_opt_field,
prfitem::{DownloadedSubscription, build_profile},
profile_storage,
prfitem::{RemoteProfileRefresh, build_profile},
};
use crate::core::notify::{Refresh, announce};
use crate::{
@@ -71,62 +70,58 @@ pub(crate) async fn cleanup_profile_files(files: Vec<String>) {
}
pub(crate) async fn load_profiles() -> IProfiles {
match load_profiles_checked().await {
Ok(profiles) => profiles,
Err(error) => {
logging!(error, Type::Config, "failed to load profiles: {error:#}");
let path = match dirs::profiles_path() {
Ok(p) => p,
Err(err) => {
logging!(error, Type::Config, "failed to get profiles path: {err:#}");
return IProfiles::default();
}
};
match help::read_yaml::<IProfiles>(&path).await {
Ok(mut profiles) => {
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
for item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d").into());
}
if item.itype.as_deref() == Some("remote") {
item.option
.get_or_insert_with(PrfOption::default)
.allow_auto_update
.get_or_insert(true);
}
if item
.home
.as_deref()
.is_some_and(|home| normalize_profile_home_url(home).is_none())
{
item.home = None;
home_changed = true;
}
}
if home_changed && let Err(err) = save_profiles(&profiles).await {
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
}
profiles
}
Err(err) => {
logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}");
IProfiles::default()
}
}
}
async fn load_profiles_checked() -> Result<IProfiles> {
profile_storage::check()?;
load_profiles_unlocked().await
}
pub(crate) async fn load_profiles_unlocked() -> Result<IProfiles> {
let mut profiles: IProfiles = help::read_yaml(&dirs::profiles_path()?).await?;
let items = profiles.items.get_or_insert_with(Vec::new);
let mut home_changed = false;
for item in items.iter_mut() {
if item.uid.is_none() {
item.uid = Some(help::get_uid("d").into());
}
if item.itype.as_deref() == Some("remote") {
item.option
.get_or_insert_with(PrfOption::default)
.allow_auto_update
.get_or_insert(true);
}
if item
.home
.as_deref()
.is_some_and(|home| normalize_profile_home_url(home).is_none())
{
item.home = None;
home_changed = true;
}
}
if home_changed && let Err(err) = save_profiles_unlocked(&profiles).await {
logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}");
}
Ok(profiles)
}
pub(crate) async fn save_profiles(profiles: &IProfiles) -> Result<()> {
let _guard = profile_storage::write().await?;
save_profiles_unlocked(profiles).await
}
pub(crate) async fn save_profiles_unlocked(profiles: &IProfiles) -> Result<()> {
save_profile_index(&dirs::profiles_path()?, profiles).await
}
pub(super) async fn save_profile_index(path: &Path, profiles: &IProfiles) -> Result<()> {
help::save_yaml(path, profiles, Some("# Profiles Config for Clash Verge")).await
help::save_yaml(
&dirs::profiles_path()?,
profiles,
Some("# Profiles Config for Clash Verge"),
)
.await
}
async fn append_item(profiles: &mut IProfiles, item: &mut PrfItem) -> Result<()> {
@@ -182,7 +177,7 @@ async fn patch_item(profiles: &mut IProfiles, uid: &str, item: &PrfItem) -> Resu
bail!("failed to find the profile item \"uid:{uid}\"")
}
pub(crate) fn validate_profile_file(file: &str) -> Result<()> {
fn validate_profile_file(file: &str) -> Result<()> {
let mut components = Path::new(file).components();
if file.is_empty()
|| file.contains('/')
@@ -266,7 +261,6 @@ pub(crate) async fn append_profile(item: &mut PrfItem) -> Result<()> {
pub(super) async fn append_to_profile_index(profiles: &Draft<IProfiles>, item: &mut PrfItem) -> Result<()> {
profiles
.with_data_modify(|mut profiles| async move {
let _guard = profile_storage::write().await?;
append_item(&mut profiles, item).await?;
Ok((profiles, ()))
})
@@ -295,62 +289,28 @@ pub(crate) async fn save_committed_profiles() -> Result<()> {
with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await
}
fn check_refresh_source(current: &PrfItem, url: &str, file: Option<&String>) -> Result<()> {
anyhow::ensure!(
current.itype.as_deref() == Some("remote")
&& current.url.as_deref() == Some(url)
&& current.file.as_ref() == file,
"profile source or filename changed during refresh"
);
Ok(())
}
pub(crate) async fn save_remote_refresh(
uid: &str,
url: String,
file: Option<String>,
downloaded: DownloadedSubscription,
) -> Result<()> {
let uid = uid.to_owned();
// Dropping the caller must not separate an issued disk write from its Draft publication.
tokio::spawn(async move {
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
anyhow::ensure!(!handle::Handle::global().is_exiting(), "application is exiting");
let draft = Config::profiles().await;
let mut name = None;
let mut storage_guard = None;
let mut persisted = false;
let result = {
let storage_guard = &mut storage_guard;
let persisted = &mut persisted;
let name = &mut name;
draft
.with_data_modify(|mut candidate| async move {
*storage_guard = Some(profile_storage::write().await?);
let profile = candidate.get_item_mut(&uid)?;
check_refresh_source(profile, &url, file.as_ref())?;
*name = profile.name.clone();
let (body, companions) = downloaded.apply(profile);
profile
.file
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
candidate.items.get_or_insert_with(Vec::new).extend(companions);
let candidate = profile_storage::commit_refresh(uid, candidate, body).await?;
*persisted = true;
Ok((candidate, ()))
})
.await
};
if let Err(error) = &result
&& persisted
{
return Err(profile_storage::block(name.as_deref(), error).context("Profile refresh was saved"));
}
drop(storage_guard);
result?;
profile_storage::check().context("Profile refresh was saved")
pub(crate) async fn save_remote_refresh(uid: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> {
with_profiles_edit(|mut profiles| async move {
let profile = profiles.get_item_mut(uid)?;
anyhow::ensure!(
profile.itype.as_deref() == Some("remote") && profile.url.as_deref() == Some(url),
"profile source changed during refresh"
);
profile.extra = refresh.extra;
profile.updated = Some(refresh.updated);
profile.home = refresh.home;
profile.option = PrfOption::merge(profile.option.as_ref(), Some(&refresh.option));
let file = profile
.file
.get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into());
let path = dirs::app_profiles_dir()?.join(file.as_str());
fs::write(&path, refresh.body.as_bytes())
.await
.with_context(|| format!("failed to write to file \"{file}\""))?;
save_profiles(&profiles).await?;
Ok(profiles)
})
.await?
.await
}
fn selected_group<'a>(snapshot: &'a Proxies, name: &str) -> Option<SelectedGroup<'a>> {
+15 -15
View File
@@ -277,22 +277,20 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
let mut archive = BackupWriter::new(file)?;
let profile_guard = crate::config::profile_storage::read().await?;
let mut entries = fs::read_dir(dirs::app_profiles_dir()?).await?;
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.is_file() {
let file_name_os = entry.file_name();
let file_name = file_name_os
.to_str()
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
let mut entry = archive.start_profile(file_name)?;
let file_content = fs::read(&path).await?;
entry.write_all(&file_content)?;
if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await {
while let Some(entry) = entries.next_entry().await? {
let path = entry.path();
if path.is_file() {
let file_name_os = entry.file_name();
let file_name = file_name_os
.to_str()
.ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?;
let mut entry = archive.start_profile(file_name)?;
let file_content = fs::read(&path).await?;
entry.write_all(&file_content)?;
}
}
}
let profile_index = fs::read(dirs::profiles_path()?).await?;
drop(profile_guard);
archive
.start_file(dirs::CLASH_CONFIG)?
@@ -316,7 +314,9 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
.write_all(&fs::read(&dns_config_path).await?)?;
}
archive.start_file(dirs::PROFILE_YAML)?.write_all(&profile_index)?;
archive
.start_file(dirs::PROFILE_YAML)?
.write_all(&fs::read(dirs::profiles_path()?).await?)?;
archive.finish()?;
Ok((zip_file_name, zip_path))
}
+2 -2
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,
@@ -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(())
-2
View File
@@ -231,8 +231,6 @@ impl CoreManager {
pub async fn init(&self) -> Result<bool> {
const MAX_PORT_FALLBACK_RETRIES: usize = 3;
crate::config::profile_storage::check()?;
if let Some(reason) = crate::config::Config::startup_core_block_reason() {
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
}
+1 -2
View File
@@ -35,7 +35,6 @@ pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::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)?;
@@ -48,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;
+5 -1
View File
@@ -36,6 +36,8 @@ pub enum NoticeStatus {
AppQuitCoreStopFailed,
#[serde(rename = "update_with_clash_proxy")]
UpdateWithClashProxy,
#[serde(rename = "update_failed_even_with_clash")]
UpdateFailedEvenWithClash,
#[serde(rename = "reactivate_profiles::error")]
ReactivateProfilesError,
#[serde(rename = "update_failed")]
@@ -79,7 +81,7 @@ 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,
@@ -94,6 +96,7 @@ impl NoticeStatus {
Self::AppRestartCoreStopFailed,
Self::AppQuitCoreStopFailed,
Self::UpdateWithClashProxy,
Self::UpdateFailedEvenWithClash,
Self::ReactivateProfilesError,
Self::UpdateFailed,
Self::ConfigValidateBootError,
@@ -137,6 +140,7 @@ mod tests {
"app_restart::core_stop_failed",
"app_quit::core_stop_failed",
"update_with_clash_proxy",
"update_failed_even_with_clash",
"reactivate_profiles::error",
"update_failed",
"config_validate::boot_error",
+2 -2
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,
@@ -613,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()
+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()));
+33 -39
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;
@@ -132,7 +132,7 @@ async fn get_config_values(profile_uid: &str) -> ConfigValues {
#[allow(clippy::cognitive_complexity)]
async fn collect_profile_items(profiles: &IProfiles) -> Result<RenderProfile> {
let current_profile_uid = match profiles.current.as_deref() {
let current_profile_uid = match profiles.current.clone() {
Some(uid) => uid,
None => return Ok(default_profile()),
};
@@ -141,18 +141,27 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result<RenderProfile> {
.await
.with_context(|| format!("failed to read current profile \"{current_profile_uid}\""))?;
let current_item = match profiles.get_item(current_profile_uid) {
let current_item = match profiles.get_item(&current_profile_uid) {
Ok(item) => item,
Err(err) => {
return Err(err).with_context(|| format!("failed to get current profile \"{current_profile_uid}\""));
}
};
let merge_uid = current_item.current_merge().map_or("Merge", String::as_str);
let script_uid = current_item.current_script().map_or("Script", String::as_str);
let rules_uid = current_item.current_rules().map_or("Rules", String::as_str);
let proxies_uid = current_item.current_proxies().map_or("Proxies", String::as_str);
let groups_uid = current_item.current_groups().map_or("Groups", String::as_str);
let merge_uid = current_item.current_merge().cloned().unwrap_or_else(|| "Merge".into());
let script_uid = current_item
.current_script()
.cloned()
.unwrap_or_else(|| "Script".into());
let rules_uid = current_item.current_rules().cloned().unwrap_or_else(|| "Rules".into());
let proxies_uid = current_item
.current_proxies()
.cloned()
.unwrap_or_else(|| "Proxies".into());
let groups_uid = current_item
.current_groups()
.cloned()
.unwrap_or_else(|| "Groups".into());
let name = current_item.name.clone().unwrap_or_default();
@@ -168,11 +177,11 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result<RenderProfile> {
} = default_profile();
let (merge_item, script_item, rules_item, proxies_item, groups_item, global_merge, global_script) = tokio::join!(
chain_item_or_default(profiles.get_item(merge_uid).ok(), || default_merge,),
chain_item_or_default(profiles.get_item(script_uid).ok(), || default_script,),
chain_item_or_default(profiles.get_item(rules_uid).ok(), || default_rules,),
chain_item_or_default(profiles.get_item(proxies_uid).ok(), || default_proxies,),
chain_item_or_default(profiles.get_item(groups_uid).ok(), || default_groups,),
chain_item_or_default(profiles.get_item(&merge_uid).ok(), || default_merge,),
chain_item_or_default(profiles.get_item(&script_uid).ok(), || default_script,),
chain_item_or_default(profiles.get_item(&rules_uid).ok(), || default_rules,),
chain_item_or_default(profiles.get_item(&proxies_uid).ok(), || default_proxies,),
chain_item_or_default(profiles.get_item(&groups_uid).ok(), || default_groups,),
chain_item_or_default(profiles.get_item("Merge").ok(), || default_global_merge,),
chain_item_or_default(profiles.get_item("Script").ok(), || default_global_script,),
);
@@ -235,48 +244,33 @@ async fn read_dns_settings(enabled: bool) -> Option<Mapping> {
serde_yaml_ng::from_str(&yaml).ok()
}
pub(crate) struct ProfileRenderInputs {
profile: RenderProfile,
settings: RenderSettings,
dns_config: Option<Mapping>,
dns_override: DnsOverrideState,
}
pub(crate) async fn collect_render_inputs(profiles: &IProfiles) -> Result<ProfileRenderInputs> {
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
pub async fn render_runtime_config(
profiles: &IProfiles,
) -> Result<(Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState)> {
let profile_uid = profiles.current.as_deref().unwrap_or_default();
let settings = get_config_values(profile_uid).await;
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,
);
let dns_config = read_dns_settings(dns_override.enabled).await;
Ok(ProfileRenderInputs {
profile,
settings: settings.render,
dns_config,
dns_override,
})
}
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
pub(crate) async fn render_runtime_config(
inputs: ProfileRenderInputs,
) -> (Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState) {
let RenderedConfig {
config,
exists_keys,
logs,
discarded_keys,
} = render(
inputs.profile,
inputs.settings,
inputs.dns_config,
profile,
settings.render,
dns_config,
clash_verge_profile_script::execute,
)
.await;
notify_discarded_keys(discarded_keys);
(config, exists_keys, logs, inputs.dns_override)
Ok((config, exists_keys, logs, dns_override))
}
+75 -285
View File
@@ -1,29 +1,18 @@
use crate::{
config::{
Config, IClashTemp, IProfiles, IVerge, profile_storage,
profiles::{load_profiles_unlocked, validate_profile_file},
},
config::{Config, IClashTemp, IVerge, profiles::load_profiles},
core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown},
process::AsyncHandler,
utils::{
dirs::{
PROFILE_YAML, PROFILES_DIR, PathBufExec as _, VERGE_CONFIG, app_home_dir, local_backup_dir, verge_path,
},
dirs::{PathBufExec as _, app_home_dir, local_backup_dir, verge_path},
help,
},
};
use anyhow::{Context as _, Result, anyhow};
use anyhow::{Result, anyhow};
use chrono::Utc;
use clash_verge_backup_archive::{BackupArchive, StagedBackup};
use clash_verge_draft::DraftConflict;
use clash_verge_logging::{Type, logging};
use clash_verge_profile_store::RECOVERY_ENTRY_NAMES;
use reqwest_dav::list_cmd::ListFile;
use serde::Serialize;
use std::{
fs::File,
path::{Path, PathBuf},
};
use std::path::PathBuf;
use tokio::fs;
use tristr::alias::String;
@@ -35,39 +24,21 @@ pub struct LocalBackupFile {
pub content_length: u64,
}
async fn apply_backup(archive: BackupArchive<File>) -> Result<()> {
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
/// Reloads restored configs into memory while preserving WebDAV credentials.
async fn finalize_restored_verge_config(
webdav_url: Option<String>,
webdav_username: Option<String>,
webdav_password: Option<String>,
) -> Result<()> {
let config_write = Config::lock_config_write().await;
let verge_draft = Config::verge().await;
let live = verge_draft.latest_arc();
let profiles_draft = Config::profiles().await;
let mut profile_guard = None;
let restored = {
let guard = &mut profile_guard;
let draft = &profiles_draft;
profiles_draft
.with_data_modify(|_| async move {
let (io_guard, retry) = profile_storage::write_for_restore().await?;
*guard = Some(io_guard);
let (profiles, mut restored) = restore_files(archive, retry).await?;
restored.webdav_url.clone_from(&live.webdav_url);
restored.webdav_username.clone_from(&live.webdav_username);
restored.webdav_password.clone_from(&live.webdav_password);
restored
.save_file()
.await
.context("backup files were restored, but the live WebDAV settings could not be saved")
.inspect_err(profile_storage::block_restore)?;
draft.discard();
Ok((profiles, restored))
})
.await
.inspect_err(|error: &anyhow::Error| {
if error.is::<DraftConflict>() {
profile_storage::block_restore(error);
}
})?
};
// A broken restored `verge.yaml` is a restore failure, not a reason to load defaults.
let mut restored = help::read_yaml::<IVerge>(&verge_path()?).await?;
restored.webdav_url = webdav_url;
restored.webdav_username = webdav_username;
restored.webdav_password = webdav_password;
restored.save_file().await?;
let restored_clash = IClashTemp::new().await;
let clash_draft = Config::clash().await;
clash_draft.edit_draft(|d| {
@@ -75,16 +46,19 @@ async fn apply_backup(archive: BackupArchive<File>) -> Result<()> {
});
clash_draft.apply();
let restored_profiles = load_profiles().await;
let profiles_draft = Config::profiles().await;
profiles_draft.edit_draft(|d| {
*d = restored_profiles;
});
profiles_draft.apply();
let verge_draft = Config::verge().await;
verge_draft.edit_draft(|d| {
*d = restored;
*d = restored.clone();
});
verge_draft.apply();
if let Some(guard) = &profile_guard {
profile_storage::finish_restore(guard);
}
drop(profile_guard);
let restored = verge_draft.data_arc();
auto_backup::publish_settings(&restored);
auto_backup::publish_settings(&verge_draft.data_arc());
// Turn it off here; a failing core side effect below would otherwise skip this step.
if !restored.enable_system_proxy.unwrap_or_default() {
@@ -102,16 +76,16 @@ async fn apply_backup(archive: BackupArchive<File>) -> Result<()> {
}
}
let applied = super::config::apply_verge_patch_locked(&config_write, &restored, true).await;
// `patch_verge` re-acquires the configuration write lock.
drop(config_write);
if let Err(err) = applied {
// Run configuration side effects without rewriting the already-restored file.
if let Err(err) = super::patch_verge(&restored, true).await {
logging!(error, Type::Backup, "Failed to apply restored verge config: {err:#}");
// Propagate unknown proxy state; ordinary side-effect failures stay logged.
if SystemProxyStateUnknown::is_in(&err) {
return Err(err);
}
} else if restored.enable_tun_mode.is_some() {
super::reconcile_tun_availability().await;
}
Ok(())
}
@@ -158,127 +132,53 @@ pub async fn delete_webdav_backup(filename: String) -> Result<()> {
})
}
async fn restore_input_path(staged: &Path, name: &str, fallback: Option<&Path>) -> Result<PathBuf> {
let path = staged.join(name);
if let Some(dir) = fallback
&& !fs::try_exists(&path).await?
{
return Ok(dir.join(name));
}
Ok(path)
}
async fn validate_restore(archive: BackupArchive<File>, home_dir: &Path, retry: bool) -> Result<StagedBackup> {
let staging_root = home_dir.to_owned();
let staged = AsyncHandler::spawn_blocking(move || archive.stage(&staging_root))
.await
.map_err(|join| anyhow!("backup staging task failed: {join}"))??;
if let Err(error) = validate_restore_inputs(staged.path(), home_dir, retry).await {
AsyncHandler::spawn_blocking(move || drop(staged)).await?;
return Err(error);
}
Ok(staged)
}
async fn validate_restore_inputs(staged: &Path, home_dir: &Path, retry: bool) -> Result<()> {
let fallback = (!retry).then_some(home_dir);
let verge = restore_input_path(staged, VERGE_CONFIG, fallback).await?;
let profiles_path = restore_input_path(staged, PROFILE_YAML, fallback).await?;
help::read_yaml::<IVerge>(&verge).await?;
let profiles: IProfiles = help::read_yaml(&profiles_path).await?;
// A previous partial restore may have left an omitted runtime setting unreadable.
let existing_settings = retry.then_some(home_dir);
let clash = restore_input_path(staged, crate::utils::dirs::CLASH_CONFIG, existing_settings).await?;
if fs::try_exists(&clash).await? {
help::read_mapping(&clash).await?;
}
let dns = restore_input_path(staged, crate::constants::files::DNS_CONFIG, existing_settings).await?;
if fs::try_exists(&dns).await? {
help::read_yaml::<serde_yaml_ng::Mapping>(&dns).await?;
}
let staged_bodies = staged.join(PROFILES_DIR);
let live_bodies = home_dir.join(PROFILES_DIR);
for file in profiles.items.iter().flatten().filter_map(|item| item.file.as_deref()) {
let file = if !retry && let Ok(relative) = Path::new(file).strip_prefix(".") {
relative.to_str().context("invalid profile filename")?
} else {
file
};
validate_profile_file(file)?;
let body = restore_input_path(&staged_bodies, file, (!retry).then_some(live_bodies.as_path())).await?;
if body.parent() == Some(&live_bodies) {
anyhow::ensure!(
fs::symlink_metadata(&live_bodies).await?.is_dir(),
"live profiles path is not a directory"
);
}
let metadata = fs::symlink_metadata(&body)
.await
.with_context(|| format!("failed to inspect backup profile body {file}"))?;
anyhow::ensure!(metadata.is_file(), "backup profile body {file} is not a file");
}
Ok(())
}
async fn restore_files(archive: BackupArchive<File>, retry: bool) -> Result<(IProfiles, IVerge)> {
let home_dir = app_home_dir()?;
let staged = validate_restore(archive, &home_dir, retry)
.await
.context("backup staging failed before live files were changed")?;
let installed = AsyncHandler::spawn_blocking(move || staged.install(&home_dir))
.await
.context("backup installation task stopped unexpectedly")
.inspect_err(profile_storage::block_restore)?;
if let Err(error) = installed {
if !error.live_changed {
return Err(error).context("backup installation failed before live files were changed");
}
let error = anyhow::Error::from(error)
.context("backup restore failed while writing live files; a complete restore may be required");
profile_storage::block_restore(&error);
return Err(error);
}
async {
let verge = help::read_yaml::<IVerge>(&verge_path()?).await?;
let profiles = load_profiles_unlocked().await?;
Ok::<_, anyhow::Error>((profiles, verge))
}
.await
.context("backup files were restored, but the restored settings could not be loaded")
.inspect_err(profile_storage::block_restore)
}
/// Backup creation strips the WebDAV credentials, so the live ones are kept.
async fn restore_backup_archive(file: File) -> Result<()> {
let archive = AsyncHandler::spawn_blocking(move || BackupArchive::open(file, RECOVERY_ENTRY_NAMES))
.await
.map_err(|join| anyhow!("backup preflight task failed: {join}"))??;
tokio::spawn(apply_backup(archive)).await?
async fn restore_backup_archive(path: PathBuf) -> Result<()> {
let (webdav_url, webdav_username, webdav_password) = {
let verge = Config::verge().await;
let verge = verge.latest_arc();
(
verge.webdav_url.clone(),
verge.webdav_username.clone(),
verge.webdav_password.clone(),
)
};
let home_dir = app_home_dir()?;
AsyncHandler::spawn_blocking(move || -> Result<()> {
let file = std::fs::File::open(&path)?;
let mut zip = zip::ZipArchive::new(file)?;
zip.extract(&home_dir)?;
Ok(())
})
.await
.map_err(|join| anyhow!("backup extraction task failed: {join}"))??;
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
finalize_restored_verge_config(webdav_url, webdav_username, webdav_password).await
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename))]
pub async fn restore_webdav_backup(filename: String) -> Result<()> {
tokio::spawn(async move {
let archive_dir = tempfile::tempdir()?;
let archive = archive_dir.path().join("backup.zip");
let name = filename.clone();
backup::WebDavClient::global()
.download(filename, archive.clone())
.await
.map_err(|err| {
logging!(
error,
Type::Backup,
"Failed to download WebDAV backup file {name}: {err:#}"
);
err
})?;
let file = fs::File::open(archive).await?.into_std().await;
let result = restore_backup_archive(file).await;
drop(archive_dir);
result
})
.await?
let backup_storage_path = app_home_dir()
.map_err(|e| anyhow::anyhow!("Failed to get app home dir: {e}"))?
.join(filename.as_str());
let name = filename.clone();
backup::WebDavClient::global()
.download(filename, backup_storage_path.clone())
.await
.map_err(|err| {
logging!(
error,
Type::Backup,
"Failed to download WebDAV backup file {name}: {err:#}"
);
err
})?;
let res = restore_backup_archive(backup_storage_path.clone()).await;
let _ = backup_storage_path.remove_if_exists().await;
res
}
pub async fn create_local_backup() -> Result<()> {
@@ -435,13 +335,6 @@ pub async fn delete_local_backup(filename: String) -> Result<()> {
Ok(())
}
fn snapshot_local_backup(path: &Path) -> Result<File> {
// Header checks and staging must read the same bytes even if the local ZIP changes during restore.
let mut snapshot = tempfile::tempfile()?;
std::io::copy(&mut File::open(path)?, &mut snapshot)?;
Ok(snapshot)
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename))]
pub async fn restore_local_backup(filename: String) -> Result<()> {
let backup_dir = local_backup_dir()?;
@@ -450,8 +343,7 @@ pub async fn restore_local_backup(filename: String) -> Result<()> {
return Err(anyhow!("Backup file not found: {}", filename));
}
let snapshot = AsyncHandler::spawn_blocking(move || snapshot_local_backup(&target_path)).await??;
restore_backup_archive(snapshot).await
restore_backup_archive(target_path).await
}
#[tracing::instrument(skip_all, level = "info", fields(filename = %filename, destination = %destination))]
@@ -473,105 +365,3 @@ pub async fn export_local_backup(filename: String, destination: String) -> Resul
.map_err(|err| anyhow!("Failed to export backup file: {err:#}"))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use clash_verge_backup_archive::BackupWriter;
use std::io::Write as _;
#[test]
fn local_restore_reads_the_same_archive_after_the_source_changes() -> Result<()> {
let source = tempfile::NamedTempFile::new()?;
let mut writer = BackupWriter::new(source.reopen()?)?;
writer.start_file(PROFILE_YAML)?.write_all(b"items: []")?;
writer.finish()?;
let snapshot = snapshot_local_backup(source.path())?;
std::fs::write(source.path(), b"replaced")?;
let staging = tempfile::tempdir()?;
BackupArchive::open(snapshot, RECOVERY_ENTRY_NAMES)?
.stage(staging.path())?
.install(staging.path())?;
assert_eq!(std::fs::read(staging.path().join(PROFILE_YAML))?, b"items: []");
Ok(())
}
#[tokio::test]
async fn rejects_malformed_runtime_settings_in_staging() -> Result<()> {
let home = tempfile::tempdir()?;
fs::write(home.path().join(PROFILE_YAML), b"items: []").await?;
fs::write(home.path().join(VERGE_CONFIG), b"{}").await?;
for name in [crate::utils::dirs::CLASH_CONFIG, crate::constants::files::DNS_CONFIG] {
fs::write(home.path().join(name), b"key: original").await?;
let mut writer = BackupWriter::new(tempfile::tempfile()?)?;
writer.start_file(name)?.write_all(b"[invalid")?;
let archive = BackupArchive::open(writer.finish()?, RECOVERY_ENTRY_NAMES)?;
assert!(validate_restore(archive, home.path(), false).await.is_err(), "{name}");
assert_eq!(fs::read(home.path().join(name)).await?, b"key: original");
fs::write(home.path().join(name), b"[invalid").await?;
let mut writer = BackupWriter::new(tempfile::tempfile()?)?;
writer.start_file(VERGE_CONFIG)?.write_all(b"{}")?;
writer.start_file(PROFILE_YAML)?.write_all(b"items: []")?;
let archive = BackupArchive::open(writer.finish()?, RECOVERY_ENTRY_NAMES)?;
assert!(validate_restore(archive, home.path(), true).await.is_err(), "{name}");
fs::remove_file(home.path().join(name)).await?;
}
Ok(())
}
#[tokio::test]
async fn validates_config_before_replacing_live_files() -> Result<()> {
let home = tempfile::tempdir()?;
let path = home.path().join(PROFILE_YAML);
let live = b"items: []\n";
fs::write(&path, live).await?;
fs::write(home.path().join(VERGE_CONFIG), b"{}\n").await?;
let open_backup = |index: Option<&[u8]>, include_body: bool| -> Result<_> {
let file = tempfile::tempfile()?;
let mut writer = BackupWriter::new(file)?;
writer.start_file(VERGE_CONFIG)?.write_all(b"{}\n")?;
if let Some(index) = index {
writer.start_file(PROFILE_YAML)?.write_all(index)?;
}
if include_body {
writer.start_profile("r.yaml")?.write_all(b"proxies: []\n")?;
}
Ok(BackupArchive::open(writer.finish()?, RECOVERY_ENTRY_NAMES)?)
};
let invalid = open_backup(Some(b"items: invalid\n"), false)?;
assert!(validate_restore(invalid, home.path(), false).await.is_err());
assert_eq!(fs::read(&path).await?, live);
validate_restore(open_backup(None, false)?, home.path(), false).await?;
assert!(
validate_restore(open_backup(None, false)?, home.path(), true)
.await
.is_err()
);
let index = b"items: [{uid: r, type: remote, file: r.yaml}]\n";
assert!(
validate_restore(open_backup(Some(index), false)?, home.path(), true)
.await
.is_err()
);
assert!(
validate_restore(open_backup(Some(index), false)?, home.path(), false)
.await
.is_err()
);
assert_eq!(fs::read(&path).await?, live);
fs::create_dir(home.path().join(PROFILES_DIR)).await?;
fs::write(home.path().join(PROFILES_DIR).join("r.yaml"), b"old body").await?;
validate_restore(open_backup(Some(index), false)?, home.path(), false).await?;
assert!(
validate_restore(open_backup(Some(index), false)?, home.path(), true)
.await
.is_err()
);
validate_restore(open_backup(Some(index), true)?, home.path(), true).await?;
let old_index = b"items: [{uid: r, type: remote, file: ./r.yaml}]";
validate_restore(open_backup(Some(old_index), true)?, home.path(), false).await?;
Ok(())
}
}
+6 -8
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,13 +35,10 @@ pub async fn set_dns_override(
profiles.current.as_ref() == Some(&profile_uid),
"The active profile changed; retry the DNS setting"
);
let source = {
let _guard = crate::config::profile_storage::read().await?;
dns_override_source(
profiles.current.as_deref().unwrap_or_default(),
&current_mapping(&profiles).await?,
)?
};
let source = override_source(
profiles.current.as_deref().unwrap_or_default(),
&current_mapping(&profiles).await?,
)?;
if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) {
return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() });
}
+74 -43
View File
@@ -1,6 +1,7 @@
use crate::{
config::{
Config, PrfOption, download_subscription, profile_storage, profiles::save_remote_refresh, subscription_proxy,
Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::save_remote_refresh,
subscription_proxy,
},
core::{
CoreManager, handle,
@@ -16,46 +17,57 @@ use anyhow::{Result, bail};
use clash_verge_logging::{Type, logging};
use tristr::alias::String;
struct RefreshSource {
name: Option<String>,
url: String,
file: Option<String>,
option: Option<PrfOption>,
}
async fn refresh_source(uid: &str, ignore_auto_update: bool) -> Result<Option<RefreshSource>> {
async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result<Option<(String, Option<PrfOption>)>> {
let profiles = Config::profiles().await;
let _guard = profile_storage::read().await?;
let profiles = profiles.latest_arc();
let item = profiles.get_item(uid)?;
if item.itype.as_deref() != Some("remote") {
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
if !is_remote {
logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新");
return Ok(None);
}
let Some(url) = &item.url else {
Ok(None)
} else if item.url.is_none() {
logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新");
bail!("failed to get the profile item url");
};
if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
} else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) {
logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新");
return Ok(None);
Ok(None)
} else {
logging!(
info,
Type::Config,
"[订阅更新] 远程订阅,URL: {}",
mask_url(
item.url
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?
)
);
Ok(Some((
item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?,
item.option.clone(),
)))
}
logging!(info, Type::Config, "[订阅更新] 远程订阅,URL: {}", mask_url(url));
Ok(Some(RefreshSource {
name: item.name.clone(),
url: url.clone(),
file: item.file.clone(),
option: item.option.clone(),
}))
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
async fn perform_profile_update(uid: &str, source: RefreshSource, overrides: Option<&PrfOption>) -> Result<()> {
let url = source.url.as_str();
let options = PrfOption::merge(source.option.as_ref(), overrides);
let download_options = options.as_ref();
let configured_proxy = subscription_proxy(download_options);
let profile_name = source.name.as_deref().unwrap_or("UnKnown Profile");
async fn perform_profile_update(
uid: &str,
url: &str,
profile_options: Option<&PrfOption>,
overrides: Option<&PrfOption>,
is_manual_trigger: bool,
) -> Result<()> {
let options = PrfOption::merge(profile_options, overrides);
let options = options.as_ref();
let configured_proxy = subscription_proxy(options);
let profiles = Config::profiles().await;
let profiles_arc = profiles.latest_arc();
let profile_name = profiles_arc
.get_item(uid)
.ok()
.and_then(|item| item.name.clone())
.unwrap_or_else(|| String::from("UnKnown Profile"));
#[derive(Clone, Copy)]
enum Strategy {
@@ -93,7 +105,7 @@ async fn perform_profile_update(uid: &str, source: RefreshSource, overrides: Opt
};
tracing::Span::current().record("strategy", name);
let started = std::time::Instant::now();
let result = download_subscription(url, download_options, proxy).await;
let result = download_subscription(url, options, proxy).await;
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
match &result {
Ok(_) => logging!(info, Type::Config, "{success}"),
@@ -108,22 +120,43 @@ async fn perform_profile_update(uid: &str, source: RefreshSource, overrides: Opt
},
)
.await;
let (strategy, downloaded) = result.map_err(|err| anyhow::anyhow!(mask_err(&format!("{err:#}"))))?;
// A persistence error must not replay a successful download with another transport.
save_remote_refresh(uid, source.url, source.file, downloaded).await?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name);
let last_err = match result {
Ok((strategy, downloaded)) => {
// A persistence error must not replay a successful download with another transport.
let profiles = Config::profiles().await;
let snapshot = profiles.latest_arc();
let current = snapshot.get_item(uid)?;
anyhow::ensure!(
current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url),
"profile source changed during refresh"
);
let refresh = prepare_remote_refresh(downloaded, options).await?;
save_remote_refresh(uid, url, refresh).await?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
}
return Ok(());
}
Err(error) => error,
};
let last_err = mask_err(&last_err.to_string());
if is_manual_trigger {
handle::Handle::notice(
NoticeStatus::UpdateFailedEvenWithClash,
format!("{profile_name} - {last_err}"),
);
}
Ok(())
bail!(last_err)
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))]
pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_trigger: bool) -> Result<()> {
let subscription = refresh_source(uid, is_manual_trigger).await?;
let subscription = should_update_profile(uid, is_manual_trigger).await?;
let profile_persisted = match subscription {
Some(source) => {
perform_profile_update(uid, source, option).await?;
Some((url, profile_options)) => {
perform_profile_update(uid, &url, profile_options.as_ref(), option, is_manual_trigger).await?;
true
}
None => false,
@@ -151,9 +184,7 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_tri
message
};
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
if !is_manual_trigger {
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
}
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
bail!(message);
}
}
+1 -2
View File
@@ -21,7 +21,6 @@ pub static BACKUP_DIR: &str = "clash-verge-rev-backup-dev";
pub static CLASH_CONFIG: &str = "config.yaml";
pub static VERGE_CONFIG: &str = "verge.yaml";
pub static PROFILE_YAML: &str = "profiles.yaml";
pub static PROFILES_DIR: &str = "profiles";
/// Marks that the one-shot raise of too-short auto-update intervals has already run.
pub static UPDATE_INTERVAL_MIGRATED: &str = ".update-interval-migrated";
@@ -49,7 +48,7 @@ pub fn app_resources_dir() -> Result<PathBuf> {
}
pub fn app_profiles_dir() -> Result<PathBuf> {
Ok(app_home_dir()?.join(PROFILES_DIR))
Ok(app_home_dir()?.join("profiles"))
}
pub fn app_icons_dir() -> Result<PathBuf> {
+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);
}
}
+1 -6
View File
@@ -470,8 +470,7 @@ async fn initialize_config_files() -> Result<()> {
logging!(info, Type::Setup, "Created verge config at {:?}", path);
}
if crate::config::profile_storage::check().is_ok()
&& let Ok(path) = dirs::profiles_path()
if let Ok(path) = dirs::profiles_path()
&& !path.exists()
{
let template = IProfiles::default();
@@ -490,10 +489,6 @@ async fn initialize_config_files() -> Result<()> {
/// Initializes configuration required before Tauri setup.
pub async fn init_config() -> Result<()> {
if let Err(error) = crate::config::profile_storage::recover_at_startup().await {
logging!(error, Type::Config, "Profile recovery failed: {error:#}");
}
#[cfg(target_os = "macos")]
migrate_legacy_macos_logs().await?;
+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;
+10 -1
View File
@@ -26,6 +26,7 @@ import { useNavigate } from 'react-router'
import { useAppRefreshers } from '@/providers/app-data-context'
import { updateProfile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { isValidUrl } from '@/utils/network'
import { openExternalUrl } from '@/utils/open-external-url'
@@ -278,11 +279,19 @@ export const HomeProfileCard = ({
setUpdating(true)
try {
if (!(await updateProfile(current))) return
await mutate(
() => updateProfile(current.uid!, current.option ?? undefined),
{
id: `update-profile:${current.uid}`,
errorNotice: false,
},
)
onProfileUpdated?.()
// 刷新首页数据
refreshAll()
} catch (err) {
showNotice.error(err, 3000)
} finally {
setUpdating(false)
}
+7 -1
View File
@@ -425,7 +425,13 @@ const ProfileItemBase = (props: ProfileItemProps) => {
try {
const payload = Object.keys(option).length > 0 ? option : undefined
if (await updateProfile(itemData, payload)) void mutateProfiles()
await mutate(() => updateProfile(itemData.uid!, payload), {
id: `update-profile:${itemData.uid}`,
errorNotice: false,
})
void mutateProfiles()
} catch {
} finally {
setLoading(false)
}
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "تم إلغاء تثبيت الخدمة بنجاح"
},
"updater": {
"withClashProxySuccess": "Update with Clash proxy successfully"
"withClashProxySuccess": "Update with Clash proxy successfully",
"withClashProxyFailed": "Update failed even with Clash proxy"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "Service erfolgreich deinstalliert"
},
"updater": {
"withClashProxySuccess": "Aktualisierung mit Clash-Proxy erfolgreich"
"withClashProxySuccess": "Aktualisierung mit Clash-Proxy erfolgreich",
"withClashProxyFailed": "Aktualisierung auch mit Clash-Proxy fehlgeschlagen"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "Service Uninstalled Successfully"
},
"updater": {
"withClashProxySuccess": "Update with Clash proxy successfully"
"withClashProxySuccess": "Update with Clash proxy successfully",
"withClashProxyFailed": "Update failed even with Clash proxy"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "Servicio desinstalado con éxito"
},
"updater": {
"withClashProxySuccess": "Actualización con el proxy de Clash exitosa"
"withClashProxySuccess": "Actualización con el proxy de Clash exitosa",
"withClashProxyFailed": "Error al actualizar incluso con el proxy de Clash"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "سرویس با موفقیت حذف نصب شد"
},
"updater": {
"withClashProxySuccess": "با موفقیت با پروکسی کلش به‌روزرسانی شد"
"withClashProxySuccess": "با موفقیت با پروکسی کلش به‌روزرسانی شد",
"withClashProxyFailed": "به‌روزرسانی حتی با پروکسی کلش هم انجام نشد"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "Layanan Berhasil Dicopot"
},
"updater": {
"withClashProxySuccess": "Update with Clash proxy successfully"
"withClashProxySuccess": "Update with Clash proxy successfully",
"withClashProxyFailed": "Update failed even with Clash proxy"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "サービスのアンインストールに成功しました。"
},
"updater": {
"withClashProxySuccess": "Clashプロキシを使用して更新に成功しました。"
"withClashProxySuccess": "Clashプロキシを使用して更新に成功しました。",
"withClashProxyFailed": "Clashプロキシを使用しても更新に失敗しました。"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "서비스가 제거되었습니다"
},
"updater": {
"withClashProxySuccess": "Clash 프록시로 업데이트 성공"
"withClashProxySuccess": "Clash 프록시로 업데이트 성공",
"withClashProxyFailed": "Clash 프록시로도 업데이트 실패"
}
}
},
+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",
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "Serviço Desinstalado com Sucesso"
},
"updater": {
"withClashProxySuccess": "Atualização com o proxy do Clash concluída com sucesso"
"withClashProxySuccess": "Atualização com o proxy do Clash concluída com sucesso",
"withClashProxyFailed": "A atualização falhou mesmo com o proxy do Clash"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "Служба успешно удалена"
},
"updater": {
"withClashProxySuccess": "Обновление через Clash proxy выполнено успешно"
"withClashProxySuccess": "Обновление через Clash proxy выполнено успешно",
"withClashProxyFailed": "Обновление не удалось даже через Clash proxy"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "Hizmet Başarıyla Kaldırıldı"
},
"updater": {
"withClashProxySuccess": "Clash vekil ile güncelleme başarılı"
"withClashProxySuccess": "Clash vekil ile güncelleme başarılı",
"withClashProxyFailed": "Clash vekil ile bile güncelleme başarısız oldu"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "Сервис уңышлы салдырылды"
},
"updater": {
"withClashProxySuccess": "Update with Clash proxy successfully"
"withClashProxySuccess": "Update with Clash proxy successfully",
"withClashProxyFailed": "Update failed even with Clash proxy"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "已成功卸载服务"
},
"updater": {
"withClashProxySuccess": "使用 Clash 代理更新成功"
"withClashProxySuccess": "使用 Clash 代理更新成功",
"withClashProxyFailed": "使用 Clash 代理更新失败"
}
}
},
+2 -1
View File
@@ -701,7 +701,8 @@
"uninstallSuccess": "已成功解除安裝服務"
},
"updater": {
"withClashProxySuccess": "使用 Clash 代理更新成功"
"withClashProxySuccess": "使用 Clash 代理更新成功",
"withClashProxyFailed": "使用 Clash 代理更新也失敗"
}
}
},
+29 -31
View File
@@ -16,15 +16,7 @@ import {
RefreshRounded,
TextSnippetOutlined,
} from '@mui/icons-material'
import {
Alert,
Box,
Button,
Divider,
Grid,
IconButton,
Stack,
} from '@mui/material'
import { Box, Button, Divider, Grid, IconButton, Stack } from '@mui/material'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { readText } from '@tauri-apps/plugin-clipboard-manager'
import { readTextFile } from '@tauri-apps/plugin-fs'
@@ -58,7 +50,7 @@ import {
updateProfile,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { errorDetail, failureCode, showNotice } from '@/services/notice-service'
import { errorDetail, showNotice } from '@/services/notice-service'
import { revalidateQuery, useQuery } from '@/services/query-client'
import { useThemeMode } from '@/services/states'
import {
@@ -545,43 +537,52 @@ const ProfilePage = () => {
const setLoadingProfiles = useSetProfileLoading()
const runProfileUpdates = useCallback(
async (items: IProfileItem[]) => {
if (items.length === 0) return
async (uids: string[]) => {
if (uids.length === 0) return
const throttleMutate = throttle(mutateProfiles, 2000, {
trailing: true,
})
let cursor = 0
const updateOne = async (uid: string) => {
try {
// Per-uid id: the worker pool must not dedupe distinct subscriptions.
await mutate(() => updateProfile(uid), {
id: `update-profile:${uid}`,
errorNotice: false,
})
throttleMutate()
} catch (err: any) {
console.error(`更新订阅 ${uid} 失败:`, err)
}
}
const worker = async () => {
while (cursor < items.length) {
if (await updateProfile(items[cursor++])) throttleMutate()
while (cursor < uids.length) {
const uid = uids[cursor++]
await updateOne(uid)
}
}
try {
const active = Math.min(PROFILE_UPDATE_WORKER_LIMIT, items.length)
const active = Math.min(PROFILE_UPDATE_WORKER_LIMIT, uids.length)
await Promise.allSettled(Array.from({ length: active }, worker))
} finally {
setLoadingProfiles(
items.map((item) => item.uid!),
false,
)
setLoadingProfiles(uids, false)
void mutateProfiles()
}
},
[mutateProfiles, setLoadingProfiles],
)
const onUpdateAll = useLockFn(async () => {
const items = profileItems.filter(
(item) =>
item.type === 'remote' && item.uid && !loadingCache.has(item.uid),
)
setLoadingProfiles(
items.map((item) => item.uid!),
true,
)
await runProfileUpdates(items)
const items = profileItems.filter((e) => e.type === 'remote')
const target = items
.map((item) => item.uid!)
.filter((uid) => !loadingCache.has(uid))
setLoadingProfiles(target, true)
await runProfileUpdates(target)
})
const onCopyLink = async () => {
@@ -830,9 +831,6 @@ const ProfilePage = () => {
</Box>
}
>
{failureCode(error) === 'PROFILE_RECOVERY_REQUIRED' && (
<Alert severity="error">{errorDetail(error)}</Alert>
)}
<Stack
direction="row"
spacing={1}
+1
View File
@@ -635,6 +635,7 @@ export type NoticeStatus =
| 'app_restart::core_stop_failed'
| 'app_quit::core_stop_failed'
| 'update_with_clash_proxy'
| 'update_failed_even_with_clash'
| 'reactivate_profiles::error'
| 'update_failed'
| 'config_validate::boot_error'
+3 -26
View File
@@ -1,8 +1,7 @@
import { Channel } from '@tauri-apps/api/core'
import dayjs from 'dayjs'
import { mutate } from '@/services/mutate'
import { errorDetail, failureCode, showNotice } from '@/services/notice-service'
import { showNotice } from '@/services/notice-service'
import { debugLog } from '@/utils/debug'
import { commands } from './bindings'
@@ -83,30 +82,8 @@ export async function reorderProfile(activeId: string, overId: string) {
return commands.reorderProfile(activeId, overId)
}
export async function updateProfile(
item: IProfileItem,
option?: IProfileOption,
) {
if (!item.uid) return false
const uid = item.uid
try {
await mutate(() => commands.updateProfile(uid, option ?? null), {
id: `update-profile:${uid}`,
errorNotice: false,
})
return true
} catch (error) {
if (failureCode(error) === 'PROFILE_RECOVERY_REQUIRED') {
showNotice.error(error)
return false
}
const detail = errorDetail(error)
showNotice.error(
'profiles.page.feedback.errors.updateFailed',
item.name?.trim() ? `${item.name} - ${detail}` : detail,
)
return false
}
export async function updateProfile(index: string, option?: IProfileOption) {
return commands.updateProfile(index, option ?? null)
}
export async function deleteProfile(index: string) {
+5
View File
@@ -182,6 +182,11 @@ const handlers: Record<
'settings.feedback.notifications.updater.withClashProxySuccess',
msg,
),
update_failed_even_with_clash: (msg) =>
showNotice.error(
'settings.feedback.notifications.updater.withClashProxyFailed',
msg,
),
'reactivate_profiles::error': (msg) => showNotice.error(msg),
update_failed: (msg) => showNotice.error(msg),
'config_validate::boot_error': (msg) =>
+1 -1
View File
@@ -481,7 +481,7 @@ const baseShowNotice = (
return id
}
export function failureCode(input: unknown): string | undefined {
function failureCode(input: unknown): string | undefined {
return isCommandFailure(input) ? input.code! : undefined
}
+1
View File
@@ -860,6 +860,7 @@ export const translationKeys = [
'settings.feedback.notifications.clashService.sidecarFallback',
'settings.feedback.notifications.clashService.uninstallSuccess',
'settings.feedback.notifications.updater.withClashProxySuccess',
'settings.feedback.notifications.updater.withClashProxyFailed',
'settings.statuses.clash.stopping',
'settings.statuses.clash.restarting',
'settings.statuses.clashService.installing',
+1
View File
@@ -898,6 +898,7 @@ export interface TranslationResources {
uninstallSuccess: string
}
updater: {
withClashProxyFailed: string
withClashProxySuccess: string
}
}