mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-01 02:20:07 +08:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7dfaf3221c | ||
|
|
11af96dba1 | ||
|
|
7ba832ac2f | ||
|
|
9319a4894a | ||
|
|
b68438556a |
@@ -8,7 +8,7 @@
|
||||
"pnpmVersion": "12.23.0"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/rust:1": {
|
||||
"version": "1.100.1",
|
||||
"version": "1.100.0",
|
||||
"profile": "default"
|
||||
},
|
||||
"ghcr.io/devcontainers/features/git:1": {},
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
"version": "v9.0.0",
|
||||
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
||||
},
|
||||
"github/gh-aw-actions/setup@v1.4.1": {
|
||||
"github/gh-aw-actions/setup@v1.4.0": {
|
||||
"repo": "github/gh-aw-actions/setup",
|
||||
"version": "v1.4.1",
|
||||
"sha": "367d4dc4e89caf85422092845006e4a4a660d926"
|
||||
"version": "v1.4.0",
|
||||
"sha": "b907753c079ddd7d6829a0d8c24e02e818b4b45f"
|
||||
}
|
||||
},
|
||||
"containers": {
|
||||
@@ -47,11 +47,6 @@
|
||||
"digest": "sha256:b9cd8d7d1a9c2693e5d91db035a678fb1ea8d87ce691e08ec091b327e5e8ba75",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.20@sha256:b9cd8d7d1a9c2693e5d91db035a678fb1ea8d87ce691e08ec091b327e5e8ba75"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/agent:0.29.21": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21",
|
||||
"digest": "sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.29.21@sha256:fef2443688fc8991d995b935963ef82cec704a867d5e53146f13e86819484059"
|
||||
},
|
||||
"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",
|
||||
@@ -87,11 +82,6 @@
|
||||
"digest": "sha256:fc6c1eff686514d26ff90ae1398e0f6e3dcad8d2e43d11b16df312c1e72c0ace",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.20@sha256:fc6c1eff686514d26ff90ae1398e0f6e3dcad8d2e43d11b16df312c1e72c0ace"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21",
|
||||
"digest": "sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.29.21@sha256:3293e5813a4e51bf1c5a1b22a762a25033d3ccc5f3582acb2572ad68045ce0e7"
|
||||
},
|
||||
"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",
|
||||
@@ -107,11 +97,6 @@
|
||||
"digest": "sha256:743396030b149763880978f35ad679fe02b1c0be6697b01fbf6d43f4ac2ae081",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.20@sha256:743396030b149763880978f35ad679fe02b1c0be6697b01fbf6d43f4ac2ae081"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21",
|
||||
"digest": "sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/cli-proxy:0.29.21@sha256:facec98ac9b6ce41273f325b78475ef8d11c38842f62fc2ad823937203564cc3"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/router:0.29.14": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.14",
|
||||
"digest": "sha256:b8822defe0cc2abebc619ee1cf49c34c67286fab117512f0d667962572564be0",
|
||||
@@ -122,11 +107,6 @@
|
||||
"digest": "sha256:732c3741e866099c6c2095aad7c84a18266486563deb51d7cce723f9bfc48721",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.20@sha256:732c3741e866099c6c2095aad7c84a18266486563deb51d7cce723f9bfc48721"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/router:0.29.21": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/router:0.29.21",
|
||||
"digest": "sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/router:0.29.21@sha256:681b2ca49f33e3954e5f3824767b3f2d4c747a60272ec303d0be27221531450a"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
|
||||
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
|
||||
@@ -162,15 +142,10 @@
|
||||
"digest": "sha256:1c4a4a12fcea206a81d656cb1f73847420a2c041d02ab51235364079a1e31d71",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.20@sha256:1c4a4a12fcea206a81d656cb1f73847420a2c041d02ab51235364079a1e31d71"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-firewall/squid:0.29.21": {
|
||||
"image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21",
|
||||
"digest": "sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.29.21@sha256:ccc189ace632f3f42fa2ee1e77feb67d438e0975c591520da3f473c132e6216d"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-mcpg:v0.5.15": {
|
||||
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.15",
|
||||
"digest": "sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.15@sha256:3f6567e6db31d820e43031fa17a745e5a056fd074604192a884ac12a443ff5c1"
|
||||
"ghcr.io/github/gh-aw-mcpg:v0.5.14": {
|
||||
"image": "ghcr.io/github/gh-aw-mcpg:v0.5.14",
|
||||
"digest": "sha256:716b41d53a20660e945c351c08140380430d65d98d3263596e45114c29fa7a43",
|
||||
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.5.14@sha256:716b41d53a20660e945c351c08140380430d65d98d3263596e45114c29fa7a43"
|
||||
},
|
||||
"ghcr.io/github/gh-aw-node": {
|
||||
"image": "ghcr.io/github/gh-aw-node",
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
# GitHub Copilot Instructions
|
||||
|
||||
Read and follow [AGENTS.md](../AGENTS.md) before working in this repository.
|
||||
|
||||
@../AGENTS.md
|
||||
@@ -156,7 +156,6 @@ Use the task routes above first. This inventory is not required startup context.
|
||||
- `.github/aw/otel.md`
|
||||
- `.github/aw/patterns.md`
|
||||
- `.github/aw/playwright.md`
|
||||
- `.github/aw/pr-finisher.md`
|
||||
- `.github/aw/pr-reviewer.md`
|
||||
- `.github/aw/release-workflow.md`
|
||||
- `.github/aw/repo-factory.md`
|
||||
|
||||
@@ -154,7 +154,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.1'
|
||||
toolchain: '1.100.0'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -240,7 +240,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.1'
|
||||
toolchain: '1.100.0'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -373,7 +373,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.1'
|
||||
toolchain: '1.100.0'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
|
||||
@@ -31,9 +31,9 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Install gh-aw extension
|
||||
uses: github/gh-aw-actions/setup-cli@367d4dc4e89caf85422092845006e4a4a660d926 # v1.4.1
|
||||
uses: github/gh-aw-actions/setup-cli@b907753c079ddd7d6829a0d8c24e02e818b4b45f # v1.4.0
|
||||
with:
|
||||
version: v1.4.1
|
||||
version: v1.4.0
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
|
||||
@@ -74,7 +74,7 @@ jobs:
|
||||
|
||||
- name: Install Rust Stable
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
uses: dtolnay/rust-toolchain@1.100.1
|
||||
uses: dtolnay/rust-toolchain@1.100.0
|
||||
|
||||
- name: Rust Cache
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
@@ -121,7 +121,7 @@ jobs:
|
||||
if: github.event.inputs[matrix.input] == 'true'
|
||||
run: |
|
||||
# Ensure cross target is installed for the pinned toolchain; fallback without explicit toolchain if needed
|
||||
rustup target add ${{ matrix.target }} --toolchain 1.100.1 || rustup target add ${{ matrix.target }}
|
||||
rustup target add ${{ matrix.target }} --toolchain 1.100.0 || rustup target add ${{ matrix.target }}
|
||||
rustup target list --installed
|
||||
echo "Rust target ${{ matrix.target }} installed."
|
||||
|
||||
|
||||
+78
-59
File diff suppressed because one or more lines are too long
Generated
+80
-61
File diff suppressed because one or more lines are too long
@@ -203,7 +203,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.1'
|
||||
toolchain: '1.100.0'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -308,7 +308,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.1'
|
||||
toolchain: '1.100.0'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
@@ -439,7 +439,7 @@ jobs:
|
||||
- name: Install Rust Stable
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.1'
|
||||
toolchain: '1.100.0'
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Rust Cache
|
||||
|
||||
+78
-59
File diff suppressed because one or more lines are too long
@@ -22,7 +22,7 @@ jobs:
|
||||
- name: Install Rust
|
||||
uses: dtolnay/rust-toolchain@master
|
||||
with:
|
||||
toolchain: '1.100.1'
|
||||
toolchain: '1.100.0'
|
||||
targets: x86_64-pc-windows-msvc
|
||||
|
||||
- name: Install Node
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
nodejs 26.13.1
|
||||
pnpm 12.23.0
|
||||
rust 1.100.1
|
||||
rust 1.100.0
|
||||
|
||||
@@ -60,10 +60,6 @@ the ownership evidence the AI-slop review evaluates (see
|
||||
|
||||
- For development and bug fixes, follow the
|
||||
[development workflow](CONTRIBUTING.md#development-workflow).
|
||||
- For Rust backend changes that affect capability ownership or dependency
|
||||
boundaries, follow [Workspace Crate Architecture](crates/AGENTS.md).
|
||||
For Tauri commands and desktop integration, also follow
|
||||
[Backend Architecture Guardrails](src-tauri/AGENTS.md).
|
||||
- For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md).
|
||||
Review is read-only unless changes are authorized; findings do not expand
|
||||
that authorization to unrelated fixes, commits, pushes, or GitHub updates.
|
||||
|
||||
Generated
+5
-118
@@ -1089,23 +1089,15 @@ dependencies = [
|
||||
"async-trait",
|
||||
"backon",
|
||||
"base64 0.23.1",
|
||||
"boa_engine",
|
||||
"bytes",
|
||||
"chrono",
|
||||
"clash-verge-backup-archive",
|
||||
"clash-verge-config-render",
|
||||
"clash-verge-draft",
|
||||
"clash-verge-i18n",
|
||||
"clash-verge-limiter",
|
||||
"clash-verge-logging",
|
||||
"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",
|
||||
"clash-verge-subscription",
|
||||
"clash-verge-task",
|
||||
"clash_verge_service_ipc",
|
||||
"dark-light",
|
||||
"deelevate",
|
||||
@@ -1159,7 +1151,6 @@ dependencies = [
|
||||
"tauri-plugin-wdio-webdriver",
|
||||
"tauri-plugin-window-state",
|
||||
"tauri-specta",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
@@ -1174,34 +1165,13 @@ dependencies = [
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-backup-archive"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"thiserror 2.0.20",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-config-render"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clash-verge-logging",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml_ng",
|
||||
"tokio",
|
||||
"tristr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-draft"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"criterion",
|
||||
"parking_lot 0.13.0",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
@@ -1221,10 +1191,10 @@ version = "0.1.0"
|
||||
name = "clash-verge-logging"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"flexi_logger",
|
||||
"log",
|
||||
"parking_lot 0.13.0",
|
||||
"thiserror 2.0.20",
|
||||
"tracing-estuary",
|
||||
]
|
||||
|
||||
@@ -1243,69 +1213,6 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-profile"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml_ng",
|
||||
"specta",
|
||||
"thiserror 2.0.20",
|
||||
"tristr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-profile-script"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"boa_engine",
|
||||
"clash-verge-logging",
|
||||
"log",
|
||||
"parking_lot 0.13.0",
|
||||
"serde_json",
|
||||
"serde_yaml_ng",
|
||||
"tokio",
|
||||
"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"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"specta",
|
||||
"tristr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-runtime-bundle"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clash-verge-logging",
|
||||
"hex",
|
||||
"log",
|
||||
"serde_yaml_ng",
|
||||
"sha2 0.11.2",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
"tristr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-signal"
|
||||
version = "0.1.0"
|
||||
@@ -1315,26 +1222,6 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-subscription"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"http",
|
||||
"percent-encoding",
|
||||
"serde_yaml_ng",
|
||||
"thiserror 2.0.20",
|
||||
"url",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash-verge-task"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"parking_lot 0.13.0",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clash_verge_service_ipc"
|
||||
version = "2.8.2"
|
||||
@@ -10312,9 +10199,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "9.9.0"
|
||||
version = "9.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "07db37dec4a7c468df4723fba4cadb4822d1d0f10dbea367100b6a6881b2a9c9"
|
||||
checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"bzip2",
|
||||
|
||||
+2
-26
@@ -2,21 +2,12 @@
|
||||
members = [
|
||||
"src-tauri",
|
||||
"crates/clash-verge-draft",
|
||||
"crates/clash-verge-task",
|
||||
"crates/clash-verge-media-unlock",
|
||||
"crates/clash-verge-logging",
|
||||
"crates/clash-verge-signal",
|
||||
"crates/tauri-plugin-clash-verge-sysinfo",
|
||||
"crates/clash-verge-i18n",
|
||||
"crates/clash-verge-limiter",
|
||||
"crates/clash-verge-subscription",
|
||||
"crates/clash-verge-runtime-bundle",
|
||||
"crates/clash-verge-config-render",
|
||||
"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"
|
||||
|
||||
@@ -60,22 +51,12 @@ split-debuginfo = "unpacked"
|
||||
muda = { git = "https://github.com/wonfen/muda.git", rev = "547de49352791653fbdfa785f20f3c7ece8468e2" }
|
||||
|
||||
[workspace.dependencies]
|
||||
clash-verge-config-render = { path = "crates/clash-verge-config-render" }
|
||||
clash-verge-profile-script = { path = "crates/clash-verge-profile-script" }
|
||||
clash-verge-draft = { path = "crates/clash-verge-draft" }
|
||||
clash-verge-task = { path = "crates/clash-verge-task" }
|
||||
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
|
||||
clash-verge-logging = { path = "crates/clash-verge-logging" }
|
||||
clash-verge-signal = { path = "crates/clash-verge-signal" }
|
||||
clash-verge-i18n = { path = "crates/clash-verge-i18n" }
|
||||
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
|
||||
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" }
|
||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||
tracing = "0.1.44"
|
||||
@@ -84,10 +65,6 @@ tauri = { version = "2.12.7" }
|
||||
tauri-plugin-clipboard-manager = "2.5.0"
|
||||
parking_lot = "0.13.0"
|
||||
anyhow = "1.0.105"
|
||||
thiserror = "2.0.20"
|
||||
zip = "9.9.0"
|
||||
boa_engine = "0.22.0"
|
||||
futures = "0.3.34"
|
||||
chrono = "0.4.45"
|
||||
criterion = { version = "0.8.2", features = ["async_tokio"] }
|
||||
tokio = { version = "1.54.1", features = [
|
||||
@@ -111,9 +88,6 @@ serde = { version = "1.0.229" }
|
||||
tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] }
|
||||
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"
|
||||
|
||||
# *** For Windows platform only ***
|
||||
@@ -147,6 +121,7 @@ copy_iterator = "deny"
|
||||
correctness = { level = "deny", priority = -1 }
|
||||
dbg_macro = "warn"
|
||||
equatable_if_let = "deny"
|
||||
expect_used = "warn"
|
||||
expl_impl_clone_on_copy = "deny"
|
||||
future_not_send = "deny"
|
||||
iter_on_empty_collections = "deny"
|
||||
@@ -185,6 +160,7 @@ unnecessary_self_imports = "deny"
|
||||
unnecessary_wraps = "deny"
|
||||
unused_async = "deny"
|
||||
unused_trait_names = "deny"
|
||||
unwrap_used = "warn"
|
||||
use_self = "deny"
|
||||
useless_let_if_seq = "deny"
|
||||
wildcard_imports = "deny"
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
# Clippy loads a single configuration file, so repeat the workspace defaults.
|
||||
avoid-breaking-exported-api = true
|
||||
allow-unwrap-in-tests = true
|
||||
cognitive-complexity-threshold = 25
|
||||
excessive-nesting-threshold = 5
|
||||
@@ -1,88 +0,0 @@
|
||||
# Workspace Crate Architecture
|
||||
|
||||
## Choose the boundary
|
||||
|
||||
- Apply Functional Core, Imperative Shell and Ports and Adapters. Keep domain
|
||||
types, invariants, parsing, validation, and deterministic transitions
|
||||
independent of Tauri, concrete OS APIs, and implicit application state.
|
||||
- Keep use cases, async coordination, cancellation, and timeouts in
|
||||
framework-independent application modules. Pass dependencies explicitly.
|
||||
Define ports where an external effect needs a contract. Adapters implement
|
||||
the contracts owned by their consumers. Keep filesystem, network, IPC, process,
|
||||
and OS-specific operations in their adapters.
|
||||
- Extract a capability whose invariants can be owned behind a small API. Before
|
||||
creating a crate, identify its owner, what callers supply, and what can be
|
||||
verified through the crate API. Extract a crate when it provides a useful
|
||||
dependency, portability, testing, or ownership boundary. Keep a module when
|
||||
the proposed boundary only relocates implementation or introduces a
|
||||
pass-through API.
|
||||
- Keep capability crates independent by default. Compose peer capabilities in
|
||||
the application and pass inputs or callbacks through the consumer's API.
|
||||
Depend on another workspace crate for foundational mechanisms such as logging
|
||||
and task primitives, or for a shared domain contract required to enforce the
|
||||
same invariant. Keep tightly coupled rules together when separating them
|
||||
would duplicate that contract or split its ownership.
|
||||
- Keep dependencies pointing toward domain and application contracts. Resolve
|
||||
app paths and read current settings at the application boundary. Pass in the
|
||||
required values, resources, or callbacks. For example,
|
||||
[logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the
|
||||
app supplies directories and limits through `LoggerConfig`.
|
||||
- Run framework-independent tests without starting the desktop app. A platform
|
||||
adapter can own runtime startup when its resource lifetime requires it, as
|
||||
[signal](clash-verge-signal/src/lib.rs) does for Linux shutdown.
|
||||
|
||||
## Design the API
|
||||
|
||||
- Start with concrete types for data and outcomes. Use a trait when methods must
|
||||
cooperate under one contract, a closure for one supplied operation, and
|
||||
`impl Future` when the caller owns scheduling. Add type parameters and bounds
|
||||
where the contract needs them. Use dynamic dispatch when the API needs to hold
|
||||
heterogeneous implementations, as [draft](clash-verge-draft/src/lib.rs) does
|
||||
for the layers claimed by `DraftTransaction`.
|
||||
- Keep state and its invariants with one owner. Expose snapshots, typed
|
||||
operations, or guards. Draft owns claim, commit, and rollback of its in-memory
|
||||
layers. The caller owns persistence and the recovery of external effects.
|
||||
- Name product workspace libraries with the `clash-verge-` prefix and inherit
|
||||
workspace lints. Reuse workspace dependencies where available and declare
|
||||
only the features the crate needs.
|
||||
|
||||
## Handle fallible input
|
||||
|
||||
- Define crate-owned error types with `thiserror` in a dedicated `error` module.
|
||||
Re-export public errors through their established import paths.
|
||||
- Crates may use `unwrap()` or `expect()` for internal invariants. Propagate
|
||||
errors from required external data and use defaults only when the input
|
||||
contract gives the default a meaning.
|
||||
|
||||
## Own background work
|
||||
|
||||
- Give ordered start, replacement, and cleanup to one task owner. Reuse
|
||||
[`clash-verge-task`](clash-verge-task/src/lib.rs) for coalescing scheduled jobs
|
||||
and replaceable sessions. Keep domain policy, execution callbacks, and runtime
|
||||
startup at the call site. Select a driver whose delivery guarantees match the
|
||||
caller's needs.
|
||||
- Use typed inputs. Coalesce only when intermediate requests may be skipped.
|
||||
Reply with the actual outcome when a caller waits for completion. Preserve
|
||||
transaction boundaries and keep the reply path free of locks held by the
|
||||
waiting caller. Cancel only at safe boundaries and own issued effects through
|
||||
completion or explicit reconciliation.
|
||||
- Distinguish requested effects from completed effects in typed outcomes.
|
||||
Define how failures, cancellation, and timeouts affect publication, retry,
|
||||
rollback, or reconciliation.
|
||||
|
||||
## Validate new crates
|
||||
|
||||
- Fuzz the public boundary before tuning. Exercise malformed input, fallback
|
||||
behavior, and failures that can affect user data. Preserve the corpus and
|
||||
record the baseline revision and dependency resolution.
|
||||
- Try at least one targeted performance improvement. Compare the baseline and
|
||||
candidate on the same workload and build settings. Record stable gains, flat
|
||||
cases, and regressions, and justify which changes to keep.
|
||||
- Fuzz the final candidate again. Use the baseline corpus and compare outputs,
|
||||
diagnostics, and errors with the baseline where behavior should be preserved.
|
||||
|
||||
Verify the extracted contract through its public API when practical. Use
|
||||
`cargo test -p <crate>` for focused tests and keep native behavior checks at the
|
||||
app boundary. For timing, prefer Tokio's paused clock for task drivers or a
|
||||
small clock interface where time is an input, as in
|
||||
[`clash-verge-limiter`](clash-verge-limiter/src/lib.rs).
|
||||
@@ -1,11 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-backup-archive"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
thiserror = { workspace = true }
|
||||
zip = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,13 +0,0 @@
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ArchiveError {
|
||||
#[error(transparent)]
|
||||
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,
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
mod error;
|
||||
|
||||
pub use error::ArchiveError;
|
||||
|
||||
use std::{
|
||||
io::{self, Read, Seek, Write},
|
||||
path::{Component, Path},
|
||||
};
|
||||
use zip::{CompressionMethod, ZipArchive, ZipWriter, write::SimpleFileOptions};
|
||||
|
||||
pub struct BackupWriter<W: Write + Seek> {
|
||||
zip: ZipWriter<W>,
|
||||
options: SimpleFileOptions,
|
||||
}
|
||||
|
||||
impl<W: Write + Seek> BackupWriter<W> {
|
||||
pub fn new(target: W) -> Result<Self, ArchiveError> {
|
||||
let mut zip = ZipWriter::new(target);
|
||||
zip.add_directory("profiles/", SimpleFileOptions::default())?;
|
||||
let options = SimpleFileOptions::default().compression_method(CompressionMethod::Stored);
|
||||
Ok(Self { zip, options })
|
||||
}
|
||||
|
||||
pub fn start_profile<'a>(&'a mut self, filename: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
|
||||
self.start_file(&format!("profiles/{filename}"))
|
||||
}
|
||||
|
||||
pub fn start_file<'a>(&'a mut self, name: &str) -> Result<impl Write + use<'a, W>, ArchiveError> {
|
||||
self.zip.start_file_with_options(self.options.name(name.as_bytes()))?;
|
||||
Ok(&mut self.zip)
|
||||
}
|
||||
|
||||
pub fn finish(self) -> Result<W, ArchiveError> {
|
||||
Ok(self.zip.finish()?)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ValidatedBackup<R: Read + Seek> {
|
||||
zip: ZipArchive<R>,
|
||||
}
|
||||
|
||||
impl<R: Read + Seek> ValidatedBackup<R> {
|
||||
pub fn open(source: R, reserved_names: &[&str]) -> Result<Self, ArchiveError> {
|
||||
let mut zip = ZipArchive::new(source)?;
|
||||
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);
|
||||
}
|
||||
}
|
||||
io::copy(&mut entry, &mut io::sink())?;
|
||||
}
|
||||
Ok(Self { zip })
|
||||
}
|
||||
|
||||
pub fn extract_to(&mut self, destination: &Path) -> Result<(), ArchiveError> {
|
||||
self.zip.extract(destination)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::Cursor;
|
||||
|
||||
#[test]
|
||||
fn writes_and_validates_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())?;
|
||||
assert_eq!(zip.len(), 3);
|
||||
assert_eq!(zip.by_index(0)?.name()?, "profiles/");
|
||||
let profile_time = {
|
||||
let mut entry = zip.by_index(1)?;
|
||||
assert_eq!(entry.name()?, "profiles/example.yaml");
|
||||
assert_eq!(entry.compression(), CompressionMethod::Stored);
|
||||
let mut contents = Vec::new();
|
||||
entry.read_to_end(&mut contents)?;
|
||||
assert_eq!(contents, b"proxies: []\n");
|
||||
entry.last_modified()
|
||||
};
|
||||
let index = zip.by_index(2)?;
|
||||
assert_eq!(index.name()?, "profiles.yaml");
|
||||
assert_eq!(index.last_modified(), profile_time);
|
||||
ValidatedBackup::open(source, &[".profile-refresh", ".profile-refresh.lock"])?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-config-render"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
clash-verge-logging = { workspace = true }
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml_ng = { workspace = true }
|
||||
tristr = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,81 +0,0 @@
|
||||
use super::{ResultLog, ScriptOutcome, field::use_lowercase};
|
||||
use serde_yaml_ng::Mapping;
|
||||
use tristr::alias::String;
|
||||
|
||||
type ScriptResult = (Mapping, Vec<String>, ResultLog);
|
||||
|
||||
/// Never fails: exceptions are logged and the input config is returned unchanged.
|
||||
pub(super) async fn use_script<Fut: Future<Output = ScriptOutcome> + Send>(
|
||||
script: String,
|
||||
config: Mapping,
|
||||
name: String,
|
||||
execute: impl FnOnce(String, serde_json::Value, String) -> Fut + Send,
|
||||
) -> ScriptResult {
|
||||
// The template is identity-plus-lowercasing; skip the Boa round-trip.
|
||||
if script == super::ITEM_SCRIPT {
|
||||
return (use_lowercase(config), vec![], vec![]);
|
||||
}
|
||||
|
||||
let json = match serde_json::to_value(&config) {
|
||||
Ok(mut json) => {
|
||||
if let Some(map) = json.as_object_mut() {
|
||||
let mut lowered = serde_json::Map::with_capacity(map.len());
|
||||
for (key, value) in std::mem::take(map) {
|
||||
let mut key = key;
|
||||
key.make_ascii_lowercase();
|
||||
lowered.insert(key, value);
|
||||
}
|
||||
*map = lowered;
|
||||
}
|
||||
json
|
||||
}
|
||||
Err(err) => return (config, vec![], vec![("exception".into(), err.to_string().into())]),
|
||||
};
|
||||
|
||||
let (outcome, mut logs) = execute(script, json, name).await;
|
||||
match outcome {
|
||||
Ok(result) => {
|
||||
let result = use_lowercase(result);
|
||||
// Compared against the config as handed in, not the lowercased copy the script saw.
|
||||
let changed_keys = result
|
||||
.iter()
|
||||
.filter(|(key, value)| config.get(key) != Some(value))
|
||||
.filter_map(|(key, _)| {
|
||||
let mut key: String = key.as_str()?.into();
|
||||
key.make_ascii_lowercase();
|
||||
Some(key)
|
||||
})
|
||||
.collect();
|
||||
(result, changed_keys, logs)
|
||||
}
|
||||
Err(reason) => {
|
||||
logs.push(("exception".into(), reason.into()));
|
||||
(config, vec![], logs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::future::ready;
|
||||
|
||||
use super::{Mapping, use_script};
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_template_skips_the_executor() {
|
||||
let mut called = false;
|
||||
let mut config = Mapping::new();
|
||||
config.insert("MiXeD".into(), true.into());
|
||||
let (config, changed_keys, logs) =
|
||||
use_script(crate::ITEM_SCRIPT.into(), config, "profile".into(), |_, _, _| {
|
||||
called = true;
|
||||
ready((Ok(Mapping::new()), vec![]))
|
||||
})
|
||||
.await;
|
||||
|
||||
assert!(!called);
|
||||
assert_eq!(config["mixed"], serde_yaml_ng::Value::Bool(true));
|
||||
assert!(changed_keys.is_empty());
|
||||
assert!(logs.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ harness = false
|
||||
|
||||
[dependencies]
|
||||
parking_lot = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -2,7 +2,7 @@ use criterion::{Criterion, criterion_group, criterion_main};
|
||||
use std::hint::black_box;
|
||||
use tokio::runtime::Runtime;
|
||||
|
||||
use clash_verge_draft::{Draft, DraftConflict};
|
||||
use clash_verge_draft::Draft;
|
||||
|
||||
#[derive(Default, Clone, Debug)]
|
||||
struct IVerge {
|
||||
@@ -99,8 +99,8 @@ pub fn bench_draft(c: &mut Criterion) {
|
||||
group.bench_function("with_data_modify_async", |b| {
|
||||
b.to_async(&rt).iter(|| async {
|
||||
let draft = black_box(make_draft());
|
||||
let _: Result<(), DraftConflict> = draft
|
||||
.with_data_modify(|mut box_data| async move {
|
||||
let _: Result<(), anyhow::Error> = draft
|
||||
.with_data_modify::<_, _, _>(|mut box_data| async move {
|
||||
box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false));
|
||||
Ok((box_data, ()))
|
||||
})
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
/// Committed data changed before an asynchronous edit could publish.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("Optimistic lock failed: Committed data has changed during async operation")]
|
||||
pub struct DraftConflict;
|
||||
|
||||
/// Another transaction is already staging a change to one of the layers asked for.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("configuration layer {layer} is being changed elsewhere")]
|
||||
pub struct DraftBusy {
|
||||
/// The layer that was already claimed.
|
||||
pub layer: &'static str,
|
||||
}
|
||||
@@ -1,7 +1,3 @@
|
||||
mod error;
|
||||
|
||||
pub use error::{DraftBusy, DraftConflict};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{
|
||||
@@ -95,16 +91,14 @@ impl<T: Clone> Draft<T> {
|
||||
}
|
||||
|
||||
/// Optimistically replaces committed data after an asynchronous edit.
|
||||
/// The caller's error type carries both edit failures and publication conflicts.
|
||||
#[inline]
|
||||
pub async fn with_data_modify<F, Fut, R, E>(&self, f: F) -> Result<R, E>
|
||||
pub async fn with_data_modify<F, Fut, R>(&self, f: F) -> Result<R, anyhow::Error>
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
F: FnOnce(T) -> Fut + Send,
|
||||
Fut: std::future::Future<Output = Result<(T, R), E>> + Send,
|
||||
E: From<DraftConflict>,
|
||||
Fut: std::future::Future<Output = Result<(T, R), anyhow::Error>> + Send,
|
||||
{
|
||||
let permit = self.acquire_data_modify_permit().await;
|
||||
let _permit = self.acquire_data_modify_permit().await;
|
||||
let (local, original_arc) = {
|
||||
let guard = self.inner.data.lock();
|
||||
let arc = Arc::clone(&guard.0);
|
||||
@@ -114,9 +108,9 @@ impl<T: Clone> Draft<T> {
|
||||
let (new_local, res) = f(local).await?;
|
||||
let mut guard = self.inner.data.lock();
|
||||
if !Arc::ptr_eq(&guard.0, &original_arc) {
|
||||
drop(guard);
|
||||
drop(permit);
|
||||
return Err(DraftConflict.into());
|
||||
return Err(anyhow::anyhow!(
|
||||
"Optimistic lock failed: Committed data has changed during async operation"
|
||||
));
|
||||
}
|
||||
guard.0 = Arc::new(Box::new(new_local));
|
||||
drop(guard);
|
||||
@@ -197,6 +191,25 @@ impl<T: Clone + Send + Sync> DraftLayer for Draft<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Another transaction is already staging a change to one of the layers asked for.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct DraftBusy {
|
||||
/// The layer that was already claimed.
|
||||
pub layer: &'static str,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for DraftBusy {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(
|
||||
formatter,
|
||||
"configuration layer {} is being changed elsewhere",
|
||||
self.layer
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for DraftBusy {}
|
||||
|
||||
/// Exclusively claims several draft layers and rolls them all back unless committed.
|
||||
///
|
||||
/// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use clash_verge_draft::{Draft, DraftBusy, DraftConflict, DraftTransaction};
|
||||
use clash_verge_draft::{Draft, DraftTransaction};
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -28,19 +28,14 @@ fn edits_can_be_committed_or_discarded() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn async_updates_are_serialized() -> Result<(), Box<dyn std::error::Error>> {
|
||||
async fn async_updates_are_serialized() -> anyhow::Result<()> {
|
||||
let draft = Arc::new(Draft::new(0_u8));
|
||||
let mut updates = Vec::new();
|
||||
|
||||
for _ in 0..16 {
|
||||
let draft = Arc::clone(&draft);
|
||||
updates.push(tokio::spawn(async move {
|
||||
draft
|
||||
.with_data_modify(|value| async move {
|
||||
tokio::task::yield_now().await;
|
||||
Ok::<_, DraftConflict>((value + 1, ()))
|
||||
})
|
||||
.await
|
||||
draft.with_data_modify(|value| async move { Ok((value + 1, ())) }).await
|
||||
}));
|
||||
}
|
||||
for update in updates {
|
||||
@@ -52,7 +47,7 @@ async fn async_updates_are_serialized() -> Result<(), Box<dyn std::error::Error>
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn std::error::Error>> {
|
||||
async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> {
|
||||
let draft = Arc::new(Draft::new(Config::default()));
|
||||
let started = Arc::new(Notify::new());
|
||||
let finish = Arc::new(Notify::new());
|
||||
@@ -66,7 +61,7 @@ async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn
|
||||
started.notify_one();
|
||||
finish.notified().await;
|
||||
config.enabled = true;
|
||||
Ok::<_, DraftConflict>((config, ()))
|
||||
Ok((config, ()))
|
||||
})
|
||||
.await
|
||||
})
|
||||
@@ -77,14 +72,14 @@ async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box<dyn
|
||||
draft.apply();
|
||||
finish.notify_one();
|
||||
|
||||
assert_eq!(update.await?, Err(DraftConflict));
|
||||
assert!(update.await?.is_err());
|
||||
assert!(!draft.data_arc().enabled);
|
||||
assert_eq!(draft.data_arc().port, 7897);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_commits_every_layer() -> Result<(), DraftBusy> {
|
||||
fn transaction_commits_every_layer() -> anyhow::Result<()> {
|
||||
let first = Draft::new(1_u8);
|
||||
let second = Draft::new(String::from("a"));
|
||||
let transaction = DraftTransaction::begin(vec![&first, &second])?;
|
||||
@@ -99,7 +94,7 @@ fn transaction_commits_every_layer() -> Result<(), DraftBusy> {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> {
|
||||
fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> {
|
||||
let first = Draft::new(1_u8);
|
||||
let second = Draft::new(String::from("a"));
|
||||
|
||||
@@ -115,7 +110,7 @@ fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transaction_claims_are_exclusive_and_release_partial_claims() -> Result<(), DraftBusy> {
|
||||
fn transaction_claims_are_exclusive_and_release_partial_claims() -> anyhow::Result<()> {
|
||||
let first = Draft::new(1_u8);
|
||||
let second = Draft::new(2_u8);
|
||||
let held = DraftTransaction::begin(vec![&second])?;
|
||||
|
||||
@@ -6,7 +6,7 @@ edition = "2024"
|
||||
[dependencies]
|
||||
log = { workspace = true }
|
||||
parking_lot = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
flexi_logger = { workspace = true }
|
||||
tracing-estuary = { workspace = true }
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum LoggerError {
|
||||
#[error(transparent)]
|
||||
Pipeline(Box<dyn std::error::Error + Send + Sync>),
|
||||
#[error(transparent)]
|
||||
Sidecar(#[from] flexi_logger::FlexiLoggerError),
|
||||
#[error("failed to get tracing pipeline, make sure it init")]
|
||||
PipelineUnavailable,
|
||||
#[error("failed to reset log writer: {0}")]
|
||||
ResetWriter(String),
|
||||
}
|
||||
@@ -1,7 +1,3 @@
|
||||
mod error;
|
||||
|
||||
pub use error::LoggerError;
|
||||
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
fmt,
|
||||
@@ -14,6 +10,7 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
use flexi_logger::{
|
||||
Cleanup, Criterion, DeferredNow, FileSpec, Naming,
|
||||
writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _},
|
||||
@@ -180,7 +177,7 @@ impl Logger {
|
||||
|
||||
/// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare
|
||||
/// level) overrides the configured level.
|
||||
pub fn init(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> {
|
||||
pub fn init(&self, cfg: &LoggerConfig) -> Result<()> {
|
||||
let log_level = std::env::var("RUST_LOG")
|
||||
.ok()
|
||||
.and_then(|v| LevelFilter::from_str(v.trim()).ok())
|
||||
@@ -189,15 +186,14 @@ impl Logger {
|
||||
let pipeline = tracing_estuary::PipelineBuilder::new()
|
||||
.default_level(log_level)
|
||||
.file_writer(self.generate_file_log_writer())
|
||||
.init()
|
||||
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
|
||||
.init()?;
|
||||
self.pipeline.set(pipeline).ok();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Installs the sidecar file writer and the panic hook. Safe to call when
|
||||
/// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber).
|
||||
pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> {
|
||||
pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<()> {
|
||||
self.store_config(cfg);
|
||||
self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
|
||||
|
||||
@@ -249,7 +245,7 @@ impl Logger {
|
||||
/// Ensures the sidecar writer exists and points at `builder`'s config:
|
||||
/// built once, then reset in place — flexi's flusher thread cannot be
|
||||
/// stopped, so every dropped writer would leak a thread and an fd.
|
||||
fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<(), LoggerError> {
|
||||
fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<()> {
|
||||
let sidecar = self.sidecar_file_writer.write();
|
||||
match sidecar.as_ref() {
|
||||
Some(writer) => {
|
||||
@@ -300,29 +296,27 @@ impl Logger {
|
||||
}
|
||||
|
||||
/// only update app log level
|
||||
pub fn update_log_level(&self, level: LevelFilter) -> Result<(), LoggerError> {
|
||||
pub fn update_log_level(&self, level: LevelFilter) -> Result<()> {
|
||||
if let Some(pipeline) = self.pipeline.get() {
|
||||
pipeline
|
||||
.filter
|
||||
.set_default_level(level)
|
||||
.map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?;
|
||||
pipeline.filter.set_default_level(level)?;
|
||||
} else {
|
||||
return Err(LoggerError::PipelineUnavailable);
|
||||
bail!("failed to get tracing pipeline, make sure it init");
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rebuilds both file writers with the new limits.
|
||||
pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<(), LoggerError> {
|
||||
pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<()> {
|
||||
self.log_max_size.store(log_max_size, Ordering::SeqCst);
|
||||
self.log_max_count.store(log_max_count, Ordering::SeqCst);
|
||||
if let Some(pipeline) = self.pipeline.get() {
|
||||
let log_file_writer = self.generate_file_log_writer();
|
||||
if let Some(sink) = pipeline.sink.as_ref() {
|
||||
sink.reset(log_file_writer).map_err(LoggerError::ResetWriter)?;
|
||||
sink.reset(log_file_writer)
|
||||
.map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?;
|
||||
}
|
||||
} else {
|
||||
return Err(LoggerError::PipelineUnavailable);
|
||||
bail!("failed to get tracing pipeline, make sure it init");
|
||||
};
|
||||
self.ensure_sidecar_writer(self.generate_sidecar_builder())?;
|
||||
Ok(())
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-profile-script"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
boa_engine = { workspace = true }
|
||||
clash-verge-logging = { workspace = true }
|
||||
log = { workspace = true }
|
||||
parking_lot = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml_ng = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
tristr = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -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,76 +0,0 @@
|
||||
use std::{io, path::PathBuf};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum StoreError {
|
||||
#[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),
|
||||
}
|
||||
@@ -1,637 +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";
|
||||
|
||||
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),
|
||||
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],
|
||||
}
|
||||
|
||||
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)? {
|
||||
return Err(StoreError::UnsupportedVolume);
|
||||
}
|
||||
let lock = platform::open_lock(&root.join(RECOVERY_LOCK_NAME))?;
|
||||
lock.lock()?;
|
||||
let session = Self { root, _lock: lock };
|
||||
session.recover(checkpoint)?;
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn journal(&self) -> PathBuf {
|
||||
self.root.join(RECOVERY_JOURNAL_NAME)
|
||||
}
|
||||
|
||||
pub fn read_index(&self) -> Result<IProfiles> {
|
||||
let bytes = fs::read(self.root.join(INDEX))?;
|
||||
Ok(serde_yaml_ng::from_slice(&bytes)?)
|
||||
}
|
||||
|
||||
pub fn snapshot(&self, uid: &str) -> Result<(IProfiles, Vec<u8>)> {
|
||||
let profiles = self.read_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 {
|
||||
self.commit_with_checkpoint(uid, candidate, body, &mut |_| Ok(()))
|
||||
}
|
||||
|
||||
#[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)
|
||||
})();
|
||||
match published {
|
||||
Err(error) => CommitOutcome::NeedsRecovery(error),
|
||||
Ok(InstallOutcome::Installed) => match self.disarm_and_clean(checkpoint) {
|
||||
Ok(()) => CommitOutcome::Committed,
|
||||
Err(error) => CommitOutcome::CommittedCleanupPending(error),
|
||||
},
|
||||
Ok(InstallOutcome::Reverted(rejection)) => match self.disarm_and_clean(checkpoint) {
|
||||
Ok(()) => CommitOutcome::Retryable(rejection),
|
||||
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 new_item = candidate.get_item(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 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, ¤t, file)?;
|
||||
unshared_body(&profiles_dir, candidate, file)?;
|
||||
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 index = format!(
|
||||
"# Profiles Config for Clash Verge\n\n{}",
|
||||
serde_yaml_ng::to_string(candidate)?
|
||||
);
|
||||
let decision = Decision {
|
||||
version: 1,
|
||||
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.as_bytes()).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")?;
|
||||
write_new(&journal.join(INDEX_NEXT), index.as_bytes(), 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 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)?;
|
||||
}
|
||||
|
||||
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 {
|
||||
let apply = journal.join("body.apply");
|
||||
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)?;
|
||||
if !index_installed {
|
||||
let (index, _) = verified(&index_path, decision.old_index_digest)?;
|
||||
let current = serde_yaml_ng::from_slice(&index)?;
|
||||
unshared_body(&profiles_dir, ¤t, &decision.file)?;
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
if index_installed {
|
||||
platform::sync_file(&index_path)?;
|
||||
} else {
|
||||
let apply = journal.join("index.apply");
|
||||
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,
|
||||
"body.apply",
|
||||
"index.apply",
|
||||
] {
|
||||
remove_file_if_exists(&journal.join(name))?;
|
||||
}
|
||||
fs::remove_dir(&journal)?;
|
||||
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);
|
||||
}
|
||||
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 decision.version != 1 {
|
||||
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']) {
|
||||
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) -> Result<Option<fs::Metadata>> {
|
||||
let 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 != 1) {
|
||||
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)?;
|
||||
let other = dir.join(other);
|
||||
match fs::metadata(&other) {
|
||||
Ok(metadata) => {
|
||||
if let Some(identity) = &identity
|
||||
&& platform::file_identity(&other, &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()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,95 +0,0 @@
|
||||
#![cfg(any(unix, windows))]
|
||||
|
||||
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, stored_body) = Session::open(root)?.snapshot("assigned")?;
|
||||
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_allows_an_unrelated_unix_filename() -> 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/r.yaml"), b"old")?;
|
||||
fs::write(root.join("profiles/office:old.yaml"), b"local")?;
|
||||
let old = "items:\n- {uid: r, type: remote, file: r.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/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(())
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-profile"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
specta = { workspace = true, features = ["derive"] }
|
||||
thiserror = { workspace = true }
|
||||
tristr = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml_ng = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,5 +0,0 @@
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("failed to get the profile item \"uid:{uid}\"")]
|
||||
pub struct ProfileNotFound {
|
||||
pub(super) uid: String,
|
||||
}
|
||||
@@ -1,410 +0,0 @@
|
||||
mod error;
|
||||
pub mod selected_nodes;
|
||||
mod subscription_schedule;
|
||||
|
||||
pub use error::ProfileNotFound;
|
||||
pub use subscription_schedule::SubscriptionSchedule;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tristr::alias::String;
|
||||
|
||||
macro_rules! patch_opt_field {
|
||||
($lv:expr, $rv:expr, $key:tt) => {
|
||||
if ($rv.$key).is_some() {
|
||||
$lv.$key = $rv.$key.clone();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct PrfItem {
|
||||
pub uid: Option<String>,
|
||||
|
||||
/// enum value: remote | local | script | merge
|
||||
#[serde(rename = "type")]
|
||||
pub itype: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub file: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub desc: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub selected: Option<Vec<PrfSelected>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub extra: Option<PrfExtra>,
|
||||
pub updated: Option<usize>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub option: Option<PrfOption>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub home: Option<String>,
|
||||
#[serde(skip)]
|
||||
pub file_data: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct PrfSelected {
|
||||
pub name: Option<String>,
|
||||
pub now: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)]
|
||||
pub struct PrfExtra {
|
||||
pub upload: u64,
|
||||
pub download: u64,
|
||||
pub total: u64,
|
||||
pub expire: u64,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct PrfOption {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub user_agent: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub with_proxy: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub self_proxy: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub update_interval: Option<u64>,
|
||||
/// HTTP request timeout in seconds
|
||||
/// default is 60 seconds
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub timeout_seconds: Option<u64>,
|
||||
/// default is `false`
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub danger_accept_invalid_certs: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub allow_auto_update: Option<bool>,
|
||||
pub merge: Option<String>,
|
||||
pub script: Option<String>,
|
||||
pub rules: Option<String>,
|
||||
pub proxies: Option<String>,
|
||||
pub groups: Option<String>,
|
||||
}
|
||||
|
||||
impl PrfOption {
|
||||
pub fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
|
||||
match (one, other) {
|
||||
(Some(a_ref), Some(b_ref)) => {
|
||||
let mut result = a_ref.clone();
|
||||
patch_opt_field!(result, b_ref, user_agent);
|
||||
patch_opt_field!(result, b_ref, with_proxy);
|
||||
patch_opt_field!(result, b_ref, self_proxy);
|
||||
patch_opt_field!(result, b_ref, danger_accept_invalid_certs);
|
||||
patch_opt_field!(result, b_ref, allow_auto_update);
|
||||
patch_opt_field!(result, b_ref, update_interval);
|
||||
patch_opt_field!(result, b_ref, merge);
|
||||
patch_opt_field!(result, b_ref, script);
|
||||
patch_opt_field!(result, b_ref, rules);
|
||||
patch_opt_field!(result, b_ref, proxies);
|
||||
patch_opt_field!(result, b_ref, groups);
|
||||
patch_opt_field!(result, b_ref, timeout_seconds);
|
||||
Some(result)
|
||||
}
|
||||
(Some(a_ref), None) => Some(a_ref.clone()),
|
||||
(None, Some(b_ref)) => Some(b_ref.clone()),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! current_field {
|
||||
($name:ident, $field:ident) => {
|
||||
pub fn $name(&self) -> Option<&String> {
|
||||
self.option.as_ref().and_then(|o| o.$field.as_ref())
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl PrfItem {
|
||||
current_field!(current_merge, merge);
|
||||
current_field!(current_script, script);
|
||||
current_field!(current_rules, rules);
|
||||
current_field!(current_proxies, proxies);
|
||||
current_field!(current_groups, groups);
|
||||
}
|
||||
|
||||
/// Define the `profiles.yaml` schema
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct IProfiles {
|
||||
pub current: Option<String>,
|
||||
pub items: Option<Vec<PrfItem>>,
|
||||
}
|
||||
|
||||
pub struct IProfilePreview<'a> {
|
||||
pub uid: &'a String,
|
||||
pub name: &'a String,
|
||||
pub is_current: bool,
|
||||
}
|
||||
|
||||
pub struct ProfileDeletePlan {
|
||||
pub deleting_current: bool,
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
impl IProfiles {
|
||||
pub fn patch_current(&mut self, current: Option<&String>) {
|
||||
let items = self.items.get_or_insert_with(Vec::new);
|
||||
if let Some(current) = current
|
||||
&& items.iter().any(|item| item.uid.as_ref() == Some(current))
|
||||
{
|
||||
self.current = Some(current.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_item(&self, uid: impl AsRef<str>) -> Result<&PrfItem, ProfileNotFound> {
|
||||
let uid_str = uid.as_ref();
|
||||
|
||||
if let Some(items) = self.items.as_ref() {
|
||||
for each in items.iter() {
|
||||
if let Some(uid_val) = &each.uid
|
||||
&& uid_val.as_str() == uid_str
|
||||
{
|
||||
return Ok(each);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(ProfileNotFound {
|
||||
uid: uid_str.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Inserts a prepared entry after any required body write.
|
||||
pub fn append_item(&mut self, item: &PrfItem) {
|
||||
if self.current.is_none() && matches!(item.itype.as_deref(), Some("remote" | "local")) {
|
||||
self.current = item.uid.clone();
|
||||
}
|
||||
|
||||
self.items.get_or_insert_with(Vec::new).push(item.clone());
|
||||
}
|
||||
|
||||
/// Returns true if both IDs were found, including when the item stayed at its old position.
|
||||
pub fn reorder(&mut self, active_id: &str, over_id: &str) -> bool {
|
||||
let Some(items) = self.items.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id));
|
||||
let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id));
|
||||
let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else {
|
||||
return false;
|
||||
};
|
||||
let item = items.remove(old_idx);
|
||||
items.insert(new_idx, item);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn plan_delete_item(&mut self, uid: &str) -> Result<ProfileDeletePlan, ProfileNotFound> {
|
||||
let deleting_current = self.current.as_deref().is_none_or(|current| current == uid);
|
||||
let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| {
|
||||
[
|
||||
op.merge.clone(),
|
||||
op.script.clone(),
|
||||
op.rules.clone(),
|
||||
op.proxies.clone(),
|
||||
op.groups.clone(),
|
||||
]
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
let mut items = self.items.take().unwrap_or_default();
|
||||
let mut files = Vec::new();
|
||||
|
||||
if let Some(file) = take_item_file_by_uid(&mut items, Some(uid)) {
|
||||
files.push(file);
|
||||
}
|
||||
|
||||
for delete_uid in delete_uids {
|
||||
if let Some(file) = take_item_file_by_uid(&mut items, delete_uid.as_deref()) {
|
||||
files.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
if deleting_current {
|
||||
self.current = None;
|
||||
for item in items.iter() {
|
||||
if matches!(item.itype.as_deref(), Some("remote" | "local")) {
|
||||
self.current = item.uid.clone();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.items = Some(items);
|
||||
Ok(ProfileDeletePlan {
|
||||
deleting_current,
|
||||
files,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn profiles_preview(&self) -> Option<Vec<IProfilePreview<'_>>> {
|
||||
self.items.as_ref().map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) {
|
||||
let is_current = self.current.as_ref() == Some(uid);
|
||||
let preview = IProfilePreview { uid, name, is_current };
|
||||
Some(preview)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn take_item_file_by_uid(items: &mut Vec<PrfItem>, target_uid: Option<&str>) -> Option<String> {
|
||||
let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?;
|
||||
items.remove(index).file
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn old_index_preserves_missing_and_explicit_values() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut profiles: IProfiles = serde_yaml_ng::from_str(
|
||||
r#"
|
||||
current: first
|
||||
items:
|
||||
- uid: first
|
||||
type: remote
|
||||
option: {allow_auto_update: false, update_interval: 0, merge: ""}
|
||||
file_data: ignored
|
||||
- uid: second
|
||||
name: ""
|
||||
"#,
|
||||
)?;
|
||||
let first = profiles.get_item("first")?;
|
||||
assert!(first.file_data.is_none());
|
||||
assert_eq!(first.current_merge().map(String::as_str), Some(""));
|
||||
assert!(first.current_script().is_none());
|
||||
if let Some(items) = profiles.items.as_mut() {
|
||||
items[0].file_data = Some("in memory".into());
|
||||
}
|
||||
assert_eq!(
|
||||
serde_json::to_value(&profiles)?,
|
||||
serde_json::json!({
|
||||
"current": "first",
|
||||
"items": [
|
||||
{"uid": "first", "type": "remote", "name": null, "file": null, "updated": null,
|
||||
"option": {"allow_auto_update": false, "update_interval": 0, "merge": "",
|
||||
"script": null, "rules": null, "proxies": null, "groups": null}},
|
||||
{"uid": "second", "type": null, "name": "", "file": null, "updated": null}
|
||||
]
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(serde_yaml_ng::from_str::<IProfiles>("{}")?)?,
|
||||
serde_json::json!({"current": null, "items": null})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_overrides_only_explicit_values() {
|
||||
let base = PrfOption {
|
||||
user_agent: Some("original".into()),
|
||||
allow_auto_update: Some(true),
|
||||
update_interval: Some(60),
|
||||
merge: Some("original-merge".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let overrides = PrfOption {
|
||||
user_agent: Some("".into()),
|
||||
allow_auto_update: Some(false),
|
||||
update_interval: Some(0),
|
||||
..Default::default()
|
||||
};
|
||||
let expected = PrfOption {
|
||||
merge: base.merge.clone(),
|
||||
..overrides.clone()
|
||||
};
|
||||
assert_eq!(PrfOption::merge(Some(&base), Some(&overrides)), Some(expected));
|
||||
assert_eq!(PrfOption::merge(None, None), None);
|
||||
assert_eq!(
|
||||
PrfOption::merge(None, Some(&PrfOption::default())),
|
||||
Some(PrfOption::default())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_preview_and_reorder_preserve_duplicate_uid_rules() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut profiles: IProfiles = serde_yaml_ng::from_str(
|
||||
r#"
|
||||
current: duplicate
|
||||
items:
|
||||
- {uid: duplicate, name: first}
|
||||
- {uid: duplicate, name: last}
|
||||
- {uid: target, name: ""}
|
||||
- {name: no UID}
|
||||
"#,
|
||||
)?;
|
||||
assert_eq!(profiles.get_item("duplicate")?.name.as_deref(), Some("first"));
|
||||
assert!(!profiles.reorder("missing", "target"));
|
||||
assert!(!profiles.reorder("duplicate", "missing"));
|
||||
assert!(profiles.reorder("duplicate", "duplicate"));
|
||||
assert!(profiles.reorder("duplicate", "target"));
|
||||
let preview = profiles.profiles_preview().unwrap_or_default();
|
||||
let names: Vec<_> = preview
|
||||
.iter()
|
||||
.map(|item| (item.name.as_str(), item.is_current))
|
||||
.collect();
|
||||
assert_eq!(names, [("first", true), ("", false), ("last", true)]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_patch_initializes_missing_items_and_only_selects_an_existing_uid() {
|
||||
let mut profiles = IProfiles::default();
|
||||
profiles.patch_current(None);
|
||||
assert!(matches!(&profiles.items, Some(items) if items.is_empty()));
|
||||
assert!(profiles.current.is_none());
|
||||
profiles.append_item(&PrfItem {
|
||||
uid: Some("script".into()),
|
||||
itype: Some("script".into()),
|
||||
..Default::default()
|
||||
});
|
||||
assert!(profiles.current.is_none());
|
||||
profiles.append_item(&PrfItem {
|
||||
uid: Some("local".into()),
|
||||
itype: Some("local".into()),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(profiles.current.as_deref(), Some("local"));
|
||||
profiles.patch_current(None);
|
||||
profiles.patch_current(Some(&String::from("missing")));
|
||||
assert_eq!(profiles.current.as_deref(), Some("local"));
|
||||
profiles.patch_current(Some(&String::from("script")));
|
||||
assert_eq!(profiles.current.as_deref(), Some("script"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_plan_preserves_file_order_and_legacy_missing_uid_matching() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut profiles: IProfiles = serde_yaml_ng::from_str(
|
||||
r"
|
||||
items:
|
||||
- {uid: active, type: remote, file: first.yaml, option: {merge: owned}}
|
||||
- {uid: owned, type: merge, file: owned.yaml}
|
||||
- {type: script, file: missing-uid.js}
|
||||
- {uid: next, type: local, file: next.yaml}
|
||||
",
|
||||
)?;
|
||||
let plan = profiles.plan_delete_item("active")?;
|
||||
assert!(plan.deleting_current);
|
||||
assert_eq!(
|
||||
plan.files,
|
||||
["first.yaml", "owned.yaml", "missing-uid.js"].map(String::from)
|
||||
);
|
||||
assert_eq!(profiles.current.as_deref(), Some("next"));
|
||||
assert!(profiles.get_item("owned").is_err());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
use super::PrfSelected;
|
||||
use std::collections::HashSet;
|
||||
use tristr::alias::String;
|
||||
|
||||
pub struct SelectedGroup<'a> {
|
||||
pub members: Option<&'a [std::string::String]>,
|
||||
pub current: Option<&'a str>,
|
||||
pub selectable: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct SelectedNodesPlan {
|
||||
pub selected: Vec<PrfSelected>,
|
||||
pub activations: Vec<(String, String)>,
|
||||
pub repaired_count: usize,
|
||||
}
|
||||
|
||||
fn node_is_available(available_nodes: &[std::string::String], node: &str) -> bool {
|
||||
available_nodes.iter().any(|available| available == node)
|
||||
}
|
||||
|
||||
pub fn selected_nodes_need_confirmation<'a, Snapshot>(
|
||||
selected: &[PrfSelected],
|
||||
snapshot: &'a Snapshot,
|
||||
lookup: impl Fn(&'a Snapshot, &str) -> Option<SelectedGroup<'a>>,
|
||||
) -> bool {
|
||||
selected.iter().any(|selected_item| {
|
||||
let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else {
|
||||
return false;
|
||||
};
|
||||
let Some(group) = lookup(snapshot, group_name) else {
|
||||
return true;
|
||||
};
|
||||
let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else {
|
||||
return true;
|
||||
};
|
||||
!node_is_available(available_nodes, node)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn reconcile_selected_nodes<'a, Snapshot>(
|
||||
selected: &[PrfSelected],
|
||||
previous: Option<&'a Snapshot>,
|
||||
current: &'a Snapshot,
|
||||
lookup: impl Fn(&'a Snapshot, &str) -> Option<SelectedGroup<'a>>,
|
||||
) -> SelectedNodesPlan {
|
||||
let mut plan = SelectedNodesPlan {
|
||||
selected: Vec::with_capacity(selected.len()),
|
||||
activations: Vec::new(),
|
||||
repaired_count: 0,
|
||||
};
|
||||
let mut seen_groups = HashSet::new();
|
||||
let mut unique_selected = selected
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|item| item.name.as_deref().is_some_and(|name| seen_groups.insert(name)))
|
||||
.collect::<Vec<_>>();
|
||||
unique_selected.reverse();
|
||||
plan.repaired_count += selected.len() - unique_selected.len();
|
||||
|
||||
for selected_item in unique_selected {
|
||||
let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else {
|
||||
plan.repaired_count += 1;
|
||||
continue;
|
||||
};
|
||||
let Some(group) = lookup(current, group_name) else {
|
||||
if previous.is_some_and(|snapshot| lookup(snapshot, group_name).is_none()) {
|
||||
plan.repaired_count += 1;
|
||||
} else {
|
||||
plan.selected.push(selected_item.clone());
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else {
|
||||
// Provider-backed groups can be temporarily incomplete immediately after a reload.
|
||||
plan.selected.push(selected_item.clone());
|
||||
continue;
|
||||
};
|
||||
if !group.selectable {
|
||||
let preferred_node = group
|
||||
.current
|
||||
.filter(|current| node_is_available(available_nodes, current))
|
||||
.or_else(|| node_is_available(available_nodes, node).then_some(node.as_str()));
|
||||
let Some(preferred_node) = preferred_node else {
|
||||
plan.repaired_count += 1;
|
||||
continue;
|
||||
};
|
||||
plan.repaired_count += usize::from(preferred_node != node.as_str());
|
||||
plan.selected.push(PrfSelected {
|
||||
name: Some(group_name.clone()),
|
||||
now: Some(preferred_node.into()),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if node_is_available(available_nodes, node) {
|
||||
plan.selected.push(selected_item.clone());
|
||||
if group.current != Some(node.as_str()) {
|
||||
plan.activations.push((group_name.clone(), node.clone()));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let missing_was_confirmed = previous
|
||||
.and_then(|snapshot| lookup(snapshot, group_name))
|
||||
.and_then(|group| group.members)
|
||||
.filter(|nodes| !nodes.is_empty())
|
||||
.is_some_and(|nodes| !node_is_available(nodes, node));
|
||||
if !missing_was_confirmed {
|
||||
plan.selected.push(selected_item.clone());
|
||||
continue;
|
||||
}
|
||||
|
||||
plan.repaired_count += 1;
|
||||
if let Some(current_node) = group
|
||||
.current
|
||||
.filter(|current| node_is_available(available_nodes, current))
|
||||
{
|
||||
plan.selected.push(PrfSelected {
|
||||
name: Some(group_name.clone()),
|
||||
now: Some(current_node.into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
plan
|
||||
}
|
||||
|
||||
/// Returns recorded selections whose groups have not reached the requested node.
|
||||
pub fn unsettled_selections<'a, Snapshot>(
|
||||
selected: &[PrfSelected],
|
||||
snapshot: &'a Snapshot,
|
||||
lookup: impl Fn(&'a Snapshot, &str) -> Option<SelectedGroup<'a>>,
|
||||
) -> Vec<String> {
|
||||
selected
|
||||
.iter()
|
||||
.filter_map(|item| {
|
||||
let (Some(group_name), Some(node)) = (&item.name, &item.now) else {
|
||||
return None;
|
||||
};
|
||||
match lookup(snapshot, group_name) {
|
||||
Some(group) if group.current == Some(node.as_str()) => None,
|
||||
_ => Some(group_name.clone()),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
use super::PrfItem;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Scheduling policy for a Profile, independent of the task queue and clock.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct SubscriptionSchedule {
|
||||
pub interval_minutes: u64,
|
||||
pub first_delay: Duration,
|
||||
}
|
||||
|
||||
impl SubscriptionSchedule {
|
||||
pub fn for_profile(item: &PrfItem, initializing: bool, now: i64) -> Option<Self> {
|
||||
let option = item.option.as_ref()?;
|
||||
let interval = option.update_interval.filter(|interval| *interval > 0)?;
|
||||
if !option.allow_auto_update.unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut schedule = Self::new(interval, item.updated, now);
|
||||
// Startup historically treats an explicit zero timestamp as overdue.
|
||||
if initializing && item.updated == Some(0) {
|
||||
schedule.first_delay = Duration::ZERO;
|
||||
}
|
||||
Some(schedule)
|
||||
}
|
||||
|
||||
pub fn new(interval_minutes: u64, updated: Option<usize>, now: i64) -> Self {
|
||||
let full = Self::interval_duration(interval_minutes);
|
||||
let elapsed = updated
|
||||
.filter(|updated| *updated > 0)
|
||||
.map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64);
|
||||
|
||||
Self {
|
||||
interval_minutes,
|
||||
first_delay: full.saturating_sub(Duration::from_secs(elapsed)),
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn interval_duration(interval_minutes: u64) -> Duration {
|
||||
Duration::from_secs(interval_minutes.saturating_mul(60))
|
||||
}
|
||||
|
||||
/// The UI deadline is based on the last saved update. The queue can delay retries further.
|
||||
pub fn reported_deadline(interval_minutes: u64, updated: Option<usize>) -> Option<i64> {
|
||||
let updated = i64::try_from(updated.filter(|updated| *updated > 0)?).ok()?;
|
||||
let interval = i64::try_from(interval_minutes).ok()?.checked_mul(60)?;
|
||||
updated.checked_add(interval)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-proxy-view"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
specta = { workspace = true, features = ["derive"] }
|
||||
tristr = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,17 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-runtime-bundle"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
thiserror = { workspace = true }
|
||||
clash-verge-logging = { workspace = true }
|
||||
hex = "0.4.3"
|
||||
log = { workspace = true }
|
||||
serde_yaml_ng = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
tristr = { workspace = true }
|
||||
tokio = { workspace = true, features = ["fs"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,43 +0,0 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum RuntimeBundleError {
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("failed to read runtime config {path:?}")]
|
||||
ReadConfig {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to parse runtime config {path:?}")]
|
||||
ParseConfig {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: serde_yaml_ng::Error,
|
||||
},
|
||||
#[error("runtime config has no parent directory")]
|
||||
MissingConfigDirectory,
|
||||
#[error("runtime provider destination {0:?} is declared for two different sources")]
|
||||
DifferentSources(String),
|
||||
#[error("runtime provider destination {0:?} is claimed more than once")]
|
||||
DuplicateDestination(String),
|
||||
#[error("local runtime provider is unavailable: {path:?}")]
|
||||
LocalProviderUnavailable {
|
||||
path: PathBuf,
|
||||
#[source]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("local runtime provider is outside the config root: {0:?}")]
|
||||
LocalProviderOutsideRoot(PathBuf),
|
||||
#[error("runtime provider destination traverses outside the runtime")]
|
||||
DestinationOutsideRuntime,
|
||||
#[error("runtime provider path has no existing ancestor: {0:?}")]
|
||||
MissingAncestor(PathBuf),
|
||||
#[error("runtime provider path is outside the config root: {0:?}")]
|
||||
ProviderOutsideRoot(PathBuf),
|
||||
#[error("local runtime provider destination traverses outside the runtime")]
|
||||
LocalDestinationOutsideRuntime,
|
||||
#[error("local runtime provider destination is empty")]
|
||||
EmptyDestination,
|
||||
}
|
||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
[dependencies]
|
||||
clash-verge-logging = { workspace = true }
|
||||
log = { workspace = true }
|
||||
tokio = { workspace = true, features = ["signal"] }
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-subscription"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
thiserror = { workspace = true }
|
||||
http = "1"
|
||||
percent-encoding = "2.3.2"
|
||||
serde_yaml_ng = { workspace = true }
|
||||
url = "2.5"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,59 +0,0 @@
|
||||
use percent_encoding::percent_decode_str;
|
||||
use std::borrow::Cow;
|
||||
use url::Url;
|
||||
|
||||
pub struct SubscriptionLink<'a> {
|
||||
pub url: Cow<'a, str>,
|
||||
pub name: Option<Cow<'a, str>>,
|
||||
}
|
||||
|
||||
pub fn decode_subscription_link(link: &Url) -> Option<SubscriptionLink<'_>> {
|
||||
if !matches!(link.scheme(), "clash" | "clash-verge") {
|
||||
return None;
|
||||
}
|
||||
|
||||
// The embedded URL can contain unescaped query separators of its own.
|
||||
let raw_url = link.query()?.split_once("url=")?.1.trim();
|
||||
let name = link.query_pairs().find(|(key, _)| key == "name").map(|(_, name)| name);
|
||||
Some(SubscriptionLink {
|
||||
url: decode_subscription_url(raw_url),
|
||||
name,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> {
|
||||
let mut candidate = Cow::Borrowed(raw_url);
|
||||
if Url::parse(raw_url).is_ok() {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
for _ in 0..2 {
|
||||
let decoded = percent_decode_str(&candidate).decode_utf8_lossy();
|
||||
if decoded == candidate {
|
||||
break;
|
||||
}
|
||||
candidate = Cow::Owned(decoded.into_owned());
|
||||
if Url::parse(&candidate).is_ok() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
candidate
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn preserves_nested_query_separators_and_decodes_wrapped_links() -> Result<(), url::ParseError> {
|
||||
let plain = Url::parse("clash://install-config?name=Work%20VPN&url=https://example.invalid/sub?a=1&b=2")?;
|
||||
let link = decode_subscription_link(&plain).expect("plain subscription link");
|
||||
assert_eq!(link.name.as_deref(), Some("Work VPN"));
|
||||
assert!(matches!(link.url, Cow::Borrowed("https://example.invalid/sub?a=1&b=2")));
|
||||
|
||||
let encoded = Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub")?;
|
||||
let link = decode_subscription_link(&encoded).expect("double-encoded subscription link");
|
||||
assert_eq!(link.url, "https://example.invalid/sub");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum SubscriptionError {
|
||||
#[error("the remote profile data is invalid yaml")]
|
||||
InvalidYaml(#[source] serde_yaml_ng::Error),
|
||||
#[error("profile does not contain `proxies` or `proxy-providers`")]
|
||||
MissingProviders,
|
||||
}
|
||||
@@ -1,193 +0,0 @@
|
||||
mod deep_link;
|
||||
mod error;
|
||||
|
||||
pub use deep_link::{SubscriptionLink, decode_subscription_link};
|
||||
pub use error::SubscriptionError;
|
||||
|
||||
use http::HeaderMap;
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde_yaml_ng::Mapping;
|
||||
use url::Url;
|
||||
|
||||
pub struct SubscriptionDocument<'a> {
|
||||
pub body: &'a str,
|
||||
pub filename: Option<String>,
|
||||
pub usage: Option<SubscriptionUsage>,
|
||||
pub update_interval_minutes: Option<u64>,
|
||||
pub home: Option<String>,
|
||||
}
|
||||
|
||||
pub struct SubscriptionUsage {
|
||||
pub upload: u64,
|
||||
pub download: u64,
|
||||
pub total: u64,
|
||||
pub expire: u64,
|
||||
}
|
||||
|
||||
pub fn decode_subscription<'a>(
|
||||
url: &Url,
|
||||
headers: &HeaderMap,
|
||||
body: &'a str,
|
||||
) -> Result<SubscriptionDocument<'a>, SubscriptionError> {
|
||||
let body = body.trim_start_matches('\u{feff}');
|
||||
let yaml = serde_yaml_ng::from_str::<Mapping>(body).map_err(SubscriptionError::InvalidYaml)?;
|
||||
|
||||
if !yaml.contains_key("proxies") && !yaml.contains_key("proxy-providers") {
|
||||
return Err(SubscriptionError::MissingProviders);
|
||||
}
|
||||
|
||||
let usage = headers.iter().find_map(|(name, value)| {
|
||||
let prefix = name.as_str().strip_suffix("subscription-userinfo")?;
|
||||
if !prefix.is_empty() && !prefix.ends_with('-') {
|
||||
return None;
|
||||
}
|
||||
|
||||
let value = value.to_str().unwrap_or("");
|
||||
Some(SubscriptionUsage {
|
||||
upload: find_field(value, "upload", |field| field.parse().ok()).unwrap_or(0),
|
||||
download: find_field(value, "download", |field| field.parse().ok()).unwrap_or(0),
|
||||
total: find_field(value, "total", |field| field.parse().ok()).unwrap_or(0),
|
||||
expire: find_field(value, "expire", |field| field.parse().ok()).unwrap_or(0),
|
||||
})
|
||||
});
|
||||
let update_interval_minutes = headers.get("profile-update-interval").and_then(|value| {
|
||||
let hours = value.to_str().ok()?.parse::<u64>().ok()?;
|
||||
hours.checked_mul(60)
|
||||
});
|
||||
let home = headers
|
||||
.get("profile-web-page-url")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(normalize_profile_home_url);
|
||||
|
||||
Ok(SubscriptionDocument {
|
||||
body,
|
||||
filename: subscription_filename(url, headers),
|
||||
usage,
|
||||
update_interval_minutes,
|
||||
home,
|
||||
})
|
||||
}
|
||||
|
||||
fn subscription_filename(url: &Url, headers: &HeaderMap) -> Option<String> {
|
||||
if let Some(value) = headers.get("content-disposition") {
|
||||
let disposition = format!("{value:?}");
|
||||
let disposition = disposition.trim_matches('"');
|
||||
if let Some(encoded) = find_field(disposition, "filename*", Some)
|
||||
&& let Ok(decoded) = percent_decode_str(encoded).decode_utf8()
|
||||
&& let Some(filename) = decoded.split("''").last()
|
||||
&& !filename.trim().is_empty()
|
||||
{
|
||||
return Some(filename.to_owned());
|
||||
}
|
||||
if let Some(filename) = find_field(disposition, "filename", Some).map(|name| name.trim_matches('"'))
|
||||
&& !filename.trim().is_empty()
|
||||
{
|
||||
return Some(filename.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
let url = url.as_str();
|
||||
let path = url.split_once('?').map_or(url, |(path, _)| path);
|
||||
let filename = path.rsplit_once('/').map_or(path, |(_, filename)| filename);
|
||||
let filename = percent_decode_str(filename).decode_utf8_lossy();
|
||||
if filename.trim().is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(filename.into_owned())
|
||||
}
|
||||
|
||||
pub fn normalize_profile_home_url(raw: &str) -> Option<String> {
|
||||
let url = Url::parse(raw.trim()).ok()?;
|
||||
|
||||
if !matches!(url.scheme(), "http" | "https") {
|
||||
return None;
|
||||
}
|
||||
|
||||
url.host_str()?;
|
||||
Some(url.as_str().into())
|
||||
}
|
||||
|
||||
fn find_field<'a, T>(target: &'a str, key: &str, mut parse: impl FnMut(&'a str) -> Option<T>) -> Option<T> {
|
||||
target.split(';').map(str::trim).find_map(|s| {
|
||||
let (name, value) = s.split_once('=')?;
|
||||
if name != key {
|
||||
return None;
|
||||
}
|
||||
|
||||
parse(value)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use http::HeaderValue;
|
||||
|
||||
#[test]
|
||||
fn decodes_metadata_and_preserves_provider_only_yaml() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let url = Url::parse("https://example.com/fallback.yaml")?;
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"content-disposition",
|
||||
HeaderValue::from_static("attachment; filename*=UTF-8''My%20Profile.yaml; filename=fallback.yaml"),
|
||||
);
|
||||
headers.insert(
|
||||
"x-amz-meta-subscription-userinfo",
|
||||
HeaderValue::from_static("upload=1; download=2; total=3; expire=4"),
|
||||
);
|
||||
headers.insert("profile-update-interval", HeaderValue::from_static("2"));
|
||||
headers.insert(
|
||||
"profile-web-page-url",
|
||||
HeaderValue::from_static(" https://example.com "),
|
||||
);
|
||||
let yaml = "# keep this comment\nproxy-providers: {}\n";
|
||||
let body = format!("\u{feff}{yaml}");
|
||||
|
||||
let document = decode_subscription(&url, &headers, &body)?;
|
||||
assert_eq!(document.body, yaml);
|
||||
assert_eq!(document.filename.as_deref(), Some("My Profile.yaml"));
|
||||
assert_eq!(document.update_interval_minutes, Some(120));
|
||||
assert_eq!(document.home.as_deref(), Some("https://example.com/"));
|
||||
let usage = document.usage.ok_or("missing subscription usage")?;
|
||||
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn falls_back_when_suggested_filename_is_invalid_or_empty() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let url = Url::parse("https://example.com/url.yaml?token=value")?;
|
||||
let root_url = Url::parse("https://example.com/")?;
|
||||
for (disposition, url, expected) in [
|
||||
(
|
||||
"attachment; filename*=UTF-8''%FF; filename=valid.yaml",
|
||||
&url,
|
||||
Some("valid.yaml"),
|
||||
),
|
||||
(
|
||||
"attachment; filename*=UTF-8''; filename=valid.yaml",
|
||||
&url,
|
||||
Some("valid.yaml"),
|
||||
),
|
||||
("attachment; filename*=UTF-8''%FF", &url, Some("url.yaml")),
|
||||
("attachment; filename=", &root_url, None),
|
||||
] {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("content-disposition", HeaderValue::from_static(disposition));
|
||||
let document = decode_subscription(url, &headers, "proxies: []")?;
|
||||
assert_eq!(document.filename.as_deref(), expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_overflowing_server_interval() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let url = Url::parse("https://example.com/My%20Profile.yaml?token=value")?;
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert("profile-update-interval", HeaderValue::from_str(&u64::MAX.to_string())?);
|
||||
|
||||
let document = decode_subscription(&url, &headers, "proxies: []")?;
|
||||
assert_eq!(document.update_interval_minutes, None);
|
||||
assert_eq!(document.filename.as_deref(), Some("My Profile.yaml"));
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
[package]
|
||||
name = "clash-verge-task"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
futures = { workspace = true }
|
||||
parking_lot = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -1,60 +0,0 @@
|
||||
use std::{future::Future, time::Duration};
|
||||
use tokio::{sync::mpsc, time::sleep};
|
||||
|
||||
enum Command<T> {
|
||||
Arm(T),
|
||||
Disarm,
|
||||
}
|
||||
|
||||
pub struct Countdown<T> {
|
||||
commands: mpsc::UnboundedSender<Command<T>>,
|
||||
}
|
||||
|
||||
impl<T> Countdown<T> {
|
||||
pub fn arm(&self, input: T) {
|
||||
let _ = self.commands.send(Command::Arm(input));
|
||||
}
|
||||
|
||||
pub fn disarm(&self) {
|
||||
let _ = self.commands.send(Command::Disarm);
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a countdown with a caller-owned driver. An active countdown ignores
|
||||
/// additional arms. Disarm and channel closure take precedence over expiry.
|
||||
///
|
||||
/// Return `None` from `delay` to reject an arm before starting the countdown.
|
||||
/// The delay future may be dropped on disarm, including while it loads the duration.
|
||||
pub fn new<T, Fut>(
|
||||
mut delay: impl FnMut(T) -> Option<Fut> + Send,
|
||||
mut elapsed: impl FnMut(T) + Send,
|
||||
) -> (Countdown<T>, impl Future<Output = ()> + Send)
|
||||
where
|
||||
T: Copy + Send,
|
||||
Fut: Future<Output = Duration> + Send,
|
||||
{
|
||||
let (commands, mut receiver) = mpsc::unbounded_channel();
|
||||
let driver = async move {
|
||||
while let Some(command) = receiver.recv().await {
|
||||
let Command::Arm(input) = command else { continue };
|
||||
let Some(delay) = delay(input) else { continue };
|
||||
let countdown = async { sleep(delay.await).await };
|
||||
tokio::pin!(countdown);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
command = receiver.recv() => match command {
|
||||
Some(Command::Arm(_)) => {}
|
||||
Some(Command::Disarm) => break,
|
||||
None => return,
|
||||
},
|
||||
() = &mut countdown => {
|
||||
elapsed(input);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
(Countdown { commands }, driver)
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
//! Task drivers and retry primitives with caller-managed runtime and cancellation.
|
||||
|
||||
pub mod countdown;
|
||||
pub mod retry;
|
||||
pub mod scheduled_task;
|
||||
pub mod watch_task;
|
||||
@@ -1,146 +0,0 @@
|
||||
use futures::FutureExt as _;
|
||||
use parking_lot::Mutex;
|
||||
use std::{
|
||||
future::Future,
|
||||
panic::AssertUnwindSafe,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
use tokio::{
|
||||
sync::Notify,
|
||||
time::{Instant, sleep_until},
|
||||
};
|
||||
|
||||
/// The next decision after the driver drains pending inputs.
|
||||
pub enum Next<W> {
|
||||
Idle,
|
||||
At(Instant),
|
||||
Run(W),
|
||||
}
|
||||
|
||||
/// Synchronous policy owned and called by one driver.
|
||||
pub trait ScheduledTask {
|
||||
/// The merged pending input. Its default value represents no requests.
|
||||
type Input: Default;
|
||||
type Work: Copy + Send;
|
||||
type Output;
|
||||
|
||||
fn on_input(&mut self, input: Self::Input, now: Instant);
|
||||
fn next(&mut self, now: Instant) -> Next<Self::Work>;
|
||||
/// Receives the execution result or an unwind from the execution callback.
|
||||
fn finished(&mut self, work: Self::Work, result: std::thread::Result<Self::Output>, now: Instant);
|
||||
}
|
||||
|
||||
/// A coalescing slot shared with one driver.
|
||||
pub struct Mailbox<I> {
|
||||
pending: Mutex<I>,
|
||||
changed: Notify,
|
||||
}
|
||||
|
||||
impl<I> Mailbox<I> {
|
||||
/// Merge into the pending slot under a short synchronous lock.
|
||||
///
|
||||
/// Return true from `merge` when the driver should wake up. This only
|
||||
/// submits input. Any completion reply belongs to the caller's protocol.
|
||||
pub fn update(&self, merge: impl FnOnce(&mut I) -> bool) {
|
||||
let changed = merge(&mut *self.pending.lock());
|
||||
if changed {
|
||||
self.changed.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Create the mailbox and its driver. The caller chooses how to run the future.
|
||||
///
|
||||
/// While the driver is running, pending inputs wake idle waits and do not
|
||||
/// interrupt an active job. Keep the driver alive until any issued effects
|
||||
/// complete. Dropping producers does not shut it down.
|
||||
pub fn new<P, F, Fut>(policy: P, execute: F) -> (Arc<Mailbox<P::Input>>, impl Future<Output = ()> + Send + 'static)
|
||||
where
|
||||
P: ScheduledTask + Send + 'static,
|
||||
P::Input: Send + 'static,
|
||||
F: FnMut(P::Work) -> Fut + Send + 'static,
|
||||
Fut: Future<Output = P::Output> + Send + 'static,
|
||||
{
|
||||
let inbox = Arc::new(Mailbox {
|
||||
pending: Mutex::default(),
|
||||
changed: Notify::new(),
|
||||
});
|
||||
let receiver = Arc::clone(&inbox);
|
||||
(inbox, drive(policy, receiver, execute))
|
||||
}
|
||||
|
||||
async fn drive<P, F, Fut>(mut policy: P, inbox: Arc<Mailbox<P::Input>>, mut execute: F)
|
||||
where
|
||||
P: ScheduledTask,
|
||||
F: FnMut(P::Work) -> Fut,
|
||||
Fut: Future<Output = P::Output>,
|
||||
{
|
||||
loop {
|
||||
let input = std::mem::take(&mut *inbox.pending.lock());
|
||||
let now = Instant::now();
|
||||
policy.on_input(input, now);
|
||||
match policy.next(now) {
|
||||
Next::Idle => inbox.changed.notified().await,
|
||||
Next::At(due) => {
|
||||
tokio::select! {
|
||||
_ = inbox.changed.notified() => {}
|
||||
_ = sleep_until(due) => {}
|
||||
}
|
||||
}
|
||||
Next::Run(work) => {
|
||||
// Pending inputs merge while the job runs. They cannot interrupt its effects.
|
||||
let run = &mut execute;
|
||||
let result = AssertUnwindSafe(async move { run(work).await }).catch_unwind().await;
|
||||
policy.finished(work, result, Instant::now());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A request to run a job with at most one pending successor.
|
||||
pub struct CoalescingJob(Arc<JobSignal>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct JobSignal {
|
||||
pending: AtomicBool,
|
||||
changed: Notify,
|
||||
}
|
||||
|
||||
impl CoalescingJob {
|
||||
pub fn request(&self) {
|
||||
if !self.0.pending.swap(true, Ordering::Release) {
|
||||
self.0.changed.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconcile on demand without interrupting work in progress.
|
||||
pub fn coalescing<Fut>(
|
||||
mut execute: impl FnMut() -> Fut + Send + 'static,
|
||||
mut on_panic: impl FnMut() + Send + 'static,
|
||||
) -> (CoalescingJob, impl Future<Output = ()> + Send + 'static)
|
||||
where
|
||||
Fut: Future<Output = ()> + Send + 'static,
|
||||
{
|
||||
let signal = Arc::new(JobSignal::default());
|
||||
let worker_signal = Arc::clone(&signal);
|
||||
let driver = async move {
|
||||
loop {
|
||||
worker_signal.changed.notified().await;
|
||||
// Requests coalesce until the driver claims the batch, even after it has been woken.
|
||||
worker_signal.pending.swap(false, Ordering::Acquire);
|
||||
let run = &mut execute;
|
||||
if AssertUnwindSafe(async move { run().await })
|
||||
.catch_unwind()
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
on_panic();
|
||||
}
|
||||
}
|
||||
};
|
||||
(CoalescingJob(signal), driver)
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
use futures::FutureExt as _;
|
||||
use std::{future::Future, panic::AssertUnwindSafe};
|
||||
use tokio::sync::watch;
|
||||
|
||||
/// Run a session for each observed nonempty plan, beginning on the first change.
|
||||
///
|
||||
/// Subscribe while the plan is `None` before publishing the first session.
|
||||
/// While a session runs, plans may coalesce to the latest value. The callback
|
||||
/// chooses where to observe replacements and owns any issued effects until it
|
||||
/// returns. An unwinding callback is reported before observing the next plan.
|
||||
pub async fn run<T, F, Fut>(mut desired: watch::Receiver<Option<T>>, mut run: F, mut on_panic: impl FnMut(T) + Send)
|
||||
where
|
||||
T: Clone + Send + Sync,
|
||||
F: FnMut(T, watch::Receiver<Option<T>>) -> Fut + Send,
|
||||
Fut: Future<Output = ()> + Send,
|
||||
{
|
||||
while desired.changed().await.is_ok() {
|
||||
let state = desired.borrow_and_update().clone();
|
||||
if let Some(state) = state {
|
||||
// Cancellation can consume updates on this clone without skipping them in the owner.
|
||||
let updates = desired.clone();
|
||||
if AssertUnwindSafe(async { run(state.clone(), updates).await })
|
||||
.catch_unwind()
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
on_panic(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,259 +0,0 @@
|
||||
use clash_verge_task::{
|
||||
countdown,
|
||||
scheduled_task::{self, Mailbox, Next, ScheduledTask},
|
||||
watch_task,
|
||||
};
|
||||
use std::{error::Error, future::ready, time::Duration};
|
||||
use tokio::{
|
||||
sync::{mpsc, oneshot, watch},
|
||||
time::{Instant, advance, timeout},
|
||||
};
|
||||
|
||||
type TestResult = Result<(), Box<dyn Error>>;
|
||||
|
||||
struct Schedule {
|
||||
due: Option<Instant>,
|
||||
completed: mpsc::UnboundedSender<bool>,
|
||||
}
|
||||
|
||||
impl ScheduledTask for Schedule {
|
||||
type Input = Option<Instant>;
|
||||
type Work = Instant;
|
||||
type Output = ();
|
||||
|
||||
fn on_input(&mut self, input: Self::Input, _: Instant) {
|
||||
self.due = self.due.into_iter().chain(input).min();
|
||||
}
|
||||
|
||||
fn next(&mut self, now: Instant) -> Next<Instant> {
|
||||
match self.due {
|
||||
Some(due) if due <= now => {
|
||||
self.due = None;
|
||||
Next::Run(due)
|
||||
}
|
||||
Some(due) => Next::At(due),
|
||||
None => Next::Idle,
|
||||
}
|
||||
}
|
||||
|
||||
fn finished(&mut self, _: Instant, result: std::thread::Result<()>, _: Instant) {
|
||||
let _ = self.completed.send(result.is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
fn request(mailbox: &Mailbox<Option<Instant>>, due: Instant) {
|
||||
mailbox.update(|pending| {
|
||||
if pending.is_some_and(|current| current <= due) {
|
||||
return false;
|
||||
}
|
||||
*pending = Some(due);
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
async fn receive<T: Send>(receiver: &mut mpsc::UnboundedReceiver<T>) -> Result<T, Box<dyn Error>> {
|
||||
timeout(Duration::from_secs(10), receiver.recv())
|
||||
.await?
|
||||
.ok_or_else(|| "driver event channel closed".into())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn countdown_keeps_the_first_arm_until_it_expires() -> TestResult {
|
||||
let delay = Duration::from_secs(4);
|
||||
let (elapsed, mut events) = mpsc::unbounded_channel();
|
||||
let (countdown, driver) = countdown::new(
|
||||
move |_| Some(ready(delay)),
|
||||
move |input| {
|
||||
let _ = elapsed.send(input);
|
||||
},
|
||||
);
|
||||
let mut driver = Box::pin(driver);
|
||||
let start = Instant::now();
|
||||
countdown.arm(1);
|
||||
assert!(futures::poll!(driver.as_mut()).is_pending());
|
||||
advance(Duration::from_secs(2)).await;
|
||||
countdown.arm(2);
|
||||
let driver = tokio::spawn(driver);
|
||||
|
||||
assert_eq!(receive(&mut events).await?, 1);
|
||||
assert_eq!(Instant::now() - start, delay);
|
||||
drop(countdown);
|
||||
driver.await?;
|
||||
assert!(events.try_recv().is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn ready_disarm_wins_and_the_next_arm_starts_a_new_countdown() -> TestResult {
|
||||
let delay = Duration::from_secs(4);
|
||||
let (elapsed, mut events) = mpsc::unbounded_channel();
|
||||
let (countdown, driver) = countdown::new(
|
||||
move |_| Some(ready(delay)),
|
||||
move |input| {
|
||||
let _ = elapsed.send(input);
|
||||
},
|
||||
);
|
||||
let mut driver = Box::pin(driver);
|
||||
countdown.arm(1);
|
||||
assert!(futures::poll!(driver.as_mut()).is_pending());
|
||||
advance(delay).await;
|
||||
countdown.disarm();
|
||||
countdown.arm(2);
|
||||
let rearmed_at = Instant::now();
|
||||
let driver = tokio::spawn(driver);
|
||||
|
||||
assert_eq!(receive(&mut events).await?, 2);
|
||||
assert_eq!(Instant::now() - rearmed_at, delay);
|
||||
drop(countdown);
|
||||
driver.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[allow(clippy::panic, reason = "inject an unwind into a coalescing job")]
|
||||
async fn coalescing_preserves_one_pending_batch_through_a_panic() -> TestResult {
|
||||
let (started, mut runs) = mpsc::unbounded_channel();
|
||||
let (panicked, mut panics) = mpsc::unbounded_channel();
|
||||
let mut first = true;
|
||||
let (job, driver) = scheduled_task::coalescing(
|
||||
move || {
|
||||
let (release, wait) = oneshot::channel();
|
||||
let _ = started.send(release);
|
||||
let fail = std::mem::take(&mut first);
|
||||
async move {
|
||||
let _ = wait.await;
|
||||
if fail {
|
||||
panic!("test job panic");
|
||||
}
|
||||
}
|
||||
},
|
||||
move || {
|
||||
let _ = panicked.send(());
|
||||
},
|
||||
);
|
||||
let mut driver = Box::pin(driver);
|
||||
|
||||
assert!(futures::poll!(driver.as_mut()).is_pending());
|
||||
job.request();
|
||||
job.request();
|
||||
assert!(futures::poll!(driver.as_mut()).is_pending());
|
||||
runs.try_recv()?.send(()).map_err(|()| "first job was dropped")?;
|
||||
assert!(futures::poll!(driver.as_mut()).is_pending());
|
||||
panics.try_recv()?;
|
||||
assert!(runs.try_recv().is_err());
|
||||
|
||||
job.request();
|
||||
assert!(futures::poll!(driver.as_mut()).is_pending());
|
||||
let release = runs.try_recv()?;
|
||||
job.request();
|
||||
job.request();
|
||||
release.send(()).map_err(|()| "second job was dropped")?;
|
||||
assert!(futures::poll!(driver.as_mut()).is_pending());
|
||||
runs.try_recv()?.send(()).map_err(|()| "successor was dropped")?;
|
||||
assert!(futures::poll!(driver.as_mut()).is_pending());
|
||||
assert!(runs.try_recv().is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn an_earlier_request_reschedules_an_idle_wait() -> TestResult {
|
||||
let (completed, mut results) = mpsc::unbounded_channel();
|
||||
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, |_| async {});
|
||||
let mut driver = Box::pin(driver);
|
||||
let start = Instant::now();
|
||||
|
||||
request(&mailbox, start + Duration::from_secs(8));
|
||||
assert!(futures::poll!(driver.as_mut()).is_pending());
|
||||
request(&mailbox, start + Duration::from_secs(2));
|
||||
let driver = tokio::spawn(driver);
|
||||
assert!(receive(&mut results).await?);
|
||||
assert_eq!(Instant::now() - start, Duration::from_secs(2));
|
||||
driver.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn active_work_finishes_before_one_coalesced_successor() -> TestResult {
|
||||
let (completed, mut results) = mpsc::unbounded_channel();
|
||||
let (started, mut runs) = mpsc::unbounded_channel();
|
||||
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, move |due| {
|
||||
let (release, wait) = oneshot::channel();
|
||||
let _ = started.send((due, release));
|
||||
async move {
|
||||
let _ = wait.await;
|
||||
}
|
||||
});
|
||||
let driver = tokio::spawn(driver);
|
||||
let start = Instant::now();
|
||||
request(&mailbox, start);
|
||||
let (_, release) = receive(&mut runs).await?;
|
||||
|
||||
let next = start + Duration::from_secs(2);
|
||||
request(&mailbox, start + Duration::from_secs(4));
|
||||
request(&mailbox, next);
|
||||
advance(Duration::from_secs(5)).await;
|
||||
assert!(runs.try_recv().is_err());
|
||||
assert!(results.try_recv().is_err());
|
||||
|
||||
release.send(()).map_err(|()| "first job was dropped")?;
|
||||
assert!(receive(&mut results).await?);
|
||||
let (due, release) = receive(&mut runs).await?;
|
||||
assert_eq!(due, next);
|
||||
release.send(()).map_err(|()| "second job was dropped")?;
|
||||
assert!(receive(&mut results).await?);
|
||||
assert!(timeout(Duration::from_secs(1), runs.recv()).await.is_err());
|
||||
driver.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
#[allow(clippy::panic, reason = "inject an unwind into the execution future")]
|
||||
async fn a_job_panic_reports_failure_and_allows_more_work() -> TestResult {
|
||||
let (completed, mut results) = mpsc::unbounded_channel();
|
||||
let start = Instant::now();
|
||||
let (mailbox, driver) = scheduled_task::new(Schedule { due: None, completed }, move |due| async move {
|
||||
if due == start {
|
||||
panic!("test job panic");
|
||||
}
|
||||
});
|
||||
let driver = tokio::spawn(driver);
|
||||
|
||||
request(&mailbox, start);
|
||||
assert!(!receive(&mut results).await?);
|
||||
request(&mailbox, start + Duration::from_secs(1));
|
||||
assert!(receive(&mut results).await?);
|
||||
driver.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
#[allow(clippy::panic, reason = "inject an unwind after observing session replacement")]
|
||||
async fn a_session_panic_does_not_consume_the_replacement() -> TestResult {
|
||||
let (plan, desired) = watch::channel(None);
|
||||
let (event, mut events) = mpsc::unbounded_channel();
|
||||
let panicked = event.clone();
|
||||
let driver = tokio::spawn(watch_task::run(
|
||||
desired,
|
||||
move |session, mut updates| {
|
||||
let event = event.clone();
|
||||
async move {
|
||||
let _ = event.send((session, false));
|
||||
if session == 1 && updates.changed().await.is_ok() {
|
||||
panic!("test session panic");
|
||||
}
|
||||
}
|
||||
},
|
||||
move |session| {
|
||||
let _ = panicked.send((session, true));
|
||||
},
|
||||
));
|
||||
|
||||
plan.send_replace(Some(1));
|
||||
assert_eq!(receive(&mut events).await?, (1, false));
|
||||
plan.send_replace(Some(2));
|
||||
assert_eq!(receive(&mut events).await?, (1, true));
|
||||
assert_eq!(receive(&mut events).await?, (2, false));
|
||||
drop(plan);
|
||||
driver.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -73,4 +73,4 @@ Native UI strings (tray menu, notifications, dialogs) use `rust-i18n` with YAML
|
||||
|
||||
- File an issue for missing context, tooling bugs, or localization gaps so we can track them.
|
||||
- PRs that touch UI should include screenshots or GIFs whenever text length may affect layout.
|
||||
- Keep routine command results in the working conversation rather than the PR body; report only material localization or layout gaps. If you need extra context or review help, request it via a PR comment.
|
||||
- Mention the commands you ran (formatting, type generation, tests) in the PR checklist. If you need extra context or review help, request it via a PR comment.
|
||||
|
||||
+4
-4
@@ -78,7 +78,7 @@
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"swr": "^2.5.1",
|
||||
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
|
||||
"tldts": "7.6.2",
|
||||
"tldts": "7.5.5",
|
||||
"types-pac": "^1.0.3",
|
||||
"validator": "^13.15.35"
|
||||
},
|
||||
@@ -90,7 +90,7 @@
|
||||
"@tauri-apps/cli": "2.12.6",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^26.0.0",
|
||||
"@types/react": "19.3.3",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "19.3.0",
|
||||
"@types/validator": "^13.15.10",
|
||||
"@vitejs/plugin-legacy": "^8.2.3",
|
||||
@@ -113,10 +113,10 @@
|
||||
"https-proxy-agent": "^9.1.0",
|
||||
"husky": "^9.1.7",
|
||||
"jiti": "^2.7.0",
|
||||
"knip": "6.49.0",
|
||||
"knip": "6.48.0",
|
||||
"lint-staged": "^17.5.1",
|
||||
"sass": "^1.104.1",
|
||||
"tar": "^8.0.0",
|
||||
"tar": "^7.5.22",
|
||||
"terser": "^5.51.2",
|
||||
"tsrs": "0.20.0-ts7.1.0-beta",
|
||||
"typescript": "^6.0.3",
|
||||
|
||||
Generated
+208
-198
@@ -199,10 +199,10 @@ importers:
|
||||
version: 0.5.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
'@emotion/react':
|
||||
specifier: ^11.14.0
|
||||
version: 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
version: 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/styled':
|
||||
specifier: ^11.14.1
|
||||
version: 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
version: 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@juggle/resize-observer':
|
||||
specifier: ^3.4.0
|
||||
version: 3.4.0
|
||||
@@ -211,10 +211,10 @@ importers:
|
||||
version: 4.7.0(monaco-editor@0.58.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
'@mui/icons-material':
|
||||
specifier: ^9.4.0
|
||||
version: 9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.3)(react@19.3.1)
|
||||
version: 9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.0)(react@19.3.1)
|
||||
'@mui/material':
|
||||
specifier: ^9.4.0
|
||||
version: 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
version: 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
'@tanstack/react-virtual':
|
||||
specifier: ^3.14.13
|
||||
version: 3.14.13(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
@@ -286,16 +286,16 @@ importers:
|
||||
version: 19.3.1(react@19.3.1)
|
||||
react-error-boundary:
|
||||
specifier: 6.1.6
|
||||
version: 6.1.6(@types/react@19.3.3)(react@19.3.1)
|
||||
version: 6.1.6(@types/react@19.3.0)(react@19.3.1)
|
||||
react-hook-form:
|
||||
specifier: ^7.88.0
|
||||
version: 7.88.0(react@19.3.1)
|
||||
react-i18next:
|
||||
specifier: 18.0.3
|
||||
version: 18.0.3(@types/react@19.3.3)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3)
|
||||
version: 18.0.3(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3)
|
||||
react-markdown:
|
||||
specifier: 10.1.0
|
||||
version: 10.1.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
version: 10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
react-router:
|
||||
specifier: ^8.4.0
|
||||
version: 8.4.0(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
@@ -312,8 +312,8 @@ importers:
|
||||
specifier: github:clash-verge-rev/tauri-plugin-mihomo#main
|
||||
version: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f
|
||||
tldts:
|
||||
specifier: 7.6.2
|
||||
version: 7.6.2
|
||||
specifier: 7.5.5
|
||||
version: 7.5.5
|
||||
types-pac:
|
||||
specifier: ^1.0.3
|
||||
version: 1.0.3
|
||||
@@ -343,11 +343,11 @@ importers:
|
||||
specifier: ^26.0.0
|
||||
version: 26.6.5
|
||||
'@types/react':
|
||||
specifier: 19.3.3
|
||||
version: 19.3.3
|
||||
specifier: 19.3.0
|
||||
version: 19.3.0
|
||||
'@types/react-dom':
|
||||
specifier: 19.3.0
|
||||
version: 19.3.0(@types/react@19.3.3)
|
||||
version: 19.3.0(@types/react@19.3.0)
|
||||
'@types/validator':
|
||||
specifier: ^13.15.10
|
||||
version: 13.15.10
|
||||
@@ -412,8 +412,8 @@ importers:
|
||||
specifier: ^2.7.0
|
||||
version: 2.7.0
|
||||
knip:
|
||||
specifier: 6.49.0
|
||||
version: 6.49.0
|
||||
specifier: 6.48.0
|
||||
version: 6.48.0
|
||||
lint-staged:
|
||||
specifier: ^17.5.1
|
||||
version: 17.5.1
|
||||
@@ -421,8 +421,8 @@ importers:
|
||||
specifier: ^1.104.1
|
||||
version: 1.104.1
|
||||
tar:
|
||||
specifier: ^8.0.0
|
||||
version: 8.0.2
|
||||
specifier: ^7.5.22
|
||||
version: 7.5.22
|
||||
terser:
|
||||
specifier: ^5.51.2
|
||||
version: 5.51.2
|
||||
@@ -1387,6 +1387,10 @@ packages:
|
||||
resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==}
|
||||
engines: {node: '>=18.18'}
|
||||
|
||||
'@isaacs/fs-minipass@4.0.1':
|
||||
resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==}
|
||||
engines: {node: '>=18.0.0'}
|
||||
|
||||
'@jridgewell/gen-mapping@0.3.13':
|
||||
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
|
||||
|
||||
@@ -1574,124 +1578,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.156.0':
|
||||
resolution: {integrity: sha512-RMq7DKNzEp1T51QKNLTn0NryNEt2IYfh7mZBlIdi2Ju52ltOEDMeIXv0XBpA6dL7j7ChjlcovtGcc1Jv4qMipg==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-mwkWKhOBpmh8fWc3m4MiLsmEAtx0YuHmvyo9ff557cnb3QZ2kt2eauSz75wCGIpiZG3gUsJ4WwzEjm4R4/BHig==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-6pGR5fUszM9M4eBBapqpGjCRJolFwuCldx8bRQjqXyM09cQysBTWVF2Ttg4UNJVxYSaw5RRINbveCOOCrsuGvA==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-M9QghL7uCAqMKjYJv1rDGblfEvkeQu3QzTPd7Uwo16gG3uO7m9ikVQ9OL8FZTnKzU4vbCEby6kTlEkqN+JeEMA==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-lX0ANxSwAOrpOT7NHB+YsrBqDJ8sOVon5m7GS9eQtkuUeNzQMMGpFsJLsStawTbrdwOF5KDVxgPWcKmt/DIZUQ==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-iPgYpasRcqk7X3TGncQg7B+6RotDvG8weug0UrgF+FXLf4KmaNDyT91BKONlqbHcNgK9Nryp7AEZGuQn32fP6g==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-sJqJDEZevtkEfoxrXfaRTkSt6Itckr549cIfBbs11UgXv8bFyqQsXTQa6iKm8mTiWYmCDDFJf7TLnqxcbqzPOw==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-mrQs5OdRiqKskRuWEORPKT6YGIFhrpVvCvL9hqVaIh60EzgR4qjPvSsV6hWZcOfyWHBTbdEvfnDJPh/eQlxPRQ==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-ZtPqgCU3+wpU7dvX7YbaEiw71r0UdguzuPhcx4PIEZSs4XFqc6F5wXCtNdb6M7m3DMErlxrwosryoXrzYOY/Gg==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-ZuGRT/adReZZJn3PYNneb1HQIOH0iIZ2fzFgC1/XJYpMQ5KsRKmWIEzy3wEFsUwIOTomCmnmTZ/zbFYo9z9VeA==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-T+iWCeAOoEAJpHqr6/pogHIv98g9p8Ctccysm/h962hG4ayX5OL2c0Ih4oYe+JuFndLXy/OASvwMlTPe76sIiw==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-wL55bI2kVKfwdxScbw60zVgzAqbQbmE5zpSPWPZoZ9RSG8egm6ITE/UWE5mDWlglxz1QElJCcUbpaJCtHD11BQ==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-+D+JilhLqwrDLODYEl4qtovVwgxKALb23FkAWBiPvgmUWYgjCV83KKuwwxZJM8GCdKlNA1vt3iKtow8HUFjXtg==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-jRfwpN4xKrsEpC+SgrUPY5k0mINYZn7aLrt22I3uQFoumiSgHgsLYgS9f84ntbkvSydH4HiwGuDa2b1XCHaJzw==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-P/ajnypgLmxmuRRyCIZcp2o4lOwmCaXYH5+eqDTcCW+MCTI+csKSw/Zc6GB67jZoVa4ey3q1jXEt7S60adBEMQ==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-WSN6rQZZc9KqgZ4lMfjVDvqKhVOCjey/YEZIPisGXmwBqwgWOzru207dyiH50LHcf1n9LO2oceGk/id6RL9v0g==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-l21Tz6tjraGBC3JefVeJZ9pojD0fCiB62PydAv+i9nrqJX7z/pDmyDNYLamDr/PRcQ4UQbFwkSnz7NKBB9UMLw==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-CUq0ZFl/RODqPiIgfNNSamkpTj5x8AjBTkR/y1DNVIQiTGnmWqjHcn3o08ZW3q/LgkI4g9G9g6UirmmQFvuOZw==}
|
||||
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.156.0':
|
||||
resolution: {integrity: sha512-dcpx5Y1x2v/cs7U/q3SZMvmxfyXjVvqC86jMuw2ZZUbHDd7W2cW7uSMQfg3GLVaE68Su3H9xd/Pc4v6QNyeSRg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
@@ -1699,9 +1703,6 @@ 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-resolver/binding-android-arm-eabi@11.24.2':
|
||||
resolution: {integrity: sha512-y09e0L0SRI2OA2tUIrjBgoV3eH5hvUKXNkJqXmNo5V2WxIjyC7I7aJfRLMEVpA8yi95f90gFDvO0VMgrDw+vwA==}
|
||||
cpu: [arm]
|
||||
@@ -2004,9 +2005,6 @@ packages:
|
||||
rollup:
|
||||
optional: true
|
||||
|
||||
'@standard-schema/spec@1.1.0':
|
||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
||||
|
||||
'@svgr/babel-plugin-add-jsx-attribute@8.0.0':
|
||||
resolution: {integrity: sha512-b9MIk7yhdS1pMCZM8VeNfUlSKVRhsHZNMl5O9SfaX0l0t5wjdgu4IDzGB8bpnGBBOjGST3rRFVsaaEtI4W6f7g==}
|
||||
engines: {node: '>=14'}
|
||||
@@ -2285,8 +2283,8 @@ packages:
|
||||
peerDependencies:
|
||||
'@types/react': '*'
|
||||
|
||||
'@types/react@19.3.3':
|
||||
resolution: {integrity: sha512-K8uWpJc4teiuOPdiP1umjeA9rGMgVPiXuoL66fcS1QlwBT1WMqY8PORmub9FadopIs+RCW6siYEs7Lpq+vDlog==}
|
||||
'@types/react@19.3.0':
|
||||
resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}
|
||||
|
||||
'@types/trusted-types@2.0.7':
|
||||
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
||||
@@ -2663,6 +2661,10 @@ packages:
|
||||
resolution: {integrity: sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==}
|
||||
engines: {node: '>= 20.19.0'}
|
||||
|
||||
chownr@3.0.0:
|
||||
resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
cidr-block@2.3.0:
|
||||
resolution: {integrity: sha512-U5NE6QJKNOhIsVrI6sicbwGtEmEORbrz9B5Mbl+Mi05sz1Ic4egoLGV4DkJp56VWva61WxOf+vzIxTKEmRazqg==}
|
||||
engines: {node: '>=16'}
|
||||
@@ -3104,9 +3106,9 @@ packages:
|
||||
resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}
|
||||
engines: {node: '>= 6'}
|
||||
|
||||
formatly@0.12.3:
|
||||
resolution: {integrity: sha512-jGtjZLVw6OXvfwqxrxYBc+x+CxmOcMT/KjZagmkrYCQTEtQxJPablRqZPFSNq75drNsHsadjb1djIsE9KE705w==}
|
||||
engines: {node: ^20.12.0 || >=22}
|
||||
formatly@0.11.4:
|
||||
resolution: {integrity: sha512-TeCC10lP8KCgoX+Fe5lryILIT0/Dy+nP0OSVnsuB5CwXoLuOdqxCYlPFF1inR8S/zTy1ec7TjhS2TeRKWzzImA==}
|
||||
engines: {node: '>=18.14.0'}
|
||||
hasBin: true
|
||||
|
||||
foxact@0.3.12:
|
||||
@@ -3356,8 +3358,8 @@ packages:
|
||||
keyv@5.6.0:
|
||||
resolution: {integrity: sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==}
|
||||
|
||||
knip@6.49.0:
|
||||
resolution: {integrity: sha512-8Gf4R0xcJx1NdNKfr6gOGgSVBE1flB+KHPKPybDTKJ/hPtnswxyFE7Zpsk71kBvzAKReezakbe3DbQ0qAT4vzA==}
|
||||
knip@6.48.0:
|
||||
resolution: {integrity: sha512-v+Gfp6uiOeXaaj+Khk2Z7/fTTZYWLnDwxZapQUyy8WoQFLYXiUHXqRdFJTwRnrKNA1gPXTPi5NGTKKLXyImVrg==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
hasBin: true
|
||||
|
||||
@@ -3599,6 +3601,14 @@ packages:
|
||||
resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==}
|
||||
engines: {node: 18 || 20 || >=22}
|
||||
|
||||
minipass@7.1.3:
|
||||
resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}
|
||||
engines: {node: '>=16 || 14 >=14.17'}
|
||||
|
||||
minizlib@3.1.0:
|
||||
resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==}
|
||||
engines: {node: '>= 18'}
|
||||
|
||||
monaco-editor@0.58.0:
|
||||
resolution: {integrity: sha512-Lj5hlfT4zdM5GSG9VxTHslWnwibGBvO6d9Mq/+9zmb1CkTZnib4+uAZUKl1zg+tMHRgY2OGax6hHKZNBtldR1g==}
|
||||
|
||||
@@ -3667,8 +3677,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.156.0:
|
||||
resolution: {integrity: sha512-7JhjgOfZjrIFJH5TlHrpRua864Si5GvwrPr5+eIRCY2sszhKXo6pyhP0HQKOGTtfO4UowwZ72XTGba0+lZphOQ==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
|
||||
oxc-resolver@11.24.2:
|
||||
@@ -3696,15 +3706,6 @@ packages:
|
||||
resolution: {integrity: sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
parse-standard-args@0.3.0:
|
||||
resolution: {integrity: sha512-SH663jox6V7vxSZgroZJw9DgvSbcNHWOnjHjgvsPyj0/+OIbFraNJyDQbA+ATaAUIi0OGAmV27bIGUgcAEM41g==}
|
||||
engines: {node: '>=18.7.0'}
|
||||
peerDependencies:
|
||||
'@clack/prompts': '>=0.11'
|
||||
peerDependenciesMeta:
|
||||
'@clack/prompts':
|
||||
optional: true
|
||||
|
||||
parse5@7.3.0:
|
||||
resolution: {integrity: sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==}
|
||||
|
||||
@@ -4023,9 +4024,9 @@ packages:
|
||||
systemjs@6.15.1:
|
||||
resolution: {integrity: sha512-Nk8c4lXvMB98MtbmjX7JwJRgJOL8fluecYCfCeYBznwmpOs8Bf15hLM6z4z71EDAhQVrQrI+wt1aLWSXZq+hXA==}
|
||||
|
||||
tar@8.0.2:
|
||||
resolution: {integrity: sha512-1keL/dBVXwzliTinVjILeV/qZ2K3NNVFpg4JM1h3REOUJFamSLZmzVbCJXS6mF91//NwSaCbQ0gqmNwzE+ExCA==}
|
||||
engines: {node: '>=22'}
|
||||
tar@7.5.22:
|
||||
resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f:
|
||||
resolution: {gitHosted: true, integrity: sha512-4nRJ9eBOdd+mT9KaqEhUNya8bh/zaHHAJMBRgFR62KxSZ0S77mcjkB6Bz2xmHqPdYrhbi58aD6UcybEp4a6UyA==, tarball: https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f}
|
||||
@@ -4056,11 +4057,11 @@ packages:
|
||||
resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}
|
||||
engines: {node: '>=12.0.0'}
|
||||
|
||||
tldts-core@7.6.2:
|
||||
resolution: {integrity: sha512-/ZG+gignPzfgtpWNnbS7AKcU1ptt9jDqhIlr7vHOaw/Psz6HjXyB2CeFS3RrUGYwER/Q4F6IS8+9rZuYfRUz+Q==}
|
||||
tldts-core@7.5.5:
|
||||
resolution: {integrity: sha512-rEJz/8cJFY/bdF354gl14yxavbrIbvM+FcbkYVQ6CSCMQTJdUFUIm39TTWSiGPvcpQh7/F6qHrD3SkwwdgtDCw==}
|
||||
|
||||
tldts@7.6.2:
|
||||
resolution: {integrity: sha512-IylRLICacWmPVf5tQIOvKkZzf2Vp8qJT3bAZox+3bWXj5P/pn45PC1a9l86loP7D/ywbSt/h/NnyIoR0fg4utA==}
|
||||
tldts@7.5.5:
|
||||
resolution: {integrity: sha512-Hy6IImaWALzJOgCIss4gIFi4G0M9lqk95pFKCUVxQPZw+biZ1Pv6f28JpYgahpJB+BufA0HYsIU/aP/WIx3KRg==}
|
||||
hasBin: true
|
||||
|
||||
trim-lines@3.0.1:
|
||||
@@ -4112,8 +4113,8 @@ packages:
|
||||
engines: {node: '>=14.17'}
|
||||
hasBin: true
|
||||
|
||||
unbash@6.0.5:
|
||||
resolution: {integrity: sha512-5P8o+nYRueKpHxmemofYqZRZCSWAi+Tqy31MQS8l/sT54Z+Axn55N9CnWPo19BxxJD4wYYf6RqlcURhWkrFXew==}
|
||||
unbash@6.0.4:
|
||||
resolution: {integrity: sha512-t3OptUArewg9OpYGDskTSlxhyLDahfmZ4d36hE44Efb1y3HRLLpzsVqwH+AwBVymP4t7pP71xN+nnduudn2awA==}
|
||||
engines: {node: '>=14'}
|
||||
|
||||
undici-types@8.9.0:
|
||||
@@ -4319,6 +4320,10 @@ packages:
|
||||
yallist@3.1.1:
|
||||
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
|
||||
|
||||
yallist@5.0.0:
|
||||
resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==}
|
||||
engines: {node: '>=18'}
|
||||
|
||||
yaml@1.10.3:
|
||||
resolution: {integrity: sha512-vIYeF1u3CjlhAFekPPAk2h/Kv4T3mAkMox5OymRiJQB0spDP10LHvt+K7G9Ny6NuuMAb25/6n1qyUjAcGNf/AA==}
|
||||
engines: {node: '>= 6'}
|
||||
@@ -5196,7 +5201,7 @@ snapshots:
|
||||
|
||||
'@emotion/memoize@0.9.0': {}
|
||||
|
||||
'@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)':
|
||||
'@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@emotion/babel-plugin': 11.13.5(supports-color@7.2.0)
|
||||
@@ -5208,7 +5213,7 @@ snapshots:
|
||||
hoist-non-react-statics: 3.3.2
|
||||
react: 19.3.1
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -5222,18 +5227,18 @@ snapshots:
|
||||
|
||||
'@emotion/sheet@1.4.0': {}
|
||||
|
||||
'@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)':
|
||||
'@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@emotion/babel-plugin': 11.13.5(supports-color@7.2.0)
|
||||
'@emotion/is-prop-valid': 1.4.0
|
||||
'@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/serialize': 1.3.3
|
||||
'@emotion/use-insertion-effect-with-fallbacks': 1.2.0(react@19.3.1)
|
||||
'@emotion/utils': 1.4.2
|
||||
react: 19.3.1
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -5463,6 +5468,10 @@ snapshots:
|
||||
|
||||
'@humanwhocodes/retry@0.4.3': {}
|
||||
|
||||
'@isaacs/fs-minipass@4.0.1':
|
||||
dependencies:
|
||||
minipass: 7.1.3
|
||||
|
||||
'@jridgewell/gen-mapping@0.3.13':
|
||||
dependencies:
|
||||
'@jridgewell/sourcemap-codec': 1.6.0
|
||||
@@ -5510,23 +5519,23 @@ snapshots:
|
||||
|
||||
'@mui/core-downloads-tracker@9.4.0': {}
|
||||
|
||||
'@mui/icons-material@9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.3)(react@19.3.1)':
|
||||
'@mui/icons-material@9.4.0(@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1))(@types/react@19.3.0)(react@19.3.1)':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@mui/material': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
'@mui/material': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
react: 19.3.1
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
|
||||
'@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
|
||||
'@mui/material@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@mui/core-downloads-tracker': 9.4.0
|
||||
'@mui/system': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)
|
||||
'@mui/types': 9.4.0(@types/react@19.3.3)
|
||||
'@mui/utils': 9.4.0(@types/react@19.3.3)(react@19.3.1)
|
||||
'@mui/system': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)
|
||||
'@mui/types': 9.4.0(@types/react@19.3.0)
|
||||
'@mui/utils': 9.4.0(@types/react@19.3.0)(react@19.3.1)
|
||||
'@popperjs/core': 2.11.8
|
||||
'@types/react-transition-group': 4.4.12(@types/react@19.3.3)
|
||||
'@types/react-transition-group': 4.4.12(@types/react@19.3.0)
|
||||
clsx: 2.1.1
|
||||
csstype: 3.2.3
|
||||
prop-types: 15.8.1
|
||||
@@ -5535,20 +5544,20 @@ snapshots:
|
||||
react-is: 19.3.0
|
||||
react-transition-group: 4.4.5(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
|
||||
optionalDependencies:
|
||||
'@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@types/react': 19.3.3
|
||||
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@types/react': 19.3.0
|
||||
|
||||
'@mui/private-theming@9.4.0(@types/react@19.3.3)(react@19.3.1)':
|
||||
'@mui/private-theming@9.4.0(@types/react@19.3.0)(react@19.3.1)':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@mui/utils': 9.4.0(@types/react@19.3.3)(react@19.3.1)
|
||||
'@mui/utils': 9.4.0(@types/react@19.3.0)(react@19.3.1)
|
||||
prop-types: 15.8.1
|
||||
react: 19.3.1
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
|
||||
'@mui/styled-engine@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)':
|
||||
'@mui/styled-engine@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@emotion/cache': 11.14.0
|
||||
@@ -5558,42 +5567,42 @@ snapshots:
|
||||
prop-types: 15.8.1
|
||||
react: 19.3.1
|
||||
optionalDependencies:
|
||||
'@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
|
||||
'@mui/system@9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)':
|
||||
'@mui/system@9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@mui/private-theming': 9.4.0(@types/react@19.3.3)(react@19.3.1)
|
||||
'@mui/styled-engine': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)
|
||||
'@mui/types': 9.4.0(@types/react@19.3.3)
|
||||
'@mui/utils': 9.4.0(@types/react@19.3.3)(react@19.3.1)
|
||||
'@mui/private-theming': 9.4.0(@types/react@19.3.0)(react@19.3.1)
|
||||
'@mui/styled-engine': 9.4.0(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@emotion/styled@11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(react@19.3.1)
|
||||
'@mui/types': 9.4.0(@types/react@19.3.0)
|
||||
'@mui/utils': 9.4.0(@types/react@19.3.0)(react@19.3.1)
|
||||
clsx: 2.1.1
|
||||
csstype: 3.2.3
|
||||
prop-types: 15.8.1
|
||||
react: 19.3.1
|
||||
optionalDependencies:
|
||||
'@emotion/react': 11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@types/react': 19.3.3
|
||||
'@emotion/react': 11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@emotion/styled': 11.14.1(@emotion/react@11.14.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0))(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0)
|
||||
'@types/react': 19.3.0
|
||||
|
||||
'@mui/types@9.4.0(@types/react@19.3.3)':
|
||||
'@mui/types@9.4.0(@types/react@19.3.0)':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
|
||||
'@mui/utils@9.4.0(@types/react@19.3.3)(react@19.3.1)':
|
||||
'@mui/utils@9.4.0(@types/react@19.3.0)(react@19.3.1)':
|
||||
dependencies:
|
||||
'@babel/runtime': 7.29.7
|
||||
'@mui/types': 9.4.0(@types/react@19.3.3)
|
||||
'@mui/types': 9.4.0(@types/react@19.3.0)
|
||||
'@types/prop-types': 15.7.15
|
||||
clsx: 2.1.1
|
||||
prop-types: 15.8.1
|
||||
react: 19.3.1
|
||||
react-is: 19.3.0
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
|
||||
'@napi-rs/wasm-runtime@1.2.4(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
|
||||
dependencies:
|
||||
@@ -5667,67 +5676,65 @@ snapshots:
|
||||
dependencies:
|
||||
'@octokit/openapi-types': 29.0.1
|
||||
|
||||
'@oxc-parser/binding-android-arm-eabi@0.160.0':
|
||||
'@oxc-parser/binding-android-arm-eabi@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-android-arm64@0.160.0':
|
||||
'@oxc-parser/binding-android-arm64@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-darwin-arm64@0.160.0':
|
||||
'@oxc-parser/binding-darwin-arm64@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-darwin-x64@0.160.0':
|
||||
'@oxc-parser/binding-darwin-x64@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-freebsd-x64@0.160.0':
|
||||
'@oxc-parser/binding-freebsd-x64@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-arm-gnueabihf@0.160.0':
|
||||
'@oxc-parser/binding-linux-arm-gnueabihf@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-arm-musleabihf@0.160.0':
|
||||
'@oxc-parser/binding-linux-arm-musleabihf@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-arm64-gnu@0.160.0':
|
||||
'@oxc-parser/binding-linux-arm64-gnu@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-arm64-musl@0.160.0':
|
||||
'@oxc-parser/binding-linux-arm64-musl@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-ppc64-gnu@0.160.0':
|
||||
'@oxc-parser/binding-linux-ppc64-gnu@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-riscv64-gnu@0.160.0':
|
||||
'@oxc-parser/binding-linux-riscv64-gnu@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-riscv64-musl@0.160.0':
|
||||
'@oxc-parser/binding-linux-riscv64-musl@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-s390x-gnu@0.160.0':
|
||||
'@oxc-parser/binding-linux-s390x-gnu@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-x64-gnu@0.160.0':
|
||||
'@oxc-parser/binding-linux-x64-gnu@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-linux-x64-musl@0.160.0':
|
||||
'@oxc-parser/binding-linux-x64-musl@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-openharmony-arm64@0.160.0':
|
||||
'@oxc-parser/binding-openharmony-arm64@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-win32-arm64-msvc@0.160.0':
|
||||
'@oxc-parser/binding-win32-arm64-msvc@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-win32-ia32-msvc@0.160.0':
|
||||
'@oxc-parser/binding-win32-ia32-msvc@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-parser/binding-win32-x64-msvc@0.160.0':
|
||||
'@oxc-parser/binding-win32-x64-msvc@0.156.0':
|
||||
optional: true
|
||||
|
||||
'@oxc-project/types@0.156.0': {}
|
||||
|
||||
'@oxc-project/types@0.160.0': {}
|
||||
|
||||
'@oxc-resolver/binding-android-arm-eabi@11.24.2':
|
||||
optional: true
|
||||
|
||||
@@ -5905,8 +5912,6 @@ snapshots:
|
||||
estree-walker: 2.0.2
|
||||
picomatch: 4.0.7
|
||||
|
||||
'@standard-schema/spec@1.1.0': {}
|
||||
|
||||
'@svgr/babel-plugin-add-jsx-attribute@8.0.0(@babel/core@7.29.7(supports-color@7.2.0))':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.7(supports-color@7.2.0)
|
||||
@@ -6129,15 +6134,15 @@ snapshots:
|
||||
|
||||
'@types/prop-types@15.7.15': {}
|
||||
|
||||
'@types/react-dom@19.3.0(@types/react@19.3.3)':
|
||||
'@types/react-dom@19.3.0(@types/react@19.3.0)':
|
||||
dependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
|
||||
'@types/react-transition-group@4.4.12(@types/react@19.3.3)':
|
||||
'@types/react-transition-group@4.4.12(@types/react@19.3.0)':
|
||||
dependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
|
||||
'@types/react@19.3.3':
|
||||
'@types/react@19.3.0':
|
||||
dependencies:
|
||||
csstype: 3.2.3
|
||||
|
||||
@@ -6496,6 +6501,8 @@ snapshots:
|
||||
dependencies:
|
||||
readdirp: 5.1.1
|
||||
|
||||
chownr@3.0.0: {}
|
||||
|
||||
cidr-block@2.3.0: {}
|
||||
|
||||
cli-color@2.0.4:
|
||||
@@ -7038,15 +7045,10 @@ snapshots:
|
||||
hasown: 2.0.4
|
||||
mime-types: 2.1.35
|
||||
|
||||
formatly@0.12.3:
|
||||
formatly@0.11.4:
|
||||
dependencies:
|
||||
fd-package-json: 2.0.0
|
||||
package-manager-detector: 1.8.0
|
||||
parse-standard-args: 0.3.0
|
||||
tinyexec: 1.3.1
|
||||
zod: 4.6.5
|
||||
transitivePeerDependencies:
|
||||
- '@clack/prompts'
|
||||
|
||||
foxact@0.3.12(react-dom@19.3.1(react@19.3.1))(react@19.3.1):
|
||||
dependencies:
|
||||
@@ -7317,21 +7319,19 @@ snapshots:
|
||||
dependencies:
|
||||
'@keyv/serialize': 1.1.1
|
||||
|
||||
knip@6.49.0:
|
||||
knip@6.48.0:
|
||||
dependencies:
|
||||
formatly: 0.12.3
|
||||
formatly: 0.11.4
|
||||
get-tsconfig: 4.14.3
|
||||
jiti: 2.7.0
|
||||
oxc-parser: 0.160.0
|
||||
oxc-parser: 0.156.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
|
||||
unbash: 6.0.4
|
||||
yaml: 2.9.1
|
||||
transitivePeerDependencies:
|
||||
- '@clack/prompts'
|
||||
|
||||
levn@0.4.1:
|
||||
dependencies:
|
||||
@@ -7680,6 +7680,12 @@ snapshots:
|
||||
dependencies:
|
||||
brace-expansion: 5.0.12
|
||||
|
||||
minipass@7.1.3: {}
|
||||
|
||||
minizlib@3.1.0:
|
||||
dependencies:
|
||||
minipass: 7.1.3
|
||||
|
||||
monaco-editor@0.58.0:
|
||||
dependencies:
|
||||
'@vscode/diff': 0.0.2-145
|
||||
@@ -7754,29 +7760,29 @@ snapshots:
|
||||
type-check: 0.4.0
|
||||
word-wrap: 1.2.5
|
||||
|
||||
oxc-parser@0.160.0:
|
||||
oxc-parser@0.156.0:
|
||||
dependencies:
|
||||
'@oxc-project/types': 0.160.0
|
||||
'@oxc-project/types': 0.156.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.156.0
|
||||
'@oxc-parser/binding-android-arm64': 0.156.0
|
||||
'@oxc-parser/binding-darwin-arm64': 0.156.0
|
||||
'@oxc-parser/binding-darwin-x64': 0.156.0
|
||||
'@oxc-parser/binding-freebsd-x64': 0.156.0
|
||||
'@oxc-parser/binding-linux-arm-gnueabihf': 0.156.0
|
||||
'@oxc-parser/binding-linux-arm-musleabihf': 0.156.0
|
||||
'@oxc-parser/binding-linux-arm64-gnu': 0.156.0
|
||||
'@oxc-parser/binding-linux-arm64-musl': 0.156.0
|
||||
'@oxc-parser/binding-linux-ppc64-gnu': 0.156.0
|
||||
'@oxc-parser/binding-linux-riscv64-gnu': 0.156.0
|
||||
'@oxc-parser/binding-linux-riscv64-musl': 0.156.0
|
||||
'@oxc-parser/binding-linux-s390x-gnu': 0.156.0
|
||||
'@oxc-parser/binding-linux-x64-gnu': 0.156.0
|
||||
'@oxc-parser/binding-linux-x64-musl': 0.156.0
|
||||
'@oxc-parser/binding-openharmony-arm64': 0.156.0
|
||||
'@oxc-parser/binding-win32-arm64-msvc': 0.156.0
|
||||
'@oxc-parser/binding-win32-ia32-msvc': 0.156.0
|
||||
'@oxc-parser/binding-win32-x64-msvc': 0.156.0
|
||||
|
||||
oxc-resolver@11.24.2:
|
||||
optionalDependencies:
|
||||
@@ -7831,10 +7837,6 @@ snapshots:
|
||||
json-parse-even-better-errors: 2.3.1
|
||||
lines-and-columns: 1.2.4
|
||||
|
||||
parse-standard-args@0.3.0:
|
||||
dependencies:
|
||||
'@standard-schema/spec': 1.1.0
|
||||
|
||||
parse5@7.3.0:
|
||||
dependencies:
|
||||
entities: 6.0.1
|
||||
@@ -7892,11 +7894,11 @@ snapshots:
|
||||
react: 19.3.1
|
||||
scheduler: 0.28.0
|
||||
|
||||
react-error-boundary@6.1.6(@types/react@19.3.3)(react@19.3.1):
|
||||
react-error-boundary@6.1.6(@types/react@19.3.0)(react@19.3.1):
|
||||
dependencies:
|
||||
react: 19.3.1
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
|
||||
react-fast-compare@3.2.2: {}
|
||||
|
||||
@@ -7904,24 +7906,24 @@ snapshots:
|
||||
dependencies:
|
||||
react: 19.3.1
|
||||
|
||||
react-i18next@18.0.3(@types/react@19.3.3)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3):
|
||||
react-i18next@18.0.3(@types/react@19.3.0)(i18next@27.0.1(typescript@6.0.3))(react@19.3.1)(typescript@6.0.3):
|
||||
dependencies:
|
||||
html-parse-stringify: 4.0.1
|
||||
i18next: 27.0.1(typescript@6.0.3)
|
||||
react: 19.3.1
|
||||
optionalDependencies:
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
typescript: 6.0.3
|
||||
|
||||
react-is@16.13.1: {}
|
||||
|
||||
react-is@19.3.0: {}
|
||||
|
||||
react-markdown@10.1.0(@types/react@19.3.3)(react@19.3.1)(supports-color@7.2.0):
|
||||
react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.1)(supports-color@7.2.0):
|
||||
dependencies:
|
||||
'@types/hast': 3.0.5
|
||||
'@types/mdast': 4.0.4
|
||||
'@types/react': 19.3.3
|
||||
'@types/react': 19.3.0
|
||||
devlop: 1.1.0
|
||||
hast-util-to-jsx-runtime: 2.3.6(supports-color@7.2.0)
|
||||
html-url-attributes: 3.0.1
|
||||
@@ -8133,7 +8135,13 @@ snapshots:
|
||||
|
||||
systemjs@6.15.1: {}
|
||||
|
||||
tar@8.0.2: {}
|
||||
tar@7.5.22:
|
||||
dependencies:
|
||||
'@isaacs/fs-minipass': 4.0.1
|
||||
chownr: 3.0.0
|
||||
minipass: 7.1.3
|
||||
minizlib: 3.1.0
|
||||
yallist: 5.0.0
|
||||
|
||||
tauri-plugin-mihomo-api@https://codeload.github.com/clash-verge-rev/tauri-plugin-mihomo/tar.gz/7e4fa8642cf6c394ed88b5a969420d8eab60087f:
|
||||
dependencies:
|
||||
@@ -8162,11 +8170,11 @@ snapshots:
|
||||
fdir: 6.5.0(picomatch@4.0.7)
|
||||
picomatch: 4.0.7
|
||||
|
||||
tldts-core@7.6.2: {}
|
||||
tldts-core@7.5.5: {}
|
||||
|
||||
tldts@7.6.2:
|
||||
tldts@7.5.5:
|
||||
dependencies:
|
||||
tldts-core: 7.6.2
|
||||
tldts-core: 7.5.5
|
||||
|
||||
trim-lines@3.0.1: {}
|
||||
|
||||
@@ -8213,7 +8221,7 @@ snapshots:
|
||||
|
||||
typescript@6.0.3: {}
|
||||
|
||||
unbash@6.0.5: {}
|
||||
unbash@6.0.4: {}
|
||||
|
||||
undici-types@8.9.0: {}
|
||||
|
||||
@@ -8401,6 +8409,8 @@ snapshots:
|
||||
|
||||
yallist@3.1.1: {}
|
||||
|
||||
yallist@5.0.0: {}
|
||||
|
||||
yaml@1.10.3: {}
|
||||
|
||||
yaml@2.9.1: {}
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
[toolchain]
|
||||
channel = "1.100.1"
|
||||
channel = "1.100.0"
|
||||
components = ["rustfmt", "clippy"]
|
||||
|
||||
+21
-23
@@ -1,26 +1,24 @@
|
||||
# Backend Architecture Guardrails
|
||||
|
||||
Follow [Workspace Crate Architecture](../crates/AGENTS.md) when changing
|
||||
backend capability boundaries, reusable orchestration, or background task
|
||||
ownership.
|
||||
These rules supplement the repository's root `AGENTS.md`.
|
||||
|
||||
- **Tauri adapter.** Commands validate transport input, delegate to application
|
||||
use cases, and map results and errors to IPC. Tauri wires dependencies and
|
||||
owns desktop lifecycle, window and tray integration, and event delivery.
|
||||
Keep domain validation and reusable orchestration independent of command
|
||||
handlers and framework state.
|
||||
- **Configuration and effects.** `config` owns source configuration, drafts, and
|
||||
persistence coordination. Persistence adapters perform storage and recovery.
|
||||
The effects layer classifies every Verge patch field, including
|
||||
fields without effects and platform-specific fields, and reconciles requested
|
||||
state in dependency order. Publish rollbackable state after persistence and
|
||||
commit. On failure, preserve already applied runtime effects, independently
|
||||
committed state, their notifications, and the error.
|
||||
- **Wire contract.** Use typed notifications and preserve event names, status
|
||||
values, and payload compatibility with frontend consumers.
|
||||
- **Lock order.** Acquire configuration-write, configuration-update, Core
|
||||
lifecycle, and DNS ownership in that order when needed. Preserve independent
|
||||
transaction boundaries and release synchronous guards before suspension.
|
||||
- **Retries.** Reuse the backend retry policy and preserve attempts, delays, and
|
||||
terminal errors. Keep monitor lifetime, condition waits, and candidate fallback
|
||||
under their own contracts.
|
||||
- **Configuration ownership.** `config` owns source configuration, drafts and
|
||||
persistence. The effects layer owns patch orchestration. Rollbackable
|
||||
transactions publish state after persistence and commit; already applied
|
||||
runtime and independently committed state remain authoritative even when a
|
||||
later step fails. Preserve that state, its notifications and the error.
|
||||
- **Effect ownership.** The declarative registry classifies every Verge patch field,
|
||||
including fields without effects and platform-specific fields. Effects
|
||||
reconcile toward the requested state with explicit dependencies and ordering.
|
||||
Configuration rollback does not imply reversal of OS or lifecycle effects.
|
||||
- **Shared wire contract.** Notifications are typed. Event names, status values
|
||||
and payload shapes stay compatible with frontend producers and consumers.
|
||||
- **Synchronization ownership.** Configuration-write serialization precedes
|
||||
configuration-update ownership, which precedes Core lifecycle ownership.
|
||||
When both are held, the lifecycle lock precedes the DNS lock. Independent
|
||||
transactions retain their ownership boundaries; asynchronous work does not
|
||||
hold synchronous data guards across suspension.
|
||||
- **Retry ownership.** Bounded retries share backend policy while preserving
|
||||
attempts, delays and terminal errors. Background monitors own their lifetime
|
||||
and cancellation separately; waiting for a condition or traversing distinct
|
||||
candidates is not a retry policy.
|
||||
|
||||
+8
-18
@@ -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,20 +30,11 @@ identifier = "io.github.clash-verge-rev.clash-verge-rev"
|
||||
tauri-build = { version = "2.7.6", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tempfile = { workspace = true }
|
||||
clash-verge-draft = { workspace = true }
|
||||
clash-verge-task = { workspace = true }
|
||||
clash-verge-media-unlock = { workspace = true }
|
||||
clash-verge-logging = { workspace = true }
|
||||
clash-verge-i18n = { workspace = true }
|
||||
clash-verge-limiter = { workspace = true }
|
||||
clash-verge-subscription = { workspace = true }
|
||||
clash-verge-runtime-bundle = { workspace = true }
|
||||
clash-verge-config-render = { workspace = true }
|
||||
clash-verge-profile-script = { workspace = true }
|
||||
clash-verge-proxy-view = { workspace = true }
|
||||
clash-verge-profile = { workspace = true }
|
||||
clash-verge-backup-archive = { workspace = true }
|
||||
tauri-plugin-clash-verge-sysinfo = { workspace = true }
|
||||
tauri-plugin-clipboard-manager = { workspace = true }
|
||||
tauri = { workspace = true, features = [
|
||||
@@ -71,6 +61,7 @@ dirs = "7.0.0"
|
||||
dunce = "1.0.5"
|
||||
nanoid = "0.5"
|
||||
chrono = { workspace = true }
|
||||
boa_engine = "0.22.0"
|
||||
http-body-util = "0.1.5"
|
||||
percent-encoding = "2.3.2"
|
||||
reqwest = { workspace = true }
|
||||
@@ -84,13 +75,14 @@ tauri-plugin-dialog = "2.8.4"
|
||||
tauri-plugin-fs = "2.7.1"
|
||||
tauri-plugin-deep-link = "2.6.3"
|
||||
tauri-plugin-window-state = "2.5.0"
|
||||
zip = "9.8.2"
|
||||
flate2 = "1.1.11"
|
||||
reqwest_dav = "0.4.0"
|
||||
aes-gcm = { version = "0.11.1" }
|
||||
base64 = "0.23.1"
|
||||
sha2 = { workspace = true }
|
||||
sha2 = "0.11.2"
|
||||
getrandom = "0.4.3"
|
||||
futures = { workspace = true }
|
||||
futures = "0.3.34"
|
||||
gethostname = "1.1.0"
|
||||
tauri-plugin-notification = "2.8.1"
|
||||
backon = { version = "1.6.0", features = ["tokio-sleep"] }
|
||||
@@ -99,7 +91,9 @@ tracing = { workspace = true }
|
||||
tauri-plugin-devtools = { version = "2.2.3", optional = true }
|
||||
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", rev = "7e4fa8642cf6c394ed88b5a969420d8eab60087f" }
|
||||
async-trait = "0.1.92"
|
||||
clash_verge_service_ipc = { workspace = true, features = ["client"] }
|
||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", features = [
|
||||
"client",
|
||||
] }
|
||||
arc-swap = "1.9.5"
|
||||
tokio-rustls = "0.26.6"
|
||||
rustls = { version = "0.23.46", features = ["ring"] }
|
||||
@@ -107,13 +101,10 @@ webpki-roots = "1.0.12"
|
||||
dark-light = "3.0.0"
|
||||
bytes = "1.12.2"
|
||||
tokio-util = { version = "0.7.20", features = ["time"] }
|
||||
specta = { workspace = true, features = ["derive", "function", "serde_json"] }
|
||||
specta = { version = "=2.0.0-rc.26", 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"
|
||||
|
||||
@@ -146,7 +137,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"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
#![deny(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
|
||||
&& std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc")
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
#![deny(clippy::expect_used, clippy::unwrap_used)]
|
||||
|
||||
// Dev-only target: Tauri ships everything under src/bin/ to /usr/bin in deb/rpm
|
||||
// bundles (PR #8131), so this generator must stay an example, never a bin.
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
@@ -66,7 +66,8 @@ pub async fn install_update(
|
||||
on_event: Channel<DownloadEvent>,
|
||||
) -> CmdResult<InstallUpdateOutcome> {
|
||||
SilentUpdater::global()
|
||||
.install_update(&app_handle, &version, |event| {
|
||||
.ok_or("silent updater is not running")?
|
||||
.install_update(&app_handle, &version, move |event| {
|
||||
let _ = on_event.send(event);
|
||||
})
|
||||
.await
|
||||
@@ -76,7 +77,19 @@ pub async fn install_update(
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn cancel_update_download() {
|
||||
SilentUpdater::global().cancel_download();
|
||||
if let Some(updater) = SilentUpdater::global() {
|
||||
updater.cancel_download();
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn get_staged_update() -> CmdResult<Option<std::string::String>> {
|
||||
SilentUpdater::global()
|
||||
.ok_or("silent updater is not running")?
|
||||
.staged_version()
|
||||
.await
|
||||
.stringify_err()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
|
||||
use crate::core::notify::NoticeStatus;
|
||||
use crate::feat;
|
||||
use crate::utils::dirs;
|
||||
use crate::utils::{dirs, yaml_emitter};
|
||||
use crate::{
|
||||
cmd::StringifyErr as _,
|
||||
config::{ClashInfo, Config, mihomo_yaml, profiles::profiles_save_file_safe},
|
||||
config::{ClashInfo, Config, profiles::profiles_save_file_safe},
|
||||
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 = yaml_emitter::to_mihomo_config_string(&dns_config.0).stringify_err()?;
|
||||
fs::write(&dns_path, yaml_str).await.stringify_err()?;
|
||||
logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
|
||||
|
||||
|
||||
@@ -5,13 +5,12 @@ use crate::core::notify::NoticeStatus;
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use crate::{
|
||||
config::{
|
||||
Config, IProfiles, PrfItem, PrfOption, build_remote_profile,
|
||||
Config, IProfiles, PrfItem, PrfOption,
|
||||
profiles::{
|
||||
PROFILE_WRITE_LOCK, cleanup_profile_files, profiles_append_item_safe,
|
||||
profiles_append_item_with_filedata_safe, profiles_patch_item_safe, profiles_reorder_safe,
|
||||
profiles_save_file_safe, save_profiles,
|
||||
PROFILE_WRITE_LOCK, profiles_append_item_with_filedata_safe, profiles_patch_item_safe,
|
||||
profiles_reorder_safe, profiles_save_file_safe,
|
||||
},
|
||||
read_profile_item_file,
|
||||
profiles_append_item_safe,
|
||||
},
|
||||
core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome},
|
||||
feat,
|
||||
@@ -39,7 +38,6 @@ fn profile_import_error(err: &anyhow::Error) -> std::string::String {
|
||||
#[specta::specta]
|
||||
pub async fn get_profiles() -> CmdResult<SharedDraft<IProfiles>> {
|
||||
let draft = Config::profiles().await;
|
||||
let _guard = crate::config::profile_storage::read().await.stringify_err()?;
|
||||
let data = draft.data_arc();
|
||||
Ok(data)
|
||||
}
|
||||
@@ -73,7 +71,7 @@ pub async fn enhance_profiles() -> CmdResult<ValidationOutcome> {
|
||||
#[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))]
|
||||
#[specta::specta]
|
||||
pub async fn import_profile(url: std::string::String, option: Option<PrfOption>) -> CmdResult {
|
||||
let item = &mut match build_remote_profile(&url, None, None, option.as_ref()).await {
|
||||
let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await {
|
||||
Ok(it) => it,
|
||||
Err(e) => {
|
||||
logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}");
|
||||
@@ -158,16 +156,12 @@ 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 {
|
||||
.with_data_modify(|mut candidate| async move {
|
||||
let original = candidate.clone();
|
||||
let plan = candidate.plan_delete_item(&index)?;
|
||||
let should_update = plan.deleting_current;
|
||||
let (should_update, plan) = candidate.plan_delete_item(&index)?;
|
||||
let guard = if should_update {
|
||||
match CoreManager::global()
|
||||
.update_config_forced_with_profiles(&candidate, &original)
|
||||
@@ -177,17 +171,15 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||
Err(outcome) => return Ok((original, Err(outcome))),
|
||||
}
|
||||
} else {
|
||||
save_profiles(&candidate).await?;
|
||||
candidate.save_file().await?;
|
||||
None
|
||||
};
|
||||
let current = candidate.current.clone();
|
||||
*slot = Some(crate::config::profile_storage::write().await?);
|
||||
cleanup_profile_files(plan.files).await;
|
||||
plan.cleanup().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) => {
|
||||
@@ -218,11 +210,16 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
|
||||
async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> {
|
||||
logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile);
|
||||
commit_current_profile(&Config::profiles().await, Some(prev_profile.clone()))
|
||||
let restore_profiles = IProfiles {
|
||||
current: Some(prev_profile.into()),
|
||||
items: None,
|
||||
};
|
||||
Config::profiles()
|
||||
.await
|
||||
.stringify_err()?;
|
||||
.edit_draft(|d| d.patch_config(&restore_profiles));
|
||||
Config::profiles().await.apply();
|
||||
crate::process::AsyncHandler::spawn(|| async move {
|
||||
if let Err(e) = profiles_save_file_safe().await {
|
||||
logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}");
|
||||
@@ -239,7 +236,10 @@ async fn commit_current_profile(profiles: &Draft<IProfiles>, current: Option<Str
|
||||
|
||||
profiles
|
||||
.with_data_modify(|mut committed| async move {
|
||||
committed.patch_current(Some(¤t));
|
||||
committed.patch_config(&IProfiles {
|
||||
current: Some(current),
|
||||
items: None,
|
||||
});
|
||||
Ok((committed, ()))
|
||||
})
|
||||
.await
|
||||
@@ -396,14 +396,17 @@ 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 profiles = IProfiles {
|
||||
current: profiles.current,
|
||||
items: None,
|
||||
};
|
||||
let target_profile = profiles.current.as_ref();
|
||||
|
||||
let previous_profile = Config::profiles().await.data_arc().current.clone();
|
||||
|
||||
Config::profiles().await.edit_draft(|d| {
|
||||
d.patch_current(target_profile);
|
||||
d.patch_config(&profiles);
|
||||
});
|
||||
|
||||
perform_config_update(target_profile, previous_profile.as_ref())
|
||||
@@ -464,7 +467,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
|
||||
@@ -490,18 +492,20 @@ 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 item = {
|
||||
let profiles = Config::profiles().await;
|
||||
let profiles_ref = profiles.latest_arc();
|
||||
profiles_ref
|
||||
.get_item(&index)
|
||||
.with_error_code("PROFILE_READ_FAILED")?
|
||||
.file
|
||||
.clone()
|
||||
PrfItem {
|
||||
file: profiles_ref
|
||||
.get_item(&index)
|
||||
.with_error_code("PROFILE_READ_FAILED")?
|
||||
.file
|
||||
.to_owned(),
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(file) = file.as_ref() {
|
||||
if let Some(file) = item.file.as_ref() {
|
||||
let path = dirs::app_profiles_dir()
|
||||
.with_error_code("PROFILE_READ_FAILED")?
|
||||
.join(file.as_str());
|
||||
@@ -517,9 +521,7 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult<std::str
|
||||
}
|
||||
}
|
||||
|
||||
let data = read_profile_item_file(file.as_deref())
|
||||
.await
|
||||
.with_error_code("PROFILE_READ_FAILED")?;
|
||||
let data = item.read_file().await.with_error_code("PROFILE_READ_FAILED")?;
|
||||
Ok(data.into())
|
||||
}
|
||||
|
||||
@@ -573,11 +575,16 @@ mod tests {
|
||||
current: Some("a".into()),
|
||||
items: Some(vec![profile("a"), profile("b")]),
|
||||
});
|
||||
profiles.edit_draft(|draft| draft.patch_current(Some(&"b".into())));
|
||||
profiles.edit_draft(|draft| {
|
||||
draft.patch_config(&IProfiles {
|
||||
current: Some("b".into()),
|
||||
items: None,
|
||||
});
|
||||
});
|
||||
profiles
|
||||
.with_data_modify(|mut committed| async move {
|
||||
committed.items.get_or_insert_with(Vec::new).push(profile("new"));
|
||||
Ok::<_, clash_verge_draft::DraftConflict>((committed, ()))
|
||||
Ok((committed, ()))
|
||||
})
|
||||
.await?;
|
||||
|
||||
|
||||
+92
-10
@@ -1,6 +1,14 @@
|
||||
use super::CmdResult;
|
||||
use crate::{cmd::StringifyErr as _, config::Config, core::handle::Handle};
|
||||
use clash_verge_proxy_view::ProxyViewV1;
|
||||
use crate::{
|
||||
cmd::StringifyErr as _,
|
||||
config::Config,
|
||||
core::{
|
||||
handle::Handle,
|
||||
proxy_view::{GroupScope, ProxyViewBuilder, ProxyViewInput, ProxyViewV1},
|
||||
},
|
||||
};
|
||||
use serde_yaml_ng::Mapping;
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
|
||||
/// Merges one selection pair into fresh backend state to avoid stale-list overwrites.
|
||||
#[tauri::command]
|
||||
@@ -19,16 +27,90 @@ pub async fn switch_proxy_node(group_name: String, proxy_name: String, unfix: bo
|
||||
.stringify_err()
|
||||
}
|
||||
|
||||
fn runtime_group_order(config: Option<&Mapping>) -> Vec<String> {
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
config
|
||||
.and_then(|config| config.get("proxy-groups"))
|
||||
.and_then(|groups| groups.as_sequence())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|group| group.get("name"))
|
||||
.filter_map(|name| name.as_str())
|
||||
.filter(|name| !name.is_empty() && *name != "GLOBAL")
|
||||
.filter(|name| seen.insert(*name))
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Mirrors Mihomo: `include-all`/`include-all-providers` replace `use` with every provider, sorted.
|
||||
fn runtime_group_scopes(config: Option<&Mapping>) -> BTreeMap<String, GroupScope> {
|
||||
let Some(config) = config else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
let mut all_providers = config
|
||||
.get("proxy-providers")
|
||||
.and_then(|providers| providers.as_mapping())
|
||||
.into_iter()
|
||||
.flat_map(|providers| providers.keys())
|
||||
.filter_map(|name| name.as_str())
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
all_providers.sort();
|
||||
let flag = |group: &Mapping, key: &str| group.get(key).and_then(|value| value.as_bool()) == Some(true);
|
||||
|
||||
config
|
||||
.get("proxy-groups")
|
||||
.and_then(|groups| groups.as_sequence())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|group| group.as_mapping())
|
||||
.filter_map(|group| {
|
||||
let name = group.get("name")?.as_str()?.to_owned();
|
||||
let providers = if flag(group, "include-all") || flag(group, "include-all-providers") {
|
||||
all_providers.clone()
|
||||
} else {
|
||||
group
|
||||
.get("use")
|
||||
.and_then(|providers| providers.as_sequence())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|provider| provider.as_str())
|
||||
.map(str::to_owned)
|
||||
.collect()
|
||||
};
|
||||
let exclude_types = group
|
||||
.get("exclude-type")
|
||||
.and_then(|types| types.as_str())
|
||||
.filter(|types| !types.is_empty())
|
||||
.map_or_default(|types| types.split('|').map(str::to_owned).collect());
|
||||
Some((
|
||||
name,
|
||||
GroupScope {
|
||||
providers,
|
||||
exclude_types,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn get_proxy_view() -> CmdResult<ProxyViewV1> {
|
||||
let runtime = Config::runtime().await.latest_arc();
|
||||
let runtime = Config::runtime().await;
|
||||
let latest_runtime = runtime.latest_arc();
|
||||
let runtime_group_order = runtime_group_order(latest_runtime.config.as_ref());
|
||||
let group_scopes = runtime_group_scopes(latest_runtime.config.as_ref());
|
||||
|
||||
let mihomo = Handle::mihomo();
|
||||
crate::feat::proxy_view::load_proxy_view(
|
||||
runtime.config.as_ref(),
|
||||
mihomo.get_proxies(),
|
||||
mihomo.get_proxy_providers(),
|
||||
)
|
||||
.await
|
||||
.stringify_err()
|
||||
let (proxies, providers) = tokio::join!(mihomo.get_proxies(), mihomo.get_proxy_providers(),);
|
||||
let proxies = proxies.stringify_err()?;
|
||||
|
||||
Ok(ProxyViewBuilder::build(ProxyViewInput {
|
||||
runtime_group_order,
|
||||
group_scopes,
|
||||
proxies,
|
||||
providers: providers.ok(),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -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, utils::yaml_emitter};
|
||||
use anyhow::{Context as _, anyhow};
|
||||
use std::collections::HashMap;
|
||||
use tristr::alias::String;
|
||||
@@ -28,7 +24,7 @@ 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| yaml_emitter::to_mihomo_config_string(config).context("failed to convert config to yaml"))
|
||||
.stringify_err()
|
||||
}
|
||||
|
||||
@@ -91,7 +87,7 @@ pub async fn get_runtime_proxy_chain_config(
|
||||
|
||||
config.insert("proxies".into(), proxies_chain);
|
||||
|
||||
mihomo_yaml::serialize_for_export(&config)
|
||||
yaml_emitter::to_mihomo_config_string(&config)
|
||||
.context("YAML generation failed")
|
||||
.stringify_err()
|
||||
} else {
|
||||
|
||||
@@ -2,8 +2,8 @@ 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},
|
||||
core::auto_backup::{self, AutoBackupTrigger},
|
||||
config::{Config, IProfiles, PrfItem},
|
||||
core::auto_backup::{AutoBackupManager, AutoBackupTrigger},
|
||||
core::{
|
||||
CoreManager, handle,
|
||||
validate::{CoreConfigValidator, ValidationOutcome},
|
||||
@@ -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;
|
||||
@@ -61,25 +58,25 @@ pub async fn save_profile_file(
|
||||
))
|
||||
})?;
|
||||
let original_content = if original_existed {
|
||||
read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()?
|
||||
PrfItem {
|
||||
file: Some(rel_path.clone()),
|
||||
..Default::default()
|
||||
}
|
||||
.read_file()
|
||||
.await
|
||||
.stringify_err()?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
// 保存新的配置文件
|
||||
fs::write(&file_path, &file_data).await.stringify_err()?;
|
||||
drop(profile_guard);
|
||||
|
||||
let original = OriginalProfileFile {
|
||||
content: &original_content,
|
||||
existed: original_existed,
|
||||
written: &file_data,
|
||||
};
|
||||
|
||||
let changes_applied = handle_saved_profile_file(
|
||||
&file_path_str,
|
||||
&file_path,
|
||||
&original,
|
||||
&original_content,
|
||||
original_existed,
|
||||
is_merge_file,
|
||||
is_script_file,
|
||||
affects_runtime,
|
||||
@@ -89,25 +86,19 @@ pub async fn save_profile_file(
|
||||
if changes_applied.is_valid()
|
||||
&& let Some(trigger) = backup_trigger
|
||||
{
|
||||
auto_backup::trigger_backup(trigger);
|
||||
AutoBackupManager::trigger_backup(trigger);
|
||||
}
|
||||
|
||||
Ok(changes_applied)
|
||||
}
|
||||
|
||||
struct OriginalProfileFile<'a> {
|
||||
content: &'a str,
|
||||
existed: bool,
|
||||
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 original.existed {
|
||||
fs::write(file_path, original.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()
|
||||
}
|
||||
@@ -137,7 +128,8 @@ fn profile_affects_runtime(profiles: &IProfiles, index: &str) -> bool {
|
||||
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,
|
||||
@@ -154,13 +146,13 @@ async fn handle_saved_profile_file(
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -181,13 +173,13 @@ async fn handle_saved_profile_file(
|
||||
}
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
@@ -151,9 +150,7 @@ impl IClashTemp {
|
||||
}
|
||||
|
||||
pub async fn save_config(&self) -> Result<()> {
|
||||
let path = dirs::clash_path()?;
|
||||
let yaml = mihomo_yaml::serialize(&self.0)?;
|
||||
help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await
|
||||
help::save_yaml(&dirs::clash_path()?, &self.0, Some("# Generated by Clash Verge")).await
|
||||
}
|
||||
|
||||
pub fn get_mixed_port(&self) -> u16 {
|
||||
|
||||
@@ -1,17 +1,13 @@
|
||||
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::{load_profiles, profiles_append_item_to_safe, save_profiles_unlocked},
|
||||
runtime::IRuntime,
|
||||
},
|
||||
config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
|
||||
constants::{files, timing},
|
||||
core::{
|
||||
CoreManager,
|
||||
handle::{self, Handle},
|
||||
listener::MIXED_PORT_KEY,
|
||||
runtime_bundle::resolve_provider_path_conflicts,
|
||||
tray,
|
||||
validate::CoreConfigValidator,
|
||||
},
|
||||
@@ -23,7 +19,6 @@ use anyhow::{Result, anyhow};
|
||||
use backon::{ExponentialBuilder, Retryable as _};
|
||||
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 tokio::sync::{Mutex, MutexGuard, OnceCell};
|
||||
@@ -50,7 +45,7 @@ impl Config {
|
||||
Self {
|
||||
clash_config: Draft::new(IClashTemp::new().await),
|
||||
verge_config: Draft::new(IVerge::new().await),
|
||||
profiles_config: Draft::new(load_profiles().await),
|
||||
profiles_config: Draft::new(IProfiles::new().await),
|
||||
runtime_config: Draft::new(IRuntime::default()),
|
||||
}
|
||||
})
|
||||
@@ -85,7 +80,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();
|
||||
@@ -143,11 +137,11 @@ impl Config {
|
||||
}
|
||||
|
||||
if profiles.latest_arc().get_item("Merge").is_err() {
|
||||
let merge_item = &mut build_merge_profile(Some("Merge".into()));
|
||||
let merge_item = &mut PrfItem::from_merge(Some("Merge".into()));
|
||||
profiles_append_item_to_safe(&profiles, merge_item).await?;
|
||||
}
|
||||
if profiles.latest_arc().get_item("Script").is_err() {
|
||||
let script_item = &mut build_script_profile(Some("Script".into()));
|
||||
let script_item = &mut PrfItem::from_script(Some("Script".into()));
|
||||
profiles_append_item_to_safe(&profiles, script_item).await?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -232,7 +226,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 +241,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::enhance(inputs).await;
|
||||
let (mut config, exists_keys, logs, dns_override) = enhance::enhance(profiles).await?;
|
||||
|
||||
resolve_provider_path_conflicts(&mut config, &dirs::app_home_dir()?)?;
|
||||
sanitize_tunnels_proxy(&mut config);
|
||||
@@ -327,20 +309,8 @@ 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, profiles.data_arc().save_file().await);
|
||||
});
|
||||
|
||||
let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task);
|
||||
|
||||
@@ -2,19 +2,14 @@ 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},
|
||||
};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use tristr::alias::String;
|
||||
|
||||
use super::{Config, IVerge};
|
||||
use crate::{core::handle::Handle, process::AsyncHandler};
|
||||
use crate::core::handle::Handle;
|
||||
|
||||
static PENDING_DNS_OVERRIDE_NOTICE: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
@@ -129,18 +124,7 @@ impl IVerge {
|
||||
}
|
||||
}
|
||||
|
||||
static DNS_OVERRIDE_SYNC: LazyLock<CoalescingJob> = LazyLock::new(|| {
|
||||
AsyncHandler::start_driver(scheduled_task::coalescing(
|
||||
|| async { logging_error!(Type::Config, Config::sync_dns_override().await) },
|
||||
|| logging!(error, Type::Config, "DNS override synchronization panicked"),
|
||||
))
|
||||
});
|
||||
|
||||
impl Config {
|
||||
pub(crate) fn request_dns_override_sync() {
|
||||
DNS_OVERRIDE_SYNC.request();
|
||||
}
|
||||
|
||||
pub(crate) async fn sync_dns_override() -> Result<()> {
|
||||
let _config_write = Self::lock_config_write().await;
|
||||
let state = Self::runtime().await.data_arc().dns_override.clone();
|
||||
|
||||
@@ -3,20 +3,16 @@ 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;
|
||||
mod verge;
|
||||
|
||||
pub(crate) use self::config::Config;
|
||||
pub(crate) use self::prfitem::{build_remote_profile, fetch_remote_refresh, read_profile_item_file};
|
||||
pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*};
|
||||
pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected};
|
||||
pub use self::{clash::*, encrypt::*, mixed_port::*, prfitem::*, profiles::*, verge::*};
|
||||
|
||||
macro_rules! patch_opt_field {
|
||||
($lv:expr, $rv:expr, $key:tt) => {
|
||||
|
||||
+460
-393
@@ -1,4 +1,4 @@
|
||||
use super::{PrfExtra, PrfItem, PrfOption};
|
||||
use super::patch_opt_field;
|
||||
|
||||
use crate::{
|
||||
config::profiles,
|
||||
@@ -9,7 +9,8 @@ use crate::{
|
||||
},
|
||||
};
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use clash_verge_subscription::decode_subscription;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_yaml_ng::Mapping;
|
||||
use std::time::Duration;
|
||||
use tokio::fs;
|
||||
use tristr::alias::String;
|
||||
@@ -17,323 +18,472 @@ use tristr::alias::String;
|
||||
use reqwest_dav::re_exports::url::form_urlencoded;
|
||||
use tauri::Url;
|
||||
|
||||
/// Builds an item from a partial value that must include `itype`.
|
||||
pub(super) async fn build_profile(item: &PrfItem, file_data: Option<String>) -> Result<PrfItem> {
|
||||
let itype = item
|
||||
.itype
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("type should not be null"))?;
|
||||
match itype.as_str() {
|
||||
"remote" => {
|
||||
let url = item
|
||||
.url
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("url should not be null"))?;
|
||||
let name = item.name.as_ref();
|
||||
let desc = item.desc.as_ref();
|
||||
let option = item.option.as_ref();
|
||||
build_remote_profile(url, name, desc, option).await
|
||||
pub(super) fn normalize_profile_home_url(raw: &str) -> Option<String> {
|
||||
let url = Url::parse(raw.trim()).ok()?;
|
||||
|
||||
if !matches!(url.scheme(), "http" | "https") {
|
||||
return None;
|
||||
}
|
||||
|
||||
url.host_str()?;
|
||||
Some(url.as_str().into())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct PrfItem {
|
||||
pub uid: Option<String>,
|
||||
|
||||
/// enum value: remote | local | script | merge
|
||||
#[serde(rename = "type")]
|
||||
pub itype: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub file: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub desc: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub url: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub selected: Option<Vec<PrfSelected>>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub extra: Option<PrfExtra>,
|
||||
|
||||
pub updated: Option<usize>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub option: Option<PrfOption>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub home: Option<String>,
|
||||
|
||||
#[serde(skip)]
|
||||
pub file_data: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct PrfSelected {
|
||||
pub name: Option<String>,
|
||||
pub now: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)]
|
||||
pub struct PrfExtra {
|
||||
pub upload: u64,
|
||||
pub download: u64,
|
||||
pub total: u64,
|
||||
pub expire: u64,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)]
|
||||
#[serde(default)]
|
||||
pub struct PrfOption {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub user_agent: Option<String>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub with_proxy: Option<bool>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub self_proxy: Option<bool>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub update_interval: Option<u64>,
|
||||
|
||||
/// HTTP request timeout in seconds
|
||||
/// default is 60 seconds
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub timeout_seconds: Option<u64>,
|
||||
|
||||
/// default is `false`
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub danger_accept_invalid_certs: Option<bool>,
|
||||
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub allow_auto_update: Option<bool>,
|
||||
pub merge: Option<String>,
|
||||
pub script: Option<String>,
|
||||
pub rules: Option<String>,
|
||||
pub proxies: Option<String>,
|
||||
pub groups: Option<String>,
|
||||
}
|
||||
|
||||
impl PrfOption {
|
||||
pub(crate) fn merge(one: Option<&Self>, other: Option<&Self>) -> Option<Self> {
|
||||
match (one, other) {
|
||||
(Some(a_ref), Some(b_ref)) => {
|
||||
let mut result = a_ref.clone();
|
||||
patch_opt_field!(result, b_ref, user_agent);
|
||||
patch_opt_field!(result, b_ref, with_proxy);
|
||||
patch_opt_field!(result, b_ref, self_proxy);
|
||||
patch_opt_field!(result, b_ref, danger_accept_invalid_certs);
|
||||
patch_opt_field!(result, b_ref, allow_auto_update);
|
||||
patch_opt_field!(result, b_ref, update_interval);
|
||||
patch_opt_field!(result, b_ref, merge);
|
||||
patch_opt_field!(result, b_ref, script);
|
||||
patch_opt_field!(result, b_ref, rules);
|
||||
patch_opt_field!(result, b_ref, proxies);
|
||||
patch_opt_field!(result, b_ref, groups);
|
||||
patch_opt_field!(result, b_ref, timeout_seconds);
|
||||
Some(result)
|
||||
}
|
||||
(Some(a_ref), None) => Some(a_ref.clone()),
|
||||
(None, Some(b_ref)) => Some(b_ref.clone()),
|
||||
(None, None) => None,
|
||||
}
|
||||
"local" => {
|
||||
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
|
||||
let desc = item.desc.clone().unwrap_or_else(|| "".into());
|
||||
let option = item.option.as_ref();
|
||||
from_local(name, desc, file_data, option).await
|
||||
}
|
||||
}
|
||||
|
||||
impl PrfItem {
|
||||
/// Builds an item from a partial value that must include `itype`.
|
||||
pub(super) async fn from(item: &Self, file_data: Option<String>) -> Result<Self> {
|
||||
let itype = item
|
||||
.itype
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("type should not be null"))?;
|
||||
match itype.as_str() {
|
||||
"remote" => {
|
||||
let url = item
|
||||
.url
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("url should not be null"))?;
|
||||
let name = item.name.as_ref();
|
||||
let desc = item.desc.as_ref();
|
||||
let option = item.option.as_ref();
|
||||
Self::from_url(url, name, desc, option).await
|
||||
}
|
||||
"local" => {
|
||||
let name = item.name.clone().unwrap_or_else(|| "Local File".into());
|
||||
let desc = item.desc.clone().unwrap_or_else(|| "".into());
|
||||
let option = item.option.as_ref();
|
||||
Self::from_local(name, desc, file_data, option).await
|
||||
}
|
||||
typ => bail!("invalid profile item type \"{typ}\""),
|
||||
}
|
||||
typ => bail!("invalid profile item type \"{typ}\""),
|
||||
}
|
||||
|
||||
async fn append_companion_item(item: &mut Self) -> Result<String> {
|
||||
profiles::profiles_append_item_safe(item).await?;
|
||||
item.uid
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
|
||||
}
|
||||
|
||||
async fn ensure_companion_items(
|
||||
merge: &mut Option<String>,
|
||||
script: &mut Option<String>,
|
||||
rules: &mut Option<String>,
|
||||
proxies: &mut Option<String>,
|
||||
groups: &mut Option<String>,
|
||||
) -> Result<()> {
|
||||
if merge.is_none() {
|
||||
*merge = Some(Self::append_companion_item(&mut Self::from_merge(None)).await?);
|
||||
}
|
||||
if script.is_none() {
|
||||
*script = Some(Self::append_companion_item(&mut Self::from_script(None)).await?);
|
||||
}
|
||||
if rules.is_none() {
|
||||
*rules = Some(Self::append_companion_item(&mut Self::from_rules()).await?);
|
||||
}
|
||||
if proxies.is_none() {
|
||||
*proxies = Some(Self::append_companion_item(&mut Self::from_proxies()).await?);
|
||||
}
|
||||
if groups.is_none() {
|
||||
*groups = Some(Self::append_companion_item(&mut Self::from_groups()).await?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn from_local(
|
||||
name: String,
|
||||
desc: String,
|
||||
file_data: Option<String>,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<Self> {
|
||||
let uid = help::get_uid("L").into();
|
||||
let file = format!("{uid}.yaml").into();
|
||||
let opt_ref = option.as_ref();
|
||||
let update_interval = opt_ref.and_then(|o| o.update_interval);
|
||||
let mut merge = opt_ref.and_then(|o| o.merge.clone());
|
||||
let mut script = opt_ref.and_then(|o| o.script.clone());
|
||||
let mut rules = opt_ref.and_then(|o| o.rules.clone());
|
||||
let mut proxies = opt_ref.and_then(|o| o.proxies.clone());
|
||||
let mut groups = opt_ref.and_then(|o| o.groups.clone());
|
||||
|
||||
Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
|
||||
Ok(Self {
|
||||
uid: Some(uid),
|
||||
itype: Some("local".into()),
|
||||
name: Some(name),
|
||||
desc: Some(desc),
|
||||
file: Some(file),
|
||||
url: None,
|
||||
selected: None,
|
||||
extra: None,
|
||||
option: Some(PrfOption {
|
||||
update_interval,
|
||||
merge,
|
||||
script,
|
||||
rules,
|
||||
proxies,
|
||||
groups,
|
||||
..PrfOption::default()
|
||||
}),
|
||||
home: None,
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn from_url(
|
||||
url: &str,
|
||||
name: Option<&String>,
|
||||
desc: Option<&String>,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<Self> {
|
||||
let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false));
|
||||
let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false));
|
||||
let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false));
|
||||
let allow_auto_update = Some(allow_auto_update_enabled(option));
|
||||
let user_agent = option.and_then(|o| o.user_agent.clone());
|
||||
let update_interval = option.and_then(|o| o.update_interval);
|
||||
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
|
||||
let mut merge = option.and_then(|o| o.merge.clone());
|
||||
let mut script = option.and_then(|o| o.script.clone());
|
||||
let mut rules = option.and_then(|o| o.rules.clone());
|
||||
let mut proxies = option.and_then(|o| o.proxies.clone());
|
||||
let mut groups = option.and_then(|o| o.groups.clone());
|
||||
|
||||
let proxy_type = if self_proxy {
|
||||
ProxyType::Localhost
|
||||
} else if with_proxy {
|
||||
ProxyType::System
|
||||
} else {
|
||||
ProxyType::None
|
||||
};
|
||||
|
||||
let url = fix_dirty_url(url)?;
|
||||
|
||||
let resp = match NetworkManager::new()
|
||||
.get(
|
||||
url.as_str(),
|
||||
proxy_type,
|
||||
Some(timeout),
|
||||
user_agent.clone(),
|
||||
accept_invalid_certs,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
return Err(e).context("failed to fetch remote profile");
|
||||
}
|
||||
};
|
||||
|
||||
let status_code = resp.status();
|
||||
if !status_code.is_success() {
|
||||
bail!("failed to fetch remote profile with status {status_code}")
|
||||
}
|
||||
|
||||
let header = resp.headers();
|
||||
|
||||
let extra;
|
||||
'extra: {
|
||||
for (k, v) in header.iter() {
|
||||
let key_lower = k.as_str().to_ascii_lowercase();
|
||||
// Accept standard custom-metadata prefixes (x-amz-meta-, x-obs-meta-, x-cos-meta-, etc.).
|
||||
if key_lower
|
||||
.strip_suffix("subscription-userinfo")
|
||||
.is_some_and(|prefix| prefix.is_empty() || prefix.ends_with('-'))
|
||||
{
|
||||
let sub_info = v.to_str().unwrap_or("");
|
||||
extra = Some(PrfExtra {
|
||||
upload: help::parse_str(sub_info, "upload").unwrap_or(0),
|
||||
download: help::parse_str(sub_info, "download").unwrap_or(0),
|
||||
total: help::parse_str(sub_info, "total").unwrap_or(0),
|
||||
expire: help::parse_str(sub_info, "expire").unwrap_or(0),
|
||||
});
|
||||
break 'extra;
|
||||
}
|
||||
}
|
||||
extra = None;
|
||||
}
|
||||
|
||||
let filename = match header.get("Content-Disposition") {
|
||||
Some(value) => {
|
||||
let filename = format!("{value:?}");
|
||||
let filename = filename.trim_matches('"');
|
||||
match help::parse_str::<String>(filename, "filename*") {
|
||||
Some(filename) => {
|
||||
let iter = percent_encoding::percent_decode(filename.as_bytes());
|
||||
let filename = iter.decode_utf8().unwrap_or_default();
|
||||
filename.split("''").last().map(|s| s.into())
|
||||
}
|
||||
None => match help::parse_str::<String>(filename, "filename") {
|
||||
Some(filename) => {
|
||||
let filename = filename.trim_matches('"');
|
||||
Some(filename.into())
|
||||
}
|
||||
None => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
None => {
|
||||
Some(crate::utils::help::get_last_part_and_decode(url.as_str()).unwrap_or_else(|| "Remote File".into()))
|
||||
}
|
||||
};
|
||||
let update_interval = match update_interval {
|
||||
Some(val) => Some(val),
|
||||
None => match header.get("profile-update-interval") {
|
||||
Some(value) => match value.to_str().unwrap_or("").parse::<u64>() {
|
||||
Ok(val) => Some(val * 60), // hour -> min
|
||||
Err(_) => None,
|
||||
},
|
||||
None => None,
|
||||
},
|
||||
};
|
||||
|
||||
let home = header
|
||||
.get("profile-web-page-url")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(normalize_profile_home_url);
|
||||
|
||||
let uid = help::get_uid("R").into();
|
||||
let file = format!("{uid}.yaml").into();
|
||||
let name = name.map_or_else(
|
||||
|| filename.map_or_else(|| "Remote File".into(), |s| s.into()),
|
||||
|s| s.to_owned(),
|
||||
);
|
||||
let data = resp.text();
|
||||
|
||||
let data = data.trim_start_matches('\u{feff}');
|
||||
|
||||
let yaml = serde_yaml_ng::from_str::<Mapping>(data).context("the remote profile data is invalid yaml")?;
|
||||
|
||||
if !yaml.contains_key("proxies") && !yaml.contains_key("proxy-providers") {
|
||||
bail!("profile does not contain `proxies` or `proxy-providers`");
|
||||
}
|
||||
|
||||
Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
|
||||
|
||||
Ok(Self {
|
||||
uid: Some(uid),
|
||||
itype: Some("remote".into()),
|
||||
name: Some(name),
|
||||
desc: desc.cloned(),
|
||||
file: Some(file),
|
||||
url: Some(url.as_str().into()),
|
||||
selected: None,
|
||||
extra,
|
||||
option: Some(PrfOption {
|
||||
update_interval,
|
||||
merge,
|
||||
script,
|
||||
rules,
|
||||
proxies,
|
||||
groups,
|
||||
allow_auto_update,
|
||||
..PrfOption::default()
|
||||
}),
|
||||
home,
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(data.into()),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn from_merge(uid: Option<String>) -> Self {
|
||||
let (id, template) = if let Some(uid) = uid {
|
||||
(uid, tmpl::ITEM_MERGE.into())
|
||||
} else {
|
||||
(help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into())
|
||||
};
|
||||
let file = format!("{id}.yaml").into();
|
||||
|
||||
Self {
|
||||
uid: Some(id),
|
||||
itype: Some("merge".into()),
|
||||
file: Some(file),
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(template),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn from_script(uid: Option<String>) -> Self {
|
||||
let id = if let Some(uid) = uid {
|
||||
uid
|
||||
} else {
|
||||
help::get_uid("s").into()
|
||||
};
|
||||
let file = format!("{id}.js").into(); // js ext
|
||||
Self {
|
||||
uid: Some(id),
|
||||
itype: Some("script".into()),
|
||||
file: Some(file),
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(tmpl::ITEM_SCRIPT.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn new_seq_item(prefix: &str, itype: &str, template: &str) -> Self {
|
||||
let uid = help::get_uid(prefix).into();
|
||||
let file = format!("{uid}.yaml").into(); // yaml ext
|
||||
|
||||
Self {
|
||||
uid: Some(uid),
|
||||
itype: Some(itype.into()),
|
||||
file: Some(file),
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(template.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn from_rules() -> Self {
|
||||
Self::new_seq_item("r", "rules", tmpl::ITEM_RULES)
|
||||
}
|
||||
|
||||
fn from_proxies() -> Self {
|
||||
Self::new_seq_item("p", "proxies", tmpl::ITEM_PROXIES)
|
||||
}
|
||||
|
||||
fn from_groups() -> Self {
|
||||
Self::new_seq_item("g", "groups", tmpl::ITEM_GROUPS)
|
||||
}
|
||||
|
||||
pub(crate) async fn read_file(&self) -> Result<String> {
|
||||
let file = self
|
||||
.file
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("could not find the file"))?;
|
||||
let path = dirs::app_profiles_dir()?.join(file.as_str());
|
||||
let content = fs::read_to_string(&path)
|
||||
.await
|
||||
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
|
||||
Ok(content.into())
|
||||
}
|
||||
}
|
||||
|
||||
async fn append_companion_item(item: &mut PrfItem) -> Result<String> {
|
||||
profiles::profiles_append_item_safe(item).await?;
|
||||
item.uid
|
||||
.clone()
|
||||
.ok_or_else(|| anyhow::anyhow!("appended companion item has no uid"))
|
||||
}
|
||||
|
||||
async fn ensure_companion_items(
|
||||
merge: &mut Option<String>,
|
||||
script: &mut Option<String>,
|
||||
rules: &mut Option<String>,
|
||||
proxies: &mut Option<String>,
|
||||
groups: &mut Option<String>,
|
||||
) -> Result<()> {
|
||||
if merge.is_none() {
|
||||
*merge = Some(append_companion_item(&mut build_merge_profile(None)).await?);
|
||||
}
|
||||
if script.is_none() {
|
||||
*script = Some(append_companion_item(&mut build_script_profile(None)).await?);
|
||||
}
|
||||
if rules.is_none() {
|
||||
*rules = Some(append_companion_item(&mut from_rules()).await?);
|
||||
}
|
||||
if proxies.is_none() {
|
||||
*proxies = Some(append_companion_item(&mut from_proxies()).await?);
|
||||
}
|
||||
if groups.is_none() {
|
||||
*groups = Some(append_companion_item(&mut from_groups()).await?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn from_local(
|
||||
name: String,
|
||||
desc: String,
|
||||
file_data: Option<String>,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<PrfItem> {
|
||||
let uid = help::get_uid("L").into();
|
||||
let file = format!("{uid}.yaml").into();
|
||||
let opt_ref = option.as_ref();
|
||||
let update_interval = opt_ref.and_then(|o| o.update_interval);
|
||||
let mut merge = opt_ref.and_then(|o| o.merge.clone());
|
||||
let mut script = opt_ref.and_then(|o| o.script.clone());
|
||||
let mut rules = opt_ref.and_then(|o| o.rules.clone());
|
||||
let mut proxies = opt_ref.and_then(|o| o.proxies.clone());
|
||||
let mut groups = opt_ref.and_then(|o| o.groups.clone());
|
||||
|
||||
ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?;
|
||||
Ok(PrfItem {
|
||||
uid: Some(uid),
|
||||
itype: Some("local".into()),
|
||||
name: Some(name),
|
||||
desc: Some(desc),
|
||||
file: Some(file),
|
||||
url: None,
|
||||
selected: None,
|
||||
extra: None,
|
||||
option: Some(PrfOption {
|
||||
update_interval,
|
||||
merge,
|
||||
script,
|
||||
rules,
|
||||
proxies,
|
||||
groups,
|
||||
..PrfOption::default()
|
||||
}),
|
||||
home: None,
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())),
|
||||
})
|
||||
}
|
||||
|
||||
struct DownloadedSubscription {
|
||||
url: Url,
|
||||
suggested_name: Option<std::string::String>,
|
||||
extra: Option<PrfExtra>,
|
||||
update_interval_minutes: Option<u64>,
|
||||
home: Option<String>,
|
||||
body: String,
|
||||
}
|
||||
|
||||
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(
|
||||
url: &str,
|
||||
name: Option<&String>,
|
||||
desc: Option<&String>,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<PrfItem> {
|
||||
let mut downloaded = download_subscription(url, option).await?;
|
||||
let uid: String = help::get_uid("R").into();
|
||||
let file = format!("{uid}.yaml").into();
|
||||
let name = name
|
||||
.cloned()
|
||||
.or_else(|| downloaded.suggested_name.take().map(Into::into))
|
||||
.unwrap_or_else(|| "Remote File".into());
|
||||
let url = downloaded.url.as_str().into();
|
||||
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),
|
||||
selected: None,
|
||||
extra,
|
||||
option: Some(option),
|
||||
home,
|
||||
updated: Some(updated),
|
||||
file_data: Some(body),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn fetch_remote_refresh(url: &str, option: Option<&PrfOption>) -> Result<RemoteProfileRefresh> {
|
||||
let downloaded = download_subscription(url, option).await?;
|
||||
prepare_remote_refresh(downloaded, option).await
|
||||
}
|
||||
|
||||
async fn download_subscription(url: &str, option: Option<&PrfOption>) -> Result<DownloadedSubscription> {
|
||||
let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false));
|
||||
let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false));
|
||||
let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false));
|
||||
let user_agent = option.and_then(|o| o.user_agent.clone());
|
||||
let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20);
|
||||
|
||||
let proxy_type = if self_proxy {
|
||||
ProxyType::Localhost
|
||||
} else if with_proxy {
|
||||
ProxyType::System
|
||||
} else {
|
||||
ProxyType::None
|
||||
};
|
||||
|
||||
let url = fix_dirty_url(url)?;
|
||||
|
||||
let resp = match NetworkManager::new()
|
||||
.get(
|
||||
url.as_str(),
|
||||
proxy_type,
|
||||
Some(timeout),
|
||||
user_agent,
|
||||
accept_invalid_certs,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
return Err(e).context("failed to fetch remote profile");
|
||||
macro_rules! current_field {
|
||||
($name:ident, $field:ident) => {
|
||||
pub(crate) fn $name(&self) -> Option<&String> {
|
||||
self.option.as_ref().and_then(|o| o.$field.as_ref())
|
||||
}
|
||||
};
|
||||
|
||||
let status_code = resp.status();
|
||||
if !status_code.is_success() {
|
||||
bail!("failed to fetch remote profile with status {status_code}")
|
||||
}
|
||||
|
||||
let document = decode_subscription(&url, resp.headers(), resp.text())?;
|
||||
let extra = document.usage.map(|usage| PrfExtra {
|
||||
upload: usage.upload,
|
||||
download: usage.download,
|
||||
total: usage.total,
|
||||
expire: usage.expire,
|
||||
});
|
||||
Ok(DownloadedSubscription {
|
||||
suggested_name: document.filename,
|
||||
update_interval_minutes: document.update_interval_minutes,
|
||||
home: document.home.map(Into::into),
|
||||
body: document.body.into(),
|
||||
url,
|
||||
extra,
|
||||
})
|
||||
}
|
||||
|
||||
async fn prepare_remote_refresh(
|
||||
downloaded: DownloadedSubscription,
|
||||
option: Option<&PrfOption>,
|
||||
) -> Result<RemoteProfileRefresh> {
|
||||
let mut resolved = PrfOption {
|
||||
update_interval: option
|
||||
.and_then(|o| o.update_interval)
|
||||
.or(downloaded.update_interval_minutes),
|
||||
merge: option.and_then(|o| o.merge.clone()),
|
||||
script: option.and_then(|o| o.script.clone()),
|
||||
rules: option.and_then(|o| o.rules.clone()),
|
||||
proxies: option.and_then(|o| o.proxies.clone()),
|
||||
groups: option.and_then(|o| o.groups.clone()),
|
||||
allow_auto_update: Some(allow_auto_update_enabled(option)),
|
||||
..PrfOption::default()
|
||||
};
|
||||
ensure_companion_items(
|
||||
&mut resolved.merge,
|
||||
&mut resolved.script,
|
||||
&mut resolved.rules,
|
||||
&mut resolved.proxies,
|
||||
&mut resolved.groups,
|
||||
)
|
||||
.await?;
|
||||
Ok(RemoteProfileRefresh {
|
||||
extra: downloaded.extra,
|
||||
home: downloaded.home,
|
||||
updated: chrono::Local::now().timestamp() as usize,
|
||||
option: resolved,
|
||||
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())
|
||||
} else {
|
||||
(help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into())
|
||||
};
|
||||
let file = format!("{id}.yaml").into();
|
||||
|
||||
PrfItem {
|
||||
uid: Some(id),
|
||||
itype: Some("merge".into()),
|
||||
file: Some(file),
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(template),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn build_script_profile(uid: Option<String>) -> PrfItem {
|
||||
let id = if let Some(uid) = uid {
|
||||
uid
|
||||
} else {
|
||||
help::get_uid("s").into()
|
||||
};
|
||||
let file = format!("{id}.js").into(); // js ext
|
||||
PrfItem {
|
||||
uid: Some(id),
|
||||
itype: Some("script".into()),
|
||||
file: Some(file),
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(tmpl::ITEM_SCRIPT.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn new_seq_item(prefix: &str, itype: &str, template: &str) -> PrfItem {
|
||||
let uid = help::get_uid(prefix).into();
|
||||
let file = format!("{uid}.yaml").into(); // yaml ext
|
||||
|
||||
PrfItem {
|
||||
uid: Some(uid),
|
||||
itype: Some(itype.into()),
|
||||
file: Some(file),
|
||||
updated: Some(chrono::Local::now().timestamp() as usize),
|
||||
file_data: Some(template.into()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn from_rules() -> PrfItem {
|
||||
new_seq_item("r", "rules", tmpl::ITEM_RULES)
|
||||
}
|
||||
|
||||
fn from_proxies() -> PrfItem {
|
||||
new_seq_item("p", "proxies", tmpl::ITEM_PROXIES)
|
||||
}
|
||||
|
||||
fn from_groups() -> PrfItem {
|
||||
new_seq_item("g", "groups", tmpl::ITEM_GROUPS)
|
||||
}
|
||||
|
||||
pub(crate) async fn read_profile_item_file(file: Option<&str>) -> Result<String> {
|
||||
let file = file.ok_or_else(|| anyhow::anyhow!("could not find the file"))?;
|
||||
let path = dirs::app_profiles_dir()?.join(file);
|
||||
let content = fs::read_to_string(&path)
|
||||
.await
|
||||
.with_context(|| format!("failed to read the file \"{}\"", path.display()))?;
|
||||
Ok(content.into())
|
||||
impl PrfItem {
|
||||
current_field!(current_merge, merge);
|
||||
current_field!(current_script, script);
|
||||
current_field!(current_rules, rules);
|
||||
current_field!(current_proxies, proxies);
|
||||
current_field!(current_groups, groups);
|
||||
}
|
||||
|
||||
fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool {
|
||||
@@ -368,86 +518,3 @@ fn fix_dirty_url(input: &str) -> Result<Url> {
|
||||
|
||||
Ok(url)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::{
|
||||
io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader},
|
||||
net::TcpListener,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn import_and_refresh_share_subscription_decoding() -> Result<()> {
|
||||
const BODY: &str = "# keep this comment\nproxies: []\n";
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let url = format!("http://{}/subscription", listener.local_addr()?);
|
||||
let server = tokio::spawn(async move {
|
||||
let response = format!(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\
|
||||
Content-Disposition: attachment; filename=remote.yaml\r\n\
|
||||
Profile-Update-Interval: 2\r\n\
|
||||
Profile-Web-Page-Url: https://example.invalid/\r\n\
|
||||
Subscription-Userinfo: upload=1; download=2; total=3; expire=4\r\n\r\n{BODY}",
|
||||
BODY.len()
|
||||
);
|
||||
for _ in 0..2 {
|
||||
let (socket, _) = listener.accept().await?;
|
||||
let mut socket = BufReader::new(socket);
|
||||
let mut line = std::string::String::new();
|
||||
loop {
|
||||
line.clear();
|
||||
if socket.read_line(&mut line).await? == 0 || line == "\r\n" {
|
||||
break;
|
||||
}
|
||||
}
|
||||
socket.get_mut().write_all(response.as_bytes()).await?;
|
||||
}
|
||||
Ok::<_, std::io::Error>(())
|
||||
});
|
||||
let option = PrfOption {
|
||||
update_interval: Some(0),
|
||||
allow_auto_update: Some(false),
|
||||
timeout_seconds: Some(5),
|
||||
merge: Some("test-merge".into()),
|
||||
script: Some("test-script".into()),
|
||||
rules: Some("test-rules".into()),
|
||||
proxies: Some("test-proxies".into()),
|
||||
groups: Some("test-groups".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let item: clash_verge_profile::PrfItem = build_remote_profile(&url, None, None, Some(&option)).await?;
|
||||
let refresh = fetch_remote_refresh(
|
||||
&url,
|
||||
Some(&PrfOption {
|
||||
update_interval: None,
|
||||
..option
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
server.await??;
|
||||
assert_eq!(item.itype.as_deref(), Some("remote"));
|
||||
assert_eq!(item.name.as_deref(), Some("remote.yaml"));
|
||||
assert_eq!(item.home.as_deref(), Some("https://example.invalid/"));
|
||||
assert_eq!(item.file_data.as_deref(), Some(BODY));
|
||||
assert_eq!(item.current_merge().map(String::as_str), Some("test-merge"));
|
||||
let usage = item.extra.context("expected decoded usage")?;
|
||||
assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4));
|
||||
let fetched_option = item.option.context("expected profile options")?;
|
||||
assert_eq!(fetched_option.update_interval, Some(0));
|
||||
assert_eq!(fetched_option.allow_auto_update, Some(false));
|
||||
|
||||
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!(
|
||||
refresh.option,
|
||||
PrfOption {
|
||||
update_interval: Some(120),
|
||||
..fetched_option
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
use anyhow::{Result, anyhow};
|
||||
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(String),
|
||||
Restore(String),
|
||||
}
|
||||
|
||||
pub(crate) fn check() -> Result<()> {
|
||||
match BLOCKED.lock().as_ref() {
|
||||
Some(StorageBlock::Transaction(reason) | StorageBlock::Restore(reason)) => {
|
||||
Err(anyhow!("Profile storage requires recovery before use: {reason}"))
|
||||
}
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn block(error: &anyhow::Error) {
|
||||
let mut blocked = BLOCKED.lock();
|
||||
if !matches!(*blocked, Some(StorageBlock::Transaction(_))) {
|
||||
*blocked = Some(StorageBlock::Transaction(format!("{error:#}")));
|
||||
}
|
||||
}
|
||||
|
||||
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(anyhow!("Profile storage requires recovery before use: {reason}"));
|
||||
}
|
||||
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().inspect_err(block)?;
|
||||
let result: Result<()> = async {
|
||||
if !journal_exists(&root).await? {
|
||||
return Ok(());
|
||||
}
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
return tokio::task::spawn_blocking(move || clash_verge_profile_store::recover_pending(&root))
|
||||
.await?
|
||||
.map_err(Into::into);
|
||||
#[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))]
|
||||
return Err(anyhow!(
|
||||
"restore the pending profile transaction with redo support enabled"
|
||||
));
|
||||
}
|
||||
.await;
|
||||
if let Err(error) = &result {
|
||||
block(error);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
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()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(unix, all(windows, feature = "profile-store-windows")))]
|
||||
pub(super) async fn commit_refresh(
|
||||
uid: String,
|
||||
candidate: super::IProfiles,
|
||||
body: tristr::alias::String,
|
||||
) -> Result<super::IProfiles> {
|
||||
use clash_verge_profile_store::{CommitOutcome, Session, recover_pending};
|
||||
|
||||
let root = crate::utils::dirs::app_home_dir()?;
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use anyhow::Context as _;
|
||||
|
||||
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");
|
||||
block(&error);
|
||||
return Err(error);
|
||||
}
|
||||
let file = candidate
|
||||
.get_item(&uid)?
|
||||
.file
|
||||
.as_deref()
|
||||
.context("missing profile filename")?;
|
||||
let path = crate::utils::dirs::app_profiles_dir()?.join(file);
|
||||
tokio::fs::write(path, body.as_bytes())
|
||||
.await
|
||||
.with_context(|| format!("failed to write to file \"{file}\""))?;
|
||||
super::profiles::save_profiles_unlocked(&candidate).await?;
|
||||
return Ok(candidate);
|
||||
}
|
||||
}
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
let session = Session::open(&root).map_err(anyhow::Error::from).inspect_err(|error| {
|
||||
match std::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) {
|
||||
Err(status) if status.kind() == std::io::ErrorKind::NotFound => {}
|
||||
_ => block(error),
|
||||
}
|
||||
})?;
|
||||
let item = candidate.get_item(&uid)?;
|
||||
if let Some(file) = item.file.as_deref()
|
||||
&& !file.contains(['/', '\\', ':', '\0'])
|
||||
&& !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) => {
|
||||
if recover_pending(&root).is_err() {
|
||||
block(&error.into());
|
||||
}
|
||||
Ok(candidate)
|
||||
}
|
||||
CommitOutcome::Retryable(error) => {
|
||||
if let Err(recovery) = recover_pending(&root).map_err(anyhow::Error::from) {
|
||||
block(&recovery);
|
||||
return Err(recovery.context("failed to discard the incomplete profile refresh"));
|
||||
}
|
||||
Err(anyhow::Error::from(error).context("profile refresh stopped before commit"))
|
||||
}
|
||||
CommitOutcome::NeedsRecovery(error) => {
|
||||
let error = anyhow::Error::from(error);
|
||||
block(&error);
|
||||
Err(error.context("profile refresh requires recovery"))
|
||||
}
|
||||
}
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(result) => result,
|
||||
Err(error) => {
|
||||
let error = anyhow::Error::from(error).context("profile storage worker stopped unexpectedly");
|
||||
block(&error);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
+679
-448
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,7 @@ use serde_yaml_ng::{Mapping, Value};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use tristr::alias::String;
|
||||
|
||||
use clash_verge_config_render::use_keys;
|
||||
use crate::enhance::field::use_keys;
|
||||
|
||||
const PATCH_CONFIG_INNER: [&str; 5] = ["allow-lan", "ipv6", "log-level", "unified-delay", "tunnels"];
|
||||
|
||||
|
||||
@@ -42,6 +42,12 @@ pub mod timing {
|
||||
#[cfg(target_os = "windows")]
|
||||
pub const SERVICE_WAIT_INTERVAL: Duration = Duration::from_millis(200);
|
||||
|
||||
// 回退 sidecar 后继续等待服务就绪并尝试交接。
|
||||
#[cfg(target_os = "windows")]
|
||||
pub const SERVICE_HANDOFF_WINDOW: Duration = Duration::from_secs(120);
|
||||
#[cfg(target_os = "windows")]
|
||||
pub const SERVICE_HANDOFF_INTERVAL: Duration = Duration::from_secs(2);
|
||||
|
||||
// 交接时等待 sidecar 释放 ext-controller 通道。
|
||||
#[cfg(target_os = "windows")]
|
||||
pub const SERVICE_START_RETRIES: usize = 5;
|
||||
@@ -64,5 +70,22 @@ pub mod files {
|
||||
pub mod tun {
|
||||
pub const DEFAULT_STACK: &str = "mips";
|
||||
|
||||
pub const DEFAULT_MTU: u16 = 1500;
|
||||
|
||||
pub const DNS_HIJACK: &[&str] = &["any:53"];
|
||||
|
||||
/// Saved dialog fields; `enable` belongs to the verge switch.
|
||||
pub const GUI_KEYS: &[&str] = &[
|
||||
"stack",
|
||||
"device",
|
||||
"auto-route",
|
||||
"route-exclude-address",
|
||||
#[cfg(target_os = "linux")]
|
||||
"auto-redirect",
|
||||
"auto-detect-interface",
|
||||
"dns-hijack",
|
||||
"dns-mode",
|
||||
"strict-route",
|
||||
"mtu",
|
||||
];
|
||||
}
|
||||
|
||||
+151
-130
@@ -1,23 +1,29 @@
|
||||
use crate::process::AsyncHandler;
|
||||
use crate::{
|
||||
config::{Config, IVerge},
|
||||
feat::create_local_backup_with_namer,
|
||||
process::AsyncHandler,
|
||||
utils::dirs::local_backup_dir,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use chrono::Local;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
sync::{Arc, LazyLock},
|
||||
sync::{
|
||||
OnceLock,
|
||||
atomic::{AtomicBool, AtomicI64, Ordering},
|
||||
},
|
||||
time::{Duration, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::{fs, time::Instant};
|
||||
use tokio::{
|
||||
fs,
|
||||
sync::{Mutex, watch},
|
||||
};
|
||||
|
||||
const DEFAULT_INTERVAL_HOURS: u64 = 24;
|
||||
const MIN_INTERVAL_HOURS: u64 = 1;
|
||||
const MAX_INTERVAL_HOURS: u64 = 168;
|
||||
const MIN_BACKUP_INTERVAL: Duration = Duration::from_secs(60);
|
||||
const MIN_BACKUP_INTERVAL_SECS: i64 = 60;
|
||||
const AUTO_BACKUP_KEEP: usize = 20;
|
||||
const AUTO_MARKER: &str = "-auto-";
|
||||
|
||||
@@ -36,9 +42,13 @@ impl AutoBackupTrigger {
|
||||
Self::GlobalScript => "script",
|
||||
}
|
||||
}
|
||||
|
||||
const fn is_schedule(self) -> bool {
|
||||
matches!(self, Self::Scheduled)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct AutoBackupSettings {
|
||||
schedule_enabled: bool,
|
||||
interval_hours: u64,
|
||||
@@ -46,11 +56,6 @@ struct AutoBackupSettings {
|
||||
}
|
||||
|
||||
impl AutoBackupSettings {
|
||||
fn interval(self) -> Option<Duration> {
|
||||
self.schedule_enabled
|
||||
.then(|| Duration::from_secs(self.interval_hours * 3600))
|
||||
}
|
||||
|
||||
fn from_verge(verge: &IVerge) -> Self {
|
||||
let interval = verge
|
||||
.auto_backup_interval_hours
|
||||
@@ -75,139 +80,155 @@ impl Default for AutoBackupSettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct BackupInput {
|
||||
settings: Option<AutoBackupSettings>,
|
||||
restart_schedule: bool,
|
||||
clear_pending_edit: bool,
|
||||
edit_before_settings: Option<AutoBackupTrigger>,
|
||||
edit: Option<AutoBackupTrigger>,
|
||||
pub struct AutoBackupManager {
|
||||
settings_tx: watch::Sender<AutoBackupSettings>,
|
||||
// The watch channel is the single settings store; no duplicate copies.
|
||||
settings_rx: watch::Receiver<AutoBackupSettings>,
|
||||
runner_started: AtomicBool,
|
||||
exec_lock: Mutex<()>,
|
||||
last_backup: AtomicI64,
|
||||
}
|
||||
|
||||
impl BackupInput {
|
||||
fn update_settings(&mut self, settings: AutoBackupSettings) -> bool {
|
||||
if self.settings == Some(settings) {
|
||||
return false;
|
||||
}
|
||||
// A pending off/on or interval round trip still restarts the countdown.
|
||||
self.restart_schedule |= self
|
||||
.settings
|
||||
.is_some_and(|previous| previous.interval() != settings.interval());
|
||||
self.settings = Some(settings);
|
||||
if !settings.change_enabled {
|
||||
self.clear_pending_edit = true;
|
||||
self.edit = None;
|
||||
self.edit_before_settings = None;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
const fn request_edit(&mut self, trigger: AutoBackupTrigger) -> bool {
|
||||
let pending = match self.settings {
|
||||
Some(settings) if settings.change_enabled => &mut self.edit,
|
||||
Some(_) => return false,
|
||||
None => &mut self.edit_before_settings,
|
||||
};
|
||||
if pending.is_some() {
|
||||
return false;
|
||||
}
|
||||
*pending = Some(trigger);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
static BACKUP_REQUESTS: LazyLock<Arc<Mailbox<BackupInput>>> =
|
||||
LazyLock::new(|| AsyncHandler::start_driver(scheduled_task::new(BackupSchedule::default(), execute_backup)));
|
||||
|
||||
pub(crate) async fn init() {
|
||||
let _write = Config::lock_config_write().await;
|
||||
publish_settings(&Config::verge().await.data_arc());
|
||||
}
|
||||
|
||||
pub(crate) fn publish_settings(verge: &IVerge) {
|
||||
let settings = AutoBackupSettings::from_verge(verge);
|
||||
BACKUP_REQUESTS.update(|pending| pending.update_settings(settings));
|
||||
}
|
||||
|
||||
pub(crate) fn trigger_backup(trigger: AutoBackupTrigger) {
|
||||
BACKUP_REQUESTS.update(|pending| pending.request_edit(trigger));
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct BackupSchedule {
|
||||
settings: AutoBackupSettings,
|
||||
due: Option<Instant>,
|
||||
edit: Option<AutoBackupTrigger>,
|
||||
last_backup: Option<Instant>,
|
||||
}
|
||||
|
||||
impl ScheduledTask for BackupSchedule {
|
||||
type Input = BackupInput;
|
||||
type Work = AutoBackupTrigger;
|
||||
type Output = Result<Instant>;
|
||||
|
||||
fn on_input(&mut self, input: BackupInput, now: Instant) {
|
||||
if input.clear_pending_edit {
|
||||
self.edit = None;
|
||||
}
|
||||
let previous_edit = if self.settings.change_enabled {
|
||||
input.edit_before_settings
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(settings) = input.settings {
|
||||
if input.restart_schedule || self.settings.interval() != settings.interval() {
|
||||
self.due = settings.interval().map(|interval| now + interval);
|
||||
impl AutoBackupManager {
|
||||
pub fn global() -> &'static Self {
|
||||
static INSTANCE: OnceLock<AutoBackupManager> = OnceLock::new();
|
||||
INSTANCE.get_or_init(|| {
|
||||
let (settings_tx, settings_rx) = watch::channel(AutoBackupSettings::default());
|
||||
Self {
|
||||
settings_tx,
|
||||
settings_rx,
|
||||
runner_started: AtomicBool::new(false),
|
||||
exec_lock: Mutex::new(()),
|
||||
last_backup: AtomicI64::new(0),
|
||||
}
|
||||
self.settings = settings;
|
||||
}
|
||||
if self.settings.change_enabled {
|
||||
self.edit = self.edit.or(previous_edit).or(input.edit);
|
||||
} else {
|
||||
self.edit = None;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn next(&mut self, now: Instant) -> Next<AutoBackupTrigger> {
|
||||
let throttled = self.last_backup.is_some_and(|last| now - last < MIN_BACKUP_INTERVAL);
|
||||
if self.due.is_some_and(|due| due <= now) {
|
||||
self.due = None;
|
||||
if !throttled {
|
||||
return Next::Run(AutoBackupTrigger::Scheduled);
|
||||
pub async fn init(&self) -> Result<()> {
|
||||
let settings = Self::load_settings().await;
|
||||
let _ = self.settings_tx.send_replace(settings);
|
||||
self.maybe_start_runner(settings);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn refresh_settings(&self) -> Result<()> {
|
||||
let settings = Self::load_settings().await;
|
||||
let _ = self.settings_tx.send_replace(settings);
|
||||
self.maybe_start_runner(settings);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn trigger_backup(trigger: AutoBackupTrigger) {
|
||||
AsyncHandler::spawn(move || async move {
|
||||
if let Err(err) = Self::global().execute_trigger(trigger).await {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Backup,
|
||||
"Auto backup execution failed ({:?}): {err:#?}",
|
||||
trigger
|
||||
);
|
||||
}
|
||||
self.due = self.settings.interval().map(|interval| now + interval);
|
||||
}
|
||||
|
||||
if let Some(edit) = self.edit.take()
|
||||
&& !throttled
|
||||
{
|
||||
return Next::Run(edit);
|
||||
}
|
||||
self.due.map_or(Next::Idle, Next::At)
|
||||
});
|
||||
}
|
||||
|
||||
fn finished(&mut self, trigger: AutoBackupTrigger, result: std::thread::Result<Self::Output>, now: Instant) {
|
||||
if trigger == AutoBackupTrigger::Scheduled {
|
||||
self.due = self.settings.interval().map(|interval| now + interval);
|
||||
}
|
||||
match result {
|
||||
Ok(Ok(created_at)) => self.last_backup = Some(created_at),
|
||||
Ok(Err(err)) => logging!(warn, Type::Backup, "Auto backup failed ({trigger:?}): {err:#}"),
|
||||
Err(_) => logging!(error, Type::Backup, "Auto backup panicked ({trigger:?})"),
|
||||
fn maybe_start_runner(&self, settings: AutoBackupSettings) {
|
||||
if settings.schedule_enabled {
|
||||
self.ensure_runner();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_backup(trigger: AutoBackupTrigger) -> Result<Instant> {
|
||||
let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
|
||||
let created_at = Instant::now();
|
||||
fn ensure_runner(&self) {
|
||||
if self.runner_started.swap(true, Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Err(err) = cleanup_auto_backups().await {
|
||||
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
|
||||
let mut rx = self.settings_tx.subscribe();
|
||||
AsyncHandler::spawn(move || async move {
|
||||
Self::run_scheduler(&mut rx).await;
|
||||
});
|
||||
}
|
||||
|
||||
logging!(info, Type::Backup, "Auto backup created ({trigger:?}): {file_name}");
|
||||
Ok(created_at)
|
||||
async fn run_scheduler(rx: &mut watch::Receiver<AutoBackupSettings>) {
|
||||
let mut current = *rx.borrow();
|
||||
loop {
|
||||
if !current.schedule_enabled {
|
||||
if rx.changed().await.is_err() {
|
||||
break;
|
||||
}
|
||||
current = *rx.borrow();
|
||||
continue;
|
||||
}
|
||||
|
||||
let duration = Duration::from_secs(current.interval_hours.saturating_mul(3600));
|
||||
let sleeper = tokio::time::sleep(duration);
|
||||
tokio::pin!(sleeper);
|
||||
|
||||
tokio::select! {
|
||||
_ = &mut sleeper => {
|
||||
if let Err(err) = Self::global()
|
||||
.execute_trigger(AutoBackupTrigger::Scheduled)
|
||||
.await
|
||||
{
|
||||
logging!(
|
||||
warn,
|
||||
Type::Backup,
|
||||
"Scheduled auto backup failed: {err:#?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
changed = rx.changed() => {
|
||||
if changed.is_err() {
|
||||
break;
|
||||
}
|
||||
current = *rx.borrow();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_trigger(&self, trigger: AutoBackupTrigger) -> Result<()> {
|
||||
let snapshot = *self.settings_rx.borrow();
|
||||
|
||||
if trigger.is_schedule() && !snapshot.schedule_enabled {
|
||||
return Ok(());
|
||||
}
|
||||
if !trigger.is_schedule() && !snapshot.change_enabled {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !self.should_run_now() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let _guard = self.exec_lock.lock().await;
|
||||
if !self.should_run_now() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let file_name = create_local_backup_with_namer(|name| append_auto_suffix(name, trigger.slug()).into()).await?;
|
||||
self.last_backup.store(Local::now().timestamp(), Ordering::Release);
|
||||
|
||||
if let Err(err) = cleanup_auto_backups().await {
|
||||
logging!(warn, Type::Backup, "Failed to cleanup old auto backups: {err:#?}");
|
||||
}
|
||||
|
||||
logging!(info, Type::Backup, "Auto backup created ({:?}): {}", trigger, file_name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn should_run_now(&self) -> bool {
|
||||
let last = self.last_backup.load(Ordering::Acquire);
|
||||
if last == 0 {
|
||||
return true;
|
||||
}
|
||||
let now = Local::now().timestamp();
|
||||
now.saturating_sub(last) >= MIN_BACKUP_INTERVAL_SECS
|
||||
}
|
||||
|
||||
async fn load_settings() -> AutoBackupSettings {
|
||||
let verge = Config::verge().await;
|
||||
AutoBackupSettings::from_verge(&verge.latest_arc())
|
||||
}
|
||||
}
|
||||
|
||||
fn append_auto_suffix(file_name: &str, slug: &str) -> String {
|
||||
|
||||
@@ -3,7 +3,6 @@ use crate::{config::Config, process::AsyncHandler, utils::dirs};
|
||||
use anyhow::Error;
|
||||
use arc_swap::{ArcSwap, ArcSwapOption};
|
||||
use backon::{ConstantBuilder, Retryable as _};
|
||||
use clash_verge_backup_archive::BackupWriter;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
|
||||
use std::{
|
||||
@@ -16,6 +15,7 @@ use std::{
|
||||
};
|
||||
use tokio::{fs, time::timeout};
|
||||
use tristr::alias::String;
|
||||
use zip::write::SimpleFileOptions;
|
||||
|
||||
const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
@@ -275,28 +275,27 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
||||
|
||||
let value = zip_path.clone();
|
||||
let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??;
|
||||
let mut archive = BackupWriter::new(file)?;
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
zip.add_directory("profiles/", SimpleFileOptions::default())?;
|
||||
let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored);
|
||||
|
||||
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 backup_path = format!("profiles/{}", file_name);
|
||||
zip.start_file(backup_path, options)?;
|
||||
let file_content = fs::read(&path).await?;
|
||||
zip.write_all(&file_content)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let profile_index = fs::read(dirs::profiles_path()?).await?;
|
||||
drop(profile_guard);
|
||||
|
||||
archive
|
||||
.start_file(dirs::CLASH_CONFIG)?
|
||||
.write_all(&fs::read(dirs::clash_path()?).await?)?;
|
||||
zip.start_file(dirs::CLASH_CONFIG, options)?;
|
||||
zip.write_all(fs::read(dirs::clash_path()?).await?.as_slice())?;
|
||||
|
||||
let verge_text = fs::read_to_string(dirs::verge_path()?).await?;
|
||||
let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?;
|
||||
@@ -305,18 +304,17 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> {
|
||||
obj.remove("webdav_password");
|
||||
obj.remove("webdav_url");
|
||||
}
|
||||
archive
|
||||
.start_file(dirs::VERGE_CONFIG)?
|
||||
.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
|
||||
zip.start_file(dirs::VERGE_CONFIG, options)?;
|
||||
zip.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?;
|
||||
|
||||
let dns_config_path = dirs::app_home_dir()?.join(DNS_CONFIG);
|
||||
if dns_config_path.exists() {
|
||||
archive
|
||||
.start_file(DNS_CONFIG)?
|
||||
.write_all(&fs::read(&dns_config_path).await?)?;
|
||||
zip.start_file(DNS_CONFIG, options)?;
|
||||
zip.write_all(fs::read(&dns_config_path).await?.as_slice())?;
|
||||
}
|
||||
|
||||
archive.start_file(dirs::PROFILE_YAML)?.write_all(&profile_index)?;
|
||||
archive.finish()?;
|
||||
zip.start_file(dirs::PROFILE_YAML, options)?;
|
||||
zip.write_all(fs::read(dirs::profiles_path()?).await?.as_slice())?;
|
||||
zip.finish()?;
|
||||
Ok((zip_file_name, zip_path))
|
||||
}
|
||||
|
||||
+101
-102
@@ -5,16 +5,14 @@ use crate::{
|
||||
};
|
||||
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_task::countdown::{self, Countdown};
|
||||
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
use anyhow::Result;
|
||||
use parking_lot::Mutex;
|
||||
use std::future::Future;
|
||||
use std::sync::LazyLock;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU32, Ordering};
|
||||
use tauri::Listener as _;
|
||||
use tokio::sync::oneshot;
|
||||
use tokio::time::{Duration, sleep};
|
||||
|
||||
#[repr(u8)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -43,24 +41,27 @@ impl LightweightState {
|
||||
static LIGHTWEIGHT_STATE: AtomicU8 = AtomicU8::new(LightweightState::Normal as u8);
|
||||
|
||||
struct WindowListener {
|
||||
handler_id: Option<tauri::EventId>,
|
||||
handler_id: AtomicU32,
|
||||
event: &'static str,
|
||||
label: &'static str,
|
||||
}
|
||||
|
||||
impl WindowListener {
|
||||
fn setup(&mut self, on_event: impl Fn() + Send + 'static) {
|
||||
fn setup(&self, on_event: impl Fn() + Send + 'static) {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
if let Some(id) = self.handler_id.take() {
|
||||
window.unlisten(id);
|
||||
let previous_handler_id = self.handler_id.swap(0, Ordering::AcqRel);
|
||||
if previous_handler_id != 0 {
|
||||
window.unlisten(previous_handler_id);
|
||||
logging!(debug, Type::Lightweight, "覆盖旧的{}监听", self.label);
|
||||
}
|
||||
self.handler_id = Some(window.listen(self.event, move |_event| on_event()));
|
||||
let handler_id = window.listen(self.event, move |_event| on_event());
|
||||
self.handler_id.store(handler_id, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel(&mut self) {
|
||||
if let Some(id) = self.handler_id.take() {
|
||||
fn cancel(&self) {
|
||||
let id = self.handler_id.swap(0, Ordering::AcqRel);
|
||||
if id != 0 {
|
||||
if let Some(window) = WindowManager::get_main_window() {
|
||||
window.unlisten(id);
|
||||
}
|
||||
@@ -69,28 +70,19 @@ impl WindowListener {
|
||||
}
|
||||
}
|
||||
|
||||
struct WindowListeners {
|
||||
close: WindowListener,
|
||||
focus: WindowListener,
|
||||
}
|
||||
static WINDOW_CLOSE_LISTENER: WindowListener = WindowListener {
|
||||
handler_id: AtomicU32::new(0),
|
||||
event: "tauri://close-requested",
|
||||
label: "窗口关闭",
|
||||
};
|
||||
|
||||
static WINDOW_LISTENERS: Mutex<WindowListeners> = Mutex::new(WindowListeners {
|
||||
close: WindowListener {
|
||||
handler_id: None,
|
||||
event: "tauri://close-requested",
|
||||
label: "窗口关闭",
|
||||
},
|
||||
focus: WindowListener {
|
||||
handler_id: None,
|
||||
event: "tauri://focus",
|
||||
label: "窗口焦点",
|
||||
},
|
||||
});
|
||||
static WEBVIEW_FOCUS_LISTENER: WindowListener = WindowListener {
|
||||
handler_id: AtomicU32::new(0),
|
||||
event: "tauri://focus",
|
||||
label: "窗口焦点",
|
||||
};
|
||||
|
||||
static TIMER_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
static COUNTDOWN: LazyLock<Countdown<u64>> =
|
||||
LazyLock::new(|| AsyncHandler::start_driver(countdown::new(prepare_countdown, enter_lightweight_on_timeout)));
|
||||
static CANCEL_TX: Mutex<Option<oneshot::Sender<()>>> = Mutex::new(None);
|
||||
|
||||
#[inline]
|
||||
fn get_state() -> LightweightState {
|
||||
@@ -126,12 +118,11 @@ async fn refresh_lightweight_tray_state() {
|
||||
}
|
||||
|
||||
pub async fn auto_lightweight_boot() -> Result<()> {
|
||||
let generation = TIMER_GENERATION.load(Ordering::Acquire);
|
||||
let verge_config = Config::verge().await;
|
||||
let is_enable_auto = verge_config.data_arc().enable_auto_light_weight_mode.unwrap_or(false);
|
||||
let is_silent_start = verge_config.data_arc().enable_silent_start.unwrap_or(false);
|
||||
if is_enable_auto && verge_config.latest_arc().enable_auto_light_weight_mode.unwrap_or(false) {
|
||||
enable_auto_light_weight_mode_at(generation).await;
|
||||
if is_enable_auto {
|
||||
enable_auto_light_weight_mode().await;
|
||||
}
|
||||
if is_silent_start {
|
||||
entry_lightweight_mode().await;
|
||||
@@ -140,43 +131,32 @@ pub async fn auto_lightweight_boot() -> Result<()> {
|
||||
}
|
||||
|
||||
pub async fn enable_auto_light_weight_mode() {
|
||||
enable_auto_light_weight_mode_at(TIMER_GENERATION.load(Ordering::Acquire)).await;
|
||||
}
|
||||
|
||||
async fn enable_auto_light_weight_mode_at(generation: u64) {
|
||||
if let Err(e) = Timer::global().init().await {
|
||||
logging!(error, Type::Lightweight, "Failed to initialize timer: {e}");
|
||||
return;
|
||||
}
|
||||
logging!(info, Type::Lightweight, "开启自动轻量模式");
|
||||
setup_auto_light_weight_listeners(generation);
|
||||
setup_window_close_listener();
|
||||
setup_webview_focus_listener();
|
||||
}
|
||||
|
||||
pub fn disable_auto_light_weight_mode() {
|
||||
logging!(info, Type::Lightweight, "关闭自动轻量模式");
|
||||
TIMER_GENERATION.fetch_add(1, Ordering::AcqRel);
|
||||
COUNTDOWN.disarm();
|
||||
let mut listeners = WINDOW_LISTENERS.lock();
|
||||
listeners.close.cancel();
|
||||
listeners.focus.cancel();
|
||||
cancel_light_weight_timer();
|
||||
cancel_window_close_listener();
|
||||
cancel_webview_focus_listener();
|
||||
}
|
||||
|
||||
pub async fn entry_lightweight_mode() -> bool {
|
||||
let entered = begin_lightweight_mode();
|
||||
if entered {
|
||||
COUNTDOWN.disarm();
|
||||
}
|
||||
refresh_lightweight_tray_state().await;
|
||||
entered
|
||||
}
|
||||
|
||||
fn begin_lightweight_mode() -> bool {
|
||||
if !try_transition(LightweightState::Normal, LightweightState::In) {
|
||||
logging!(debug, Type::Lightweight, "无需进入轻量模式,跳过调用");
|
||||
refresh_lightweight_tray_state().await;
|
||||
return false;
|
||||
}
|
||||
record_state_and_log(LightweightState::In);
|
||||
WindowManager::destroy_main_window();
|
||||
cancel_light_weight_timer();
|
||||
refresh_lightweight_tray_state().await;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -192,11 +172,16 @@ pub async fn exit_lightweight_mode() -> bool {
|
||||
}
|
||||
record_state_and_log(LightweightState::Exiting);
|
||||
WindowManager::show_main_window().await;
|
||||
let generation = TIMER_GENERATION.load(Ordering::Acquire);
|
||||
if auto_light_weight_is_enabled().await {
|
||||
setup_auto_light_weight_listeners(generation);
|
||||
let enable_auto_light_weight_mode = Config::verge()
|
||||
.await
|
||||
.data_arc()
|
||||
.enable_auto_light_weight_mode
|
||||
.unwrap_or(false);
|
||||
if enable_auto_light_weight_mode {
|
||||
setup_window_close_listener();
|
||||
setup_webview_focus_listener();
|
||||
}
|
||||
COUNTDOWN.disarm();
|
||||
cancel_light_weight_timer();
|
||||
record_state_and_log(LightweightState::Normal);
|
||||
refresh_lightweight_tray_state().await;
|
||||
true
|
||||
@@ -204,64 +189,78 @@ pub async fn exit_lightweight_mode() -> bool {
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub async fn add_light_weight_timer() {
|
||||
let generation = TIMER_GENERATION.load(Ordering::Acquire);
|
||||
if auto_light_weight_is_enabled().await {
|
||||
COUNTDOWN.arm(generation);
|
||||
}
|
||||
setup_light_weight_timer().await;
|
||||
}
|
||||
|
||||
async fn auto_light_weight_is_enabled() -> bool {
|
||||
let verge = Config::verge().await;
|
||||
// A disable applies before persistence. A rollback restores eligibility for future hides.
|
||||
verge.data_arc().enable_auto_light_weight_mode.unwrap_or(false)
|
||||
&& verge.latest_arc().enable_auto_light_weight_mode.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn setup_auto_light_weight_listeners(generation: u64) {
|
||||
let mut listeners = WINDOW_LISTENERS.lock();
|
||||
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
listeners.close.setup(move || {
|
||||
COUNTDOWN.arm(generation);
|
||||
fn setup_window_close_listener() {
|
||||
WINDOW_CLOSE_LISTENER.setup(|| {
|
||||
std::mem::drop(AsyncHandler::spawn(|| async {
|
||||
setup_light_weight_timer().await;
|
||||
}));
|
||||
logging!(info, Type::Lightweight, "监听到关闭请求,开始轻量模式计时");
|
||||
});
|
||||
listeners.focus.setup(move || {
|
||||
if generation == TIMER_GENERATION.load(Ordering::Acquire) {
|
||||
COUNTDOWN.disarm();
|
||||
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
|
||||
}
|
||||
}
|
||||
|
||||
fn cancel_window_close_listener() {
|
||||
WINDOW_CLOSE_LISTENER.cancel();
|
||||
}
|
||||
|
||||
fn setup_webview_focus_listener() {
|
||||
WEBVIEW_FOCUS_LISTENER.setup(|| {
|
||||
cancel_light_weight_timer();
|
||||
logging!(debug, Type::Lightweight, "监听到窗口获得焦点,取消轻量模式计时");
|
||||
});
|
||||
}
|
||||
|
||||
fn prepare_countdown(generation: u64) -> Option<impl Future<Output = Duration>> {
|
||||
// Unlisten can be deferred while Tauri is delivering an event.
|
||||
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(async {
|
||||
let minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"Lightweight mode timer set, entering lightweight mode in {} minutes",
|
||||
minutes
|
||||
);
|
||||
Duration::from_secs(minutes.saturating_mul(60))
|
||||
})
|
||||
fn cancel_webview_focus_listener() {
|
||||
WEBVIEW_FOCUS_LISTENER.cancel();
|
||||
}
|
||||
|
||||
fn enter_lightweight_on_timeout(generation: u64) {
|
||||
if generation != TIMER_GENERATION.load(Ordering::Acquire) {
|
||||
async fn setup_light_weight_timer() {
|
||||
let once_by_minutes = Config::verge().await.data_arc().auto_light_weight_minutes.unwrap_or(10);
|
||||
|
||||
let mut cancel_tx_guard = CANCEL_TX.lock();
|
||||
if cancel_tx_guard.is_some() {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Lightweight mode timer already exists, skipping setup"
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let (tx, rx) = oneshot::channel::<()>();
|
||||
*cancel_tx_guard = Some(tx);
|
||||
drop(cancel_tx_guard);
|
||||
|
||||
AsyncHandler::spawn(move || async move {
|
||||
tokio::select! {
|
||||
_ = sleep(Duration::from_secs(once_by_minutes.saturating_mul(60))) => {
|
||||
logging!(info, Type::Timer, "Lightweight mode timer expired, entering lightweight mode");
|
||||
{
|
||||
let mut guard = CANCEL_TX.lock();
|
||||
*guard = None;
|
||||
}
|
||||
entry_lightweight_mode().await;
|
||||
}
|
||||
_ = rx => {
|
||||
logging!(debug, Type::Timer, "Received cancel signal, stopping lightweight mode timer");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"Lightweight mode timer expired, entering lightweight mode"
|
||||
"Lightweight mode timer set, entering lightweight mode in {} minutes",
|
||||
once_by_minutes
|
||||
);
|
||||
begin_lightweight_mode();
|
||||
AsyncHandler::spawn(refresh_lightweight_tray_state);
|
||||
}
|
||||
|
||||
fn cancel_light_weight_timer() {
|
||||
let mut cancel_tx_guard = CANCEL_TX.lock();
|
||||
if let Some(tx) = cancel_tx_guard.take() {
|
||||
let _ = tx.send(());
|
||||
logging!(debug, Type::Timer, "Timer cancelled");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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, runtime::IRuntime},
|
||||
constants::timing,
|
||||
core::{
|
||||
handle,
|
||||
@@ -170,8 +170,7 @@ impl CoreManager {
|
||||
}
|
||||
});
|
||||
|
||||
let yaml = mihomo_yaml::serialize(clash_config)?;
|
||||
help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?;
|
||||
help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
|
||||
handle::Handle::notice(status, message);
|
||||
Ok(())
|
||||
}
|
||||
@@ -244,7 +243,7 @@ impl CoreManager {
|
||||
crate::config::profiles::restore_selected_nodes().await;
|
||||
return Ok(Err(outcome));
|
||||
}
|
||||
match save_profiles(candidate).await {
|
||||
match candidate.save_file().await {
|
||||
Ok(()) => {
|
||||
tracing::Span::current().record("outcome", "committed");
|
||||
Ok(Ok(guard))
|
||||
|
||||
@@ -326,6 +326,13 @@ where
|
||||
start_sidecar().await
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
enum HandoffOutcome {
|
||||
NotReady,
|
||||
Done,
|
||||
Failed,
|
||||
}
|
||||
|
||||
fn report_sidecar_failure(error: anyhow::Error, service_rejection: Option<&str>) -> anyhow::Error {
|
||||
let error = match service_rejection {
|
||||
Some(reason) => error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
|
||||
@@ -681,6 +688,11 @@ impl CoreManager {
|
||||
return result;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
if matches!(*self.get_running_mode(), RunningMode::Sidecar) {
|
||||
self.spawn_service_handoff_watcher().await;
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
@@ -871,6 +883,167 @@ impl CoreManager {
|
||||
let wait = crate::core::runstate::RUN_STATE.await_ready(attempts, timing::SERVICE_WAIT_INTERVAL);
|
||||
let _ = tokio::time::timeout(timing::SERVICE_WAIT_MAX, wait).await;
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn spawn_service_handoff_watcher(&self) {
|
||||
use crate::constants::timing;
|
||||
use crate::process::AsyncHandler;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Instant;
|
||||
|
||||
// An accepted Sidecar is the user's decision for this session, not a wait for the Service.
|
||||
let needs_service = Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|
||||
&& !crate::core::runstate::RUN_STATE.state().sidecar_allowed;
|
||||
if !needs_service {
|
||||
return;
|
||||
}
|
||||
|
||||
if self.handoff_watcher_running.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service not ready at startup; sidecar active, watching for handoff"
|
||||
);
|
||||
|
||||
AsyncHandler::spawn(|| async move {
|
||||
let manager = Self::global();
|
||||
let started = Instant::now();
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
let attempts = std::num::NonZeroUsize::MIN.saturating_add(
|
||||
(timing::SERVICE_HANDOFF_WINDOW.as_millis() / timing::SERVICE_HANDOFF_INTERVAL.as_millis()) as usize,
|
||||
);
|
||||
let _ = retry(RetryPolicy::fixed(attempts, std::time::Duration::ZERO), |_| async {
|
||||
if started.elapsed() >= timing::SERVICE_HANDOFF_WINDOW {
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service handoff window elapsed; staying in sidecar mode"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
// The window is checked before waiting, including the final handoff attempt.
|
||||
tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await;
|
||||
if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) {
|
||||
return Ok(());
|
||||
}
|
||||
match manager.try_handoff_sidecar_to_service().await {
|
||||
HandoffOutcome::Done => Ok(()),
|
||||
HandoffOutcome::Failed => {
|
||||
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
|
||||
Ok(())
|
||||
}
|
||||
HandoffOutcome::NotReady => Err(RetryError::Retry(())),
|
||||
}
|
||||
})
|
||||
.await;
|
||||
manager.handoff_watcher_running.store(false, Ordering::Release);
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
async fn refresh_service_readiness_for_handoff() -> bool {
|
||||
if SERVICE_MANAGER.confirm_ready().await.is_err() {
|
||||
return false;
|
||||
}
|
||||
crate::core::runstate::RUN_STATE.state().service_usable()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
#[tracing::instrument(skip_all, level = "debug", fields(outcome = tracing::field::Empty))]
|
||||
async fn try_handoff_sidecar_to_service(&self) -> HandoffOutcome {
|
||||
// Before probing: a probe reply records an observation, which clears sidecar_allowed.
|
||||
if crate::core::runstate::RUN_STATE.state().sidecar_allowed {
|
||||
return HandoffOutcome::Done;
|
||||
}
|
||||
if !Self::refresh_service_readiness_for_handoff().await {
|
||||
return HandoffOutcome::NotReady;
|
||||
}
|
||||
|
||||
if !self.try_start_config_update() {
|
||||
return HandoffOutcome::NotReady;
|
||||
}
|
||||
let _config_update = DropGuard::new((), |()| {
|
||||
self.finish_config_update();
|
||||
});
|
||||
|
||||
// Lock order is config then lifecycle.
|
||||
let _life = self.lifecycle_lock.lock().await;
|
||||
|
||||
if !matches!(*self.get_running_mode(), RunningMode::Sidecar)
|
||||
|| !Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|
||||
|| crate::core::runstate::RUN_STATE.state().sidecar_allowed
|
||||
{
|
||||
return HandoffOutcome::Done;
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"service became ready; handing off from sidecar to service"
|
||||
);
|
||||
if let Err(error) = self.stop_sidecar_after_proxy_clear().await {
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"failed to clear proxy before sidecar handoff: {error:#}"
|
||||
);
|
||||
return HandoffOutcome::Failed;
|
||||
}
|
||||
|
||||
let service_result = run_ready_core_start_transition(
|
||||
|| self.start_core_by_service(),
|
||||
|| {
|
||||
matches!(*self.get_running_mode(), RunningMode::Service)
|
||||
&& self.current_core_readiness_generation().is_some()
|
||||
},
|
||||
|| self.apply_proxy_after_start(),
|
||||
)
|
||||
.await;
|
||||
let Err(service_error) = service_result else {
|
||||
logging!(info, Type::Core, "handoff to service mode succeeded");
|
||||
return HandoffOutcome::Done;
|
||||
};
|
||||
|
||||
logging!(error, Type::Core, "handoff to service failed: {service_error:#}");
|
||||
if let Err(cleanup_error) = self.controlled_stop_core_inner().await {
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"failed to stop service before sidecar fallback: {cleanup_error:#}"
|
||||
);
|
||||
return HandoffOutcome::Failed;
|
||||
}
|
||||
|
||||
let sidecar_result = run_ready_core_start_transition(
|
||||
|| self.start_core_by_sidecar(),
|
||||
|| {
|
||||
matches!(*self.get_running_mode(), RunningMode::Sidecar)
|
||||
&& self.current_core_readiness_generation().is_some()
|
||||
},
|
||||
|| self.apply_proxy_after_start(),
|
||||
)
|
||||
.await;
|
||||
if let Err(sidecar_error) = sidecar_result {
|
||||
logging!(error, Type::Core, "sidecar fallback failed: {sidecar_error:#}");
|
||||
if let Err(cleanup_error) = self.rollback_failed_sidecar_transition().await {
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"failed to clear proxy before sidecar rollback: {cleanup_error:#}"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
"sidecar fallback became ready and restored proxy state"
|
||||
);
|
||||
}
|
||||
HandoffOutcome::Failed
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -4,8 +4,8 @@ mod lifecycle;
|
||||
mod state;
|
||||
|
||||
use anyhow::Result;
|
||||
use arc_swap::ArcSwapOption;
|
||||
use clash_verge_logging::{LogRing, Type, logging};
|
||||
use arc_swap::{ArcSwap, ArcSwapOption};
|
||||
use clash_verge_logging::{LogRing, Type, logging, logging_error};
|
||||
use std::{
|
||||
fmt,
|
||||
sync::{
|
||||
@@ -14,9 +14,12 @@ use std::{
|
||||
},
|
||||
time::Instant,
|
||||
};
|
||||
use tauri_plugin_shell::process::CommandChild;
|
||||
|
||||
use crate::core::runstate::{RUN_STATE, RealEnv, RunStateStore};
|
||||
use crate::singleton;
|
||||
#[cfg(target_os = "windows")]
|
||||
use std::os::windows::io::OwnedHandle;
|
||||
|
||||
pub(crate) static CLASH_LOGGER: LazyLock<Arc<LogRing>> = LazyLock::new(|| Arc::new(LogRing::new()));
|
||||
|
||||
@@ -86,26 +89,46 @@ pub struct CoreManager {
|
||||
/// A reference rather than the global directly, so a test can supervise a Core without
|
||||
/// racing every other test for one process-wide Running Mode.
|
||||
run_state: &'static RunStateStore<RealEnv>,
|
||||
sidecar: parking_lot::Mutex<state::SidecarSession>,
|
||||
state: ArcSwap<State>,
|
||||
last_update: ArcSwapOption<Instant>,
|
||||
#[cfg(target_os = "windows")]
|
||||
job_handle: ArcSwapOption<OwnedHandle>,
|
||||
config_update_in_progress: AtomicBool,
|
||||
core_readiness_state: AtomicU64,
|
||||
startup_error: parking_lot::Mutex<Option<CoreFailure>>,
|
||||
sidecar_exit: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
|
||||
// 串行化 start/stop/restart 和 sidecar→service 交接。
|
||||
// 锁序固定为 config_update_in_progress → lifecycle_lock。
|
||||
pub(crate) lifecycle_lock: tokio::sync::Mutex<()>,
|
||||
// sidecar→service 交接 watcher 单实例标志。
|
||||
#[cfg(target_os = "windows")]
|
||||
handoff_watcher_running: AtomicBool,
|
||||
}
|
||||
|
||||
/// Process-level state owned by `CoreManager`.
|
||||
///
|
||||
/// Running Mode deliberately does *not* live here — it belongs to `core::runstate`, which
|
||||
/// keeps it consistent with Service Health and derives PAC availability from it.
|
||||
#[derive(Debug, Default)]
|
||||
struct State {
|
||||
child_sidecar: ArcSwapOption<CommandChild>,
|
||||
}
|
||||
|
||||
impl Default for CoreManager {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
run_state: &RUN_STATE,
|
||||
sidecar: parking_lot::Mutex::default(),
|
||||
state: ArcSwap::new(Arc::new(State::default())),
|
||||
last_update: ArcSwapOption::new(None),
|
||||
#[cfg(target_os = "windows")]
|
||||
job_handle: ArcSwapOption::new(None),
|
||||
config_update_in_progress: AtomicBool::new(false),
|
||||
core_readiness_state: AtomicU64::new(0),
|
||||
startup_error: parking_lot::Mutex::new(None),
|
||||
sidecar_exit: tokio::sync::Mutex::new(None),
|
||||
lifecycle_lock: tokio::sync::Mutex::new(()),
|
||||
#[cfg(target_os = "windows")]
|
||||
handoff_watcher_running: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,6 +162,18 @@ impl CoreManager {
|
||||
self.startup_error.lock().clone()
|
||||
}
|
||||
|
||||
pub fn take_child_sidecar(&self) -> Option<CommandChild> {
|
||||
self.state
|
||||
.load()
|
||||
.child_sidecar
|
||||
.swap(None)
|
||||
.and_then(|arc| Arc::try_unwrap(arc).ok())
|
||||
}
|
||||
|
||||
pub fn get_running_sidecar_pid(&self) -> Option<u32> {
|
||||
self.state.load().child_sidecar.load_full().map(|child| child.pid())
|
||||
}
|
||||
|
||||
pub fn get_last_update(&self) -> Option<Arc<Instant>> {
|
||||
self.last_update.load_full()
|
||||
}
|
||||
@@ -183,6 +218,11 @@ impl CoreManager {
|
||||
self.run_state.core_start_settled();
|
||||
}
|
||||
|
||||
pub fn set_running_child_sidecar(&self, child: CommandChild) {
|
||||
let state = self.state.load();
|
||||
state.child_sidecar.store(Some(Arc::new(child)));
|
||||
}
|
||||
|
||||
fn mark_core_ready(&self) -> u64 {
|
||||
let mut current = self.core_readiness_state.load(Ordering::Acquire);
|
||||
loop {
|
||||
@@ -217,27 +257,38 @@ impl CoreManager {
|
||||
self.last_update.store(Some(Arc::new(time)));
|
||||
}
|
||||
|
||||
/// Replaces the Windows Job Object handle owned by the core manager
|
||||
///
|
||||
/// Passing `None` drops the current handle, which closes the Job Object
|
||||
/// and terminates its assigned processes due to `KILL_ON_JOB_CLOSE`.
|
||||
///
|
||||
/// This method is currently only used on Windows.
|
||||
#[cfg(target_os = "windows")]
|
||||
fn set_job_handle(&self, handle: Option<OwnedHandle>) {
|
||||
self.job_handle.store(handle.map(Arc::new));
|
||||
}
|
||||
|
||||
pub(crate) fn try_start_config_update(&self) -> bool {
|
||||
!self.config_update_in_progress.swap(true, Ordering::AcqRel)
|
||||
}
|
||||
|
||||
pub(crate) fn finish_config_update(&self) {
|
||||
self.config_update_in_progress.store(false, Ordering::Release);
|
||||
// The caller may still hold the config write lock that synchronization needs.
|
||||
crate::config::Config::request_dns_override_sync();
|
||||
// Spawned because the caller may still hold the config write lock this waits for.
|
||||
crate::process::AsyncHandler::spawn(|| async {
|
||||
logging_error!(Type::Config, crate::config::Config::sync_dns_override().await);
|
||||
});
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(retries = 0))]
|
||||
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}");
|
||||
}
|
||||
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#[cfg(test)]
|
||||
use super::claim_core_readiness_generation;
|
||||
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
use crate::{
|
||||
AsyncHandler,
|
||||
config::Config,
|
||||
@@ -10,19 +11,11 @@ use crate::{
|
||||
};
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_logging::Type;
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
use futures::{
|
||||
FutureExt as _,
|
||||
future::{Map, Shared},
|
||||
};
|
||||
use log::Level;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use tauri_plugin_mihomo::MihomoExt as _;
|
||||
use tauri_plugin_shell::ShellExt as _;
|
||||
use tauri_plugin_shell::process::CommandChild;
|
||||
use tokio::task::{JoinError, JoinHandle};
|
||||
|
||||
pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
|
||||
let detail = error.to_string();
|
||||
@@ -35,7 +28,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 +40,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;
|
||||
@@ -138,34 +130,8 @@ where
|
||||
.context("Mihomo API did not become ready")
|
||||
}
|
||||
|
||||
fn should_clear_terminated_sidecar(
|
||||
running_mode: &RunningMode,
|
||||
current_generation: Option<u64>,
|
||||
terminated_generation: u64,
|
||||
) -> bool {
|
||||
matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation)
|
||||
}
|
||||
|
||||
type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc<JoinError>>;
|
||||
type SidecarExit = Shared<Map<JoinHandle<()>, ShareExitResult>>;
|
||||
|
||||
fn share_exit(exit: JoinHandle<()>) -> SidecarExit {
|
||||
let share_error: ShareExitResult = |result| result.map_err(Arc::new);
|
||||
exit.map(share_error).shared()
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct SidecarSession {
|
||||
process: Option<SidecarProcess>,
|
||||
exit: Option<SidecarExit>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct SidecarProcess {
|
||||
generation: u64,
|
||||
child: CommandChild,
|
||||
#[cfg(target_os = "windows")]
|
||||
job: OwnedHandle,
|
||||
fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool {
|
||||
matches!(running_mode, RunningMode::Sidecar) && current_pid == Some(terminated_pid)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
@@ -252,8 +218,7 @@ impl CoreManager {
|
||||
)
|
||||
})?;
|
||||
let (terminated, termination) = tokio::sync::oneshot::channel();
|
||||
let exit = execution.release_after_exit(child.pid(), termination);
|
||||
self.sidecar.lock().exit = Some(share_exit(exit));
|
||||
*self.sidecar_exit.lock().await = Some(execution.release_after_exit(child.pid(), termination));
|
||||
#[cfg(target_os = "windows")]
|
||||
let job = {
|
||||
match create_and_assign_sidecar_job(child.pid()) {
|
||||
@@ -309,7 +274,7 @@ impl CoreManager {
|
||||
};
|
||||
Logger::global().writer_sidecar_log(Level::Info, &message);
|
||||
CLASH_LOGGER.clear_logs();
|
||||
manager.clear_terminated_sidecar(core_readiness_generation).await;
|
||||
manager.clear_terminated_sidecar(pid).await;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
@@ -337,12 +302,9 @@ impl CoreManager {
|
||||
};
|
||||
}
|
||||
|
||||
self.sidecar.lock().process = Some(SidecarProcess {
|
||||
generation: core_readiness_generation,
|
||||
child,
|
||||
#[cfg(target_os = "windows")]
|
||||
job,
|
||||
});
|
||||
#[cfg(target_os = "windows")]
|
||||
self.set_job_handle(Some(job));
|
||||
self.set_running_child_sidecar(child);
|
||||
self.core_started(RunningMode::Sidecar);
|
||||
self.restore_selected_nodes().await;
|
||||
|
||||
@@ -352,13 +314,18 @@ impl CoreManager {
|
||||
/// Terminates the sidecar after its caller has successfully cleared the
|
||||
/// system proxy.
|
||||
pub(super) async fn stop_core_by_sidecar_unprepared(&self) -> Result<()> {
|
||||
let process = self.sidecar.lock().process.take();
|
||||
if let Some(process) = process {
|
||||
let pid = process.child.pid();
|
||||
#[cfg(target_os = "windows")]
|
||||
drop(process.job);
|
||||
if let Some(child) = self.take_child_sidecar() {
|
||||
let pid = child.pid();
|
||||
|
||||
if let Err(error) = process.child.kill() {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// Setting the job handle to None clears the stored handle and
|
||||
// closes the previous Windows job handle in `set_job_handle`.
|
||||
self.set_job_handle(None);
|
||||
let _ = pid;
|
||||
}
|
||||
|
||||
if let Err(error) = child.kill() {
|
||||
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
|
||||
}
|
||||
}
|
||||
@@ -368,15 +335,15 @@ impl CoreManager {
|
||||
}
|
||||
|
||||
async fn wait_for_sidecar_exit(&self) -> Result<()> {
|
||||
// The lifecycle lock serializes callers. Keep a receipt in the session across timeouts.
|
||||
let exit = self.sidecar.lock().exit.clone();
|
||||
if let Some(exit) = exit {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), exit)
|
||||
let mut exit = self.sidecar_exit.lock().await;
|
||||
if let Some(task) = exit.as_mut() {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), task)
|
||||
.await
|
||||
.context("Sidecar has not exited; core handoff is blocked")?
|
||||
.context("Sidecar exit monitoring failed")?;
|
||||
self.sidecar.lock().exit.take();
|
||||
exit.take();
|
||||
}
|
||||
drop(exit);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -425,17 +392,15 @@ impl CoreManager {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn clear_terminated_sidecar(&self, terminated_generation: u64) {
|
||||
async fn clear_terminated_sidecar(&self, terminated_pid: u32) {
|
||||
let _life = self.lifecycle_lock.lock().await;
|
||||
let process = {
|
||||
let mut session = self.sidecar.lock();
|
||||
let current = session.process.as_ref().map(|process| process.generation);
|
||||
if !should_clear_terminated_sidecar(&self.get_running_mode(), current, terminated_generation) {
|
||||
return;
|
||||
}
|
||||
session.process.take()
|
||||
};
|
||||
drop(process);
|
||||
if !should_clear_terminated_sidecar(&self.get_running_mode(), self.get_running_sidecar_pid(), terminated_pid) {
|
||||
return;
|
||||
}
|
||||
|
||||
let _ = self.take_child_sidecar();
|
||||
#[cfg(target_os = "windows")]
|
||||
self.set_job_handle(None);
|
||||
proxy_control::stop_guard().await;
|
||||
self.core_stopped();
|
||||
#[cfg(target_os = "macos")]
|
||||
|
||||
@@ -11,7 +11,9 @@ pub mod network_watch;
|
||||
pub mod notify;
|
||||
pub(crate) mod owner_identity;
|
||||
pub mod proxy_control;
|
||||
pub mod proxy_view;
|
||||
pub mod runstate;
|
||||
pub(crate) mod runtime_bundle;
|
||||
pub mod service;
|
||||
pub mod sysopt;
|
||||
pub mod timer;
|
||||
|
||||
@@ -3,25 +3,13 @@
|
||||
//! Proxy settings live per network service. A write that found no service wrote nothing, and a
|
||||
//! switch to another service leaves the proxy on the old one; both need the write repeated.
|
||||
|
||||
use crate::{
|
||||
config::Config,
|
||||
core::{CoreManager, proxy_control},
|
||||
process::AsyncHandler,
|
||||
};
|
||||
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_task::scheduled_task::{self, CoalescingJob};
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::LazyLock;
|
||||
use sysproxy::NetworkServiceMonitor;
|
||||
|
||||
static MONITOR: Mutex<Option<NetworkServiceMonitor>> = Mutex::new(None);
|
||||
|
||||
static REAPPLY: LazyLock<CoalescingJob> = LazyLock::new(|| {
|
||||
AsyncHandler::start_driver(scheduled_task::coalescing(reapply, || {
|
||||
logging!(error, Type::Core, "network proxy reapply panicked");
|
||||
}))
|
||||
});
|
||||
|
||||
pub fn is_armed() -> bool {
|
||||
MONITOR.lock().is_some()
|
||||
}
|
||||
@@ -30,7 +18,7 @@ pub fn is_armed() -> bool {
|
||||
/// appearing from here on is never missed.
|
||||
pub fn start() {
|
||||
match NetworkServiceMonitor::start(|| {
|
||||
REAPPLY.request();
|
||||
AsyncHandler::spawn(reapply);
|
||||
}) {
|
||||
Ok(monitor) => {
|
||||
*MONITOR.lock() = Some(monitor);
|
||||
|
||||
@@ -74,6 +74,12 @@ impl Handle {
|
||||
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
||||
}
|
||||
|
||||
/// A verified installer became ready (or was cleared); the frontend refetches the staged
|
||||
/// version.
|
||||
pub fn notify_staged_update_changed() {
|
||||
Self::send_event(FrontendEvent::StagedUpdateChanged);
|
||||
}
|
||||
|
||||
pub fn notice(status: NoticeStatus, message: impl Into<Arc<str>>) {
|
||||
Self::send_event(FrontendEvent::NoticeMessage {
|
||||
status,
|
||||
|
||||
@@ -35,6 +35,7 @@ pub enum FrontendEvent<'a> {
|
||||
state: crate::core::runstate::RunStateView,
|
||||
},
|
||||
PendingFailuresChanged,
|
||||
StagedUpdateChanged,
|
||||
#[cfg(target_os = "linux")]
|
||||
ThemeChanged {
|
||||
theme: tauri::Theme,
|
||||
@@ -408,6 +409,11 @@ fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, se
|
||||
"verge://pending-failures-changed",
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
FrontendEvent::StagedUpdateChanged,
|
||||
"verge://staged-update-changed",
|
||||
json!(null),
|
||||
),
|
||||
(
|
||||
FrontendEvent::ProfileChanged {
|
||||
current_profile_id: uid,
|
||||
@@ -460,6 +466,7 @@ frontend_events! {
|
||||
profile_completed: ProfileUpdatePayload = "profile-update-completed", FrontendEvent::ProfileUpdateCompleted { uid } => ProfileUpdatePayload { uid: uid.to_string() };
|
||||
run_state: crate::core::runstate::RunStateView = "verge://run-state-changed", FrontendEvent::RunStateChanged { state } => state;
|
||||
pending_failures: () = "verge://pending-failures-changed", FrontendEvent::PendingFailuresChanged => ();
|
||||
staged_update: () = "verge://staged-update-changed", FrontendEvent::StagedUpdateChanged => ();
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, specta::Type)]
|
||||
|
||||
@@ -18,20 +18,13 @@ use crate::{
|
||||
use anyhow::{Result, ensure};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_service_ipc::{MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome};
|
||||
use clash_verge_task::watch_task;
|
||||
use std::{
|
||||
borrow::Borrow,
|
||||
future::Future,
|
||||
sync::{
|
||||
Arc, LazyLock, Once,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
sync::atomic::{AtomicU64, Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
sync::{Mutex, watch},
|
||||
time::timeout,
|
||||
};
|
||||
use tokio::{sync::Mutex, time::timeout};
|
||||
|
||||
const CLEAR_ATTEMPTS: u32 = 3;
|
||||
const CLEAR_RETRY_DELAY: Duration = Duration::from_millis(100);
|
||||
@@ -222,40 +215,23 @@ const fn refusal_classification(service_usable: Option<bool>) -> SysproxyFailure
|
||||
const LOOPBACK_HOST: &str = "127.0.0.1";
|
||||
const MAX_SERVICE_BYPASS_LEN: usize = 8192;
|
||||
|
||||
static SERVICE_PROXY_OPERATIONS: LazyLock<ServiceProxyOperations> = LazyLock::new(ServiceProxyOperations::new);
|
||||
static SERVICE_PROXY_OPERATIONS: ServiceProxyOperations = ServiceProxyOperations::new();
|
||||
|
||||
struct ServiceProxyOperations {
|
||||
guard: watch::Sender<Option<Arc<ServiceGuard>>>,
|
||||
guard_generation: AtomicU64,
|
||||
operation_lock: Mutex<()>,
|
||||
}
|
||||
|
||||
impl ServiceProxyOperations {
|
||||
fn new() -> Self {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
guard: watch::channel(None).0,
|
||||
guard_generation: AtomicU64::new(0),
|
||||
operation_lock: Mutex::const_new(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn invalidate_guard(&self) -> u64 {
|
||||
let mut generation = 0;
|
||||
self.guard.send_if_modified(|active| {
|
||||
generation = self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1);
|
||||
active.take().is_some()
|
||||
});
|
||||
generation
|
||||
}
|
||||
|
||||
fn start_guard(&self, guard: ServiceGuard) -> bool {
|
||||
self.guard.send_if_modified(|active| {
|
||||
if !guard_generation_is_current(&self.guard_generation, guard.generation) {
|
||||
return false;
|
||||
}
|
||||
*active = Some(Arc::new(guard));
|
||||
true
|
||||
})
|
||||
self.guard_generation.fetch_add(1, Ordering::AcqRel).wrapping_add(1)
|
||||
}
|
||||
|
||||
async fn run_service_operation<F, Fut, T>(&self, operation: F) -> T
|
||||
@@ -555,7 +531,7 @@ pub async fn clear() -> Result<()> {
|
||||
|
||||
/// A failed system call is usually a transient RPC hiccup, so give it a few tries.
|
||||
async fn clear_with_retry() -> Result<()> {
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
|
||||
@@ -630,90 +606,51 @@ pub async fn refresh_guard() -> Result<()> {
|
||||
let proxy = current_service_proxy_config(&verge).await?;
|
||||
let proof = service::active_service_session()?;
|
||||
let interval = Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30).max(1));
|
||||
static START_GUARD_MONITOR: Once = Once::new();
|
||||
START_GUARD_MONITOR.call_once(|| {
|
||||
let receiver = SERVICE_PROXY_OPERATIONS.guard.subscribe();
|
||||
AsyncHandler::spawn(move || {
|
||||
watch_task::run(receiver, monitor_guard, |guard| {
|
||||
let generation = guard.generation;
|
||||
logging!(
|
||||
error,
|
||||
Type::Core,
|
||||
"service proxy guard panicked (generation {generation})"
|
||||
);
|
||||
})
|
||||
});
|
||||
});
|
||||
if SERVICE_PROXY_OPERATIONS.start_guard(ServiceGuard {
|
||||
generation,
|
||||
proof,
|
||||
proxy,
|
||||
interval,
|
||||
}) {
|
||||
notification::retire_guard_failures();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct ServiceGuard {
|
||||
generation: u64,
|
||||
proof: Arc<OwnerSessionProof>,
|
||||
proxy: MacosProxyConfig,
|
||||
interval: Duration,
|
||||
}
|
||||
|
||||
async fn monitor_guard(guard: Arc<ServiceGuard>, mut updates: watch::Receiver<Option<Arc<ServiceGuard>>>) {
|
||||
let ServiceGuard {
|
||||
generation,
|
||||
proof,
|
||||
proxy,
|
||||
interval,
|
||||
} = guard.as_ref();
|
||||
let mut consecutive_failures = 0u32;
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = updates.changed() => return,
|
||||
() = tokio::time::sleep(*interval) => {}
|
||||
}
|
||||
|
||||
match SERVICE_PROXY_OPERATIONS
|
||||
.run_guard_request(
|
||||
*generation,
|
||||
proof,
|
||||
proxy,
|
||||
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
|
||||
service::active_service_session,
|
||||
|| service::set_system_proxy_by_service_with_session(proxy, proof),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(true) => consecutive_failures = 0,
|
||||
Ok(false) => {
|
||||
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
|
||||
return;
|
||||
}
|
||||
Err(error) if is_missing_network_service_failure(&error) => {
|
||||
consecutive_failures = 0;
|
||||
logging!(debug, Type::Core, "system proxy guard waits for a network service");
|
||||
}
|
||||
Err(error) => {
|
||||
consecutive_failures += 1;
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}",
|
||||
consecutive_failures,
|
||||
GUARD_FAILURES_BEFORE_STOPPING,
|
||||
error
|
||||
);
|
||||
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
|
||||
report_guard_stopped(*generation, &error).await;
|
||||
return;
|
||||
AsyncHandler::spawn(move || async move {
|
||||
let mut consecutive_failures = 0u32;
|
||||
loop {
|
||||
tokio::time::sleep(interval).await;
|
||||
match SERVICE_PROXY_OPERATIONS
|
||||
.run_guard_request(
|
||||
generation,
|
||||
&proof,
|
||||
&proxy,
|
||||
|| matches!(*CoreManager::global().get_running_mode(), RunningMode::Service),
|
||||
service::active_service_session,
|
||||
|| service::set_system_proxy_by_service_with_session(&proxy, &proof),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(true) => consecutive_failures = 0,
|
||||
Ok(false) => {
|
||||
logging!(debug, Type::Core, "proxy guard superseded (generation {generation})");
|
||||
break;
|
||||
}
|
||||
Err(error) if is_missing_network_service_failure(&error) => {
|
||||
consecutive_failures = 0;
|
||||
logging!(debug, Type::Core, "system proxy guard waits for a network service");
|
||||
}
|
||||
Err(error) => {
|
||||
consecutive_failures += 1;
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"failed to refresh system proxy through Service (generation {generation}, {}/{}): {:#}",
|
||||
consecutive_failures,
|
||||
GUARD_FAILURES_BEFORE_STOPPING,
|
||||
error
|
||||
);
|
||||
if consecutive_failures >= GUARD_FAILURES_BEFORE_STOPPING {
|
||||
report_guard_stopped(generation, &error).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
// Retire only after the replacement guard starts successfully.
|
||||
notification::retire_guard_failures();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const GUARD_FAILURES_BEFORE_STOPPING: u32 = 3;
|
||||
|
||||
@@ -1,40 +1,15 @@
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::Serialize;
|
||||
use tristr::alias::String;
|
||||
use tauri_plugin_mihomo::models::{
|
||||
DelayHistory, Proxies, Proxy, ProxyProvider, ProxyProviders, ProxyType, VehicleType,
|
||||
};
|
||||
|
||||
pub struct ProxyViewInput {
|
||||
pub runtime_group_order: Vec<String>,
|
||||
pub group_scopes: BTreeMap<String, GroupScope>,
|
||||
pub proxies: HashMap<String, ProxySnapshot>,
|
||||
pub providers: Option<HashMap<String, ProviderSnapshot>>,
|
||||
}
|
||||
|
||||
pub struct ProxySnapshot {
|
||||
pub name: String,
|
||||
pub proxy_type: String,
|
||||
pub all: Option<Vec<String>>,
|
||||
pub fixed: Option<String>,
|
||||
pub hidden: Option<bool>,
|
||||
pub icon: Option<String>,
|
||||
pub now: Option<String>,
|
||||
pub test_url: Option<String>,
|
||||
pub id: Option<String>,
|
||||
pub history: Vec<DelayHistory>,
|
||||
pub capabilities: ProxyCapabilities,
|
||||
}
|
||||
|
||||
pub struct ProviderSnapshot {
|
||||
pub vehicle_type: ProxyProviderVehicleType,
|
||||
pub proxies: Vec<ProxySnapshot>,
|
||||
pub updated_at: Option<String>,
|
||||
pub subscription_info: Option<ProxySubscriptionInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, specta::Type)]
|
||||
pub struct DelayHistory {
|
||||
pub time: String,
|
||||
pub delay: u16,
|
||||
pub proxies: Proxies,
|
||||
pub providers: Option<ProxyProviders>,
|
||||
}
|
||||
|
||||
/// The providers a group draws from (Mihomo order) and its `exclude-type` entries.
|
||||
@@ -87,7 +62,8 @@ pub struct ProxyCapabilities {
|
||||
pub struct ProxyGroupView {
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub proxy_type: String,
|
||||
#[specta(type = String)]
|
||||
pub proxy_type: ProxyType,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub now: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -98,6 +74,7 @@ pub struct ProxyGroupView {
|
||||
pub icon: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub test_url: Option<String>,
|
||||
#[specta(type = Vec<crate::ipc::DelayHistory>)]
|
||||
pub history: Vec<DelayHistory>,
|
||||
#[serde(flatten)]
|
||||
pub capabilities: ProxyCapabilities,
|
||||
@@ -110,7 +87,9 @@ pub struct ProxyNodeView {
|
||||
pub record_id: String,
|
||||
pub name: String,
|
||||
#[serde(rename = "type")]
|
||||
pub proxy_type: String,
|
||||
#[specta(type = String)]
|
||||
pub proxy_type: ProxyType,
|
||||
#[specta(type = Vec<crate::ipc::DelayHistory>)]
|
||||
pub history: Vec<DelayHistory>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<String>,
|
||||
@@ -221,13 +200,12 @@ impl<'a> MemberResolver<'a> {
|
||||
.flat_map(|provider| candidates.iter().filter(move |(owner, _)| owner == provider))
|
||||
.map(|(_, record_id)| record_id)
|
||||
.filter(|record_id| {
|
||||
scope.exclude_types.is_empty()
|
||||
|| !self.records.get(*record_id).is_some_and(|node| {
|
||||
scope
|
||||
.exclude_types
|
||||
.iter()
|
||||
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
|
||||
})
|
||||
!self.records.get(*record_id).is_some_and(|node| {
|
||||
scope
|
||||
.exclude_types
|
||||
.iter()
|
||||
.any(|excluded| excluded.eq_ignore_ascii_case(node.proxy_type.as_str()))
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -292,7 +270,7 @@ impl ProxyViewBuilder {
|
||||
|
||||
let global = core_groups
|
||||
.remove("GLOBAL")
|
||||
.map(|proxy| build_group("GLOBAL".into(), proxy, &resolver));
|
||||
.map(|proxy| build_group("GLOBAL".to_owned(), proxy, &resolver));
|
||||
let (groups, order_source) = build_ordered_groups(core_groups, runtime_group_order, &resolver);
|
||||
let direct = core_node_ids.get("DIRECT").cloned();
|
||||
let standalone = build_standalone(&core_node_ids);
|
||||
@@ -311,13 +289,11 @@ impl ProxyViewBuilder {
|
||||
}
|
||||
}
|
||||
|
||||
fn partition_core(
|
||||
proxies: HashMap<String, ProxySnapshot>,
|
||||
) -> (BTreeMap<String, ProxySnapshot>, BTreeMap<String, ProxySnapshot>) {
|
||||
fn partition_core(proxies: Proxies) -> (BTreeMap<String, Proxy>, BTreeMap<String, Proxy>) {
|
||||
let mut groups = BTreeMap::new();
|
||||
let mut nodes = BTreeMap::new();
|
||||
|
||||
for (name, proxy) in proxies {
|
||||
for (name, proxy) in proxies.proxies {
|
||||
if proxy.all.is_some() {
|
||||
groups.insert(name, proxy);
|
||||
} else {
|
||||
@@ -329,13 +305,13 @@ fn partition_core(
|
||||
}
|
||||
|
||||
fn build_core_records(
|
||||
core_nodes: BTreeMap<String, ProxySnapshot>,
|
||||
core_nodes: BTreeMap<String, Proxy>,
|
||||
) -> (BTreeMap<String, ProxyNodeView>, BTreeMap<String, String>) {
|
||||
let mut records = BTreeMap::new();
|
||||
let mut ids = BTreeMap::new();
|
||||
|
||||
for (index, (name, proxy)) in core_nodes.into_iter().enumerate() {
|
||||
let record_id: String = format!("c:{index}").into();
|
||||
let record_id = format!("c:{index}");
|
||||
ids.insert(name.clone(), record_id.clone());
|
||||
records.insert(
|
||||
record_id.clone(),
|
||||
@@ -352,25 +328,32 @@ fn build_core_records(
|
||||
}
|
||||
|
||||
fn build_provider_records(
|
||||
providers: Option<HashMap<String, ProviderSnapshot>>,
|
||||
providers: Option<ProxyProviders>,
|
||||
records: &mut BTreeMap<String, ProxyNodeView>,
|
||||
) -> (Vec<ProxyProviderView>, ProviderCandidates) {
|
||||
let providers = providers.map_or_default(|providers| providers.into_iter().collect::<BTreeMap<_, _>>());
|
||||
let providers = providers.map_or_default(|providers| providers.providers.into_iter().collect::<BTreeMap<_, _>>());
|
||||
let mut views = Vec::new();
|
||||
let mut candidates = BTreeMap::new();
|
||||
|
||||
for (provider_name, provider) in providers {
|
||||
let ProviderSnapshot {
|
||||
let ProxyProvider {
|
||||
vehicle_type,
|
||||
proxies,
|
||||
updated_at,
|
||||
subscription_info,
|
||||
..
|
||||
} = provider;
|
||||
let vehicle_type = match vehicle_type {
|
||||
VehicleType::HTTP => ProxyProviderVehicleType::Http,
|
||||
VehicleType::File => ProxyProviderVehicleType::File,
|
||||
VehicleType::Inline => ProxyProviderVehicleType::Inline,
|
||||
_ => continue,
|
||||
};
|
||||
let provider_index = views.len();
|
||||
let mut proxy_record_ids = Vec::new();
|
||||
|
||||
for (member_index, proxy) in proxies.into_iter().enumerate() {
|
||||
let record_id: String = format!("p:{provider_index}:{member_index}").into();
|
||||
let record_id = format!("p:{provider_index}:{member_index}");
|
||||
let proxy_name = proxy.name.clone();
|
||||
let node_name = proxy.name.clone();
|
||||
candidates
|
||||
@@ -396,7 +379,12 @@ fn build_provider_records(
|
||||
name: provider_name,
|
||||
vehicle_type,
|
||||
updated_at,
|
||||
subscription_info,
|
||||
subscription_info: subscription_info.map(|subscription_info| ProxySubscriptionInfo {
|
||||
upload: subscription_info.upload,
|
||||
download: subscription_info.download,
|
||||
total: subscription_info.total,
|
||||
expire: subscription_info.expire,
|
||||
}),
|
||||
proxy_record_ids,
|
||||
});
|
||||
}
|
||||
@@ -404,8 +392,8 @@ fn build_provider_records(
|
||||
(views, candidates)
|
||||
}
|
||||
|
||||
fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>) -> ProxyGroupView {
|
||||
let ProxySnapshot {
|
||||
fn build_group(name: String, proxy: Proxy, resolver: &MemberResolver<'_>) -> ProxyGroupView {
|
||||
let Proxy {
|
||||
all,
|
||||
fixed,
|
||||
hidden,
|
||||
@@ -413,7 +401,11 @@ fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>
|
||||
now,
|
||||
test_url,
|
||||
history,
|
||||
capabilities,
|
||||
udp,
|
||||
xudp,
|
||||
tfo,
|
||||
mptcp,
|
||||
smux,
|
||||
proxy_type,
|
||||
..
|
||||
} = proxy;
|
||||
@@ -441,19 +433,29 @@ fn build_group(name: String, proxy: ProxySnapshot, resolver: &MemberResolver<'_>
|
||||
icon,
|
||||
test_url,
|
||||
history,
|
||||
capabilities,
|
||||
capabilities: ProxyCapabilities {
|
||||
udp,
|
||||
xudp,
|
||||
tfo,
|
||||
mptcp,
|
||||
smux,
|
||||
},
|
||||
members,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: ProxyNodeSource) -> ProxyNodeView {
|
||||
let ProxySnapshot {
|
||||
fn build_node(record_id: String, name: String, proxy: Proxy, source: ProxyNodeSource) -> ProxyNodeView {
|
||||
let Proxy {
|
||||
id,
|
||||
hidden,
|
||||
icon,
|
||||
test_url,
|
||||
history,
|
||||
capabilities,
|
||||
udp,
|
||||
xudp,
|
||||
tfo,
|
||||
mptcp,
|
||||
smux,
|
||||
proxy_type,
|
||||
..
|
||||
} = proxy;
|
||||
@@ -467,13 +469,19 @@ fn build_node(record_id: String, name: String, proxy: ProxySnapshot, source: Pro
|
||||
hidden,
|
||||
icon,
|
||||
test_url,
|
||||
capabilities,
|
||||
capabilities: ProxyCapabilities {
|
||||
udp,
|
||||
xudp,
|
||||
tfo,
|
||||
mptcp,
|
||||
smux,
|
||||
},
|
||||
source,
|
||||
}
|
||||
}
|
||||
|
||||
fn build_ordered_groups(
|
||||
mut core_groups: BTreeMap<String, ProxySnapshot>,
|
||||
mut core_groups: BTreeMap<String, Proxy>,
|
||||
runtime_group_order: Vec<String>,
|
||||
resolver: &MemberResolver<'_>,
|
||||
) -> (Vec<ProxyGroupView>, ProxyViewOrderSource) {
|
||||
@@ -93,7 +93,9 @@ impl RunStateEnv for RealEnv {
|
||||
|
||||
fn publish(&self, state: &RunState) {
|
||||
// Reconciliation must run before the app handle exists and must not block this transition.
|
||||
crate::feat::request_tun_reconciliation();
|
||||
crate::process::AsyncHandler::spawn(|| async {
|
||||
crate::feat::reconcile_tun_availability().await;
|
||||
});
|
||||
|
||||
let Some(app_handle) = crate::APP_HANDLE.get() else {
|
||||
return;
|
||||
|
||||
@@ -9,7 +9,10 @@ mod owner;
|
||||
mod probe;
|
||||
|
||||
use std::{
|
||||
sync::{Arc, LazyLock},
|
||||
sync::{
|
||||
Arc, LazyLock,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
@@ -54,7 +57,6 @@ impl std::fmt::Display for ReadyWaitError {
|
||||
#[derive(Debug, Default)]
|
||||
struct VersionedService {
|
||||
service: StoredService,
|
||||
operation_running: bool,
|
||||
generation: u64,
|
||||
observation: u64,
|
||||
}
|
||||
@@ -77,6 +79,7 @@ pub struct RunStateStore<E: RunStateEnv> {
|
||||
env: E,
|
||||
service: Mutex<VersionedService>,
|
||||
mode: ArcSwap<RunningMode>,
|
||||
operation_running: AtomicBool,
|
||||
operation_done: Notify,
|
||||
}
|
||||
|
||||
@@ -86,6 +89,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
env,
|
||||
service: Mutex::new(VersionedService::default()),
|
||||
mode: ArcSwap::new(Arc::new(RunningMode::NotRunning)),
|
||||
operation_running: AtomicBool::new(false),
|
||||
operation_done: Notify::new(),
|
||||
}
|
||||
}
|
||||
@@ -93,18 +97,8 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
/// The last known Run State, without waiting and without probing.
|
||||
/// It reports when a privileged operation may make the snapshot stale.
|
||||
pub fn state(&self) -> RunState {
|
||||
let (service, op_in_flight) = {
|
||||
let state = self.service.lock();
|
||||
(state.service.clone(), state.operation_running)
|
||||
};
|
||||
RunState {
|
||||
health: service.health,
|
||||
pending: service.pending,
|
||||
sidecar_allowed: service.sidecar_allowed,
|
||||
mode: *self.mode.load().as_ref(),
|
||||
is_admin: self.env.is_elevated(),
|
||||
op_in_flight,
|
||||
}
|
||||
let service = self.service.lock().service.clone();
|
||||
self.snapshot(service)
|
||||
}
|
||||
|
||||
/// Returns one snapshot taken after any operation visible in that snapshot has settled.
|
||||
@@ -135,7 +129,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
|
||||
/// Retries transport failures but stops at the first readable reply, including a rejection.
|
||||
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| {
|
||||
ReadyWaitError::Unreachable(anyhow::anyhow!(
|
||||
"service readiness wait was configured with no attempts"
|
||||
@@ -315,7 +309,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
/// Accepts Sidecar only while the Service is unusable and no conflicting operation is active.
|
||||
pub fn allow_sidecar_for_session(&self) -> Result<()> {
|
||||
let mut state = self.service.lock();
|
||||
if state.operation_running {
|
||||
if self.operation_running.load(Ordering::Acquire) {
|
||||
bail!("service operation already running");
|
||||
}
|
||||
let permitted = match (state.service.pending, state.service.sidecar_allowed) {
|
||||
@@ -339,7 +333,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn allow_sidecar_after_service_refusal(&self, reason: String) -> Result<()> {
|
||||
let mut state = self.service.lock();
|
||||
if state.operation_running || state.service.pending.is_some() {
|
||||
if self.operation_running.load(Ordering::Acquire) || state.service.pending.is_some() {
|
||||
bail!("cannot fall back while a service operation is pending");
|
||||
}
|
||||
// Publish the refusal and allowance together so it never asks the UI for a repair.
|
||||
@@ -354,7 +348,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
/// Requests installation only for a confirmed absent Service.
|
||||
pub fn require_install_for_session(&self) -> Result<()> {
|
||||
let mut state = self.service.lock();
|
||||
if state.operation_running {
|
||||
if self.operation_running.load(Ordering::Acquire) {
|
||||
bail!("service operation already running");
|
||||
}
|
||||
if state.service.pending.is_none()
|
||||
@@ -433,10 +427,9 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
/// Only one privileged operation may be in flight; [`Self::settled`] waits on this.
|
||||
pub fn begin_operation(&self) -> Result<OperationGuard<'_, E>> {
|
||||
let mut state = self.service.lock();
|
||||
if state.operation_running {
|
||||
if self.operation_running.swap(true, Ordering::AcqRel) {
|
||||
bail!("service operation already running");
|
||||
}
|
||||
state.operation_running = true;
|
||||
state.bump();
|
||||
drop(state);
|
||||
self.announce();
|
||||
@@ -445,7 +438,7 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn operation_in_flight(&self) -> bool {
|
||||
self.service.lock().operation_running
|
||||
self.operation_running.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -462,6 +455,17 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
||||
fn announce(&self) {
|
||||
self.env.publish(&self.state());
|
||||
}
|
||||
|
||||
fn snapshot(&self, service: StoredService) -> RunState {
|
||||
RunState {
|
||||
health: service.health,
|
||||
pending: service.pending,
|
||||
sidecar_allowed: service.sidecar_allowed,
|
||||
mode: *self.mode.load().as_ref(),
|
||||
is_admin: self.env.is_elevated(),
|
||||
op_in_flight: self.operation_running.load(Ordering::Acquire),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases the privileged-operation slot and wakes everything waiting in [`RunStateStore::settled`].
|
||||
@@ -472,7 +476,7 @@ pub struct OperationGuard<'a, E: RunStateEnv> {
|
||||
|
||||
impl<E: RunStateEnv> Drop for OperationGuard<'_, E> {
|
||||
fn drop(&mut self) {
|
||||
self.store.service.lock().operation_running = false;
|
||||
self.store.operation_running.store(false, Ordering::Release);
|
||||
self.store.operation_done.notify_waiters();
|
||||
self.store.announce();
|
||||
}
|
||||
|
||||
+105
-105
@@ -1,15 +1,12 @@
|
||||
mod error;
|
||||
|
||||
pub use error::RuntimeBundleError;
|
||||
|
||||
use anyhow::{Context as _, Result, bail};
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_service_ipc::{RemoteProvider, RuntimeAsset, RuntimeBundle};
|
||||
use serde_yaml_ng::{Mapping, Value};
|
||||
use sha2::{Digest as _, Sha256};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::{Component, Path, PathBuf, Prefix};
|
||||
use tristr::TriStr;
|
||||
|
||||
pub const GEO_ASSETS: &[&str] = &[
|
||||
pub(crate) const GEO_ASSETS: &[&str] = &[
|
||||
"Country.mmdb",
|
||||
"ASN.mmdb",
|
||||
"geoip.dat",
|
||||
@@ -20,42 +17,41 @@ pub const GEO_ASSETS: &[&str] = &[
|
||||
|
||||
/// Provider identity used by the runtime config and core API.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RemoteProviderRef {
|
||||
pub(crate) struct RemoteProviderRef {
|
||||
pub section: &'static str,
|
||||
pub name: String,
|
||||
pub destination: TriStr,
|
||||
pub url: String,
|
||||
pub provider: RemoteProvider,
|
||||
}
|
||||
|
||||
pub struct RuntimeAsset {
|
||||
pub source: String,
|
||||
pub destination: TriStr,
|
||||
struct RuntimeParts {
|
||||
config: Value,
|
||||
assets: Vec<RuntimeAsset>,
|
||||
remote_providers: Vec<RemoteProviderRef>,
|
||||
}
|
||||
|
||||
pub struct RuntimeBundlePlan {
|
||||
pub config: Value,
|
||||
pub assets: Vec<RuntimeAsset>,
|
||||
pub remote_providers: Vec<RemoteProviderRef>,
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, RuntimeBundleError>;
|
||||
|
||||
pub async fn collect_runtime_bundle(config_file: &Path) -> Result<RuntimeBundlePlan> {
|
||||
pub(crate) async fn collect_runtime_bundle(config_file: &Path, core_path: &Path) -> Result<RuntimeBundle> {
|
||||
let yaml = tokio::fs::read_to_string(config_file)
|
||||
.await
|
||||
.map_err(|source| RuntimeBundleError::ReadConfig {
|
||||
path: config_file.to_owned(),
|
||||
source,
|
||||
})?;
|
||||
let config: Value = serde_yaml_ng::from_str(&yaml).map_err(|source| RuntimeBundleError::ParseConfig {
|
||||
path: config_file.to_owned(),
|
||||
source,
|
||||
})?;
|
||||
let config_root = config_file.parent().ok_or(RuntimeBundleError::MissingConfigDirectory)?;
|
||||
collect_runtime_parts(config, config_root)
|
||||
.with_context(|| format!("failed to read runtime config {config_file:?}"))?;
|
||||
let config: Value =
|
||||
serde_yaml_ng::from_str(&yaml).with_context(|| format!("failed to parse runtime config {config_file:?}"))?;
|
||||
let config_root = config_file
|
||||
.parent()
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime config has no parent directory"))?;
|
||||
let parts = collect_runtime_parts(config, config_root)?;
|
||||
Ok(RuntimeBundle {
|
||||
yaml: serde_yaml_ng::to_string(&parts.config).context("failed to serialize service runtime config")?,
|
||||
assets: parts.assets,
|
||||
remote_providers: parts
|
||||
.remote_providers
|
||||
.into_iter()
|
||||
.map(|declared| declared.provider)
|
||||
.collect(),
|
||||
core_path: core_path.to_string_lossy().into_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
|
||||
pub(crate) fn remote_providers_of(config: &Mapping, config_root: &Path) -> Result<Vec<RemoteProviderRef>> {
|
||||
Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers)
|
||||
}
|
||||
|
||||
@@ -65,10 +61,10 @@ struct ProviderPathOwners {
|
||||
local: bool,
|
||||
}
|
||||
|
||||
pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> {
|
||||
pub(crate) fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path) -> Result<()> {
|
||||
let config_root = std::fs::canonicalize(config_root)?;
|
||||
let mut paths = BTreeMap::<TriStr, ProviderPathOwners>::new();
|
||||
let mut reserved: HashSet<TriStr> = GEO_ASSETS.iter().copied().map(TriStr::from).collect();
|
||||
let mut paths = BTreeMap::<String, ProviderPathOwners>::new();
|
||||
let mut reserved: HashSet<String> = GEO_ASSETS.iter().map(|name| (*name).to_owned()).collect();
|
||||
for section in ["proxy-providers", "rule-providers"] {
|
||||
let Some(providers) = config.get(section).and_then(Value::as_mapping) else {
|
||||
continue;
|
||||
@@ -88,7 +84,6 @@ pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path)
|
||||
let Ok(destination) = destination else {
|
||||
continue;
|
||||
};
|
||||
let destination = TriStr::from(destination.as_str());
|
||||
reserved.insert(destination.clone());
|
||||
let owners = paths.entry(destination).or_default();
|
||||
match (is_remote, provider.get("url").and_then(Value::as_str)) {
|
||||
@@ -122,12 +117,12 @@ pub fn resolve_provider_path_conflicts(config: &mut Mapping, config_root: &Path)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet<TriStr>) -> String {
|
||||
fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut HashSet<String>) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(destination.as_bytes());
|
||||
digest.update([0]);
|
||||
digest.update(url.as_bytes());
|
||||
let digest = hex::encode(digest.finalize());
|
||||
let digest: String = crate::utils::help::hex_encode(&digest.finalize());
|
||||
let path = Path::new(destination);
|
||||
let extension = path
|
||||
.extension()
|
||||
@@ -139,7 +134,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
|
||||
.with_file_name(format!("cvr-{digest}{suffix}{extension}"))
|
||||
.to_string_lossy()
|
||||
.replace('\\', "/");
|
||||
if reserved.insert(TriStr::from(candidate.as_str())) {
|
||||
if reserved.insert(candidate.clone()) {
|
||||
return candidate;
|
||||
}
|
||||
sequence += 1;
|
||||
@@ -147,7 +142,7 @@ fn allocate_provider_destination(destination: &str, url: &str, reserved: &mut Ha
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeBundlePlan> {
|
||||
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeParts> {
|
||||
let config_root = std::fs::canonicalize(config_root)?;
|
||||
let mut assets = Vec::new();
|
||||
let mut destinations = HashSet::new();
|
||||
@@ -172,15 +167,15 @@ fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<Runtim
|
||||
collect_ssh_private_keys(&mut config, &config_root, &mut destinations, &mut assets);
|
||||
for filename in GEO_ASSETS {
|
||||
let source = config_root.join(filename);
|
||||
if source.is_file() && destinations.insert(TriStr::from(*filename)) {
|
||||
if source.is_file() && destinations.insert((*filename).to_string()) {
|
||||
assets.push(RuntimeAsset {
|
||||
source: std::fs::canonicalize(&source)?.to_string_lossy().into_owned(),
|
||||
destination: (*filename).into(),
|
||||
destination: (*filename).to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RuntimeBundlePlan {
|
||||
Ok(RuntimeParts {
|
||||
config,
|
||||
assets,
|
||||
remote_providers,
|
||||
@@ -193,7 +188,7 @@ fn collect_provider_assets(
|
||||
config: &mut Value,
|
||||
section: &'static str,
|
||||
config_root: &Path,
|
||||
destinations: &mut HashSet<TriStr>,
|
||||
destinations: &mut HashSet<String>,
|
||||
assets: &mut Vec<RuntimeAsset>,
|
||||
remote_providers: &mut Vec<RemoteProviderRef>,
|
||||
) -> Result<()> {
|
||||
@@ -219,22 +214,26 @@ fn collect_provider_assets(
|
||||
(true, Some(url)) => {
|
||||
let destination = provider_destination(config_root, raw_path)?;
|
||||
// Reserve remote destinations too; copied and downloaded files must not collide.
|
||||
let reserved = TriStr::from(destination.as_str());
|
||||
if destinations.insert(reserved.clone()) {
|
||||
remote_providers.push(RemoteProviderRef {
|
||||
section,
|
||||
name: name.as_str().unwrap_or_default().to_owned(),
|
||||
destination: reserved,
|
||||
url,
|
||||
});
|
||||
} else {
|
||||
match remote_providers
|
||||
.iter()
|
||||
.find(|declared| declared.destination == destination)
|
||||
{
|
||||
Some(declared) if declared.url == url => {}
|
||||
Some(_) => return Err(RuntimeBundleError::DifferentSources(destination)),
|
||||
None => return Err(RuntimeBundleError::DuplicateDestination(destination)),
|
||||
match remote_providers
|
||||
.iter()
|
||||
.find(|declared| declared.provider.destination == destination)
|
||||
{
|
||||
Some(declared) if declared.provider.url == url => {}
|
||||
Some(_) => {
|
||||
bail!("runtime provider destination {destination:?} is declared for two different sources")
|
||||
}
|
||||
None => {
|
||||
if !destinations.insert(destination.clone()) {
|
||||
bail!("runtime provider destination {destination:?} is claimed more than once");
|
||||
}
|
||||
remote_providers.push(RemoteProviderRef {
|
||||
section,
|
||||
name: name.as_str().unwrap_or_default().to_owned(),
|
||||
provider: RemoteProvider {
|
||||
destination: destination.clone(),
|
||||
url,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
destination
|
||||
@@ -257,11 +256,10 @@ fn collect_provider_assets(
|
||||
continue;
|
||||
};
|
||||
let destination = destination_below_root(config_root, &source)?;
|
||||
let reserved = TriStr::from(destination.as_str());
|
||||
if destinations.insert(reserved.clone()) {
|
||||
if destinations.insert(destination.clone()) {
|
||||
assets.push(RuntimeAsset {
|
||||
source: source.to_string_lossy().into_owned(),
|
||||
destination: reserved,
|
||||
destination: destination.clone(),
|
||||
});
|
||||
}
|
||||
destination
|
||||
@@ -276,7 +274,7 @@ fn collect_provider_assets(
|
||||
fn collect_ssh_private_keys(
|
||||
config: &mut Value,
|
||||
config_root: &Path,
|
||||
destinations: &mut HashSet<TriStr>,
|
||||
destinations: &mut HashSet<String>,
|
||||
assets: &mut Vec<RuntimeAsset>,
|
||||
) {
|
||||
let Some(config) = config.as_mapping_mut() else {
|
||||
@@ -327,7 +325,7 @@ fn collect_ssh_private_keys(
|
||||
let destination = allocate_provider_destination("ssh-private-key", &source, destinations);
|
||||
assets.push(RuntimeAsset {
|
||||
source,
|
||||
destination: TriStr::from(destination.as_str()),
|
||||
destination: destination.clone(),
|
||||
});
|
||||
proxy.insert(Value::String("private-key".to_owned()), Value::String(destination));
|
||||
}
|
||||
@@ -349,13 +347,10 @@ fn local_provider_source(config_root: &Path, raw_path: &str) -> Result<PathBuf>
|
||||
config_root.join(path)
|
||||
};
|
||||
let canonical_source =
|
||||
std::fs::canonicalize(&source).map_err(|error| RuntimeBundleError::LocalProviderUnavailable {
|
||||
path: source,
|
||||
source: error,
|
||||
})?;
|
||||
std::fs::canonicalize(&source).with_context(|| format!("local runtime provider is unavailable: {source:?}"))?;
|
||||
canonical_source
|
||||
.strip_prefix(config_root)
|
||||
.map_err(|_| RuntimeBundleError::LocalProviderOutsideRoot(canonical_source.clone()))?;
|
||||
.map_err(|_| anyhow::anyhow!("local runtime provider is outside the config root: {canonical_source:?}"))?;
|
||||
Ok(canonical_source)
|
||||
}
|
||||
|
||||
@@ -365,7 +360,7 @@ fn provider_destination(config_root: &Path, raw_path: &str) -> Result<String> {
|
||||
.components()
|
||||
.any(|component| matches!(component, Component::ParentDir))
|
||||
{
|
||||
return Err(RuntimeBundleError::DestinationOutsideRuntime);
|
||||
bail!("runtime provider destination traverses outside the runtime");
|
||||
}
|
||||
if path.is_absolute() {
|
||||
let normalized = canonicalize_with_missing_tail(path)?;
|
||||
@@ -381,11 +376,11 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
|
||||
while !ancestor.exists() {
|
||||
let name = ancestor
|
||||
.file_name()
|
||||
.ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?;
|
||||
tail.push(name.to_owned());
|
||||
ancestor = ancestor
|
||||
.parent()
|
||||
.ok_or_else(|| RuntimeBundleError::MissingAncestor(path.to_owned()))?;
|
||||
.ok_or_else(|| anyhow::anyhow!("runtime provider path has no existing ancestor: {path:?}"))?;
|
||||
}
|
||||
let mut normalized = std::fs::canonicalize(ancestor)?;
|
||||
for component in tail.iter().rev() {
|
||||
@@ -397,7 +392,7 @@ fn canonicalize_with_missing_tail(path: &Path) -> Result<PathBuf> {
|
||||
fn destination_below_root(config_root: &Path, path: &Path) -> Result<String> {
|
||||
let relative = path
|
||||
.strip_prefix(config_root)
|
||||
.map_err(|_| RuntimeBundleError::ProviderOutsideRoot(path.to_owned()))?;
|
||||
.map_err(|_| anyhow::anyhow!("runtime provider path is outside the config root: {path:?}"))?;
|
||||
normalized_destination(relative)
|
||||
}
|
||||
|
||||
@@ -407,11 +402,11 @@ fn normalized_destination(relative: &Path) -> Result<String> {
|
||||
match component {
|
||||
Component::Normal(component) => destination.push(component),
|
||||
Component::CurDir => {}
|
||||
_ => return Err(RuntimeBundleError::LocalDestinationOutsideRuntime),
|
||||
_ => bail!("local runtime provider destination traverses outside the runtime"),
|
||||
}
|
||||
}
|
||||
if destination.as_os_str().is_empty() {
|
||||
return Err(RuntimeBundleError::EmptyDestination);
|
||||
bail!("local runtime provider destination is empty");
|
||||
}
|
||||
Ok(destination.to_string_lossy().replace('\\', "/"))
|
||||
}
|
||||
@@ -421,8 +416,7 @@ mod tests {
|
||||
use super::{collect_runtime_bundle, remote_providers_of, resolve_provider_path_conflicts};
|
||||
|
||||
#[tokio::test]
|
||||
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
async fn conflicting_sources_get_separate_paths_in_config_bundle_and_readback() -> anyhow::Result<()> {
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-provider-paths-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&root)?;
|
||||
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
||||
@@ -439,7 +433,7 @@ mod tests {
|
||||
resolve_provider_path_conflicts(&mut config, &root)?;
|
||||
let config_file = root.join("config.yaml");
|
||||
std::fs::write(&config_file, serde_yaml_ng::to_string(&config)?)?;
|
||||
let bundle = collect_runtime_bundle(&config_file).await?;
|
||||
let bundle = collect_runtime_bundle(&config_file, &root.join("mihomo")).await?;
|
||||
let paths = &config["rule-providers"];
|
||||
assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]);
|
||||
resolve_provider_path_conflicts(&mut reordered, &root)?;
|
||||
@@ -454,14 +448,14 @@ mod tests {
|
||||
"resolving an already generated config must be idempotent"
|
||||
);
|
||||
|
||||
assert_eq!(bundle.config.as_mapping(), Some(&config));
|
||||
assert_eq!(serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&bundle.yaml)?, config);
|
||||
let readback = remote_providers_of(&config, &root)?;
|
||||
assert_eq!(bundle.remote_providers.len(), 2);
|
||||
for declared in readback {
|
||||
assert!(bundle.remote_providers.contains(&declared));
|
||||
assert!(bundle.remote_providers.contains(&declared.provider));
|
||||
assert_eq!(
|
||||
config[declared.section][&declared.name]["path"],
|
||||
declared.destination.as_str()
|
||||
declared.provider.destination
|
||||
);
|
||||
assert_eq!(
|
||||
config[declared.section][&declared.name]["url"],
|
||||
@@ -473,8 +467,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn allocated_provider_paths_do_not_claim_another_declared_path()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
fn allocated_provider_paths_do_not_claim_another_declared_path() -> anyhow::Result<()> {
|
||||
let root = std::env::temp_dir();
|
||||
let original: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
||||
"proxy-providers:\n a:\n type: http\n url: https://one.example/p.yaml\n path: ./providers/shared.yaml\nrule-providers:\n b:\n type: http\n url: https://two.example/r.yaml\n path: ./providers/shared.yaml\n",
|
||||
@@ -496,8 +489,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
fn provider_path_resolution_leaves_shared_sources_and_local_files_unchanged() -> anyhow::Result<()> {
|
||||
let mut config: serde_yaml_ng::Mapping = serde_yaml_ng::from_str(
|
||||
"rule-providers:\n a:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n b:\n type: http\n url: https://one.example/r.yaml\n path: ./rules/shared.yaml\n local:\n type: file\n path: ./rules/local.yaml\n remote:\n type: http\n url: https://two.example/r.yaml\n path: ./rules/local.yaml\n mirror:\n type: http\n url: https://three.example/r.yaml\n path: ./rules/local.yaml\n",
|
||||
)?;
|
||||
@@ -508,8 +500,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn collects_only_local_providers_and_existing_geo_assets()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
async fn collects_only_local_providers_and_existing_geo_assets() -> anyhow::Result<()> {
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-{}", std::process::id()));
|
||||
std::fs::create_dir_all(root.join("providers"))?;
|
||||
std::fs::write(root.join("providers/local.yaml"), b"proxies: []\n")?;
|
||||
@@ -525,10 +516,12 @@ mod tests {
|
||||
absolute_remote.display()
|
||||
),
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let bundle = collect_runtime_bundle(&config).await?;
|
||||
let bundle = collect_runtime_bundle(&config, &core).await?;
|
||||
|
||||
let bundled_config = &bundle.config;
|
||||
let bundled_config: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?;
|
||||
assert_eq!(
|
||||
bundled_config["proxy-providers"]["local"]["path"].as_str(),
|
||||
Some("providers/local.yaml")
|
||||
@@ -537,7 +530,7 @@ mod tests {
|
||||
bundled_config["proxy-providers"]["remote"]["path"].as_str(),
|
||||
Some("providers/remote.yaml")
|
||||
);
|
||||
assert!(!serde_yaml_ng::to_string(bundled_config)?.contains(root.to_string_lossy().as_ref()));
|
||||
assert!(!bundle.yaml.contains(&root.to_string_lossy().into_owned()));
|
||||
assert!(
|
||||
bundle
|
||||
.assets
|
||||
@@ -567,8 +560,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn two_names_for_one_remote_file_are_folded_rather_than_refused()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
async fn two_names_for_one_remote_file_are_folded_rather_than_refused() -> anyhow::Result<()> {
|
||||
// Identical repeats are one service-side file and are safe to fold.
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-bundle-dup-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
@@ -578,8 +570,10 @@ mod tests {
|
||||
&config,
|
||||
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n",
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let bundle = collect_runtime_bundle(&config).await?;
|
||||
let bundle = collect_runtime_bundle(&config, &core).await?;
|
||||
|
||||
assert_eq!(bundle.remote_providers.len(), 1, "one file, declared twice");
|
||||
assert_eq!(bundle.remote_providers[0].destination, "rules/x.yaml");
|
||||
@@ -588,7 +582,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn two_sources_for_one_remote_file_are_refused() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
async fn two_sources_for_one_remote_file_are_refused() -> anyhow::Result<()> {
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-bundle-conflict-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root)?;
|
||||
@@ -597,9 +591,11 @@ mod tests {
|
||||
&config,
|
||||
"rule-providers:\n a:\n type: http\n url: https://one.example/x.yaml\n path: ./rules/x.yaml\n b:\n type: http\n url: https://two.example/x.yaml\n path: ./rules/x.yaml\n",
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let Err(error) = collect_runtime_bundle(&config).await else {
|
||||
return Err("two sources cannot own one file".into());
|
||||
let Err(error) = collect_runtime_bundle(&config, &core).await else {
|
||||
anyhow::bail!("two sources cannot own one file");
|
||||
};
|
||||
|
||||
assert!(error.to_string().contains("two different sources"), "{error}");
|
||||
@@ -608,8 +604,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle()
|
||||
-> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
async fn an_odd_provider_is_left_alone_instead_of_failing_the_whole_bundle() -> anyhow::Result<()> {
|
||||
// Odd providers accepted by mihomo must not block the rest of the bundle.
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-bundle-odd-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
@@ -619,8 +614,10 @@ mod tests {
|
||||
&config,
|
||||
"rule-providers:\n nourl:\n type: http\n path: ./rules/nourl.yaml\n missing:\n type: inline\n url: https://one.example/i.yaml\n path: ./rules/missing.yaml\n good:\n type: http\n url: https://one.example/g.yaml\n path: ./rules/g.yaml\n",
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let bundle = collect_runtime_bundle(&config).await?;
|
||||
let bundle = collect_runtime_bundle(&config, &core).await?;
|
||||
|
||||
assert_eq!(
|
||||
bundle.remote_providers.len(),
|
||||
@@ -628,8 +625,9 @@ mod tests {
|
||||
"only the provider that could be classified is declared"
|
||||
);
|
||||
assert_eq!(bundle.remote_providers[0].destination, "rules/g.yaml");
|
||||
let reserialized: serde_yaml_ng::Value = serde_yaml_ng::from_str(&bundle.yaml)?;
|
||||
assert_eq!(
|
||||
bundle.config["rule-providers"]["nourl"]["path"].as_str(),
|
||||
reserialized["rule-providers"]["nourl"]["path"].as_str(),
|
||||
Some("./rules/nourl.yaml"),
|
||||
"an unclassifiable provider keeps the path the core was given"
|
||||
);
|
||||
@@ -638,13 +636,13 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rejects_provider_paths_outside_the_config_root() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
async fn rejects_provider_paths_outside_the_config_root() -> anyhow::Result<()> {
|
||||
let root = std::env::temp_dir().join(format!("clash-verge-runtime-bundle-outside-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&root)?;
|
||||
let config = root.join("config.yaml");
|
||||
let outside = root
|
||||
.parent()
|
||||
.ok_or("test root has no parent")?
|
||||
.ok_or_else(|| anyhow::anyhow!("test root has no parent"))?
|
||||
.join(format!("outside-{}.yaml", std::process::id()));
|
||||
std::fs::write(
|
||||
&config,
|
||||
@@ -653,9 +651,11 @@ mod tests {
|
||||
outside.display()
|
||||
),
|
||||
)?;
|
||||
let core = root.join("mihomo");
|
||||
std::fs::write(&core, b"core")?;
|
||||
|
||||
let Err(error) = collect_runtime_bundle(&config).await else {
|
||||
return Err("outside provider path must be rejected".into());
|
||||
let Err(error) = collect_runtime_bundle(&config, &core).await else {
|
||||
anyhow::bail!("outside provider path must be rejected");
|
||||
};
|
||||
|
||||
assert!(error.to_string().contains("outside the config root"));
|
||||
+110
-175
@@ -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,
|
||||
@@ -13,6 +13,7 @@ use crate::{
|
||||
CORE_REJECTED_PREFIX, OwnerRecoveryReason, OwnerSample, OwnerStep, OwnerWatch, PendingAction, RUN_STATE,
|
||||
ReadyWaitError, RunState, RunStateEnv, RunStateStore, ServiceHealth,
|
||||
},
|
||||
runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of},
|
||||
tray::Tray,
|
||||
},
|
||||
process::AsyncHandler,
|
||||
@@ -20,15 +21,14 @@ use crate::{
|
||||
use anyhow::{Context as _, Result, anyhow, bail};
|
||||
use clash_verge_draft::Draft;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use clash_verge_runtime_bundle::{GEO_ASSETS, RemoteProviderRef, collect_runtime_bundle, remote_providers_of};
|
||||
use clash_verge_service_ipc::{
|
||||
MacosProxyConfig, OwnerCredentials, OwnerIdentity, OwnerSessionProof, ProtocolInfo, ProxyApplyOutcome,
|
||||
RemoteProvider, RuntimeAsset, RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode,
|
||||
ServiceStatusSnapshot, StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||
RuntimeBundle, RuntimeFileOutcome, RuntimeFileRequest, ServiceErrorCode, ServiceStatusSnapshot,
|
||||
StageRuntimeOutcome, StartClashRequest, WriterConfig,
|
||||
};
|
||||
use clash_verge_task::scheduled_task::{self, Mailbox, Next, ScheduledTask};
|
||||
use clash_verge_task::watch_task;
|
||||
use parking_lot::Mutex;
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::sync::LazyLock;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
env::current_exe,
|
||||
@@ -36,12 +36,11 @@ use std::{
|
||||
path::{Path, PathBuf},
|
||||
process::Command as StdCommand,
|
||||
sync::{
|
||||
Arc, LazyLock,
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
},
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::{sync::watch, time::Instant};
|
||||
|
||||
static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
static ACTIVE_SERVICE_SESSION: Mutex<Option<ActiveServiceSession>> = Mutex::new(None);
|
||||
@@ -611,27 +610,7 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result<RuntimeBun
|
||||
|
||||
let bin_ext = if cfg!(windows) { ".exe" } else { "" };
|
||||
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")?,
|
||||
assets: plan
|
||||
.assets
|
||||
.into_iter()
|
||||
.map(|asset| RuntimeAsset {
|
||||
source: asset.source,
|
||||
destination: asset.destination.into(),
|
||||
})
|
||||
.collect(),
|
||||
remote_providers: plan
|
||||
.remote_providers
|
||||
.into_iter()
|
||||
.map(|provider| RemoteProvider {
|
||||
destination: provider.destination.into(),
|
||||
url: provider.url,
|
||||
})
|
||||
.collect(),
|
||||
core_path: bin_path.to_string_lossy().into_owned(),
|
||||
})
|
||||
collect_runtime_bundle(config_file, &bin_path).await
|
||||
}
|
||||
|
||||
/// A staging response whose refusal code tells callers whether a fresh start can help.
|
||||
@@ -859,85 +838,63 @@ fn decode_hex(encoded: &str) -> Result<Vec<u8>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
static PROVIDER_SYNC_REQUESTS: LazyLock<Arc<Mailbox<Option<Instant>>>> = LazyLock::new(|| {
|
||||
AsyncHandler::start_driver(scheduled_task::new(ProviderSchedule::default(), |_| {
|
||||
sync_runtime_providers_by_service()
|
||||
}))
|
||||
});
|
||||
static PROVIDER_SYNC_QUEUED: AtomicBool = AtomicBool::new(false);
|
||||
// Serializing the whole read-and-publish pass prevents an older cache from replacing a newer one.
|
||||
static PROVIDER_SYNC_SERIAL: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
||||
static SYNC_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
|
||||
const RUNTIME_PROVIDER_SYNC_ATTEMPTS: u32 = 4;
|
||||
const CONTENT_COMPARE_CHUNK: usize = 64 * 1024;
|
||||
|
||||
pub(crate) fn request_runtime_provider_sync(delay: Duration) {
|
||||
let due = Instant::now() + delay;
|
||||
PROVIDER_SYNC_REQUESTS.update(|pending| {
|
||||
if pending.is_some_and(|current| current <= due) {
|
||||
return false;
|
||||
}
|
||||
*pending = Some(due);
|
||||
true
|
||||
if PROVIDER_SYNC_QUEUED.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
AsyncHandler::spawn(move || async move {
|
||||
tokio::time::sleep(delay).await;
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
let _ = retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add((RUNTIME_PROVIDER_SYNC_ATTEMPTS - 1) as usize),
|
||||
constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY,
|
||||
),
|
||||
|index| async move {
|
||||
let attempt = index as u32 + 1;
|
||||
let outcome = {
|
||||
let _serial = PROVIDER_SYNC_SERIAL.lock().await;
|
||||
if attempt == 1 {
|
||||
PROVIDER_SYNC_QUEUED.store(false, Ordering::Release);
|
||||
}
|
||||
sync_runtime_providers_by_service().await
|
||||
};
|
||||
match outcome {
|
||||
Ok(ProviderSync { pending: 0, .. }) => Ok(()),
|
||||
Ok(ProviderSync { pending, .. }) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
"{pending} provider caches are not ready yet; retrying"
|
||||
);
|
||||
Err(RetryError::Retry(()))
|
||||
}
|
||||
Ok(ProviderSync { pending, .. }) => {
|
||||
logging!(warn, Type::Service, "{pending} provider caches were not synced");
|
||||
Ok(())
|
||||
}
|
||||
Err(error) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"failed to sync provider caches from the service: {error:#}"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ProviderSchedule {
|
||||
requested: Option<Instant>,
|
||||
retry: Option<(Instant, u32)>,
|
||||
}
|
||||
|
||||
impl ScheduledTask for ProviderSchedule {
|
||||
type Input = Option<Instant>;
|
||||
type Work = u32;
|
||||
type Output = Result<ProviderSync>;
|
||||
|
||||
fn on_input(&mut self, requested: Self::Input, _: Instant) {
|
||||
if let Some(requested) = requested {
|
||||
self.requested = Some(self.requested.map_or(requested, |current| current.min(requested)));
|
||||
}
|
||||
}
|
||||
|
||||
fn next(&mut self, now: Instant) -> Next<u32> {
|
||||
let Some(due) = self.requested.into_iter().chain(self.retry.map(|(due, _)| due)).min() else {
|
||||
return Next::Idle;
|
||||
};
|
||||
if due > now {
|
||||
return Next::At(due);
|
||||
}
|
||||
|
||||
let retry_attempt = self
|
||||
.retry
|
||||
.take_if(|(due, _)| *due <= now)
|
||||
.map_or(1, |(_, attempt)| attempt);
|
||||
let fresh_request = self.requested.take_if(|due| *due <= now).is_some();
|
||||
Next::Run(if fresh_request { 1 } else { retry_attempt })
|
||||
}
|
||||
|
||||
fn finished(&mut self, attempt: u32, result: std::thread::Result<Self::Output>, now: Instant) {
|
||||
match result {
|
||||
Ok(Ok(ProviderSync { pending: 0, .. })) => self.retry = None,
|
||||
Ok(Ok(ProviderSync { pending, .. })) if attempt < RUNTIME_PROVIDER_SYNC_ATTEMPTS => {
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
"{pending} provider caches are not ready yet; retrying"
|
||||
);
|
||||
self.retry = Some((now + constants::timing::RUNTIME_PROVIDER_SYNC_RETRY_DELAY, attempt + 1));
|
||||
}
|
||||
Ok(Ok(ProviderSync { pending, .. })) => {
|
||||
logging!(warn, Type::Service, "{pending} provider caches were not synced");
|
||||
}
|
||||
Ok(Err(error)) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"failed to sync provider caches from the service: {error:#}"
|
||||
);
|
||||
}
|
||||
Err(_) => logging!(error, Type::Service, "provider cache sync panicked"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ProviderSync {
|
||||
synced: usize,
|
||||
@@ -968,7 +925,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
let loaded_before = provider_load_times().await;
|
||||
let mut fetched = Vec::new();
|
||||
for declared in applied_remote_providers(&runtime, &app_dir)? {
|
||||
let (temp, file) = match create_sync_temp(&app_dir.join(declared.destination.as_str())).await {
|
||||
let (temp, file) = match create_sync_temp(&app_dir.join(&declared.provider.destination)).await {
|
||||
Ok(created) => created,
|
||||
Err(error) => {
|
||||
logging!(warn, Type::Service, "{error:#}");
|
||||
@@ -976,7 +933,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
match fetch_runtime_file(&credentials, &session, &declared.destination, file).await {
|
||||
match fetch_runtime_file(&credentials, &session, &declared.provider.destination, file).await {
|
||||
Ok(Fetch::Complete { len, mtime_ns }) => fetched.push(FetchedCache {
|
||||
declared,
|
||||
temp,
|
||||
@@ -997,7 +954,7 @@ async fn sync_runtime_providers_by_service() -> Result<ProviderSync> {
|
||||
warn,
|
||||
Type::Service,
|
||||
"failed to read provider cache {} into {}: {error:#}",
|
||||
declared.destination,
|
||||
declared.provider.destination,
|
||||
temp.display()
|
||||
);
|
||||
outcome.pending += 1;
|
||||
@@ -1108,7 +1065,7 @@ async fn sync_runtime_geo(
|
||||
fn applied_remote_providers(runtime: &Draft<IRuntime>, app_dir: &Path) -> Result<Vec<RemoteProviderRef>> {
|
||||
let applied = runtime.data_arc();
|
||||
match applied.config.as_ref() {
|
||||
Some(config) => remote_providers_of(config, app_dir).map_err(Into::into),
|
||||
Some(config) => remote_providers_of(config, app_dir),
|
||||
None => Ok(Vec::new()),
|
||||
}
|
||||
}
|
||||
@@ -1137,7 +1094,7 @@ async fn publish_fetched(
|
||||
};
|
||||
let mut synced = 0;
|
||||
for cache in fetched {
|
||||
let target = app_dir.join(cache.declared.destination.as_str());
|
||||
let target = app_dir.join(&cache.declared.provider.destination);
|
||||
if !declared.contains(&cache.declared) || same_contents(&cache.temp, &target).await {
|
||||
remove_temp(&cache.temp).await;
|
||||
continue;
|
||||
@@ -1214,7 +1171,7 @@ async fn recheck_identity(
|
||||
cache: &FetchedCache,
|
||||
) -> Result<Fetch> {
|
||||
let request = RuntimeFileRequest {
|
||||
destination: cache.declared.destination.as_str().to_owned(),
|
||||
destination: cache.declared.provider.destination.to_owned(),
|
||||
offset: cache.len,
|
||||
};
|
||||
Ok(match read_chunk(credentials, session, &request).await? {
|
||||
@@ -1302,7 +1259,7 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> {
|
||||
.with_context(|| format!("failed to create provider cache directory {}", parent.display()))?;
|
||||
}
|
||||
let name = target.file_name().map_or_default(|name| name.to_string_lossy());
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
retry(
|
||||
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO),
|
||||
|_| async {
|
||||
@@ -1494,74 +1451,55 @@ const OWNER_MONITOR_INTERVAL: Duration = Duration::from_secs(5);
|
||||
/// Mirrors `OwnerWatch`'s tolerance, for the log line only.
|
||||
const SUSTAINED_OWNER_SAMPLES: u8 = 3;
|
||||
|
||||
static OWNER_MONITOR: LazyLock<watch::Sender<Option<u64>>> = LazyLock::new(|| {
|
||||
let (sender, receiver) = watch::channel(None);
|
||||
AsyncHandler::spawn(move || {
|
||||
watch_task::run(receiver, monitor_owner, |generation| {
|
||||
logging!(error, Type::Service, "owner monitor panicked (generation {generation})");
|
||||
})
|
||||
});
|
||||
sender
|
||||
});
|
||||
|
||||
fn start_owner_monitor() {
|
||||
OWNER_MONITOR.send_modify(|active| {
|
||||
*active = Some(OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel).wrapping_add(1));
|
||||
});
|
||||
}
|
||||
|
||||
async fn monitor_owner(generation: u64, mut updates: watch::Receiver<Option<u64>>) {
|
||||
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
|
||||
let mut watch = OwnerWatch::new();
|
||||
let mut core_restarts = None;
|
||||
loop {
|
||||
let (step, status) = tokio::select! {
|
||||
biased;
|
||||
_ = updates.changed() => return,
|
||||
result = async {
|
||||
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
|
||||
if owner_monitor_generation() != generation
|
||||
|| !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(probe_owner(generation, &mut watch, &mut core_restarts).await)
|
||||
} => match result {
|
||||
Some(observation) => observation,
|
||||
None => return,
|
||||
let generation = OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;
|
||||
AsyncHandler::spawn(move || async move {
|
||||
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
|
||||
let mut watch = OwnerWatch::new();
|
||||
let mut core_restarts = None;
|
||||
loop {
|
||||
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
|
||||
if OWNER_MONITOR_GENERATION.load(Ordering::Acquire) != generation {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Service,
|
||||
"owner monitor superseded (generation {generation})"
|
||||
);
|
||||
break;
|
||||
}
|
||||
if !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service) {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Service,
|
||||
"owner monitor stopped; core no longer in service mode (generation {generation})"
|
||||
);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
if let OwnerStep::Recover(reason) = step {
|
||||
recover_after_owner_loss(generation, reason, status.as_ref()).await;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let (sample, status) = read_owner_sample().await;
|
||||
if let Some(status) = &status {
|
||||
log_core_restarts(&mut core_restarts, status);
|
||||
}
|
||||
let mut step = watch.observe(sample);
|
||||
if matches!(step, OwnerStep::VerifyTransport) {
|
||||
if watch.just_became_sustained() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples (generation {generation}); \
|
||||
preserving local proxy state while the core endpoint still answers"
|
||||
);
|
||||
}
|
||||
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
|
||||
step = watch.resolve_transport(owner_endpoint_available);
|
||||
}
|
||||
|
||||
async fn probe_owner(
|
||||
generation: u64,
|
||||
watch: &mut OwnerWatch,
|
||||
core_restarts: &mut Option<u32>,
|
||||
) -> (OwnerStep, Option<ServiceStatusSnapshot>) {
|
||||
let (sample, status) = read_owner_sample().await;
|
||||
if let Some(status) = &status {
|
||||
log_core_restarts(core_restarts, status);
|
||||
}
|
||||
let mut step = watch.observe(sample);
|
||||
if matches!(step, OwnerStep::VerifyTransport) {
|
||||
if watch.just_became_sustained() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples (generation {generation}); \
|
||||
preserving local proxy state while the core endpoint still answers"
|
||||
);
|
||||
if let OwnerStep::Recover(reason) = step {
|
||||
recover_after_owner_loss(generation, reason, status.as_ref()).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
let owner_endpoint_available = Handle::mihomo().get_version().await.is_ok();
|
||||
step = watch.resolve_transport(owner_endpoint_available);
|
||||
}
|
||||
(step, status)
|
||||
});
|
||||
}
|
||||
|
||||
/// The Service logs its watchdog restarts where the app cannot read them.
|
||||
@@ -1645,10 +1583,7 @@ fn session_matches_active_status(is_active: bool, active_generation: Option<u64>
|
||||
}
|
||||
|
||||
fn cancel_owner_monitors() {
|
||||
OWNER_MONITOR.send_modify(|active| {
|
||||
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel);
|
||||
*active = None;
|
||||
});
|
||||
OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
pub(crate) fn owner_monitor_generation() -> u64 {
|
||||
@@ -1719,7 +1654,7 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
|
||||
}
|
||||
|
||||
async fn clear_proxy_after_owner_loss() {
|
||||
use clash_verge_task::retry::{RetryError, RetryPolicy, retry};
|
||||
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||
let result = retry(
|
||||
RetryPolicy::fixed(
|
||||
std::num::NonZeroUsize::MIN.saturating_add(2),
|
||||
|
||||
@@ -6,9 +6,13 @@ use crate::{
|
||||
};
|
||||
use anyhow::Result;
|
||||
use clash_verge_logging::{Type, logging};
|
||||
use parking_lot::RwLock;
|
||||
use std::{
|
||||
mem::DropGuard,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use sysproxy::{Autoproxy, GuardMonitor, GuardType, Sysproxy};
|
||||
@@ -239,16 +243,18 @@ async fn current_os_proxy_state(sys: Sysproxy, auto: Autoproxy) -> OsProxyState
|
||||
pub(crate) struct Sysopt {
|
||||
// Owns the proxy target pair; every reader and writer goes through this lock.
|
||||
proxy_state_lock: TokioMutex<(Sysproxy, Autoproxy)>,
|
||||
guard_operation_lock: TokioMutex<()>,
|
||||
reset_sysproxy: AtomicBool,
|
||||
guard: TokioMutex<GuardMonitor>,
|
||||
guard: Arc<RwLock<GuardMonitor>>,
|
||||
}
|
||||
|
||||
impl Default for Sysopt {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
proxy_state_lock: TokioMutex::new((Sysproxy::default(), Autoproxy::default())),
|
||||
guard_operation_lock: TokioMutex::new(()),
|
||||
reset_sysproxy: AtomicBool::new(false),
|
||||
guard: TokioMutex::new(GuardMonitor::new(GuardType::None, Duration::from_secs(30))),
|
||||
guard: Arc::new(RwLock::new(GuardMonitor::new(GuardType::None, Duration::from_secs(30)))),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -289,9 +295,14 @@ impl Sysopt {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
fn access_guard(&self) -> Arc<RwLock<GuardMonitor>> {
|
||||
Arc::clone(&self.guard)
|
||||
}
|
||||
|
||||
/// Stop the guard and return whether it drained.
|
||||
async fn drain_guard(guard: &GuardMonitor) -> bool {
|
||||
let idle = guard.shutdown();
|
||||
async fn stop_proxy_guard_locked(&self) -> bool {
|
||||
// Drop the parking_lot read guard before awaiting.
|
||||
let idle = self.access_guard().read().shutdown();
|
||||
let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await;
|
||||
if !drained {
|
||||
logging!(
|
||||
@@ -305,23 +316,23 @@ impl Sysopt {
|
||||
|
||||
/// Stop the guard before handing OS proxy ownership elsewhere.
|
||||
pub(super) async fn stop_proxy_guard(&self) -> bool {
|
||||
let guard = self.guard.lock().await;
|
||||
Self::drain_guard(&guard).await
|
||||
let _operation = self.guard_operation_lock.lock().await;
|
||||
self.stop_proxy_guard_locked().await
|
||||
}
|
||||
|
||||
/// Reconcile guard state with configuration and report success.
|
||||
pub(super) async fn refresh_guard(&self) -> bool {
|
||||
logging!(info, Type::Core, "Refreshing system proxy guard...");
|
||||
let verge = Config::verge().await.latest_arc();
|
||||
let mut guard = self.guard.lock().await;
|
||||
let _operation = self.guard_operation_lock.lock().await;
|
||||
if !verge.enable_system_proxy.unwrap_or_default() {
|
||||
logging!(info, Type::Core, "System proxy is disabled.");
|
||||
let _drained = Self::drain_guard(&guard).await;
|
||||
let _drained = self.stop_proxy_guard_locked().await;
|
||||
return true;
|
||||
}
|
||||
if !verge.enable_proxy_guard.unwrap_or_default() {
|
||||
logging!(info, Type::Core, "System proxy guard is disabled.");
|
||||
let _drained = Self::drain_guard(&guard).await;
|
||||
let _drained = self.stop_proxy_guard_locked().await;
|
||||
return true;
|
||||
}
|
||||
logging!(
|
||||
@@ -330,27 +341,52 @@ impl Sysopt {
|
||||
"Updating system proxy with duration: {} seconds",
|
||||
verge.proxy_guard_duration.unwrap_or(30)
|
||||
);
|
||||
guard.set_interval(Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30)));
|
||||
logging!(info, Type::Core, "Starting system proxy guard...");
|
||||
if !guard.start() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"the system proxy guard refused to start; a previous run has not finished"
|
||||
);
|
||||
{
|
||||
let guard = self.access_guard();
|
||||
guard
|
||||
.write()
|
||||
.set_interval(Duration::from_secs(verge.proxy_guard_duration.unwrap_or(30)));
|
||||
}
|
||||
while guard.get_state().is_pendding() {
|
||||
logging!(info, Type::Core, "Starting system proxy guard...");
|
||||
{
|
||||
let guard = self.access_guard();
|
||||
if !guard.read().start() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
"the system proxy guard refused to start; a previous run has not finished"
|
||||
);
|
||||
}
|
||||
}
|
||||
while self.access_guard().read().get_state().is_pendding() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
// `start()` false may also mean a guard was already running.
|
||||
!guard.get_state().is_stopped()
|
||||
!self.access_guard().read().get_state().is_stopped()
|
||||
}
|
||||
|
||||
/// Recover OS and guard state after a failed write.
|
||||
async fn recover_from_failed_write(
|
||||
&self,
|
||||
error: anyhow::Error,
|
||||
earlier_step_completed: bool,
|
||||
guard_was_running: bool,
|
||||
off: (Sysproxy, Autoproxy),
|
||||
) -> anyhow::Error {
|
||||
recover_from_failed_write(
|
||||
error,
|
||||
earlier_step_completed,
|
||||
|state| self.recover_guard_after_failure(state, guard_was_running),
|
||||
|| disable_all_proxies(off.0, off.1),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Reconcile the guard with the authoritative state.
|
||||
fn recover_guard_after_failure(guard: &mut GuardMonitor, state: AuthoritativeState, was_running: bool) {
|
||||
fn recover_guard_after_failure(&self, state: AuthoritativeState, was_running: bool) {
|
||||
match state {
|
||||
AuthoritativeState::Unchanged if was_running => {
|
||||
let restarted = guard.start();
|
||||
let restarted = self.access_guard().read().start();
|
||||
if !restarted {
|
||||
logging!(
|
||||
warn,
|
||||
@@ -361,7 +397,7 @@ impl Sysopt {
|
||||
}
|
||||
AuthoritativeState::Unchanged => {}
|
||||
AuthoritativeState::Unknown => {
|
||||
guard.set_guard_type(GuardType::None);
|
||||
self.access_guard().write().set_guard_type(GuardType::None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -429,11 +465,11 @@ impl Sysopt {
|
||||
(sys.clone(), auto.clone(), guard_type)
|
||||
};
|
||||
|
||||
let mut guard = self.guard.lock().await;
|
||||
let _guard_operation = self.guard_operation_lock.lock().await;
|
||||
|
||||
// Drain the guard before any OS read or write.
|
||||
let guard_was_running = !guard.get_state().is_stopped();
|
||||
let idle = guard.shutdown();
|
||||
let guard_was_running = !self.access_guard().read().get_state().is_stopped();
|
||||
let idle = self.access_guard().read().shutdown();
|
||||
let drained = idle.wait_timeout(GUARD_DRAIN_TIMEOUT).await;
|
||||
|
||||
// A slow guard does not stop the write, but it does make the OS read untrustworthy.
|
||||
@@ -441,7 +477,7 @@ impl Sysopt {
|
||||
&& drained
|
||||
&& current_os_proxy_state(sys.clone(), auto.clone()).await == OsProxyState::AlreadyApplied
|
||||
{
|
||||
guard.set_guard_type(guard_type);
|
||||
self.access_guard().write().set_guard_type(guard_type);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -472,25 +508,24 @@ impl Sysopt {
|
||||
})
|
||||
.await;
|
||||
|
||||
let (earlier_step_completed, error) = match applied {
|
||||
Ok(Ok(())) => {
|
||||
guard.set_guard_type(guard_type);
|
||||
return Ok(());
|
||||
match applied {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err((earlier_step_completed, error))) => {
|
||||
return Err(self
|
||||
.recover_from_failed_write(error, earlier_step_completed, guard_was_running, compensation)
|
||||
.await);
|
||||
}
|
||||
Ok(Err(failure)) => failure,
|
||||
Err(error) => (
|
||||
false,
|
||||
anyhow::Error::from(error).context("the system proxy write task did not finish"),
|
||||
),
|
||||
};
|
||||
Err(join_error) => {
|
||||
let error = anyhow::Error::from(join_error).context("the system proxy write task did not finish");
|
||||
return Err(self
|
||||
.recover_from_failed_write(error, false, guard_was_running, compensation)
|
||||
.await);
|
||||
}
|
||||
}
|
||||
|
||||
Err(recover_from_failed_write(
|
||||
error,
|
||||
earlier_step_completed,
|
||||
|state| Self::recover_guard_after_failure(&mut guard, state, guard_was_running),
|
||||
|| disable_all_proxies(compensation.0, compensation.1),
|
||||
)
|
||||
.await)
|
||||
// Never point the guard at a target that failed to reach the OS.
|
||||
self.access_guard().write().set_guard_type(guard_type);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// reset the sysproxy
|
||||
@@ -510,8 +545,8 @@ impl Sysopt {
|
||||
self.reset_sysproxy.store(false, Ordering::SeqCst);
|
||||
});
|
||||
let mut proxy_state = self.proxy_state_lock.lock().await;
|
||||
let guard = self.guard.lock().await;
|
||||
let drained = Self::drain_guard(&guard).await;
|
||||
let _guard_operation = self.guard_operation_lock.lock().await;
|
||||
let drained = self.stop_proxy_guard_locked().await;
|
||||
|
||||
// 直接关闭所有代理
|
||||
let (sys, auto) = {
|
||||
@@ -532,7 +567,7 @@ impl Sysopt {
|
||||
disable_until_the_last_write_is_ours(
|
||||
drained,
|
||||
|| disable_all_proxies(sys.clone(), auto.clone()),
|
||||
|| Self::drain_guard(&guard),
|
||||
|| self.stop_proxy_guard_locked(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
+220
-83
@@ -1,30 +1,57 @@
|
||||
use crate::{
|
||||
config::{Config, IProfiles, PrfItem},
|
||||
config::{Config, PrfItem},
|
||||
feat,
|
||||
process::AsyncHandler,
|
||||
singleton,
|
||||
utils::resolve::is_resolve_done,
|
||||
};
|
||||
use anyhow::{Context as _, Result};
|
||||
use clash_verge_draft::Draft;
|
||||
use anyhow::Result;
|
||||
use clash_verge_logging::{Type, logging, logging_error};
|
||||
use clash_verge_profile::SubscriptionSchedule as TaskSchedule;
|
||||
use futures::{FutureExt as _, StreamExt as _};
|
||||
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
|
||||
use futures::StreamExt as _;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
sync::{mpsc, oneshot},
|
||||
sync::mpsc,
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
use tokio_util::time::{DelayQueue, delay_queue::Key};
|
||||
use tristr::alias::String;
|
||||
|
||||
enum TimerCommand {
|
||||
Initialize(oneshot::Sender<()>),
|
||||
Refresh(oneshot::Sender<()>),
|
||||
NextUpdateTime(String, oneshot::Sender<Option<i64>>),
|
||||
Apply(HashMap<String, TaskSchedule>),
|
||||
RunNow(String),
|
||||
TaskFinished(String),
|
||||
}
|
||||
|
||||
/// Next update is due at `updated + interval`, but the queue only takes a delay from now.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct TaskSchedule {
|
||||
interval_minutes: u64,
|
||||
first_delay: Duration,
|
||||
}
|
||||
|
||||
impl TaskSchedule {
|
||||
/// No recorded `updated` -> full interval. Deadline already past -> `ZERO`, fires at once.
|
||||
fn new(interval_minutes: u64, updated: Option<usize>, now: i64) -> Self {
|
||||
let full = Timer::interval_duration(interval_minutes);
|
||||
let elapsed = updated
|
||||
.filter(|updated| *updated > 0)
|
||||
.map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64);
|
||||
|
||||
Self {
|
||||
interval_minutes,
|
||||
first_delay: full.saturating_sub(Duration::from_secs(elapsed)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct TaskState {
|
||||
key: Option<Key>,
|
||||
interval_minutes: u64,
|
||||
@@ -43,19 +70,19 @@ async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Fini
|
||||
Started: FnOnce(),
|
||||
Update: FnOnce() -> UpdateFuture,
|
||||
UpdateFuture: std::future::Future<Output = Output>,
|
||||
Finished: FnOnce(std::thread::Result<Output>),
|
||||
Finished: FnOnce(Output),
|
||||
Completed: FnOnce(),
|
||||
{
|
||||
update_started();
|
||||
let result = AssertUnwindSafe(async { update_profile().await }).catch_unwind().await;
|
||||
let result = update_profile().await;
|
||||
update_finished(result);
|
||||
update_completed();
|
||||
}
|
||||
|
||||
impl TaskState {
|
||||
const fn new(key: Option<Key>, interval_minutes: u64) -> Self {
|
||||
const fn new(key: Key, interval_minutes: u64) -> Self {
|
||||
Self {
|
||||
key,
|
||||
key: Some(key),
|
||||
interval_minutes,
|
||||
running: false,
|
||||
retired: false,
|
||||
@@ -65,6 +92,10 @@ impl TaskState {
|
||||
|
||||
pub struct Timer {
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
command_rx: Mutex<Option<mpsc::UnboundedReceiver<TimerCommand>>>,
|
||||
refresh_lock: tokio::sync::Mutex<()>,
|
||||
pub timer_map: Arc<RwLock<HashMap<String, u64>>>,
|
||||
pub initialized: AtomicBool,
|
||||
}
|
||||
|
||||
singleton!(Timer, TIMER_INSTANCE);
|
||||
@@ -72,39 +103,125 @@ singleton!(Timer, TIMER_INSTANCE);
|
||||
impl Timer {
|
||||
fn new() -> Self {
|
||||
let (command_tx, command_rx) = mpsc::unbounded_channel();
|
||||
let scheduler_tx = command_tx.clone();
|
||||
AsyncHandler::spawn(move || async move {
|
||||
let profiles = Config::profiles().await;
|
||||
Self::run_scheduler(command_rx, scheduler_tx, profiles).await;
|
||||
});
|
||||
Self { command_tx }
|
||||
Self {
|
||||
command_tx,
|
||||
command_rx: Mutex::new(Some(command_rx)),
|
||||
refresh_lock: tokio::sync::Mutex::new(()),
|
||||
timer_map: Arc::new(RwLock::new(HashMap::new())),
|
||||
initialized: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn init(&self) -> Result<()> {
|
||||
self.update_schedule(TimerCommand::Initialize).await
|
||||
if self
|
||||
.initialized
|
||||
.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
|
||||
.is_err()
|
||||
{
|
||||
logging!(debug, Type::Timer, "Timer already initialized, skipping...");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let command_rx = { self.command_rx.lock().take() };
|
||||
if let Some(command_rx) = command_rx {
|
||||
let command_tx = self.command_tx.clone();
|
||||
AsyncHandler::spawn(move || async move {
|
||||
Self::run_scheduler(command_rx, command_tx).await;
|
||||
});
|
||||
}
|
||||
|
||||
if let Err(e) = self.refresh().await {
|
||||
self.initialized.store(false, Ordering::SeqCst);
|
||||
logging!(error, Type::Timer, "Failed to initialize timer: {e:#}");
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
{
|
||||
let timer_map = self.timer_map.read();
|
||||
logging!(debug, Type::Timer, "Registered timer task count: {}", timer_map.len());
|
||||
for (uid, interval) in timer_map.iter() {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Registered timer task: uid={}, interval={}min",
|
||||
uid,
|
||||
interval
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Redundant with first_delay == ZERO, kept as the immediate path; mark_task_running
|
||||
// no-ops whichever of the two arrives second.
|
||||
let cur_timestamp = chrono::Local::now().timestamp();
|
||||
if let Some(items) = Config::profiles().await.data_arc().items.as_ref() {
|
||||
for item in items.iter() {
|
||||
if let Some(option) = item.option.as_ref()
|
||||
&& option.allow_auto_update.unwrap_or(true)
|
||||
&& let Some(interval) = option.update_interval
|
||||
&& interval > 0
|
||||
&& let Some(uid) = item.uid.as_ref()
|
||||
&& let Some(updated) = item.updated
|
||||
&& cur_timestamp - (updated as i64) >= (interval as i64) * 60
|
||||
{
|
||||
logging!(info, Type::Timer, "Running overdue timer task immediately: uid={}", uid);
|
||||
let _ = self.command_tx.send(TimerCommand::RunNow(uid.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logging!(info, Type::Timer, "Timer initialization completed");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn refresh(&self) -> Result<()> {
|
||||
self.update_schedule(TimerCommand::Refresh).await
|
||||
let _refresh_guard = self.refresh_lock.lock().await;
|
||||
let new_schedule = self.gen_map().await;
|
||||
// Cache intervals only: first_delay shrinks every second, so comparing it would make
|
||||
// every refresh look like a change.
|
||||
let new_map: HashMap<String, u64> = new_schedule
|
||||
.iter()
|
||||
.map(|(uid, schedule)| (uid.clone(), schedule.interval_minutes))
|
||||
.collect();
|
||||
|
||||
let mut cache = self.timer_map.write();
|
||||
if *cache == new_map {
|
||||
logging!(debug, Type::Timer, "No timer changes needed");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"Refreshing timer tasks map, count: {}",
|
||||
new_map.len()
|
||||
);
|
||||
*cache = new_map;
|
||||
drop(cache);
|
||||
|
||||
let _ = self.command_tx.send(TimerCommand::Apply(new_schedule));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn update_schedule(&self, command: fn(oneshot::Sender<()>) -> TimerCommand) -> Result<()> {
|
||||
let (reply, done) = oneshot::channel();
|
||||
self.command_tx
|
||||
.send(command(reply))
|
||||
.context("profile timer scheduler stopped")?;
|
||||
done.await.context("profile timer scheduler stopped")
|
||||
async fn gen_map(&self) -> HashMap<String, TaskSchedule> {
|
||||
if let Some(items) = Config::profiles().await.data_arc().items.as_ref() {
|
||||
return Self::gen_map_from_items(items);
|
||||
}
|
||||
|
||||
HashMap::new()
|
||||
}
|
||||
|
||||
fn gen_map_from_items(items: &[PrfItem], initializing: bool) -> HashMap<String, TaskSchedule> {
|
||||
fn gen_map_from_items(items: &[PrfItem]) -> HashMap<String, TaskSchedule> {
|
||||
let now = chrono::Local::now().timestamp();
|
||||
let mut new_map = HashMap::new();
|
||||
|
||||
for item in items {
|
||||
if let Some(uid) = &item.uid
|
||||
&& let Some(schedule) = TaskSchedule::for_profile(item, initializing, now)
|
||||
if let Some(option) = item.option.as_ref()
|
||||
&& let (Some(interval), Some(uid)) = (option.update_interval, &item.uid)
|
||||
&& option.allow_auto_update.unwrap_or(true)
|
||||
&& interval > 0
|
||||
{
|
||||
new_map.insert(uid.clone(), schedule);
|
||||
new_map.insert(uid.clone(), TaskSchedule::new(interval, item.updated, now));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,50 +231,24 @@ impl Timer {
|
||||
async fn run_scheduler(
|
||||
mut command_rx: mpsc::UnboundedReceiver<TimerCommand>,
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
profiles: Draft<IProfiles>,
|
||||
) {
|
||||
let mut queue = DelayQueue::new();
|
||||
let mut tasks = HashMap::new();
|
||||
let mut initialized = false;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
Some(expired) = queue.next(), if initialized => {
|
||||
Some(expired) = queue.next() => {
|
||||
let uid = expired.into_inner();
|
||||
Self::run_expired_task(&mut tasks, uid, command_tx.clone());
|
||||
}
|
||||
|
||||
command = command_rx.recv() => {
|
||||
match command {
|
||||
Some(TimerCommand::Initialize(reply)) => {
|
||||
if !initialized {
|
||||
// Pre-init refreshes are queryable. Start from the current
|
||||
// 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);
|
||||
initialized = true;
|
||||
logging!(info, Type::Timer, "Timer initialization completed");
|
||||
}
|
||||
let _ = reply.send(());
|
||||
Some(TimerCommand::Apply(new_map)) => {
|
||||
Self::apply_timer_map(&mut queue, &mut tasks, new_map);
|
||||
}
|
||||
Some(TimerCommand::Refresh(reply)) => {
|
||||
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);
|
||||
} else {
|
||||
tasks = schedule
|
||||
.into_iter()
|
||||
.map(|(uid, schedule)| (uid, TaskState::new(None, schedule.interval_minutes)))
|
||||
.collect();
|
||||
}
|
||||
let _ = reply.send(());
|
||||
}
|
||||
Some(TimerCommand::NextUpdateTime(uid, reply)) => {
|
||||
let next = Self::next_update_time(&tasks, &profiles.latest_arc(), &uid);
|
||||
let _ = reply.send(next);
|
||||
Some(TimerCommand::RunNow(uid)) => {
|
||||
Self::run_task_now(&mut queue, &mut tasks, uid, command_tx.clone());
|
||||
}
|
||||
Some(TimerCommand::TaskFinished(uid)) => {
|
||||
Self::finish_task(&mut queue, &mut tasks, uid);
|
||||
@@ -230,7 +321,7 @@ impl Timer {
|
||||
schedule.interval_minutes,
|
||||
schedule.first_delay.as_secs()
|
||||
);
|
||||
tasks.insert(uid, TaskState::new(Some(key), schedule.interval_minutes));
|
||||
tasks.insert(uid, TaskState::new(key, schedule.interval_minutes));
|
||||
}
|
||||
|
||||
fn update_task_interval(queue: &mut DelayQueue<String>, uid: &str, state: &mut TaskState, schedule: &TaskSchedule) {
|
||||
@@ -262,13 +353,52 @@ impl Timer {
|
||||
};
|
||||
|
||||
state.key = None;
|
||||
if state.running {
|
||||
if !Self::mark_task_running(state, &uid, false) {
|
||||
return;
|
||||
}
|
||||
state.running = true;
|
||||
|
||||
Self::spawn_update_task(uid, command_tx);
|
||||
}
|
||||
|
||||
fn run_task_now(
|
||||
queue: &mut DelayQueue<String>,
|
||||
tasks: &mut HashMap<String, TaskState>,
|
||||
uid: String,
|
||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||
) {
|
||||
let Some(state) = tasks.get_mut(&uid) else {
|
||||
return;
|
||||
};
|
||||
|
||||
if !Self::mark_task_running(state, &uid, true) {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(key) = state.key.take() {
|
||||
queue.remove(&key);
|
||||
}
|
||||
Self::spawn_update_task(uid, command_tx);
|
||||
}
|
||||
|
||||
fn mark_task_running(state: &mut TaskState, uid: &str, immediate: bool) -> bool {
|
||||
if !state.running {
|
||||
state.running = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
if immediate {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Timer task already running, skip immediate uid={}",
|
||||
uid
|
||||
);
|
||||
} else {
|
||||
logging!(debug, Type::Timer, "Timer task already running, skip uid={}", uid);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn finish_task(queue: &mut DelayQueue<String>, tasks: &mut HashMap<String, TaskState>, uid: String) {
|
||||
let Some(state) = tasks.get_mut(&uid) else {
|
||||
return;
|
||||
@@ -289,7 +419,7 @@ impl Timer {
|
||||
|
||||
// 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));
|
||||
let key = Self::schedule_task(queue, &uid, Self::interval_duration(state.interval_minutes));
|
||||
state.key = Some(key);
|
||||
}
|
||||
|
||||
@@ -302,22 +432,30 @@ impl Timer {
|
||||
});
|
||||
}
|
||||
|
||||
const fn interval_duration(interval_minutes: u64) -> Duration {
|
||||
Duration::from_secs(interval_minutes.saturating_mul(60))
|
||||
}
|
||||
|
||||
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
|
||||
.send(TimerCommand::NextUpdateTime(uid.into(), reply))
|
||||
.ok()?;
|
||||
result.await.ok().flatten()
|
||||
}
|
||||
logging!(debug, Type::Timer, "Getting next update time, uid={}", uid);
|
||||
|
||||
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
|
||||
let task = tasks.get(uid).filter(|task| !task.retired)?;
|
||||
let updated = profiles.get_item(uid).ok()?.updated;
|
||||
TaskSchedule::reported_deadline(task.interval_minutes, updated)
|
||||
let task_interval = *self.timer_map.read().get(uid)?;
|
||||
let profiles = Config::profiles().await;
|
||||
let profiles_guard = profiles.latest_arc();
|
||||
let items = profiles_guard.items.as_ref()?;
|
||||
|
||||
let profile = items.iter().find(|item| item.uid.as_deref() == Some(uid))?;
|
||||
let updated = profile.updated.unwrap_or(0) as i64;
|
||||
|
||||
if updated > 0 {
|
||||
Some(updated + (task_interval as i64 * 60))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_update_event(uid: &str, is_start: bool) {
|
||||
@@ -336,13 +474,12 @@ impl Timer {
|
||||
|| Self::emit_update_event(uid, true),
|
||||
|| feat::update_profile(uid, None, false),
|
||||
|result| match result {
|
||||
Ok(Ok(_)) => {
|
||||
Ok(_) => {
|
||||
logging!(debug, Type::Timer, "timer task completed for uid: {}", uid);
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
Err(e) => {
|
||||
logging_error!(Type::Timer, "Failed to update profile uid {}: {e:#}", uid);
|
||||
}
|
||||
Err(_) => logging!(error, Type::Timer, "Profile update worker panicked"),
|
||||
},
|
||||
|| Self::emit_update_event(uid, false),
|
||||
)
|
||||
@@ -415,7 +552,7 @@ mod tests {
|
||||
remote_profile("missing-interval", Some(true), None),
|
||||
];
|
||||
|
||||
let map = Timer::gen_map_from_items(&items, false);
|
||||
let map = Timer::gen_map_from_items(&items);
|
||||
|
||||
assert_eq!(map.len(), 2);
|
||||
assert_eq!(map.get("enabled").map(|s| s.interval_minutes), Some(30));
|
||||
@@ -626,8 +763,8 @@ mod tests {
|
||||
},
|
||||
{
|
||||
let calls = Arc::clone(&calls);
|
||||
move |result| {
|
||||
assert!(matches!(result, Ok(Ok(()))));
|
||||
move |result: anyhow::Result<()>| {
|
||||
assert!(result.is_ok());
|
||||
calls.lock().push("terminal-result");
|
||||
}
|
||||
},
|
||||
|
||||
@@ -212,9 +212,22 @@ impl Tray {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let verge = Config::verge().await;
|
||||
let verge = Config::verge().await.latest_arc();
|
||||
let system_proxy = verge.enable_system_proxy.unwrap_or(false);
|
||||
let tun_mode = verge.enable_tun_mode.unwrap_or(false);
|
||||
let mode = {
|
||||
Config::clash()
|
||||
.await
|
||||
.latest_arc()
|
||||
.0
|
||||
.get("mode")
|
||||
.map_or("rule", |val| val.as_str().unwrap_or("rule"))
|
||||
.to_owned()
|
||||
};
|
||||
let is_lightweight_mode = is_in_lightweight_mode();
|
||||
|
||||
let fetch_proxy_groups =
|
||||
include_proxy_groups && verge.latest_arc().tray_proxy_groups_display_mode.as_deref() != Some("disable");
|
||||
include_proxy_groups && verge.tray_proxy_groups_display_mode.as_deref() != Some("disable");
|
||||
|
||||
// TODO: should update tray menu again when it was timeout error
|
||||
let (proxy_nodes_data, runtime_proxy_groups_order) = if fetch_proxy_groups {
|
||||
@@ -244,28 +257,29 @@ impl Tray {
|
||||
(None, None)
|
||||
};
|
||||
|
||||
let clash = Config::clash().await;
|
||||
let profiles = Config::profiles().await;
|
||||
let verge = if fetch_proxy_groups {
|
||||
Config::verge().await.latest_arc()
|
||||
} else {
|
||||
verge
|
||||
};
|
||||
let profiles = Config::profiles().await.latest_arc();
|
||||
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
let dispatch_handle = app_handle.clone();
|
||||
app_handle
|
||||
.run_on_main_thread(move || {
|
||||
let _ = tx.send((|| -> Result<()> {
|
||||
let verge = verge.latest_arc();
|
||||
let clash = clash.latest_arc();
|
||||
let mode = clash.0.get("mode").and_then(|mode| mode.as_str()).unwrap_or("rule");
|
||||
let menu = build_tray_menu(
|
||||
&dispatch_handle,
|
||||
TrayMenuOptions {
|
||||
mode: Some(mode),
|
||||
system_proxy_enabled: verge.enable_system_proxy.unwrap_or(false),
|
||||
tun_mode_enabled: verge.enable_tun_mode.unwrap_or(false),
|
||||
is_lightweight_mode: is_in_lightweight_mode(),
|
||||
mode: Some(mode.as_str()),
|
||||
system_proxy_enabled: system_proxy,
|
||||
tun_mode_enabled: tun_mode,
|
||||
is_lightweight_mode,
|
||||
include_proxy_groups,
|
||||
},
|
||||
&verge,
|
||||
&profiles.latest_arc(),
|
||||
&profiles,
|
||||
runtime_proxy_groups_order,
|
||||
proxy_nodes_data,
|
||||
)?;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user