mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-27 16:00:09 +08:00
Compare commits
104
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c8a8d2034c | ||
|
|
f17ccdc227 | ||
|
|
92303ce60d | ||
|
|
ecd60d317a | ||
|
|
c2b6c0378e | ||
|
|
adbe3ffec4 | ||
|
|
a146d78b9f | ||
|
|
1552f8e2f9 | ||
|
|
70d1298bc9 | ||
|
|
42ec30633b | ||
|
|
4a6f0da237 | ||
|
|
3e91458799 | ||
|
|
763338dade | ||
|
|
5b53c32de1 | ||
|
|
43cf001e68 | ||
|
|
5bf0de0d0b | ||
|
|
96d68b057a | ||
|
|
917d97f335 | ||
|
|
5364468ad4 | ||
|
|
866899593e | ||
|
|
079414253e | ||
|
|
6de4df8c9f | ||
|
|
86605f197d | ||
|
|
5375ce360f | ||
|
|
9d1b400299 | ||
|
|
7aed7be2f1 | ||
|
|
438f6f7461 | ||
|
|
edcd76f27d | ||
|
|
7eb24d8c69 | ||
|
|
8ddd99f226 | ||
|
|
e0e97a920e | ||
|
|
c4f9d65e07 | ||
|
|
0c7e0c8535 | ||
|
|
1638ab48d8 | ||
|
|
5d7dc3aed9 | ||
|
|
b057bd964c | ||
|
|
897a117dc5 | ||
|
|
6a752994cf | ||
|
|
32e5d5bda3 | ||
|
|
daae17a40c | ||
|
|
1f140dfd3a | ||
|
|
04d74ac48f | ||
|
|
78bf79cc09 | ||
|
|
61c33c6113 | ||
|
|
ae4f416766 | ||
|
|
fbc4b516b8 | ||
|
|
3456de1fb6 | ||
|
|
f9ef9d78cb | ||
|
|
3458c9b075 | ||
|
|
afc32f568a | ||
|
|
22e3f1ac8a | ||
|
|
758300ac34 | ||
|
|
659ee1a181 | ||
|
|
fd06fbb3b7 | ||
|
|
ed0b801573 | ||
|
|
ff1ce92fac | ||
|
|
6a85d0344e | ||
|
|
bffe91db5e | ||
|
|
93b7bb8fe8 | ||
|
|
3b958acb22 | ||
|
|
d374ab4350 | ||
|
|
b7197f6f4b | ||
|
|
7bf8e1dcf5 | ||
|
|
07825afb1e | ||
|
|
d7e0126586 | ||
|
|
5059cdcb9d | ||
|
|
af0f502f98 | ||
|
|
8982525fd2 | ||
|
|
81ce247ecc | ||
|
|
b469bee352 | ||
|
|
df79ed3efb | ||
|
|
c6a4de1c6a | ||
|
|
433cd0628f | ||
|
|
13676d3335 | ||
|
|
2a7972fa5b | ||
|
|
19334368cd | ||
|
|
73ea0fbd80 | ||
|
|
9f97d938f5 | ||
|
|
04a2a09368 | ||
|
|
94491b4ba4 | ||
|
|
78516dc1dc | ||
|
|
8f6fd3bbf9 | ||
|
|
c599f5547e | ||
|
|
f6fdb34745 | ||
|
|
65ed8d3cf2 | ||
|
|
2baa629ac4 | ||
|
|
c7ffb21294 | ||
|
|
0d0ed72467 | ||
|
|
a36dcd319f | ||
|
|
9a879dd8d8 | ||
|
|
20141e791e | ||
|
|
e385d37e5b | ||
|
|
2f097790ed | ||
|
|
619d6ae36a | ||
|
|
de24496fa7 | ||
|
|
f58e0a0af5 | ||
|
|
a8e8fe66dc | ||
|
|
75c921b466 | ||
|
|
e3bdea4386 | ||
|
|
ce963d175a | ||
|
|
d289a608d9 | ||
|
|
8a5548af10 | ||
|
|
1d9bca13c8 | ||
|
|
6f19c3dfaa |
@@ -5,7 +5,7 @@
|
|||||||
"features": {
|
"features": {
|
||||||
"ghcr.io/devcontainers/features/node:2": {
|
"ghcr.io/devcontainers/features/node:2": {
|
||||||
"version": "24.21.0",
|
"version": "24.21.0",
|
||||||
"pnpmVersion": "12.3.3"
|
"pnpmVersion": "12.8.1"
|
||||||
},
|
},
|
||||||
"ghcr.io/devcontainers/features/rust:1": {
|
"ghcr.io/devcontainers/features/rust:1": {
|
||||||
"version": "1.98.1",
|
"version": "1.98.1",
|
||||||
|
|||||||
@@ -5,10 +5,10 @@
|
|||||||
"version": "v9.0.0",
|
"version": "v9.0.0",
|
||||||
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
"sha": "3a2844b7e9c422d3c10d287c895573f7108da1b3"
|
||||||
},
|
},
|
||||||
"github/gh-aw-actions/setup@v0.89.1": {
|
"github/gh-aw-actions/setup@v0.89.21": {
|
||||||
"repo": "github/gh-aw-actions/setup",
|
"repo": "github/gh-aw-actions/setup",
|
||||||
"version": "v0.89.1",
|
"version": "v0.89.21",
|
||||||
"sha": "4537e5924c9abb366dcbece06750e498e0218fae"
|
"sha": "924af5fdc64061cfbf66fb584c8b07e2ac230c60"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"containers": {
|
"containers": {
|
||||||
@@ -22,6 +22,16 @@
|
|||||||
"digest": "sha256:f7df036c86575527b61f3f7df91c4412349a12b2a74988d929eafa2999230c98",
|
"digest": "sha256:f7df036c86575527b61f3f7df91c4412349a12b2a74988d929eafa2999230c98",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.14@sha256:f7df036c86575527b61f3f7df91c4412349a12b2a74988d929eafa2999230c98"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.14@sha256:f7df036c86575527b61f3f7df91c4412349a12b2a74988d929eafa2999230c98"
|
||||||
},
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/agent:0.28.16": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/agent:0.28.16",
|
||||||
|
"digest": "sha256:57a3e27388a6d7d32719088581e52567727fa0bf2f0d477bf565b0c4baa12a3f",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.16@sha256:57a3e27388a6d7d32719088581e52567727fa0bf2f0d477bf565b0c4baa12a3f"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/agent:0.28.23": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/agent:0.28.23",
|
||||||
|
"digest": "sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/agent:0.28.23@sha256:2c78aaba1c108e130e2d6d01e4f2cca334ea04c53e6f258913ac34173fe7e3b2"
|
||||||
|
},
|
||||||
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
|
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.13": {
|
||||||
"image": "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",
|
"digest": "sha256:61f12dcff38eb008b645d87a5541763452f409d9040eb243718764944167b1a2",
|
||||||
@@ -32,6 +42,16 @@
|
|||||||
"digest": "sha256:6f95e2234dd9bd6333a8ff28ccea7ecf0204acd4a09108723844dbd2bf6268c5",
|
"digest": "sha256:6f95e2234dd9bd6333a8ff28ccea7ecf0204acd4a09108723844dbd2bf6268c5",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.14@sha256:6f95e2234dd9bd6333a8ff28ccea7ecf0204acd4a09108723844dbd2bf6268c5"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.14@sha256:6f95e2234dd9bd6333a8ff28ccea7ecf0204acd4a09108723844dbd2bf6268c5"
|
||||||
},
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.16": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.16",
|
||||||
|
"digest": "sha256:cd400948638ffe1b87ec319abf73fa29b6ac9881b015da58bba971c4cc13a400",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.16@sha256:cd400948638ffe1b87ec319abf73fa29b6ac9881b015da58bba971c4cc13a400"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23",
|
||||||
|
"digest": "sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/api-proxy:0.28.23@sha256:c15c3d1208df10c5b588a3657be53742aa982ae0909d1eb1812525268794ca64"
|
||||||
|
},
|
||||||
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
|
"ghcr.io/github/gh-aw-firewall/squid:0.28.13": {
|
||||||
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
|
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.13",
|
||||||
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
|
"digest": "sha256:58a8dc5be3fbafeef7da0532c38bd9047f86bf1b3c4cfd7d9b7d8d28e80a2b56",
|
||||||
@@ -42,20 +62,30 @@
|
|||||||
"digest": "sha256:2ce8df3abf3e9b76e9c0cf5863da41f1ab3f89b20ad14b988806ab89e7bf2cd5",
|
"digest": "sha256:2ce8df3abf3e9b76e9c0cf5863da41f1ab3f89b20ad14b988806ab89e7bf2cd5",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.14@sha256:2ce8df3abf3e9b76e9c0cf5863da41f1ab3f89b20ad14b988806ab89e7bf2cd5"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.14@sha256:2ce8df3abf3e9b76e9c0cf5863da41f1ab3f89b20ad14b988806ab89e7bf2cd5"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/gh-aw-mcpg:v0.4.20": {
|
"ghcr.io/github/gh-aw-firewall/squid:0.28.16": {
|
||||||
"image": "ghcr.io/github/gh-aw-mcpg:v0.4.20",
|
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.16",
|
||||||
"digest": "sha256:980ea7aa4fb07e444f0e2c6e3af5aff8b45e4e415d617667b8ba064a1768b684",
|
"digest": "sha256:452197f2e241b2cda8eb0b5674960aa8ca544a64dc242e24f8263c3df6452919",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.4.20@sha256:980ea7aa4fb07e444f0e2c6e3af5aff8b45e4e415d617667b8ba064a1768b684"
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.16@sha256:452197f2e241b2cda8eb0b5674960aa8ca544a64dc242e24f8263c3df6452919"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-firewall/squid:0.28.23": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-firewall/squid:0.28.23",
|
||||||
|
"digest": "sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-firewall/squid:0.28.23@sha256:02ffc56dd40158223064ef03a78c2d9717473c93723b4e403d455ea6f0b09ae0"
|
||||||
|
},
|
||||||
|
"ghcr.io/github/gh-aw-mcpg:v0.4.25": {
|
||||||
|
"image": "ghcr.io/github/gh-aw-mcpg:v0.4.25",
|
||||||
|
"digest": "sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086",
|
||||||
|
"pinned_image": "ghcr.io/github/gh-aw-mcpg:v0.4.25@sha256:9be0a86220e807a0ecc89e53d7453468f7a53fbc6b3d1efd2299025ffe01d086"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/gh-aw-node": {
|
"ghcr.io/github/gh-aw-node": {
|
||||||
"image": "ghcr.io/github/gh-aw-node",
|
"image": "ghcr.io/github/gh-aw-node",
|
||||||
"digest": "sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e",
|
"digest": "sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e",
|
||||||
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"
|
"pinned_image": "ghcr.io/github/gh-aw-node@sha256:bac2192f6374d6262116399b34fc5e143d576f82719e90a18261cae7480f4d4e"
|
||||||
},
|
},
|
||||||
"ghcr.io/github/github-mcp-server:v1.12.1": {
|
"ghcr.io/github/github-mcp-server:v1.12.2": {
|
||||||
"image": "ghcr.io/github/github-mcp-server:v1.12.1",
|
"image": "ghcr.io/github/github-mcp-server:v1.12.2",
|
||||||
"digest": "sha256:0ba840c46a237879c8300e7fddb0b6347f20e029ccb9cbe2ce4a943daa1ff560",
|
"digest": "sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6",
|
||||||
"pinned_image": "ghcr.io/github/github-mcp-server:v1.12.1@sha256:0ba840c46a237879c8300e7fddb0b6347f20e029ccb9cbe2ce4a943daa1ff560"
|
"pinned_image": "ghcr.io/github/github-mcp-server:v1.12.2@sha256:508a0857ec762b1ab1cece29193345b501fab1dd9d1228a7b617062954cecac6"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -30,11 +30,19 @@ jobs:
|
|||||||
PR_BODY: ${{ github.event.pull_request.body }}
|
PR_BODY: ${{ github.event.pull_request.body }}
|
||||||
LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}
|
LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}
|
||||||
DRAFT: ${{ github.event.pull_request.draft }}
|
DRAFT: ${{ github.event.pull_request.draft }}
|
||||||
|
ASSOCIATION: ${{ github.event.pull_request.author_association }}
|
||||||
|
AUTHOR_TYPE: ${{ github.event.pull_request.user.type }}
|
||||||
run: |
|
run: |
|
||||||
if [ "$DRAFT" = "true" ] || printf '%s' "$LABELS" | grep -q 'no-issue-needed'; then
|
if [ "$DRAFT" = "true" ] || printf '%s' "$LABELS" | grep -q 'no-issue-needed'; then
|
||||||
echo "Draft or no-issue-needed; linkage check skipped."
|
echo "Draft or no-issue-needed; linkage check skipped."
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
# OWNER/MEMBER/COLLABORATOR and bots mirror the slop review's
|
||||||
|
# skip-roles/skip-bots trust tier.
|
||||||
|
if [ "$AUTHOR_TYPE" = "Bot" ] || [ "$ASSOCIATION" = "OWNER" ] || [ "$ASSOCIATION" = "MEMBER" ] || [ "$ASSOCIATION" = "COLLABORATOR" ]; then
|
||||||
|
echo "Bot or trusted author ($ASSOCIATION); linkage check skipped."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
if printf '%s\n%s\n' "$PR_TITLE" "$PR_BODY" | grep -Eq '#[0-9]+|issues/[0-9]+'; then
|
if printf '%s\n%s\n' "$PR_TITLE" "$PR_BODY" | grep -Eq '#[0-9]+|issues/[0-9]+'; then
|
||||||
echo "Issue reference found."
|
echo "Issue reference found."
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ name: Auto Build
|
|||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
schedule:
|
schedule:
|
||||||
# UTC+8 12:00, 18:00 -> UTC 4:00, 10:00
|
# UTC+8 06:00, 18:00 -> UTC 22:00, 10:00
|
||||||
- cron: '0 4,10 * * *'
|
- cron: '0 10,22 * * *'
|
||||||
permissions: write-all
|
permissions: write-all
|
||||||
env:
|
env:
|
||||||
TAG_NAME: autobuild
|
TAG_NAME: autobuild
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
name: Backend Guardrails
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
paths:
|
||||||
|
- "src-tauri/**"
|
||||||
|
- ".github/workflows/backend-guardrails.yml"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
banned-patterns:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: No Handle::refresh calls in feat
|
||||||
|
run: '! grep -rn "Handle::refresh" src-tauri/src/feat'
|
||||||
|
|
||||||
|
- name: No notice_message outside core/notify
|
||||||
|
run: '! grep -rn "notice_message(" src-tauri/src --include="*.rs" | grep -v "core/notify"'
|
||||||
|
|
||||||
|
- name: No manual update-flag chains
|
||||||
|
run: '! grep -rnE "determine_update_flags|UpdateFlags" src-tauri/src'
|
||||||
@@ -31,6 +31,6 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Install gh-aw extension
|
- name: Install gh-aw extension
|
||||||
uses: github/gh-aw-actions/setup-cli@96dc6d905bdbe195f719ddc990a3f5b59b751016 # v0.89.10
|
uses: github/gh-aw-actions/setup-cli@924af5fdc64061cfbf66fb584c8b07e2ac230c60 # v0.89.21
|
||||||
with:
|
with:
|
||||||
version: v0.89.1
|
version: v0.89.15
|
||||||
|
|||||||
@@ -85,3 +85,82 @@ jobs:
|
|||||||
- name: Run Knip
|
- name: Run Knip
|
||||||
if: steps.check_frontend.outputs.frontend == 'true'
|
if: steps.check_frontend.outputs.frontend == 'true'
|
||||||
run: pnpm knip:check
|
run: pnpm knip:check
|
||||||
|
|
||||||
|
- name: Architecture gates (listen/emit only in the event bus, invoke only in services)
|
||||||
|
if: steps.check_frontend.outputs.frontend == 'true'
|
||||||
|
run: node scripts/check-architecture.mjs listen emit invoke
|
||||||
|
|
||||||
|
contract-parity:
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Check contract inputs
|
||||||
|
id: check_inputs
|
||||||
|
uses: dorny/paths-filter@v4
|
||||||
|
with:
|
||||||
|
filters: |
|
||||||
|
contract:
|
||||||
|
- 'src/services/contract.ts'
|
||||||
|
- 'scripts/gen-contract.mjs'
|
||||||
|
- 'src-tauri/src/core/notify/**'
|
||||||
|
- 'src-tauri/src/bin/**'
|
||||||
|
- 'src-tauri/src/lib.rs'
|
||||||
|
- '.github/workflows/frontend-check.yml'
|
||||||
|
|
||||||
|
- name: Skip if contract inputs unchanged
|
||||||
|
if: steps.check_inputs.outputs.contract != 'true'
|
||||||
|
run: echo "No contract inputs changed, skipping parity check."
|
||||||
|
|
||||||
|
- name: Install Rust Stable
|
||||||
|
if: steps.check_inputs.outputs.contract == 'true'
|
||||||
|
uses: dtolnay/rust-toolchain@master
|
||||||
|
with:
|
||||||
|
toolchain: stable
|
||||||
|
|
||||||
|
- name: Rust Cache
|
||||||
|
if: steps.check_inputs.outputs.contract == 'true'
|
||||||
|
uses: Swatinem/rust-cache@v2
|
||||||
|
with:
|
||||||
|
prefix-key: 'v1-rust'
|
||||||
|
key: 'rust-shared-stable-ubuntu-22.04-x86_64-unknown-linux-gnu-contract'
|
||||||
|
workspaces: |
|
||||||
|
. -> target
|
||||||
|
cache-all-crates: true
|
||||||
|
cache-workspace-crates: true
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
if: steps.check_inputs.outputs.contract == 'true'
|
||||||
|
run: |
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y libxslt1.1 libwebkit2gtk-4.1-dev libayatana-appindicator3-dev librsvg2-dev patchelf
|
||||||
|
|
||||||
|
- name: Install pnpm
|
||||||
|
if: steps.check_inputs.outputs.contract == 'true'
|
||||||
|
uses: pnpm/action-setup@v6
|
||||||
|
with:
|
||||||
|
run_install: false
|
||||||
|
|
||||||
|
- uses: actions/setup-node@v7
|
||||||
|
if: steps.check_inputs.outputs.contract == 'true'
|
||||||
|
with:
|
||||||
|
node-version: '24.21.0'
|
||||||
|
cache: 'pnpm'
|
||||||
|
|
||||||
|
- run: pnpm install --frozen-lockfile
|
||||||
|
if: steps.check_inputs.outputs.contract == 'true'
|
||||||
|
|
||||||
|
- name: Provision sidecar placeholders for tauri-build
|
||||||
|
if: steps.check_inputs.outputs.contract == 'true'
|
||||||
|
run: |
|
||||||
|
mkdir -p src-tauri/sidecar src-tauri/resources dist
|
||||||
|
touch dist/index.html
|
||||||
|
for bin in clash-verge-service clash-verge-service-install clash-verge-service-uninstall verge-mihomo verge-mihomo-alpha; do
|
||||||
|
touch "src-tauri/sidecar/${bin}-x86_64-unknown-linux-gnu"
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Regenerate contract and require empty diff
|
||||||
|
if: steps.check_inputs.outputs.contract == 'true'
|
||||||
|
run: |
|
||||||
|
pnpm gen:contract
|
||||||
|
git diff --exit-code -- src/services/contract.ts
|
||||||
|
|||||||
+171
-127
File diff suppressed because one or more lines are too long
+1
-1
@@ -1,3 +1,3 @@
|
|||||||
nodejs 24.21.0
|
nodejs 24.21.0
|
||||||
pnpm 12.4.1
|
pnpm 12.8.1
|
||||||
rust 1.98.1
|
rust 1.98.1
|
||||||
|
|||||||
Generated
+460
-603
File diff suppressed because it is too large
Load Diff
+20
-7
@@ -46,6 +46,12 @@ inherits = "fast-release"
|
|||||||
codegen-units = 1
|
codegen-units = 1
|
||||||
split-debuginfo = "unpacked"
|
split-debuginfo = "unpacked"
|
||||||
|
|
||||||
|
[patch.crates-io]
|
||||||
|
# macOS Golden Gate fix for tray-icon click reentrancy issue
|
||||||
|
# Remove the following patch once the fix is merged upstream(tauri)
|
||||||
|
# https://github.com/tauri-apps/tray-icon/pull/365
|
||||||
|
tray-icon = { git = "https://github.com/Tunglies/tray-icon.git", branch = "fix/macos-27-click-reentrancy" }
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
clash-verge-draft = { path = "crates/clash-verge-draft" }
|
clash-verge-draft = { path = "crates/clash-verge-draft" }
|
||||||
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
|
clash-verge-media-unlock = { path = "crates/clash-verge-media-unlock" }
|
||||||
@@ -55,10 +61,10 @@ clash-verge-i18n = { path = "crates/clash-verge-i18n" }
|
|||||||
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
|
clash-verge-limiter = { path = "crates/clash-verge-limiter" }
|
||||||
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" }
|
||||||
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" }
|
||||||
tracing = "0.1"
|
tracing = "0.1.44"
|
||||||
|
|
||||||
tauri = { version = "2.11.5" }
|
tauri = { version = "2.11.6" }
|
||||||
tauri-plugin-clipboard-manager = "2.3.2"
|
tauri-plugin-clipboard-manager = "2.3.3"
|
||||||
parking_lot = { version = "0.12.5", features = ["hardware-lock-elision"] }
|
parking_lot = { version = "0.12.5", features = ["hardware-lock-elision"] }
|
||||||
anyhow = "1.0.104"
|
anyhow = "1.0.104"
|
||||||
chrono = "0.4.45"
|
chrono = "0.4.45"
|
||||||
@@ -70,9 +76,15 @@ tokio = { version = "1.53.1", features = [
|
|||||||
"sync",
|
"sync",
|
||||||
] }
|
] }
|
||||||
flexi_logger = "0.31.10"
|
flexi_logger = "0.31.10"
|
||||||
log = "0.4.33"
|
log = "0.4.34"
|
||||||
regex = "1.13.1"
|
regex = "1.13.1"
|
||||||
reqwest = { version = "0.13.4", features = ["json", "cookies", "gzip", "rustls", "form"] }
|
reqwest = { version = "0.13.5", features = [
|
||||||
|
"json",
|
||||||
|
"cookies",
|
||||||
|
"gzip",
|
||||||
|
"rustls",
|
||||||
|
"form",
|
||||||
|
] }
|
||||||
rust_iso3166 = "0.2.0"
|
rust_iso3166 = "0.2.0"
|
||||||
|
|
||||||
smartstring = { version = "1.0.1" }
|
smartstring = { version = "1.0.1" }
|
||||||
@@ -80,7 +92,7 @@ smartstring = { version = "1.0.1" }
|
|||||||
serde = { version = "1.0.229" }
|
serde = { version = "1.0.229" }
|
||||||
serde_json = { version = "1.0.151" }
|
serde_json = { version = "1.0.151" }
|
||||||
serde_yaml_ng = { version = "0.10.0" }
|
serde_yaml_ng = { version = "0.10.0" }
|
||||||
bitflags = { version = "2.13.1" }
|
bitflags = { version = "2.13.2" }
|
||||||
socket2 = "0.6.5"
|
socket2 = "0.6.5"
|
||||||
|
|
||||||
# *** For Windows platform only ***
|
# *** For Windows platform only ***
|
||||||
@@ -93,7 +105,8 @@ windows-sys = { version = "0.61.2", features = [
|
|||||||
"Win32_Security_Authorization",
|
"Win32_Security_Authorization",
|
||||||
"Win32_Storage_FileSystem",
|
"Win32_Storage_FileSystem",
|
||||||
"Win32_System_Threading",
|
"Win32_System_Threading",
|
||||||
"Win32_System_JobObjects"
|
"Win32_System_Diagnostics_ToolHelp",
|
||||||
|
"Win32_System_JobObjects",
|
||||||
] }
|
] }
|
||||||
# *********************************
|
# *********************************
|
||||||
|
|
||||||
|
|||||||
+7
-82
@@ -1,100 +1,25 @@
|
|||||||
## v2.5.4
|
## v2.5.7
|
||||||
|
|
||||||
> [!IMPORTANT]
|
|
||||||
> 服务模式下,配置目录中的规则集、代理集合文件只是缓存副本,手动修改不会影响正在运行的内核。需要手动维护的文件请使用 `type: file`。
|
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary><strong> 🐞 修复问题 </strong></summary>
|
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||||
|
|
||||||
- 修复系统代理切换失败后,开关状态显示错误的问题
|
- 修复读屏软件将普通模式下的侧边栏导航项播报为不可用的可拖拽控件的问题
|
||||||
- 修复代理守卫失败后反复重试且没有提示的问题
|
- 修复订阅包含自定义 DNS 时,确认开启的 DNS 覆写在重启应用后被自动关闭的问题
|
||||||
- 修复未开启系统代理时,启动仍提示代理错误的问题
|
|
||||||
- 修复恢复备份后未按备份设置关闭系统代理的问题
|
|
||||||
- 修复服务模式下操作超时后,后续操作报错或状态异常的问题
|
|
||||||
- 修复部分节点显示「Unknown」或无法测试延迟的问题
|
|
||||||
- 修复 `PASS-RULE` 节点被错误隐藏的问题
|
|
||||||
- 修复重启内核后未恢复上次所选节点的问题
|
|
||||||
- 修复部分代理组和首页图标无法显示、页面报错的问题
|
|
||||||
- 修复同时修改端口、TUN 等设置时,部分修改丢失的问题
|
|
||||||
- 修复 TUN 模式下 IPv6 Fake-IP 默认地址范围错误的问题
|
|
||||||
- 修复切换节点时应用可能卡住的问题
|
|
||||||
- 修复订阅文件被误删、删除或排序后列表异常的问题
|
|
||||||
- 修复订阅自动更新失败无提示、重启后更新时间延后及状态误报的问题
|
|
||||||
- 修复订阅编辑器因节点名称为空而崩溃、因格式错误而丢失内容的问题
|
|
||||||
- 修复 DNS 编辑器空内容报错、初始值覆盖已有设置的问题
|
|
||||||
- 修复关闭自动检查更新后,手动检查更新无效的问题
|
|
||||||
- 修复应用冷启动或从轻量模式打开界面时, 系统代理被重复设置的问题
|
|
||||||
|
|
||||||
**🖥️ Windows**
|
**🖥️ Windows**
|
||||||
|
|
||||||
- 修复 Windows 系统代理设置偶发失败的问题
|
- 修复 Windows 系统盘根目录的删除权限被误判,导致服务模式和 TUN 无法使用的问题
|
||||||
- 修复 Windows 关机被应用阻止的问题
|
|
||||||
|
|
||||||
**🍎 macOS**
|
**🍎 macOS**
|
||||||
|
|
||||||
- 修复 macOS 内核更新失败后无法启动的问题
|
- macOS 修复启动或重启应用时偶发内核启动失败,并误提示「需要更新系统服务」的问题
|
||||||
- 修复 macOS 需要管理员授权或开机自启时,系统代理设置失败的问题
|
- macOS 修复 VPN 接管网络或开机网络未就绪时的问题:服务模式内核无法启动、TUN 不可用、系统代理状态读取报错
|
||||||
- 修复 macOS 切换显示器后托盘速率样式不同步的问题
|
- macOS 修复用 `ipconfig set` 手动配置网卡后无法设置系统代理的问题
|
||||||
|
|
||||||
**🐧 Linux**
|
|
||||||
|
|
||||||
- 修复 Linux 安装或卸载服务时授权失败的问题
|
|
||||||
|
|
||||||
**🍎/🐧 macOS/Linux**
|
|
||||||
|
|
||||||
- 修复 macOS/Linux 系统代理绕过规则未正确生效的问题
|
|
||||||
- 修复 macOS/Linux 因旧版服务缓存权限异常而无法记住节点的问题
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary><strong> ✨ 新增功能 </strong></summary>
|
|
||||||
|
|
||||||
- 新增混合代理端口自动避让,被占用时临时使用其他端口
|
|
||||||
- 新增系统代理和 TUN 权限引导,可直接安装服务并恢复原设置
|
|
||||||
- 新增服务模式多用户隔离,支持旧版服务升级迁移
|
|
||||||
- 新增手动取消节点固定功能
|
|
||||||
- 新增代理组标题栏拖动调整,可交换组名和工具栏的位置
|
|
||||||
- 新增前置规则与后置规则互相移动功能
|
|
||||||
- 新增 DNS 覆写保护:订阅含自定义 DNS 时先确认,订阅更新后自动关闭覆写
|
|
||||||
- 新增代理页排查提示,方便检查订阅和内核状态
|
|
||||||
- 新增订阅更新频率提醒,间隔不足 24 小时时提示
|
|
||||||
- 新增启动失败提示,显示原因并保存启动日志
|
|
||||||
|
|
||||||
**🍎 macOS**
|
|
||||||
|
|
||||||
- 新增 macOS Liquid Glass 风格图标
|
|
||||||
- 新增 macOS 多用户启动保护,避免多个实例冲突
|
|
||||||
|
|
||||||
**🐧 Linux**
|
|
||||||
|
|
||||||
- 新增 Linux 系统主题跟随,自动切换深浅色外观
|
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary><strong> 🚀 优化改进 </strong></summary>
|
<summary><strong> 🚀 优化改进 </strong></summary>
|
||||||
|
|
||||||
- 优化 TUN 配置优先级:界面设置优先,其他选项仍可通过订阅、覆写和脚本调整
|
|
||||||
- 优化系统代理失败后的恢复流程,保持系统设置和界面状态一致
|
|
||||||
- 优化错误提示,支持复制完整原因,托盘和快捷键操作失败时也会提醒
|
|
||||||
- 优化代理列表刷新、排序和页面切换速度
|
|
||||||
- 优化首页节点操作,显示节点固定状态
|
|
||||||
- 优化外部链接检查,仅允许打开 HTTP/HTTPS 网页
|
|
||||||
- 优化更新说明排版,支持表格和提示框
|
|
||||||
- 优化搜索框聚焦、界面字体和拖动排序动画
|
|
||||||
- 优化后台连接和托盘刷新,降低资源占用
|
|
||||||
- 优化解锁检测,支持同时检测多个项目并逐项显示结果
|
|
||||||
- 优化日志记录,减少重复信息
|
|
||||||
- 移除便携模式,统一使用系统应用数据目录
|
|
||||||
- 优化繁体中文、俄语翻译及语言名称显示
|
|
||||||
|
|
||||||
**🖥️ Windows**
|
|
||||||
|
|
||||||
- 优化 Windows 自动更新,跳过安装语言选择
|
|
||||||
|
|
||||||
**🐧 Linux**
|
|
||||||
|
|
||||||
- 优化 Linux 系统代理设置,减少额外命令依赖,并明确提示缺少的命令
|
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
rust-i18n = "4.2.1"
|
rust-i18n = "4.2.2"
|
||||||
sys-locale = "0.3.2"
|
sys-locale = "0.3.2"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: على وشك الخروج
|
title: على وشك الخروج
|
||||||
body: Clash Verge على وشك الخروج.
|
body: Clash Verge على وشك الخروج.
|
||||||
appHidden:
|
|
||||||
title: تم إخفاء التطبيق
|
|
||||||
body: Clash Verge يعمل في الخلفية.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Update
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: A new version (v{version}) has been downloaded and is ready to install.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: Beenden steht bevor
|
title: Beenden steht bevor
|
||||||
body: Clash Verge wird gleich beendet.
|
body: Clash Verge wird gleich beendet.
|
||||||
appHidden:
|
|
||||||
title: Anwendung ausgeblendet
|
|
||||||
body: Clash Verge läuft im Hintergrund.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Update
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: A new version (v{version}) has been downloaded and is ready to install.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: About to Exit
|
title: About to Exit
|
||||||
body: Clash Verge is about to exit.
|
body: Clash Verge is about to exit.
|
||||||
appHidden:
|
|
||||||
title: Application Hidden
|
|
||||||
body: Clash Verge is running in the background.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Update
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: A new version (v{version}) has been downloaded and is ready to install.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: A punto de salir
|
title: A punto de salir
|
||||||
body: Clash Verge está a punto de salir.
|
body: Clash Verge está a punto de salir.
|
||||||
appHidden:
|
|
||||||
title: Aplicación oculta
|
|
||||||
body: Clash Verge se está ejecutando en segundo plano.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Update
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: A new version (v{version}) has been downloaded and is ready to install.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: در آستانه خروج
|
title: در آستانه خروج
|
||||||
body: Clash Verge در آستانه خروج است.
|
body: Clash Verge در آستانه خروج است.
|
||||||
appHidden:
|
|
||||||
title: برنامه پنهان شد
|
|
||||||
body: Clash Verge در پسزمینه در حال اجراست.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Update
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: A new version (v{version}) has been downloaded and is ready to install.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: Akan Keluar
|
title: Akan Keluar
|
||||||
body: Clash Verge akan keluar.
|
body: Clash Verge akan keluar.
|
||||||
appHidden:
|
|
||||||
title: Aplikasi Disembunyikan
|
|
||||||
body: Clash Verge berjalan di latar belakang.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Update
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: A new version (v{version}) has been downloaded and is ready to install.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: 終了間近
|
title: 終了間近
|
||||||
body: Clash Verge はまもなく終了します。
|
body: Clash Verge はまもなく終了します。
|
||||||
appHidden:
|
|
||||||
title: アプリが非表示
|
|
||||||
body: Clash Verge はバックグラウンドで実行中です。
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Update
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: A new version (v{version}) has been downloaded and is ready to install.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: 곧 종료
|
title: 곧 종료
|
||||||
body: Clash Verge가 곧 종료됩니다.
|
body: Clash Verge가 곧 종료됩니다.
|
||||||
appHidden:
|
|
||||||
title: 앱이 숨겨짐
|
|
||||||
body: Clash Verge가 백그라운드에서 실행 중입니다.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Update
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: A new version (v{version}) has been downloaded and is ready to install.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: Скорый выход
|
title: Скорый выход
|
||||||
body: Clash Verge скоро завершит работу.
|
body: Clash Verge скоро завершит работу.
|
||||||
appHidden:
|
|
||||||
title: Приложение скрыто
|
|
||||||
body: Clash Verge работает в фоновом режиме.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Обновление Clash Verge
|
title: Обновление Clash Verge
|
||||||
body: Новая версия (v{version}) скачана и готова к установке.
|
body: Новая версия (v{version}) скачана и готова к установке.
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ notifications:
|
|||||||
body: '{mode} moduna geçildi.'
|
body: '{mode} moduna geçildi.'
|
||||||
systemProxyToggled:
|
systemProxyToggled:
|
||||||
title: Sistem Vekil'i
|
title: Sistem Vekil'i
|
||||||
'on': System proxy has been enabled.
|
'on': Sistem vekili etkinleştirildi.
|
||||||
'off': System proxy has been disabled.
|
'off': Sistem vekili devre dışı bırakıldı.
|
||||||
systemProxyFailed:
|
systemProxyFailed:
|
||||||
title: Sistem Vekili
|
title: Sistem Vekili
|
||||||
body: Sistem vekil sunucusu ayarlanamadı. Nedenini görmek için Clash Verge'i açın.
|
body: Sistem vekil sunucusu ayarlanamadı. Nedenini görmek için Clash Verge'i açın.
|
||||||
@@ -18,8 +18,8 @@ notifications:
|
|||||||
body: Art arda birkaç başarısızlıktan sonra durdu. Nedenini görmek için Clash Verge'i açın.
|
body: Art arda birkaç başarısızlıktan sonra durdu. Nedenini görmek için Clash Verge'i açın.
|
||||||
tunModeToggled:
|
tunModeToggled:
|
||||||
title: TUN Modu
|
title: TUN Modu
|
||||||
'on': TUN mode has been enabled.
|
'on': TUN modu etkinleştirildi.
|
||||||
'off': TUN mode has been disabled.
|
'off': TUN modu devre dışı bırakıldı.
|
||||||
lightweightModeEntered:
|
lightweightModeEntered:
|
||||||
title: Hafif Mod
|
title: Hafif Mod
|
||||||
body: Hafif moda geçildi.
|
body: Hafif moda geçildi.
|
||||||
@@ -29,14 +29,11 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: Çıkış Yapılmak Üzere
|
title: Çıkış Yapılmak Üzere
|
||||||
body: Clash Verge kapanmak üzere.
|
body: Clash Verge kapanmak üzere.
|
||||||
appHidden:
|
|
||||||
title: Uygulama Gizlendi
|
|
||||||
body: Clash Verge arka planda çalışıyor.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Güncellemesi
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: Yeni bir sürüm (v{version}) indirildi ve kurulmaya hazır.
|
||||||
installNow: Install Now
|
installNow: Şimdi Kur
|
||||||
later: Later
|
later: Daha Sonra
|
||||||
service:
|
service:
|
||||||
adminInstallPrompt: Clash Verge hizmetini kurmak için yönetici ayrıcalıkları gerekir.
|
adminInstallPrompt: Clash Verge hizmetini kurmak için yönetici ayrıcalıkları gerekir.
|
||||||
adminUninstallPrompt: Clash Verge hizmetini kaldırmak için yönetici ayrıcalıkları gerekir.
|
adminUninstallPrompt: Clash Verge hizmetini kaldırmak için yönetici ayrıcalıkları gerekir.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: Чыгар алдыннан
|
title: Чыгар алдыннан
|
||||||
body: Clash Verge чыгарга җыена.
|
body: Clash Verge чыгарга җыена.
|
||||||
appHidden:
|
|
||||||
title: Кушымта яшерелде
|
|
||||||
body: Clash Verge фон режимында эшли.
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge Update
|
title: Clash Verge Update
|
||||||
body: A new version (v{version}) has been downloaded and is ready to install.
|
body: A new version (v{version}) has been downloaded and is ready to install.
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: 即将退出
|
title: 即将退出
|
||||||
body: Clash Verge 即将退出。
|
body: Clash Verge 即将退出。
|
||||||
appHidden:
|
|
||||||
title: 应用已隐藏
|
|
||||||
body: Clash Verge 正在后台运行。
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge 更新
|
title: Clash Verge 更新
|
||||||
body: 新版本 (v{version}) 已下载完成,是否立即安装?
|
body: 新版本 (v{version}) 已下载完成,是否立即安装?
|
||||||
|
|||||||
@@ -29,9 +29,6 @@ notifications:
|
|||||||
appQuit:
|
appQuit:
|
||||||
title: 即將退出
|
title: 即將退出
|
||||||
body: Clash Verge 即將退出。
|
body: Clash Verge 即將退出。
|
||||||
appHidden:
|
|
||||||
title: 應用已隱藏
|
|
||||||
body: Clash Verge 正在背景執行。
|
|
||||||
updateReady:
|
updateReady:
|
||||||
title: Clash Verge 更新
|
title: Clash Verge 更新
|
||||||
body: 新版本(v{version})已下載完成,是否立即安裝?
|
body: 新版本(v{version})已下載完成,是否立即安裝?
|
||||||
|
|||||||
@@ -1,3 +1,180 @@
|
|||||||
|
## v2.5.6
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||||
|
|
||||||
|
- 修复「代理集合」「规则集合」订阅响应较慢时更新误报失败、且不显示真实失败原因的问题
|
||||||
|
|
||||||
|
**🖥️ Windows**
|
||||||
|
|
||||||
|
- 修复 Windows 部分未安装服务的用户以普通权限运行时,内核无法启动的问题
|
||||||
|
- 修复 Windows 系统隔离权限被误判,导致服务模式和 TUN 无法使用的问题
|
||||||
|
- 修复 Windows 旧版服务状态残留导致无法重装的问题,自动备份可识别的残留并恢复安装
|
||||||
|
- 修复 Windows 服务已停止时,启动要等约两分钟才显示窗口的问题
|
||||||
|
- 优化 Windows 服务安全检查失败提示:用易懂的文字说明原因,并提供修复文档链接
|
||||||
|
|
||||||
|
**🍎 macOS**
|
||||||
|
|
||||||
|
- macOS 修复编辑规则时「规则内容」输入的首字母被自动转为大写的问题
|
||||||
|
- macOS 修复残留的服务进程导致内核无法启动、「继续使用 Sidecar」失败且无法修复的问题
|
||||||
|
- macOS 修复部分账户安装或修复服务时提示无法解析用户组而失败的问题
|
||||||
|
- macOS 优化用户目录在外置磁盘时服务拒绝启动内核的提示:说明原因并给出修复命令
|
||||||
|
- macOS 修复服务模式内核意外停止后,系统代理仍指向失效端口导致无法上网的问题
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><strong> 🚀 优化改进 </strong></summary>
|
||||||
|
|
||||||
|
- 优化内核启动失败和服务模式内核意外停止的提示:显示具体原因,并在窗口恢复后提示尚未解决的错误
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## v2.5.5
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||||
|
|
||||||
|
- 修复不同来源的订阅或规则集共用缓存路径时,服务模式无法启动内核的问题
|
||||||
|
- 优化文件错误日志,显示具体文件路径和失败原因
|
||||||
|
- 修复 DNS 覆写:空内容报错、初始值覆盖已有设置、已填写字段残留原配置、空字段在高级编辑器中缺失
|
||||||
|
- 修复 DNS 覆写中已填写的字段被 Merge 或 Script 覆盖的问题,空字段继续使用扩展配置
|
||||||
|
- 修复 Merge 覆写 DNS 策略、过滤条件和 hosts 时,旧条目仍被保留的问题
|
||||||
|
- 修复首次以管理员身份启动后,系统服务因数据目录所有权不符而拒绝启动内核的问题
|
||||||
|
- 修复重新安装服务后内核缺失、无法继续使用 Sidecar 的问题
|
||||||
|
- 修复内核未运行时,首页仍显示服务模式的问题
|
||||||
|
- 修复服务重装重复请求管理员授权、卸载后误报失败的问题
|
||||||
|
|
||||||
|
**🖥️ Windows**
|
||||||
|
|
||||||
|
- 修复 Windows 服务因路径或目录权限问题无法启动时,缺少重新安装服务的提示
|
||||||
|
- 修复 Windows 服务回退检查失败后状态未更新、无法重新尝试 Sidecar 的问题
|
||||||
|
|
||||||
|
**🐧 Linux**
|
||||||
|
|
||||||
|
- Linux 修复安装或修复服务后仍无法启动内核、开启 TUN 模式的问题
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><strong> 🚀 优化改进 </strong></summary>
|
||||||
|
|
||||||
|
- 优化扩展覆写配置和脚本编辑窗口,提示作用范围、执行顺序及应用设置优先级,并高亮当前步骤
|
||||||
|
- 优化 DNS 覆写开关:按订阅独立记忆,自动关闭仅影响当前订阅,并提示作用范围
|
||||||
|
- 优化系统服务兼容性检查:升级后服务版本或协议不兼容时,提示重新安装
|
||||||
|
- 优化预构建资源,补充 ASN 数据库文件
|
||||||
|
- 扩展配置或脚本写入由应用设置接管的字段时,弹出提示并在扩展日志中记录该值已被丢弃
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## v2.5.4
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><strong> 🐞 修复问题 </strong></summary>
|
||||||
|
|
||||||
|
- 修复首页代理组和节点下拉菜单:再次点击无法收起或误选、小窗口显示不全、切换模式后意外展开
|
||||||
|
- 修复系统代理切换失败后,开关状态显示错误的问题
|
||||||
|
- 修复代理守卫失败后反复重试且没有提示的问题
|
||||||
|
- 修复未开启系统代理时,启动仍提示代理错误的问题
|
||||||
|
- 修复恢复备份后未按备份设置关闭系统代理的问题
|
||||||
|
- 修复服务模式下操作超时后,后续操作报错或状态异常的问题
|
||||||
|
- 修复部分节点显示「Unknown」或无法测试延迟的问题
|
||||||
|
- 修复 `PASS-RULE` 节点被错误隐藏的问题
|
||||||
|
- 修复重启内核后未恢复上次所选节点的问题
|
||||||
|
- 修复部分代理组和首页图标无法显示、页面报错的问题
|
||||||
|
- 修复同时修改端口、TUN 等设置时,部分修改丢失的问题
|
||||||
|
- 修复 TUN 模式下 IPv6 Fake-IP 默认地址范围错误的问题
|
||||||
|
- 修复切换节点时应用可能卡住的问题
|
||||||
|
- 修复订阅文件被误删、删除或排序后列表异常的问题
|
||||||
|
- 修复订阅自动更新失败无提示、重启后更新时间延后及状态误报的问题
|
||||||
|
- 修复订阅编辑器因节点名称为空而崩溃、因格式错误而丢失内容的问题
|
||||||
|
- 修复 DNS 编辑器空内容报错、初始值覆盖已有设置的问题
|
||||||
|
- 修复关闭自动检查更新后,手动检查更新无效的问题
|
||||||
|
- 修复应用冷启动或从轻量模式打开界面时, 系统代理被重复设置的问题
|
||||||
|
|
||||||
|
**🖥️ Windows**
|
||||||
|
|
||||||
|
- 修复 Windows 管理员运行时,服务权限校验失败后无法继续使用代理的问题
|
||||||
|
- 修复 Windows 便携版或 Scoop 安装后服务内核无法启动的问题
|
||||||
|
- 修复 Windows 系统代理设置偶发失败的问题
|
||||||
|
- 修复 Windows 关机被应用阻止的问题
|
||||||
|
- 修复 Windows 服务模式下 TUN 使用 system/mixed 堆栈时无法接管流量的问题,防火墙放行规则改为自动添加
|
||||||
|
- 修复 Windows 配置中 GEO 规则较多时,首次启动内核失败的问题
|
||||||
|
|
||||||
|
**🍎 macOS**
|
||||||
|
|
||||||
|
- 修复 macOS 内核更新失败后无法启动的问题
|
||||||
|
- 修复 macOS 需要管理员授权或开机自启时,系统代理设置失败的问题
|
||||||
|
- 修复 macOS 切换显示器后托盘速率样式不同步的问题
|
||||||
|
|
||||||
|
**🐧 Linux**
|
||||||
|
|
||||||
|
- 修复 Linux 安装或卸载服务时授权失败的问题
|
||||||
|
- 修复 Fedora 等启用 SELinux 的系统更新后服务无法启动的问题
|
||||||
|
|
||||||
|
**🍎/🐧 macOS/Linux**
|
||||||
|
|
||||||
|
- 修复 macOS/Linux 系统代理绕过规则未正确生效的问题
|
||||||
|
- 修复 macOS/Linux 因旧版服务缓存权限异常而无法记住节点的问题
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><strong> ✨ 新增功能 </strong></summary>
|
||||||
|
|
||||||
|
- 新增混合代理端口自动避让,被占用时临时使用其他端口
|
||||||
|
- 新增系统代理和 TUN 权限引导,可直接安装服务并恢复原设置
|
||||||
|
- 新增服务模式多用户隔离,支持旧版服务升级迁移
|
||||||
|
- 新增手动取消节点固定功能
|
||||||
|
- 新增代理组标题栏拖动调整,可交换组名和工具栏的位置
|
||||||
|
- 新增前置规则与后置规则互相移动功能
|
||||||
|
- 新增 DNS 覆写保护:订阅含自定义 DNS 时先确认,订阅更新后自动关闭覆写
|
||||||
|
- 新增代理页排查提示,方便检查订阅和内核状态
|
||||||
|
- 新增订阅更新频率提醒,间隔不足 24 小时时提示
|
||||||
|
- 新增启动失败提示,显示原因并保存启动日志
|
||||||
|
- 新增 TUN「Mips」堆栈选项,需配合 mihomo v1.19.31 及以上内核
|
||||||
|
|
||||||
|
**🍎 macOS**
|
||||||
|
|
||||||
|
- 新增 macOS Liquid Glass 风格图标
|
||||||
|
- 新增 macOS 多用户启动保护,避免多个实例冲突
|
||||||
|
|
||||||
|
**🐧 Linux**
|
||||||
|
|
||||||
|
- 新增 Linux 系统主题跟随,自动切换深浅色外观
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><strong> 🚀 优化改进 </strong></summary>
|
||||||
|
|
||||||
|
- 优化首页节点菜单关闭时的刷新性能
|
||||||
|
- 优化 TUN 配置优先级:界面设置优先,其他选项仍可通过订阅、覆写和脚本调整
|
||||||
|
- 优化 DNS 覆写:仅覆盖已填写的字段和已开启的开关,留空或关闭的项保留订阅设置
|
||||||
|
- 优化系统代理失败后的恢复流程,保持系统设置和界面状态一致
|
||||||
|
- 优化错误提示,支持复制完整原因,托盘和快捷键操作失败时也会提醒
|
||||||
|
- 优化代理列表刷新、排序和页面切换速度
|
||||||
|
- 优化首页节点操作,显示节点固定状态
|
||||||
|
- 优化外部链接检查,仅允许打开 HTTP/HTTPS 网页
|
||||||
|
- 优化更新说明排版,支持表格和提示框
|
||||||
|
- 优化搜索框聚焦、界面字体和拖动排序动画
|
||||||
|
- 优化后台连接和托盘刷新,降低资源占用
|
||||||
|
- 优化解锁检测,支持同时检测多个项目并逐项显示结果
|
||||||
|
- 优化日志记录,减少重复信息
|
||||||
|
- 移除便携模式,统一使用系统应用数据目录
|
||||||
|
- 优化繁体中文、俄语翻译及语言名称显示
|
||||||
|
|
||||||
|
**🖥️ Windows**
|
||||||
|
|
||||||
|
- 优化 Windows 自动更新,跳过安装语言选择
|
||||||
|
|
||||||
|
**🐧 Linux**
|
||||||
|
|
||||||
|
- 优化 Linux 系统代理设置,减少额外命令依赖,并明确提示缺少的命令
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
|
||||||
## v2.5.2
|
## v2.5.2
|
||||||
|
|
||||||
### 🐞 修复问题
|
### 🐞 修复问题
|
||||||
|
|||||||
@@ -17,7 +17,8 @@
|
|||||||
"ignoreBinaries": ["rustc", "cc"],
|
"ignoreBinaries": ["rustc", "cc"],
|
||||||
"ignoreDependencies": ["lint-staged"],
|
"ignoreDependencies": ["lint-staged"],
|
||||||
"ignoreIssues": {
|
"ignoreIssues": {
|
||||||
"src/types/generated/**": ["exports", "types"]
|
"src/types/generated/**": ["exports", "types"],
|
||||||
|
"src/services/contract.ts": ["exports", "types"]
|
||||||
},
|
},
|
||||||
"cycles": {
|
"cycles": {
|
||||||
"dynamicImports": true
|
"dynamicImports": true
|
||||||
|
|||||||
+57
-55
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "clash-verge",
|
"name": "clash-verge",
|
||||||
"version": "2.5.4",
|
"version": "2.5.7",
|
||||||
"license": "GPL-3.0-only",
|
"license": "GPL-3.0-only",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepare": "husky || true",
|
"prepare": "husky || true",
|
||||||
@@ -30,6 +30,8 @@
|
|||||||
"i18n:check": "node scripts/cleanup-unused-i18n.mjs",
|
"i18n:check": "node scripts/cleanup-unused-i18n.mjs",
|
||||||
"i18n:format": "node scripts/cleanup-unused-i18n.mjs --align --apply",
|
"i18n:format": "node scripts/cleanup-unused-i18n.mjs --align --apply",
|
||||||
"i18n:types": "node scripts/generate-i18n-keys.mjs",
|
"i18n:types": "node scripts/generate-i18n-keys.mjs",
|
||||||
|
"gen:contract": "node scripts/gen-contract.mjs",
|
||||||
|
"arch:check": "node scripts/check-architecture.mjs listen emit invoke",
|
||||||
"typecheck": "tsc --noEmit",
|
"typecheck": "tsc --noEmit",
|
||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:watch": "vitest",
|
"test:watch": "vitest",
|
||||||
@@ -49,90 +51,90 @@
|
|||||||
"@emotion/styled": "^11.14.1",
|
"@emotion/styled": "^11.14.1",
|
||||||
"@juggle/resize-observer": "^3.4.0",
|
"@juggle/resize-observer": "^3.4.0",
|
||||||
"@monaco-editor/react": "^4.7.0",
|
"@monaco-editor/react": "^4.7.0",
|
||||||
"@mui/icons-material": "^9.0.1",
|
"@mui/icons-material": "^9.4.0",
|
||||||
"@mui/material": "^9.0.1",
|
"@mui/material": "^9.4.0",
|
||||||
"@tanstack/react-virtual": "^3.13.25",
|
"@tanstack/react-virtual": "^3.14.13",
|
||||||
"@tauri-apps/api": "2.11.1",
|
"@tauri-apps/api": "2.11.1",
|
||||||
"@tauri-apps/plugin-clipboard-manager": "^2.3.2",
|
"@tauri-apps/plugin-clipboard-manager": "^2.3.3",
|
||||||
"@tauri-apps/plugin-dialog": "^2.7.1",
|
"@tauri-apps/plugin-dialog": "^2.7.3",
|
||||||
"@tauri-apps/plugin-fs": "^2.5.1",
|
"@tauri-apps/plugin-fs": "^2.5.2",
|
||||||
"@tauri-apps/plugin-http": "~2.5.9",
|
"@tauri-apps/plugin-http": "~2.6.1",
|
||||||
"@tauri-apps/plugin-opener": "2.5.4",
|
"@tauri-apps/plugin-opener": "2.5.5",
|
||||||
"@tauri-apps/plugin-updater": "2.10.1",
|
"@tauri-apps/plugin-updater": "2.12.0",
|
||||||
"ahooks": "^3.9.7",
|
"ahooks": "^3.10.0",
|
||||||
"cidr-block": "^2.3.0",
|
"cidr-block": "^2.3.0",
|
||||||
"compare-versions": "^6.1.1",
|
"compare-versions": "^6.1.1",
|
||||||
"dayjs": "1.11.21",
|
"dayjs": "1.11.23",
|
||||||
"foxact": "^0.3.4",
|
"foxact": "^0.3.12",
|
||||||
"foxts": "^5.4.2",
|
"foxts": "^5.9.1",
|
||||||
"i18next": "^26.2.0",
|
"i18next": "^26.4.2",
|
||||||
"js-yaml": "^5.0.0",
|
"js-yaml": "^5.4.2",
|
||||||
"lodash-es": "^4.18.1",
|
"lodash-es": "^4.18.1",
|
||||||
"meta-json-schema": "^1.19.25",
|
"meta-json-schema": "^1.19.31",
|
||||||
"monaco-editor": "^0.56.0",
|
"monaco-editor": "^0.56.0",
|
||||||
"monaco-yaml": "^5.5.0",
|
"monaco-yaml": "^5.5.1",
|
||||||
"nanoid": "^6.0.0",
|
"nanoid": "^6.0.1",
|
||||||
"qrcode.react": "^4.2.0",
|
"qrcode.react": "^4.2.0",
|
||||||
"react": "19.2.8",
|
"react": "19.3.0",
|
||||||
"react-dom": "19.2.8",
|
"react-dom": "19.3.0",
|
||||||
"react-error-boundary": "6.1.2",
|
"react-error-boundary": "6.1.5",
|
||||||
"react-hook-form": "^7.76.1",
|
"react-hook-form": "^7.88.0",
|
||||||
"react-i18next": "17.0.11",
|
"react-i18next": "17.0.14",
|
||||||
"react-markdown": "10.1.0",
|
"react-markdown": "10.1.0",
|
||||||
"react-router": "^8.0.0",
|
"react-router": "^8.4.0",
|
||||||
"rehype-raw": "^7.0.0",
|
"rehype-raw": "^7.0.0",
|
||||||
"rehype-sanitize": "^6.0.0",
|
"rehype-sanitize": "^6.0.0",
|
||||||
"remark-gfm": "^4.0.1",
|
"remark-gfm": "^4.0.1",
|
||||||
"swr": "^2.4.2",
|
"swr": "^2.5.1",
|
||||||
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
|
"tauri-plugin-mihomo-api": "github:clash-verge-rev/tauri-plugin-mihomo#main",
|
||||||
"types-pac": "^1.0.3",
|
"types-pac": "^1.0.3",
|
||||||
"validator": "^13.15.35"
|
"validator": "^13.15.35"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@actions/github": "^9.1.1",
|
"@actions/github": "^9.1.1",
|
||||||
"@biomejs/biome": "^2.4.15",
|
"@biomejs/biome": "^2.5.14",
|
||||||
"@eslint-react/eslint-plugin": "^5.8.5",
|
"@eslint-react/eslint-plugin": "^5.20.5",
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
"@tauri-apps/cli": "2.11.4",
|
"@tauri-apps/cli": "2.11.4",
|
||||||
"@types/lodash-es": "^4.17.12",
|
"@types/lodash-es": "^4.17.12",
|
||||||
"@types/node": "^24.12.4",
|
"@types/node": "^24.13.6",
|
||||||
"@types/react": "19.2.18",
|
"@types/react": "19.3.0",
|
||||||
"@types/react-dom": "19.2.4",
|
"@types/react-dom": "19.3.0",
|
||||||
"@types/validator": "^13.15.10",
|
"@types/validator": "^13.15.10",
|
||||||
"@vitejs/plugin-legacy": "^8.0.2",
|
"@vitejs/plugin-legacy": "^8.2.3",
|
||||||
"@vitejs/plugin-react": "^6.0.2",
|
"@vitejs/plugin-react": "^6.1.1",
|
||||||
"@wdio/tauri-service": "1.3.0",
|
"@wdio/tauri-service": "1.4.0",
|
||||||
"adm-zip": "^0.6.0",
|
"adm-zip": "^0.6.1",
|
||||||
"axios": "^1.16.1",
|
"axios": "^1.20.0",
|
||||||
"cli-color": "^2.0.4",
|
"cli-color": "^2.0.4",
|
||||||
"commander": "^15.0.0",
|
"commander": "^15.0.0",
|
||||||
"cross-env": "^10.1.0",
|
"cross-env": "^10.1.0",
|
||||||
"eslint": "^10.4.0",
|
"eslint": "^10.11.0",
|
||||||
"eslint-import-resolver-typescript": "^4.4.4",
|
"eslint-import-resolver-typescript": "^4.4.5",
|
||||||
"eslint-plugin-es-x": "^10.0.0",
|
"eslint-plugin-es-x": "^10.0.1",
|
||||||
"eslint-plugin-import-x": "^4.16.2",
|
"eslint-plugin-import-x": "^4.17.1",
|
||||||
"eslint-plugin-react-compiler": "19.1.0-rc.2",
|
"eslint-plugin-react-compiler": "19.1.0-rc.2",
|
||||||
"eslint-plugin-react-hooks": "^7.1.1",
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
"eslint-plugin-react-refresh": "^0.5.2",
|
"eslint-plugin-react-refresh": "^0.5.7",
|
||||||
"eslint-plugin-sukka": "^10.0.0",
|
"eslint-plugin-sukka": "^10.2.0",
|
||||||
"eslint-plugin-unused-imports": "^4.4.1",
|
"eslint-plugin-unused-imports": "^4.4.1",
|
||||||
"glob": "^13.0.6",
|
"glob": "^13.0.6",
|
||||||
"globals": "^17.6.0",
|
"globals": "^17.12.0",
|
||||||
"https-proxy-agent": "^9.0.0",
|
"https-proxy-agent": "^9.1.0",
|
||||||
"husky": "^9.1.7",
|
"husky": "^9.1.7",
|
||||||
"jiti": "^2.7.0",
|
"jiti": "^2.7.0",
|
||||||
"knip": "6.32.1",
|
"knip": "6.35.1",
|
||||||
"lint-staged": "^17.0.5",
|
"lint-staged": "^17.5.1",
|
||||||
"sass": "^1.100.0",
|
"sass": "^1.104.1",
|
||||||
"tar": "^7.5.15",
|
"tar": "^7.5.22",
|
||||||
"terser": "^5.48.0",
|
"terser": "^5.51.2",
|
||||||
"typescript": "^6.0.3",
|
"typescript": "^6.0.3",
|
||||||
"typescript-eslint": "^8.59.4",
|
"typescript-eslint": "^8.70.0",
|
||||||
"vite": "^8.0.14",
|
"vite": "^8.3.0",
|
||||||
"vite-plugin-svgr": "^5.2.0",
|
"vite-plugin-svgr": "^5.2.0",
|
||||||
"vitest": "^5.0.0",
|
"vitest": "^5.0.1",
|
||||||
"webdriverio": "9.30.0",
|
"webdriverio": "9.31.9",
|
||||||
"ws": "8.21.0"
|
"ws": "8.21.3"
|
||||||
},
|
},
|
||||||
"lint-staged": {
|
"lint-staged": {
|
||||||
"*.{ts,tsx,js,mjs}": [
|
"*.{ts,tsx,js,mjs}": [
|
||||||
@@ -144,5 +146,5 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"packageManager": "pnpm@12.4.1"
|
"packageManager": "pnpm@12.8.1"
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+1301
-1335
File diff suppressed because it is too large
Load Diff
+17
-1
@@ -56,6 +56,12 @@
|
|||||||
"matchFileNames": [".github/workflows/*.lock.yml"],
|
"matchFileNames": [".github/workflows/*.lock.yml"],
|
||||||
"enabled": false
|
"enabled": false
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"description": "Ignore gh-aw dependency updates in workflow files; upgrade agentic workflows with gh aw upgrade instead",
|
||||||
|
"matchFileNames": [".github/workflows/**"],
|
||||||
|
"matchPackageNames": ["/gh-aw/"],
|
||||||
|
"enabled": false
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"description": "Skip TypeScript 7.0 series",
|
"description": "Skip TypeScript 7.0 series",
|
||||||
"matchManagers": ["npm"],
|
"matchManagers": ["npm"],
|
||||||
@@ -78,7 +84,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"description": "Group PNPM version updates across package.json, tool-versions, workflows, and devcontainer",
|
"description": "Group PNPM version updates across package.json, tool-versions, workflows, and devcontainer",
|
||||||
"matchPackageNames": ["pnpm", "ghcr.io/devcontainers/features/pnpm"],
|
"matchPackageNames": ["pnpm"],
|
||||||
"groupName": "pnpm"
|
"groupName": "pnpm"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -131,6 +137,16 @@
|
|||||||
],
|
],
|
||||||
"depNameTemplate": "rust-lang/rust",
|
"depNameTemplate": "rust-lang/rust",
|
||||||
"datasourceTemplate": "github-releases"
|
"datasourceTemplate": "github-releases"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"customType": "regex",
|
||||||
|
"description": "Update pnpm in devcontainer.json",
|
||||||
|
"fileMatch": ["^\\.devcontainer/devcontainer\\.json$"],
|
||||||
|
"matchStrings": [
|
||||||
|
"\"ghcr\\.io/devcontainers/features/node:[^\"]+\":\\s*\\{[^}]*\"pnpmVersion\":\\s*\"(?<currentValue>[^\"]+)\""
|
||||||
|
],
|
||||||
|
"depNameTemplate": "pnpm",
|
||||||
|
"datasourceTemplate": "npm"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"postUpdateOptions": ["pnpmDedupe"],
|
"postUpdateOptions": ["pnpmDedupe"],
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Architecture grep gates for the frontend contract flow. Select gates via
|
||||||
|
* argv:
|
||||||
|
*
|
||||||
|
* node scripts/check-architecture.mjs listen emit invoke
|
||||||
|
*
|
||||||
|
* - listen/emit: the Tauri event API may only be used under src/services/bus/**
|
||||||
|
* (the event bus). Detected as a bare `listen(`/`emit(` call (member calls
|
||||||
|
* like `this.emit(` are unrelated class methods) or as importing the name
|
||||||
|
* from '@tauri-apps/api/event'.
|
||||||
|
* - invoke: `invoke(` calls may exist only under src/services/**.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const ROOT = path.resolve(import.meta.dirname, '..')
|
||||||
|
const SRC = path.join(ROOT, 'src')
|
||||||
|
|
||||||
|
const tauriEventImport = (name) =>
|
||||||
|
new RegExp(
|
||||||
|
`import\\s*\\{[^}]*\\b${name}\\b[^}]*\\}\\s*from\\s*'@tauri-apps/api/event'`,
|
||||||
|
)
|
||||||
|
|
||||||
|
const GATES = {
|
||||||
|
listen: {
|
||||||
|
patterns: [/(?<![.\w])listen\(/, tauriEventImport('listen')],
|
||||||
|
allowed: (file) => file.startsWith('src/services/bus/'),
|
||||||
|
description: 'Tauri listen outside the event bus (src/services/bus)',
|
||||||
|
},
|
||||||
|
emit: {
|
||||||
|
patterns: [/(?<![.\w])emit\(/, tauriEventImport('emit')],
|
||||||
|
allowed: (file) => file.startsWith('src/services/bus/'),
|
||||||
|
description: 'Tauri emit outside the event bus (src/services/bus)',
|
||||||
|
},
|
||||||
|
invoke: {
|
||||||
|
patterns: [/\binvoke\(/],
|
||||||
|
allowed: (file) => file.startsWith('src/services/'),
|
||||||
|
description: 'invoke( outside the services layer (src/services)',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
const walk = (dir) => {
|
||||||
|
const entries = fs.readdirSync(dir, { withFileTypes: true })
|
||||||
|
return entries.flatMap((entry) => {
|
||||||
|
const full = path.join(dir, entry.name)
|
||||||
|
if (entry.isDirectory()) return walk(full)
|
||||||
|
return /\.(ts|tsx|js|jsx|mts|mjs)$/.test(entry.name) ? [full] : []
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const selected = process.argv.slice(2)
|
||||||
|
if (selected.length === 0) {
|
||||||
|
console.error('usage: check-architecture.mjs <gate>... (listen|emit|invoke)')
|
||||||
|
process.exit(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
let violations = 0
|
||||||
|
for (const gate of selected) {
|
||||||
|
const rule = GATES[gate]
|
||||||
|
if (!rule) {
|
||||||
|
console.error(`unknown gate: ${gate}`)
|
||||||
|
process.exit(2)
|
||||||
|
}
|
||||||
|
for (const file of walk(SRC)) {
|
||||||
|
const relative = path.relative(ROOT, file).replaceAll('\\', '/')
|
||||||
|
if (rule.allowed(relative)) continue
|
||||||
|
const lines = fs.readFileSync(file, 'utf8').split('\n')
|
||||||
|
lines.forEach((line, index) => {
|
||||||
|
if (rule.patterns.some((pattern) => pattern.test(line))) {
|
||||||
|
violations += 1
|
||||||
|
console.error(
|
||||||
|
`[arch] ${rule.description}: ${relative}:${index + 1}: ${line.trim()}`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (violations > 0) {
|
||||||
|
console.error(`[arch] ${violations} violation(s) found`)
|
||||||
|
process.exit(1)
|
||||||
|
}
|
||||||
|
console.log('[arch] no violations')
|
||||||
+86
-142
@@ -1,36 +1,23 @@
|
|||||||
import { spawn } from 'node:child_process'
|
import { execFileSync, spawn } from 'node:child_process'
|
||||||
import { createHash } from 'node:crypto'
|
import { access } from 'node:fs/promises'
|
||||||
import { access, mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
||||||
import { dirname, join, resolve } from 'node:path'
|
import { dirname, join, resolve } from 'node:path'
|
||||||
import { fileURLToPath } from 'node:url'
|
import { fileURLToPath } from 'node:url'
|
||||||
|
|
||||||
export const developmentServiceDirectoryEnvironment =
|
export const developmentServiceDirectoryEnvironment =
|
||||||
'CLASH_VERGE_DEV_SERVICE_DIR'
|
'CLASH_VERGE_DEV_SERVICE_DIR'
|
||||||
const developmentServiceInstallerEnvironment =
|
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||||
'CLASH_VERGE_DEV_SERVICE_INSTALLER'
|
|
||||||
|
|
||||||
const scriptDirectory = dirname(fileURLToPath(import.meta.url))
|
|
||||||
const repositoryRoot = resolve(scriptDirectory, '..')
|
|
||||||
const serviceRepository = resolve(
|
const serviceRepository = resolve(
|
||||||
repositoryRoot,
|
repositoryRoot,
|
||||||
'..',
|
'..',
|
||||||
'clash-verge-service-ipc',
|
'clash-verge-service-ipc',
|
||||||
)
|
)
|
||||||
const serviceManifest = join(serviceRepository, 'Cargo.toml')
|
const serviceManifest = join(serviceRepository, 'Cargo.toml')
|
||||||
const developmentReceipt = join(
|
export const developmentServiceWatchPaths = [
|
||||||
repositoryRoot,
|
'src',
|
||||||
'target',
|
'resources',
|
||||||
'development-service.json',
|
'Cargo.toml',
|
||||||
)
|
'Cargo.lock',
|
||||||
|
].map((name) => join(serviceRepository, name))
|
||||||
function executable(name, platform) {
|
|
||||||
return join(
|
|
||||||
serviceRepository,
|
|
||||||
'target',
|
|
||||||
'debug',
|
|
||||||
platform === 'win32' ? `${name}.exe` : name,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function run(command, args, options = {}) {
|
function run(command, args, options = {}) {
|
||||||
return new Promise((resolvePromise, reject) => {
|
return new Promise((resolvePromise, reject) => {
|
||||||
@@ -39,10 +26,15 @@ function run(command, args, options = {}) {
|
|||||||
stdio: options.stdio ?? 'inherit',
|
stdio: options.stdio ?? 'inherit',
|
||||||
windowsHide: true,
|
windowsHide: true,
|
||||||
})
|
})
|
||||||
|
let stdout = ''
|
||||||
|
child.stdout?.setEncoding('utf8')
|
||||||
|
child.stdout?.on('data', (chunk) => {
|
||||||
|
stdout += chunk
|
||||||
|
})
|
||||||
child.once('error', reject)
|
child.once('error', reject)
|
||||||
child.once('exit', (code, signal) => {
|
child.once('close', (code, signal) => {
|
||||||
if (code === 0) {
|
if (code === 0) {
|
||||||
resolvePromise()
|
resolvePromise(stdout)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
const error = new Error(
|
const error = new Error(
|
||||||
@@ -54,134 +46,86 @@ function run(command, args, options = {}) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async function hashFiles(paths) {
|
export async function prepareDevelopmentService() {
|
||||||
const hash = createHash('sha256')
|
|
||||||
for (const path of paths) {
|
|
||||||
hash.update(await readFile(path))
|
|
||||||
}
|
|
||||||
return hash.digest('hex')
|
|
||||||
}
|
|
||||||
|
|
||||||
async function readInstalledFingerprint() {
|
|
||||||
try {
|
|
||||||
const parsed = JSON.parse(await readFile(developmentReceipt, 'utf8'))
|
|
||||||
return typeof parsed.fingerprint === 'string' ? parsed.fingerprint : null
|
|
||||||
} catch {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function writeInstalledFingerprint(fingerprint) {
|
|
||||||
await mkdir(dirname(developmentReceipt), { recursive: true })
|
|
||||||
await writeFile(
|
|
||||||
developmentReceipt,
|
|
||||||
`${JSON.stringify({ fingerprint }, null, 2)}\n`,
|
|
||||||
'utf8',
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function windowsElevationInvocation(installer, environment = process.env) {
|
|
||||||
const script = [
|
|
||||||
"$ErrorActionPreference = 'Stop'",
|
|
||||||
`$installer = [Environment]::GetEnvironmentVariable('${developmentServiceInstallerEnvironment}', 'Process')`,
|
|
||||||
"if ([string]::IsNullOrWhiteSpace($installer)) { throw 'Development service installer path is missing' }",
|
|
||||||
'$child = Start-Process -FilePath $installer -Verb RunAs -Wait -PassThru -WindowStyle Hidden',
|
|
||||||
'exit $child.ExitCode',
|
|
||||||
].join('; ')
|
|
||||||
return {
|
|
||||||
command: 'powershell.exe',
|
|
||||||
args: ['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', script],
|
|
||||||
env: {
|
|
||||||
...environment,
|
|
||||||
[developmentServiceInstallerEnvironment]: installer,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function elevateInstaller(installer, platform) {
|
|
||||||
if (platform === 'win32') {
|
|
||||||
const invocation = windowsElevationInvocation(installer)
|
|
||||||
return run(invocation.command, invocation.args, { env: invocation.env })
|
|
||||||
}
|
|
||||||
|
|
||||||
if (platform === 'darwin') {
|
|
||||||
const script =
|
|
||||||
'on run argv\nset toolPath to item 1 of argv\nset groupId to item 2 of argv\ndo shell script "CLASH_VERGE_SERVICE_GID=" & quoted form of groupId & " " & quoted form of toolPath with administrator privileges\nend run'
|
|
||||||
return run('osascript', ['-e', script, installer, String(process.getgid())])
|
|
||||||
}
|
|
||||||
|
|
||||||
if (typeof process.getuid === 'function' && process.getuid() === 0) {
|
|
||||||
return run(installer, [], {
|
|
||||||
env: {
|
|
||||||
...process.env,
|
|
||||||
CLASH_VERGE_SERVICE_GID: String(process.getgid()),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await run('pkexec', [installer])
|
|
||||||
} catch (error) {
|
|
||||||
if (error.code !== 'ENOENT' && error.exitCode !== 127) throw error
|
|
||||||
await run('sudo', [installer])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function prepareDevelopmentService({
|
|
||||||
platform = process.platform,
|
|
||||||
} = {}) {
|
|
||||||
await access(serviceManifest)
|
await access(serviceManifest)
|
||||||
await run('cargo', [
|
const output = await run(
|
||||||
'build',
|
'cargo',
|
||||||
'--manifest-path',
|
[
|
||||||
serviceManifest,
|
'build',
|
||||||
'--features',
|
'--manifest-path',
|
||||||
'standalone,client,development-channel',
|
serviceManifest,
|
||||||
'--bins',
|
'--target-dir',
|
||||||
])
|
process.env.CARGO_TARGET_DIR ||
|
||||||
|
join(serviceRepository, 'target', 'development'),
|
||||||
|
'--features',
|
||||||
|
'standalone,client,development-channel',
|
||||||
|
'--bins',
|
||||||
|
'--message-format=json-render-diagnostics',
|
||||||
|
],
|
||||||
|
{ stdio: ['inherit', 'pipe', 'inherit'] },
|
||||||
|
)
|
||||||
|
|
||||||
const service = executable('clash-verge-service', platform)
|
const artifacts = new Map()
|
||||||
await access(service)
|
for (const line of output.split(/\r?\n/).filter(Boolean)) {
|
||||||
return dirname(service)
|
const artifact = JSON.parse(line)
|
||||||
|
if (
|
||||||
|
artifact.reason === 'compiler-artifact' &&
|
||||||
|
resolve(artifact.manifest_path) === serviceManifest &&
|
||||||
|
artifact.target.kind.includes('bin') &&
|
||||||
|
artifact.executable
|
||||||
|
) {
|
||||||
|
artifacts.set(artifact.target.name, resolve(artifact.executable))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const executables = [
|
||||||
|
'clash-verge-service',
|
||||||
|
'clash-verge-service-install',
|
||||||
|
'clash-verge-service-uninstall',
|
||||||
|
'service-integration-driver',
|
||||||
|
].map((name) => {
|
||||||
|
const executable = artifacts.get(name)
|
||||||
|
if (!executable)
|
||||||
|
throw new Error(`Cargo did not report the ${name} executable`)
|
||||||
|
return executable
|
||||||
|
})
|
||||||
|
const serviceDirectory = dirname(executables[0])
|
||||||
|
for (const executable of executables) {
|
||||||
|
if (dirname(executable) !== serviceDirectory) {
|
||||||
|
throw new Error(
|
||||||
|
'Development service tools were built in different directories',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
await access(executable)
|
||||||
|
}
|
||||||
|
return serviceDirectory
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function ensureDevelopmentService({
|
export async function ensureDevelopmentService({
|
||||||
platform = process.platform,
|
platform = process.platform,
|
||||||
} = {}) {
|
} = {}) {
|
||||||
const serviceDirectory = await prepareDevelopmentService({ platform })
|
const serviceDirectory = await prepareDevelopmentService()
|
||||||
const service = join(
|
const extension = platform === 'win32' ? '.exe' : ''
|
||||||
serviceDirectory,
|
|
||||||
platform === 'win32' ? 'clash-verge-service.exe' : 'clash-verge-service',
|
|
||||||
)
|
|
||||||
const installer = join(
|
const installer = join(
|
||||||
serviceDirectory,
|
serviceDirectory,
|
||||||
platform === 'win32'
|
`clash-verge-service-install${extension}`,
|
||||||
? 'clash-verge-service-install.exe'
|
|
||||||
: 'clash-verge-service-install',
|
|
||||||
)
|
)
|
||||||
const driver = join(
|
const host = execFileSync('rustc', ['-vV'], { encoding: 'utf8' }).match(
|
||||||
serviceDirectory,
|
/^host: (.+)$/m,
|
||||||
platform === 'win32'
|
)?.[1]
|
||||||
? 'service-integration-driver.exe'
|
if (!host) throw new Error('rustc did not report its host target')
|
||||||
: 'service-integration-driver',
|
const args = ['--prepare-install', '--ensure']
|
||||||
)
|
for (const name of ['verge-mihomo', 'verge-mihomo-alpha']) {
|
||||||
const fingerprint = await hashFiles([service, installer])
|
args.push(
|
||||||
const installedFingerprint = await readInstalledFingerprint()
|
'--core',
|
||||||
|
`${name}${extension}`,
|
||||||
if (installedFingerprint === fingerprint) {
|
join(
|
||||||
try {
|
repositoryRoot,
|
||||||
await run(driver, ['probe'], { stdio: 'ignore' })
|
'src-tauri',
|
||||||
return serviceDirectory
|
'sidecar',
|
||||||
} catch {
|
`${name}-${host}${extension}`,
|
||||||
// The expected binary is installed but unavailable; the repair tool owns recovery.
|
),
|
||||||
}
|
)
|
||||||
}
|
}
|
||||||
|
await run(installer, args)
|
||||||
try {
|
|
||||||
await elevateInstaller(installer, platform)
|
|
||||||
} catch (error) {
|
|
||||||
if (error.exitCode !== 75) throw error
|
|
||||||
}
|
|
||||||
await run(driver, ['ready'])
|
|
||||||
await writeInstalledFingerprint(fingerprint)
|
|
||||||
return serviceDirectory
|
return serviceDirectory
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
} from './dev-control.mjs'
|
} from './dev-control.mjs'
|
||||||
import {
|
import {
|
||||||
developmentServiceDirectoryEnvironment,
|
developmentServiceDirectoryEnvironment,
|
||||||
|
developmentServiceWatchPaths,
|
||||||
ensureDevelopmentService,
|
ensureDevelopmentService,
|
||||||
prepareDevelopmentService,
|
prepareDevelopmentService,
|
||||||
} from './dev-service.mjs'
|
} from './dev-service.mjs'
|
||||||
@@ -31,6 +32,9 @@ export function buildTauriInvocation(
|
|||||||
env.RUSTFLAGS = '--cfg tokio_unstable'
|
env.RUSTFLAGS = '--cfg tokio_unstable'
|
||||||
args.push('tokio-trace')
|
args.push('tokio-trace')
|
||||||
}
|
}
|
||||||
|
for (const path of developmentServiceWatchPaths) {
|
||||||
|
args.push('--additional-watch-folders', path)
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
command: 'pnpm',
|
command: 'pnpm',
|
||||||
args,
|
args,
|
||||||
|
|||||||
@@ -0,0 +1,91 @@
|
|||||||
|
import { execFileSync } from 'node:child_process'
|
||||||
|
import fs from 'node:fs'
|
||||||
|
import path from 'node:path'
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regenerates src/services/contract.ts from the backend wire contract.
|
||||||
|
* Source of truth: `cargo run -p clash-verge --bin frontend-contract` inside
|
||||||
|
* src-tauri, which serializes the same enum variants and event payloads the
|
||||||
|
* app emits at runtime. CI reruns this and fails on a non-empty diff.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const ROOT = path.resolve(import.meta.dirname, '..')
|
||||||
|
const OUT = path.join(ROOT, 'src/services/contract.ts')
|
||||||
|
|
||||||
|
const contract = JSON.parse(
|
||||||
|
execFileSync(
|
||||||
|
'cargo',
|
||||||
|
['run', '-p', 'clash-verge', '--bin', 'frontend-contract', '-q'],
|
||||||
|
{
|
||||||
|
cwd: path.join(ROOT, 'src-tauri'),
|
||||||
|
encoding: 'utf8',
|
||||||
|
maxBuffer: 16 * 1024 * 1024,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
if (contract.version !== 1) {
|
||||||
|
throw new Error(`unsupported wire contract version: ${contract.version}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TS type per event, derived from the serialized sample payload's JSON shape. */
|
||||||
|
const payloadType = (name, sample) => {
|
||||||
|
if (sample === null) return 'null'
|
||||||
|
if (typeof sample === 'string') return 'string'
|
||||||
|
if (Array.isArray(sample)) {
|
||||||
|
if (name === 'verge://notice-message') return '[NoticeStatus, string]'
|
||||||
|
throw new Error(`unexpected array payload for ${name}`)
|
||||||
|
}
|
||||||
|
if (typeof sample === 'object') {
|
||||||
|
const keys = Object.keys(sample)
|
||||||
|
if (keys.length === 1 && keys[0] === 'uid') return '{ uid: string }'
|
||||||
|
if (name === 'verge://run-state-changed') return 'RunState'
|
||||||
|
throw new Error(`unexpected object payload for ${name}: ${keys.join(',')}`)
|
||||||
|
}
|
||||||
|
throw new Error(`unexpected payload for ${name}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const needsRunState = contract.events.some(
|
||||||
|
(e) => e.name === 'verge://run-state-changed',
|
||||||
|
)
|
||||||
|
if (!needsRunState)
|
||||||
|
throw new Error('run-state-changed event missing from contract')
|
||||||
|
|
||||||
|
const lines = []
|
||||||
|
lines.push(
|
||||||
|
'// @generated by scripts/gen-contract.mjs from the backend wire contract. DO NOT EDIT.',
|
||||||
|
)
|
||||||
|
lines.push('// Regen: pnpm gen:contract')
|
||||||
|
lines.push('')
|
||||||
|
lines.push("import type { RunState } from './cmds'")
|
||||||
|
lines.push('')
|
||||||
|
lines.push(
|
||||||
|
'/** Wire status strings from NoticeStatus; keep in sync via `pnpm gen:contract`. */',
|
||||||
|
)
|
||||||
|
lines.push('export type NoticeStatus =')
|
||||||
|
for (const status of contract.noticeStatuses) {
|
||||||
|
lines.push(` | ${JSON.stringify(status)}`)
|
||||||
|
}
|
||||||
|
lines.push('')
|
||||||
|
lines.push('/** Event name → payload type for every backend-emitted event. */')
|
||||||
|
lines.push('export interface VergeEventPayloads {')
|
||||||
|
for (const event of contract.events) {
|
||||||
|
const key = JSON.stringify(event.name)
|
||||||
|
lines.push(` ${key}: ${payloadType(event.name, event.sample)}`)
|
||||||
|
}
|
||||||
|
lines.push('}')
|
||||||
|
lines.push('')
|
||||||
|
|
||||||
|
const content = `${lines.join('\n')}\n`
|
||||||
|
fs.writeFileSync(OUT, content)
|
||||||
|
|
||||||
|
// Match the repo's biome style so CI parity (`git diff --exit-code`) is stable.
|
||||||
|
execFileSync(
|
||||||
|
process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm',
|
||||||
|
['exec', 'biome', 'format', '--write', path.relative(ROOT, OUT)],
|
||||||
|
{ cwd: ROOT, stdio: 'ignore' },
|
||||||
|
)
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`[gen-contract] wrote ${path.relative(ROOT, OUT)}: ${contract.events.length} events, ${contract.noticeStatuses.length} statuses`,
|
||||||
|
)
|
||||||
+53
-11
@@ -1,9 +1,9 @@
|
|||||||
import { execFileSync, execSync } from 'child_process'
|
import { execFileSync, execSync } from 'node:child_process'
|
||||||
import { createHash } from 'crypto'
|
import { createHash } from 'node:crypto'
|
||||||
import fs from 'fs'
|
import fs from 'node:fs'
|
||||||
import fsp from 'fs/promises'
|
import fsp from 'node:fs/promises'
|
||||||
import path from 'path'
|
import path from 'node:path'
|
||||||
import zlib from 'zlib'
|
import zlib from 'node:zlib'
|
||||||
|
|
||||||
import AdmZip from 'adm-zip'
|
import AdmZip from 'adm-zip'
|
||||||
import { glob } from 'glob'
|
import { glob } from 'glob'
|
||||||
@@ -485,7 +485,7 @@ const resolvePlugin = async () => {
|
|||||||
const zip = new AdmZip(tempZip)
|
const zip = new AdmZip(tempZip)
|
||||||
zip
|
zip
|
||||||
.getEntries()
|
.getEntries()
|
||||||
.forEach((entry) => log_debug(`"SimpleSC" entry`, entry.entryName))
|
.forEach((entry) => void log_debug(`"SimpleSC" entry`, entry.entryName))
|
||||||
zip.extractAllTo(tempDir, true)
|
zip.extractAllTo(tempDir, true)
|
||||||
if (fs.existsSync(tempDll)) {
|
if (fs.existsSync(tempDll)) {
|
||||||
await fsp.cp(tempDll, pluginPath, { recursive: true, force: true })
|
await fsp.cp(tempDll, pluginPath, { recursive: true, force: true })
|
||||||
@@ -553,7 +553,7 @@ const SERVICE_BINARIES = [
|
|||||||
|
|
||||||
function serviceFileInfo(name) {
|
function serviceFileInfo(name) {
|
||||||
const ext = platform === 'win32' ? '.exe' : ''
|
const ext = platform === 'win32' ? '.exe' : ''
|
||||||
const suffix = platform === 'linux' ? '-' + SIDECAR_HOST : ''
|
const suffix = platform === 'linux' ? `-${SIDECAR_HOST}` : ''
|
||||||
return {
|
return {
|
||||||
sourceFile: `${name}${ext}`,
|
sourceFile: `${name}${ext}`,
|
||||||
targetFile: `${name}${suffix}${ext}`,
|
targetFile: `${name}${suffix}${ext}`,
|
||||||
@@ -586,6 +586,41 @@ async function resolveServiceBundle() {
|
|||||||
path.join(cwd, 'src-tauri', 'Cargo.toml'),
|
path.join(cwd, 'src-tauri', 'Cargo.toml'),
|
||||||
'utf8',
|
'utf8',
|
||||||
)
|
)
|
||||||
|
const serviceDependency = cargoManifest
|
||||||
|
.split(/\r?\n/)
|
||||||
|
.find((line) => line.trimStart().startsWith('clash_verge_service_ipc ='))
|
||||||
|
const sourcePath = serviceDependency?.match(/\bpath\s*=\s*"([^"]+)"/)?.[1]
|
||||||
|
if (sourcePath) {
|
||||||
|
const manifest = path.resolve(cwd, 'src-tauri', sourcePath, 'Cargo.toml')
|
||||||
|
const targetDirectory = path.join(cwd, 'target', 'bundled-service')
|
||||||
|
execFileSync(
|
||||||
|
'cargo',
|
||||||
|
[
|
||||||
|
'build',
|
||||||
|
'--manifest-path',
|
||||||
|
manifest,
|
||||||
|
'--target-dir',
|
||||||
|
targetDirectory,
|
||||||
|
'--target',
|
||||||
|
SIDECAR_HOST,
|
||||||
|
'--release',
|
||||||
|
'--features',
|
||||||
|
'standalone,client',
|
||||||
|
'--bins',
|
||||||
|
],
|
||||||
|
{ stdio: 'inherit' },
|
||||||
|
)
|
||||||
|
await fsp.mkdir(SERVICE_DIR, { recursive: true })
|
||||||
|
for (const { sourceFile, targetPath } of files) {
|
||||||
|
await fsp.copyFile(
|
||||||
|
path.join(targetDirectory, SIDECAR_HOST, 'release', sourceFile),
|
||||||
|
targetPath,
|
||||||
|
)
|
||||||
|
if (platform !== 'win32') await fsp.chmod(targetPath, 0o755)
|
||||||
|
await updateHashCache(targetPath)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
const { archiveFile, downloadURL } = resolveServiceRelease(
|
const { archiveFile, downloadURL } = resolveServiceRelease(
|
||||||
cargoManifest,
|
cargoManifest,
|
||||||
SIDECAR_HOST,
|
SIDECAR_HOST,
|
||||||
@@ -604,8 +639,9 @@ async function resolveServiceBundle() {
|
|||||||
const zip = new AdmZip(tempArchive)
|
const zip = new AdmZip(tempArchive)
|
||||||
zip
|
zip
|
||||||
.getEntries()
|
.getEntries()
|
||||||
.forEach((entry) =>
|
.forEach(
|
||||||
log_debug('"clash-verge-service-ipc" entry:', entry.entryName),
|
(entry) =>
|
||||||
|
void log_debug('"clash-verge-service-ipc" entry:', entry.entryName),
|
||||||
)
|
)
|
||||||
zip.extractAllTo(tempDir, true)
|
zip.extractAllTo(tempDir, true)
|
||||||
} else {
|
} else {
|
||||||
@@ -652,7 +688,7 @@ async function resolveCoreHashes() {
|
|||||||
.digest('hex')
|
.digest('hex')
|
||||||
lines.push(`!define ${define} "${digest}"`)
|
lines.push(`!define ${define} "${digest}"`)
|
||||||
}
|
}
|
||||||
await fsp.writeFile(CORE_HASHES_NSH, lines.join('\n') + '\n')
|
await fsp.writeFile(CORE_HASHES_NSH, `${lines.join('\n')}\n`)
|
||||||
log_success(`Generated ${CORE_HASHES_NSH}`)
|
log_success(`Generated ${CORE_HASHES_NSH}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -661,6 +697,11 @@ const resolveMmdb = () =>
|
|||||||
file: 'Country.mmdb',
|
file: 'Country.mmdb',
|
||||||
downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/country.mmdb`,
|
downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/country.mmdb`,
|
||||||
})
|
})
|
||||||
|
const resolveASNMmdb = () =>
|
||||||
|
resolveResource({
|
||||||
|
file: 'ASN.mmdb',
|
||||||
|
downloadURL: `https://github.com/MetaCubeX/meta-rules-dat/releases/download/latest/GeoLite2-ASN.mmdb`,
|
||||||
|
})
|
||||||
const resolveGeosite = () =>
|
const resolveGeosite = () =>
|
||||||
resolveResource({
|
resolveResource({
|
||||||
file: 'geosite.dat',
|
file: 'geosite.dat',
|
||||||
@@ -706,6 +747,7 @@ const tasks = [
|
|||||||
{ name: 'plugin', func: resolvePlugin, retry: 5, winOnly: true },
|
{ name: 'plugin', func: resolvePlugin, retry: 5, winOnly: true },
|
||||||
{ name: 'service', func: resolveServiceBundle, retry: 5 },
|
{ name: 'service', func: resolveServiceBundle, retry: 5 },
|
||||||
{ name: 'mmdb', func: resolveMmdb, retry: 5 },
|
{ name: 'mmdb', func: resolveMmdb, retry: 5 },
|
||||||
|
{ name: 'asn_mmdb', func: resolveASNMmdb, retry: 5 },
|
||||||
{ name: 'geosite', func: resolveGeosite, retry: 5 },
|
{ name: 'geosite', func: resolveGeosite, retry: 5 },
|
||||||
{ name: 'geoip', func: resolveGeoIP, retry: 5 },
|
{ name: 'geoip', func: resolveGeoIP, retry: 5 },
|
||||||
{
|
{
|
||||||
|
|||||||
+50
-15
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* CLI tool to update version numbers in package.json, src-tauri/Cargo.toml, and src-tauri/tauri.conf.json.
|
* CLI tool to update version numbers in package.json, src-tauri/Cargo.toml, Cargo.lock, and src-tauri/tauri.conf.json.
|
||||||
*
|
*
|
||||||
* Usage:
|
* Usage:
|
||||||
* pnpm release-version <version>
|
* pnpm release-version <version>
|
||||||
@@ -108,17 +108,20 @@ async function updatePackageVersion(newVersion) {
|
|||||||
'[INFO]: Current package.json version is: ',
|
'[INFO]: Current package.json version is: ',
|
||||||
packageJson.version,
|
packageJson.version,
|
||||||
)
|
)
|
||||||
packageJson.version = newVersion.startsWith('v')
|
const versionWithoutV = newVersion.startsWith('v')
|
||||||
? newVersion.slice(1)
|
? newVersion.slice(1)
|
||||||
: newVersion
|
: newVersion
|
||||||
await fs.writeFile(
|
const updatedData = data.replace(
|
||||||
packageJsonPath,
|
/^(\s*"version"\s*:\s*)"[^"]+"/m,
|
||||||
JSON.stringify(packageJson, null, 2),
|
`$1"${versionWithoutV}"`,
|
||||||
'utf8',
|
|
||||||
)
|
|
||||||
console.log(
|
|
||||||
`[INFO]: package.json version updated to: ${packageJson.version}`,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (updatedData === data) {
|
||||||
|
throw new Error('version field was not found in package.json')
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.writeFile(packageJsonPath, updatedData, 'utf8')
|
||||||
|
console.log(`[INFO]: package.json version updated to: ${versionWithoutV}`)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error updating package.json version:', error)
|
console.error('Error updating package.json version:', error)
|
||||||
throw error
|
throw error
|
||||||
@@ -153,6 +156,34 @@ async function updateCargoVersion(newVersion) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function updateCargoLockVersion(newVersion) {
|
||||||
|
const _dirname = process.cwd()
|
||||||
|
const cargoLockPath = path.join(_dirname, 'Cargo.lock')
|
||||||
|
const versionWithoutV = newVersion.startsWith('v')
|
||||||
|
? newVersion.slice(1)
|
||||||
|
: newVersion
|
||||||
|
const packageVersionPattern =
|
||||||
|
/(\[\[package\]\]\r?\nname = "clash-verge"\r?\nversion = )"[^"]+"/
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = await fs.readFile(cargoLockPath, 'utf8')
|
||||||
|
const updatedData = data.replace(
|
||||||
|
packageVersionPattern,
|
||||||
|
`$1"${versionWithoutV}"`,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (updatedData === data) {
|
||||||
|
throw new Error('clash-verge package entry was not found in Cargo.lock')
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.writeFile(cargoLockPath, updatedData, 'utf8')
|
||||||
|
console.log(`[INFO]: Cargo.lock version updated to: ${versionWithoutV}`)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error updating Cargo.lock version:', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function updateTauriConfigVersion(newVersion) {
|
async function updateTauriConfigVersion(newVersion) {
|
||||||
const _dirname = process.cwd()
|
const _dirname = process.cwd()
|
||||||
const tauriConfigPath = path.join(_dirname, 'src-tauri', 'tauri.conf.json')
|
const tauriConfigPath = path.join(_dirname, 'src-tauri', 'tauri.conf.json')
|
||||||
@@ -168,13 +199,16 @@ async function updateTauriConfigVersion(newVersion) {
|
|||||||
tauriConfig.version,
|
tauriConfig.version,
|
||||||
)
|
)
|
||||||
|
|
||||||
tauriConfig.version = versionWithoutV
|
const updatedData = data.replace(
|
||||||
|
/^(\s*"version"\s*:\s*)"[^"]+"/m,
|
||||||
await fs.writeFile(
|
`$1"${versionWithoutV}"`,
|
||||||
tauriConfigPath,
|
|
||||||
JSON.stringify(tauriConfig, null, 2),
|
|
||||||
'utf8',
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (updatedData === data) {
|
||||||
|
throw new Error('version field was not found in tauri.conf.json')
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.writeFile(tauriConfigPath, updatedData, 'utf8')
|
||||||
console.log(
|
console.log(
|
||||||
`[INFO]: tauri.conf.json version updated to: ${versionWithoutV}`,
|
`[INFO]: tauri.conf.json version updated to: ${versionWithoutV}`,
|
||||||
)
|
)
|
||||||
@@ -239,6 +273,7 @@ async function main(versionArg) {
|
|||||||
console.log(`[INFO]: Updating versions to: ${newVersion}`)
|
console.log(`[INFO]: Updating versions to: ${newVersion}`)
|
||||||
await updatePackageVersion(newVersion)
|
await updatePackageVersion(newVersion)
|
||||||
await updateCargoVersion(newVersion)
|
await updateCargoVersion(newVersion)
|
||||||
|
await updateCargoLockVersion(newVersion)
|
||||||
await updateTauriConfigVersion(newVersion)
|
await updateTauriConfigVersion(newVersion)
|
||||||
console.log('[SUCCESS]: All version updates completed successfully!')
|
console.log('[SUCCESS]: All version updates completed successfully!')
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -14,22 +14,13 @@ async function resolveUpdater() {
|
|||||||
const options = { owner: context.repo.owner, repo: context.repo.repo }
|
const options = { owner: context.repo.owner, repo: context.repo.repo }
|
||||||
const github = getOctokit(process.env.GITHUB_TOKEN)
|
const github = getOctokit(process.env.GITHUB_TOKEN)
|
||||||
|
|
||||||
const { data: tags } = await github.rest.repos.listTags({
|
const { data: latestRelease } =
|
||||||
...options,
|
await github.rest.repos.getLatestRelease(options)
|
||||||
per_page: 10,
|
const tag = { name: latestRelease.tag_name }
|
||||||
page: 1,
|
|
||||||
})
|
|
||||||
|
|
||||||
const tag = tags.find((t) => t.name.startsWith('v'))
|
|
||||||
|
|
||||||
console.log(tag)
|
console.log(tag)
|
||||||
console.log()
|
console.log()
|
||||||
|
|
||||||
const { data: latestRelease } = await github.rest.repos.getReleaseByTag({
|
|
||||||
...options,
|
|
||||||
tag: tag.name,
|
|
||||||
})
|
|
||||||
|
|
||||||
const updateData = {
|
const updateData = {
|
||||||
name: tag.name,
|
name: tag.name,
|
||||||
notes: await resolveUpdateLog(tag.name), // use Changelog.md
|
notes: await resolveUpdateLog(tag.name), // use Changelog.md
|
||||||
|
|||||||
+3
-2
@@ -40,10 +40,11 @@ async function resolveUpdater() {
|
|||||||
const tags = allTags
|
const tags = allTags
|
||||||
console.log(`Retrieved ${tags.length} tags in total`)
|
console.log(`Retrieved ${tags.length} tags in total`)
|
||||||
|
|
||||||
const stableTagRegex = /^v\d+\.\d+\.\d+$/
|
|
||||||
const preReleaseRegex = /^(alpha|beta|rc|pre)$/i
|
const preReleaseRegex = /^(alpha|beta|rc|pre)$/i
|
||||||
|
|
||||||
const stableTag = tags.find((t) => stableTagRegex.test(t.name))
|
const { data: latestRelease } =
|
||||||
|
await github.rest.repos.getLatestRelease(options)
|
||||||
|
const stableTag = { name: latestRelease.tag_name }
|
||||||
const preReleaseTag = tags.find((t) => preReleaseRegex.test(t.name))
|
const preReleaseTag = tags.find((t) => preReleaseRegex.test(t.name))
|
||||||
|
|
||||||
console.log('All tags:', tags.map((t) => t.name).join(', '))
|
console.log('All tags:', tags.map((t) => t.name).join(', '))
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Backend Architecture Guardrails
|
||||||
|
|
||||||
|
These rules supplement the repository's root `AGENTS.md`.
|
||||||
|
|
||||||
|
1. **Keep configuration ownership in `config`.** Configuration writes must use
|
||||||
|
its draft and persistence APIs. Patch orchestration must use
|
||||||
|
`feat/effects.rs` and `feat/executor.rs`; refresh notifications must use
|
||||||
|
`core::notify::announce` after successful persistence and commit. This keeps
|
||||||
|
failed transactions from publishing state. Independent transactions retain
|
||||||
|
their boundaries and announce via `after_commit`; runtime-only profile
|
||||||
|
activation announces after successful application. New cross-layer
|
||||||
|
exceptions require a rationale in the PR and an update to this file.
|
||||||
|
2. **Register every new `IVerge` field.** Add one row, including an explicit
|
||||||
|
`NoEffect` where appropriate, to the exhaustive registry and preserve its
|
||||||
|
platform attributes. Keep the serialized-field coverage test passing. Manual
|
||||||
|
field-to-flag chains hide missing effects and are forbidden. No exceptions.
|
||||||
|
3. **Use `utils::retry` for bounded retries.** Do not introduce handwritten retry
|
||||||
|
loops, including `loop` plus `sleep`; preserve attempt budgets, delays and
|
||||||
|
terminal errors. Permanent watchers are the exception and must document
|
||||||
|
their exit conditions. Traversal of distinct data or port candidates is not
|
||||||
|
a retry policy.
|
||||||
|
4. **Keep notifications typed.** Send notice statuses through `NoticeStatus` and
|
||||||
|
use `Arc<str>` for notice message payloads. Preserve the event names and
|
||||||
|
status strings pinned by the golden tests. Status additions or changes
|
||||||
|
require frontend and backend changes in the same PR and an updated golden
|
||||||
|
list; this protects the wire contract. No exceptions.
|
||||||
|
5. **Preserve lock order.** The order is `config_write` before
|
||||||
|
`config_update_in_progress` before `lifecycle_lock`. Patch callers must use
|
||||||
|
the executor's guarded claim instead of independently combining these locks;
|
||||||
|
this preserves Busy rejection and prevents inverted acquisition. Existing
|
||||||
|
lifecycle and independent port transactions keep their established locking
|
||||||
|
boundaries. A new lock requires registering its position in this rule before
|
||||||
|
introducing acquisition sites.
|
||||||
|
6. **Prefer reconciliation.** Express new effects as idempotent `ensure`
|
||||||
|
operations in `EFFECT_ORDER` so repeated application converges on the same
|
||||||
|
state. A trigger chain is an exception only with a code comment explaining
|
||||||
|
why the operation cannot be idempotent. Configuration rollback does not
|
||||||
|
authorize reverse OS effects.
|
||||||
+18
-21
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "clash-verge"
|
name = "clash-verge"
|
||||||
version = "2.5.4"
|
version = "2.5.7"
|
||||||
description = "clash verge"
|
description = "clash verge"
|
||||||
authors = ["zzzgydi", "Tunglies", "wonfen", "MystiPanda"]
|
authors = ["zzzgydi", "Tunglies", "wonfen", "MystiPanda"]
|
||||||
license = "GPL-3.0-only"
|
license = "GPL-3.0-only"
|
||||||
@@ -59,14 +59,13 @@ smartstring = { workspace = true, features = ["serde"] }
|
|||||||
bitflags = { workspace = true }
|
bitflags = { workspace = true }
|
||||||
socket2 = { workspace = true }
|
socket2 = { workspace = true }
|
||||||
warp = { version = "0.4.3", features = ["server"] }
|
warp = { version = "0.4.3", features = ["server"] }
|
||||||
open = "5.4.1"
|
open = "5.4.4"
|
||||||
rfd = { version = "0.16.0", default-features = false, features = ["common-controls-v6"] }
|
rfd = { version = "0.16.0", default-features = false, features = ["common-controls-v6"] }
|
||||||
dirs = "7.0.0"
|
dirs = "7.0.0"
|
||||||
dunce = "1.0.5"
|
dunce = "1.0.5"
|
||||||
nanoid = "0.5"
|
nanoid = "0.5"
|
||||||
chrono = { workspace = true }
|
chrono = { workspace = true }
|
||||||
boa_engine = "0.21.1"
|
boa_engine = "0.22.0"
|
||||||
once_cell = { version = "1.21.4", features = ["parking_lot"] }
|
|
||||||
percent-encoding = "2.3.2"
|
percent-encoding = "2.3.2"
|
||||||
reqwest = { workspace = true }
|
reqwest = { workspace = true }
|
||||||
regex = { workspace = true }
|
regex = { workspace = true }
|
||||||
@@ -74,37 +73,37 @@ sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs.git", branch
|
|||||||
"guard",
|
"guard",
|
||||||
] }
|
] }
|
||||||
network-interface = { version = "2.0.5", features = ["serde"] }
|
network-interface = { version = "2.0.5", features = ["serde"] }
|
||||||
tauri-plugin-shell = "2.3.5"
|
tauri-plugin-shell = "2.3.6"
|
||||||
tauri-plugin-opener = "2.5.4"
|
tauri-plugin-opener = "2.5.5"
|
||||||
tauri-plugin-dialog = "2.7.2"
|
tauri-plugin-dialog = "2.7.3"
|
||||||
tauri-plugin-fs = "2.5.1"
|
tauri-plugin-fs = "2.5.2"
|
||||||
tauri-plugin-process = "2.3.1"
|
tauri-plugin-process = "2.3.1"
|
||||||
tauri-plugin-deep-link = "2.4.9"
|
tauri-plugin-deep-link = "2.4.10"
|
||||||
tauri-plugin-window-state = "2.4.1"
|
tauri-plugin-window-state = "2.4.1"
|
||||||
zip = "8.6.0"
|
zip = "8.6.0"
|
||||||
flate2 = "1.1.9"
|
flate2 = "1.1.10"
|
||||||
reqwest_dav = "0.3.3"
|
reqwest_dav = "0.3.3"
|
||||||
aes-gcm = { version = "0.11.0" }
|
aes-gcm = { version = "0.11.1" }
|
||||||
base64 = "0.23.1"
|
base64 = "0.23.1"
|
||||||
sha2 = "0.11"
|
sha2 = "0.11"
|
||||||
getrandom = "0.4.3"
|
getrandom = "0.4.3"
|
||||||
futures = "0.3.34"
|
futures = "0.3.34"
|
||||||
gethostname = "1.1.0"
|
gethostname = "1.1.0"
|
||||||
scopeguard = "1.2.0"
|
scopeguard = "1.2.0"
|
||||||
tauri-plugin-notification = "2.3.3"
|
tauri-plugin-notification = "2.4.0"
|
||||||
tokio-stream = "0.1.19"
|
tokio-stream = "0.1.19"
|
||||||
backon = { version = "1.6.0", features = ["tokio-sleep"] }
|
backon = { version = "1.6.0", features = ["tokio-sleep"] }
|
||||||
tauri-plugin-http = "2.5.9"
|
tauri-plugin-http = "2.6.1"
|
||||||
tracing = { workspace = true }
|
tracing = { workspace = true }
|
||||||
tauri-plugin-devtools = { version = "2.1.0", optional = true }
|
tauri-plugin-devtools = { version = "2.2.1", optional = true }
|
||||||
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", branch = "main" }
|
tauri-plugin-mihomo = { git = "https://github.com/clash-verge-rev/tauri-plugin-mihomo", branch = "main" }
|
||||||
async-trait = "0.1.92"
|
async-trait = "0.1.92"
|
||||||
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.6.9", version = "2.6.9", features = [
|
clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", tag = "v2.7.5", version = "2.7.5", features = [
|
||||||
"client",
|
"client",
|
||||||
] }
|
] }
|
||||||
arc-swap = "1.9.2"
|
arc-swap = "1.9.2"
|
||||||
tokio-rustls = "0.26.4"
|
tokio-rustls = "0.26.5"
|
||||||
rustls = { version = "0.23.43", features = ["ring"] }
|
rustls = { version = "0.23.45", features = ["ring"] }
|
||||||
webpki-roots = "1.0.9"
|
webpki-roots = "1.0.9"
|
||||||
dark-light = "3.0.0"
|
dark-light = "3.0.0"
|
||||||
bytes = "1.12.1"
|
bytes = "1.12.1"
|
||||||
@@ -114,9 +113,7 @@ tokio-util = { version = "0.7.19", features = ["time"] }
|
|||||||
libc = "0.2.189"
|
libc = "0.2.189"
|
||||||
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
tauri-plugin-wdio-webdriver = { version = "=1.3.0", optional = true }
|
tauri-plugin-wdio-webdriver = { version = "=1.4.0", optional = true }
|
||||||
core-foundation = "0.9"
|
|
||||||
system-configuration = "0.7"
|
|
||||||
objc2 = "0.6.4"
|
objc2 = "0.6.4"
|
||||||
objc2-foundation = { version = "0.3.2", features = [
|
objc2-foundation = { version = "0.3.2", features = [
|
||||||
"NSString",
|
"NSString",
|
||||||
@@ -150,7 +147,7 @@ windows-sys.workspace = true
|
|||||||
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
|
||||||
tauri-plugin-autostart = "2.5.1"
|
tauri-plugin-autostart = "2.5.1"
|
||||||
tauri-plugin-global-shortcut = "2.3.2"
|
tauri-plugin-global-shortcut = "2.3.2"
|
||||||
tauri-plugin-updater = "2.10.1"
|
tauri-plugin-updater = "2.12.0"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
criterion = { workspace = true }
|
criterion = { workspace = true }
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
set -e
|
||||||
|
|
||||||
|
chmod +x /usr/bin/clash-verge-service-install
|
||||||
|
chmod +x /usr/bin/clash-verge-service-uninstall
|
||||||
|
chmod +x /usr/bin/clash-verge-service
|
||||||
|
|
||||||
|
# The enforcement file exists in both Enforcing and Permissive mode.
|
||||||
|
if [ ! -e /sys/fs/selinux/enforce ]; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -x /usr/sbin/semanage ] || [ ! -x /usr/sbin/restorecon ]; then
|
||||||
|
echo "Warning: persistent SELinux rules were not installed; install policycoreutils and policycoreutils-python-utils, then reinstall this package. The service installer repairs executable labels, but a system relabel can reset them." >&2
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Keep these local rules on removal: they may predate this package or serve a standalone development service.
|
||||||
|
for service in clash-verge-service clash-verge-service-dev; do
|
||||||
|
for directory in bin cores; do
|
||||||
|
target="/var/lib/$service/$directory"
|
||||||
|
if [ -L "/var/lib/$service" ] || [ -L "$target" ]; then
|
||||||
|
echo "Refusing to relabel a symlinked service directory: $target" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
spec="$target(/.*)?"
|
||||||
|
# Older semanage versions reject -a when an exact rule already exists.
|
||||||
|
if ! add_error="$(/usr/sbin/semanage fcontext -a -t bin_t "$spec" 2>&1)"; then
|
||||||
|
if ! /usr/sbin/semanage fcontext -m -t bin_t "$spec"; then
|
||||||
|
printf '%s\n' "$add_error" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ -d "$target" ]; then
|
||||||
|
/usr/sbin/restorecon -R "$target"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
done
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
//! Prints the frontend wire contract as JSON to stdout. Zero new dependencies:
|
||||||
|
//! the payload is derived from the same serializers the app uses at runtime.
|
||||||
|
//! Consumed by scripts/gen-contract.mjs; CI regenerates and diffs the committed
|
||||||
|
//! TypeScript artifact.
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
println!("{}", app_lib::frontend_wire_contract());
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
|
use super::{CmdResult, CommandFailure, WithErrorCode as _, proxy_aware_coded_error, proxy_aware_error};
|
||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::feat;
|
use crate::feat;
|
||||||
use crate::utils::{dirs, yaml_emitter};
|
use crate::utils::{dirs, yaml_emitter};
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -56,14 +57,14 @@ pub async fn change_clash_core(clash_core: String) -> CmdResult<Option<CommandFa
|
|||||||
|
|
||||||
match CoreManager::global().restart_core().await {
|
match CoreManager::global().restart_core().await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
handle::Handle::notice_message("config_core::change_success", clash_core);
|
handle::Handle::notice(NoticeStatus::ConfigCoreChangeSuccess, clash_core.as_str());
|
||||||
handle::Handle::refresh_clash();
|
handle::Handle::refresh_clash();
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let failed = err.context("core changed but failed to restart");
|
let failed = err.context("core changed but failed to restart");
|
||||||
let error_msg: String = format!("{failed:#}").into();
|
let error_msg: String = format!("{failed:#}").into();
|
||||||
handle::Handle::notice_message("config_core::change_error", error_msg.clone());
|
handle::Handle::notice(NoticeStatus::ConfigCoreChangeError, error_msg.as_str());
|
||||||
logging!(error, Type::Core, "core changed but failed to restart: {error_msg}");
|
logging!(error, Type::Core, "core changed but failed to restart: {error_msg}");
|
||||||
Ok(Some(proxy_aware_coded_error(&failed, "CORE_CHANGE_FAILED")))
|
Ok(Some(proxy_aware_coded_error(&failed, "CORE_CHANGE_FAILED")))
|
||||||
}
|
}
|
||||||
@@ -72,7 +73,7 @@ pub async fn change_clash_core(clash_core: String) -> CmdResult<Option<CommandFa
|
|||||||
Err(err) => {
|
Err(err) => {
|
||||||
let error_msg: String = format!("{err:#}").into();
|
let error_msg: String = format!("{err:#}").into();
|
||||||
logging!(error, Type::Core, "failed to change core: {error_msg}");
|
logging!(error, Type::Core, "failed to change core: {error_msg}");
|
||||||
handle::Handle::notice_message("config_core::change_error", error_msg);
|
handle::Handle::notice(NoticeStatus::ConfigCoreChangeError, error_msg.as_str());
|
||||||
Ok(Some(proxy_aware_coded_error(&err, "CORE_CHANGE_FAILED")))
|
Ok(Some(proxy_aware_coded_error(&err, "CORE_CHANGE_FAILED")))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -133,8 +134,12 @@ pub fn take_dns_override_notice() -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn set_dns_override(enabled: bool, confirmation: Option<String>) -> CmdResult<feat::DnsOverrideOutcome> {
|
pub async fn set_dns_override(
|
||||||
feat::set_dns_override(enabled, confirmation)
|
profile_uid: String,
|
||||||
|
enabled: bool,
|
||||||
|
confirmation: Option<String>,
|
||||||
|
) -> CmdResult<feat::DnsOverrideOutcome> {
|
||||||
|
feat::set_dns_override(profile_uid, enabled, confirmation)
|
||||||
.await
|
.await
|
||||||
.map_err(|error| proxy_aware_coded_error(&error, "DNS_OVERRIDE_UPDATE_FAILED"))
|
.map_err(|error| proxy_aware_coded_error(&error, "DNS_OVERRIDE_UPDATE_FAILED"))
|
||||||
}
|
}
|
||||||
@@ -145,16 +150,26 @@ pub async fn apply_dns_config(apply: bool) -> CmdResult {
|
|||||||
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
|
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
|
||||||
|
|
||||||
if !dns_path.exists() {
|
if !dns_path.exists() {
|
||||||
logging!(warn, Type::Config, "DNS config file not found");
|
logging!(warn, Type::Config, "DNS config file not found: {}", dns_path.display());
|
||||||
return Err("DNS config file not found".into());
|
return Err("DNS config file not found".into());
|
||||||
}
|
}
|
||||||
|
|
||||||
let dns_yaml = fs::read_to_string(&dns_path).await.stringify_err_log(|e| {
|
let dns_yaml = fs::read_to_string(&dns_path).await.stringify_err_log(|e| {
|
||||||
logging!(error, Type::Config, "Failed to read DNS config: {e}");
|
logging!(
|
||||||
|
error,
|
||||||
|
Type::Config,
|
||||||
|
"Failed to read DNS config {}: {e}",
|
||||||
|
dns_path.display()
|
||||||
|
);
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let patch_config = serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&dns_yaml).stringify_err_log(|e| {
|
let patch_config = serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&dns_yaml).stringify_err_log(|e| {
|
||||||
logging!(error, Type::Config, "Failed to parse DNS config: {e}");
|
logging!(
|
||||||
|
error,
|
||||||
|
Type::Config,
|
||||||
|
"Failed to parse DNS config {}: {e}",
|
||||||
|
dns_path.display()
|
||||||
|
);
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let mut patch = serde_yaml_ng::Mapping::new();
|
let mut patch = serde_yaml_ng::Mapping::new();
|
||||||
@@ -210,7 +225,8 @@ pub async fn validate_dns_config() -> CmdResult<ValidationOutcome> {
|
|||||||
return Ok(ValidationOutcome::invalid_from_message("DNS config file not found"));
|
return Ok(ValidationOutcome::invalid_from_message("DNS config file not found"));
|
||||||
}
|
}
|
||||||
|
|
||||||
CoreConfigValidator::validate_config_file_outcome(dns_path_str, None)
|
// A fragment, not a runnable config; the merged result is validated on apply.
|
||||||
|
CoreConfigValidator::validate_config_file_outcome(dns_path_str, Some(true))
|
||||||
.await
|
.await
|
||||||
.stringify_err()
|
.stringify_err()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use crate::module::lightweight;
|
use crate::core::lightweight;
|
||||||
|
|
||||||
use super::CmdResult;
|
use super::CmdResult;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use super::{CmdResult, StringifyErr as _, WithErrorCode as _, coded_error};
|
use super::{CmdResult, StringifyErr as _, WithErrorCode as _, coded_error};
|
||||||
use crate::cmd::validate::{ValidationNoticeTarget, handle_validation_notice};
|
use crate::cmd::validate::{ValidationNoticeTarget, handle_validation_notice};
|
||||||
use crate::config::profiles;
|
use crate::config::profiles;
|
||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::utils::window_manager::WindowManager;
|
use crate::utils::window_manager::WindowManager;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
@@ -282,7 +283,7 @@ async fn handle_update_error<E: std::fmt::Display>(
|
|||||||
logging!(warn, Type::Cmd, "更新过程发生错误: {}", e,);
|
logging!(warn, Type::Cmd, "更新过程发生错误: {}", e,);
|
||||||
discard_and_restore(current_profile).await?;
|
discard_and_restore(current_profile).await?;
|
||||||
let message: String = e.to_string().into();
|
let message: String = e.to_string().into();
|
||||||
handle::Handle::notice_message("config_validate::boot_error", message.clone());
|
handle::Handle::notice(NoticeStatus::ConfigValidateBootError, message.as_str());
|
||||||
Ok(ValidationOutcome::invalid_from_message(message))
|
Ok(ValidationOutcome::invalid_from_message(message))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -84,6 +84,7 @@ pub async fn sync_tray_proxy_selection() -> CmdResult<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn run_tray_sync_loop() {
|
async fn run_tray_sync_loop() {
|
||||||
|
// Permanent watcher: keeps syncing until a pass finds no pending sync request.
|
||||||
loop {
|
loop {
|
||||||
match Tray::global().update_menu().await {
|
match Tray::global().update_menu().await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
|
|||||||
@@ -32,6 +32,11 @@ pub async fn get_runtime_logs() -> CmdResult<HashMap<String, Vec<(String, String
|
|||||||
Ok(Config::runtime().await.latest_arc().chain_logs.clone())
|
Ok(Config::runtime().await.latest_arc().chain_logs.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn take_discarded_keys_notice() -> Option<String> {
|
||||||
|
crate::enhance::take_discarded_keys_notice()
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn get_runtime_proxy_chain_config(proxy_chain_exit_node: String) -> CmdResult<String> {
|
pub async fn get_runtime_proxy_chain_config(proxy_chain_exit_node: String) -> CmdResult<String> {
|
||||||
let runtime = Config::runtime().await;
|
let runtime = Config::runtime().await;
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ use crate::{
|
|||||||
cmd::StringifyErr as _,
|
cmd::StringifyErr as _,
|
||||||
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
cmd::validate::{ValidationNoticeTarget, handle_validation_notice},
|
||||||
config::{Config, IProfiles, PrfItem},
|
config::{Config, IProfiles, PrfItem},
|
||||||
|
core::auto_backup::{AutoBackupManager, AutoBackupTrigger},
|
||||||
core::{
|
core::{
|
||||||
CoreManager, handle,
|
CoreManager, handle,
|
||||||
validate::{CoreConfigValidator, ValidationOutcome},
|
validate::{CoreConfigValidator, ValidationOutcome},
|
||||||
},
|
},
|
||||||
module::auto_backup::{AutoBackupManager, AutoBackupTrigger},
|
|
||||||
utils::dirs,
|
utils::dirs,
|
||||||
};
|
};
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
use clash_verge_logging::{Type, logging, logging_error};
|
||||||
|
|||||||
+162
-17
@@ -8,26 +8,81 @@ use crate::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult {
|
#[derive(Debug, PartialEq, Eq, serde::Serialize)]
|
||||||
|
#[serde(tag = "status", rename_all = "camelCase")]
|
||||||
|
pub enum ServiceInstallOutcome {
|
||||||
|
Installed,
|
||||||
|
#[cfg(any(windows, test))]
|
||||||
|
Sidecar {
|
||||||
|
reason: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn execute_service_operation_sync(status: ServiceStatus, error_code: &str) -> CmdResult<ServiceInstallOutcome> {
|
||||||
let manager = CoreManager::global();
|
let manager = CoreManager::global();
|
||||||
let _lifecycle = manager.lifecycle_lock.lock().await;
|
let result = {
|
||||||
if matches!(
|
let _lifecycle = manager.lifecycle_lock.lock().await;
|
||||||
&status,
|
if matches!(
|
||||||
ServiceStatus::ReinstallRequired | ServiceStatus::ForceReinstallRequired
|
&status,
|
||||||
) {
|
ServiceStatus::ReinstallRequired | ServiceStatus::ForceReinstallRequired
|
||||||
manager
|
) {
|
||||||
.controlled_stop_core_inner()
|
manager
|
||||||
.await
|
.controlled_stop_core_inner()
|
||||||
.map_err(|error| proxy_aware_coded_error(&error, error_code))?;
|
.await
|
||||||
}
|
.map_err(|error| proxy_aware_coded_error(&error, error_code))?;
|
||||||
SERVICE_MANAGER
|
}
|
||||||
.handle_service_status(status)
|
SERVICE_MANAGER.handle_service_status(status).await
|
||||||
.await
|
};
|
||||||
|
#[cfg(windows)]
|
||||||
|
return finish_service_installation(result, error_code, || manager.continue_with_sidecar()).await;
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
result
|
||||||
|
.map(|()| ServiceInstallOutcome::Installed)
|
||||||
.map_err(|error| proxy_aware_coded_error(&error, error_code))
|
.map_err(|error| proxy_aware_coded_error(&error, error_code))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(any(windows, test))]
|
||||||
|
async fn finish_service_installation<Fallback, FallbackFuture>(
|
||||||
|
installation: anyhow::Result<()>,
|
||||||
|
error_code: &str,
|
||||||
|
fallback: Fallback,
|
||||||
|
) -> CmdResult<ServiceInstallOutcome>
|
||||||
|
where
|
||||||
|
Fallback: FnOnce() -> FallbackFuture,
|
||||||
|
FallbackFuture: std::future::Future<Output = anyhow::Result<()>>,
|
||||||
|
{
|
||||||
|
let Err(error) = installation else {
|
||||||
|
return Ok(ServiceInstallOutcome::Installed);
|
||||||
|
};
|
||||||
|
let Some(failure) = error.downcast_ref::<clash_verge_service_ipc::management::InstallationVerificationError>()
|
||||||
|
else {
|
||||||
|
return Err(proxy_aware_coded_error(&error, error_code));
|
||||||
|
};
|
||||||
|
let reasons = failure
|
||||||
|
.status
|
||||||
|
.cores
|
||||||
|
.iter()
|
||||||
|
.filter_map(|core| match &core.availability {
|
||||||
|
clash_verge_service_ipc::CoreAvailability::Rejected { reason } => Some(format!("{}: {reason}", core.name)),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if reasons.is_empty() {
|
||||||
|
return Err(proxy_aware_coded_error(&error, error_code));
|
||||||
|
}
|
||||||
|
let reason = reasons.join("\n");
|
||||||
|
fallback().await.map_err(|error| {
|
||||||
|
proxy_aware_coded_error(
|
||||||
|
&error.context(format!("Service core rejected: {reason}; Sidecar fallback failed")),
|
||||||
|
"SERVICE_SIDECAR_FAILED",
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
Ok(ServiceInstallOutcome::Sidecar { reason })
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn install_service() -> CmdResult {
|
pub async fn install_service() -> CmdResult<ServiceInstallOutcome> {
|
||||||
execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await
|
execute_service_operation_sync(ServiceStatus::InstallRequired, "SERVICE_INSTALL_FAILED").await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,12 +95,12 @@ pub async fn uninstall_service() -> CmdResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn reinstall_service() -> CmdResult {
|
pub async fn reinstall_service() -> CmdResult<ServiceInstallOutcome> {
|
||||||
execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await
|
execute_service_operation_sync(ServiceStatus::ReinstallRequired, "SERVICE_REINSTALL_FAILED").await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub async fn repair_service() -> CmdResult {
|
pub async fn repair_service() -> CmdResult<ServiceInstallOutcome> {
|
||||||
execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await
|
execute_service_operation_sync(ServiceStatus::ForceReinstallRequired, "SERVICE_REPAIR_FAILED").await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,9 +112,99 @@ pub async fn continue_with_sidecar() -> CmdResult {
|
|||||||
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))
|
.map_err(|error| proxy_aware_coded_error(&error, "SERVICE_SIDECAR_FAILED"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn take_service_fallback_notice() -> bool {
|
||||||
|
crate::core::service::take_service_fallback_notice()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_core_startup_error() -> Option<crate::core::manager::CoreFailure> {
|
||||||
|
crate::core::CoreManager::global().get_startup_error()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn take_service_repair_notice() -> bool {
|
||||||
|
crate::core::service::take_service_repair_notice()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn take_service_owner_notice() -> Option<String> {
|
||||||
|
crate::core::service::take_service_owner_notice()
|
||||||
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
pub fn sync_runtime_providers() {
|
pub fn sync_runtime_providers() {
|
||||||
if matches!(*CoreManager::global().get_running_mode(), RunningMode::Service) {
|
if matches!(*CoreManager::global().get_running_mode(), RunningMode::Service) {
|
||||||
request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE);
|
request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SETTLE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
|
||||||
|
mod tests {
|
||||||
|
use super::{ServiceInstallOutcome, finish_service_installation};
|
||||||
|
use clash_verge_service_ipc::{
|
||||||
|
CoreAvailability, CoreInspection, InstallationStatus, ProtocolInfo, management::InstallationVerificationError,
|
||||||
|
};
|
||||||
|
use std::cell::Cell;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejected_installation_reports_sidecar_only_after_successful_continuation() {
|
||||||
|
let reason = "core path C:\\ is writable by Everyone";
|
||||||
|
for (availability, fallback_ready) in [
|
||||||
|
(None, false),
|
||||||
|
(Some(CoreAvailability::Missing), false),
|
||||||
|
(Some(CoreAvailability::DigestMismatch), false),
|
||||||
|
(Some(CoreAvailability::Rejected { reason: reason.into() }), false),
|
||||||
|
(Some(CoreAvailability::Rejected { reason: reason.into() }), true),
|
||||||
|
] {
|
||||||
|
let fallback_called = Cell::new(false);
|
||||||
|
let rejected = matches!(&availability, Some(CoreAvailability::Rejected { .. }));
|
||||||
|
let error = match availability {
|
||||||
|
Some(availability) => anyhow::Error::new(InstallationVerificationError {
|
||||||
|
status: InstallationStatus {
|
||||||
|
service_sha256: String::new(),
|
||||||
|
protocol: ProtocolInfo::current(),
|
||||||
|
cores: vec![CoreInspection {
|
||||||
|
name: "verge-mihomo.exe".into(),
|
||||||
|
availability,
|
||||||
|
}],
|
||||||
|
core_busy: false,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
None => anyhow::anyhow!("{reason}"),
|
||||||
|
}
|
||||||
|
.context("install service failed");
|
||||||
|
let result = finish_service_installation(Err(error), "SERVICE_INSTALL_FAILED", || async {
|
||||||
|
fallback_called.set(true);
|
||||||
|
anyhow::ensure!(fallback_ready, "another core is running");
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(fallback_called.get(), rejected);
|
||||||
|
if rejected && fallback_ready {
|
||||||
|
assert_eq!(
|
||||||
|
result,
|
||||||
|
Ok(ServiceInstallOutcome::Sidecar {
|
||||||
|
reason: format!("verge-mihomo.exe: {reason}")
|
||||||
|
})
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
let error = result.expect_err("an unavailable fallback must remain an error");
|
||||||
|
assert_eq!(
|
||||||
|
error.code.as_deref(),
|
||||||
|
Some(if rejected {
|
||||||
|
"SERVICE_SIDECAR_FAILED"
|
||||||
|
} else {
|
||||||
|
"SERVICE_INSTALL_FAILED"
|
||||||
|
})
|
||||||
|
);
|
||||||
|
if rejected {
|
||||||
|
assert!(error.detail.contains(reason));
|
||||||
|
assert!(error.detail.contains("another core is running"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::core::{
|
use crate::core::{
|
||||||
handle,
|
handle,
|
||||||
validate::{ValidationErrorKind, ValidationOutcome},
|
validate::{ValidationErrorKind, ValidationOutcome},
|
||||||
@@ -11,27 +12,27 @@ pub enum ValidationNoticeTarget {
|
|||||||
Script,
|
Script,
|
||||||
}
|
}
|
||||||
|
|
||||||
const fn notice_key(kind: ValidationErrorKind, target: ValidationNoticeTarget) -> &'static str {
|
const fn notice_key(kind: ValidationErrorKind, target: ValidationNoticeTarget) -> NoticeStatus {
|
||||||
match kind {
|
match kind {
|
||||||
ValidationErrorKind::FileMissing => "config_validate::file_not_found",
|
ValidationErrorKind::FileMissing => NoticeStatus::ConfigValidateFileNotFound,
|
||||||
ValidationErrorKind::FileRead => match target {
|
ValidationErrorKind::FileRead => match target {
|
||||||
ValidationNoticeTarget::Script => "config_validate::script_error",
|
ValidationNoticeTarget::Script => NoticeStatus::ConfigValidateScriptError,
|
||||||
_ => "config_validate::yaml_read_error",
|
_ => NoticeStatus::ConfigValidateYamlReadError,
|
||||||
},
|
},
|
||||||
ValidationErrorKind::YamlSyntax => match target {
|
ValidationErrorKind::YamlSyntax => match target {
|
||||||
ValidationNoticeTarget::Merge => "config_validate::merge_syntax_error",
|
ValidationNoticeTarget::Merge => NoticeStatus::ConfigValidateMergeSyntaxError,
|
||||||
ValidationNoticeTarget::Script => "config_validate::script_error",
|
ValidationNoticeTarget::Script => NoticeStatus::ConfigValidateScriptError,
|
||||||
ValidationNoticeTarget::Runtime => "config_validate::yaml_syntax_error",
|
ValidationNoticeTarget::Runtime => NoticeStatus::ConfigValidateYamlSyntaxError,
|
||||||
},
|
},
|
||||||
ValidationErrorKind::YamlMapping => match target {
|
ValidationErrorKind::YamlMapping => match target {
|
||||||
ValidationNoticeTarget::Merge => "config_validate::merge_mapping_error",
|
ValidationNoticeTarget::Merge => NoticeStatus::ConfigValidateMergeMappingError,
|
||||||
ValidationNoticeTarget::Script => "config_validate::script_error",
|
ValidationNoticeTarget::Script => NoticeStatus::ConfigValidateScriptError,
|
||||||
ValidationNoticeTarget::Runtime => "config_validate::yaml_mapping_error",
|
ValidationNoticeTarget::Runtime => NoticeStatus::ConfigValidateYamlMappingError,
|
||||||
},
|
},
|
||||||
ValidationErrorKind::ScriptSyntax => "config_validate::script_syntax_error",
|
ValidationErrorKind::ScriptSyntax => NoticeStatus::ConfigValidateScriptSyntaxError,
|
||||||
ValidationErrorKind::ScriptMissingMain => "config_validate::script_missing_main",
|
ValidationErrorKind::ScriptMissingMain => NoticeStatus::ConfigValidateScriptMissingMain,
|
||||||
ValidationErrorKind::ProcessTerminated => "config_validate::process_terminated",
|
ValidationErrorKind::ProcessTerminated => NoticeStatus::ConfigValidateProcessTerminated,
|
||||||
ValidationErrorKind::CoreRejected | ValidationErrorKind::Timeout => "config_validate::error",
|
ValidationErrorKind::CoreRejected | ValidationErrorKind::Timeout => NoticeStatus::ConfigValidateError,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,12 +41,12 @@ pub fn handle_validation_notice(outcome: &ValidationOutcome, target: ValidationN
|
|||||||
ValidationOutcome::Invalid { kind, message } => {
|
ValidationOutcome::Invalid { kind, message } => {
|
||||||
let status = notice_key(*kind, target);
|
let status = notice_key(*kind, target);
|
||||||
logging!(warn, Type::Config, "{} 验证失败: {}", file_type, message);
|
logging!(warn, Type::Config, "{} 验证失败: {}", file_type, message);
|
||||||
handle::Handle::notice_message(status, message.to_owned());
|
handle::Handle::notice(status, message.as_str());
|
||||||
}
|
}
|
||||||
ValidationOutcome::Busy | ValidationOutcome::Skipped { .. } => {
|
ValidationOutcome::Busy | ValidationOutcome::Skipped { .. } => {
|
||||||
let message = outcome.to_string();
|
let message = outcome.to_string();
|
||||||
logging!(warn, Type::Config, "{} 验证跳过: {}", file_type, message);
|
logging!(warn, Type::Config, "{} 验证跳过: {}", file_type, message);
|
||||||
handle::Handle::notice_message("config_validate::error", message);
|
handle::Handle::notice(NoticeStatus::ConfigValidateError, message.as_str());
|
||||||
}
|
}
|
||||||
ValidationOutcome::Valid => {}
|
ValidationOutcome::Valid => {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
|
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
|
||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
|
config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime},
|
||||||
constants::{files, timing},
|
constants::{files, timing},
|
||||||
@@ -6,6 +7,7 @@ use crate::{
|
|||||||
CoreManager,
|
CoreManager,
|
||||||
handle::{self, Handle},
|
handle::{self, Handle},
|
||||||
listener::MIXED_PORT_KEY,
|
listener::MIXED_PORT_KEY,
|
||||||
|
runtime_bundle::resolve_provider_path_conflicts,
|
||||||
tray,
|
tray,
|
||||||
validate::CoreConfigValidator,
|
validate::CoreConfigValidator,
|
||||||
},
|
},
|
||||||
@@ -68,6 +70,12 @@ impl Config {
|
|||||||
CONFIG_WRITE_LOCK.lock().await
|
CONFIG_WRITE_LOCK.lock().await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn try_lock_config_write() -> Result<MutexGuard<'static, ()>> {
|
||||||
|
CONFIG_WRITE_LOCK
|
||||||
|
.try_lock()
|
||||||
|
.map_err(|_| anyhow!("configuration update is already running"))
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn init_config_before_window() -> Result<()> {
|
pub async fn init_config_before_window() -> Result<()> {
|
||||||
Self::ensure_default_profile_items().await?;
|
Self::ensure_default_profile_items().await?;
|
||||||
|
|
||||||
@@ -105,7 +113,7 @@ impl Config {
|
|||||||
|
|
||||||
if let Some((msg_type, msg_content)) = validation_result {
|
if let Some((msg_type, msg_content)) = validation_result {
|
||||||
sleep(timing::STARTUP_ERROR_DELAY).await;
|
sleep(timing::STARTUP_ERROR_DELAY).await;
|
||||||
handle::Handle::notice_message(msg_type, msg_content);
|
handle::Handle::notice(msg_type, msg_content.as_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
Self::runtime().await.apply();
|
Self::runtime().await.apply();
|
||||||
@@ -136,14 +144,14 @@ impl Config {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn generate_and_validate() -> Result<Option<(&'static str, String)>> {
|
async fn generate_and_validate() -> Result<Option<(NoticeStatus, String)>> {
|
||||||
if let Err(err) = Self::generate().await {
|
if let Err(err) = Self::generate().await {
|
||||||
let error_msg: String = err.to_string().into();
|
let error_msg: String = err.to_string().into();
|
||||||
logging!(error, Type::Config, "生成运行时配置失败: {}", error_msg);
|
logging!(error, Type::Config, "生成运行时配置失败: {}", error_msg);
|
||||||
CoreManager::global()
|
CoreManager::global()
|
||||||
.use_default_config("config_validate::boot_error", &error_msg)
|
.use_default_config(NoticeStatus::ConfigValidateBootError, &error_msg)
|
||||||
.await?;
|
.await?;
|
||||||
return Ok(Some(("config_validate::boot_error", error_msg)));
|
return Ok(Some((NoticeStatus::ConfigValidateBootError, error_msg)));
|
||||||
}
|
}
|
||||||
logging!(debug, Type::Config, "生成运行时配置成功");
|
logging!(debug, Type::Config, "生成运行时配置成功");
|
||||||
|
|
||||||
@@ -170,25 +178,25 @@ impl Config {
|
|||||||
error_msg
|
error_msg
|
||||||
);
|
);
|
||||||
CoreManager::global()
|
CoreManager::global()
|
||||||
.use_default_config("config_validate::boot_error", &error_msg)
|
.use_default_config(NoticeStatus::ConfigValidateBootError, &error_msg)
|
||||||
.await?;
|
.await?;
|
||||||
Ok(Some(("config_validate::boot_error", error_msg)))
|
Ok(Some((NoticeStatus::ConfigValidateBootError, error_msg)))
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
logging!(warn, Type::Config, "验证过程执行失败: {err:#}");
|
logging!(warn, Type::Config, "验证过程执行失败: {err:#}");
|
||||||
CoreManager::global()
|
CoreManager::global()
|
||||||
.use_default_config("config_validate::process_terminated", "")
|
.use_default_config(NoticeStatus::ConfigValidateProcessTerminated, "")
|
||||||
.await?;
|
.await?;
|
||||||
Ok(Some(("config_validate::process_terminated", String::new())))
|
Ok(Some((NoticeStatus::ConfigValidateProcessTerminated, String::new())))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let error_msg = config_result.err().map(|err| err.to_string()).unwrap_or_default();
|
let error_msg = config_result.err().map(|err| err.to_string()).unwrap_or_default();
|
||||||
logging!(warn, Type::Config, "生成配置文件失败,使用默认配置: {error_msg}");
|
logging!(warn, Type::Config, "生成配置文件失败,使用默认配置: {error_msg}");
|
||||||
CoreManager::global()
|
CoreManager::global()
|
||||||
.use_default_config("config_validate::error", "")
|
.use_default_config(NoticeStatus::ConfigValidateError, "")
|
||||||
.await?;
|
.await?;
|
||||||
Ok(Some(("config_validate::error", String::new())))
|
Ok(Some((NoticeStatus::ConfigValidateError, String::new())))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -228,6 +236,7 @@ impl Config {
|
|||||||
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
|
pub(crate) async fn generate_with_profiles(profiles: &IProfiles) -> Result<()> {
|
||||||
let (mut config, exists_keys, logs, dns_override) = enhance::enhance(profiles).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);
|
sanitize_tunnels_proxy(&mut config);
|
||||||
// Apply only to generated core config so the saved choice survives the next launch.
|
// Apply only to generated core config so the saved choice survives the next launch.
|
||||||
if let Some(port) = MixedPort::session_fallback() {
|
if let Some(port) = MixedPort::session_fallback() {
|
||||||
|
|||||||
+138
-38
@@ -1,5 +1,7 @@
|
|||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clash_verge_draft::DraftTransaction;
|
use clash_verge_draft::DraftTransaction;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use sha2::{Digest as _, Sha256};
|
use sha2::{Digest as _, Sha256};
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
@@ -54,6 +56,7 @@ pub(crate) fn dns_override_source(profile_uid: &str, config: &Mapping) -> Result
|
|||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub(crate) struct DnsOverrideState {
|
pub(crate) struct DnsOverrideState {
|
||||||
|
profile_uid: String,
|
||||||
pub source: Option<String>,
|
pub source: Option<String>,
|
||||||
pub enabled: bool,
|
pub enabled: bool,
|
||||||
requested: bool,
|
requested: bool,
|
||||||
@@ -61,9 +64,10 @@ pub(crate) struct DnsOverrideState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl DnsOverrideState {
|
impl DnsOverrideState {
|
||||||
pub fn new(source: Option<String>, requested: bool, confirmation: Option<String>) -> Self {
|
pub fn new(profile_uid: &str, source: Option<String>, requested: bool, confirmation: Option<String>) -> Self {
|
||||||
let enabled = requested && (source.is_none() || source == confirmation);
|
let enabled = requested && (source.is_none() || source == confirmation);
|
||||||
Self {
|
Self {
|
||||||
|
profile_uid: profile_uid.into(),
|
||||||
source,
|
source,
|
||||||
enabled,
|
enabled,
|
||||||
requested,
|
requested,
|
||||||
@@ -72,24 +76,55 @@ impl DnsOverrideState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn apply_to(&self, verge: &mut IVerge) -> bool {
|
fn apply_to(&self, verge: &mut IVerge) -> bool {
|
||||||
|
if self.profile_uid.is_empty() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let settings = verge.dns_settings_for(&self.profile_uid);
|
||||||
// A later settings write must not be overwritten by an earlier runtime generation.
|
// A later settings write must not be overwritten by an earlier runtime generation.
|
||||||
if verge.enable_dns_settings.unwrap_or(false) != self.requested
|
if (settings.enabled, settings.confirmation.as_ref()) != (self.requested, self.confirmation.as_ref()) {
|
||||||
|| verge.dns_override_confirmation != self.confirmation
|
|
||||||
{
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let clear_confirmation = self.confirmation.is_some() && self.source != self.confirmation;
|
let clear_confirmation = self.confirmation.is_some() && self.source != self.confirmation;
|
||||||
if self.enabled == self.requested && !clear_confirmation {
|
if self.enabled == self.requested
|
||||||
|
&& !clear_confirmation
|
||||||
|
&& verge.profile_dns_settings.contains_key(&self.profile_uid)
|
||||||
|
{
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
verge.enable_dns_settings = Some(self.enabled);
|
verge.profile_dns_settings.insert(
|
||||||
if clear_confirmation {
|
self.profile_uid.clone(),
|
||||||
verge.dns_override_confirmation = None;
|
ProfileDnsSettings {
|
||||||
}
|
enabled: self.enabled,
|
||||||
|
confirmation: if clear_confirmation {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
self.confirmation.clone()
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||||
|
pub struct ProfileDnsSettings {
|
||||||
|
pub enabled: bool,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub confirmation: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IVerge {
|
||||||
|
pub(crate) fn dns_settings_for(&self, profile_uid: &str) -> ProfileDnsSettings {
|
||||||
|
self.profile_dns_settings
|
||||||
|
.get(profile_uid)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or(ProfileDnsSettings {
|
||||||
|
enabled: self.enable_dns_settings.unwrap_or(false),
|
||||||
|
confirmation: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
pub(crate) async fn sync_dns_override() -> Result<()> {
|
pub(crate) async fn sync_dns_override() -> Result<()> {
|
||||||
let _config_write = Self::lock_config_write().await;
|
let _config_write = Self::lock_config_write().await;
|
||||||
@@ -104,19 +139,20 @@ impl Config {
|
|||||||
}
|
}
|
||||||
// The runtime is already committed; a disk failure cannot undo its effective settings.
|
// The runtime is already committed; a disk failure cannot undo its effective settings.
|
||||||
transaction.commit();
|
transaction.commit();
|
||||||
Handle::refresh_verge();
|
|
||||||
if state.requested && !state.enabled {
|
if state.requested && !state.enabled {
|
||||||
PENDING_DNS_OVERRIDE_NOTICE.store(true, Ordering::Relaxed);
|
PENDING_DNS_OVERRIDE_NOTICE.store(true, Ordering::Relaxed);
|
||||||
Handle::notice_message("dns_override::auto_disabled", "");
|
Handle::notice(NoticeStatus::DnsOverrideAutoDisabled, "");
|
||||||
}
|
}
|
||||||
verge.data_arc().save_file().await
|
verge.data_arc().save_file().await?;
|
||||||
|
Handle::refresh_verge();
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
|
#[allow(clippy::expect_used, reason = "tests assert by panicking")]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{DnsOverrideState, dns_override_source};
|
use super::{DnsOverrideState, ProfileDnsSettings, dns_override_source};
|
||||||
use crate::config::IVerge;
|
use crate::config::IVerge;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use serde_yaml_ng::Mapping;
|
use serde_yaml_ng::Mapping;
|
||||||
@@ -152,35 +188,46 @@ mod tests {
|
|||||||
let reordered =
|
let reordered =
|
||||||
mapping("dns:\n nameserver-policy:\n b.example: [8.8.8.8]\n a.example: 1.1.1.1\nport: 7890");
|
mapping("dns:\n nameserver-policy:\n b.example: [8.8.8.8]\n a.example: 1.1.1.1\nport: 7890");
|
||||||
assert_eq!(source, dns_override_source("one", &reordered)?);
|
assert_eq!(source, dns_override_source("one", &reordered)?);
|
||||||
assert!(DnsOverrideState::new(source.clone(), true, source.clone()).enabled);
|
assert!(DnsOverrideState::new("one", source.clone(), true, source.clone()).enabled);
|
||||||
assert!(!DnsOverrideState::new(dns_override_source("two", &original)?, true, source.clone()).enabled);
|
assert!(!DnsOverrideState::new("two", dns_override_source("two", &original)?, true, source.clone()).enabled);
|
||||||
let changed = mapping("dns: {nameserver-policy: {a.example: 9.9.9.9, b.example: [8.8.8.8]}}");
|
let changed = mapping("dns: {nameserver-policy: {a.example: 9.9.9.9, b.example: [8.8.8.8]}}");
|
||||||
assert!(!DnsOverrideState::new(dns_override_source("one", &changed)?, true, source).enabled);
|
assert!(!DnsOverrideState::new("one", dns_override_source("one", &changed)?, true, source).enabled);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dns_override_confirmation_expires_on_restart() -> Result<()> {
|
fn dns_override_confirmation_survives_restart_only_for_the_same_source() -> Result<()> {
|
||||||
let source = Some("provider-dns".into());
|
let source = Some("provider-dns".into());
|
||||||
let confirmed = IVerge {
|
let confirmed = IVerge {
|
||||||
enable_dns_settings: Some(true),
|
profile_dns_settings: [(
|
||||||
dns_override_confirmation: source.clone(),
|
"one".into(),
|
||||||
|
ProfileDnsSettings {
|
||||||
|
enabled: true,
|
||||||
|
confirmation: source.clone(),
|
||||||
|
},
|
||||||
|
)]
|
||||||
|
.into(),
|
||||||
..IVerge::default()
|
..IVerge::default()
|
||||||
};
|
};
|
||||||
assert!(DnsOverrideState::new(source.clone(), true, confirmed.dns_override_confirmation.clone()).enabled);
|
let saved = serde_yaml_ng::to_string(&confirmed)?;
|
||||||
for saved in [
|
let mut restarted: IVerge = serde_yaml_ng::from_str(&saved)?;
|
||||||
serde_yaml_ng::to_string(&confirmed)?,
|
let settings = restarted.dns_settings_for("one");
|
||||||
"enable_dns_settings: true\ndns_override_confirmation: provider-dns".to_owned(),
|
let state = DnsOverrideState::new("one", source.clone(), settings.enabled, settings.confirmation);
|
||||||
|
assert!(state.enabled);
|
||||||
|
assert!(!state.apply_to(&mut restarted));
|
||||||
|
for (saved, source) in [
|
||||||
|
(saved, Some("updated".into())),
|
||||||
|
(
|
||||||
|
"enable_dns_settings: true\ndns_override_confirmation: provider-dns".to_owned(),
|
||||||
|
source,
|
||||||
|
),
|
||||||
] {
|
] {
|
||||||
let mut restarted: IVerge = serde_yaml_ng::from_str(&saved)?;
|
let mut restarted: IVerge = serde_yaml_ng::from_str(&saved)?;
|
||||||
let state = DnsOverrideState::new(
|
let settings = restarted.dns_settings_for("one");
|
||||||
source.clone(),
|
let state = DnsOverrideState::new("one", source, settings.enabled, settings.confirmation);
|
||||||
restarted.enable_dns_settings.unwrap_or(false),
|
|
||||||
restarted.dns_override_confirmation.clone(),
|
|
||||||
);
|
|
||||||
assert!(!state.enabled, "a previous session must not bypass startup protection");
|
assert!(!state.enabled, "a previous session must not bypass startup protection");
|
||||||
assert!(state.apply_to(&mut restarted));
|
assert!(state.apply_to(&mut restarted));
|
||||||
assert_eq!(restarted.enable_dns_settings, Some(false));
|
assert!(!restarted.dns_settings_for("one").enabled);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -191,21 +238,74 @@ mod tests {
|
|||||||
enable_dns_settings: Some(true),
|
enable_dns_settings: Some(true),
|
||||||
..IVerge::default()
|
..IVerge::default()
|
||||||
};
|
};
|
||||||
let state = DnsOverrideState::new(Some("provider-dns".into()), true, None);
|
let state = DnsOverrideState::new("one", Some("provider-dns".into()), true, None);
|
||||||
assert!(state.apply_to(&mut verge));
|
assert!(state.apply_to(&mut verge));
|
||||||
assert_eq!(verge.enable_dns_settings, Some(false));
|
assert!(!verge.dns_settings_for("one").enabled);
|
||||||
assert!(!state.apply_to(&mut verge));
|
assert!(!state.apply_to(&mut verge));
|
||||||
let disabled = DnsOverrideState::new(None, false, None);
|
let disabled = DnsOverrideState::new("one", None, false, None);
|
||||||
assert!(!disabled.apply_to(&mut verge));
|
assert!(!disabled.apply_to(&mut verge));
|
||||||
assert!(!disabled.enabled);
|
assert!(!disabled.enabled);
|
||||||
|
|
||||||
verge.enable_dns_settings = Some(true);
|
verge.profile_dns_settings.insert(
|
||||||
verge.dns_override_confirmation = Some("provider-dns".into());
|
"one".into(),
|
||||||
|
ProfileDnsSettings {
|
||||||
|
enabled: true,
|
||||||
|
confirmation: Some("provider-dns".into()),
|
||||||
|
},
|
||||||
|
);
|
||||||
assert!(!state.apply_to(&mut verge));
|
assert!(!state.apply_to(&mut verge));
|
||||||
assert_eq!(verge.enable_dns_settings, Some(true));
|
let settings = verge.dns_settings_for("one");
|
||||||
assert_eq!(verge.dns_override_confirmation.as_deref(), Some("provider-dns"));
|
assert!(settings.enabled);
|
||||||
let leaving = DnsOverrideState::new(None, true, verge.dns_override_confirmation.clone());
|
assert_eq!(settings.confirmation.as_deref(), Some("provider-dns"));
|
||||||
|
let leaving = DnsOverrideState::new("one", None, true, settings.confirmation);
|
||||||
assert!(leaving.apply_to(&mut verge));
|
assert!(leaving.apply_to(&mut verge));
|
||||||
assert!(verge.dns_override_confirmation.is_none());
|
assert!(verge.dns_settings_for("one").confirmation.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn automatic_disable_is_saved_only_for_the_affected_profile() -> Result<()> {
|
||||||
|
let mut verge = IVerge {
|
||||||
|
enable_dns_settings: Some(true),
|
||||||
|
..IVerge::default()
|
||||||
|
};
|
||||||
|
let first = DnsOverrideState::new("one", None, true, None);
|
||||||
|
assert!(first.apply_to(&mut verge));
|
||||||
|
let protected = DnsOverrideState::new("two", Some("provider-dns".into()), true, None);
|
||||||
|
assert!(protected.apply_to(&mut verge));
|
||||||
|
assert!(verge.dns_settings_for("one").enabled);
|
||||||
|
assert!(!verge.dns_settings_for("two").enabled);
|
||||||
|
assert!(verge.dns_settings_for("unvisited").enabled);
|
||||||
|
assert_eq!(verge.enable_dns_settings, Some(true));
|
||||||
|
let restarted: IVerge = serde_yaml_ng::from_str(&serde_yaml_ng::to_string(&verge)?)?;
|
||||||
|
assert!(restarted.dns_settings_for("one").enabled);
|
||||||
|
assert!(!restarted.dns_settings_for("two").enabled);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn switching_profiles_preserves_each_confirmation_until_its_source_changes() {
|
||||||
|
let mut verge = IVerge::default();
|
||||||
|
for uid in ["one", "two"] {
|
||||||
|
verge.profile_dns_settings.insert(
|
||||||
|
uid.into(),
|
||||||
|
ProfileDnsSettings {
|
||||||
|
enabled: true,
|
||||||
|
confirmation: Some(uid.into()),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for uid in ["one", "two", "one"] {
|
||||||
|
let settings = verge.dns_settings_for(uid);
|
||||||
|
let state = DnsOverrideState::new(uid, Some(uid.into()), settings.enabled, settings.confirmation);
|
||||||
|
assert!(state.enabled);
|
||||||
|
assert!(!state.apply_to(&mut verge));
|
||||||
|
}
|
||||||
|
let settings = verge.dns_settings_for("two");
|
||||||
|
let updated = DnsOverrideState::new("two", Some("updated".into()), settings.enabled, settings.confirmation);
|
||||||
|
assert!(updated.apply_to(&mut verge));
|
||||||
|
assert!(!verge.dns_settings_for("two").enabled);
|
||||||
|
assert!(verge.dns_settings_for("two").confirmation.is_none());
|
||||||
|
assert!(verge.dns_settings_for("one").enabled);
|
||||||
|
assert_eq!(verge.dns_settings_for("one").confirmation.as_deref(), Some("one"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use super::{Config, IClashTemp, IVerge, MixedPort};
|
use super::{Config, IClashTemp, IVerge, MixedPort};
|
||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::{
|
use crate::{
|
||||||
constants::timing,
|
constants::timing,
|
||||||
core::{
|
core::{
|
||||||
@@ -14,14 +15,13 @@ use crate::{
|
|||||||
use anyhow::{Context as _, Result, anyhow, bail};
|
use anyhow::{Context as _, Result, anyhow, bail};
|
||||||
use clash_verge_draft::DraftTransaction;
|
use clash_verge_draft::DraftTransaction;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use serde_yaml_ng::Value;
|
use serde_yaml_ng::Value;
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashSet,
|
collections::HashSet,
|
||||||
net::SocketAddr,
|
net::SocketAddr,
|
||||||
str::FromStr as _,
|
str::FromStr as _,
|
||||||
sync::atomic::{AtomicBool, Ordering},
|
sync::{LazyLock, OnceLock},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
@@ -30,9 +30,8 @@ struct MixedPortFallback {
|
|||||||
current: u16,
|
current: u16,
|
||||||
}
|
}
|
||||||
|
|
||||||
static PENDING_FALLBACK_NOTICE: Lazy<Mutex<Option<MixedPortFallback>>> = Lazy::new(|| Mutex::new(None));
|
static PENDING_FALLBACK_NOTICE: LazyLock<Mutex<Option<MixedPortFallback>>> = LazyLock::new(|| Mutex::new(None));
|
||||||
static STARTUP_CORE_BLOCKED: AtomicBool = AtomicBool::new(false);
|
static STARTUP_CORE_BLOCK_REASON: OnceLock<String> = OnceLock::new();
|
||||||
static STARTUP_CORE_BLOCK_REASON: Lazy<Mutex<Option<String>>> = Lazy::new(|| Mutex::new(None));
|
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
pub(crate) async fn resolve_startup_mixed_port() -> Result<bool> {
|
pub(crate) async fn resolve_startup_mixed_port() -> Result<bool> {
|
||||||
@@ -147,17 +146,12 @@ impl Config {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn block_startup_core(error: &anyhow::Error) {
|
pub(crate) fn block_startup_core(error: &anyhow::Error) {
|
||||||
STARTUP_CORE_BLOCKED.store(true, Ordering::Release);
|
let _ = STARTUP_CORE_BLOCK_REASON.set(error.to_string());
|
||||||
*STARTUP_CORE_BLOCK_REASON.lock() = Some(error.to_string());
|
|
||||||
report_fallback_error(error.to_string());
|
report_fallback_error(error.to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn startup_core_block_reason() -> Option<String> {
|
pub(crate) fn startup_core_block_reason() -> Option<String> {
|
||||||
if STARTUP_CORE_BLOCKED.load(Ordering::Acquire) {
|
STARTUP_CORE_BLOCK_REASON.get().cloned()
|
||||||
STARTUP_CORE_BLOCK_REASON.lock().clone()
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn notify_startup_mixed_port_fallback() {
|
pub(crate) fn notify_startup_mixed_port_fallback() {
|
||||||
@@ -166,8 +160,8 @@ impl Config {
|
|||||||
};
|
};
|
||||||
AsyncHandler::spawn(move || async move {
|
AsyncHandler::spawn(move || async move {
|
||||||
tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await;
|
tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await;
|
||||||
Handle::notice_message(
|
Handle::notice(
|
||||||
"mixed_port::fallback",
|
NoticeStatus::MixedPortFallback,
|
||||||
format!("{},{}", change.original, change.current),
|
format!("{},{}", change.original, change.current),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -196,7 +190,7 @@ fn report_fallback_error(message: String) {
|
|||||||
);
|
);
|
||||||
AsyncHandler::spawn(move || async move {
|
AsyncHandler::spawn(move || async move {
|
||||||
tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await;
|
tokio::time::sleep(timing::STARTUP_ERROR_DELAY).await;
|
||||||
Handle::notice_message("mixed_port::fallback_error", message);
|
Handle::notice(NoticeStatus::MixedPortFallbackError, message);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+163
-150
@@ -2,6 +2,8 @@ use super::{
|
|||||||
PrfOption,
|
PrfOption,
|
||||||
prfitem::{PrfItem, PrfSelected, normalize_profile_home_url},
|
prfitem::{PrfItem, PrfSelected, normalize_profile_home_url},
|
||||||
};
|
};
|
||||||
|
use crate::core::notify::{Refresh, announce};
|
||||||
|
use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state};
|
||||||
use crate::{
|
use crate::{
|
||||||
core::{handle, tray::Tray},
|
core::{handle, tray::Tray},
|
||||||
utils::{
|
utils::{
|
||||||
@@ -16,6 +18,7 @@ use parking_lot::Mutex;
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_yaml_ng::Mapping;
|
use serde_yaml_ng::Mapping;
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
|
use std::num::NonZeroUsize;
|
||||||
use std::{
|
use std::{
|
||||||
collections::{HashMap, HashSet},
|
collections::{HashMap, HashSet},
|
||||||
path::{Component, Path},
|
path::{Component, Path},
|
||||||
@@ -68,8 +71,14 @@ impl ProfileDeletePlan {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
for file in self.files {
|
for file in self.files {
|
||||||
if let Err(error) = dir.join(file.as_str()).remove_if_exists().await {
|
let path = dir.join(file.as_str());
|
||||||
logging!(warn, Type::Config, "清理已删除订阅文件失败: {file} - {error}");
|
if let Err(error) = path.remove_if_exists().await {
|
||||||
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::Config,
|
||||||
|
"Failed to remove deleted profile file {}: {error:#}",
|
||||||
|
path.display()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -594,19 +603,21 @@ fn is_activation_current(generation: u64) -> bool {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn fetch_proxies_with_timeout() -> Result<Proxies> {
|
async fn fetch_proxies_with_timeout() -> Result<Proxies> {
|
||||||
tokio::time::timeout(MIHOMO_OPERATION_TIMEOUT, async {
|
let interval = Duration::from_millis(500);
|
||||||
loop {
|
let attempts =
|
||||||
match handle::Handle::mihomo().get_proxies().await {
|
NonZeroUsize::MIN.saturating_add((MIHOMO_OPERATION_TIMEOUT.as_millis() / interval.as_millis()) as usize + 1);
|
||||||
Ok(proxies) => return proxies,
|
tokio::time::timeout(
|
||||||
Err(err) => {
|
MIHOMO_OPERATION_TIMEOUT,
|
||||||
logging!(debug, Type::Config, "mihomo proxies are not ready yet: {err:#}");
|
retry(RetryPolicy::fixed(attempts, interval), |_| async {
|
||||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
handle::Handle::mihomo().get_proxies().await.map_err(|error| {
|
||||||
}
|
logging!(debug, Type::Config, "mihomo proxies are not ready yet: {error:#}");
|
||||||
}
|
RetryError::Retry(error)
|
||||||
}
|
})
|
||||||
})
|
}),
|
||||||
|
)
|
||||||
.await
|
.await
|
||||||
.context("timed out while waiting for mihomo proxies")
|
.context("timed out while waiting for mihomo proxies")?
|
||||||
|
.map_err(Into::into)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> {
|
async fn select_node_with_timeout(group_name: &String, node: &String) -> Result<()> {
|
||||||
@@ -685,51 +696,58 @@ async fn update_tray_after_activation(generation: u64) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn persist_selected_update<F, Fut>(supersede: bool, edit: F) -> Result<()>
|
||||||
|
where
|
||||||
|
F: FnOnce(IProfiles) -> Fut + Send,
|
||||||
|
Fut: std::future::Future<Output = Result<(IProfiles, bool)>> + Send,
|
||||||
|
{
|
||||||
|
let changed = Config::profiles().await.with_data_modify(edit).await?;
|
||||||
|
if changed {
|
||||||
|
if supersede {
|
||||||
|
supersede_selected_activation();
|
||||||
|
}
|
||||||
|
announce(Refresh::Profiles);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Records a backend-made selection so the next core start restores it.
|
/// Records a backend-made selection so the next core start restores it.
|
||||||
pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result<()> {
|
pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result<()> {
|
||||||
let group_name = String::from(group_name);
|
let group_name = String::from(group_name);
|
||||||
let node = String::from(node);
|
let node = String::from(node);
|
||||||
let recorded = Config::profiles()
|
persist_selected_update(true, move |mut profiles| async move {
|
||||||
.await
|
let Some(current) = profiles.current.clone() else {
|
||||||
.with_data_modify(move |mut profiles| async move {
|
return Ok((profiles, false));
|
||||||
let Some(current) = profiles.current.clone() else {
|
};
|
||||||
return Ok((profiles, false));
|
let Some(item) = profiles
|
||||||
};
|
.items
|
||||||
let Some(item) = profiles
|
.as_mut()
|
||||||
.items
|
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(¤t)))
|
||||||
.as_mut()
|
else {
|
||||||
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(¤t)))
|
return Ok((profiles, false));
|
||||||
else {
|
};
|
||||||
return Ok((profiles, false));
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut selected = item.selected.clone().unwrap_or_default();
|
let mut selected = item.selected.clone().unwrap_or_default();
|
||||||
match selected
|
match selected
|
||||||
.iter_mut()
|
.iter_mut()
|
||||||
.find(|entry| entry.name.as_ref() == Some(&group_name))
|
.find(|entry| entry.name.as_ref() == Some(&group_name))
|
||||||
{
|
{
|
||||||
Some(entry) => {
|
Some(entry) => {
|
||||||
if entry.now.as_ref() == Some(&node) {
|
if entry.now.as_ref() == Some(&node) {
|
||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
}
|
|
||||||
entry.now = Some(node);
|
|
||||||
}
|
}
|
||||||
None => selected.push(PrfSelected {
|
entry.now = Some(node);
|
||||||
name: Some(group_name),
|
|
||||||
now: Some(node),
|
|
||||||
}),
|
|
||||||
}
|
}
|
||||||
item.selected = Some(selected);
|
None => selected.push(PrfSelected {
|
||||||
profiles.save_file().await?;
|
name: Some(group_name),
|
||||||
Ok((profiles, true))
|
now: Some(node),
|
||||||
})
|
}),
|
||||||
.await?;
|
}
|
||||||
|
item.selected = Some(selected);
|
||||||
if recorded {
|
profiles.save_file().await?;
|
||||||
supersede_selected_activation();
|
Ok((profiles, true))
|
||||||
handle::Handle::refresh_profiles();
|
})
|
||||||
}
|
.await
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bool {
|
fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bool {
|
||||||
@@ -739,36 +757,28 @@ fn remove_selected_node(selected: &mut Vec<PrfSelected>, group_name: &str) -> bo
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
|
pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> {
|
||||||
let cleared = Config::profiles()
|
persist_selected_update(true, move |mut profiles| async move {
|
||||||
.await
|
let Some(current) = profiles.current.clone() else {
|
||||||
.with_data_modify(move |mut profiles| async move {
|
return Ok((profiles, false));
|
||||||
let Some(current) = profiles.current.clone() else {
|
};
|
||||||
return Ok((profiles, false));
|
let Some(item) = profiles
|
||||||
};
|
.items
|
||||||
let Some(item) = profiles
|
.as_mut()
|
||||||
.items
|
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(¤t)))
|
||||||
.as_mut()
|
else {
|
||||||
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(¤t)))
|
return Ok((profiles, false));
|
||||||
else {
|
};
|
||||||
return Ok((profiles, false));
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut selected = item.selected.clone().unwrap_or_default();
|
let mut selected = item.selected.clone().unwrap_or_default();
|
||||||
if !remove_selected_node(&mut selected, group_name) {
|
if !remove_selected_node(&mut selected, group_name) {
|
||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
item.selected = (!selected.is_empty()).then_some(selected);
|
item.selected = (!selected.is_empty()).then_some(selected);
|
||||||
profiles.save_file().await?;
|
profiles.save_file().await?;
|
||||||
Ok((profiles, true))
|
Ok((profiles, true))
|
||||||
})
|
})
|
||||||
.await?;
|
.await
|
||||||
|
|
||||||
if cleared {
|
|
||||||
supersede_selected_activation();
|
|
||||||
handle::Handle::refresh_profiles();
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn persist_reconciled_selected(
|
async fn persist_reconciled_selected(
|
||||||
@@ -781,34 +791,27 @@ async fn persist_reconciled_selected(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let profiles = Config::profiles().await;
|
|
||||||
let profile_uid = profile_uid.clone();
|
let profile_uid = profile_uid.clone();
|
||||||
let original_selected = original_selected.to_vec();
|
let original_selected = original_selected.to_vec();
|
||||||
let updated = profiles
|
persist_selected_update(false, move |mut profiles| async move {
|
||||||
.with_data_modify(move |mut profiles| async move {
|
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
|
||||||
if !is_activation_current(generation) || profiles.current.as_ref() != Some(&profile_uid) {
|
return Ok((profiles, false));
|
||||||
return Ok((profiles, false));
|
}
|
||||||
}
|
|
||||||
|
|
||||||
let profile = profiles
|
let profile = profiles
|
||||||
.items
|
.items
|
||||||
.as_mut()
|
.as_mut()
|
||||||
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&profile_uid)))
|
.and_then(|items| items.iter_mut().find(|item| item.uid.as_ref() == Some(&profile_uid)))
|
||||||
.with_context(|| format!("failed to find the profile item \"uid:{profile_uid}\""))?;
|
.with_context(|| format!("failed to find the profile item \"uid:{profile_uid}\""))?;
|
||||||
if profile.selected.as_deref().unwrap_or(&[]) != original_selected.as_slice() {
|
if profile.selected.as_deref().unwrap_or(&[]) != original_selected.as_slice() {
|
||||||
return Ok((profiles, false));
|
return Ok((profiles, false));
|
||||||
}
|
}
|
||||||
|
|
||||||
profile.selected = (!selected.is_empty()).then_some(selected);
|
profile.selected = (!selected.is_empty()).then_some(selected);
|
||||||
profiles.save_file().await?;
|
profiles.save_file().await?;
|
||||||
Ok((profiles, true))
|
Ok((profiles, true))
|
||||||
})
|
})
|
||||||
.await?;
|
.await
|
||||||
|
|
||||||
if updated {
|
|
||||||
handle::Handle::refresh_profiles();
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns recorded selections whose groups have not reached the requested node.
|
/// Returns recorded selections whose groups have not reached the requested node.
|
||||||
@@ -830,48 +833,58 @@ fn unsettled_selections(selected: &[PrfSelected], proxies: &Proxies) -> Vec<Stri
|
|||||||
/// Retries selections while provider-backed groups finish loading.
|
/// Retries selections while provider-backed groups finish loading.
|
||||||
async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut HashMap<String, String>, generation: u64) {
|
async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut HashMap<String, String>, generation: u64) {
|
||||||
let deadline = Instant::now() + SELECTED_NODES_SETTLE_DEADLINE;
|
let deadline = Instant::now() + SELECTED_NODES_SETTLE_DEADLINE;
|
||||||
loop {
|
let attempts = NonZeroUsize::MIN.saturating_add(
|
||||||
tokio::time::sleep(SELECTED_NODES_SETTLE_INTERVAL).await;
|
(SELECTED_NODES_SETTLE_DEADLINE.as_millis() / SELECTED_NODES_SETTLE_INTERVAL.as_millis()) as usize,
|
||||||
if !is_activation_current(generation) {
|
);
|
||||||
return;
|
tokio::time::sleep(SELECTED_NODES_SETTLE_INTERVAL).await;
|
||||||
}
|
let _ = retry_with_state(
|
||||||
let Ok(snapshot) = fetch_proxies_with_timeout().await else {
|
RetryPolicy::fixed(attempts, SELECTED_NODES_SETTLE_INTERVAL),
|
||||||
// Unreachable core: the deadline still applies, so this cannot spin forever.
|
(selected, completed, generation, deadline),
|
||||||
if Instant::now() >= deadline {
|
|state, _| {
|
||||||
return;
|
Box::pin(async move {
|
||||||
}
|
let (selected, completed, generation, deadline) = state;
|
||||||
continue;
|
if !is_activation_current(*generation) {
|
||||||
};
|
return Ok(());
|
||||||
if !is_activation_current(generation) {
|
}
|
||||||
return;
|
let Ok(snapshot) = fetch_proxies_with_timeout().await else {
|
||||||
}
|
return if Instant::now() >= *deadline {
|
||||||
|
Ok(())
|
||||||
let pending = unsettled_selections(selected, &snapshot);
|
} else {
|
||||||
if pending.is_empty() {
|
Err(RetryError::Retry(()))
|
||||||
return;
|
};
|
||||||
}
|
};
|
||||||
if Instant::now() >= deadline {
|
if !is_activation_current(*generation) {
|
||||||
logging!(
|
return Ok(());
|
||||||
warn,
|
}
|
||||||
Type::Config,
|
let pending = unsettled_selections(selected, &snapshot);
|
||||||
"gave up putting back {} selected node(s) the core never loaded: {}",
|
if pending.is_empty() {
|
||||||
pending.len(),
|
return Ok(());
|
||||||
pending.iter().map(String::as_str).collect::<Vec<_>>().join(", ")
|
}
|
||||||
);
|
if Instant::now() >= *deadline {
|
||||||
return;
|
logging!(
|
||||||
}
|
warn,
|
||||||
|
Type::Config,
|
||||||
let plan = reconcile_selected_nodes(selected, None, &snapshot);
|
"gave up putting back {} selected node(s) the core never loaded: {}",
|
||||||
if apply_activations(&plan.activations, completed, generation)
|
pending.len(),
|
||||||
.await
|
pending.iter().map(String::as_str).collect::<Vec<_>>().join(", ")
|
||||||
.is_none()
|
);
|
||||||
{
|
return Ok(());
|
||||||
return;
|
}
|
||||||
}
|
let plan = reconcile_selected_nodes(selected, None, &snapshot);
|
||||||
if is_activation_current(generation) {
|
if apply_activations(&plan.activations, completed, *generation)
|
||||||
handle::Handle::refresh_clash();
|
.await
|
||||||
}
|
.is_none()
|
||||||
}
|
{
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if is_activation_current(*generation) {
|
||||||
|
announce(Refresh::Clash);
|
||||||
|
}
|
||||||
|
Err(RetryError::Retry(()))
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Releases the first-pass waiter even when restoration exits early.
|
/// Releases the first-pass waiter even when restoration exits early.
|
||||||
@@ -914,7 +927,7 @@ async fn activate_selected_nodes_worker(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if is_activation_current(generation) {
|
if is_activation_current(generation) {
|
||||||
handle::Handle::refresh_clash();
|
announce(Refresh::Clash);
|
||||||
}
|
}
|
||||||
|
|
||||||
let plan = if needs_confirmation {
|
let plan = if needs_confirmation {
|
||||||
@@ -938,7 +951,7 @@ async fn activate_selected_nodes_worker(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
if confirmed_activated_count > 0 && is_activation_current(generation) {
|
if confirmed_activated_count > 0 && is_activation_current(generation) {
|
||||||
handle::Handle::refresh_clash();
|
announce(Refresh::Clash);
|
||||||
}
|
}
|
||||||
confirmed_plan
|
confirmed_plan
|
||||||
} else {
|
} else {
|
||||||
@@ -1028,7 +1041,7 @@ fn activate_selected_nodes_with(repair: SelectionRepair) -> tokio::sync::oneshot
|
|||||||
|
|
||||||
if selected.is_empty() {
|
if selected.is_empty() {
|
||||||
if is_activation_current(generation) {
|
if is_activation_current(generation) {
|
||||||
handle::Handle::refresh_clash();
|
announce(Refresh::Clash);
|
||||||
}
|
}
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -1040,7 +1053,7 @@ fn activate_selected_nodes_with(repair: SelectionRepair) -> tokio::sync::oneshot
|
|||||||
if let Err(err) = result {
|
if let Err(err) = result {
|
||||||
logging!(error, Type::Config, "failed to activate selected nodes: {err:#}");
|
logging!(error, Type::Config, "failed to activate selected nodes: {err:#}");
|
||||||
// The profile itself is already active even if node restoration failed.
|
// The profile itself is already active even if node restoration failed.
|
||||||
handle::Handle::refresh_clash();
|
announce(Refresh::Clash);
|
||||||
}
|
}
|
||||||
update_tray_after_activation(generation).await;
|
update_tray_after_activation(generation).await;
|
||||||
logging!(debug, Type::Config, "activating selected nodes done!");
|
logging!(debug, Type::Config, "activating selected nodes done!");
|
||||||
|
|||||||
@@ -80,12 +80,11 @@ pub struct IVerge {
|
|||||||
|
|
||||||
pub enable_bypass_check: Option<bool>,
|
pub enable_bypass_check: Option<bool>,
|
||||||
|
|
||||||
/// enable dns settings - this controls whether dns_config.yaml is applied
|
/// Initial DNS override preference for profiles without a saved setting.
|
||||||
pub enable_dns_settings: Option<bool>,
|
pub enable_dns_settings: Option<bool>,
|
||||||
|
|
||||||
// Force-enable confirmation is valid only for the current app session.
|
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
|
||||||
#[serde(skip)]
|
pub profile_dns_settings: std::collections::BTreeMap<String, super::dns::ProfileDnsSettings>,
|
||||||
pub dns_override_confirmation: Option<String>,
|
|
||||||
|
|
||||||
pub use_default_bypass: Option<bool>,
|
pub use_default_bypass: Option<bool>,
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
use crate::{
|
||||||
|
config::{Config, IVerge},
|
||||||
|
core::{autostart, hotkey, lightweight, tray},
|
||||||
|
};
|
||||||
|
use anyhow::Result;
|
||||||
|
use futures::future::BoxFuture;
|
||||||
|
|
||||||
|
pub(crate) fn ensure_autostart(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
|
||||||
|
Box::pin(async move { autostart::update_launch().await })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ensure_hotkey(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
if let Some(hotkeys) = &patch.hotkeys {
|
||||||
|
hotkey::Hotkey::global().update(hotkeys.to_owned()).await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ensure_tray_menu(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
|
||||||
|
Box::pin(async move { tray::Tray::global().update_menu().await })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ensure_tray_icon(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
tray::Tray::global()
|
||||||
|
.update_icon(&Config::verge().await.latest_arc())
|
||||||
|
.await?;
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
if let Some(enabled) = patch.enable_tray_speed {
|
||||||
|
tray::Tray::global().update_speed_task(enabled);
|
||||||
|
}
|
||||||
|
#[cfg(not(target_os = "macos"))]
|
||||||
|
let _ = patch;
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ensure_tray_tooltip(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
|
||||||
|
Box::pin(async move { tray::Tray::global().update_tooltip().await })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ensure_tray_click(_patch: &IVerge) -> BoxFuture<'_, Result<()>> {
|
||||||
|
Box::pin(async move { tray::Tray::global().update_click_behavior().await })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ensure_lightweight(patch: &IVerge) -> BoxFuture<'_, Result<()>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
if patch.enable_auto_light_weight_mode.unwrap_or(false) {
|
||||||
|
lightweight::enable_auto_light_weight_mode().await;
|
||||||
|
} else {
|
||||||
|
lightweight::disable_auto_light_weight_mode();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -7,8 +7,8 @@ use crate::{
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use chrono::Local;
|
use chrono::Local;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use once_cell::sync::OnceCell;
|
|
||||||
use parking_lot::RwLock;
|
use parking_lot::RwLock;
|
||||||
|
use std::sync::OnceLock;
|
||||||
use std::{
|
use std::{
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::{
|
sync::{
|
||||||
@@ -92,7 +92,7 @@ pub struct AutoBackupManager {
|
|||||||
|
|
||||||
impl AutoBackupManager {
|
impl AutoBackupManager {
|
||||||
pub fn global() -> &'static Self {
|
pub fn global() -> &'static Self {
|
||||||
static INSTANCE: OnceCell<AutoBackupManager> = OnceCell::new();
|
static INSTANCE: OnceLock<AutoBackupManager> = OnceLock::new();
|
||||||
INSTANCE.get_or_init(|| {
|
INSTANCE.get_or_init(|| {
|
||||||
let (tx, _rx) = watch::channel(AutoBackupSettings::default());
|
let (tx, _rx) = watch::channel(AutoBackupSettings::default());
|
||||||
Self {
|
Self {
|
||||||
@@ -4,9 +4,9 @@ use anyhow::Error;
|
|||||||
use arc_swap::{ArcSwap, ArcSwapOption};
|
use arc_swap::{ArcSwap, ArcSwapOption};
|
||||||
use backon::{ConstantBuilder, Retryable as _};
|
use backon::{ConstantBuilder, Retryable as _};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use once_cell::sync::OnceCell;
|
|
||||||
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
|
use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus};
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
|
use std::sync::OnceLock;
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
env::{consts::OS, temp_dir},
|
env::{consts::OS, temp_dir},
|
||||||
@@ -58,7 +58,7 @@ pub struct WebDavClient {
|
|||||||
|
|
||||||
impl WebDavClient {
|
impl WebDavClient {
|
||||||
pub fn global() -> &'static Self {
|
pub fn global() -> &'static Self {
|
||||||
static WEBDAV_CLIENT: OnceCell<WebDavClient> = OnceCell::new();
|
static WEBDAV_CLIENT: OnceLock<WebDavClient> = OnceLock::new();
|
||||||
WEBDAV_CLIENT.get_or_init(|| Self {
|
WEBDAV_CLIENT.get_or_init(|| Self {
|
||||||
config: ArcSwapOption::new(None),
|
config: ArcSwapOption::new(None),
|
||||||
clients: ArcSwap::new(Arc::new(HashMap::new())),
|
clients: ArcSwap::new(Arc::new(HashMap::new())),
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::process::AsyncHandler;
|
use crate::process::AsyncHandler;
|
||||||
use crate::singleton;
|
use crate::singleton;
|
||||||
use crate::utils::notification::{NotificationEvent, notify_event};
|
use crate::utils::notification::{NotificationEvent, notify_event};
|
||||||
use crate::utils::window_manager::WindowManager;
|
use crate::utils::window_manager::WindowManager;
|
||||||
use crate::{config::Config, core::handle, feat, module::lightweight::entry_lightweight_mode};
|
use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_mode, feat};
|
||||||
use anyhow::{Result, bail};
|
use anyhow::{Result, bail};
|
||||||
use arc_swap::ArcSwap;
|
use arc_swap::ArcSwap;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
@@ -177,7 +178,7 @@ impl Hotkey {
|
|||||||
"Hotkey profile reactivation failed validation: {}",
|
"Hotkey profile reactivation failed validation: {}",
|
||||||
message.as_str()
|
message.as_str()
|
||||||
);
|
);
|
||||||
handle::Handle::notice_message("reactivate_profiles::error", message);
|
handle::Handle::notice(NoticeStatus::ReactivateProfilesError, message);
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
logging!(
|
logging!(
|
||||||
@@ -186,7 +187,7 @@ impl Hotkey {
|
|||||||
"Failed to reactivate subscriptions via hotkey: {}",
|
"Failed to reactivate subscriptions via hotkey: {}",
|
||||||
err
|
err
|
||||||
);
|
);
|
||||||
handle::Handle::notice_message("reactivate_profiles::error", err.to_string());
|
handle::Handle::notice(NoticeStatus::ReactivateProfilesError, err.to_string());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -200,7 +201,6 @@ impl Hotkey {
|
|||||||
HotkeyFunction::Hide => {
|
HotkeyFunction::Hide => {
|
||||||
AsyncHandler::spawn(async move || {
|
AsyncHandler::spawn(async move || {
|
||||||
feat::hide().await;
|
feat::hide().await;
|
||||||
notify_event(NotificationEvent::AppHidden).await;
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::core::service::StageRequest;
|
use crate::core::service::StageRequest;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IProfiles, runtime::IRuntime},
|
config::{Config, IProfiles, runtime::IRuntime},
|
||||||
@@ -129,7 +130,31 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl CoreManager {
|
impl CoreManager {
|
||||||
pub async fn use_default_config(&self, error_key: &str, error_msg: &str) -> Result<()> {
|
pub(crate) fn claim_config_update(
|
||||||
|
&self,
|
||||||
|
_config_write: &tokio::sync::MutexGuard<'_, ()>,
|
||||||
|
) -> Result<ConfigUpdateGuard<'_>> {
|
||||||
|
if !self.try_start_config_update() {
|
||||||
|
anyhow::bail!("configuration update is already running");
|
||||||
|
}
|
||||||
|
Ok(ConfigUpdateGuard(self))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn update_config_in_patch(&self, _update: &ConfigUpdateGuard<'_>) -> Result<()> {
|
||||||
|
if handle::Handle::global().is_exiting() {
|
||||||
|
anyhow::bail!("application is exiting");
|
||||||
|
}
|
||||||
|
self.set_last_update(Instant::now());
|
||||||
|
Config::generate().await?;
|
||||||
|
let outcome = self.validate_and_apply_draft().await?;
|
||||||
|
if outcome.is_valid() {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(anyhow!("{outcome}"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn use_default_config(&self, status: NoticeStatus, message: &str) -> Result<()> {
|
||||||
use crate::constants::files::RUNTIME_CONFIG;
|
use crate::constants::files::RUNTIME_CONFIG;
|
||||||
|
|
||||||
let runtime_path = dirs::app_home_dir()?.join(RUNTIME_CONFIG);
|
let runtime_path = dirs::app_home_dir()?.join(RUNTIME_CONFIG);
|
||||||
@@ -145,7 +170,7 @@ impl CoreManager {
|
|||||||
});
|
});
|
||||||
|
|
||||||
help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
|
help::save_yaml(&runtime_path, &clash_config, Some("# Clash Verge Runtime")).await?;
|
||||||
handle::Handle::notice_message(error_key, error_msg);
|
handle::Handle::notice(status, message);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,6 +324,14 @@ impl CoreManager {
|
|||||||
|
|
||||||
/// Validates and applies the caller's transaction, committing only on success.
|
/// Validates and applies the caller's transaction, committing only on success.
|
||||||
async fn validate_and_apply(&self, transaction: DraftTransaction<'_>) -> Result<ValidationOutcome> {
|
async fn validate_and_apply(&self, transaction: DraftTransaction<'_>) -> Result<ValidationOutcome> {
|
||||||
|
let outcome = self.validate_and_apply_draft().await?;
|
||||||
|
if outcome.is_valid() {
|
||||||
|
transaction.commit();
|
||||||
|
}
|
||||||
|
Ok(outcome)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn validate_and_apply_draft(&self) -> Result<ValidationOutcome> {
|
||||||
// One serialization feeds check and run files; the core never applies unvalidated bytes.
|
// One serialization feeds check and run files; the core never applies unvalidated bytes.
|
||||||
let yaml = Config::runtime_config_yaml().await?;
|
let yaml = Config::runtime_config_yaml().await?;
|
||||||
let outcome = CoreConfigValidator::global()
|
let outcome = CoreConfigValidator::global()
|
||||||
@@ -310,7 +343,6 @@ impl CoreManager {
|
|||||||
|
|
||||||
let run_path = Config::write_runtime_file(&yaml).await?;
|
let run_path = Config::write_runtime_file(&yaml).await?;
|
||||||
self.apply_config(run_path).await?;
|
self.apply_config(run_path).await?;
|
||||||
transaction.commit();
|
|
||||||
Ok(ValidationOutcome::Valid)
|
Ok(ValidationOutcome::Valid)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -62,7 +62,11 @@ const fn can_allow_sidecar_for_session(running_mode: &RunningMode, service_statu
|
|||||||
| ServiceStatus::NeedsReinstall
|
| ServiceStatus::NeedsReinstall
|
||||||
| ServiceStatus::InstallRequired
|
| ServiceStatus::InstallRequired
|
||||||
| ServiceStatus::Unavailable(_)
|
| ServiceStatus::Unavailable(_)
|
||||||
) | (RunningMode::Sidecar, ServiceStatus::InstallRequired)
|
| ServiceStatus::SidecarAllowed
|
||||||
|
) | (
|
||||||
|
RunningMode::Sidecar,
|
||||||
|
ServiceStatus::InstallRequired | ServiceStatus::Unavailable(_) | ServiceStatus::SidecarAllowed
|
||||||
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,18 +189,60 @@ where
|
|||||||
apply_proxy().await
|
apply_proxy().await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_sidecar_termination_transition<Clear, ClearFuture, Terminate>(
|
#[cfg(any(target_os = "windows", test))]
|
||||||
|
async fn run_service_start_with_sidecar_fallback<Start, StartFuture, Check, CheckFuture, Fallback, FallbackFuture>(
|
||||||
|
start_service: Start,
|
||||||
|
confirm_idle: Check,
|
||||||
|
start_sidecar: Fallback,
|
||||||
|
record_unavailable: impl FnOnce(std::string::String),
|
||||||
|
) -> Result<()>
|
||||||
|
where
|
||||||
|
Start: FnOnce() -> StartFuture,
|
||||||
|
StartFuture: std::future::Future<Output = Result<()>>,
|
||||||
|
Check: FnOnce() -> CheckFuture,
|
||||||
|
CheckFuture: std::future::Future<Output = Result<()>>,
|
||||||
|
Fallback: FnOnce(anyhow::Error) -> FallbackFuture,
|
||||||
|
FallbackFuture: std::future::Future<Output = Result<()>>,
|
||||||
|
{
|
||||||
|
let Err(error) = start_service().await else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let refusal = error.downcast_ref::<crate::core::service::ServiceStartRefusal>();
|
||||||
|
let location_refused = refusal.is_some_and(|refusal| {
|
||||||
|
refusal.code == clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16
|
||||||
|
});
|
||||||
|
if refusal.is_some() && !location_refused {
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
// A lost start response can hide a running core; the shared check must resolve occupancy.
|
||||||
|
if let Err(probe_error) = confirm_idle().await {
|
||||||
|
let error = error.context(format!("Sidecar fallback was not safe: {probe_error:#}"));
|
||||||
|
record_unavailable(format!("{error:#}"));
|
||||||
|
return Err(error);
|
||||||
|
}
|
||||||
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::Core,
|
||||||
|
"Service could not start the core; falling back to Sidecar: {error:#}"
|
||||||
|
);
|
||||||
|
let reason = format!("{error:#}");
|
||||||
|
start_sidecar(error)
|
||||||
|
.await
|
||||||
|
.map_err(|error| error.context(format!("Sidecar fallback failed after Service failure: {reason}")))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_sidecar_termination_transition<Clear, ClearFuture, Terminate, TerminateFuture>(
|
||||||
clear_proxy: Clear,
|
clear_proxy: Clear,
|
||||||
terminate_sidecar: Terminate,
|
terminate_sidecar: Terminate,
|
||||||
) -> Result<()>
|
) -> Result<()>
|
||||||
where
|
where
|
||||||
Clear: FnOnce() -> ClearFuture,
|
Clear: FnOnce() -> ClearFuture,
|
||||||
ClearFuture: std::future::Future<Output = Result<()>>,
|
ClearFuture: std::future::Future<Output = Result<()>>,
|
||||||
Terminate: FnOnce(),
|
Terminate: FnOnce() -> TerminateFuture,
|
||||||
|
TerminateFuture: std::future::Future<Output = Result<()>>,
|
||||||
{
|
{
|
||||||
clear_proxy().await?;
|
clear_proxy().await?;
|
||||||
terminate_sidecar();
|
terminate_sidecar().await
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_service_config_replacement_transition<
|
async fn run_service_config_replacement_transition<
|
||||||
@@ -335,7 +381,13 @@ impl CoreManager {
|
|||||||
if !can_allow_sidecar_for_session(&mode, &status) {
|
if !can_allow_sidecar_for_session(&mode, &status) {
|
||||||
anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}");
|
anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}");
|
||||||
}
|
}
|
||||||
SERVICE_MANAGER.allow_sidecar_for_session()?;
|
#[cfg(target_os = "windows")]
|
||||||
|
if matches!(*mode, RunningMode::NotRunning) {
|
||||||
|
clash_verge_service_ipc::execution::check_sidecar_available().await?;
|
||||||
|
}
|
||||||
|
if !matches!(status, ServiceStatus::SidecarAllowed) {
|
||||||
|
SERVICE_MANAGER.allow_sidecar_for_session()?;
|
||||||
|
}
|
||||||
// Settling on Sidecar is what makes the verdict final, so ask only once it is recorded.
|
// Settling on Sidecar is what makes the verdict final, so ask only once it is recorded.
|
||||||
// Elevation alone carries TUN on Sidecar; a Sidecar that cannot must write it off.
|
// Elevation alone carries TUN on Sidecar; a Sidecar that cannot must write it off.
|
||||||
let prepared = async {
|
let prepared = async {
|
||||||
@@ -476,10 +528,7 @@ impl CoreManager {
|
|||||||
// rather than fail — only if the watcher is actually live; a user toggling while
|
// rather than fail — only if the watcher is actually live; a user toggling while
|
||||||
// offline still fails fast.
|
// offline still fails fast.
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
let watcher_armed = crate::core::network_watch::is_armed();
|
if crate::core::network_watch::is_armed()
|
||||||
#[cfg(not(target_os = "macos"))]
|
|
||||||
let watcher_armed = false;
|
|
||||||
if watcher_armed
|
|
||||||
&& !crate::utils::resolve::is_resolve_done()
|
&& !crate::utils::resolve::is_resolve_done()
|
||||||
&& Config::verge()
|
&& Config::verge()
|
||||||
.await
|
.await
|
||||||
@@ -545,6 +594,8 @@ impl CoreManager {
|
|||||||
tracing::Span::current().record("decision", tracing::field::debug(&startup));
|
tracing::Span::current().record("decision", tracing::field::debug(&startup));
|
||||||
if matches!(startup, StartupDecision::Wait) {
|
if matches!(startup, StartupDecision::Wait) {
|
||||||
self.rollback_failed_start().await;
|
self.rollback_failed_start().await;
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
self.try_sidecar_after_service_unavailable().await?;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
if Handle::global().is_exiting() {
|
if Handle::global().is_exiting() {
|
||||||
@@ -553,7 +604,23 @@ impl CoreManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let result = match startup {
|
let result = match startup {
|
||||||
StartupDecision::Service => self.start_core_by_service().await,
|
StartupDecision::Service => {
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
{
|
||||||
|
run_service_start_with_sidecar_fallback(
|
||||||
|
|| self.start_core_by_service(),
|
||||||
|
clash_verge_service_ipc::execution::check_sidecar_available,
|
||||||
|
|error| self.start_sidecar_after_service_failure(error),
|
||||||
|
|reason| {
|
||||||
|
crate::core::runstate::RUN_STATE
|
||||||
|
.observe(crate::core::runstate::ServiceHealth::Unavailable(reason));
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
self.start_core_by_service().await
|
||||||
|
}
|
||||||
StartupDecision::Sidecar => self.start_core_by_sidecar().await,
|
StartupDecision::Sidecar => self.start_core_by_sidecar().await,
|
||||||
StartupDecision::Wait => Ok(()),
|
StartupDecision::Wait => Ok(()),
|
||||||
};
|
};
|
||||||
@@ -572,6 +639,50 @@ impl CoreManager {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
async fn try_sidecar_after_service_unavailable(&self) -> Result<()> {
|
||||||
|
use crate::core::runstate::{RUN_STATE, ServiceHealth};
|
||||||
|
|
||||||
|
let state = RUN_STATE.state();
|
||||||
|
if state.pending.is_some() || state.op_in_flight || Handle::global().is_exiting() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let reason = match state.health {
|
||||||
|
ServiceHealth::Unavailable(reason) => reason,
|
||||||
|
ServiceHealth::VersionMismatch => "registered service is unavailable or incompatible".to_owned(),
|
||||||
|
_ => return Ok(()),
|
||||||
|
};
|
||||||
|
if let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available().await {
|
||||||
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::Core,
|
||||||
|
"Service unavailable ({reason}); Sidecar fallback withheld: {error:#}"
|
||||||
|
);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
self.start_sidecar_after_service_failure(anyhow::anyhow!(reason)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
async fn start_sidecar_after_service_failure(&self, error: anyhow::Error) -> Result<()> {
|
||||||
|
use crate::core::runstate::RUN_STATE;
|
||||||
|
|
||||||
|
if Handle::global().is_exiting() {
|
||||||
|
return Err(error.context("application exited before Sidecar fallback"));
|
||||||
|
}
|
||||||
|
let reason = format!("{error:#}");
|
||||||
|
RUN_STATE.allow_sidecar_after_service_refusal(reason.clone())?;
|
||||||
|
logging!(warn, Type::Core, "Starting Sidecar with Service unavailable: {reason}");
|
||||||
|
let result = self.start_core_by_sidecar().await;
|
||||||
|
if result.is_err() {
|
||||||
|
SERVICE_MANAGER.withdraw_sidecar_allowance();
|
||||||
|
self.rollback_failed_start().await;
|
||||||
|
} else {
|
||||||
|
crate::core::service::notify_service_fallback();
|
||||||
|
}
|
||||||
|
result.map_err(|error| error.context(format!("Service failure before Sidecar startup: {reason}")))
|
||||||
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(mode = ?*self.get_running_mode()))]
|
#[tracing::instrument(skip_all, level = "info", fields(mode = ?*self.get_running_mode()))]
|
||||||
pub async fn stop_core(&self) -> Result<()> {
|
pub async fn stop_core(&self) -> Result<()> {
|
||||||
let _life = self.lifecycle_lock.lock().await;
|
let _life = self.lifecycle_lock.lock().await;
|
||||||
@@ -607,10 +718,7 @@ impl CoreManager {
|
|||||||
CLASH_LOGGER.clear_logs();
|
CLASH_LOGGER.clear_logs();
|
||||||
match *self.get_running_mode() {
|
match *self.get_running_mode() {
|
||||||
RunningMode::Service => self.stop_core_by_service().await,
|
RunningMode::Service => self.stop_core_by_service().await,
|
||||||
RunningMode::Sidecar => {
|
RunningMode::Sidecar => self.stop_core_by_sidecar_unprepared().await,
|
||||||
self.stop_core_by_sidecar_unprepared();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
RunningMode::NotRunning => Ok(()),
|
RunningMode::NotRunning => Ok(()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -732,29 +840,34 @@ impl CoreManager {
|
|||||||
AsyncHandler::spawn(|| async move {
|
AsyncHandler::spawn(|| async move {
|
||||||
let manager = Self::global();
|
let manager = Self::global();
|
||||||
let started = Instant::now();
|
let started = Instant::now();
|
||||||
loop {
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
|
let attempts = std::num::NonZeroUsize::MIN.saturating_add(
|
||||||
|
(timing::SERVICE_HANDOFF_WINDOW.as_millis() / timing::SERVICE_HANDOFF_INTERVAL.as_millis()) as usize,
|
||||||
|
);
|
||||||
|
let _ = retry(RetryPolicy::fixed(attempts, std::time::Duration::ZERO), |_| async {
|
||||||
if started.elapsed() >= timing::SERVICE_HANDOFF_WINDOW {
|
if started.elapsed() >= timing::SERVICE_HANDOFF_WINDOW {
|
||||||
logging!(
|
logging!(
|
||||||
info,
|
info,
|
||||||
Type::Core,
|
Type::Core,
|
||||||
"service handoff window elapsed; staying in sidecar mode"
|
"service handoff window elapsed; staying in sidecar mode"
|
||||||
);
|
);
|
||||||
break;
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
// The window is checked before waiting, including the final handoff attempt.
|
||||||
tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await;
|
tokio::time::sleep(timing::SERVICE_HANDOFF_INTERVAL).await;
|
||||||
|
|
||||||
if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) {
|
if !matches!(*manager.get_running_mode(), RunningMode::Sidecar) {
|
||||||
break;
|
return Ok(());
|
||||||
}
|
}
|
||||||
match manager.try_handoff_sidecar_to_service().await {
|
match manager.try_handoff_sidecar_to_service().await {
|
||||||
HandoffOutcome::Done => break,
|
HandoffOutcome::Done => Ok(()),
|
||||||
HandoffOutcome::Failed => {
|
HandoffOutcome::Failed => {
|
||||||
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
|
logging!(warn, Type::Core, "handoff attempt failed; staying in sidecar mode");
|
||||||
break;
|
Ok(())
|
||||||
}
|
}
|
||||||
HandoffOutcome::NotReady => {}
|
HandoffOutcome::NotReady => Err(RetryError::Retry(())),
|
||||||
}
|
}
|
||||||
}
|
})
|
||||||
|
.await;
|
||||||
manager.handoff_watcher_running.store(false, Ordering::Release);
|
manager.handoff_watcher_running.store(false, Ordering::Release);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1111,9 +1224,10 @@ mod tests {
|
|||||||
|
|
||||||
let result = run_sidecar_termination_transition(
|
let result = run_sidecar_termination_transition(
|
||||||
|| transition_step(&calls, "handoff-proxy-clear", fail_at),
|
|| transition_step(&calls, "handoff-proxy-clear", fail_at),
|
||||||
|| {
|
|| async {
|
||||||
sidecar_alive.store(false, Ordering::Release);
|
sidecar_alive.store(false, Ordering::Release);
|
||||||
calls.lock().push("handoff-sidecar-stop");
|
calls.lock().push("handoff-sidecar-stop");
|
||||||
|
Ok(())
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -1371,12 +1485,18 @@ mod tests {
|
|||||||
ServiceStatus::NeedsReinstall,
|
ServiceStatus::NeedsReinstall,
|
||||||
ServiceStatus::InstallRequired,
|
ServiceStatus::InstallRequired,
|
||||||
ServiceStatus::Unavailable("offline".into()),
|
ServiceStatus::Unavailable("offline".into()),
|
||||||
|
ServiceStatus::SidecarAllowed,
|
||||||
];
|
];
|
||||||
for status in &allowed_statuses {
|
for status in &allowed_statuses {
|
||||||
assert!(can_allow_sidecar_for_session(&RunningMode::NotRunning, status));
|
assert!(can_allow_sidecar_for_session(&RunningMode::NotRunning, status));
|
||||||
assert!(!can_allow_sidecar_for_session(&RunningMode::Service, status));
|
assert!(!can_allow_sidecar_for_session(&RunningMode::Service, status));
|
||||||
if !matches!(status, ServiceStatus::InstallRequired) {
|
if !matches!(
|
||||||
|
status,
|
||||||
|
ServiceStatus::InstallRequired | ServiceStatus::Unavailable(_) | ServiceStatus::SidecarAllowed
|
||||||
|
) {
|
||||||
assert!(!can_allow_sidecar_for_session(&RunningMode::Sidecar, status));
|
assert!(!can_allow_sidecar_for_session(&RunningMode::Sidecar, status));
|
||||||
|
} else {
|
||||||
|
assert!(can_allow_sidecar_for_session(&RunningMode::Sidecar, status));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1386,13 +1506,52 @@ mod tests {
|
|||||||
ServiceStatus::UninstallRequired,
|
ServiceStatus::UninstallRequired,
|
||||||
ServiceStatus::ReinstallRequired,
|
ServiceStatus::ReinstallRequired,
|
||||||
ServiceStatus::ForceReinstallRequired,
|
ServiceStatus::ForceReinstallRequired,
|
||||||
ServiceStatus::SidecarAllowed,
|
|
||||||
];
|
];
|
||||||
for status in &rejected_statuses {
|
for status in &rejected_statuses {
|
||||||
assert!(!can_allow_sidecar_for_session(&RunningMode::NotRunning, status));
|
assert!(!can_allow_sidecar_for_session(&RunningMode::NotRunning, status));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn blocked_windows_fallback_records_failure_without_starting_sidecar() {
|
||||||
|
use crate::core::runstate::{FakeEnv, RunStateStore, ServiceHealth};
|
||||||
|
|
||||||
|
for idle in [false, true] {
|
||||||
|
let store = RunStateStore::new(FakeEnv::new());
|
||||||
|
store.observe(ServiceHealth::Ready);
|
||||||
|
let started = AtomicBool::new(false);
|
||||||
|
let result = super::run_service_start_with_sidecar_fallback(
|
||||||
|
|| async {
|
||||||
|
Err(crate::core::service::ServiceStartRefusal {
|
||||||
|
code: clash_verge_service_ipc::ServiceErrorCode::InvalidInstallLocation as u16,
|
||||||
|
core_path: "verge-mihomo.exe".into(),
|
||||||
|
message: "no administrator-approved copy is installed".into(),
|
||||||
|
}
|
||||||
|
.into())
|
||||||
|
},
|
||||||
|
|| async move {
|
||||||
|
anyhow::ensure!(idle, "another core is running");
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
|_| async {
|
||||||
|
started.store(true, Ordering::SeqCst);
|
||||||
|
Ok(())
|
||||||
|
},
|
||||||
|
|reason| store.observe(ServiceHealth::Unavailable(reason)),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(started.load(Ordering::SeqCst), idle);
|
||||||
|
assert_eq!(result.is_ok(), idle);
|
||||||
|
assert!(!store.state().sidecar_allowed);
|
||||||
|
if !idle {
|
||||||
|
assert!(store.state().service_needs_attention());
|
||||||
|
assert!(!store.state().service_usable());
|
||||||
|
assert!(result.is_err_and(|error| format!("{error:#}").contains("another core is running")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn failed_service_install_can_continue_with_an_existing_sidecar() {
|
fn failed_service_install_can_continue_with_an_existing_sidecar() {
|
||||||
assert!(can_allow_sidecar_for_session(
|
assert!(can_allow_sidecar_for_session(
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
mod config;
|
mod config;
|
||||||
|
pub(crate) use config::ConfigUpdateGuard;
|
||||||
mod lifecycle;
|
mod lifecycle;
|
||||||
mod state;
|
mod state;
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use arc_swap::{ArcSwap, ArcSwapOption};
|
use arc_swap::{ArcSwap, ArcSwapOption};
|
||||||
use clash_verge_logging::{LogRing, Type, logging};
|
use clash_verge_logging::{LogRing, Type, logging};
|
||||||
use once_cell::sync::Lazy;
|
use std::sync::LazyLock;
|
||||||
use std::{
|
use std::{
|
||||||
fmt,
|
fmt,
|
||||||
sync::{
|
sync::{
|
||||||
@@ -21,7 +22,7 @@ use crate::singleton;
|
|||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
use std::os::windows::io::OwnedHandle;
|
use std::os::windows::io::OwnedHandle;
|
||||||
|
|
||||||
pub(crate) static CLASH_LOGGER: Lazy<Arc<LogRing>> = Lazy::new(|| Arc::new(LogRing::new()));
|
pub(crate) static CLASH_LOGGER: LazyLock<Arc<LogRing>> = LazyLock::new(|| Arc::new(LogRing::new()));
|
||||||
|
|
||||||
tokio::task_local! {
|
tokio::task_local! {
|
||||||
static PROFILE_SELECTIONS_PENDING_COMMIT: bool;
|
static PROFILE_SELECTIONS_PENDING_COMMIT: bool;
|
||||||
@@ -74,6 +75,14 @@ impl fmt::Display for RunningMode {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Why the Core is not running, kept until a Core starts again.
|
||||||
|
#[derive(Clone, Debug, serde::Serialize, PartialEq, Eq)]
|
||||||
|
#[serde(tag = "kind", content = "detail", rename_all = "camelCase")]
|
||||||
|
pub enum CoreFailure {
|
||||||
|
StartFailed(String),
|
||||||
|
ServiceCoreStopped(String),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct CoreManager {
|
pub struct CoreManager {
|
||||||
/// The Run State this manager reports transitions to.
|
/// The Run State this manager reports transitions to.
|
||||||
@@ -87,6 +96,8 @@ pub struct CoreManager {
|
|||||||
job_handle: ArcSwapOption<OwnedHandle>,
|
job_handle: ArcSwapOption<OwnedHandle>,
|
||||||
config_update_in_progress: AtomicBool,
|
config_update_in_progress: AtomicBool,
|
||||||
core_readiness_state: AtomicU64,
|
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 交接。
|
// 串行化 start/stop/restart 和 sidecar→service 交接。
|
||||||
// 锁序固定为 config_update_in_progress → lifecycle_lock。
|
// 锁序固定为 config_update_in_progress → lifecycle_lock。
|
||||||
pub(crate) lifecycle_lock: tokio::sync::Mutex<()>,
|
pub(crate) lifecycle_lock: tokio::sync::Mutex<()>,
|
||||||
@@ -114,6 +125,8 @@ impl Default for CoreManager {
|
|||||||
job_handle: ArcSwapOption::new(None),
|
job_handle: ArcSwapOption::new(None),
|
||||||
config_update_in_progress: AtomicBool::new(false),
|
config_update_in_progress: AtomicBool::new(false),
|
||||||
core_readiness_state: AtomicU64::new(0),
|
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(()),
|
lifecycle_lock: tokio::sync::Mutex::new(()),
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
handoff_watcher_running: AtomicBool::new(false),
|
handoff_watcher_running: AtomicBool::new(false),
|
||||||
@@ -139,6 +152,17 @@ impl CoreManager {
|
|||||||
self.run_state.mode_arc()
|
self.run_state.mode_arc()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn record_startup_error(&self, failure: CoreFailure) {
|
||||||
|
let mut startup_error = self.startup_error.lock();
|
||||||
|
if matches!(*self.get_running_mode(), RunningMode::NotRunning) {
|
||||||
|
*startup_error = Some(failure);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn get_startup_error(&self) -> Option<CoreFailure> {
|
||||||
|
self.startup_error.lock().clone()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn take_child_sidecar(&self) -> Option<CommandChild> {
|
pub fn take_child_sidecar(&self) -> Option<CommandChild> {
|
||||||
self.state
|
self.state
|
||||||
.load()
|
.load()
|
||||||
@@ -164,7 +188,9 @@ impl CoreManager {
|
|||||||
if previous != mode {
|
if previous != mode {
|
||||||
logging!(info, Type::Core, "Core running mode changed: {previous} -> {mode}");
|
logging!(info, Type::Core, "Core running mode changed: {previous} -> {mode}");
|
||||||
}
|
}
|
||||||
|
let mut startup_error = self.startup_error.lock();
|
||||||
self.run_state.core_started(mode);
|
self.run_state.core_started(mode);
|
||||||
|
*startup_error = None;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The Core is no longer running, for any reason.
|
/// The Core is no longer running, for any reason.
|
||||||
@@ -259,49 +285,83 @@ impl CoreManager {
|
|||||||
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
|
anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}");
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut retries = 0;
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
loop {
|
retry(
|
||||||
match self.start_core().await {
|
RetryPolicy::fixed(
|
||||||
Ok(()) => {
|
std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES),
|
||||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
std::time::Duration::ZERO,
|
||||||
return Ok(!matches!(*self.get_running_mode(), RunningMode::NotRunning));
|
),
|
||||||
}
|
|retries| async move {
|
||||||
Err(start_error) if retries < MAX_PORT_FALLBACK_RETRIES => {
|
match self.start_core().await {
|
||||||
if !matches!(*self.get_running_mode(), RunningMode::NotRunning) {
|
Ok(()) => {
|
||||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||||
return Err(start_error);
|
Ok(!matches!(*self.get_running_mode(), RunningMode::NotRunning))
|
||||||
}
|
}
|
||||||
match crate::config::Config::resolve_startup_mixed_port().await {
|
Err(start_error) if retries < MAX_PORT_FALLBACK_RETRIES => {
|
||||||
Ok(true) => {
|
if !matches!(*self.get_running_mode(), RunningMode::NotRunning) {
|
||||||
retries += 1;
|
|
||||||
tracing::Span::current().record("retries", retries);
|
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Core,
|
|
||||||
"Retrying core startup after mixed proxy port fallback ({}/{}): {start_error:#}",
|
|
||||||
retries,
|
|
||||||
MAX_PORT_FALLBACK_RETRIES
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok(false) => {
|
|
||||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||||
return Err(start_error);
|
return Err(RetryError::Stop(start_error));
|
||||||
}
|
}
|
||||||
Err(fallback_error) => {
|
match crate::config::Config::resolve_startup_mixed_port().await {
|
||||||
crate::config::Config::block_startup_core(&fallback_error);
|
Ok(true) => {
|
||||||
return Err(start_error.context(format!(
|
let retries = retries + 1;
|
||||||
"the mixed proxy port fallback did not rescue core startup: {fallback_error:#}"
|
tracing::Span::current().record("retries", retries);
|
||||||
)));
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::Core,
|
||||||
|
"Retrying core startup after mixed proxy port fallback ({}/{}): {start_error:#}",
|
||||||
|
retries,
|
||||||
|
MAX_PORT_FALLBACK_RETRIES
|
||||||
|
);
|
||||||
|
Err(RetryError::Retry(start_error))
|
||||||
|
}
|
||||||
|
Ok(false) => {
|
||||||
|
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||||
|
Err(RetryError::Stop(start_error))
|
||||||
|
}
|
||||||
|
Err(fallback_error) => {
|
||||||
|
crate::config::Config::block_startup_core(&fallback_error);
|
||||||
|
Err(RetryError::Stop(start_error.context(format!(
|
||||||
|
"the mixed proxy port fallback did not rescue core startup: {fallback_error:#}"
|
||||||
|
))))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Err(error) => {
|
||||||
|
crate::config::Config::notify_startup_mixed_port_fallback();
|
||||||
|
Err(RetryError::Stop(error))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Err(error) => {
|
},
|
||||||
crate::config::Config::notify_startup_mixed_port_fallback();
|
)
|
||||||
return Err(error);
|
.await
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
singleton!(CoreManager, CORE_MANAGER);
|
singleton!(CoreManager, CORE_MANAGER);
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod startup_error_tests {
|
||||||
|
use super::{CoreFailure, CoreManager, RunningMode};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recovery_invalidates_an_unread_startup_error_even_after_a_later_exit() {
|
||||||
|
for mode in [RunningMode::Sidecar, RunningMode::Service] {
|
||||||
|
let manager = CoreManager::isolated();
|
||||||
|
manager.record_startup_error(CoreFailure::StartFailed("startup failed".into()));
|
||||||
|
manager.core_started(mode);
|
||||||
|
manager.core_stopped();
|
||||||
|
assert_eq!(manager.get_startup_error(), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unresolved_startup_error_survives_repeated_reads() {
|
||||||
|
let manager = CoreManager::isolated();
|
||||||
|
let failure = CoreFailure::StartFailed("startup failed".into());
|
||||||
|
manager.record_startup_error(failure.clone());
|
||||||
|
for _ in 0..2 {
|
||||||
|
assert_eq!(manager.get_startup_error().as_ref(), Some(&failure));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
use super::claim_core_readiness_generation;
|
use super::claim_core_readiness_generation;
|
||||||
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
||||||
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
use crate::{
|
use crate::{
|
||||||
AsyncHandler,
|
AsyncHandler,
|
||||||
config::Config,
|
config::Config,
|
||||||
@@ -11,13 +12,67 @@ use crate::{
|
|||||||
use anyhow::{Context as _, Result};
|
use anyhow::{Context as _, Result};
|
||||||
use clash_verge_logging::Type;
|
use clash_verge_logging::Type;
|
||||||
use log::Level;
|
use log::Level;
|
||||||
use scopeguard::defer;
|
use std::num::NonZeroUsize;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use tauri_plugin_mihomo::MihomoExt as _;
|
use tauri_plugin_mihomo::MihomoExt as _;
|
||||||
use tauri_plugin_shell::ShellExt as _;
|
use tauri_plugin_shell::ShellExt as _;
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
||||||
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
|
|
||||||
|
let mut config: Mapping = serde_yaml_ng::from_str(yaml)?;
|
||||||
|
let tun = config
|
||||||
|
.entry(Value::from("tun"))
|
||||||
|
.or_insert_with(|| Value::Mapping(Mapping::new()));
|
||||||
|
if !tun.is_mapping() {
|
||||||
|
*tun = Value::Mapping(Mapping::new());
|
||||||
|
}
|
||||||
|
tun.as_mapping_mut()
|
||||||
|
.context("invalid Sidecar TUN configuration")?
|
||||||
|
.insert(Value::from("enable"), Value::Bool(false));
|
||||||
|
Ok(serde_yaml_ng::to_string(&config)?)
|
||||||
|
}
|
||||||
|
|
||||||
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
|
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
async fn retry_service_start<Start, StartFuture>(
|
||||||
|
attempts: usize,
|
||||||
|
retry_delay: std::time::Duration,
|
||||||
|
mut start: Start,
|
||||||
|
) -> Result<()>
|
||||||
|
where
|
||||||
|
Start: FnMut() -> StartFuture + Send,
|
||||||
|
StartFuture: std::future::Future<Output = Result<()>> + Send,
|
||||||
|
{
|
||||||
|
let attempts = NonZeroUsize::new(attempts).ok_or_else(|| anyhow::anyhow!("service start failed"))?;
|
||||||
|
retry(RetryPolicy::fixed(attempts, retry_delay), |attempt| {
|
||||||
|
// The Windows Service IPC future would otherwise inflate every enclosing lifecycle future.
|
||||||
|
let future = Box::pin(start());
|
||||||
|
async move {
|
||||||
|
future.await.map_err(|error| {
|
||||||
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::Core,
|
||||||
|
"service start attempt {}/{} failed: {error:#}",
|
||||||
|
attempt + 1,
|
||||||
|
attempts
|
||||||
|
);
|
||||||
|
if error
|
||||||
|
.downcast_ref::<service::ServiceStartRefusal>()
|
||||||
|
.is_some_and(|refusal| service::StageRequest::is_about_the_bundle(refusal.code))
|
||||||
|
{
|
||||||
|
RetryError::Stop(error)
|
||||||
|
} else {
|
||||||
|
RetryError::Retry(error)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
impl CoreManager {
|
impl CoreManager {
|
||||||
/// Restores profile selections before callers enable the system proxy.
|
/// Restores profile selections before callers enable the system proxy.
|
||||||
/// The bounded first pass continues in the background, and later calls supersede earlier ones.
|
/// The bounded first pass continues in the background, and later calls supersede earlier ones.
|
||||||
@@ -41,14 +96,16 @@ async fn poll_sidecar_readiness<F, Fut>(
|
|||||||
mut probe: F,
|
mut probe: F,
|
||||||
) -> Result<()>
|
) -> Result<()>
|
||||||
where
|
where
|
||||||
F: FnMut() -> Fut,
|
F: FnMut() -> Fut + Send,
|
||||||
Fut: std::future::Future<Output = Result<()>>,
|
Fut: std::future::Future<Output = Result<()>> + Send,
|
||||||
{
|
{
|
||||||
let mut last_error = None;
|
let attempts = NonZeroUsize::new(max_attempts)
|
||||||
for attempt in 0..max_attempts {
|
.context("sidecar readiness was configured with no attempts")
|
||||||
match probe().await {
|
.context("Mihomo API did not become ready")?;
|
||||||
Ok(()) => return Ok(()),
|
retry(RetryPolicy::fixed(attempts, retry_delay), |attempt| {
|
||||||
Err(error) => {
|
let future = probe();
|
||||||
|
async move {
|
||||||
|
future.await.map_err(|error| {
|
||||||
logging!(
|
logging!(
|
||||||
debug,
|
debug,
|
||||||
Type::Core,
|
Type::Core,
|
||||||
@@ -56,16 +113,12 @@ where
|
|||||||
attempt + 1,
|
attempt + 1,
|
||||||
max_attempts
|
max_attempts
|
||||||
);
|
);
|
||||||
last_error = Some(error);
|
RetryError::Retry(error)
|
||||||
}
|
})
|
||||||
}
|
}
|
||||||
if attempt + 1 < max_attempts {
|
})
|
||||||
tokio::time::sleep(retry_delay).await;
|
.await
|
||||||
}
|
.context("Mihomo API did not become ready")
|
||||||
}
|
|
||||||
Err(last_error
|
|
||||||
.unwrap_or_else(|| anyhow::anyhow!("sidecar readiness was configured with no attempts"))
|
|
||||||
.context("Mihomo API did not become ready"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool {
|
fn should_clear_terminated_sidecar(running_mode: &RunningMode, current_pid: Option<u32>, terminated_pid: u32) -> bool {
|
||||||
@@ -98,12 +151,25 @@ impl CoreManager {
|
|||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))]
|
||||||
pub(super) async fn start_core_by_sidecar(&self) -> Result<()> {
|
pub(super) async fn start_core_by_sidecar(&self) -> Result<()> {
|
||||||
|
self.wait_for_sidecar_exit().await?;
|
||||||
|
let execution = clash_verge_service_ipc::execution::reserve_sidecar()
|
||||||
|
.await
|
||||||
|
.inspect_err(service::record_residual_service)?;
|
||||||
self.core_stopped();
|
self.core_stopped();
|
||||||
|
|
||||||
let sidecar_ipc = dirs::sidecar_ipc_path()?;
|
let sidecar_ipc = dirs::sidecar_ipc_path()?;
|
||||||
handle::Handle::app_handle()
|
handle::Handle::app_handle()
|
||||||
.mihomo()
|
.mihomo()
|
||||||
.update_socket_path(dirs::path_to_str(&sidecar_ipc)?.to_owned())?;
|
.update_socket_path(dirs::path_to_str(&sidecar_ipc)?.to_owned())?;
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
let config_file = if crate::core::runstate::RUN_STATE.state().is_admin {
|
||||||
|
Config::generate_file().await?
|
||||||
|
} else {
|
||||||
|
// Reconciliation persists the preference later; the first spawn must already have TUN off.
|
||||||
|
let yaml = sidecar_config_without_tun(&Config::runtime_config_yaml().await?)?;
|
||||||
|
Config::write_runtime_file(&yaml).await?
|
||||||
|
};
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
let config_file = Config::generate_file().await?;
|
let config_file = Config::generate_file().await?;
|
||||||
let app_handle = handle::Handle::app_handle();
|
let app_handle = handle::Handle::app_handle();
|
||||||
let clash_core = Config::verge().await.latest_arc().get_valid_clash_core();
|
let clash_core = Config::verge().await.latest_arc().get_valid_clash_core();
|
||||||
@@ -141,6 +207,8 @@ impl CoreManager {
|
|||||||
config_dir.display()
|
config_dir.display()
|
||||||
)
|
)
|
||||||
})?;
|
})?;
|
||||||
|
let (terminated, termination) = tokio::sync::oneshot::channel();
|
||||||
|
*self.sidecar_exit.lock().await = Some(execution.release_after_exit(child.pid(), termination));
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
let job = {
|
let job = {
|
||||||
match create_and_assign_sidecar_job(child.pid()) {
|
match create_and_assign_sidecar_job(child.pid()) {
|
||||||
@@ -170,6 +238,40 @@ impl CoreManager {
|
|||||||
let pid = child.pid();
|
let pid = child.pid();
|
||||||
tracing::Span::current().record("pid", pid);
|
tracing::Span::current().record("pid", pid);
|
||||||
|
|
||||||
|
// The sidecar has to be drained from the moment it starts. tauri-plugin-shell buffers a
|
||||||
|
// single event, so an unread channel stalls its reader threads and the core blocks on a
|
||||||
|
// full stdout pipe before it ever creates the API socket.
|
||||||
|
let core_readiness_generation = self.mark_core_ready();
|
||||||
|
AsyncHandler::spawn(move || async move {
|
||||||
|
while let Some(event) = rx.recv().await {
|
||||||
|
match event {
|
||||||
|
tauri_plugin_shell::process::CommandEvent::Stdout(line)
|
||||||
|
| tauri_plugin_shell::process::CommandEvent::Stderr(line) => {
|
||||||
|
let message = String::from_utf8_lossy(&line).into_owned();
|
||||||
|
Logger::global().writer_sidecar_log(Level::Error, &message);
|
||||||
|
CLASH_LOGGER.append_log(message);
|
||||||
|
}
|
||||||
|
tauri_plugin_shell::process::CommandEvent::Terminated(term) => {
|
||||||
|
let _ = terminated.send(());
|
||||||
|
let manager = Self::global();
|
||||||
|
let _ = manager.invalidate_core_readiness_if(core_readiness_generation);
|
||||||
|
let message = if let Some(code) = term.code {
|
||||||
|
format!("Process terminated with code: {}", code)
|
||||||
|
} else if let Some(signal) = term.signal {
|
||||||
|
format!("Process terminated by signal: {}", signal)
|
||||||
|
} else {
|
||||||
|
String::from("Process terminated")
|
||||||
|
};
|
||||||
|
Logger::global().writer_sidecar_log(Level::Info, &message);
|
||||||
|
CLASH_LOGGER.clear_logs();
|
||||||
|
manager.clear_terminated_sidecar(pid).await;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async {
|
let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async {
|
||||||
tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async {
|
tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async {
|
||||||
handle::Handle::mihomo().get_version().await
|
handle::Handle::mihomo().get_version().await
|
||||||
@@ -193,48 +295,15 @@ impl CoreManager {
|
|||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
self.set_job_handle(Some(job));
|
self.set_job_handle(Some(job));
|
||||||
self.set_running_child_sidecar(child);
|
self.set_running_child_sidecar(child);
|
||||||
let core_readiness_generation = self.mark_core_ready();
|
|
||||||
self.core_started(RunningMode::Sidecar);
|
self.core_started(RunningMode::Sidecar);
|
||||||
self.restore_selected_nodes().await;
|
self.restore_selected_nodes().await;
|
||||||
|
|
||||||
AsyncHandler::spawn(move || async move {
|
|
||||||
while let Some(event) = rx.recv().await {
|
|
||||||
match event {
|
|
||||||
tauri_plugin_shell::process::CommandEvent::Stdout(line)
|
|
||||||
| tauri_plugin_shell::process::CommandEvent::Stderr(line) => {
|
|
||||||
let message = String::from_utf8_lossy(&line).into_owned();
|
|
||||||
Logger::global().writer_sidecar_log(Level::Error, &message);
|
|
||||||
CLASH_LOGGER.append_log(message);
|
|
||||||
}
|
|
||||||
tauri_plugin_shell::process::CommandEvent::Terminated(term) => {
|
|
||||||
let manager = Self::global();
|
|
||||||
let _ = manager.invalidate_core_readiness_if(core_readiness_generation);
|
|
||||||
let message = if let Some(code) = term.code {
|
|
||||||
format!("Process terminated with code: {}", code)
|
|
||||||
} else if let Some(signal) = term.signal {
|
|
||||||
format!("Process terminated by signal: {}", signal)
|
|
||||||
} else {
|
|
||||||
String::from("Process terminated")
|
|
||||||
};
|
|
||||||
Logger::global().writer_sidecar_log(Level::Info, &message);
|
|
||||||
CLASH_LOGGER.clear_logs();
|
|
||||||
manager.clear_terminated_sidecar(pid).await;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Terminates the sidecar after its caller has successfully cleared the
|
/// Terminates the sidecar after its caller has successfully cleared the
|
||||||
/// system proxy.
|
/// system proxy.
|
||||||
pub(super) fn stop_core_by_sidecar_unprepared(&self) {
|
pub(super) async fn stop_core_by_sidecar_unprepared(&self) -> Result<()> {
|
||||||
defer! {
|
|
||||||
self.core_stopped();
|
|
||||||
}
|
|
||||||
if let Some(child) = self.take_child_sidecar() {
|
if let Some(child) = self.take_child_sidecar() {
|
||||||
let pid = child.pid();
|
let pid = child.pid();
|
||||||
|
|
||||||
@@ -250,6 +319,22 @@ impl CoreManager {
|
|||||||
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
|
logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let result = self.wait_for_sidecar_exit().await;
|
||||||
|
self.core_stopped();
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn wait_for_sidecar_exit(&self) -> Result<()> {
|
||||||
|
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")?;
|
||||||
|
exit.take();
|
||||||
|
}
|
||||||
|
drop(exit);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn start_core_by_service(&self) -> Result<()> {
|
pub(super) async fn start_core_by_service(&self) -> Result<()> {
|
||||||
@@ -269,30 +354,15 @@ impl CoreManager {
|
|||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
{
|
{
|
||||||
use crate::constants::timing;
|
use crate::constants::timing;
|
||||||
let mut last_err = None;
|
retry_service_start(timing::SERVICE_START_RETRIES, timing::SERVICE_START_RETRY_DELAY, || {
|
||||||
for attempt in 0..timing::SERVICE_START_RETRIES {
|
service::run_core_by_service(config_file)
|
||||||
match service::run_core_by_service(config_file).await {
|
})
|
||||||
Ok(()) => {
|
.await?;
|
||||||
self.mark_core_ready();
|
self.mark_core_ready();
|
||||||
self.core_started(RunningMode::Service);
|
self.core_started(RunningMode::Service);
|
||||||
self.restore_selected_nodes().await;
|
self.restore_selected_nodes().await;
|
||||||
service::request_runtime_provider_sync(crate::constants::timing::RUNTIME_PROVIDER_SYNC_DELAY);
|
service::request_runtime_provider_sync(timing::RUNTIME_PROVIDER_SYNC_DELAY);
|
||||||
return Ok(());
|
Ok(())
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Core,
|
|
||||||
"service start attempt {}/{} failed: {e:#}",
|
|
||||||
attempt + 1,
|
|
||||||
timing::SERVICE_START_RETRIES
|
|
||||||
);
|
|
||||||
last_err = Some(e);
|
|
||||||
tokio::time::sleep(timing::SERVICE_START_RETRY_DELAY).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(last_err.unwrap_or_else(|| anyhow::anyhow!("service start failed")))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
|||||||
@@ -1,18 +1,20 @@
|
|||||||
|
pub(crate) mod app_effects;
|
||||||
|
pub mod auto_backup;
|
||||||
pub mod autostart;
|
pub mod autostart;
|
||||||
pub mod backup;
|
pub mod backup;
|
||||||
pub mod handle;
|
|
||||||
pub mod hotkey;
|
pub mod hotkey;
|
||||||
|
pub mod lightweight;
|
||||||
pub mod listener;
|
pub mod listener;
|
||||||
pub mod logger;
|
pub mod logger;
|
||||||
pub mod manager;
|
pub mod manager;
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
pub mod network_watch;
|
pub mod network_watch;
|
||||||
pub mod notification;
|
pub mod notify;
|
||||||
pub(crate) mod owner_identity;
|
pub(crate) mod owner_identity;
|
||||||
pub mod proxy_control;
|
pub mod proxy_control;
|
||||||
pub mod proxy_view;
|
pub mod proxy_view;
|
||||||
pub mod runstate;
|
pub mod runstate;
|
||||||
mod runtime_bundle;
|
pub(crate) mod runtime_bundle;
|
||||||
pub mod service;
|
pub mod service;
|
||||||
pub mod sysopt;
|
pub mod sysopt;
|
||||||
pub mod timer;
|
pub mod timer;
|
||||||
@@ -22,3 +24,4 @@ pub mod validate;
|
|||||||
pub mod win_uwp;
|
pub mod win_uwp;
|
||||||
|
|
||||||
pub use self::{manager::CoreManager, timer::Timer, updater::SilentUpdater};
|
pub use self::{manager::CoreManager, timer::Timer, updater::SilentUpdater};
|
||||||
|
pub use notify::{handle, notification};
|
||||||
|
|||||||
@@ -5,15 +5,9 @@
|
|||||||
|
|
||||||
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler};
|
use crate::{config::Config, core::CoreManager, core::proxy_control, process::AsyncHandler};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use core_foundation::{
|
|
||||||
array::CFArray,
|
|
||||||
runloop::{CFRunLoop, kCFRunLoopCommonModes},
|
|
||||||
string::CFString,
|
|
||||||
};
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
use system_configuration::dynamic_store::{SCDynamicStore, SCDynamicStoreBuilder, SCDynamicStoreCallBackContext};
|
use sysproxy::NetworkServiceMonitor;
|
||||||
|
|
||||||
/// Set once the subscription is live. Startup defers the proxy write to the watcher only then.
|
|
||||||
static ARMED: AtomicBool = AtomicBool::new(false);
|
static ARMED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
pub fn is_armed() -> bool {
|
pub fn is_armed() -> bool {
|
||||||
@@ -23,35 +17,30 @@ pub fn is_armed() -> bool {
|
|||||||
/// Subscribe to the primary IPv4 service on the main run loop. Armed on return, so a service
|
/// Subscribe to the primary IPv4 service on the main run loop. Armed on return, so a service
|
||||||
/// appearing from here on is never missed.
|
/// appearing from here on is never missed.
|
||||||
pub fn start() {
|
pub fn start() {
|
||||||
let store = SCDynamicStoreBuilder::new("clash-verge-rev")
|
match NetworkServiceMonitor::start(|| {
|
||||||
.callback_context(SCDynamicStoreCallBackContext {
|
AsyncHandler::spawn(reapply);
|
||||||
callout: on_change,
|
}) {
|
||||||
info: (),
|
Ok(monitor) => {
|
||||||
})
|
if ARMED
|
||||||
.build();
|
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
|
||||||
let keys = CFArray::from_CFTypes(&[CFString::from_static_string("State:/Network/Global/IPv4")]);
|
.is_err()
|
||||||
let Some(source) = store
|
{
|
||||||
.filter(|store| store.set_notification_keys(&keys, &CFArray::<CFString>::from_CFTypes(&[])))
|
return;
|
||||||
.and_then(|store| store.create_run_loop_source())
|
}
|
||||||
else {
|
// Dropping the monitor stops network notifications, so it must outlive the call.
|
||||||
logging!(
|
std::mem::forget(monitor);
|
||||||
|
logging!(
|
||||||
|
debug,
|
||||||
|
Type::Core,
|
||||||
|
"network watch armed; the system proxy is re-applied on network changes"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(error) => logging!(
|
||||||
warn,
|
warn,
|
||||||
Type::Core,
|
Type::Core,
|
||||||
"could not watch the network; the proxy is not re-applied on changes"
|
"could not watch the network; the proxy is not re-applied on changes: {error}"
|
||||||
);
|
),
|
||||||
return;
|
}
|
||||||
};
|
|
||||||
CFRunLoop::get_main().add_source(&source, unsafe { kCFRunLoopCommonModes });
|
|
||||||
ARMED.store(true, Ordering::Release);
|
|
||||||
logging!(
|
|
||||||
debug,
|
|
||||||
Type::Core,
|
|
||||||
"network watch armed; the system proxy is re-applied on network changes"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn on_change(_: SCDynamicStore, _: CFArray<CFString>, (): &mut ()) {
|
|
||||||
AsyncHandler::spawn(reapply);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn reapply() {
|
async fn reapply() {
|
||||||
@@ -66,10 +55,17 @@ async fn reapply() {
|
|||||||
.latest_arc()
|
.latest_arc()
|
||||||
.enable_system_proxy
|
.enable_system_proxy
|
||||||
.unwrap_or_default()
|
.unwrap_or_default()
|
||||||
|| !proxy_control::has_network_service().await
|
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if !proxy_control::has_network_service().await {
|
||||||
|
logging!(
|
||||||
|
debug,
|
||||||
|
Type::Core,
|
||||||
|
"network changed without a service to write the proxy on; waiting for the next change"
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
if let Err(error) = manager.apply_proxy_after_start().await {
|
if let Err(error) = manager.apply_proxy_after_start().await {
|
||||||
logging!(
|
logging!(
|
||||||
warn,
|
warn,
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
use super::{handle::Handle, notification::FrontendEvent};
|
||||||
|
use anyhow::Result;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use std::{cell::RefCell, future::Future, time::Duration};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Refresh {
|
||||||
|
Clash,
|
||||||
|
Verge,
|
||||||
|
Profiles,
|
||||||
|
Proxies,
|
||||||
|
}
|
||||||
|
|
||||||
|
tokio::task_local! {
|
||||||
|
static PENDING: RefCell<Vec<Refresh>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const REFRESH_WINDOW: Duration = Duration::from_millis(20);
|
||||||
|
static BATCH: RefreshBatch = RefreshBatch(Mutex::new(Vec::new()));
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct RefreshBatch(Mutex<Vec<Refresh>>);
|
||||||
|
|
||||||
|
impl RefreshBatch {
|
||||||
|
fn enqueue(&self, refresh: Refresh) -> bool {
|
||||||
|
let mut pending = self.0.lock();
|
||||||
|
let start_window = pending.is_empty();
|
||||||
|
if !pending.contains(&refresh) {
|
||||||
|
pending.push(refresh);
|
||||||
|
}
|
||||||
|
start_window
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn flush(&self, emit: impl Fn(Refresh)) {
|
||||||
|
// A fixed window bounds latency even under a continuous stream of refreshes.
|
||||||
|
tokio::time::sleep(REFRESH_WINDOW).await;
|
||||||
|
let refreshes = std::mem::take(&mut *self.0.lock());
|
||||||
|
for refresh in refreshes {
|
||||||
|
emit(refresh);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn announce(refresh: Refresh) {
|
||||||
|
if PENDING.try_with(|pending| pending.borrow_mut().push(refresh)).is_err() && BATCH.enqueue(refresh) {
|
||||||
|
crate::AsyncHandler::spawn(|| BATCH.flush(emit));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit(refresh: Refresh) {
|
||||||
|
Handle::send_event(match refresh {
|
||||||
|
Refresh::Clash => FrontendEvent::RefreshClash,
|
||||||
|
Refresh::Verge => FrontendEvent::RefreshVerge,
|
||||||
|
Refresh::Profiles => FrontendEvent::RefreshProfiles,
|
||||||
|
Refresh::Proxies => FrontendEvent::RefreshProxyConfig,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn collect_committed<T: Send>(operation: impl Future<Output = Result<T>> + Send) -> Result<(T, Vec<Refresh>)> {
|
||||||
|
PENDING
|
||||||
|
.scope(RefCell::new(Vec::new()), async {
|
||||||
|
let value = operation.await?;
|
||||||
|
let refreshes = PENDING.with(|pending| pending.take());
|
||||||
|
Ok((value, refreshes))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn after_commit<T: Send>(operation: impl Future<Output = Result<T>> + Send) -> Result<T> {
|
||||||
|
let (value, refreshes) = collect_committed(operation).await?;
|
||||||
|
// Nested transactions hand their notifications to the outer transaction.
|
||||||
|
for refresh in refreshes {
|
||||||
|
announce(refresh);
|
||||||
|
}
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn only_successful_transactions_publish_refreshes() -> Result<()> {
|
||||||
|
let (_, refreshes) = collect_committed(async {
|
||||||
|
announce(Refresh::Clash);
|
||||||
|
after_commit(async {
|
||||||
|
announce(Refresh::Verge);
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let failed = after_commit(async {
|
||||||
|
announce(Refresh::Profiles);
|
||||||
|
Err::<(), _>(anyhow::anyhow!("persistence failed"))
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert!(failed.is_err());
|
||||||
|
announce(Refresh::Clash);
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
assert_eq!(refreshes, [Refresh::Clash, Refresh::Verge, Refresh::Clash]);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn bursts_keep_each_refresh_kind_and_rearm_during_delivery() -> Result<()> {
|
||||||
|
let batch = RefreshBatch::default();
|
||||||
|
let delivered = Mutex::new(Vec::new());
|
||||||
|
assert!(batch.enqueue(Refresh::Clash));
|
||||||
|
for refresh in [Refresh::Verge, Refresh::Clash, Refresh::Profiles, Refresh::Proxies] {
|
||||||
|
assert!(!batch.enqueue(refresh));
|
||||||
|
}
|
||||||
|
tokio::time::timeout(Duration::from_secs(1), async {
|
||||||
|
batch
|
||||||
|
.flush(|refresh| {
|
||||||
|
delivered.lock().push(refresh);
|
||||||
|
if refresh == Refresh::Clash {
|
||||||
|
assert!(batch.enqueue(Refresh::Clash));
|
||||||
|
assert!(!batch.enqueue(Refresh::Clash));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
batch.flush(|refresh| delivered.lock().push(refresh)).await;
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
assert_eq!(
|
||||||
|
*delivered.lock(),
|
||||||
|
[
|
||||||
|
Refresh::Clash,
|
||||||
|
Refresh::Verge,
|
||||||
|
Refresh::Profiles,
|
||||||
|
Refresh::Proxies,
|
||||||
|
Refresh::Clash
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(batch.enqueue(Refresh::Verge));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -18,8 +18,6 @@ pub enum NotificationEvent<'a> {
|
|||||||
LightweightModeEntered,
|
LightweightModeEntered,
|
||||||
ProfilesReactivated,
|
ProfilesReactivated,
|
||||||
AppQuit,
|
AppQuit,
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
AppHidden,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether no app window can currently show the failure.
|
/// Whether no app window can currently show the failure.
|
||||||
@@ -95,11 +93,5 @@ pub async fn notify_event<'a>(event: NotificationEvent<'a>) {
|
|||||||
let body = clash_verge_i18n::t!("notifications.appQuit.body");
|
let body = clash_verge_i18n::t!("notifications.appQuit.body");
|
||||||
notify(title, body);
|
notify(title, body);
|
||||||
}
|
}
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
NotificationEvent::AppHidden => {
|
|
||||||
let title = clash_verge_i18n::t!("notifications.appHidden.title");
|
|
||||||
let body = clash_verge_i18n::t!("notifications.appHidden.body");
|
|
||||||
notify(title, body);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
|
use super::NoticeStatus;
|
||||||
use crate::{APP_HANDLE, singleton};
|
use crate::{APP_HANDLE, singleton};
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
};
|
||||||
use tauri::AppHandle;
|
use tauri::AppHandle;
|
||||||
use tauri_plugin_mihomo::{Mihomo, MihomoExt as _};
|
use tauri_plugin_mihomo::{Mihomo, MihomoExt as _};
|
||||||
|
|
||||||
@@ -36,19 +40,11 @@ impl Handle {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn refresh_clash() {
|
pub fn refresh_clash() {
|
||||||
Self::send_event(FrontendEvent::RefreshClash);
|
super::announce(super::Refresh::Clash);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn refresh_verge() {
|
pub fn refresh_verge() {
|
||||||
Self::send_event(FrontendEvent::RefreshVerge);
|
super::announce(super::Refresh::Verge);
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_profiles() {
|
|
||||||
Self::send_event(FrontendEvent::RefreshProfiles);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn refresh_proxy_config() {
|
|
||||||
Self::send_event(FrontendEvent::RefreshProxyConfig);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Push a Run State snapshot to the frontend.
|
/// Push a Run State snapshot to the frontend.
|
||||||
@@ -80,13 +76,10 @@ impl Handle {
|
|||||||
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn notice_message<S: AsRef<str>, M: Into<String>>(status: S, msg: M) {
|
pub fn notice(status: NoticeStatus, message: impl Into<Arc<str>>) {
|
||||||
let status_str = status.as_ref();
|
|
||||||
let msg_str = msg.into();
|
|
||||||
|
|
||||||
Self::send_event(FrontendEvent::NoticeMessage {
|
Self::send_event(FrontendEvent::NoticeMessage {
|
||||||
status: status_str,
|
status,
|
||||||
message: msg_str,
|
message: message.into(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,7 +95,7 @@ impl Handle {
|
|||||||
self.is_exiting.load(Ordering::Acquire)
|
self.is_exiting.load(Ordering::Acquire)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn send_event(event: FrontendEvent) {
|
pub(super) fn send_event(event: FrontendEvent) {
|
||||||
let handle = Self::global();
|
let handle = Self::global();
|
||||||
if handle.is_exiting() {
|
if handle.is_exiting() {
|
||||||
return;
|
return;
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
mod announce;
|
||||||
|
pub use announce::{Refresh, after_commit, announce};
|
||||||
|
pub mod desktop;
|
||||||
|
pub mod handle;
|
||||||
|
pub mod notification;
|
||||||
|
pub use notification::frontend_wire_contract;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
|
||||||
|
pub enum NoticeStatus {
|
||||||
|
#[serde(rename = "info")]
|
||||||
|
Info,
|
||||||
|
#[serde(rename = "import_sub_url::ok")]
|
||||||
|
ImportSubUrlOk,
|
||||||
|
#[serde(rename = "import_sub_url::error")]
|
||||||
|
ImportSubUrlError,
|
||||||
|
#[serde(rename = "set_config::error")]
|
||||||
|
SetConfigError,
|
||||||
|
#[serde(rename = "core_start::error")]
|
||||||
|
CoreStartError,
|
||||||
|
#[serde(rename = "service_core::repair_required")]
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
ServiceCoreRepairRequired,
|
||||||
|
#[serde(rename = "service_core::app_data_not_owned")]
|
||||||
|
ServiceCoreAppDataNotOwned,
|
||||||
|
#[serde(rename = "service_core::sidecar_fallback")]
|
||||||
|
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||||
|
ServiceCoreSidecarFallback,
|
||||||
|
#[serde(rename = "dns_override::auto_disabled")]
|
||||||
|
DnsOverrideAutoDisabled,
|
||||||
|
#[serde(rename = "enhance::discarded_keys")]
|
||||||
|
EnhanceDiscardedKeys,
|
||||||
|
#[serde(rename = "tun_mode::auto_disabled")]
|
||||||
|
TunModeAutoDisabled,
|
||||||
|
#[serde(rename = "tun_mode::auto_disable_failed")]
|
||||||
|
TunModeAutoDisableFailed,
|
||||||
|
#[serde(rename = "app_restart::core_stop_failed")]
|
||||||
|
AppRestartCoreStopFailed,
|
||||||
|
#[serde(rename = "app_quit::core_stop_failed")]
|
||||||
|
AppQuitCoreStopFailed,
|
||||||
|
#[serde(rename = "update_with_clash_proxy")]
|
||||||
|
UpdateWithClashProxy,
|
||||||
|
#[serde(rename = "update_failed_even_with_clash")]
|
||||||
|
UpdateFailedEvenWithClash,
|
||||||
|
#[serde(rename = "reactivate_profiles::error")]
|
||||||
|
ReactivateProfilesError,
|
||||||
|
#[serde(rename = "update_failed")]
|
||||||
|
UpdateFailed,
|
||||||
|
#[serde(rename = "config_validate::boot_error")]
|
||||||
|
ConfigValidateBootError,
|
||||||
|
#[serde(rename = "config_validate::error")]
|
||||||
|
ConfigValidateError,
|
||||||
|
#[serde(rename = "config_validate::process_terminated")]
|
||||||
|
ConfigValidateProcessTerminated,
|
||||||
|
#[serde(rename = "config_validate::script_error")]
|
||||||
|
ConfigValidateScriptError,
|
||||||
|
#[serde(rename = "config_validate::script_syntax_error")]
|
||||||
|
ConfigValidateScriptSyntaxError,
|
||||||
|
#[serde(rename = "config_validate::script_missing_main")]
|
||||||
|
ConfigValidateScriptMissingMain,
|
||||||
|
#[serde(rename = "config_validate::file_not_found")]
|
||||||
|
ConfigValidateFileNotFound,
|
||||||
|
#[serde(rename = "config_validate::yaml_syntax_error")]
|
||||||
|
ConfigValidateYamlSyntaxError,
|
||||||
|
#[serde(rename = "config_validate::yaml_read_error")]
|
||||||
|
ConfigValidateYamlReadError,
|
||||||
|
#[serde(rename = "config_validate::yaml_mapping_error")]
|
||||||
|
ConfigValidateYamlMappingError,
|
||||||
|
#[serde(rename = "config_validate::merge_syntax_error")]
|
||||||
|
ConfigValidateMergeSyntaxError,
|
||||||
|
#[serde(rename = "config_validate::merge_mapping_error")]
|
||||||
|
ConfigValidateMergeMappingError,
|
||||||
|
#[serde(rename = "config_core::change_success")]
|
||||||
|
ConfigCoreChangeSuccess,
|
||||||
|
#[serde(rename = "config_core::change_error")]
|
||||||
|
ConfigCoreChangeError,
|
||||||
|
#[serde(rename = "mixed_port::fallback")]
|
||||||
|
MixedPortFallback,
|
||||||
|
#[serde(rename = "mixed_port::fallback_error")]
|
||||||
|
MixedPortFallbackError,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NoticeStatus {
|
||||||
|
/// Every variant in golden order. The wire-contract export and the golden
|
||||||
|
/// test both derive their variant list from here; expected strings stay
|
||||||
|
/// hand-written in the test so renames cannot slip through.
|
||||||
|
pub const ALL: [Self; 34] = [
|
||||||
|
Self::Info,
|
||||||
|
Self::ImportSubUrlOk,
|
||||||
|
Self::ImportSubUrlError,
|
||||||
|
Self::SetConfigError,
|
||||||
|
Self::CoreStartError,
|
||||||
|
Self::ServiceCoreRepairRequired,
|
||||||
|
Self::ServiceCoreAppDataNotOwned,
|
||||||
|
Self::ServiceCoreSidecarFallback,
|
||||||
|
Self::DnsOverrideAutoDisabled,
|
||||||
|
Self::EnhanceDiscardedKeys,
|
||||||
|
Self::TunModeAutoDisabled,
|
||||||
|
Self::TunModeAutoDisableFailed,
|
||||||
|
Self::AppRestartCoreStopFailed,
|
||||||
|
Self::AppQuitCoreStopFailed,
|
||||||
|
Self::UpdateWithClashProxy,
|
||||||
|
Self::UpdateFailedEvenWithClash,
|
||||||
|
Self::ReactivateProfilesError,
|
||||||
|
Self::UpdateFailed,
|
||||||
|
Self::ConfigValidateBootError,
|
||||||
|
Self::ConfigValidateError,
|
||||||
|
Self::ConfigValidateProcessTerminated,
|
||||||
|
Self::ConfigValidateScriptError,
|
||||||
|
Self::ConfigValidateScriptSyntaxError,
|
||||||
|
Self::ConfigValidateScriptMissingMain,
|
||||||
|
Self::ConfigValidateFileNotFound,
|
||||||
|
Self::ConfigValidateYamlSyntaxError,
|
||||||
|
Self::ConfigValidateYamlReadError,
|
||||||
|
Self::ConfigValidateYamlMappingError,
|
||||||
|
Self::ConfigValidateMergeSyntaxError,
|
||||||
|
Self::ConfigValidateMergeMappingError,
|
||||||
|
Self::ConfigCoreChangeSuccess,
|
||||||
|
Self::ConfigCoreChangeError,
|
||||||
|
Self::MixedPortFallback,
|
||||||
|
Self::MixedPortFallbackError,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::NoticeStatus;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn notice_status_wire_contract() -> Result<(), serde_json::Error> {
|
||||||
|
let statuses = NoticeStatus::ALL;
|
||||||
|
let expected = [
|
||||||
|
"info",
|
||||||
|
"import_sub_url::ok",
|
||||||
|
"import_sub_url::error",
|
||||||
|
"set_config::error",
|
||||||
|
"core_start::error",
|
||||||
|
"service_core::repair_required",
|
||||||
|
"service_core::app_data_not_owned",
|
||||||
|
"service_core::sidecar_fallback",
|
||||||
|
"dns_override::auto_disabled",
|
||||||
|
"enhance::discarded_keys",
|
||||||
|
"tun_mode::auto_disabled",
|
||||||
|
"tun_mode::auto_disable_failed",
|
||||||
|
"app_restart::core_stop_failed",
|
||||||
|
"app_quit::core_stop_failed",
|
||||||
|
"update_with_clash_proxy",
|
||||||
|
"update_failed_even_with_clash",
|
||||||
|
"reactivate_profiles::error",
|
||||||
|
"update_failed",
|
||||||
|
"config_validate::boot_error",
|
||||||
|
"config_validate::error",
|
||||||
|
"config_validate::process_terminated",
|
||||||
|
"config_validate::script_error",
|
||||||
|
"config_validate::script_syntax_error",
|
||||||
|
"config_validate::script_missing_main",
|
||||||
|
"config_validate::file_not_found",
|
||||||
|
"config_validate::yaml_syntax_error",
|
||||||
|
"config_validate::yaml_read_error",
|
||||||
|
"config_validate::yaml_mapping_error",
|
||||||
|
"config_validate::merge_syntax_error",
|
||||||
|
"config_validate::merge_mapping_error",
|
||||||
|
"config_core::change_success",
|
||||||
|
"config_core::change_error",
|
||||||
|
"mixed_port::fallback",
|
||||||
|
"mixed_port::fallback_error",
|
||||||
|
];
|
||||||
|
let actual: Vec<_> = statuses
|
||||||
|
.into_iter()
|
||||||
|
.map(serde_json::to_value)
|
||||||
|
.collect::<Result<_, _>>()?;
|
||||||
|
assert_eq!(actual, expected.map(serde_json::Value::from));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,24 +1,22 @@
|
|||||||
|
use super::NoticeStatus;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::{
|
use std::sync::Arc;
|
||||||
collections::HashMap,
|
use std::sync::LazyLock;
|
||||||
future::Future,
|
use std::{collections::HashMap, future::Future};
|
||||||
sync::atomic::{AtomicU64, Ordering},
|
|
||||||
};
|
|
||||||
use tauri::{AppHandle, Emitter as _, Manager as _, WebviewWindow};
|
use tauri::{AppHandle, Emitter as _, Manager as _, WebviewWindow};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum FrontendEvent<'a> {
|
pub enum FrontendEvent<'a> {
|
||||||
RefreshClash,
|
RefreshClash,
|
||||||
RefreshVerge,
|
RefreshVerge,
|
||||||
RefreshProfiles,
|
RefreshProfiles,
|
||||||
RefreshProxyConfig,
|
RefreshProxyConfig,
|
||||||
NoticeMessage {
|
NoticeMessage {
|
||||||
status: &'a str,
|
status: NoticeStatus,
|
||||||
message: String,
|
message: Arc<str>,
|
||||||
},
|
},
|
||||||
ProfileChanged {
|
ProfileChanged {
|
||||||
current_profile_id: &'a String,
|
current_profile_id: &'a String,
|
||||||
@@ -89,16 +87,23 @@ pub struct PendingFailure {
|
|||||||
/// Non-destructive pending state, indexed by stable code.
|
/// Non-destructive pending state, indexed by stable code.
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
struct FailureTable {
|
struct FailureTable {
|
||||||
entries: Mutex<HashMap<String, PendingFailure>>,
|
entries: Mutex<FailureEntries>,
|
||||||
sequence: AtomicU64,
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct FailureEntries {
|
||||||
|
map: HashMap<String, PendingFailure>,
|
||||||
|
sequence: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FailureTable {
|
impl FailureTable {
|
||||||
fn record(&self, operation: FailedOperation, code: &str, detail: String) {
|
fn record(&self, operation: FailedOperation, code: &str, detail: String) {
|
||||||
// Sequence assignment and replacement must share one ordering lock.
|
// Sequence assignment and replacement must share one ordering lock.
|
||||||
let mut entries = self.entries.lock();
|
let mut entries = self.entries.lock();
|
||||||
|
entries.sequence = entries.sequence.wrapping_add(1);
|
||||||
// Preserve an unanswered request over a later restore.
|
// Preserve an unanswered request over a later restore.
|
||||||
let operation = entries
|
let operation = entries
|
||||||
|
.map
|
||||||
.get(code)
|
.get(code)
|
||||||
.filter(|existing| existing.operation.outranks(operation))
|
.filter(|existing| existing.operation.outranks(operation))
|
||||||
.map_or(operation, |existing| existing.operation);
|
.map_or(operation, |existing| existing.operation);
|
||||||
@@ -106,13 +111,13 @@ impl FailureTable {
|
|||||||
code: code.into(),
|
code: code.into(),
|
||||||
detail,
|
detail,
|
||||||
operation,
|
operation,
|
||||||
sequence: self.sequence.fetch_add(1, Ordering::AcqRel).wrapping_add(1),
|
sequence: entries.sequence,
|
||||||
};
|
};
|
||||||
entries.insert(code.into(), failure);
|
entries.map.insert(code.into(), failure);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn snapshot(&self) -> Vec<PendingFailure> {
|
fn snapshot(&self) -> Vec<PendingFailure> {
|
||||||
let mut failures: Vec<PendingFailure> = self.entries.lock().values().cloned().collect();
|
let mut failures: Vec<PendingFailure> = self.entries.lock().map.values().cloned().collect();
|
||||||
failures.sort_by_key(|failure| failure.sequence);
|
failures.sort_by_key(|failure| failure.sequence);
|
||||||
failures
|
failures
|
||||||
}
|
}
|
||||||
@@ -120,17 +125,21 @@ impl FailureTable {
|
|||||||
/// Return whether a guard failure was retired.
|
/// Return whether a guard failure was retired.
|
||||||
fn retire_guard(&self) -> bool {
|
fn retire_guard(&self) -> bool {
|
||||||
let mut entries = self.entries.lock();
|
let mut entries = self.entries.lock();
|
||||||
let before = entries.len();
|
let before = entries.map.len();
|
||||||
entries.retain(|_, failure| failure.operation != FailedOperation::SystemProxyGuard);
|
entries
|
||||||
before != entries.len()
|
.map
|
||||||
|
.retain(|_, failure| failure.operation != FailedOperation::SystemProxyGuard);
|
||||||
|
before != entries.map.len()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return whether any proxy failure was retired.
|
/// Return whether any proxy failure was retired.
|
||||||
fn retire_system_proxy(&self, asked: FailedOperation) -> bool {
|
fn retire_system_proxy(&self, asked: FailedOperation) -> bool {
|
||||||
let mut entries = self.entries.lock();
|
let mut entries = self.entries.lock();
|
||||||
let before = entries.len();
|
let before = entries.map.len();
|
||||||
entries.retain(|_, failure| !failure.operation.retired_by_success_of(asked));
|
entries
|
||||||
before != entries.len()
|
.map
|
||||||
|
.retain(|_, failure| !failure.operation.retired_by_success_of(asked));
|
||||||
|
before != entries.map.len()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,7 +238,7 @@ pub fn what_was_asked() -> FailedOperation {
|
|||||||
.unwrap_or(FailedOperation::SystemProxyRestore)
|
.unwrap_or(FailedOperation::SystemProxyRestore)
|
||||||
}
|
}
|
||||||
|
|
||||||
static PENDING_FAILURES: Lazy<FailureTable> = Lazy::new(FailureTable::default);
|
static PENDING_FAILURES: LazyLock<FailureTable> = LazyLock::new(FailureTable::default);
|
||||||
|
|
||||||
pub fn record_failure(operation: FailedOperation, code: &str, detail: impl Into<String>) {
|
pub fn record_failure(operation: FailedOperation, code: &str, detail: impl Into<String>) {
|
||||||
PENDING_FAILURES.record(operation, code, detail.into());
|
PENDING_FAILURES.record(operation, code, detail.into());
|
||||||
@@ -237,7 +246,7 @@ pub fn record_failure(operation: FailedOperation, code: &str, detail: impl Into<
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn has_pending_failure(code: &str) -> bool {
|
pub fn has_pending_failure(code: &str) -> bool {
|
||||||
PENDING_FAILURES.entries.lock().contains_key(code)
|
PENDING_FAILURES.entries.lock().map.contains_key(code)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Return unresolved failures oldest first without clearing them.
|
/// Return unresolved failures oldest first without clearing them.
|
||||||
@@ -283,9 +292,10 @@ impl NotificationSystem {
|
|||||||
FrontendEvent::RefreshVerge => ("verge://refresh-verge-config", Ok(json!("yes"))),
|
FrontendEvent::RefreshVerge => ("verge://refresh-verge-config", Ok(json!("yes"))),
|
||||||
FrontendEvent::RefreshProfiles => ("verge://refresh-profiles", Ok(json!("yes"))),
|
FrontendEvent::RefreshProfiles => ("verge://refresh-profiles", Ok(json!("yes"))),
|
||||||
FrontendEvent::RefreshProxyConfig => ("verge://refresh-proxy-config", Ok(serde_json::Value::Null)),
|
FrontendEvent::RefreshProxyConfig => ("verge://refresh-proxy-config", Ok(serde_json::Value::Null)),
|
||||||
FrontendEvent::NoticeMessage { status, message } => {
|
FrontendEvent::NoticeMessage { status, message } => (
|
||||||
("verge://notice-message", serde_json::to_value((status, message)))
|
"verge://notice-message",
|
||||||
}
|
serde_json::to_value((status, message.as_ref())),
|
||||||
|
),
|
||||||
FrontendEvent::ProfileChanged { current_profile_id } => ("profile-changed", Ok(json!(current_profile_id))),
|
FrontendEvent::ProfileChanged { current_profile_id } => ("profile-changed", Ok(json!(current_profile_id))),
|
||||||
FrontendEvent::TimerUpdated { profile_index } => ("verge://timer-updated", Ok(json!(profile_index))),
|
FrontendEvent::TimerUpdated { profile_index } => ("verge://timer-updated", Ok(json!(profile_index))),
|
||||||
FrontendEvent::ProfileUpdateStarted { uid } => ("profile-update-started", Ok(json!({ "uid": uid }))),
|
FrontendEvent::ProfileUpdateStarted { uid } => ("profile-update-started", Ok(json!({ "uid": uid }))),
|
||||||
@@ -313,3 +323,106 @@ impl NotificationSystem {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod wire_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frontend_event_wire_contract() -> Result<(), serde_json::Error> {
|
||||||
|
let uid = String::from("profile");
|
||||||
|
for (event, name, payload) in super::sample_frontend_events(&uid) {
|
||||||
|
let (actual_name, actual_payload) = NotificationSystem::serialize_event(event);
|
||||||
|
assert_eq!(actual_name, name);
|
||||||
|
assert_eq!(actual_payload?, payload);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One sample per `FrontendEvent` variant, paired with its wire name and payload.
|
||||||
|
/// Shared by the wire golden test and the contract export so the two cannot drift.
|
||||||
|
fn sample_frontend_events(uid: &String) -> Vec<(FrontendEvent<'_>, &'static str, serde_json::Value)> {
|
||||||
|
vec![
|
||||||
|
(
|
||||||
|
FrontendEvent::RefreshClash,
|
||||||
|
"verge://refresh-clash-config",
|
||||||
|
json!("yes"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
FrontendEvent::RefreshVerge,
|
||||||
|
"verge://refresh-verge-config",
|
||||||
|
json!("yes"),
|
||||||
|
),
|
||||||
|
(FrontendEvent::RefreshProfiles, "verge://refresh-profiles", json!("yes")),
|
||||||
|
(
|
||||||
|
FrontendEvent::RefreshProxyConfig,
|
||||||
|
"verge://refresh-proxy-config",
|
||||||
|
json!(null),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
FrontendEvent::NoticeMessage {
|
||||||
|
status: NoticeStatus::Info,
|
||||||
|
message: Arc::from("ok"),
|
||||||
|
},
|
||||||
|
"verge://notice-message",
|
||||||
|
json!(["info", "ok"]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
FrontendEvent::TimerUpdated { profile_index: uid },
|
||||||
|
"verge://timer-updated",
|
||||||
|
json!("profile"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
FrontendEvent::RunStateChanged {
|
||||||
|
state: json!({"running": true}),
|
||||||
|
},
|
||||||
|
"verge://run-state-changed",
|
||||||
|
json!({"running": true}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
FrontendEvent::PendingFailuresChanged,
|
||||||
|
"verge://pending-failures-changed",
|
||||||
|
json!(null),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
FrontendEvent::ProfileChanged {
|
||||||
|
current_profile_id: uid,
|
||||||
|
},
|
||||||
|
"profile-changed",
|
||||||
|
json!("profile"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
FrontendEvent::ProfileUpdateStarted { uid },
|
||||||
|
"profile-update-started",
|
||||||
|
json!({"uid": "profile"}),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
FrontendEvent::ProfileUpdateCompleted { uid },
|
||||||
|
"profile-update-completed",
|
||||||
|
json!({"uid": "profile"}),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Machine-readable form of the frontend wire contract: every event name with a
|
||||||
|
/// serialized sample payload, plus every notice status string. The sample
|
||||||
|
/// payload's JSON shape (string / null / array / object) is what the frontend
|
||||||
|
/// generator maps to TypeScript types. `ThemeChanged` is a Tauri built-in
|
||||||
|
/// linux-only window event, not part of this contract.
|
||||||
|
pub fn frontend_wire_contract() -> serde_json::Value {
|
||||||
|
let uid = String::from("sample");
|
||||||
|
let events: Vec<_> = sample_frontend_events(&uid)
|
||||||
|
.into_iter()
|
||||||
|
.map(|(event, _, _)| {
|
||||||
|
let (name, payload) = NotificationSystem::serialize_event(event);
|
||||||
|
json!({ "name": name, "sample": payload.unwrap_or(serde_json::Value::Null) })
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let statuses: Vec<_> = NoticeStatus::ALL
|
||||||
|
.iter()
|
||||||
|
// A unit variant with a string rename cannot fail to serialize.
|
||||||
|
.filter_map(|status| serde_json::to_value(status).ok())
|
||||||
|
.collect();
|
||||||
|
json!({ "version": 1, "events": events, "noticeStatuses": statuses })
|
||||||
|
}
|
||||||
@@ -392,13 +392,10 @@ mod windows_owner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn repair_root_owner(root: &Path) -> Result<()> {
|
pub(super) fn repair_root_owner(root: &Path) -> Result<()> {
|
||||||
|
// Elevated Windows processes can create directories owned by Administrators.
|
||||||
|
std::fs::create_dir_all(root).context("failed to create the application data root before owner repair")?;
|
||||||
// The Service canonicalizes before checking, so resolve junctions to the same object.
|
// The Service canonicalizes before checking, so resolve junctions to the same object.
|
||||||
let root = match std::fs::canonicalize(root) {
|
let root = std::fs::canonicalize(root).context("failed to canonicalize the application data root")?;
|
||||||
Ok(path) => path,
|
|
||||||
// Nothing to repair: this process creates the root and owns it by construction.
|
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
|
|
||||||
Err(error) => return Err(error).context("failed to canonicalize the application data root"),
|
|
||||||
};
|
|
||||||
let root = root.as_path();
|
let root = root.as_path();
|
||||||
|
|
||||||
let sid = current_sid()?;
|
let sid = current_sid()?;
|
||||||
|
|||||||
@@ -385,12 +385,11 @@ async fn current_service_proxy_config(verge: &IVerge) -> Result<MacosProxyConfig
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Whether macOS has a network service to write the proxy on right now.
|
/// Whether macOS has a network service to write the proxy on right now.
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
pub async fn has_network_service() -> bool {
|
pub async fn has_network_service() -> bool {
|
||||||
tokio::task::spawn_blocking(
|
tokio::task::spawn_blocking(|| sysproxy::Sysproxy::has_network_service().unwrap_or(true))
|
||||||
|| !matches!(sysproxy::Sysproxy::get_system_proxy(), Err(error) if is_missing_network_service(&error)),
|
.await
|
||||||
)
|
.unwrap_or(true)
|
||||||
.await
|
|
||||||
.unwrap_or(true)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_reportable(error: &anyhow::Error) -> bool {
|
pub fn is_reportable(error: &anyhow::Error) -> bool {
|
||||||
@@ -523,25 +522,34 @@ pub async fn clear() -> Result<()> {
|
|||||||
|
|
||||||
/// A failed system call is usually a transient RPC hiccup, so give it a few tries.
|
/// A failed system call is usually a transient RPC hiccup, so give it a few tries.
|
||||||
async fn clear_with_retry() -> Result<()> {
|
async fn clear_with_retry() -> Result<()> {
|
||||||
for attempt in 1..CLEAR_ATTEMPTS {
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
match clear_inner().await {
|
retry(
|
||||||
Err(error)
|
RetryPolicy::fixed(
|
||||||
|
std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize),
|
||||||
|
CLEAR_RETRY_DELAY,
|
||||||
|
),
|
||||||
|
|attempt| async move {
|
||||||
|
clear_inner().await.map_err(|error| {
|
||||||
if matches!(
|
if matches!(
|
||||||
SysproxyFailure::from_chain(&error),
|
SysproxyFailure::from_chain(&error),
|
||||||
Some(SysproxyFailure::SystemCallFailed)
|
Some(SysproxyFailure::SystemCallFailed)
|
||||||
) =>
|
) {
|
||||||
{
|
if attempt + 1 < CLEAR_ATTEMPTS as usize {
|
||||||
logging!(
|
logging!(
|
||||||
warn,
|
warn,
|
||||||
Type::Core,
|
Type::Core,
|
||||||
"clearing the system proxy failed (attempt {attempt}/{CLEAR_ATTEMPTS}); retrying: {error:#}"
|
"clearing the system proxy failed (attempt {}/{CLEAR_ATTEMPTS}); retrying: {error:#}",
|
||||||
);
|
attempt + 1
|
||||||
tokio::time::sleep(CLEAR_RETRY_DELAY).await;
|
);
|
||||||
}
|
}
|
||||||
other => return other,
|
RetryError::Retry(error)
|
||||||
}
|
} else {
|
||||||
}
|
RetryError::Stop(error)
|
||||||
clear_inner().await
|
}
|
||||||
|
})
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(route = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(route = tracing::field::Empty))]
|
||||||
|
|||||||
@@ -27,8 +27,42 @@ pub struct RealEnv;
|
|||||||
|
|
||||||
impl RunStateEnv for RealEnv {
|
impl RunStateEnv for RealEnv {
|
||||||
async fn probe_service_version(&self) -> Result<ServiceVersionReply> {
|
async fn probe_service_version(&self) -> Result<ServiceVersionReply> {
|
||||||
|
// The IPC client would otherwise back off for about two minutes before failing.
|
||||||
|
#[cfg(windows)]
|
||||||
|
if tokio::task::spawn_blocking(crate::core::service::service_stopped)
|
||||||
|
.await
|
||||||
|
.context("service status probe did not finish")??
|
||||||
|
{
|
||||||
|
anyhow::bail!("the Windows service is not running");
|
||||||
|
}
|
||||||
let response = clash_verge_service_ipc::get_version().await?;
|
let response = clash_verge_service_ipc::get_version().await?;
|
||||||
|
let core = if response.code == 0
|
||||||
|
&& response.data.as_ref().is_some_and(|info| {
|
||||||
|
info.supports_client(
|
||||||
|
clash_verge_service_ipc::ProtocolVersion::current(),
|
||||||
|
clash_verge_service_ipc::MIN_REQUIRED_SERVICE_REVISION,
|
||||||
|
)
|
||||||
|
}) {
|
||||||
|
let name = format!(
|
||||||
|
"{}{}",
|
||||||
|
crate::config::Config::verge().await.latest_arc().get_valid_clash_core(),
|
||||||
|
std::env::consts::EXE_SUFFIX
|
||||||
|
);
|
||||||
|
let status = clash_verge_service_ipc::inspect_installation(&[clash_verge_service_ipc::CoreRequirement {
|
||||||
|
name: name.clone(),
|
||||||
|
sha256: None,
|
||||||
|
}])
|
||||||
|
.await?;
|
||||||
|
status
|
||||||
|
.cores
|
||||||
|
.into_iter()
|
||||||
|
.find(|core| core.name == name)
|
||||||
|
.map(|core| core.availability)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
Ok(ServiceVersionReply {
|
Ok(ServiceVersionReply {
|
||||||
|
core,
|
||||||
code: response.code,
|
code: response.code,
|
||||||
message: response.message,
|
message: response.message,
|
||||||
protocol: response.data,
|
protocol: response.data,
|
||||||
@@ -36,9 +70,17 @@ impl RunStateEnv for RealEnv {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn trusted_install_evidence(&self) -> Result<bool> {
|
async fn trusted_install_evidence(&self) -> Result<bool> {
|
||||||
tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
|
let registered = tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence)
|
||||||
.await
|
.await
|
||||||
.context("service registration probe did not finish")?
|
.context("service registration probe did not finish")??;
|
||||||
|
// A helper that outlived its registration is a broken Service, not an absent one.
|
||||||
|
#[cfg(unix)]
|
||||||
|
if !registered && let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available().await {
|
||||||
|
return Ok(error
|
||||||
|
.downcast_ref::<clash_verge_service_ipc::execution::ResidualServiceError>()
|
||||||
|
.is_some());
|
||||||
|
}
|
||||||
|
Ok(registered)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_elevated(&self) -> bool {
|
fn is_elevated(&self) -> bool {
|
||||||
@@ -119,6 +161,7 @@ mod fake {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn service_ready(self) -> Self {
|
pub fn service_ready(self) -> Self {
|
||||||
self.with_evidence(true).always_replying(Ok(ServiceVersionReply {
|
self.with_evidence(true).always_replying(Ok(ServiceVersionReply {
|
||||||
|
core: Some(clash_verge_service_ipc::CoreAvailability::Ready),
|
||||||
code: 0,
|
code: 0,
|
||||||
message: "ok".to_owned(),
|
message: "ok".to_owned(),
|
||||||
protocol: Some(ProtocolInfo::current()),
|
protocol: Some(ProtocolInfo::current()),
|
||||||
@@ -128,6 +171,7 @@ mod fake {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn service_version_mismatch(self) -> Self {
|
pub fn service_version_mismatch(self) -> Self {
|
||||||
self.with_evidence(true).always_replying(Ok(ServiceVersionReply {
|
self.with_evidence(true).always_replying(Ok(ServiceVersionReply {
|
||||||
|
core: Some(clash_verge_service_ipc::CoreAvailability::Ready),
|
||||||
code: 0,
|
code: 0,
|
||||||
message: "ok".to_owned(),
|
message: "ok".to_owned(),
|
||||||
protocol: None,
|
protocol: None,
|
||||||
|
|||||||
@@ -19,8 +19,8 @@ use std::{
|
|||||||
use anyhow::{Context as _, Result, bail};
|
use anyhow::{Context as _, Result, bail};
|
||||||
use arc_swap::ArcSwap;
|
use arc_swap::ArcSwap;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
use std::sync::LazyLock;
|
||||||
use tokio::sync::Notify;
|
use tokio::sync::Notify;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -35,7 +35,7 @@ use health::StoredService;
|
|||||||
use probe::{CurrentServiceProbe, classify_service_health, probe_outcome};
|
use probe::{CurrentServiceProbe, classify_service_health, probe_outcome};
|
||||||
|
|
||||||
/// The process-wide Run State, observing the real machine.
|
/// The process-wide Run State, observing the real machine.
|
||||||
pub static RUN_STATE: Lazy<RunStateStore<RealEnv>> = Lazy::new(|| RunStateStore::new(RealEnv));
|
pub static RUN_STATE: LazyLock<RunStateStore<RealEnv>> = LazyLock::new(|| RunStateStore::new(RealEnv));
|
||||||
|
|
||||||
/// Distinguishes silence from a reply that updated Service health with a rejection.
|
/// Distinguishes silence from a reply that updated Service health with a rejection.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -130,20 +130,21 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
|||||||
|
|
||||||
/// Retries transport failures but stops at the first readable reply, including a rejection.
|
/// Retries transport failures but stops at the first readable reply, including a rejection.
|
||||||
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
|
pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result<RunState, ReadyWaitError> {
|
||||||
let mut last_error = None;
|
use crate::utils::retry::{RetryError, RetryPolicy, retry};
|
||||||
for attempt in 0..attempts {
|
let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| {
|
||||||
|
ReadyWaitError::Unreachable(anyhow::anyhow!(
|
||||||
|
"service readiness wait was configured with no attempts"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
retry(RetryPolicy::fixed(attempts, interval), |_| async {
|
||||||
match self.env.probe_service_version().await {
|
match self.env.probe_service_version().await {
|
||||||
Ok(reply) => return self.record_reply(&reply).map_err(ReadyWaitError::Rejected),
|
Ok(reply) => self
|
||||||
Err(error) => last_error = Some(error),
|
.record_reply(&reply)
|
||||||
|
.map_err(|error| RetryError::Stop(ReadyWaitError::Rejected(error))),
|
||||||
|
Err(error) => Err(RetryError::Retry(ReadyWaitError::Unreachable(error))),
|
||||||
}
|
}
|
||||||
if attempt + 1 < attempts {
|
})
|
||||||
tokio::time::sleep(interval).await;
|
.await
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Err(ReadyWaitError::Unreachable(last_error.unwrap_or_else(|| {
|
|
||||||
anyhow::anyhow!("service readiness wait was configured with no attempts")
|
|
||||||
})))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn record_reply(&self, reply: &ServiceVersionReply) -> Result<RunState> {
|
fn record_reply(&self, reply: &ServiceVersionReply) -> Result<RunState> {
|
||||||
@@ -152,6 +153,10 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
|||||||
self.observe(ServiceHealth::Ready);
|
self.observe(ServiceHealth::Ready);
|
||||||
Ok(self.state())
|
Ok(self.state())
|
||||||
}
|
}
|
||||||
|
ServiceVersionCheck::CoreUnavailable(error) => {
|
||||||
|
self.observe(ServiceHealth::Unavailable(error.clone()));
|
||||||
|
bail!(error)
|
||||||
|
}
|
||||||
ServiceVersionCheck::NeedsReinstall(error) => {
|
ServiceVersionCheck::NeedsReinstall(error) => {
|
||||||
self.observe(ServiceHealth::VersionMismatch);
|
self.observe(ServiceHealth::VersionMismatch);
|
||||||
bail!(error)
|
bail!(error)
|
||||||
@@ -178,7 +183,10 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
match self.env.probe_service_version().await {
|
match self.env.probe_service_version().await {
|
||||||
Ok(reply) => classify_service_health(probe_outcome(&reply), has_marker, ""),
|
Ok(reply) => match classify_service_version_reply(&reply) {
|
||||||
|
ServiceVersionCheck::CoreUnavailable(reason) => ServiceHealth::Unavailable(reason),
|
||||||
|
_ => classify_service_health(probe_outcome(&reply), has_marker, ""),
|
||||||
|
},
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
logging!(warn, Type::Service, "current service IPC is unavailable: {error:#}");
|
logging!(warn, Type::Service, "current service IPC is unavailable: {error:#}");
|
||||||
classify_service_health(
|
classify_service_health(
|
||||||
@@ -323,6 +331,21 @@ impl<E: RunStateEnv> RunStateStore<E> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(target_os = "windows")]
|
||||||
|
pub fn allow_sidecar_after_service_refusal(&self, reason: String) -> Result<()> {
|
||||||
|
let mut state = self.service.lock();
|
||||||
|
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.
|
||||||
|
state.service.health = ServiceHealth::Unavailable(reason);
|
||||||
|
state.service.allow_sidecar();
|
||||||
|
state.bump();
|
||||||
|
drop(state);
|
||||||
|
self.announce();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Requests installation only for a confirmed absent Service.
|
/// Requests installation only for a confirmed absent Service.
|
||||||
pub fn require_install_for_session(&self) -> Result<()> {
|
pub fn require_install_for_session(&self) -> Result<()> {
|
||||||
let mut state = self.service.lock();
|
let mut state = self.service.lock();
|
||||||
@@ -472,6 +495,7 @@ mod tests {
|
|||||||
|
|
||||||
fn ready_reply() -> ServiceVersionReply {
|
fn ready_reply() -> ServiceVersionReply {
|
||||||
ServiceVersionReply {
|
ServiceVersionReply {
|
||||||
|
core: Some(clash_verge_service_ipc::CoreAvailability::Ready),
|
||||||
code: 0,
|
code: 0,
|
||||||
message: "ok".to_owned(),
|
message: "ok".to_owned(),
|
||||||
protocol: Some(clash_verge_service_ipc::ProtocolInfo::current()),
|
protocol: Some(clash_verge_service_ipc::ProtocolInfo::current()),
|
||||||
|
|||||||
@@ -4,7 +4,9 @@
|
|||||||
//! on [`super::env::RunStateEnv`], so these classifications are testable without IPC,
|
//! on [`super::env::RunStateEnv`], so these classifications are testable without IPC,
|
||||||
//! systemd, SCM or launchd.
|
//! systemd, SCM or launchd.
|
||||||
|
|
||||||
use clash_verge_service_ipc::{MIN_REQUIRED_SERVICE_REVISION, ProtocolInfo, ProtocolVersion};
|
use clash_verge_service_ipc::{
|
||||||
|
MIN_REQUIRED_SERVICE_REVISION, ProtocolInfo, ProtocolVersion, VERSION as SERVICE_VERSION,
|
||||||
|
};
|
||||||
|
|
||||||
use super::health::ServiceHealth;
|
use super::health::ServiceHealth;
|
||||||
|
|
||||||
@@ -14,6 +16,7 @@ pub struct ServiceVersionReply {
|
|||||||
pub code: u16,
|
pub code: u16,
|
||||||
pub message: String,
|
pub message: String,
|
||||||
pub protocol: Option<ProtocolInfo>,
|
pub protocol: Option<ProtocolInfo>,
|
||||||
|
pub core: Option<clash_verge_service_ipc::CoreAvailability>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The verdict on a [`ServiceVersionReply`].
|
/// The verdict on a [`ServiceVersionReply`].
|
||||||
@@ -21,6 +24,7 @@ pub struct ServiceVersionReply {
|
|||||||
pub enum ServiceVersionCheck {
|
pub enum ServiceVersionCheck {
|
||||||
Ready,
|
Ready,
|
||||||
NeedsReinstall(String),
|
NeedsReinstall(String),
|
||||||
|
CoreUnavailable(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a live probe of the currently-installed Service told us.
|
/// What a live probe of the currently-installed Service told us.
|
||||||
@@ -32,22 +36,30 @@ pub enum CurrentServiceProbe {
|
|||||||
Unavailable,
|
Unavailable,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decide whether the Service we reached speaks a protocol this client can use.
|
/// Require the bundled Service version as well as a usable protocol.
|
||||||
pub fn classify_service_version_reply(reply: &ServiceVersionReply) -> ServiceVersionCheck {
|
pub fn classify_service_version_reply(reply: &ServiceVersionReply) -> ServiceVersionCheck {
|
||||||
let client = ProtocolVersion::current();
|
let client = ProtocolVersion::current();
|
||||||
if reply.code == 0
|
if reply.code == 0
|
||||||
&& reply
|
&& reply.protocol.as_ref().is_some_and(|info| {
|
||||||
.protocol
|
info.build_version == SERVICE_VERSION && info.supports_client(client, MIN_REQUIRED_SERVICE_REVISION)
|
||||||
.as_ref()
|
})
|
||||||
.is_some_and(|info| info.supports_client(client, MIN_REQUIRED_SERVICE_REVISION))
|
|
||||||
{
|
{
|
||||||
return ServiceVersionCheck::Ready;
|
return match &reply.core {
|
||||||
|
Some(clash_verge_service_ipc::CoreAvailability::Ready) => ServiceVersionCheck::Ready,
|
||||||
|
Some(clash_verge_service_ipc::CoreAvailability::Rejected { reason }) => {
|
||||||
|
ServiceVersionCheck::CoreUnavailable(format!("approved core was rejected: {reason}"))
|
||||||
|
}
|
||||||
|
_ => ServiceVersionCheck::CoreUnavailable(
|
||||||
|
"the selected approved core is missing or does not match; reinstall the service to repair it".into(),
|
||||||
|
),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let detail = if reply.code == 0 {
|
let detail = if reply.code == 0 {
|
||||||
match reply.protocol.as_ref() {
|
match reply.protocol.as_ref() {
|
||||||
Some(info) => format!(
|
Some(info) => format!(
|
||||||
"client requires epoch {} revision >= {}, service reports epoch {} revision {} (build {})",
|
"client requires service version {} with epoch {} revision >= {}, service reports epoch {} revision {} (build {})",
|
||||||
|
SERVICE_VERSION,
|
||||||
client.epoch,
|
client.epoch,
|
||||||
MIN_REQUIRED_SERVICE_REVISION,
|
MIN_REQUIRED_SERVICE_REVISION,
|
||||||
info.protocol.epoch,
|
info.protocol.epoch,
|
||||||
@@ -63,16 +75,16 @@ pub fn classify_service_version_reply(reply: &ServiceVersionReply) -> ServiceVer
|
|||||||
)
|
)
|
||||||
};
|
};
|
||||||
ServiceVersionCheck::NeedsReinstall(format!(
|
ServiceVersionCheck::NeedsReinstall(format!(
|
||||||
"Service helper protocol mismatch: {detail}. Choose Reinstall or Repair to continue"
|
"Service helper version or protocol mismatch: {detail}. Choose Reinstall to uninstall the existing service and install the required version"
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Classify a version reply into the probe outcome used by [`classify_service_health`].
|
/// Classify a version reply into the probe outcome used by [`classify_service_health`].
|
||||||
pub fn probe_outcome(reply: &ServiceVersionReply) -> CurrentServiceProbe {
|
pub fn probe_outcome(reply: &ServiceVersionReply) -> CurrentServiceProbe {
|
||||||
if classify_service_version_reply(reply) == ServiceVersionCheck::Ready {
|
match classify_service_version_reply(reply) {
|
||||||
CurrentServiceProbe::Ready
|
ServiceVersionCheck::Ready => CurrentServiceProbe::Ready,
|
||||||
} else {
|
ServiceVersionCheck::NeedsReinstall(_) => CurrentServiceProbe::VersionMismatch,
|
||||||
CurrentServiceProbe::VersionMismatch
|
ServiceVersionCheck::CoreUnavailable(_) => CurrentServiceProbe::Unavailable,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,6 +114,7 @@ mod tests {
|
|||||||
|
|
||||||
fn ready_reply() -> ServiceVersionReply {
|
fn ready_reply() -> ServiceVersionReply {
|
||||||
ServiceVersionReply {
|
ServiceVersionReply {
|
||||||
|
core: Some(clash_verge_service_ipc::CoreAvailability::Ready),
|
||||||
code: 0,
|
code: 0,
|
||||||
message: "ok".to_owned(),
|
message: "ok".to_owned(),
|
||||||
protocol: Some(ProtocolInfo::current()),
|
protocol: Some(ProtocolInfo::current()),
|
||||||
@@ -117,9 +130,26 @@ mod tests {
|
|||||||
assert_eq!(probe_outcome(&ready_reply()), CurrentServiceProbe::Ready);
|
assert_eq!(probe_outcome(&ready_reply()), CurrentServiceProbe::Ready);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compatible_service_with_missing_core_is_unavailable() {
|
||||||
|
for core in [
|
||||||
|
None,
|
||||||
|
Some(clash_verge_service_ipc::CoreAvailability::Missing),
|
||||||
|
Some(clash_verge_service_ipc::CoreAvailability::DigestMismatch),
|
||||||
|
] {
|
||||||
|
let reply = ServiceVersionReply { core, ..ready_reply() };
|
||||||
|
assert!(matches!(
|
||||||
|
classify_service_version_reply(&reply),
|
||||||
|
ServiceVersionCheck::CoreUnavailable(_)
|
||||||
|
));
|
||||||
|
assert_eq!(probe_outcome(&reply), CurrentServiceProbe::Unavailable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_reply_without_protocol_information_needs_reinstall() {
|
fn a_reply_without_protocol_information_needs_reinstall() {
|
||||||
let reply = ServiceVersionReply {
|
let reply = ServiceVersionReply {
|
||||||
|
core: Some(clash_verge_service_ipc::CoreAvailability::Ready),
|
||||||
code: 0,
|
code: 0,
|
||||||
message: "ok".to_owned(),
|
message: "ok".to_owned(),
|
||||||
protocol: None,
|
protocol: None,
|
||||||
@@ -137,6 +167,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn a_nonzero_code_needs_reinstall() {
|
fn a_nonzero_code_needs_reinstall() {
|
||||||
let reply = ServiceVersionReply {
|
let reply = ServiceVersionReply {
|
||||||
|
core: Some(clash_verge_service_ipc::CoreAvailability::Ready),
|
||||||
code: 7,
|
code: 7,
|
||||||
message: "nope".to_owned(),
|
message: "nope".to_owned(),
|
||||||
protocol: Some(ProtocolInfo::current()),
|
protocol: Some(ProtocolInfo::current()),
|
||||||
@@ -152,6 +183,7 @@ mod tests {
|
|||||||
let mut info = ProtocolInfo::current();
|
let mut info = ProtocolInfo::current();
|
||||||
info.protocol.epoch = info.protocol.epoch.wrapping_add(1);
|
info.protocol.epoch = info.protocol.epoch.wrapping_add(1);
|
||||||
let reply = ServiceVersionReply {
|
let reply = ServiceVersionReply {
|
||||||
|
core: Some(clash_verge_service_ipc::CoreAvailability::Ready),
|
||||||
code: 0,
|
code: 0,
|
||||||
message: "ok".to_owned(),
|
message: "ok".to_owned(),
|
||||||
protocol: Some(info),
|
protocol: Some(info),
|
||||||
@@ -172,6 +204,7 @@ mod tests {
|
|||||||
let mut info = ProtocolInfo::current();
|
let mut info = ProtocolInfo::current();
|
||||||
info.protocol.revision = revision;
|
info.protocol.revision = revision;
|
||||||
let reply = ServiceVersionReply {
|
let reply = ServiceVersionReply {
|
||||||
|
core: Some(clash_verge_service_ipc::CoreAvailability::Ready),
|
||||||
code: 0,
|
code: 0,
|
||||||
message: "ok".to_owned(),
|
message: "ok".to_owned(),
|
||||||
protocol: Some(info),
|
protocol: Some(info),
|
||||||
@@ -190,6 +223,7 @@ mod tests {
|
|||||||
for protocol in [None, Some(old_epoch)] {
|
for protocol in [None, Some(old_epoch)] {
|
||||||
for code in [0, 1] {
|
for code in [0, 1] {
|
||||||
let reply = ServiceVersionReply {
|
let reply = ServiceVersionReply {
|
||||||
|
core: None,
|
||||||
code,
|
code,
|
||||||
message: "unsupported command".to_owned(),
|
message: "unsupported command".to_owned(),
|
||||||
protocol: protocol.clone(),
|
protocol: protocol.clone(),
|
||||||
|
|||||||
@@ -2,11 +2,13 @@ use anyhow::{Context as _, Result, bail};
|
|||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use clash_verge_service_ipc::{RemoteProvider, RuntimeAsset, RuntimeBundle};
|
use clash_verge_service_ipc::{RemoteProvider, RuntimeAsset, RuntimeBundle};
|
||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use std::collections::HashSet;
|
use sha2::{Digest as _, Sha256};
|
||||||
|
use std::collections::{BTreeMap, HashSet};
|
||||||
use std::path::{Component, Path, PathBuf};
|
use std::path::{Component, Path, PathBuf};
|
||||||
|
|
||||||
pub(crate) const GEO_ASSETS: &[&str] = &[
|
pub(crate) const GEO_ASSETS: &[&str] = &[
|
||||||
"Country.mmdb",
|
"Country.mmdb",
|
||||||
|
"ASN.mmdb",
|
||||||
"geoip.dat",
|
"geoip.dat",
|
||||||
"geosite.dat",
|
"geosite.dat",
|
||||||
"geoip.metadb",
|
"geoip.metadb",
|
||||||
@@ -53,6 +55,94 @@ pub(crate) fn remote_providers_of(config: &Mapping, config_root: &Path) -> Resul
|
|||||||
Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers)
|
Ok(collect_runtime_parts(Value::Mapping(config.clone()), config_root)?.remote_providers)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct ProviderPathOwners {
|
||||||
|
remote: BTreeMap<String, Vec<(&'static str, Value)>>,
|
||||||
|
local: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
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::<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;
|
||||||
|
};
|
||||||
|
for (name, provider) in providers {
|
||||||
|
let Some(raw_path) = provider.get("path").and_then(Value::as_str) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let is_remote = provider.get("type").and_then(Value::as_str) == Some("http");
|
||||||
|
let destination = if is_remote {
|
||||||
|
provider_destination(&config_root, raw_path)
|
||||||
|
} else {
|
||||||
|
local_provider_source(&config_root, raw_path)
|
||||||
|
.and_then(|source| destination_below_root(&config_root, &source))
|
||||||
|
.or_else(|_| provider_destination(&config_root, raw_path))
|
||||||
|
};
|
||||||
|
let Ok(destination) = destination else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
reserved.insert(destination.clone());
|
||||||
|
let owners = paths.entry(destination).or_default();
|
||||||
|
match (is_remote, provider.get("url").and_then(Value::as_str)) {
|
||||||
|
(true, Some(url)) => owners
|
||||||
|
.remote
|
||||||
|
.entry(url.to_owned())
|
||||||
|
.or_default()
|
||||||
|
.push((section, name.clone())),
|
||||||
|
_ => owners.local = true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (destination, owners) in paths {
|
||||||
|
if owners.local || owners.remote.len() < 2 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Allocate every source in a conflict group, so declaration order cannot select a cache's owner.
|
||||||
|
for (url, providers) in owners.remote {
|
||||||
|
let replacement = allocate_provider_destination(&destination, &url, &mut reserved);
|
||||||
|
for (section, name) in providers {
|
||||||
|
config[section][&name]["path"] = Value::String(replacement.clone());
|
||||||
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::Config,
|
||||||
|
"provider {section}/{name:?} shared cache {destination:?} with another source; using {replacement:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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: String = digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect();
|
||||||
|
let path = Path::new(destination);
|
||||||
|
let extension = path
|
||||||
|
.extension()
|
||||||
|
.map(|ext| format!(".{}", ext.to_string_lossy()))
|
||||||
|
.unwrap_or_default();
|
||||||
|
let mut suffix = String::new();
|
||||||
|
let mut sequence = 0;
|
||||||
|
loop {
|
||||||
|
let candidate = path
|
||||||
|
.with_file_name(format!("cvr-{digest}{suffix}{extension}"))
|
||||||
|
.to_string_lossy()
|
||||||
|
.replace('\\', "/");
|
||||||
|
if reserved.insert(candidate.clone()) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
sequence += 1;
|
||||||
|
suffix = format!("-{sequence}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeParts> {
|
fn collect_runtime_parts(mut config: Value, config_root: &Path) -> Result<RuntimeParts> {
|
||||||
let config_root = std::fs::canonicalize(config_root)?;
|
let config_root = std::fs::canonicalize(config_root)?;
|
||||||
let mut assets = Vec::new();
|
let mut assets = Vec::new();
|
||||||
@@ -254,7 +344,91 @@ fn normalized_destination(relative: &Path) -> Result<String> {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::collect_runtime_bundle;
|
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() -> 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(
|
||||||
|
"rule-providers:\n AppleDev:\n type: http\n url: https://one.example/AppleDev.yaml\n path: ./providers/rule/AppleDev.yaml\n mirror:\n type: http\n url: https://two.example/AppleDev.yaml\n path: providers/rule/AppleDev.yaml\n",
|
||||||
|
)?;
|
||||||
|
let original = config.clone();
|
||||||
|
let root = std::fs::canonicalize(root)?;
|
||||||
|
let mut reordered = config.clone();
|
||||||
|
reordered["rule-providers"] = serde_yaml_ng::from_str(&format!(
|
||||||
|
"mirror:\n type: http\n url: https://two.example/AppleDev.yaml\n path: {}\nAppleDev:\n type: http\n url: https://one.example/AppleDev.yaml\n path: providers/rule/AppleDev.yaml\n",
|
||||||
|
root.join("providers/rule/AppleDev.yaml").display(),
|
||||||
|
))?;
|
||||||
|
|
||||||
|
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, &root.join("mihomo")).await?;
|
||||||
|
let paths = &config["rule-providers"];
|
||||||
|
assert_ne!(paths["AppleDev"]["path"], paths["mirror"]["path"]);
|
||||||
|
resolve_provider_path_conflicts(&mut reordered, &root)?;
|
||||||
|
assert_eq!(
|
||||||
|
config, reordered,
|
||||||
|
"path allocation must not depend on declaration order or path spelling"
|
||||||
|
);
|
||||||
|
let resolved = config.clone();
|
||||||
|
resolve_provider_path_conflicts(&mut config, &root)?;
|
||||||
|
assert_eq!(
|
||||||
|
config, resolved,
|
||||||
|
"resolving an already generated config must be idempotent"
|
||||||
|
);
|
||||||
|
|
||||||
|
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.provider));
|
||||||
|
assert_eq!(
|
||||||
|
config[declared.section][&declared.name]["path"],
|
||||||
|
declared.provider.destination
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
config[declared.section][&declared.name]["url"],
|
||||||
|
original[declared.section][&declared.name]["url"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
std::fs::remove_dir_all(root)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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",
|
||||||
|
)?;
|
||||||
|
let mut config = original.clone();
|
||||||
|
resolve_provider_path_conflicts(&mut config, &root)?;
|
||||||
|
let allocated = config["proxy-providers"]["a"]["path"].clone();
|
||||||
|
let mut config = original;
|
||||||
|
config["rule-providers"]["reserved"] = serde_yaml_ng::from_str("type: file\npath: placeholder")?;
|
||||||
|
config["rule-providers"]["reserved"]["path"] = allocated.clone();
|
||||||
|
resolve_provider_path_conflicts(&mut config, &root)?;
|
||||||
|
assert_ne!(config["proxy-providers"]["a"]["path"], allocated);
|
||||||
|
assert_ne!(
|
||||||
|
config["proxy-providers"]["a"]["path"],
|
||||||
|
config["rule-providers"]["b"]["path"]
|
||||||
|
);
|
||||||
|
assert_eq!(config["rule-providers"]["reserved"]["path"], allocated);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
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",
|
||||||
|
)?;
|
||||||
|
let original = config.clone();
|
||||||
|
resolve_provider_path_conflicts(&mut config, &std::env::temp_dir())?;
|
||||||
|
assert_eq!(config, original);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn collects_only_local_providers_and_existing_geo_assets() -> anyhow::Result<()> {
|
async fn collects_only_local_providers_and_existing_geo_assets() -> anyhow::Result<()> {
|
||||||
|
|||||||
+403
-465
File diff suppressed because it is too large
Load Diff
@@ -1,14 +1,14 @@
|
|||||||
use crate::config::{IProfilePreview, IVerge};
|
use crate::config::{IProfilePreview, IVerge};
|
||||||
|
use crate::core::lightweight;
|
||||||
use crate::core::tray::menu_def::TrayAction;
|
use crate::core::tray::menu_def::TrayAction;
|
||||||
use crate::module::lightweight;
|
|
||||||
use crate::process::AsyncHandler;
|
use crate::process::AsyncHandler;
|
||||||
use crate::singleton;
|
use crate::singleton;
|
||||||
use crate::utils::window_manager::WindowManager;
|
use crate::utils::window_manager::WindowManager;
|
||||||
use crate::{
|
use crate::{
|
||||||
Type, cmd,
|
Type, cmd,
|
||||||
config::Config,
|
config::Config,
|
||||||
|
core::lightweight::is_in_lightweight_mode,
|
||||||
feat, logging,
|
feat, logging,
|
||||||
module::lightweight::is_in_lightweight_mode,
|
|
||||||
utils::{dirs::find_target_icons, help},
|
utils::{dirs::find_target_icons, help},
|
||||||
};
|
};
|
||||||
use clash_verge_limiter::{Limiter, SystemClock, SystemLimiter};
|
use clash_verge_limiter::{Limiter, SystemClock, SystemLimiter};
|
||||||
|
|||||||
@@ -1,20 +1,16 @@
|
|||||||
use crate::{config::Config, singleton, utils::dirs};
|
use crate::{config::Config, singleton, utils::dirs};
|
||||||
use anyhow::Result;
|
use anyhow::{Context as _, Result};
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use parking_lot::RwLock;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::{
|
use std::{
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::atomic::{AtomicBool, Ordering},
|
sync::atomic::{AtomicBool, Ordering},
|
||||||
};
|
};
|
||||||
use tauri_plugin_updater::{Update, UpdaterExt as _};
|
use tauri_plugin_updater::UpdaterExt as _;
|
||||||
|
|
||||||
pub struct SilentUpdater {
|
pub struct SilentUpdater {
|
||||||
update_ready: AtomicBool,
|
update_ready: AtomicBool,
|
||||||
pending_bytes: RwLock<Option<Vec<u8>>>,
|
|
||||||
pending_update: RwLock<Option<Update>>,
|
|
||||||
pending_version: RwLock<Option<String>>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
singleton!(SilentUpdater, SILENT_UPDATER);
|
singleton!(SilentUpdater, SILENT_UPDATER);
|
||||||
@@ -23,9 +19,6 @@ impl SilentUpdater {
|
|||||||
const fn new() -> Self {
|
const fn new() -> Self {
|
||||||
Self {
|
Self {
|
||||||
update_ready: AtomicBool::new(false),
|
update_ready: AtomicBool::new(false),
|
||||||
pending_bytes: RwLock::new(None),
|
|
||||||
pending_update: RwLock::new(None),
|
|
||||||
pending_version: RwLock::new(None),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,17 +40,20 @@ impl SilentUpdater {
|
|||||||
|
|
||||||
fn write_cache(bytes: &[u8], version: &str) -> Result<()> {
|
fn write_cache(bytes: &[u8], version: &str) -> Result<()> {
|
||||||
let cache_dir = Self::cache_dir()?;
|
let cache_dir = Self::cache_dir()?;
|
||||||
std::fs::create_dir_all(&cache_dir)?;
|
std::fs::create_dir_all(&cache_dir)
|
||||||
|
.with_context(|| format!("failed to create update cache directory {}", cache_dir.display()))?;
|
||||||
|
|
||||||
let bin_path = cache_dir.join("pending_update.bin");
|
let bin_path = cache_dir.join("pending_update.bin");
|
||||||
std::fs::write(&bin_path, bytes)?;
|
std::fs::write(&bin_path, bytes)
|
||||||
|
.with_context(|| format!("failed to write update cache {}", bin_path.display()))?;
|
||||||
|
|
||||||
let meta = UpdateCacheMeta {
|
let meta = UpdateCacheMeta {
|
||||||
version: version.to_string(),
|
version: version.to_string(),
|
||||||
downloaded_at: Utc::now().to_rfc3339(),
|
downloaded_at: Utc::now().to_rfc3339(),
|
||||||
};
|
};
|
||||||
let meta_path = cache_dir.join("pending_update.json");
|
let meta_path = cache_dir.join("pending_update.json");
|
||||||
std::fs::write(&meta_path, serde_json::to_string_pretty(&meta)?)?;
|
std::fs::write(&meta_path, serde_json::to_string_pretty(&meta)?)
|
||||||
|
.with_context(|| format!("failed to write update metadata {}", meta_path.display()))?;
|
||||||
|
|
||||||
logging!(
|
logging!(
|
||||||
info,
|
info,
|
||||||
@@ -71,7 +67,7 @@ impl SilentUpdater {
|
|||||||
|
|
||||||
fn read_cache_bytes() -> Result<Vec<u8>> {
|
fn read_cache_bytes() -> Result<Vec<u8>> {
|
||||||
let bin_path = Self::cache_dir()?.join("pending_update.bin");
|
let bin_path = Self::cache_dir()?.join("pending_update.bin");
|
||||||
Ok(std::fs::read(bin_path)?)
|
std::fs::read(&bin_path).with_context(|| format!("failed to read update cache {}", bin_path.display()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn read_cache_meta() -> Result<UpdateCacheMeta> {
|
fn read_cache_meta() -> Result<UpdateCacheMeta> {
|
||||||
@@ -85,7 +81,12 @@ impl SilentUpdater {
|
|||||||
&& cache_dir.exists()
|
&& cache_dir.exists()
|
||||||
{
|
{
|
||||||
if let Err(e) = std::fs::remove_dir_all(&cache_dir) {
|
if let Err(e) = std::fs::remove_dir_all(&cache_dir) {
|
||||||
logging!(warn, Type::System, "Failed to delete update cache: {e}");
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::System,
|
||||||
|
"Failed to delete update cache {}: {e}",
|
||||||
|
cache_dir.display()
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
logging!(info, Type::System, "Update cache deleted");
|
logging!(info, Type::System, "Update cache deleted");
|
||||||
}
|
}
|
||||||
@@ -93,15 +94,22 @@ impl SilentUpdater {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Compares numeric version components after stripping `v` and prerelease suffixes.
|
pub fn is_build_to_stable(current: &str, remote: &str) -> bool {
|
||||||
|
let Some((base, build)) = current.trim_start_matches('v').split_once('+') else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
!build.is_empty() && !base.contains('-') && base == remote.trim_start_matches('v')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compares numeric version components after stripping version suffixes.
|
||||||
fn version_lte(a: &str, b: &str) -> bool {
|
fn version_lte(a: &str, b: &str) -> bool {
|
||||||
let parse = |v: &str| -> Vec<u64> {
|
let parse = |v: &str| -> Vec<u64> {
|
||||||
v.trim_start_matches('v')
|
v.trim_start_matches('v')
|
||||||
|
.split(['-', '+'])
|
||||||
|
.next()
|
||||||
|
.unwrap_or("0")
|
||||||
.split('.')
|
.split('.')
|
||||||
.filter_map(|part| {
|
.filter_map(|part| part.parse::<u64>().ok())
|
||||||
let numeric = part.split('-').next().unwrap_or("0");
|
|
||||||
numeric.parse::<u64>().ok()
|
|
||||||
})
|
|
||||||
.collect()
|
.collect()
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -144,7 +152,7 @@ impl SilentUpdater {
|
|||||||
|
|
||||||
let cached_version = &meta.version;
|
let cached_version = &meta.version;
|
||||||
|
|
||||||
if version_lte(cached_version, current_version) {
|
if !is_build_to_stable(current_version, cached_version) && version_lte(cached_version, current_version) {
|
||||||
logging!(
|
logging!(
|
||||||
info,
|
info,
|
||||||
Type::System,
|
Type::System,
|
||||||
@@ -176,7 +184,7 @@ impl SilentUpdater {
|
|||||||
logging!(
|
logging!(
|
||||||
warn,
|
warn,
|
||||||
Type::System,
|
Type::System,
|
||||||
"Failed to read cached update bytes: {e}, cleaning up"
|
"Failed to read cached update bytes: {e:#}, cleaning up"
|
||||||
);
|
);
|
||||||
Self::delete_cache();
|
Self::delete_cache();
|
||||||
return false;
|
return false;
|
||||||
@@ -373,12 +381,14 @@ impl SilentUpdater {
|
|||||||
|
|
||||||
// The new webview may not accept evaluation immediately.
|
// The new webview may not accept evaluation immediately.
|
||||||
std::thread::spawn(move || {
|
std::thread::spawn(move || {
|
||||||
for i in 0..10 {
|
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
|
||||||
std::thread::sleep(std::time::Duration::from_millis(100 * (i + 1)));
|
let _ = retry_sync(
|
||||||
if window.eval(&js).is_ok() {
|
RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(9), std::time::Duration::ZERO),
|
||||||
return;
|
|index| {
|
||||||
}
|
std::thread::sleep(std::time::Duration::from_millis(100 * (index as u64 + 1)));
|
||||||
}
|
window.eval(&js).map_err(RetryError::Retry)
|
||||||
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
logging!(info, Type::System, "Update splash window shown");
|
logging!(info, Type::System, "Update splash window shown");
|
||||||
@@ -432,8 +442,8 @@ impl SilentUpdater {
|
|||||||
Type::System,
|
Type::System,
|
||||||
"Silent updater: breaking change detected in v{version}, notifying frontend"
|
"Silent updater: breaking change detected in v{version}, notifying frontend"
|
||||||
);
|
);
|
||||||
super::handle::Handle::notice_message(
|
super::handle::Handle::notice(
|
||||||
"info",
|
super::notify::NoticeStatus::Info,
|
||||||
format!("New version v{version} contains breaking changes. Please update manually."),
|
format!("New version v{version} contains breaking changes. Please update manually."),
|
||||||
);
|
);
|
||||||
return Ok(());
|
return Ok(());
|
||||||
@@ -456,12 +466,9 @@ impl SilentUpdater {
|
|||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if let Err(e) = Self::write_cache(&bytes, &version) {
|
if let Err(e) = Self::write_cache(&bytes, &version) {
|
||||||
logging!(warn, Type::System, "Silent updater: failed to write cache: {e}");
|
logging!(warn, Type::System, "Silent updater: failed to write cache: {e:#}");
|
||||||
}
|
}
|
||||||
|
|
||||||
*self.pending_bytes.write() = Some(bytes);
|
|
||||||
*self.pending_update.write() = Some(update);
|
|
||||||
*self.pending_version.write() = Some(version.clone());
|
|
||||||
self.update_ready.store(true, Ordering::Release);
|
self.update_ready.store(true, Ordering::Release);
|
||||||
|
|
||||||
logging!(
|
logging!(
|
||||||
@@ -473,6 +480,7 @@ impl SilentUpdater {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start_background_check(&self, app_handle: tauri::AppHandle) {
|
pub async fn start_background_check(&self, app_handle: tauri::AppHandle) {
|
||||||
|
// Permanent watcher: daily update cycles for the lifetime of the app.
|
||||||
logging!(info, Type::System, "Silent updater: background task started");
|
logging!(info, Type::System, "Silent updater: background task started");
|
||||||
|
|
||||||
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
|
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ impl CoreConfigValidator {
|
|||||||
Ok(content) => content,
|
Ok(content) => content,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let error_msg: String = format!("Failed to read file: {err}").into();
|
let error_msg: String = format!("Failed to read file: {err}").into();
|
||||||
logging!(error, Type::Validate, "无法读取文件: {}", error_msg);
|
logging!(error, Type::Validate, "Failed to read file {config_path}: {err}");
|
||||||
return Ok(ValidationOutcome::invalid_from_message(error_msg));
|
return Ok(ValidationOutcome::invalid_from_message(error_msg));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -238,7 +238,7 @@ impl CoreConfigValidator {
|
|||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let error_msg: String = format!("YAML syntax error: {err}").into();
|
let error_msg: String = format!("YAML syntax error: {err}").into();
|
||||||
logging!(error, Type::Validate, "YAML语法错误: {}", error_msg);
|
logging!(error, Type::Validate, "YAML syntax error in {config_path}: {err}");
|
||||||
Ok(ValidationOutcome::invalid_from_message(error_msg))
|
Ok(ValidationOutcome::invalid_from_message(error_msg))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -249,7 +249,7 @@ impl CoreConfigValidator {
|
|||||||
Ok(content) => content,
|
Ok(content) => content,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let error_msg: String = format!("Failed to read script file: {err}").into();
|
let error_msg: String = format!("Failed to read script file: {err}").into();
|
||||||
logging!(warn, Type::Validate, "脚本语法错误: {}", err);
|
logging!(warn, Type::Validate, "Failed to read script file {path}: {err}");
|
||||||
return Ok(ValidationOutcome::invalid_from_message(error_msg));
|
return Ok(ValidationOutcome::invalid_from_message(error_msg));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -291,7 +291,7 @@ impl CoreConfigValidator {
|
|||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
let error_msg: String = format!("Script syntax error: {err}").into();
|
let error_msg: String = format!("Script syntax error: {err}").into();
|
||||||
logging!(warn, Type::Validate, "脚本语法错误: {}", err);
|
logging!(warn, Type::Validate, "Script syntax error in {path}: {err}");
|
||||||
Ok(ValidationOutcome::invalid_from_message(error_msg))
|
Ok(ValidationOutcome::invalid_from_message(error_msg))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
use clash_verge_logging::{Type, logging};
|
|
||||||
|
|
||||||
use super::field::use_lowercase;
|
use super::field::use_lowercase;
|
||||||
use serde_yaml_ng::{self, Mapping, Value};
|
use serde_yaml_ng::{self, Mapping, Value};
|
||||||
|
|
||||||
@@ -18,20 +16,19 @@ fn deep_merge(a: &mut Value, b: Value) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn use_merge(merge: &Mapping, config: Mapping) -> Mapping {
|
pub fn use_merge(merge: &Mapping, mut config: Mapping) -> Mapping {
|
||||||
let mut config = Value::from(config);
|
for (key, value) in use_lowercase(merge) {
|
||||||
let merge = use_lowercase(merge);
|
match (config.get_mut(&key), value) {
|
||||||
|
(Some(Value::Mapping(existing)), Value::Mapping(overlay)) if key.as_str() == Some("dns") => {
|
||||||
deep_merge(&mut config, Value::from(merge));
|
existing.extend(overlay);
|
||||||
|
}
|
||||||
config.as_mapping().cloned().unwrap_or_else(|| {
|
(Some(existing), value) if key.as_str() != Some("hosts") => deep_merge(existing, value),
|
||||||
logging!(
|
(_, value) => {
|
||||||
error,
|
config.insert(key, value);
|
||||||
Type::Core,
|
}
|
||||||
"Failed to convert merged config to mapping, using empty mapping"
|
}
|
||||||
);
|
}
|
||||||
Mapping::new()
|
config
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -54,18 +51,49 @@ fn test_merge() -> anyhow::Result<()> {
|
|||||||
enable: true
|
enable: true
|
||||||
dns:
|
dns:
|
||||||
enable: true
|
enable: true
|
||||||
|
nameserver-policy:
|
||||||
|
new.example: 1.1.1.1
|
||||||
|
fallback-filter:
|
||||||
|
geoip: false
|
||||||
|
hosts:
|
||||||
|
new.example: 192.0.2.2
|
||||||
";
|
";
|
||||||
|
|
||||||
let config = r"
|
let config = r"
|
||||||
rules:
|
rules:
|
||||||
- aaaaa
|
- aaaaa
|
||||||
script1: test
|
script1: test
|
||||||
|
tun:
|
||||||
|
mtu: 1500
|
||||||
|
dns:
|
||||||
|
nameserver: [9.9.9.9]
|
||||||
|
nameserver-policy:
|
||||||
|
old.example: 8.8.8.8
|
||||||
|
fallback-filter:
|
||||||
|
geoip: true
|
||||||
|
domain: [old.example]
|
||||||
|
hosts:
|
||||||
|
old.example: 192.0.2.1
|
||||||
";
|
";
|
||||||
|
|
||||||
let merge = serde_yaml_ng::from_str::<Mapping>(merge)?;
|
let merge = serde_yaml_ng::from_str::<Mapping>(merge)?;
|
||||||
let config = serde_yaml_ng::from_str::<Mapping>(config)?;
|
let config = serde_yaml_ng::from_str::<Mapping>(config)?;
|
||||||
|
|
||||||
let _ = serde_yaml_ng::to_string(&use_merge(&merge, config))?;
|
let result = use_merge(&merge, config);
|
||||||
|
assert_eq!(result["dns"]["nameserver-policy"], merge["dns"]["nameserver-policy"]);
|
||||||
|
assert_eq!(result["dns"]["fallback-filter"], merge["dns"]["fallback-filter"]);
|
||||||
|
assert_eq!(result["hosts"], merge["hosts"]);
|
||||||
|
assert_eq!(result["dns"]["nameserver"], serde_yaml_ng::to_value(["9.9.9.9"])?);
|
||||||
|
assert_eq!(result["tun"]["mtu"], Value::from(1500));
|
||||||
|
assert_eq!(result["rules"], merge["rules"]);
|
||||||
|
assert_eq!(result["script1"], Value::from("test"));
|
||||||
|
|
||||||
|
let cleared = serde_yaml_ng::from_str::<Mapping>(
|
||||||
|
"dns: {enable: false, nameserver-policy: {}, fallback-filter: {}, nameserver: []}\nhosts: {}",
|
||||||
|
)?;
|
||||||
|
let result = use_merge(&cleared, result);
|
||||||
|
assert_eq!(result["dns"], cleared["dns"]);
|
||||||
|
assert_eq!(result["hosts"], cleared["hosts"]);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+323
-97
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
mod chain;
|
mod chain;
|
||||||
pub mod field;
|
pub mod field;
|
||||||
mod merge;
|
mod merge;
|
||||||
@@ -14,6 +15,7 @@ use self::{
|
|||||||
tun::use_tun,
|
tun::use_tun,
|
||||||
};
|
};
|
||||||
use crate::config::dns::{DnsOverrideState, dns_override_source};
|
use crate::config::dns::{DnsOverrideState, dns_override_source};
|
||||||
|
use crate::core::handle::Handle;
|
||||||
use crate::utils::dirs;
|
use crate::utils::dirs;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IProfiles, IVerge, PrfItem},
|
config::{Config, IProfiles, IVerge, PrfItem},
|
||||||
@@ -22,6 +24,7 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use anyhow::{Context as _, Result};
|
use anyhow::{Context as _, Result};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
|
use parking_lot::Mutex;
|
||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
@@ -103,7 +106,7 @@ async fn chain_item_or_default(item: Option<&PrfItem>, default_item: impl FnOnce
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_config_values() -> ConfigValues {
|
async fn get_config_values(profile_uid: &str) -> ConfigValues {
|
||||||
let clash = Config::clash().await;
|
let clash = Config::clash().await;
|
||||||
let clash_arc = clash.latest_arc();
|
let clash_arc = clash.latest_arc();
|
||||||
let clash_config = clash_arc.0.clone();
|
let clash_config = clash_arc.0.clone();
|
||||||
@@ -118,12 +121,12 @@ async fn get_config_values() -> ConfigValues {
|
|||||||
ref enable_builtin_enhanced,
|
ref enable_builtin_enhanced,
|
||||||
ref verge_socks_enabled,
|
ref verge_socks_enabled,
|
||||||
ref verge_http_enabled,
|
ref verge_http_enabled,
|
||||||
ref enable_dns_settings,
|
|
||||||
ref enable_external_controller,
|
ref enable_external_controller,
|
||||||
..
|
..
|
||||||
} = **verge_arc;
|
} = **verge_arc;
|
||||||
let enable_external_controller = enable_external_controller.unwrap_or(false);
|
let enable_external_controller = enable_external_controller.unwrap_or(false);
|
||||||
let dns_override_confirmation = verge_arc.dns_override_confirmation.clone();
|
let dns_settings = verge_arc.dns_settings_for(profile_uid);
|
||||||
|
let dns_override_confirmation = dns_settings.confirmation;
|
||||||
|
|
||||||
let (clash_core, enable_tun, enable_builtin, socks_enabled, http_enabled, enable_dns_settings) = (
|
let (clash_core, enable_tun, enable_builtin, socks_enabled, http_enabled, enable_dns_settings) = (
|
||||||
Some(verge_arc.get_valid_clash_core()),
|
Some(verge_arc.get_valid_clash_core()),
|
||||||
@@ -131,7 +134,7 @@ async fn get_config_values() -> ConfigValues {
|
|||||||
enable_builtin_enhanced.unwrap_or(true),
|
enable_builtin_enhanced.unwrap_or(true),
|
||||||
verge_socks_enabled.unwrap_or(false),
|
verge_socks_enabled.unwrap_or(false),
|
||||||
verge_http_enabled.unwrap_or(false),
|
verge_http_enabled.unwrap_or(false),
|
||||||
enable_dns_settings.unwrap_or(false),
|
dns_settings.enabled,
|
||||||
);
|
);
|
||||||
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
#[cfg(not(target_os = "windows"))]
|
||||||
@@ -247,16 +250,33 @@ async fn process_global_items(
|
|||||||
global_merge: ChainItem,
|
global_merge: ChainItem,
|
||||||
global_script: ChainItem,
|
global_script: ChainItem,
|
||||||
profile_name: &String,
|
profile_name: &String,
|
||||||
|
authoritative: &AuthoritativeFields,
|
||||||
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
||||||
if let ChainType::Merge(merge) = global_merge.data {
|
if let ChainType::Merge(merge) = global_merge.data {
|
||||||
exists_keys.extend(use_keys(&merge));
|
exists_keys.extend(use_keys(&merge));
|
||||||
|
let before = authoritative.current(&config);
|
||||||
config = use_merge(&merge, config);
|
config = use_merge(&merge, config);
|
||||||
|
let notes: ResultLog = authoritative
|
||||||
|
.overridden(&before, &authoritative.current(&config))
|
||||||
|
.into_iter()
|
||||||
|
.map(discarded_note)
|
||||||
|
.collect();
|
||||||
|
if !notes.is_empty() {
|
||||||
|
result_map.entry(global_merge.uid).or_default().extend(notes);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let ChainType::Script(script) = global_script.data {
|
if let ChainType::Script(script) = global_script.data {
|
||||||
let (res_config, changed_keys, logs) = use_script(script, config, profile_name.clone()).await;
|
let before = authoritative.current(&config);
|
||||||
|
let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.clone()).await;
|
||||||
exists_keys.extend(changed_keys);
|
exists_keys.extend(changed_keys);
|
||||||
config = res_config;
|
config = res_config;
|
||||||
|
logs.extend(
|
||||||
|
authoritative
|
||||||
|
.overridden(&before, &authoritative.current(&config))
|
||||||
|
.into_iter()
|
||||||
|
.map(discarded_note),
|
||||||
|
);
|
||||||
result_map.insert(global_script.uid, logs);
|
result_map.insert(global_script.uid, logs);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,8 +304,7 @@ fn process_seq_items(
|
|||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
/// App 权威的顶层控制面键:核心连接、监听端口、UI/托盘开关。
|
/// App-owned control-plane keys; DNS settings are captured separately.
|
||||||
/// 平台键随 cfg 门控;`dns.ipv6` 单独处理。
|
|
||||||
const CONTROL_PLANE_KEYS: &[&str] = &[
|
const CONTROL_PLANE_KEYS: &[&str] = &[
|
||||||
"external-controller",
|
"external-controller",
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
@@ -308,32 +327,117 @@ const CONTROL_PLANE_KEYS: &[&str] = &[
|
|||||||
"unified-delay",
|
"unified-delay",
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The fields the app owns, held across the stages that apply the user's manual overrides.
|
/// App-owned fields: captured after the app derives them, enforced after every override.
|
||||||
///
|
|
||||||
/// Capturing and restoring are one value rather than two calls because the order is a
|
|
||||||
/// correctness requirement, not a style: capture must happen after the app has finished
|
|
||||||
/// deriving these fields and before any override runs, and restore must happen after every
|
|
||||||
/// override. As four separate calls that contract lived only in comments.
|
|
||||||
struct AuthoritativeFields {
|
struct AuthoritativeFields {
|
||||||
control_plane: Mapping,
|
control_plane: Mapping,
|
||||||
tun: Mapping,
|
tun: Mapping,
|
||||||
/// Only tracked when the DNS page owns it; otherwise overrides may set `dns.ipv6` freely.
|
dns: Mapping,
|
||||||
dns_ipv6: Option<Value>,
|
hosts: Option<Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AuthoritativeFields {
|
impl AuthoritativeFields {
|
||||||
fn capture(config: &Mapping, gui_tun_keys: &[Value], enable_dns_settings: bool) -> Self {
|
fn capture(config: &Mapping, gui_tun_keys: &[Value], mut dns_settings: Mapping) -> Self {
|
||||||
Self {
|
Self {
|
||||||
control_plane: snapshot_control_plane(config),
|
control_plane: snapshot_control_plane(config),
|
||||||
tun: snapshot_tun(config, gui_tun_keys),
|
tun: snapshot_tun(config, gui_tun_keys),
|
||||||
dns_ipv6: enable_dns_settings.then(|| snapshot_dns_ipv6(config)).flatten(),
|
dns: take_mapping(&mut dns_settings, "dns"),
|
||||||
|
hosts: dns_settings.remove("hosts"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn enforce(self, config: Mapping) -> Mapping {
|
fn enforce(self, config: Mapping) -> Mapping {
|
||||||
let config = enforce_control_plane(config, self.control_plane);
|
let config = enforce_control_plane(config, self.control_plane);
|
||||||
let config = enforce_tun(config, self.tun);
|
let mut config = enforce_tun(config, self.tun);
|
||||||
enforce_dns_ipv6(config, self.dns_ipv6)
|
if !self.dns.is_empty() {
|
||||||
|
let mut dns = take_mapping(&mut config, "dns");
|
||||||
|
dns.extend(self.dns);
|
||||||
|
config.insert("dns".into(), dns.into());
|
||||||
|
}
|
||||||
|
if let Some(hosts) = self.hosts {
|
||||||
|
config.insert("hosts".into(), hosts);
|
||||||
|
}
|
||||||
|
config
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The owned values as `config` holds them now, for diffing one override.
|
||||||
|
fn current(&self, config: &Mapping) -> Self {
|
||||||
|
let tun_keys: Vec<Value> = self.tun.keys().cloned().collect();
|
||||||
|
let dns = config.get("dns").and_then(Value::as_mapping);
|
||||||
|
Self {
|
||||||
|
control_plane: snapshot_control_plane(config),
|
||||||
|
tun: snapshot_tun(config, &tun_keys),
|
||||||
|
dns: self
|
||||||
|
.dns
|
||||||
|
.keys()
|
||||||
|
.filter_map(|key| Some((key.clone(), dns?.get(key)?.clone())))
|
||||||
|
.collect(),
|
||||||
|
hosts: self.hosts.as_ref().and_then(|_| config.get("hosts")).cloned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Owned keys an override moved off the app value; `enforce` discards those writes.
|
||||||
|
fn overridden(&self, before: &Self, after: &Self) -> Vec<String> {
|
||||||
|
let mut keys = Vec::new();
|
||||||
|
for &key in CONTROL_PLANE_KEYS {
|
||||||
|
if before.control_plane.get(key) != after.control_plane.get(key)
|
||||||
|
&& after.control_plane.get(key) != self.control_plane.get(key)
|
||||||
|
{
|
||||||
|
keys.push(key.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key in self.tun.keys() {
|
||||||
|
if before.tun.get(key) != after.tun.get(key) && after.tun.get(key) != self.tun.get(key) {
|
||||||
|
keys.push(format!("tun.{}", key.as_str().unwrap_or_default()).into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for key in self.dns.keys() {
|
||||||
|
if before.dns.get(key) != after.dns.get(key) && after.dns.get(key) != self.dns.get(key) {
|
||||||
|
keys.push(format!("dns.{}", key.as_str().unwrap_or_default()).into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.hosts.is_some() && before.hosts != after.hosts && after.hosts != self.hosts {
|
||||||
|
keys.push("hosts".into());
|
||||||
|
}
|
||||||
|
keys
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn discarded_note(key: String) -> (String, String) {
|
||||||
|
(
|
||||||
|
"warn".into(),
|
||||||
|
format!("`{key}` is managed by Settings; the value written here was discarded").into(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
struct DiscardedKeysNotice {
|
||||||
|
pending: Option<String>,
|
||||||
|
last: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
static DISCARDED_KEYS_NOTICE: Mutex<DiscardedKeysNotice> = Mutex::new(DiscardedKeysNotice {
|
||||||
|
pending: None,
|
||||||
|
last: Vec::new(),
|
||||||
|
});
|
||||||
|
|
||||||
|
pub(crate) fn take_discarded_keys_notice() -> Option<String> {
|
||||||
|
DISCARDED_KEYS_NOTICE.lock().pending.take()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One notice per distinct set, so regenerations with unchanged extensions stay quiet.
|
||||||
|
fn notify_discarded_keys(keys: Vec<String>) {
|
||||||
|
let mut notice = DISCARDED_KEYS_NOTICE.lock();
|
||||||
|
if notice.last == keys {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let should_notify = !keys.is_empty();
|
||||||
|
if should_notify {
|
||||||
|
notice.pending = Some(keys.join(", ").into());
|
||||||
|
}
|
||||||
|
notice.last = keys;
|
||||||
|
drop(notice);
|
||||||
|
|
||||||
|
if should_notify {
|
||||||
|
Handle::notice(NoticeStatus::EnhanceDiscardedKeys, "");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -401,21 +505,6 @@ fn enforce_tun(mut config: Mapping, snapshot: Mapping) -> Mapping {
|
|||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
/// DNS 页权威的嵌套开关;只在 `enable_dns_settings` 时快照。
|
|
||||||
fn snapshot_dns_ipv6(config: &Mapping) -> Option<Value> {
|
|
||||||
config.get("dns")?.get("ipv6").cloned()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 恢复 `dns.ipv6`,但不创建缺失的 `dns` 块。
|
|
||||||
fn enforce_dns_ipv6(mut config: Mapping, dns_ipv6: Option<Value>) -> Mapping {
|
|
||||||
if let Some(dns_ipv6) = dns_ipv6
|
|
||||||
&& let Some(Value::Mapping(dns)) = config.get_mut("dns")
|
|
||||||
{
|
|
||||||
dns.insert(Value::from("ipv6"), dns_ipv6);
|
|
||||||
}
|
|
||||||
config
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_loopback_bind_address(addr: &str) -> bool {
|
fn is_loopback_bind_address(addr: &str) -> bool {
|
||||||
let addr = addr.trim();
|
let addr = addr.trim();
|
||||||
let addr = addr
|
let addr = addr
|
||||||
@@ -465,27 +554,40 @@ async fn process_profile_items(
|
|||||||
merge_item: ChainItem,
|
merge_item: ChainItem,
|
||||||
script_item: ChainItem,
|
script_item: ChainItem,
|
||||||
profile_name: &String,
|
profile_name: &String,
|
||||||
|
authoritative: &AuthoritativeFields,
|
||||||
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
) -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
||||||
if let ChainType::Merge(merge) = merge_item.data {
|
if let ChainType::Merge(merge) = merge_item.data {
|
||||||
exists_keys.extend(use_keys(&merge));
|
exists_keys.extend(use_keys(&merge));
|
||||||
|
let before = authoritative.current(&config);
|
||||||
config = use_merge(&merge, config);
|
config = use_merge(&merge, config);
|
||||||
|
let notes: ResultLog = authoritative
|
||||||
|
.overridden(&before, &authoritative.current(&config))
|
||||||
|
.into_iter()
|
||||||
|
.map(discarded_note)
|
||||||
|
.collect();
|
||||||
|
if !notes.is_empty() {
|
||||||
|
result_map.entry(merge_item.uid).or_default().extend(notes);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let ChainType::Script(script) = script_item.data {
|
if let ChainType::Script(script) = script_item.data {
|
||||||
let (res_config, changed_keys, logs) = use_script(script, config, profile_name.clone()).await;
|
let before = authoritative.current(&config);
|
||||||
|
let (res_config, changed_keys, mut logs) = use_script(script, config, profile_name.clone()).await;
|
||||||
exists_keys.extend(changed_keys);
|
exists_keys.extend(changed_keys);
|
||||||
config = res_config;
|
config = res_config;
|
||||||
|
logs.extend(
|
||||||
|
authoritative
|
||||||
|
.overridden(&before, &authoritative.current(&config))
|
||||||
|
.into_iter()
|
||||||
|
.map(discarded_note),
|
||||||
|
);
|
||||||
result_map.insert(script_item.uid, logs);
|
result_map.insert(script_item.uid, logs);
|
||||||
}
|
}
|
||||||
|
|
||||||
(config, exists_keys, result_map)
|
(config, exists_keys, result_map)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Merge the Application Merge Config over the profile's own configuration.
|
/// Merges the app's clash config over the profile; switches are parameters to keep it pure.
|
||||||
///
|
|
||||||
/// Every switch it consults is a parameter: it used to read `enable_external_controller`
|
|
||||||
/// out of the global config from inside its loop, which made a stage that looks pure depend
|
|
||||||
/// on process state and left it untestable.
|
|
||||||
fn merge_default_config(
|
fn merge_default_config(
|
||||||
mut config: Mapping,
|
mut config: Mapping,
|
||||||
clash_config: Mapping,
|
clash_config: Mapping,
|
||||||
@@ -683,9 +785,7 @@ fn cleanup_proxy_groups(mut config: Mapping) -> Mapping {
|
|||||||
config
|
config
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 当 DNS 处于 fake-ip 模式且启用 IPv6 时,补充缺失的 `fake-ip-range6`,
|
/// fake-ip + IPv6 缺少 `fake-ip-range6` 时补默认值,否则 AAAA 无法解析(#7373)。
|
||||||
/// 否则 AAAA 查询无法获得 fake-ip,导致 IPv6 解析失败(见 issue #7373)。
|
|
||||||
/// 兼容旧版本生成的、缺少该字段的 dns_config.yaml。
|
|
||||||
fn ensure_fake_ip_range6(dns: &mut Mapping) {
|
fn ensure_fake_ip_range6(dns: &mut Mapping) {
|
||||||
use serde_yaml_ng::Value;
|
use serde_yaml_ng::Value;
|
||||||
|
|
||||||
@@ -708,45 +808,78 @@ fn ensure_fake_ip_range6(dns: &mut Mapping) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn apply_dns_settings(mut config: Mapping, enable_dns_settings: bool) -> Mapping {
|
/// On, non-blank text, or non-empty list/map; anything else keeps the profile's value.
|
||||||
|
fn is_set(value: &Value) -> bool {
|
||||||
|
match value {
|
||||||
|
Value::Null => false,
|
||||||
|
Value::Bool(on) => *on,
|
||||||
|
Value::String(text) => !text.trim().is_empty(),
|
||||||
|
Value::Sequence(items) => !items.is_empty(),
|
||||||
|
Value::Mapping(map) => !map.is_empty(),
|
||||||
|
Value::Number(_) | Value::Tagged(_) => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take_mapping(config: &mut Mapping, key: &str) -> Mapping {
|
||||||
|
config
|
||||||
|
.get_mut(key)
|
||||||
|
.and_then(Value::as_mapping_mut)
|
||||||
|
.map(std::mem::take)
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn merge_dns_config(mut config: Mapping, mut dns_config: Mapping) -> (Mapping, Mapping) {
|
||||||
|
let mut applied = Mapping::new();
|
||||||
|
if let Some(Value::Mapping(hosts)) = dns_config.remove("hosts")
|
||||||
|
&& !hosts.is_empty()
|
||||||
|
{
|
||||||
|
applied.insert("hosts".into(), hosts.clone().into());
|
||||||
|
config.insert("hosts".into(), hosts.into());
|
||||||
|
logging!(debug, Type::Core, "apply hosts configuration");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Legacy layout: no `dns` root.
|
||||||
|
let dns_override = match dns_config.remove("dns") {
|
||||||
|
Some(Value::Mapping(dns)) => Some(dns),
|
||||||
|
Some(_) => None,
|
||||||
|
None => Some(dns_config),
|
||||||
|
};
|
||||||
|
if let Some(mut dns_override) = dns_override {
|
||||||
|
dns_override.retain(|_, value| is_set(value));
|
||||||
|
if !dns_override.is_empty() {
|
||||||
|
applied.insert("dns".into(), dns_override.clone().into());
|
||||||
|
}
|
||||||
|
let mut dns = take_mapping(&mut config, "dns");
|
||||||
|
dns.extend(dns_override);
|
||||||
|
ensure_fake_ip_range6(&mut dns);
|
||||||
|
config.insert("dns".into(), dns.into());
|
||||||
|
logging!(debug, Type::Core, "apply dns_config.yaml");
|
||||||
|
}
|
||||||
|
(config, applied)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the merged config and the non-empty fields owned by the DNS page.
|
||||||
|
async fn apply_dns_settings(config: Mapping, enable_dns_settings: bool) -> (Mapping, Mapping) {
|
||||||
if enable_dns_settings && let Ok(app_dir) = dirs::app_home_dir() {
|
if enable_dns_settings && let Ok(app_dir) = dirs::app_home_dir() {
|
||||||
let dns_path = app_dir.join(constants::files::DNS_CONFIG);
|
let dns_path = app_dir.join(constants::files::DNS_CONFIG);
|
||||||
|
|
||||||
if dns_path.exists()
|
if dns_path.exists()
|
||||||
&& let Ok(dns_yaml) = fs::read_to_string(&dns_path).await
|
&& let Ok(dns_yaml) = fs::read_to_string(&dns_path).await
|
||||||
&& let Ok(dns_config) = serde_yaml_ng::from_str::<serde_yaml_ng::Mapping>(&dns_yaml)
|
&& let Ok(dns_config) = serde_yaml_ng::from_str::<Mapping>(&dns_yaml)
|
||||||
{
|
{
|
||||||
if let Some(hosts_value) = dns_config.get("hosts")
|
return merge_dns_config(config, dns_config);
|
||||||
&& hosts_value.is_mapping()
|
|
||||||
{
|
|
||||||
config.insert("hosts".into(), hosts_value.clone());
|
|
||||||
logging!(debug, Type::Core, "apply hosts configuration");
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(dns_value) = dns_config.get("dns") {
|
|
||||||
if let Some(dns_mapping) = dns_value.as_mapping() {
|
|
||||||
let mut dns_mapping = dns_mapping.clone();
|
|
||||||
ensure_fake_ip_range6(&mut dns_mapping);
|
|
||||||
config.insert("dns".into(), dns_mapping.into());
|
|
||||||
logging!(debug, Type::Core, "apply dns_config.yaml (dns section)");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let mut dns_config = dns_config;
|
|
||||||
ensure_fake_ip_range6(&mut dns_config);
|
|
||||||
config.insert("dns".into(), dns_config.into());
|
|
||||||
logging!(debug, Type::Core, "apply dns_config.yaml");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
config
|
(config, Mapping::new())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
|
/// Returns the enhanced profile, its original keys, script logs, and DNS override decision.
|
||||||
pub async fn enhance(
|
pub async fn enhance(
|
||||||
profiles: &IProfiles,
|
profiles: &IProfiles,
|
||||||
) -> Result<(Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState)> {
|
) -> Result<(Mapping, HashSet<String>, HashMap<String, ResultLog>, DnsOverrideState)> {
|
||||||
let cfg_vals = get_config_values().await;
|
let profile_uid = profiles.current.as_deref().unwrap_or_default();
|
||||||
|
let cfg_vals = get_config_values(profile_uid).await;
|
||||||
let ConfigValues {
|
let ConfigValues {
|
||||||
clash_config,
|
clash_config,
|
||||||
clash_core,
|
clash_core,
|
||||||
@@ -765,7 +898,8 @@ pub async fn enhance(
|
|||||||
|
|
||||||
let profile = collect_profile_items(profiles).await?;
|
let profile = collect_profile_items(profiles).await?;
|
||||||
let dns_override = DnsOverrideState::new(
|
let dns_override = DnsOverrideState::new(
|
||||||
dns_override_source(profiles.current.as_deref().unwrap_or_default(), &profile.config)?,
|
profile_uid,
|
||||||
|
dns_override_source(profile_uid, &profile.config)?,
|
||||||
enable_dns_settings,
|
enable_dns_settings,
|
||||||
dns_override_confirmation,
|
dns_override_confirmation,
|
||||||
);
|
);
|
||||||
@@ -800,9 +934,9 @@ pub async fn enhance(
|
|||||||
|
|
||||||
let config = apply_builtin_scripts(config, clash_core, enable_builtin);
|
let config = apply_builtin_scripts(config, clash_core, enable_builtin);
|
||||||
let config = use_tun(config, enable_tun);
|
let config = use_tun(config, enable_tun);
|
||||||
let config = apply_dns_settings(config, enable_dns_settings).await;
|
let (config, dns_settings) = apply_dns_settings(config, enable_dns_settings).await;
|
||||||
|
|
||||||
let authoritative = AuthoritativeFields::capture(&config, &gui_tun_keys, enable_dns_settings);
|
let authoritative = AuthoritativeFields::capture(&config, &gui_tun_keys, dns_settings);
|
||||||
|
|
||||||
let (config, exists_keys, result_map) = process_global_items(
|
let (config, exists_keys, result_map) = process_global_items(
|
||||||
config,
|
config,
|
||||||
@@ -811,12 +945,22 @@ pub async fn enhance(
|
|||||||
global_merge,
|
global_merge,
|
||||||
global_script,
|
global_script,
|
||||||
&profile_name,
|
&profile_name,
|
||||||
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let (config, exists_keys, result_map) =
|
let (config, exists_keys, result_map) = process_profile_items(
|
||||||
process_profile_items(config, exists_keys, result_map, merge_item, script_item, &profile_name).await;
|
config,
|
||||||
|
exists_keys,
|
||||||
|
result_map,
|
||||||
|
merge_item,
|
||||||
|
script_item,
|
||||||
|
&profile_name,
|
||||||
|
&authoritative,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
notify_discarded_keys(authoritative.overridden(&authoritative, &authoritative.current(&config)));
|
||||||
let config = authoritative.enforce(config);
|
let config = authoritative.enforce(config);
|
||||||
let config = ensure_lan_bind_address(config);
|
let config = ensure_lan_bind_address(config);
|
||||||
|
|
||||||
@@ -864,8 +1008,7 @@ mod fake_ip_tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_hand_edited_empty_range_counts_as_missing() {
|
fn a_hand_edited_empty_range_counts_as_missing() {
|
||||||
// The reason this is not just a `contains_key` check: YAML edited by hand often
|
// Hand-edited YAML may leave the key present but empty.
|
||||||
// leaves the key present with nothing after the colon.
|
|
||||||
for blank in ["", " "] {
|
for blank in ["", " "] {
|
||||||
let mut config = dns(&[
|
let mut config = dns(&[
|
||||||
("ipv6", Value::from(true)),
|
("ipv6", Value::from(true)),
|
||||||
@@ -1004,8 +1147,7 @@ mod use_tun_tests {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn switching_tun_off_leaves_dns_untouched() {
|
async fn switching_tun_off_leaves_dns_untouched() {
|
||||||
// Turning TUN off must not rewrite DNS the user or profile chose; only the system
|
// TUN off must not rewrite the DNS the profile chose.
|
||||||
// resolver is restored, which is not part of the configuration.
|
|
||||||
let config = mapping(&[("dns", Value::Mapping(mapping(&[("enable", Value::from(false))])))]);
|
let config = mapping(&[("dns", Value::Mapping(mapping(&[("enable", Value::from(false))])))]);
|
||||||
|
|
||||||
let result = use_tun(config, false);
|
let result = use_tun(config, false);
|
||||||
@@ -1038,8 +1180,7 @@ mod use_sort_tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_bulky_list_fields_are_written_last() {
|
fn the_bulky_list_fields_are_written_last() {
|
||||||
// These are the fields that make a config file unreadable from the top, so they are
|
// Bulky list fields go last so the top of the file stays readable.
|
||||||
// pushed below the settings a human actually scans for.
|
|
||||||
let mut config = Mapping::new();
|
let mut config = Mapping::new();
|
||||||
config.insert(Value::from("rules"), Value::from("rules"));
|
config.insert(Value::from("rules"), Value::from("rules"));
|
||||||
config.insert(Value::from("mode"), Value::from("rule"));
|
config.insert(Value::from("mode"), Value::from("rule"));
|
||||||
@@ -1129,8 +1270,7 @@ mod merge_default_config_tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_disabled_listener_is_removed_rather_than_merged() {
|
fn a_disabled_listener_is_removed_rather_than_merged() {
|
||||||
// Removed, not just skipped: the profile may have asked for the port itself, and a
|
// Removed, not skipped: the profile's own value must not reopen a disabled listener.
|
||||||
// listener the user switched off must not be opened by the profile's own value.
|
|
||||||
let config = mapping(&[("socks-port", Value::from(7891)), ("port", Value::from(7890))]);
|
let config = mapping(&[("socks-port", Value::from(7891)), ("port", Value::from(7890))]);
|
||||||
let clash_config = mapping(&[("socks-port", Value::from(1080)), ("port", Value::from(8080))]);
|
let clash_config = mapping(&[("socks-port", Value::from(1080)), ("port", Value::from(8080))]);
|
||||||
|
|
||||||
@@ -1152,8 +1292,7 @@ mod merge_default_config_tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_disabled_external_controller_is_blanked_rather_than_dropped() {
|
fn a_disabled_external_controller_is_blanked_rather_than_dropped() {
|
||||||
// Blanked, not removed: an absent key lets mihomo fall back to its own default and
|
// Blanked, not removed: an absent key makes mihomo listen on its default.
|
||||||
// listen anyway, which is the opposite of what switching it off means.
|
|
||||||
let clash_config = mapping(&[("external-controller", Value::from("127.0.0.1:9090"))]);
|
let clash_config = mapping(&[("external-controller", Value::from("127.0.0.1:9090"))]);
|
||||||
|
|
||||||
let merged = merge(Mapping::new(), clash_config, false);
|
let merged = merge(Mapping::new(), clash_config, false);
|
||||||
@@ -1223,7 +1362,7 @@ mod authoritative_field_tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn an_override_cannot_change_a_field_the_app_owns() {
|
fn an_override_cannot_change_a_field_the_app_owns() {
|
||||||
let derived = config_with(&[("mode", Value::from("rule")), ("secret", Value::from("ours"))]);
|
let derived = config_with(&[("mode", Value::from("rule")), ("secret", Value::from("ours"))]);
|
||||||
let authoritative = AuthoritativeFields::capture(&derived, &[], false);
|
let authoritative = AuthoritativeFields::capture(&derived, &[], Mapping::new());
|
||||||
|
|
||||||
let overridden = config_with(&[("mode", Value::from("global")), ("secret", Value::from("theirs"))]);
|
let overridden = config_with(&[("mode", Value::from("global")), ("secret", Value::from("theirs"))]);
|
||||||
let result = authoritative.enforce(overridden);
|
let result = authoritative.enforce(overridden);
|
||||||
@@ -1236,7 +1375,7 @@ mod authoritative_field_tests {
|
|||||||
fn an_override_cannot_introduce_a_field_the_app_left_out() {
|
fn an_override_cannot_introduce_a_field_the_app_left_out() {
|
||||||
// The app decided not to expose the external controller; a profile must not re-add it.
|
// The app decided not to expose the external controller; a profile must not re-add it.
|
||||||
let derived = Mapping::new();
|
let derived = Mapping::new();
|
||||||
let authoritative = AuthoritativeFields::capture(&derived, &[], false);
|
let authoritative = AuthoritativeFields::capture(&derived, &[], Mapping::new());
|
||||||
|
|
||||||
let overridden = config_with(&[("external-controller", Value::from("0.0.0.0:9090"))]);
|
let overridden = config_with(&[("external-controller", Value::from("0.0.0.0:9090"))]);
|
||||||
let result = authoritative.enforce(overridden);
|
let result = authoritative.enforce(overridden);
|
||||||
@@ -1247,7 +1386,7 @@ mod authoritative_field_tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn fields_the_app_does_not_own_survive_an_override() {
|
fn fields_the_app_does_not_own_survive_an_override() {
|
||||||
let derived = config_with(&[("mode", Value::from("rule"))]);
|
let derived = config_with(&[("mode", Value::from("rule"))]);
|
||||||
let authoritative = AuthoritativeFields::capture(&derived, &[], false);
|
let authoritative = AuthoritativeFields::capture(&derived, &[], Mapping::new());
|
||||||
|
|
||||||
let overridden = config_with(&[("mode", Value::from("global")), ("profile-key", Value::from(1))]);
|
let overridden = config_with(&[("mode", Value::from("global")), ("profile-key", Value::from(1))]);
|
||||||
let result = authoritative.enforce(overridden);
|
let result = authoritative.enforce(overridden);
|
||||||
@@ -1259,7 +1398,7 @@ mod authoritative_field_tests {
|
|||||||
fn dns_ipv6_is_only_reclaimed_when_the_dns_page_owns_it() {
|
fn dns_ipv6_is_only_reclaimed_when_the_dns_page_owns_it() {
|
||||||
let derived = config_with(&[("dns", dns_with_ipv6(true))]);
|
let derived = config_with(&[("dns", dns_with_ipv6(true))]);
|
||||||
|
|
||||||
let owned = AuthoritativeFields::capture(&derived, &[], true);
|
let owned = AuthoritativeFields::capture(&derived, &[], derived.clone());
|
||||||
let restored = owned.enforce(config_with(&[("dns", dns_with_ipv6(false))]));
|
let restored = owned.enforce(config_with(&[("dns", dns_with_ipv6(false))]));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
restored.get(Value::from("dns")).and_then(|dns| dns.get("ipv6")),
|
restored.get(Value::from("dns")).and_then(|dns| dns.get("ipv6")),
|
||||||
@@ -1267,7 +1406,7 @@ mod authoritative_field_tests {
|
|||||||
"with the DNS page on, the app's value wins"
|
"with the DNS page on, the app's value wins"
|
||||||
);
|
);
|
||||||
|
|
||||||
let unowned = AuthoritativeFields::capture(&derived, &[], false);
|
let unowned = AuthoritativeFields::capture(&derived, &[], Mapping::new());
|
||||||
let left_alone = unowned.enforce(config_with(&[("dns", dns_with_ipv6(false))]));
|
let left_alone = unowned.enforce(config_with(&[("dns", dns_with_ipv6(false))]));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
left_alone.get(Value::from("dns")).and_then(|dns| dns.get("ipv6")),
|
left_alone.get(Value::from("dns")).and_then(|dns| dns.get("ipv6")),
|
||||||
@@ -1277,14 +1416,13 @@ mod authoritative_field_tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn restoring_dns_ipv6_never_invents_a_dns_block() {
|
fn restoring_dns_settings_reinstates_a_removed_dns_block() {
|
||||||
let derived = config_with(&[("dns", dns_with_ipv6(true))]);
|
let derived = config_with(&[("dns", dns_with_ipv6(true))]);
|
||||||
let authoritative = AuthoritativeFields::capture(&derived, &[], true);
|
let authoritative = AuthoritativeFields::capture(&derived, &[], derived.clone());
|
||||||
|
|
||||||
// An override removed DNS entirely; reinstating just `ipv6` would be a half-config.
|
|
||||||
let result = authoritative.enforce(Mapping::new());
|
let result = authoritative.enforce(Mapping::new());
|
||||||
|
|
||||||
assert!(!result.contains_key(Value::from("dns")));
|
assert_eq!(result["dns"], derived["dns"]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1292,8 +1430,8 @@ mod authoritative_field_tests {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::{
|
use super::{
|
||||||
ChainItem, ChainType, cleanup_proxy_groups, ensure_lan_bind_address, process_global_items,
|
AuthoritativeFields, ChainItem, ChainType, Mapping, cleanup_proxy_groups, ensure_lan_bind_address,
|
||||||
process_profile_items, use_keys,
|
process_global_items, process_profile_items, use_keys,
|
||||||
};
|
};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
@@ -1301,6 +1439,89 @@ mod tests {
|
|||||||
serde_yaml_ng::from_str(yaml).expect("test config should be valid")
|
serde_yaml_ng::from_str(yaml).expect("test config should be valid")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn dns_settings_override_only_filled_fields_after_merge_and_script() {
|
||||||
|
let profile = mapping(
|
||||||
|
"dns: {nameserver: [9.9.9.9], nameserver-policy: {profile.example: 9.9.9.9}}\n\
|
||||||
|
hosts: {profile.example: 192.0.2.1}",
|
||||||
|
);
|
||||||
|
let settings = mapping(
|
||||||
|
"dns: {ipv6: true, nameserver: [8.8.8.8], nameserver-policy: {settings.example: 8.8.8.8},\n\
|
||||||
|
proxy-server-nameserver: [], fallback: null, listen: ' '}\n\
|
||||||
|
hosts: {settings.example: 192.0.2.2}",
|
||||||
|
);
|
||||||
|
let merge = mapping(
|
||||||
|
"dns: {ipv6: false, nameserver-policy: {merge.example: 1.1.1.1}}\n\
|
||||||
|
hosts: {merge.example: 192.0.2.3}",
|
||||||
|
);
|
||||||
|
let script = r#"function main(config) {
|
||||||
|
config.dns = {
|
||||||
|
ipv6: false,
|
||||||
|
nameserver: ["4.4.4.4"],
|
||||||
|
"nameserver-policy": {"script.example": "4.4.4.4"},
|
||||||
|
"proxy-server-nameserver": ["4.4.4.4"],
|
||||||
|
fallback: ["4.4.4.4"],
|
||||||
|
listen: "127.0.0.1:1053"
|
||||||
|
};
|
||||||
|
config.hosts = {"script.example": "192.0.2.4"};
|
||||||
|
return config;
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
for enabled in [false, true] {
|
||||||
|
let (config, dns_settings) = if enabled {
|
||||||
|
super::merge_dns_config(profile.clone(), settings.clone())
|
||||||
|
} else {
|
||||||
|
(profile.clone(), Mapping::new())
|
||||||
|
};
|
||||||
|
let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings);
|
||||||
|
let merge_item = |uid: &str| ChainItem {
|
||||||
|
uid: uid.into(),
|
||||||
|
data: ChainType::Merge(merge.clone()),
|
||||||
|
};
|
||||||
|
let profile_name = "test-profile".into();
|
||||||
|
let (config, keys, logs) = process_global_items(
|
||||||
|
config,
|
||||||
|
vec![],
|
||||||
|
HashMap::new(),
|
||||||
|
merge_item("global-merge"),
|
||||||
|
ChainItem::to_script("global-script", script),
|
||||||
|
&profile_name,
|
||||||
|
&authoritative,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let (config, _, logs) = process_profile_items(
|
||||||
|
config,
|
||||||
|
keys,
|
||||||
|
logs,
|
||||||
|
merge_item("profile-merge"),
|
||||||
|
ChainItem::to_script("profile-script", script),
|
||||||
|
&profile_name,
|
||||||
|
&authoritative,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let manual = config.clone();
|
||||||
|
let result = authoritative.enforce(config);
|
||||||
|
|
||||||
|
let source = if enabled { &settings } else { &manual };
|
||||||
|
assert_eq!(result["dns"]["nameserver-policy"], source["dns"]["nameserver-policy"]);
|
||||||
|
assert_eq!(result["hosts"], source["hosts"]);
|
||||||
|
assert_eq!(result["dns"]["nameserver"], source["dns"]["nameserver"]);
|
||||||
|
assert_eq!(result["dns"]["ipv6"], serde_yaml_ng::Value::from(enabled));
|
||||||
|
for key in ["proxy-server-nameserver", "fallback", "listen"] {
|
||||||
|
assert_eq!(result["dns"][key], manual["dns"][key]);
|
||||||
|
}
|
||||||
|
if enabled {
|
||||||
|
for uid in ["global-merge", "global-script", "profile-merge", "profile-script"] {
|
||||||
|
assert!(
|
||||||
|
logs[uid]
|
||||||
|
.iter()
|
||||||
|
.any(|(_, message)| message.contains("dns.nameserver-policy"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn manual_overrides_follow_expected_priority() {
|
async fn manual_overrides_follow_expected_priority() {
|
||||||
let mut config = mapping(
|
let mut config = mapping(
|
||||||
@@ -1345,6 +1566,7 @@ mod tests {
|
|||||||
);
|
);
|
||||||
|
|
||||||
let profile_name = "test-profile".into();
|
let profile_name = "test-profile".into();
|
||||||
|
let authoritative = AuthoritativeFields::capture(&config, &[], Mapping::new());
|
||||||
let (config, exists_keys, result_map) = process_global_items(
|
let (config, exists_keys, result_map) = process_global_items(
|
||||||
config,
|
config,
|
||||||
exists_keys,
|
exists_keys,
|
||||||
@@ -1352,6 +1574,7 @@ mod tests {
|
|||||||
global_merge,
|
global_merge,
|
||||||
global_script,
|
global_script,
|
||||||
&profile_name,
|
&profile_name,
|
||||||
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
let (config, exists_keys, _) = process_profile_items(
|
let (config, exists_keys, _) = process_profile_items(
|
||||||
@@ -1361,6 +1584,7 @@ mod tests {
|
|||||||
profile_merge,
|
profile_merge,
|
||||||
profile_script,
|
profile_script,
|
||||||
&profile_name,
|
&profile_name,
|
||||||
|
&authoritative,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
@@ -1498,19 +1722,21 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dns_ipv6_follows_ui_but_other_dns_stays_overridable() {
|
fn empty_dns_settings_leave_inherited_fields_overridable() {
|
||||||
let app_config = mapping(r#"{dns: {ipv6: false, proxy-server-nameserver: ["1.1.1.1"]}}"#);
|
let app_config = mapping(r#"{dns: {ipv6: false, proxy-server-nameserver: ["1.1.1.1"]}}"#);
|
||||||
let dns_ipv6 = super::snapshot_dns_ipv6(&app_config);
|
let (config, dns_settings) =
|
||||||
|
super::merge_dns_config(app_config, mapping("dns: {ipv6: false, proxy-server-nameserver: []}"));
|
||||||
|
let authoritative = AuthoritativeFields::capture(&config, &[], dns_settings);
|
||||||
|
|
||||||
let hijacked = mapping(r#"{dns: {ipv6: true, proxy-server-nameserver: ["8.8.8.8"]}}"#);
|
let hijacked = mapping(r#"{dns: {ipv6: true, proxy-server-nameserver: ["8.8.8.8"]}}"#);
|
||||||
let result = super::enforce_dns_ipv6(hijacked, dns_ipv6);
|
let result = authoritative.enforce(hijacked);
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
result
|
result
|
||||||
.get("dns")
|
.get("dns")
|
||||||
.and_then(|value| value.get("ipv6"))
|
.and_then(|value| value.get("ipv6"))
|
||||||
.and_then(serde_yaml_ng::Value::as_bool),
|
.and_then(serde_yaml_ng::Value::as_bool),
|
||||||
Some(false)
|
Some(true)
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
result
|
result
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
|
use crate::core::notify::{Refresh, announce};
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, MixedPort},
|
config::{Config, MixedPort},
|
||||||
core::{CoreManager, handle, tray},
|
core::{CoreManager, handle, tray},
|
||||||
@@ -7,13 +9,13 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use bytes::BytesMut;
|
use bytes::BytesMut;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
|
||||||
#[allow(clippy::expect_used)]
|
#[allow(clippy::expect_used)]
|
||||||
static TLS_CONFIG: Lazy<Arc<rustls::ClientConfig>> = Lazy::new(|| {
|
static TLS_CONFIG: LazyLock<Arc<rustls::ClientConfig>> = LazyLock::new(|| {
|
||||||
let root_store = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
let root_store = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
|
||||||
let config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
let config = rustls::ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||||
.with_safe_default_protocol_versions()
|
.with_safe_default_protocol_versions()
|
||||||
@@ -26,11 +28,10 @@ static TLS_CONFIG: Lazy<Arc<rustls::ClientConfig>> = Lazy::new(|| {
|
|||||||
pub async fn restart_clash_core() {
|
pub async fn restart_clash_core() {
|
||||||
match CoreManager::global().restart_core().await {
|
match CoreManager::global().restart_core().await {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
handle::Handle::refresh_clash();
|
announce(Refresh::Clash);
|
||||||
handle::Handle::notice_message("set_config::ok", "ok");
|
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
handle::Handle::notice_message("set_config::error", format!("{err:#}"));
|
handle::Handle::notice(NoticeStatus::SetConfigError, format!("{err:#}"));
|
||||||
logging!(error, Type::Core, "restart core failed: {err:#}");
|
logging!(error, Type::Core, "restart core failed: {err:#}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -53,8 +54,8 @@ pub async fn restart_app() {
|
|||||||
|
|
||||||
if !cleanup_result.core_stopped {
|
if !cleanup_result.core_stopped {
|
||||||
handle::Handle::global().clear_is_exiting();
|
handle::Handle::global().clear_is_exiting();
|
||||||
handle::Handle::notice_message(
|
handle::Handle::notice(
|
||||||
"app_restart::core_stop_failed",
|
NoticeStatus::AppRestartCoreStopFailed,
|
||||||
cleanup_result.stop_error.unwrap_or_default(),
|
cleanup_result.stop_error.unwrap_or_default(),
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
@@ -95,7 +96,7 @@ pub async fn change_clash_mode(mode: String) -> Result<(), String> {
|
|||||||
|
|
||||||
let clash_data = clash.data_arc();
|
let clash_data = clash.data_arc();
|
||||||
if clash_data.save_config().await.is_ok() {
|
if clash_data.save_config().await.is_ok() {
|
||||||
handle::Handle::refresh_clash();
|
announce(Refresh::Clash);
|
||||||
tray::Tray::global().update_menu_and_icon().await;
|
tray::Tray::global().update_menu_and_icon().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+19
-295
@@ -1,279 +1,17 @@
|
|||||||
use crate::{
|
use crate::config::{Config, IVerge};
|
||||||
config::{Config, IVerge},
|
|
||||||
core::{CoreManager, autostart, handle, hotkey, logger, proxy_control, tray},
|
|
||||||
module::{auto_backup::AutoBackupManager, lightweight},
|
|
||||||
};
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use bitflags::bitflags;
|
use clash_verge_draft::SharedDraft;
|
||||||
use clash_verge_draft::{DraftTransaction, SharedDraft};
|
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
|
||||||
use serde_yaml_ng::Mapping;
|
use serde_yaml_ng::Mapping;
|
||||||
use tokio::sync::MutexGuard;
|
use tokio::sync::MutexGuard;
|
||||||
|
|
||||||
/// Patch Clash configuration
|
|
||||||
pub async fn patch_clash(patch: &Mapping) -> Result<()> {
|
pub async fn patch_clash(patch: &Mapping) -> Result<()> {
|
||||||
Config::clash().await.edit_draft(|d| d.patch_config(patch));
|
let config_write = Config::try_lock_config_write()?;
|
||||||
|
super::executor::apply(
|
||||||
let res = {
|
&config_write,
|
||||||
// 激活订阅
|
super::executor::Patch::Clash(patch),
|
||||||
if patch.get("secret").is_some() || patch.get("external-controller").is_some() {
|
super::effects::clash_effects(patch),
|
||||||
Config::generate().await?;
|
)
|
||||||
CoreManager::global().restart_core().await?;
|
.await
|
||||||
} else if patch.get("allow-lan").is_some() {
|
|
||||||
CoreManager::global().update_config_checked().await?;
|
|
||||||
} else {
|
|
||||||
if patch.get("mode").is_some() {
|
|
||||||
tray::Tray::global().update_menu_and_icon().await;
|
|
||||||
}
|
|
||||||
CoreManager::global().update_config_checked().await?;
|
|
||||||
}
|
|
||||||
handle::Handle::refresh_clash();
|
|
||||||
<Result<()>>::Ok(())
|
|
||||||
};
|
|
||||||
match res {
|
|
||||||
Ok(()) => {
|
|
||||||
Config::clash().await.apply();
|
|
||||||
// 分离数据获取和异步调用
|
|
||||||
let clash_data = Config::clash().await.data_arc();
|
|
||||||
clash_data.save_config().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
Config::clash().await.discard();
|
|
||||||
Err(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Define update flags as bitflags for better performance
|
|
||||||
bitflags! {
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
struct UpdateFlags: u16 {
|
|
||||||
const RESTART_CORE = 1 << 0;
|
|
||||||
const CLASH_CONFIG = 1 << 1;
|
|
||||||
const VERGE_CONFIG = 1 << 2;
|
|
||||||
const LAUNCH = 1 << 3;
|
|
||||||
const SYS_PROXY = 1 << 4;
|
|
||||||
const SYSTRAY_ICON = 1 << 5;
|
|
||||||
const HOTKEY = 1 << 6;
|
|
||||||
const SYSTRAY_MENU = 1 << 7;
|
|
||||||
const SYSTRAY_TOOLTIP = 1 << 8;
|
|
||||||
const SYSTRAY_CLICK_BEHAVIOR = 1 << 9;
|
|
||||||
const LIGHT_WEIGHT = 1 << 10;
|
|
||||||
const LANGUAGE = 1 << 11;
|
|
||||||
const LOG_LEVEL = 1 << 12;
|
|
||||||
const LOG_FILE = 1 << 13;
|
|
||||||
|
|
||||||
const GROUP_SYS_TRAY = Self::SYSTRAY_MENU.bits()
|
|
||||||
| Self::SYSTRAY_TOOLTIP.bits()
|
|
||||||
| Self::SYSTRAY_ICON.bits();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn determine_update_flags(patch: &IVerge) -> UpdateFlags {
|
|
||||||
let tun_mode = patch.enable_tun_mode;
|
|
||||||
let auto_launch = patch.enable_auto_launch;
|
|
||||||
let system_proxy = patch.enable_system_proxy;
|
|
||||||
let pac = patch.proxy_auto_config;
|
|
||||||
let pac_content = &patch.pac_file_content;
|
|
||||||
let proxy_bypass = &patch.system_proxy_bypass;
|
|
||||||
let language = &patch.language;
|
|
||||||
let mixed_port = patch.verge_mixed_port;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
let tray_icon = &patch.tray_icon;
|
|
||||||
#[cfg(not(target_os = "macos"))]
|
|
||||||
let tray_icon: Option<String> = None;
|
|
||||||
let common_tray_icon = patch.common_tray_icon;
|
|
||||||
let sysproxy_tray_icon = patch.sysproxy_tray_icon;
|
|
||||||
let tun_tray_icon = patch.tun_tray_icon;
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
let redir_enabled = patch.verge_redir_enabled;
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
let redir_port = patch.verge_redir_port;
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
let tproxy_enabled = patch.verge_tproxy_enabled;
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
let tproxy_port = patch.verge_tproxy_port;
|
|
||||||
let socks_enabled = patch.verge_socks_enabled;
|
|
||||||
let socks_port = patch.verge_socks_port;
|
|
||||||
let http_enabled = patch.verge_http_enabled;
|
|
||||||
let http_port = patch.verge_port;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
let enable_tray_speed = patch.enable_tray_speed;
|
|
||||||
#[cfg(not(target_os = "macos"))]
|
|
||||||
let enable_tray_speed: Option<bool> = None;
|
|
||||||
// let enable_tray_icon = patch.enable_tray_icon;
|
|
||||||
let enable_global_hotkey = patch.enable_global_hotkey;
|
|
||||||
let tray_event = &patch.tray_event;
|
|
||||||
let home_cards = patch.home_cards.as_ref();
|
|
||||||
let enable_auto_light_weight = patch.enable_auto_light_weight_mode;
|
|
||||||
let enable_external_controller = patch.enable_external_controller;
|
|
||||||
let tray_proxy_groups_display_mode = &patch.tray_proxy_groups_display_mode;
|
|
||||||
let tray_inline_outbound_modes = patch.tray_inline_outbound_modes;
|
|
||||||
let enable_proxy_guard = patch.enable_proxy_guard;
|
|
||||||
let proxy_guard_duration = patch.proxy_guard_duration;
|
|
||||||
let log_level = &patch.app_log_level;
|
|
||||||
let log_max_size = patch.app_log_max_size;
|
|
||||||
let log_max_count = patch.app_log_max_count;
|
|
||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
|
||||||
let restart_core_needed = socks_enabled.is_some()
|
|
||||||
|| http_enabled.is_some()
|
|
||||||
|| socks_port.is_some()
|
|
||||||
|| http_port.is_some()
|
|
||||||
|| mixed_port.is_some()
|
|
||||||
|| enable_external_controller.is_some();
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
let mut restart_core_needed = socks_enabled.is_some()
|
|
||||||
|| http_enabled.is_some()
|
|
||||||
|| socks_port.is_some()
|
|
||||||
|| http_port.is_some()
|
|
||||||
|| mixed_port.is_some()
|
|
||||||
|| enable_external_controller.is_some();
|
|
||||||
#[cfg(not(target_os = "windows"))]
|
|
||||||
{
|
|
||||||
restart_core_needed |= redir_enabled.is_some() || redir_port.is_some();
|
|
||||||
}
|
|
||||||
#[cfg(target_os = "linux")]
|
|
||||||
{
|
|
||||||
restart_core_needed |= tproxy_enabled.is_some() || tproxy_port.is_some();
|
|
||||||
restart_core_needed |= tun_mode == Some(true);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut update_flags = UpdateFlags::empty();
|
|
||||||
if restart_core_needed {
|
|
||||||
update_flags.insert(UpdateFlags::RESTART_CORE);
|
|
||||||
}
|
|
||||||
if tun_mode.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::CLASH_CONFIG | UpdateFlags::GROUP_SYS_TRAY);
|
|
||||||
}
|
|
||||||
if enable_global_hotkey.is_some() || home_cards.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::VERGE_CONFIG);
|
|
||||||
}
|
|
||||||
if auto_launch.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::LAUNCH);
|
|
||||||
}
|
|
||||||
if system_proxy.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::SYS_PROXY | UpdateFlags::GROUP_SYS_TRAY);
|
|
||||||
}
|
|
||||||
if proxy_bypass.is_some()
|
|
||||||
|| pac_content.is_some()
|
|
||||||
|| pac.is_some()
|
|
||||||
|| enable_proxy_guard.is_some()
|
|
||||||
|| proxy_guard_duration.is_some()
|
|
||||||
{
|
|
||||||
update_flags.insert(UpdateFlags::SYS_PROXY);
|
|
||||||
}
|
|
||||||
if language.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::LANGUAGE | UpdateFlags::SYSTRAY_MENU | UpdateFlags::SYSTRAY_TOOLTIP);
|
|
||||||
}
|
|
||||||
if common_tray_icon.is_some()
|
|
||||||
|| sysproxy_tray_icon.is_some()
|
|
||||||
|| tun_tray_icon.is_some()
|
|
||||||
|| tray_icon.is_some()
|
|
||||||
|| enable_tray_speed.is_some()
|
|
||||||
{
|
|
||||||
update_flags.insert(UpdateFlags::SYSTRAY_ICON);
|
|
||||||
}
|
|
||||||
if patch.hotkeys.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::HOTKEY | UpdateFlags::SYSTRAY_MENU);
|
|
||||||
}
|
|
||||||
if tray_event.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::SYSTRAY_CLICK_BEHAVIOR);
|
|
||||||
}
|
|
||||||
if enable_auto_light_weight.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::LIGHT_WEIGHT);
|
|
||||||
}
|
|
||||||
if tray_proxy_groups_display_mode.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::SYSTRAY_MENU);
|
|
||||||
}
|
|
||||||
if log_level.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::LOG_LEVEL);
|
|
||||||
}
|
|
||||||
if log_max_size.is_some() || log_max_count.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::LOG_FILE);
|
|
||||||
}
|
|
||||||
if tray_inline_outbound_modes.is_some() {
|
|
||||||
update_flags.insert(UpdateFlags::SYSTRAY_MENU);
|
|
||||||
}
|
|
||||||
|
|
||||||
update_flags
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::cognitive_complexity)]
|
|
||||||
async fn process_terminated_flags(update_flags: UpdateFlags, patch: &IVerge) -> Result<()> {
|
|
||||||
// Process updates based on flags
|
|
||||||
if update_flags.contains(UpdateFlags::RESTART_CORE) {
|
|
||||||
Config::generate().await?;
|
|
||||||
CoreManager::global().restart_core().await?;
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::CLASH_CONFIG) {
|
|
||||||
CoreManager::global().update_config_checked().await?;
|
|
||||||
handle::Handle::refresh_clash();
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::LAUNCH) {
|
|
||||||
autostart::update_launch().await?;
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::LANGUAGE)
|
|
||||||
&& let Some(language) = &patch.language
|
|
||||||
{
|
|
||||||
clash_verge_i18n::set_locale(language.as_str());
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::SYS_PROXY) {
|
|
||||||
let manager = CoreManager::global();
|
|
||||||
let _lifecycle = manager.lifecycle_lock.lock().await;
|
|
||||||
// Turning it off only writes OS state, so it must stay available while the Core is down.
|
|
||||||
if Config::verge()
|
|
||||||
.await
|
|
||||||
.latest_arc()
|
|
||||||
.enable_system_proxy
|
|
||||||
.unwrap_or_default()
|
|
||||||
{
|
|
||||||
manager.apply_proxy_after_start().await?;
|
|
||||||
} else {
|
|
||||||
proxy_control::apply().await?;
|
|
||||||
proxy_control::refresh_guard().await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::HOTKEY)
|
|
||||||
&& let Some(hotkeys) = &patch.hotkeys
|
|
||||||
{
|
|
||||||
hotkey::Hotkey::global().update(hotkeys.to_owned()).await?;
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::SYSTRAY_MENU) {
|
|
||||||
tray::Tray::global().update_menu().await?;
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::SYSTRAY_ICON) {
|
|
||||||
tray::Tray::global()
|
|
||||||
.update_icon(&Config::verge().await.latest_arc())
|
|
||||||
.await?;
|
|
||||||
#[cfg(target_os = "macos")]
|
|
||||||
if patch.enable_tray_speed.is_some() {
|
|
||||||
tray::Tray::global().update_speed_task(patch.enable_tray_speed.unwrap_or(false));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::SYSTRAY_TOOLTIP) {
|
|
||||||
tray::Tray::global().update_tooltip().await?;
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::SYSTRAY_CLICK_BEHAVIOR) {
|
|
||||||
tray::Tray::global().update_click_behavior().await?;
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::LIGHT_WEIGHT) {
|
|
||||||
if patch.enable_auto_light_weight_mode.unwrap_or(false) {
|
|
||||||
lightweight::enable_auto_light_weight_mode().await;
|
|
||||||
} else {
|
|
||||||
lightweight::disable_auto_light_weight_mode();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::LOG_LEVEL) {
|
|
||||||
logger::Logger::global().update_log_level(patch.get_log_level())?;
|
|
||||||
}
|
|
||||||
if update_flags.contains(UpdateFlags::LOG_FILE) {
|
|
||||||
let log_max_size = patch.app_log_max_size.unwrap_or(128);
|
|
||||||
let log_max_count = patch.app_log_max_count.unwrap_or(8);
|
|
||||||
logger::update_log_config(log_max_size, log_max_count).await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply a patch, then reconcile TUN when its setting changes.
|
/// Apply a patch, then reconcile TUN when its setting changes.
|
||||||
@@ -289,7 +27,7 @@ pub async fn patch_verge(patch: &IVerge, not_save_file: bool) -> Result<()> {
|
|||||||
|
|
||||||
/// Apply a patch without post-update reconciliation.
|
/// Apply a patch without post-update reconciliation.
|
||||||
pub(super) async fn apply_verge_patch(patch: &IVerge, not_save_file: bool) -> Result<()> {
|
pub(super) async fn apply_verge_patch(patch: &IVerge, not_save_file: bool) -> Result<()> {
|
||||||
let config_write = Config::lock_config_write().await;
|
let config_write = Config::try_lock_config_write()?;
|
||||||
apply_verge_patch_locked(&config_write, patch, not_save_file).await
|
apply_verge_patch_locked(&config_write, patch, not_save_file).await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -300,29 +38,15 @@ pub(super) async fn apply_verge_patch_locked(
|
|||||||
patch: &IVerge,
|
patch: &IVerge,
|
||||||
not_save_file: bool,
|
not_save_file: bool,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let verge = Config::verge().await;
|
super::executor::apply(
|
||||||
// Hold the claim across side effects so concurrent transactions cannot share this draft.
|
_config_write,
|
||||||
let transaction = DraftTransaction::begin(vec![&verge])?;
|
super::executor::Patch::Verge {
|
||||||
verge.edit_draft(|d| d.patch_config(patch));
|
patch,
|
||||||
|
persist: !not_save_file,
|
||||||
let update_flags = determine_update_flags(patch);
|
},
|
||||||
logging!(debug, Type::Setup, "Determined update flags: {:?}", update_flags);
|
super::effects::verge_effects(patch),
|
||||||
// A failed patch rolls back to what the user already had; it never invents a value for them.
|
)
|
||||||
process_terminated_flags(update_flags, patch).await?;
|
.await
|
||||||
transaction.commit();
|
|
||||||
announce_verge_change();
|
|
||||||
|
|
||||||
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
|
|
||||||
if !not_save_file {
|
|
||||||
// 分离数据获取和异步调用
|
|
||||||
let verge_data = verge.data_arc();
|
|
||||||
verge_data.save_file().await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn announce_verge_change() {
|
|
||||||
handle::Handle::refresh_verge();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn fetch_verge_config() -> Result<SharedDraft<IVerge>> {
|
pub async fn fetch_verge_config() -> Result<SharedDraft<IVerge>> {
|
||||||
|
|||||||
@@ -359,24 +359,31 @@ fn stage_core(target: &Path, package: &[u8], version: &str) -> Result<StagedCore
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn create_staging_file(directory: &Path, core_name: &OsStr) -> Result<(PathBuf, File)> {
|
fn create_staging_file(directory: &Path, core_name: &OsStr) -> Result<(PathBuf, File)> {
|
||||||
for _ in 0..32 {
|
use crate::utils::retry::{RetryError, RetryPolicy, retry_sync};
|
||||||
let generation = STAGING_GENERATION.fetch_add(1, Ordering::Relaxed);
|
retry_sync(
|
||||||
let path = directory.join(format!(
|
RetryPolicy::fixed(
|
||||||
".{}.{}.{generation}.tmp",
|
std::num::NonZeroUsize::MIN.saturating_add(31),
|
||||||
core_name.to_string_lossy(),
|
std::time::Duration::ZERO,
|
||||||
std::process::id()
|
),
|
||||||
));
|
|_| {
|
||||||
|
let generation = STAGING_GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||||
|
let path = directory.join(format!(
|
||||||
|
".{}.{}.{generation}.tmp",
|
||||||
|
core_name.to_string_lossy(),
|
||||||
|
std::process::id()
|
||||||
|
));
|
||||||
|
|
||||||
match File::options().write(true).create_new(true).open(&path) {
|
match File::options().write(true).create_new(true).open(&path) {
|
||||||
Ok(file) => return Ok((path, file)),
|
Ok(file) => Ok((path, file)),
|
||||||
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
|
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Err(RetryError::Retry(
|
||||||
Err(error) => {
|
anyhow::anyhow!("failed to create a unique staging file in {}", directory.display()),
|
||||||
return Err(error).with_context(|| format!("failed to create {}", path.display()));
|
)),
|
||||||
|
Err(error) => Err(RetryError::Stop(
|
||||||
|
anyhow::Error::from(error).context(format!("failed to create {}", path.display())),
|
||||||
|
)),
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
}
|
)
|
||||||
|
|
||||||
bail!("failed to create a unique staging file in {}", directory.display())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
|
|||||||
+37
-10
@@ -1,12 +1,17 @@
|
|||||||
use anyhow::Result;
|
use crate::core::notify::{Refresh, announce};
|
||||||
|
use anyhow::{Result, ensure};
|
||||||
use clash_verge_draft::DraftTransaction;
|
use clash_verge_draft::DraftTransaction;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use smartstring::alias::String;
|
use smartstring::alias::String;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, dns::dns_override_source, profiles::PROFILE_WRITE_LOCK},
|
config::{
|
||||||
|
Config,
|
||||||
|
dns::{ProfileDnsSettings, dns_override_source},
|
||||||
|
profiles::PROFILE_WRITE_LOCK,
|
||||||
|
},
|
||||||
constants::files::DNS_CONFIG,
|
constants::files::DNS_CONFIG,
|
||||||
core::{CoreManager, handle::Handle},
|
core::CoreManager,
|
||||||
utils::dirs,
|
utils::dirs,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -17,10 +22,26 @@ pub enum DnsOverrideOutcome {
|
|||||||
ConfirmationRequired { source: String },
|
ConfirmationRequired { source: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_dns_override(enabled: bool, confirmation: Option<String>) -> Result<DnsOverrideOutcome> {
|
pub async fn set_dns_override(
|
||||||
|
profile_uid: String,
|
||||||
|
enabled: bool,
|
||||||
|
confirmation: Option<String>,
|
||||||
|
) -> Result<DnsOverrideOutcome> {
|
||||||
|
crate::core::notify::after_commit(Box::pin(set_dns_override_inner(profile_uid, enabled, confirmation))).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn set_dns_override_inner(
|
||||||
|
profile_uid: String,
|
||||||
|
enabled: bool,
|
||||||
|
confirmation: Option<String>,
|
||||||
|
) -> Result<DnsOverrideOutcome> {
|
||||||
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
|
let _profile_write = PROFILE_WRITE_LOCK.lock().await;
|
||||||
let _config_write = Config::lock_config_write().await;
|
let _config_write = Config::lock_config_write().await;
|
||||||
let profiles = Config::profiles().await.data_arc();
|
let profiles = Config::profiles().await.data_arc();
|
||||||
|
ensure!(
|
||||||
|
profiles.current.as_ref() == Some(&profile_uid),
|
||||||
|
"The active profile changed; retry the DNS setting"
|
||||||
|
);
|
||||||
let source = dns_override_source(
|
let source = dns_override_source(
|
||||||
profiles.current.as_deref().unwrap_or_default(),
|
profiles.current.as_deref().unwrap_or_default(),
|
||||||
&profiles.current_mapping().await?,
|
&profiles.current_mapping().await?,
|
||||||
@@ -37,8 +58,13 @@ pub async fn set_dns_override(enabled: bool, confirmation: Option<String>) -> Re
|
|||||||
let verge = Config::verge().await;
|
let verge = Config::verge().await;
|
||||||
let transaction = DraftTransaction::begin(vec![&verge])?;
|
let transaction = DraftTransaction::begin(vec![&verge])?;
|
||||||
verge.edit_draft(|draft| {
|
verge.edit_draft(|draft| {
|
||||||
draft.enable_dns_settings = Some(enabled);
|
draft.profile_dns_settings.insert(
|
||||||
draft.dns_override_confirmation = if enabled { source } else { None };
|
profile_uid.clone(),
|
||||||
|
ProfileDnsSettings {
|
||||||
|
enabled,
|
||||||
|
confirmation: if enabled { source } else { None },
|
||||||
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
CoreManager::global().update_config_checked().await?;
|
CoreManager::global().update_config_checked().await?;
|
||||||
|
|
||||||
@@ -47,8 +73,9 @@ pub async fn set_dns_override(enabled: bool, confirmation: Option<String>) -> Re
|
|||||||
// A subscription update can replace the file while Mihomo is validating it.
|
// A subscription update can replace the file while Mihomo is validating it.
|
||||||
if enabled && let Some(state) = state.filter(|state| !state.enabled) {
|
if enabled && let Some(state) = state.filter(|state| !state.enabled) {
|
||||||
verge.edit_draft(|draft| {
|
verge.edit_draft(|draft| {
|
||||||
draft.enable_dns_settings = Some(false);
|
draft
|
||||||
draft.dns_override_confirmation = None;
|
.profile_dns_settings
|
||||||
|
.insert(profile_uid, ProfileDnsSettings::default());
|
||||||
});
|
});
|
||||||
if let Some(source) = state.source {
|
if let Some(source) = state.source {
|
||||||
outcome = DnsOverrideOutcome::ConfirmationRequired { source };
|
outcome = DnsOverrideOutcome::ConfirmationRequired { source };
|
||||||
@@ -56,8 +83,8 @@ pub async fn set_dns_override(enabled: bool, confirmation: Option<String>) -> Re
|
|||||||
}
|
}
|
||||||
|
|
||||||
transaction.commit();
|
transaction.commit();
|
||||||
Handle::refresh_verge();
|
|
||||||
Handle::refresh_clash();
|
|
||||||
verge.data_arc().save_file().await?;
|
verge.data_arc().save_file().await?;
|
||||||
|
announce(Refresh::Verge);
|
||||||
|
announce(Refresh::Clash);
|
||||||
Ok(outcome)
|
Ok(outcome)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,296 @@
|
|||||||
|
use crate::config::IVerge;
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub(super) enum Effect {
|
||||||
|
RestartCore,
|
||||||
|
ClashConfig,
|
||||||
|
VergeConfig,
|
||||||
|
Autostart,
|
||||||
|
SystemProxy,
|
||||||
|
TrayIcon,
|
||||||
|
Hotkey,
|
||||||
|
TrayMenu,
|
||||||
|
TrayTooltip,
|
||||||
|
TrayClick,
|
||||||
|
Lightweight,
|
||||||
|
Language,
|
||||||
|
LogLevel,
|
||||||
|
LogFile,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) type Effects = BTreeSet<Effect>;
|
||||||
|
|
||||||
|
macro_rules! select_field {
|
||||||
|
($effects:ident, $field:ident, NoEffect) => { let _ = $field; };
|
||||||
|
($effects:ident, $field:ident, [$($effect:ident),*]) => {
|
||||||
|
if $field.is_some() { $effects.extend([$(Effect::$effect),*]); }
|
||||||
|
};
|
||||||
|
($effects:ident, $field:ident, Tun) => {
|
||||||
|
select_field!($effects, $field, [ClashConfig, TrayMenu, TrayTooltip, TrayIcon]);
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
if *$field == Some(true) { $effects.insert(Effect::RestartCore); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! verge_registry {
|
||||||
|
($( $(#[$cfg:meta])* $field:ident => $rule:tt; )*) => {
|
||||||
|
pub(super) fn verge_effects(patch: &IVerge) -> Effects {
|
||||||
|
// No rest pattern: even fields omitted by serde must be classified at compile time.
|
||||||
|
let IVerge { $( $(#[$cfg])* $field, )* } = patch;
|
||||||
|
let mut effects = Effects::new();
|
||||||
|
$( $(#[$cfg])* { select_field!(effects, $field, $rule); } )*
|
||||||
|
effects
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
const VERGE_FIELDS: &[&str] = &[ $( $(#[$cfg])* stringify!($field), )* ];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
verge_registry! {
|
||||||
|
app_log_level => [LogLevel];
|
||||||
|
app_log_max_size => [LogFile];
|
||||||
|
app_log_max_count => [LogFile];
|
||||||
|
language => [Language, TrayMenu, TrayTooltip];
|
||||||
|
theme_mode => NoEffect;
|
||||||
|
tray_event => [TrayClick];
|
||||||
|
env_type => NoEffect;
|
||||||
|
start_page => NoEffect;
|
||||||
|
startup_script => NoEffect;
|
||||||
|
traffic_graph => NoEffect;
|
||||||
|
enable_memory_usage => NoEffect;
|
||||||
|
enable_group_icon => NoEffect;
|
||||||
|
pause_render_traffic_stats_on_blur => NoEffect;
|
||||||
|
common_tray_icon => [TrayIcon];
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
tray_icon => [TrayIcon];
|
||||||
|
menu_icon => NoEffect;
|
||||||
|
menu_order => NoEffect;
|
||||||
|
proxy_group_tools_position => NoEffect;
|
||||||
|
notice_position => NoEffect;
|
||||||
|
collapse_navbar => NoEffect;
|
||||||
|
sysproxy_tray_icon => [TrayIcon];
|
||||||
|
tun_tray_icon => [TrayIcon];
|
||||||
|
enable_tun_mode => Tun;
|
||||||
|
enable_auto_launch => [Autostart];
|
||||||
|
enable_silent_start => NoEffect;
|
||||||
|
enable_system_proxy => [SystemProxy, TrayMenu, TrayTooltip, TrayIcon];
|
||||||
|
enable_proxy_guard => [SystemProxy];
|
||||||
|
enable_bypass_check => NoEffect;
|
||||||
|
enable_dns_settings => NoEffect;
|
||||||
|
profile_dns_settings => NoEffect;
|
||||||
|
use_default_bypass => NoEffect;
|
||||||
|
system_proxy_bypass => [SystemProxy];
|
||||||
|
proxy_guard_duration => [SystemProxy];
|
||||||
|
proxy_auto_config => [SystemProxy];
|
||||||
|
pac_file_content => [SystemProxy];
|
||||||
|
proxy_host => NoEffect;
|
||||||
|
theme_setting => NoEffect;
|
||||||
|
web_ui_list => NoEffect;
|
||||||
|
clash_core => NoEffect;
|
||||||
|
hotkeys => [Hotkey, TrayMenu];
|
||||||
|
enable_global_hotkey => [VergeConfig];
|
||||||
|
home_cards => [VergeConfig];
|
||||||
|
auto_close_connection => NoEffect;
|
||||||
|
auto_check_update => NoEffect;
|
||||||
|
default_latency_test => NoEffect;
|
||||||
|
default_latency_timeout => NoEffect;
|
||||||
|
enable_auto_delay_detection => NoEffect;
|
||||||
|
auto_delay_detection_interval_minutes => NoEffect;
|
||||||
|
enable_builtin_enhanced => NoEffect;
|
||||||
|
proxy_layout_column => NoEffect;
|
||||||
|
test_list => NoEffect;
|
||||||
|
auto_log_clean => NoEffect;
|
||||||
|
enable_auto_backup_schedule => NoEffect;
|
||||||
|
auto_backup_interval_hours => NoEffect;
|
||||||
|
auto_backup_on_change => NoEffect;
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
verge_redir_port => [RestartCore];
|
||||||
|
#[cfg(not(target_os = "windows"))]
|
||||||
|
verge_redir_enabled => [RestartCore];
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
verge_tproxy_port => [RestartCore];
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
verge_tproxy_enabled => [RestartCore];
|
||||||
|
verge_mixed_port => [RestartCore];
|
||||||
|
verge_socks_port => [RestartCore];
|
||||||
|
verge_socks_enabled => [RestartCore];
|
||||||
|
verge_port => [RestartCore];
|
||||||
|
verge_http_enabled => [RestartCore];
|
||||||
|
webdav_url => NoEffect;
|
||||||
|
webdav_username => NoEffect;
|
||||||
|
webdav_password => NoEffect;
|
||||||
|
#[cfg(target_os = "macos")]
|
||||||
|
enable_tray_speed => [TrayIcon];
|
||||||
|
tray_proxy_groups_display_mode => [TrayMenu];
|
||||||
|
tray_inline_outbound_modes => [TrayMenu];
|
||||||
|
enable_auto_light_weight_mode => [Lightweight];
|
||||||
|
auto_light_weight_minutes => NoEffect;
|
||||||
|
enable_hover_jump_navigator => NoEffect;
|
||||||
|
hover_jump_navigator_delay => NoEffect;
|
||||||
|
enable_external_controller => [RestartCore];
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn clash_effects(patch: &serde_yaml_ng::Mapping) -> Effects {
|
||||||
|
use clash_verge_logging::{Type, logging};
|
||||||
|
let mut effects = Effects::new();
|
||||||
|
for key in patch.keys() {
|
||||||
|
effects.extend(match key.as_str() {
|
||||||
|
Some("secret" | "external-controller") => &[Effect::RestartCore][..],
|
||||||
|
Some("allow-lan") => &[Effect::ClashConfig][..],
|
||||||
|
Some("mode") => &[Effect::ClashConfig, Effect::TrayMenu, Effect::TrayIcon][..],
|
||||||
|
_ => {
|
||||||
|
logging!(
|
||||||
|
warn,
|
||||||
|
Type::Config,
|
||||||
|
"Unregistered Clash configuration key {key:?}; reloading configuration"
|
||||||
|
);
|
||||||
|
&[Effect::ClashConfig][..]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// These branches were exclusive: restart supersedes reload, and allow-lan precedes mode.
|
||||||
|
if effects.contains(&Effect::RestartCore) {
|
||||||
|
effects.retain(|effect| *effect == Effect::RestartCore);
|
||||||
|
} else if patch.contains_key("allow-lan") {
|
||||||
|
effects.retain(|effect| *effect == Effect::ClashConfig);
|
||||||
|
}
|
||||||
|
if patch.is_empty() {
|
||||||
|
effects.insert(Effect::ClashConfig);
|
||||||
|
}
|
||||||
|
effects
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_serialized_verge_field_is_registered() -> Result<(), serde_json::Error> {
|
||||||
|
let fields: std::collections::BTreeMap<String, serde_json::Value> =
|
||||||
|
serde_json::from_value(serde_json::to_value(IVerge::default())?)?;
|
||||||
|
for field in fields.keys() {
|
||||||
|
assert!(VERGE_FIELDS.contains(&field.as_str()), "unregistered field: {field}");
|
||||||
|
}
|
||||||
|
let unique: BTreeSet<_> = VERGE_FIELDS.iter().collect();
|
||||||
|
assert_eq!(unique.len(), VERGE_FIELDS.len());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verge_patch(mutate: impl FnOnce(&mut IVerge)) -> IVerge {
|
||||||
|
let mut patch = IVerge::default();
|
||||||
|
mutate(&mut patch);
|
||||||
|
patch
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn representative_verge_patches_map_to_frozen_effects() {
|
||||||
|
assert_eq!(verge_effects(&IVerge::default()), Effects::new());
|
||||||
|
|
||||||
|
let cases: [(IVerge, &[Effect]); 7] = [
|
||||||
|
(
|
||||||
|
verge_patch(|p| p.verge_mixed_port = Some(27899)),
|
||||||
|
&[Effect::RestartCore],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
verge_patch(|p| p.language = Some("zh".into())),
|
||||||
|
&[Effect::TrayMenu, Effect::TrayTooltip, Effect::Language],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
verge_patch(|p| p.hotkeys = Some(vec!["CmdOrCtrl+K".into()])),
|
||||||
|
&[Effect::Hotkey, Effect::TrayMenu],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
verge_patch(|p| p.enable_system_proxy = Some(true)),
|
||||||
|
&[
|
||||||
|
Effect::SystemProxy,
|
||||||
|
Effect::TrayIcon,
|
||||||
|
Effect::TrayMenu,
|
||||||
|
Effect::TrayTooltip,
|
||||||
|
],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
verge_patch(|p| p.system_proxy_bypass = Some("localhost".into())),
|
||||||
|
&[Effect::SystemProxy],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
verge_patch(|p| p.tray_event = Some("show_main_window".into())),
|
||||||
|
&[Effect::TrayClick],
|
||||||
|
),
|
||||||
|
(verge_patch(|p| p.theme_mode = Some("dark".into())), &[]),
|
||||||
|
];
|
||||||
|
for (patch, expected) in cases {
|
||||||
|
assert_eq!(
|
||||||
|
verge_effects(&patch),
|
||||||
|
expected.iter().copied().collect::<Effects>(),
|
||||||
|
"patch mapping drifted for {expected:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let tun = verge_patch(|p| p.enable_tun_mode = Some(true));
|
||||||
|
#[cfg(target_os = "linux")]
|
||||||
|
assert_eq!(
|
||||||
|
verge_effects(&tun),
|
||||||
|
[
|
||||||
|
Effect::RestartCore,
|
||||||
|
Effect::ClashConfig,
|
||||||
|
Effect::TrayIcon,
|
||||||
|
Effect::TrayMenu,
|
||||||
|
Effect::TrayTooltip,
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.collect::<Effects>()
|
||||||
|
);
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
assert_eq!(
|
||||||
|
verge_effects(&tun),
|
||||||
|
[
|
||||||
|
Effect::ClashConfig,
|
||||||
|
Effect::TrayIcon,
|
||||||
|
Effect::TrayMenu,
|
||||||
|
Effect::TrayTooltip,
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.collect::<Effects>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clash_mapping(pairs: &[(&str, &str)]) -> serde_yaml_ng::Mapping {
|
||||||
|
let mut mapping = serde_yaml_ng::Mapping::new();
|
||||||
|
for (key, value) in pairs {
|
||||||
|
mapping.insert((*key).into(), (*value).into());
|
||||||
|
}
|
||||||
|
mapping
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clash_keys_map_to_frozen_effects() {
|
||||||
|
let cases: [(serde_yaml_ng::Mapping, &[Effect]); 7] = [
|
||||||
|
(clash_mapping(&[]), &[Effect::ClashConfig]),
|
||||||
|
(clash_mapping(&[("secret", "s")]), &[Effect::RestartCore]),
|
||||||
|
(
|
||||||
|
clash_mapping(&[("mode", "rule")]),
|
||||||
|
&[Effect::ClashConfig, Effect::TrayIcon, Effect::TrayMenu],
|
||||||
|
),
|
||||||
|
(clash_mapping(&[("allow-lan", "true")]), &[Effect::ClashConfig]),
|
||||||
|
(clash_mapping(&[("not-a-known-key", "1")]), &[Effect::ClashConfig]),
|
||||||
|
// Restart supersedes reload; allow-lan precedes mode.
|
||||||
|
(
|
||||||
|
clash_mapping(&[("secret", "s"), ("mode", "rule")]),
|
||||||
|
&[Effect::RestartCore],
|
||||||
|
),
|
||||||
|
(
|
||||||
|
clash_mapping(&[("allow-lan", "true"), ("mode", "rule")]),
|
||||||
|
&[Effect::ClashConfig],
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for (patch, expected) in cases {
|
||||||
|
assert_eq!(
|
||||||
|
clash_effects(&patch),
|
||||||
|
expected.iter().copied().collect::<Effects>(),
|
||||||
|
"clash mapping drifted for {expected:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
use super::effects::{Effect, Effects};
|
||||||
|
use crate::core::notify::{Refresh, announce};
|
||||||
|
use crate::{
|
||||||
|
config::{
|
||||||
|
Config, IVerge,
|
||||||
|
snapshot::{capture_config_files, restore_files},
|
||||||
|
},
|
||||||
|
core::auto_backup::AutoBackupManager,
|
||||||
|
core::{CoreManager, logger, manager::ConfigUpdateGuard, proxy_control},
|
||||||
|
};
|
||||||
|
use anyhow::Result;
|
||||||
|
use clash_verge_draft::DraftTransaction;
|
||||||
|
use clash_verge_logging::{Type, logging_error};
|
||||||
|
use futures::future::BoxFuture;
|
||||||
|
use serde_yaml_ng::Mapping;
|
||||||
|
use tokio::sync::MutexGuard;
|
||||||
|
|
||||||
|
pub(super) enum Patch<'a> {
|
||||||
|
Verge { patch: &'a IVerge, persist: bool },
|
||||||
|
Clash(&'a Mapping),
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EffectContext<'a> {
|
||||||
|
patch: &'a IVerge,
|
||||||
|
manager: &'a CoreManager,
|
||||||
|
update: &'a ConfigUpdateGuard<'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Ensure = for<'a> fn(&'a EffectContext<'_>) -> BoxFuture<'a, Result<()>>;
|
||||||
|
|
||||||
|
const EFFECT_ORDER: &[(Effect, Ensure)] = &[
|
||||||
|
(Effect::RestartCore, ensure_restart),
|
||||||
|
(Effect::ClashConfig, ensure_clash),
|
||||||
|
(Effect::VergeConfig, ensure_verge),
|
||||||
|
(Effect::Autostart, ensure_autostart),
|
||||||
|
(Effect::Language, ensure_language),
|
||||||
|
(Effect::SystemProxy, ensure_system_proxy),
|
||||||
|
(Effect::Hotkey, ensure_hotkey),
|
||||||
|
(Effect::TrayMenu, ensure_tray_menu),
|
||||||
|
(Effect::TrayIcon, ensure_tray_icon),
|
||||||
|
(Effect::TrayTooltip, ensure_tray_tooltip),
|
||||||
|
(Effect::TrayClick, ensure_tray_click),
|
||||||
|
(Effect::Lightweight, ensure_lightweight),
|
||||||
|
(Effect::LogLevel, ensure_log_level),
|
||||||
|
(Effect::LogFile, ensure_log_file),
|
||||||
|
];
|
||||||
|
|
||||||
|
macro_rules! ensure {
|
||||||
|
($name:ident, $ctx:ident, $body:block) => {
|
||||||
|
fn $name<'a>($ctx: &'a EffectContext<'_>) -> BoxFuture<'a, Result<()>> {
|
||||||
|
Box::pin(async move $body)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure!(ensure_restart, ctx, {
|
||||||
|
Config::generate().await?;
|
||||||
|
ctx.manager.restart_core_during_config_update().await
|
||||||
|
});
|
||||||
|
ensure!(ensure_clash, ctx, {
|
||||||
|
ctx.manager.update_config_in_patch(ctx.update).await?;
|
||||||
|
announce(Refresh::Clash);
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
ensure!(ensure_verge, _ctx, { Ok(()) });
|
||||||
|
ensure!(ensure_autostart, ctx, {
|
||||||
|
crate::core::app_effects::ensure_autostart(ctx.patch).await
|
||||||
|
});
|
||||||
|
ensure!(ensure_language, ctx, {
|
||||||
|
if let Some(language) = &ctx.patch.language {
|
||||||
|
clash_verge_i18n::set_locale(language.as_str());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
});
|
||||||
|
ensure!(ensure_system_proxy, ctx, {
|
||||||
|
let _lifecycle = ctx.manager.lifecycle_lock.lock().await;
|
||||||
|
// Disabling only writes OS state and must remain available when the Core is stopped.
|
||||||
|
if Config::verge()
|
||||||
|
.await
|
||||||
|
.latest_arc()
|
||||||
|
.enable_system_proxy
|
||||||
|
.unwrap_or_default()
|
||||||
|
{
|
||||||
|
ctx.manager.apply_proxy_after_start().await
|
||||||
|
} else {
|
||||||
|
proxy_control::apply().await?;
|
||||||
|
proxy_control::refresh_guard().await
|
||||||
|
}
|
||||||
|
});
|
||||||
|
ensure!(ensure_hotkey, ctx, {
|
||||||
|
crate::core::app_effects::ensure_hotkey(ctx.patch).await
|
||||||
|
});
|
||||||
|
ensure!(ensure_tray_menu, ctx, {
|
||||||
|
crate::core::app_effects::ensure_tray_menu(ctx.patch).await
|
||||||
|
});
|
||||||
|
ensure!(ensure_tray_icon, ctx, {
|
||||||
|
crate::core::app_effects::ensure_tray_icon(ctx.patch).await
|
||||||
|
});
|
||||||
|
ensure!(ensure_tray_tooltip, ctx, {
|
||||||
|
crate::core::app_effects::ensure_tray_tooltip(ctx.patch).await
|
||||||
|
});
|
||||||
|
ensure!(ensure_tray_click, ctx, {
|
||||||
|
crate::core::app_effects::ensure_tray_click(ctx.patch).await
|
||||||
|
});
|
||||||
|
ensure!(ensure_lightweight, ctx, {
|
||||||
|
crate::core::app_effects::ensure_lightweight(ctx.patch).await
|
||||||
|
});
|
||||||
|
ensure!(ensure_log_level, ctx, {
|
||||||
|
logger::Logger::global().update_log_level(ctx.patch.get_log_level())
|
||||||
|
});
|
||||||
|
ensure!(ensure_log_file, ctx, {
|
||||||
|
logger::update_log_config(
|
||||||
|
ctx.patch.app_log_max_size.unwrap_or(128),
|
||||||
|
ctx.patch.app_log_max_count.unwrap_or(8),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
});
|
||||||
|
|
||||||
|
async fn apply_inner(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
|
||||||
|
let manager = CoreManager::global();
|
||||||
|
let update = manager.claim_config_update(config_write)?;
|
||||||
|
let clash = Config::clash().await;
|
||||||
|
let verge = Config::verge().await;
|
||||||
|
let runtime = Config::runtime().await;
|
||||||
|
let transaction = match patch {
|
||||||
|
Patch::Verge { .. } => DraftTransaction::begin(vec![&verge, &runtime])?,
|
||||||
|
Patch::Clash(_) => DraftTransaction::begin(vec![&clash, &runtime])?,
|
||||||
|
};
|
||||||
|
let snapshots = capture_config_files().await?;
|
||||||
|
let empty = IVerge::default();
|
||||||
|
let context = EffectContext {
|
||||||
|
patch: match &patch {
|
||||||
|
Patch::Verge { patch, .. } => patch,
|
||||||
|
Patch::Clash(_) => &empty,
|
||||||
|
},
|
||||||
|
manager,
|
||||||
|
update: &update,
|
||||||
|
};
|
||||||
|
match &patch {
|
||||||
|
Patch::Verge { patch, .. } => verge.edit_draft(|draft| draft.patch_config(patch)),
|
||||||
|
Patch::Clash(patch) => clash.edit_draft(|draft| draft.patch_config(patch)),
|
||||||
|
}
|
||||||
|
let result: Result<()> = async {
|
||||||
|
for (effect, ensure) in EFFECT_ORDER {
|
||||||
|
if effects.contains(effect) {
|
||||||
|
ensure(&context).await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match patch {
|
||||||
|
Patch::Verge { persist: true, .. } => verge.latest_arc().save_file().await?,
|
||||||
|
Patch::Verge { persist: false, .. } => {}
|
||||||
|
Patch::Clash(_) => clash.latest_arc().save_config().await?,
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
if let Err(error) = result {
|
||||||
|
transaction.rollback();
|
||||||
|
return match restore_files(&snapshots).await {
|
||||||
|
Ok(()) => Err(error),
|
||||||
|
Err(rollback_error) => Err(proxy_control::rollback_failure(error, rollback_error)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
transaction.commit();
|
||||||
|
match patch {
|
||||||
|
Patch::Verge { .. } => {
|
||||||
|
logging_error!(Type::Backup, AutoBackupManager::global().refresh_settings().await);
|
||||||
|
announce(Refresh::Verge);
|
||||||
|
}
|
||||||
|
Patch::Clash(_) => announce(Refresh::Clash),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, effects: Effects) -> Result<()> {
|
||||||
|
crate::core::notify::after_commit(apply_inner(config_write, patch, effects)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn config_claim_is_exclusive_and_released_on_drop() -> Result<()> {
|
||||||
|
let write_lock = tokio::sync::Mutex::new(());
|
||||||
|
let write = write_lock.lock().await;
|
||||||
|
let manager = CoreManager::default();
|
||||||
|
let first = manager.claim_config_update(&write)?;
|
||||||
|
assert!(manager.claim_config_update(&write).is_err());
|
||||||
|
drop(first);
|
||||||
|
assert!(manager.claim_config_update(&write).is_ok());
|
||||||
|
drop(write);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::core::notify::{Refresh, announce};
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
Config, MixedPort,
|
Config, MixedPort,
|
||||||
@@ -5,7 +6,6 @@ use crate::{
|
|||||||
},
|
},
|
||||||
core::{
|
core::{
|
||||||
CoreManager,
|
CoreManager,
|
||||||
handle::Handle,
|
|
||||||
listener::{
|
listener::{
|
||||||
ListenerProbe, ListenerProbeOutcome, ProxyPortSettings, SaveProxyPortsOutcome,
|
ListenerProbe, ListenerProbeOutcome, ProxyPortSettings, SaveProxyPortsOutcome,
|
||||||
probe_listener as probe_listener_sync, probe_proxy_port_change,
|
probe_listener as probe_listener_sync, probe_proxy_port_change,
|
||||||
@@ -27,8 +27,12 @@ pub async fn probe_listener(request: ListenerProbe) -> Result<ListenerProbeOutco
|
|||||||
.context("listener probe task failed")
|
.context("listener probe task failed")
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::cognitive_complexity)]
|
|
||||||
pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPortsOutcome> {
|
pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPortsOutcome> {
|
||||||
|
crate::core::notify::after_commit(Box::pin(save_proxy_ports_inner(settings))).await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(clippy::cognitive_complexity)]
|
||||||
|
async fn save_proxy_ports_inner(settings: ProxyPortSettings) -> Result<SaveProxyPortsOutcome> {
|
||||||
settings.validate()?;
|
settings.validate()?;
|
||||||
let _config_write = Config::lock_config_write().await;
|
let _config_write = Config::lock_config_write().await;
|
||||||
let manager = CoreManager::global();
|
let manager = CoreManager::global();
|
||||||
@@ -126,8 +130,8 @@ pub async fn save_proxy_ports(settings: ProxyPortSettings) -> Result<SaveProxyPo
|
|||||||
transaction.commit();
|
transaction.commit();
|
||||||
// The save landed, so the port the app had borrowed is now irrelevant.
|
// The save landed, so the port the app had borrowed is now irrelevant.
|
||||||
let _ = ScopeGuard::into_inner(borrowed_port);
|
let _ = ScopeGuard::into_inner(borrowed_port);
|
||||||
Handle::refresh_clash();
|
announce(Refresh::Clash);
|
||||||
Handle::refresh_verge();
|
announce(Refresh::Verge);
|
||||||
logging!(info, Type::Config, "Proxy port configuration applied and persisted");
|
logging!(info, Type::Config, "Proxy port configuration applied and persisted");
|
||||||
Ok(SaveProxyPortsOutcome::Saved)
|
Ok(SaveProxyPortsOutcome::Saved)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ mod clash;
|
|||||||
mod config;
|
mod config;
|
||||||
mod core_upgrade;
|
mod core_upgrade;
|
||||||
mod dns;
|
mod dns;
|
||||||
|
mod effects;
|
||||||
|
mod executor;
|
||||||
mod icon;
|
mod icon;
|
||||||
mod listener;
|
mod listener;
|
||||||
mod profile;
|
mod profile;
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
|
use crate::core::notify::{Refresh, announce};
|
||||||
use crate::{
|
use crate::{
|
||||||
cmd,
|
cmd,
|
||||||
config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe},
|
config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe},
|
||||||
@@ -43,7 +45,7 @@ pub async fn switch_proxy_node(group_name: &str, proxy_name: &str) {
|
|||||||
{
|
{
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
record_switched_node(group_name, proxy_name).await;
|
record_switched_node(group_name, proxy_name).await;
|
||||||
handle::Handle::refresh_proxy_config();
|
announce(Refresh::Proxies);
|
||||||
let _ = tray::Tray::global().update_menu().await;
|
let _ = tray::Tray::global().update_menu().await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -100,7 +102,7 @@ async fn should_update_profile(uid: &String, ignore_auto_update: bool) -> Result
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty))]
|
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
|
||||||
async fn perform_profile_update(
|
async fn perform_profile_update(
|
||||||
uid: &String,
|
uid: &String,
|
||||||
url: &String,
|
url: &String,
|
||||||
@@ -108,7 +110,7 @@ async fn perform_profile_update(
|
|||||||
option: Option<&PrfOption>,
|
option: Option<&PrfOption>,
|
||||||
is_mannual_trigger: bool,
|
is_mannual_trigger: bool,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let mut merged_opt = PrfOption::merge(opt, option);
|
let merged_opt = PrfOption::merge(opt, option);
|
||||||
let profiles = Config::profiles().await;
|
let profiles = Config::profiles().await;
|
||||||
let profiles_arc = profiles.latest_arc();
|
let profiles_arc = profiles.latest_arc();
|
||||||
let profile_name = profiles_arc
|
let profile_name = profiles_arc
|
||||||
@@ -117,66 +119,82 @@ async fn perform_profile_update(
|
|||||||
.and_then(|item| item.name.clone())
|
.and_then(|item| item.name.clone())
|
||||||
.unwrap_or_else(|| String::from("UnKnown Profile"));
|
.unwrap_or_else(|| String::from("UnKnown Profile"));
|
||||||
|
|
||||||
match PrfItem::from_url(url, None, None, merged_opt.as_ref()).await {
|
#[derive(Clone, Copy)]
|
||||||
Ok(mut item) => {
|
enum Strategy {
|
||||||
logging!(info, Type::Config, "[订阅更新] 更新订阅配置成功");
|
Configured,
|
||||||
profiles_update_item_safe(uid, &mut item).await?;
|
Clash,
|
||||||
return Ok(());
|
System,
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Config,
|
|
||||||
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
|
|
||||||
mask_err(&format!("{err:#}"))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
merged_opt.get_or_insert_with(PrfOption::default).self_proxy = Some(true);
|
let result =
|
||||||
merged_opt.get_or_insert_with(PrfOption::default).with_proxy = Some(false);
|
crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| {
|
||||||
|
let mut options = merged_opt.clone();
|
||||||
match PrfItem::from_url(url, None, None, merged_opt.as_ref()).await {
|
async move {
|
||||||
Ok(mut item) => {
|
let (name, success, failure) = match strategy {
|
||||||
logging!(info, Type::Config, "[订阅更新] 使用 Clash代理 更新订阅配置成功");
|
Strategy::Configured => (
|
||||||
|
"configured",
|
||||||
|
"[订阅更新] 更新订阅配置成功",
|
||||||
|
"[订阅更新] 直接更新失败: {},尝试使用Clash代理更新",
|
||||||
|
),
|
||||||
|
Strategy::Clash => (
|
||||||
|
"clash",
|
||||||
|
"[订阅更新] 使用 Clash代理 更新订阅配置成功",
|
||||||
|
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
|
||||||
|
),
|
||||||
|
Strategy::System => (
|
||||||
|
"system",
|
||||||
|
"[订阅更新] 使用 系统代理 更新订阅配置成功",
|
||||||
|
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
|
||||||
|
),
|
||||||
|
};
|
||||||
|
match strategy {
|
||||||
|
Strategy::Configured => {}
|
||||||
|
Strategy::Clash | Strategy::System => {
|
||||||
|
let option = options.get_or_insert_with(PrfOption::default);
|
||||||
|
option.self_proxy = Some(matches!(strategy, Strategy::Clash));
|
||||||
|
option.with_proxy = Some(matches!(strategy, Strategy::System));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tracing::Span::current().record("strategy", name);
|
||||||
|
let started = std::time::Instant::now();
|
||||||
|
let result = PrfItem::from_url(url, None, None, options.as_ref()).await;
|
||||||
|
let elapsed_field = match strategy {
|
||||||
|
Strategy::Configured => "configured_elapsed",
|
||||||
|
Strategy::Clash => "clash_elapsed",
|
||||||
|
Strategy::System => "system_elapsed",
|
||||||
|
};
|
||||||
|
tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed()));
|
||||||
|
match &result {
|
||||||
|
Ok(_) => logging!(info, Type::Config, "{success}"),
|
||||||
|
Err(error) => logging!(
|
||||||
|
warn,
|
||||||
|
Type::Config,
|
||||||
|
"{}",
|
||||||
|
failure.replace("{}", &mask_err(&format!("{error:#}")))
|
||||||
|
),
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let last_err = match result {
|
||||||
|
Ok((strategy, mut item)) => {
|
||||||
|
// A persistence error must not replay a successful download with another transport.
|
||||||
profiles_update_item_safe(uid, &mut item).await?;
|
profiles_update_item_safe(uid, &mut item).await?;
|
||||||
handle::Handle::notice_message("update_with_clash_proxy", profile_name);
|
if !matches!(strategy, Strategy::Configured) {
|
||||||
|
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str());
|
||||||
|
}
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(error) => error,
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Config,
|
|
||||||
"[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新",
|
|
||||||
mask_err(&format!("{err:#}"))
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
merged_opt.get_or_insert_with(PrfOption::default).self_proxy = Some(false);
|
|
||||||
merged_opt.get_or_insert_with(PrfOption::default).with_proxy = Some(true);
|
|
||||||
|
|
||||||
let last_err = match PrfItem::from_url(url, None, None, merged_opt.as_ref()).await {
|
|
||||||
Ok(mut item) => {
|
|
||||||
logging!(info, Type::Config, "[订阅更新] 使用 系统代理 更新订阅配置成功");
|
|
||||||
profiles_update_item_safe(uid, &mut item).await?;
|
|
||||||
handle::Handle::notice_message("update_with_clash_proxy", profile_name);
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
logging!(
|
|
||||||
warn,
|
|
||||||
Type::Config,
|
|
||||||
"[订阅更新] 系统代理更新失败: {},所有重试均已失败",
|
|
||||||
mask_err(&format!("{err:#}"))
|
|
||||||
);
|
|
||||||
err
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let last_err = mask_err(&last_err.to_string());
|
let last_err = mask_err(&last_err.to_string());
|
||||||
if is_mannual_trigger {
|
if is_mannual_trigger {
|
||||||
handle::Handle::notice_message("update_failed_even_with_clash", format!("{profile_name} - {last_err}"));
|
handle::Handle::notice(
|
||||||
|
NoticeStatus::UpdateFailedEvenWithClash,
|
||||||
|
format!("{profile_name} - {last_err}"),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
bail!(last_err)
|
bail!(last_err)
|
||||||
}
|
}
|
||||||
@@ -201,7 +219,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
|
|||||||
match CoreManager::global().update_config_with_force(is_mannual_trigger).await {
|
match CoreManager::global().update_config_with_force(is_mannual_trigger).await {
|
||||||
Ok(outcome) if outcome.is_valid() => {
|
Ok(outcome) if outcome.is_valid() => {
|
||||||
logging_error!(Type::Config, Config::sync_dns_override().await);
|
logging_error!(Type::Config, Config::sync_dns_override().await);
|
||||||
handle::Handle::refresh_clash();
|
announce(Refresh::Clash);
|
||||||
}
|
}
|
||||||
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => {
|
Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => {
|
||||||
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
|
logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome);
|
||||||
@@ -218,7 +236,7 @@ pub async fn update_profile(uid: &String, option: Option<&PrfOption>, is_mannual
|
|||||||
message
|
message
|
||||||
};
|
};
|
||||||
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
|
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
|
||||||
handle::Handle::notice_message("update_failed", &message);
|
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
|
||||||
bail!(message);
|
bail!(message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::core::notify::{Refresh, announce};
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IVerge, MixedPort},
|
config::{Config, IVerge, MixedPort},
|
||||||
core::{
|
core::{
|
||||||
@@ -83,7 +84,7 @@ pub async fn toggle_tun_mode(not_save_file: Option<bool>) -> bool {
|
|||||||
.await
|
.await
|
||||||
{
|
{
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
handle::Handle::refresh_verge();
|
announce(Refresh::Verge);
|
||||||
// Reconciliation may immediately disable unavailable TUN; report the resulting state.
|
// Reconciliation may immediately disable unavailable TUN; report the resulting state.
|
||||||
Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|
Config::verge().await.latest_arc().enable_tun_mode.unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
//! Reconciles TUN with current Core and Service availability.
|
//! Reconciles TUN with current Core and Service availability.
|
||||||
|
|
||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
@@ -75,10 +77,10 @@ pub async fn reconcile_tun_availability() {
|
|||||||
|
|
||||||
// Skip recursive reconciliation for this internal patch.
|
// Skip recursive reconciliation for this internal patch.
|
||||||
match super::apply_verge_patch_locked(&config_write, &patch, false).await {
|
match super::apply_verge_patch_locked(&config_write, &patch, false).await {
|
||||||
Ok(()) => Handle::notice_message("tun_mode::auto_disabled", ""),
|
Ok(()) => Handle::notice(NoticeStatus::TunModeAutoDisabled, ""),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
logging!(error, Type::Core, "failed to turn TUN mode off: {error:#}");
|
logging!(error, Type::Core, "failed to turn TUN mode off: {error:#}");
|
||||||
Handle::notice_message("tun_mode::auto_disable_failed", "");
|
Handle::notice(NoticeStatus::TunModeAutoDisableFailed, "");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
use crate::config::Config;
|
use crate::config::Config;
|
||||||
|
use crate::core::lightweight;
|
||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::core::{CoreManager, handle};
|
use crate::core::{CoreManager, handle};
|
||||||
use crate::module::lightweight;
|
|
||||||
use crate::utils;
|
use crate::utils;
|
||||||
use crate::utils::window_manager::WindowManager;
|
use crate::utils::window_manager::WindowManager;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
@@ -128,8 +129,8 @@ pub async fn quit() -> clash_verge_signal::ShutdownOutcome {
|
|||||||
|
|
||||||
if should_abort_exit_after_cleanup(cleanup_result.core_stopped) {
|
if should_abort_exit_after_cleanup(cleanup_result.core_stopped) {
|
||||||
handle::Handle::global().clear_is_exiting();
|
handle::Handle::global().clear_is_exiting();
|
||||||
handle::Handle::notice_message(
|
handle::Handle::notice(
|
||||||
"app_quit::core_stop_failed",
|
NoticeStatus::AppQuitCoreStopFailed,
|
||||||
cleanup_result.stop_error.unwrap_or_default(),
|
cleanup_result.stop_error.unwrap_or_default(),
|
||||||
);
|
);
|
||||||
return clash_verge_signal::ShutdownOutcome::Canceled;
|
return clash_verge_signal::ShutdownOutcome::Canceled;
|
||||||
@@ -230,7 +231,7 @@ pub async fn clean_session_ending_best_effort() -> CleanupResult {
|
|||||||
|
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
pub async fn hide() {
|
pub async fn hide() {
|
||||||
use crate::module::lightweight::add_light_weight_timer;
|
use crate::core::lightweight::add_light_weight_timer;
|
||||||
|
|
||||||
let enable_auto_light_weight_mode = Config::verge()
|
let enable_auto_light_weight_mode = Config::verge()
|
||||||
.await
|
.await
|
||||||
|
|||||||
+21
-6
@@ -7,7 +7,6 @@ mod constants;
|
|||||||
mod core;
|
mod core;
|
||||||
mod enhance;
|
mod enhance;
|
||||||
mod feat;
|
mod feat;
|
||||||
mod module;
|
|
||||||
mod process;
|
mod process;
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
|
|
||||||
@@ -19,13 +18,17 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use once_cell::sync::OnceCell;
|
use std::sync::OnceLock;
|
||||||
use tauri::{AppHandle, Manager as _};
|
use tauri::{AppHandle, Manager as _};
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
use tauri_plugin_autostart::MacosLauncher;
|
use tauri_plugin_autostart::MacosLauncher;
|
||||||
use tauri_plugin_deep_link::DeepLinkExt as _;
|
use tauri_plugin_deep_link::DeepLinkExt as _;
|
||||||
|
|
||||||
pub static APP_HANDLE: OnceCell<AppHandle> = OnceCell::new();
|
pub static APP_HANDLE: OnceLock<AppHandle> = OnceLock::new();
|
||||||
|
|
||||||
|
// Re-exported for src/bin/frontend-contract.rs; the wire contract stays owned
|
||||||
|
// by core::notify.
|
||||||
|
pub use crate::core::notify::frontend_wire_contract;
|
||||||
/// Application initialization helper functions
|
/// Application initialization helper functions
|
||||||
mod app_init {
|
mod app_init {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -44,7 +47,14 @@ mod app_init {
|
|||||||
let mut builder = builder
|
let mut builder = builder
|
||||||
.plugin(tauri_plugin_clash_verge_sysinfo::init())
|
.plugin(tauri_plugin_clash_verge_sysinfo::init())
|
||||||
.plugin(tauri_plugin_notification::init())
|
.plugin(tauri_plugin_notification::init())
|
||||||
.plugin(tauri_plugin_updater::Builder::new().build())
|
.plugin(
|
||||||
|
tauri_plugin_updater::Builder::new()
|
||||||
|
.default_version_comparator(|current, release| {
|
||||||
|
release.version > current
|
||||||
|
|| core::updater::is_build_to_stable(¤t.to_string(), &release.version.to_string())
|
||||||
|
})
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
.plugin(tauri_plugin_clipboard_manager::init())
|
.plugin(tauri_plugin_clipboard_manager::init())
|
||||||
.plugin(tauri_plugin_process::init())
|
.plugin(tauri_plugin_process::init())
|
||||||
.plugin(tauri_plugin_global_shortcut::Builder::new().build())
|
.plugin(tauri_plugin_global_shortcut::Builder::new().build())
|
||||||
@@ -163,6 +173,11 @@ mod app_init {
|
|||||||
cmd::apply_dns_config,
|
cmd::apply_dns_config,
|
||||||
cmd::set_dns_override,
|
cmd::set_dns_override,
|
||||||
cmd::take_dns_override_notice,
|
cmd::take_dns_override_notice,
|
||||||
|
cmd::take_service_fallback_notice,
|
||||||
|
cmd::get_core_startup_error,
|
||||||
|
cmd::take_service_repair_notice,
|
||||||
|
cmd::take_service_owner_notice,
|
||||||
|
cmd::take_discarded_keys_notice,
|
||||||
cmd::get_dns_config_content,
|
cmd::get_dns_config_content,
|
||||||
cmd::validate_dns_config,
|
cmd::validate_dns_config,
|
||||||
cmd::get_clash_logs,
|
cmd::get_clash_logs,
|
||||||
@@ -321,7 +336,7 @@ pub fn run() -> std::process::ExitCode {
|
|||||||
|
|
||||||
mod event_handlers {
|
mod event_handlers {
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
use crate::module::lightweight;
|
use crate::core::lightweight;
|
||||||
use crate::utils::window_manager::WindowManager;
|
use crate::utils::window_manager::WindowManager;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::Config,
|
config::Config,
|
||||||
@@ -476,7 +491,7 @@ pub fn run() -> std::process::ExitCode {
|
|||||||
}),
|
}),
|
||||||
#[allow(unused_variables)]
|
#[allow(unused_variables)]
|
||||||
tauri::RunEvent::ExitRequested { api, code, .. } => {
|
tauri::RunEvent::ExitRequested { api, code, .. } => {
|
||||||
if module::lightweight::is_in_lightweight_mode() && !handle::Handle::global().is_exiting() {
|
if core::lightweight::is_in_lightweight_mode() && !handle::Handle::global().is_exiting() {
|
||||||
api.prevent_exit();
|
api.prevent_exit();
|
||||||
} else if code.is_none() {
|
} else if code.is_none() {
|
||||||
api.prevent_exit();
|
api.prevent_exit();
|
||||||
|
|||||||
@@ -1,2 +0,0 @@
|
|||||||
pub mod auto_backup;
|
|
||||||
pub mod lightweight;
|
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::{config::with_encryption, process::AsyncHandler};
|
use crate::{config::with_encryption, process::AsyncHandler};
|
||||||
use anyhow::{Context as _, Result, anyhow, bail};
|
use anyhow::{Context as _, Result, anyhow, bail};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
@@ -16,9 +17,13 @@ pub async fn read_yaml<T: DeserializeOwned>(path: &Path) -> Result<T> {
|
|||||||
bail!("file not found \"{}\"", path.display());
|
bail!("file not found \"{}\"", path.display());
|
||||||
}
|
}
|
||||||
|
|
||||||
let yaml_str = tokio::fs::read_to_string(path).await?;
|
let yaml_str = tokio::fs::read_to_string(path)
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("failed to read YAML file {}", path.display()))?;
|
||||||
|
|
||||||
Ok(with_encryption(|| async { serde_yaml_ng::from_str::<T>(&yaml_str) }).await?)
|
with_encryption(|| async { serde_yaml_ng::from_str::<T>(&yaml_str) })
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("failed to parse YAML file {}", path.display()))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn read_mapping(path: &Path) -> Result<Mapping> {
|
pub async fn read_mapping(path: &Path) -> Result<Mapping> {
|
||||||
@@ -54,7 +59,7 @@ fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
|
|||||||
let error_msg = format!("YAML syntax error in {}: {}", path.display(), err);
|
let error_msg = format!("YAML syntax error in {}: {}", path.display(), err);
|
||||||
logging!(error, Type::Config, "{}", error_msg);
|
logging!(error, Type::Config, "{}", error_msg);
|
||||||
|
|
||||||
crate::core::handle::Handle::notice_message("config_validate::yaml_syntax_error", &error_msg);
|
crate::core::handle::Handle::notice(NoticeStatus::ConfigValidateYamlSyntaxError, error_msg.as_str());
|
||||||
|
|
||||||
bail!("YAML syntax error: {}", err)
|
bail!("YAML syntax error: {}", err)
|
||||||
}
|
}
|
||||||
|
|||||||
+35
-29
@@ -9,7 +9,7 @@ use crate::{
|
|||||||
help,
|
help,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use anyhow::Result;
|
use anyhow::{Context as _, Result};
|
||||||
use chrono::{Local, TimeZone as _};
|
use chrono::{Local, TimeZone as _};
|
||||||
use clash_verge_logging::Type;
|
use clash_verge_logging::Type;
|
||||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||||
@@ -28,8 +28,15 @@ async fn delete_snapshot_logs(log_dir: &Path) -> Result<()> {
|
|||||||
];
|
];
|
||||||
|
|
||||||
for temp_dir in temp_dirs.iter().filter(|d| d.exists()) {
|
for temp_dir in temp_dirs.iter().filter(|d| d.exists()) {
|
||||||
let mut entries = fs::read_dir(temp_dir).await?;
|
let mut entries = fs::read_dir(temp_dir)
|
||||||
while let Some(entry) = entries.next_entry().await? {
|
.await
|
||||||
|
.with_context(|| format!("failed to read log snapshot directory {}", temp_dir.display()))?;
|
||||||
|
while let Some(entry) = entries.next_entry().await.with_context(|| {
|
||||||
|
format!(
|
||||||
|
"failed to read next entry in log snapshot directory {}",
|
||||||
|
temp_dir.display()
|
||||||
|
)
|
||||||
|
})? {
|
||||||
let path = entry.path();
|
let path = entry.path();
|
||||||
if path.extension().and_then(|s| s.to_str()) == Some("log") {
|
if path.extension().and_then(|s| s.to_str()) == Some("log") {
|
||||||
let _ = path.remove_if_exists().await;
|
let _ = path.remove_if_exists().await;
|
||||||
@@ -109,15 +116,28 @@ pub async fn delete_log() -> Result<()> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
if log_dir.exists() {
|
if log_dir.exists() {
|
||||||
let mut log_read_dir = fs::read_dir(&log_dir).await?;
|
let mut log_read_dir = fs::read_dir(&log_dir)
|
||||||
while let Some(entry) = log_read_dir.next_entry().await? {
|
.await
|
||||||
|
.with_context(|| format!("failed to read log directory {}", log_dir.display()))?;
|
||||||
|
while let Some(entry) = log_read_dir
|
||||||
|
.next_entry()
|
||||||
|
.await
|
||||||
|
.with_context(|| format!("failed to read next entry in log directory {}", log_dir.display()))?
|
||||||
|
{
|
||||||
std::mem::drop(process_file(entry).await);
|
std::mem::drop(process_file(entry).await);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if service_log_dir.exists() {
|
if service_log_dir.exists() {
|
||||||
let mut service_log_read_dir = fs::read_dir(service_log_dir).await?;
|
let mut service_log_read_dir = fs::read_dir(&service_log_dir)
|
||||||
while let Some(entry) = service_log_read_dir.next_entry().await? {
|
.await
|
||||||
|
.with_context(|| format!("failed to read service log directory {}", service_log_dir.display()))?;
|
||||||
|
while let Some(entry) = service_log_read_dir.next_entry().await.with_context(|| {
|
||||||
|
format!(
|
||||||
|
"failed to read next entry in service log directory {}",
|
||||||
|
service_log_dir.display()
|
||||||
|
)
|
||||||
|
})? {
|
||||||
std::mem::drop(process_file(entry).await);
|
std::mem::drop(process_file(entry).await);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -228,27 +248,21 @@ async fn migrate_legacy_macos_service_logs(log_dir: &Path) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Raise existing sub-floor update intervals, once per install.
|
/// Once per install; the marker is written even when no interval needed raising.
|
||||||
///
|
|
||||||
/// One-off repair, not a standing rule — the UI warns about shorter intervals but still saves
|
|
||||||
/// them, so the marker is written even when nothing needed raising.
|
|
||||||
pub async fn migrate_short_update_intervals() -> Result<()> {
|
pub async fn migrate_short_update_intervals() -> Result<()> {
|
||||||
let marker = dirs::update_interval_migrated_path()?;
|
let marker = dirs::update_interval_migrated_path()?;
|
||||||
if fs::try_exists(&marker).await? {
|
if fs::try_exists(&marker).await? {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Same order as every other writer holding it (lock, then draft permit): save_file runs
|
// Same lock order as other writers; saving inside the closure keeps a racing restore intact.
|
||||||
// inside the closure, ahead of the optimistic check, so a racing restore can't be undone.
|
|
||||||
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
|
let _profile_write = crate::config::profiles::PROFILE_WRITE_LOCK.lock().await;
|
||||||
|
|
||||||
let min = constants::profile::MIN_UPDATE_INTERVAL;
|
let min = constants::profile::MIN_UPDATE_INTERVAL;
|
||||||
let raised = Config::profiles()
|
let raised = Config::profiles()
|
||||||
.await
|
.await
|
||||||
.with_data_modify(|mut profiles: IProfiles| async move {
|
.with_data_modify(|mut profiles: IProfiles| async move {
|
||||||
// `IProfiles::new` normalises items to Some when it read the file, and returns a
|
// A failed profiles load (bare default) must not burn the one-shot marker.
|
||||||
// bare default() when it failed. A failed load also raises zero — without this the
|
|
||||||
// marker would burn the one shot on profiles nobody managed to load.
|
|
||||||
if profiles.items.is_none() {
|
if profiles.items.is_none() {
|
||||||
anyhow::bail!("profiles.yaml was not loaded; refusing to record the migration as done");
|
anyhow::bail!("profiles.yaml was not loaded; refusing to record the migration as done");
|
||||||
}
|
}
|
||||||
@@ -370,14 +384,7 @@ pub(super) async fn init_dns_config() -> Result<()> {
|
|||||||
"nameserver-policy".into(),
|
"nameserver-policy".into(),
|
||||||
Value::Mapping(serde_yaml_ng::Mapping::new()),
|
Value::Mapping(serde_yaml_ng::Mapping::new()),
|
||||||
),
|
),
|
||||||
(
|
("proxy-server-nameserver".into(), Value::Sequence(vec![])),
|
||||||
"proxy-server-nameserver".into(),
|
|
||||||
Value::Sequence(vec![
|
|
||||||
Value::String("https://doh.pub/dns-query".into()),
|
|
||||||
Value::String("https://dns.alidns.com/dns-query".into()),
|
|
||||||
Value::String("tls://223.5.5.5".into()),
|
|
||||||
]),
|
|
||||||
),
|
|
||||||
("direct-nameserver".into(), Value::Sequence(vec![])),
|
("direct-nameserver".into(), Value::Sequence(vec![])),
|
||||||
("direct-nameserver-follow-policy".into(), Value::Bool(false)),
|
("direct-nameserver-follow-policy".into(), Value::Bool(false)),
|
||||||
(
|
(
|
||||||
@@ -509,7 +516,7 @@ pub async fn init_resources() -> Result<()> {
|
|||||||
std::mem::drop(fs::create_dir_all(&res_dir).await);
|
std::mem::drop(fs::create_dir_all(&res_dir).await);
|
||||||
}
|
}
|
||||||
|
|
||||||
let file_list = ["Country.mmdb", "geoip.dat", "geosite.dat"];
|
let file_list = ["Country.mmdb", "ASN.mmdb", "geoip.dat", "geosite.dat"];
|
||||||
|
|
||||||
for file in file_list.iter() {
|
for file in file_list.iter() {
|
||||||
let src_path = res_dir.join(file);
|
let src_path = res_dir.join(file);
|
||||||
@@ -637,10 +644,9 @@ async fn handle_copy(src: &PathBuf, dest: &PathBuf, file: &str) {
|
|||||||
logging!(
|
logging!(
|
||||||
error,
|
error,
|
||||||
Type::Setup,
|
Type::Setup,
|
||||||
"failed to copy resources '{}' to '{:?}', {}",
|
"failed to copy resource {} to {}: {err}",
|
||||||
file,
|
src.display(),
|
||||||
dest,
|
dest.display()
|
||||||
err
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user