mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-06 23:00:15 +08:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6ef67718e | ||
|
|
cc074d8967 |
Generated
+63
-64
@@ -381,7 +381,7 @@ dependencies = [
|
|||||||
"dirs 6.0.0",
|
"dirs 6.0.0",
|
||||||
"os_info",
|
"os_info",
|
||||||
"smappservice-rs",
|
"smappservice-rs",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"windows-registry",
|
"windows-registry",
|
||||||
"windows-result 0.4.1",
|
"windows-result 0.4.1",
|
||||||
]
|
]
|
||||||
@@ -664,7 +664,7 @@ dependencies = [
|
|||||||
"tap",
|
"tap",
|
||||||
"temporal_rs",
|
"temporal_rs",
|
||||||
"thin-vec",
|
"thin-vec",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"time",
|
"time",
|
||||||
"timezone_provider",
|
"timezone_provider",
|
||||||
"xsum",
|
"xsum",
|
||||||
@@ -928,7 +928,7 @@ dependencies = [
|
|||||||
"semver 1.0.28",
|
"semver 1.0.28",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -1152,6 +1152,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml_ng",
|
"serde_yaml_ng",
|
||||||
|
"sha2 0.11.2",
|
||||||
"socket2",
|
"socket2",
|
||||||
"specta",
|
"specta",
|
||||||
"specta-typescript",
|
"specta-typescript",
|
||||||
@@ -1193,7 +1194,7 @@ dependencies = [
|
|||||||
name = "clash-verge-backup-archive"
|
name = "clash-verge-backup-archive"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"zip",
|
"zip",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1206,7 +1207,6 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml_ng",
|
"serde_yaml_ng",
|
||||||
"sha2 0.11.2",
|
|
||||||
"tokio",
|
"tokio",
|
||||||
"tristr",
|
"tristr",
|
||||||
]
|
]
|
||||||
@@ -1217,7 +1217,7 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"criterion",
|
"criterion",
|
||||||
"parking_lot 0.13.0",
|
"parking_lot 0.13.0",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1244,7 +1244,7 @@ dependencies = [
|
|||||||
"flexi_logger",
|
"flexi_logger",
|
||||||
"log",
|
"log",
|
||||||
"parking_lot 0.13.0",
|
"parking_lot 0.13.0",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tracing-estuary",
|
"tracing-estuary",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1271,7 +1271,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml_ng",
|
"serde_yaml_ng",
|
||||||
"specta",
|
"specta",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tristr",
|
"tristr",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1306,7 +1306,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"serde_yaml_ng",
|
"serde_yaml_ng",
|
||||||
"sha2 0.11.2",
|
"sha2 0.11.2",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tristr",
|
"tristr",
|
||||||
]
|
]
|
||||||
@@ -1327,7 +1327,7 @@ dependencies = [
|
|||||||
"http",
|
"http",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"serde_yaml_ng",
|
"serde_yaml_ng",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -1338,7 +1338,6 @@ dependencies = [
|
|||||||
"futures",
|
"futures",
|
||||||
"parking_lot 0.13.0",
|
"parking_lot 0.13.0",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-util",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2059,7 +2058,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"prost-types",
|
"prost-types",
|
||||||
"ringbuf",
|
"ringbuf",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-stream",
|
"tokio-stream",
|
||||||
"tonic",
|
"tonic",
|
||||||
@@ -2557,7 +2556,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"nu-ansi-term",
|
"nu-ansi-term",
|
||||||
"regex",
|
"regex",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2617,9 +2616,9 @@ checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "form_urlencoded"
|
name = "form_urlencoded"
|
||||||
version = "1.2.2"
|
version = "1.2.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
]
|
]
|
||||||
@@ -3014,7 +3013,7 @@ dependencies = [
|
|||||||
"objc2-app-kit",
|
"objc2-app-kit",
|
||||||
"once_cell",
|
"once_cell",
|
||||||
"serde",
|
"serde",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"windows-sys 0.59.0",
|
"windows-sys 0.59.0",
|
||||||
"x11rb",
|
"x11rb",
|
||||||
"xkeysym",
|
"xkeysym",
|
||||||
@@ -3287,9 +3286,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "http"
|
name = "http"
|
||||||
version = "1.5.0"
|
version = "1.6.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
|
checksum = "a07dc2d082802d1782faa5b3c8ac252f3a4fc89f51e76c3f37dc2d1a5b857c05"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"itoa",
|
"itoa",
|
||||||
@@ -3884,7 +3883,7 @@ dependencies = [
|
|||||||
"jni-sys 0.4.1",
|
"jni-sys 0.4.1",
|
||||||
"log",
|
"log",
|
||||||
"simd_cesu8",
|
"simd_cesu8",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"walkdir",
|
"walkdir",
|
||||||
"windows-link 0.2.1",
|
"windows-link 0.2.1",
|
||||||
]
|
]
|
||||||
@@ -3960,7 +3959,7 @@ dependencies = [
|
|||||||
"jsonptr",
|
"jsonptr",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -4011,7 +4010,7 @@ dependencies = [
|
|||||||
"rand 0.10.2",
|
"rand 0.10.2",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-stream",
|
"tokio-stream",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
@@ -4400,7 +4399,7 @@ dependencies = [
|
|||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
"png",
|
"png",
|
||||||
"serde",
|
"serde",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -4477,7 +4476,7 @@ dependencies = [
|
|||||||
"cc",
|
"cc",
|
||||||
"libc",
|
"libc",
|
||||||
"serde",
|
"serde",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"winapi",
|
"winapi",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -5059,7 +5058,7 @@ dependencies = [
|
|||||||
"objc2-osa-kit",
|
"objc2-osa-kit",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -5626,7 +5625,7 @@ dependencies = [
|
|||||||
"rustc-hash",
|
"rustc-hash",
|
||||||
"rustls",
|
"rustls",
|
||||||
"socket2",
|
"socket2",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
"web-time",
|
"web-time",
|
||||||
@@ -5649,7 +5648,7 @@ dependencies = [
|
|||||||
"rustls",
|
"rustls",
|
||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
"slab",
|
"slab",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tinyvec",
|
"tinyvec",
|
||||||
"tracing",
|
"tracing",
|
||||||
"web-time",
|
"web-time",
|
||||||
@@ -5847,7 +5846,7 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"getrandom 0.2.17",
|
"getrandom 0.2.17",
|
||||||
"libredox",
|
"libredox",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -6210,9 +6209,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustls"
|
name = "rustls"
|
||||||
version = "0.23.47"
|
version = "0.23.48"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4ac0e747c10d93d873fd4c50b26ef47ad92d1bfb48f6922003bb514070f6e88c"
|
checksum = "86c8de8f13bac4bb046743409c751e2343621c0293a805c143ede57c5c95c3f8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aws-lc-rs",
|
"aws-lc-rs",
|
||||||
"log",
|
"log",
|
||||||
@@ -6872,7 +6871,7 @@ dependencies = [
|
|||||||
"objc2",
|
"objc2",
|
||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
"objc2-service-management",
|
"objc2-service-management",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -7167,7 +7166,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"serde",
|
"serde",
|
||||||
"system-configuration",
|
"system-configuration",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"url",
|
"url",
|
||||||
"which 8.0.5",
|
"which 8.0.5",
|
||||||
@@ -7357,7 +7356,7 @@ dependencies = [
|
|||||||
"tauri-runtime",
|
"tauri-runtime",
|
||||||
"tauri-runtime-wry",
|
"tauri-runtime-wry",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tray-icon",
|
"tray-icon",
|
||||||
@@ -7407,7 +7406,7 @@ dependencies = [
|
|||||||
"sha2 0.11.2",
|
"sha2 0.11.2",
|
||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"uuid",
|
"uuid",
|
||||||
"walkdir",
|
"walkdir",
|
||||||
]
|
]
|
||||||
@@ -7453,7 +7452,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -7482,7 +7481,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -7499,7 +7498,7 @@ dependencies = [
|
|||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
"windows-registry",
|
"windows-registry",
|
||||||
@@ -7547,7 +7546,7 @@ dependencies = [
|
|||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"tauri-plugin-fs",
|
"tauri-plugin-fs",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -7570,7 +7569,7 @@ dependencies = [
|
|||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"toml 1.2.1+spec-1.1.0",
|
"toml 1.2.1+spec-1.1.0",
|
||||||
"url",
|
"url",
|
||||||
]
|
]
|
||||||
@@ -7587,7 +7586,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -7609,7 +7608,7 @@ dependencies = [
|
|||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"tauri-plugin-fs",
|
"tauri-plugin-fs",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"url",
|
"url",
|
||||||
"urlpattern",
|
"urlpattern",
|
||||||
@@ -7632,7 +7631,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-tungstenite",
|
"tokio-tungstenite",
|
||||||
"ts-rs",
|
"ts-rs",
|
||||||
@@ -7654,7 +7653,7 @@ dependencies = [
|
|||||||
"serde_repr",
|
"serde_repr",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"time",
|
"time",
|
||||||
"url",
|
"url",
|
||||||
"zbus",
|
"zbus",
|
||||||
@@ -7676,7 +7675,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"url",
|
"url",
|
||||||
"windows 0.62.2",
|
"windows 0.62.2",
|
||||||
"zbus",
|
"zbus",
|
||||||
@@ -7700,7 +7699,7 @@ dependencies = [
|
|||||||
"shared_child",
|
"shared_child",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"windows-sys 0.60.2",
|
"windows-sys 0.60.2",
|
||||||
]
|
]
|
||||||
@@ -7731,7 +7730,7 @@ dependencies = [
|
|||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"time",
|
"time",
|
||||||
"tokio",
|
"tokio",
|
||||||
"url",
|
"url",
|
||||||
@@ -7762,7 +7761,7 @@ dependencies = [
|
|||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
"uuid",
|
"uuid",
|
||||||
@@ -7784,7 +7783,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-plugin",
|
"tauri-plugin",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -7805,7 +7804,7 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tauri-utils",
|
"tauri-utils",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"url",
|
"url",
|
||||||
"webkit2gtk",
|
"webkit2gtk",
|
||||||
"webview2-com",
|
"webview2-com",
|
||||||
@@ -7854,7 +7853,7 @@ dependencies = [
|
|||||||
"specta-util",
|
"specta-util",
|
||||||
"tauri",
|
"tauri",
|
||||||
"tauri-specta-macros",
|
"tauri-specta-macros",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -7900,7 +7899,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_with",
|
"serde_with",
|
||||||
"swift-rs",
|
"swift-rs",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"toml 1.2.1+spec-1.1.0",
|
"toml 1.2.1+spec-1.1.0",
|
||||||
"url",
|
"url",
|
||||||
"urlpattern",
|
"urlpattern",
|
||||||
@@ -7925,7 +7924,7 @@ version = "0.7.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade"
|
checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"windows 0.61.3",
|
"windows 0.61.3",
|
||||||
"windows-version",
|
"windows-version",
|
||||||
]
|
]
|
||||||
@@ -8049,11 +8048,11 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "thiserror"
|
name = "thiserror"
|
||||||
version = "2.0.20"
|
version = "2.0.21"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
|
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"thiserror-impl 2.0.20",
|
"thiserror-impl 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -8069,9 +8068,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "thiserror-impl"
|
name = "thiserror-impl"
|
||||||
version = "2.0.20"
|
version = "2.0.21"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af"
|
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -8583,7 +8582,7 @@ dependencies = [
|
|||||||
"objc2-foundation",
|
"objc2-foundation",
|
||||||
"png",
|
"png",
|
||||||
"serde",
|
"serde",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -8637,7 +8636,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8"
|
checksum = "756050066659291d47a554a9f558125db17428b073c5ffce1daf5dcb0f7231d8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"ts-rs-macros",
|
"ts-rs-macros",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -8666,7 +8665,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"rand 0.9.5",
|
"rand 0.9.5",
|
||||||
"sha1 0.10.7",
|
"sha1 0.10.7",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"utf-8",
|
"utf-8",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -8759,9 +8758,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "url"
|
name = "url"
|
||||||
version = "2.5.8"
|
version = "2.5.9"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"form_urlencoded",
|
"form_urlencoded",
|
||||||
"idna",
|
"idna",
|
||||||
@@ -9199,7 +9198,7 @@ version = "0.39.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb"
|
checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"windows 0.62.2",
|
"windows 0.62.2",
|
||||||
"windows-core 0.62.2",
|
"windows-core 0.62.2",
|
||||||
]
|
]
|
||||||
@@ -10063,7 +10062,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"os_pipe",
|
"os_pipe",
|
||||||
"rustix 1.1.4",
|
"rustix 1.1.4",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tree_magic_mini",
|
"tree_magic_mini",
|
||||||
"wayland-backend",
|
"wayland-backend",
|
||||||
"wayland-client",
|
"wayland-client",
|
||||||
@@ -10115,7 +10114,7 @@ dependencies = [
|
|||||||
"sha2 0.11.2",
|
"sha2 0.11.2",
|
||||||
"soup3",
|
"soup3",
|
||||||
"tao-macros",
|
"tao-macros",
|
||||||
"thiserror 2.0.20",
|
"thiserror 2.0.21",
|
||||||
"tracing",
|
"tracing",
|
||||||
"url",
|
"url",
|
||||||
"webkit2gtk",
|
"webkit2gtk",
|
||||||
|
|||||||
+1
-2
@@ -83,7 +83,7 @@ tauri = { version = "2.13.0" }
|
|||||||
tauri-plugin-clipboard-manager = "2.5.0"
|
tauri-plugin-clipboard-manager = "2.5.0"
|
||||||
parking_lot = "0.13.0"
|
parking_lot = "0.13.0"
|
||||||
anyhow = "1.0.105"
|
anyhow = "1.0.105"
|
||||||
thiserror = "2.0.20"
|
thiserror = "2.0.21"
|
||||||
zip = "9.9.0"
|
zip = "9.9.0"
|
||||||
boa_engine = "0.22.0"
|
boa_engine = "0.22.0"
|
||||||
futures = "0.3.34"
|
futures = "0.3.34"
|
||||||
@@ -99,7 +99,6 @@ tokio = { version = "1.54.1", features = [
|
|||||||
] }
|
] }
|
||||||
flexi_logger = "0.32.0"
|
flexi_logger = "0.32.0"
|
||||||
log = "0.4.35"
|
log = "0.4.35"
|
||||||
tokio-util = { version = "0.7.20", features = ["time"] }
|
|
||||||
reqwest = { version = "0.13.5", features = [
|
reqwest = { version = "0.13.5", features = [
|
||||||
"json",
|
"json",
|
||||||
"cookies",
|
"cookies",
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ log = { workspace = true }
|
|||||||
serde = { workspace = true, features = ["derive"] }
|
serde = { workspace = true, features = ["derive"] }
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
serde_yaml_ng = { workspace = true }
|
serde_yaml_ng = { workspace = true }
|
||||||
sha2 = { workspace = true }
|
|
||||||
tristr = { workspace = true }
|
tristr = { workspace = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
|||||||
@@ -1,132 +0,0 @@
|
|||||||
use serde_yaml_ng::{Mapping, Value};
|
|
||||||
use sha2::{Digest as _, Sha256};
|
|
||||||
use tristr::alias::String;
|
|
||||||
|
|
||||||
const PROVIDER_DNS_FIELDS: [&str; 3] = [
|
|
||||||
"proxy-server-nameserver",
|
|
||||||
"proxy-server-nameserver-policy",
|
|
||||||
"nameserver-policy",
|
|
||||||
];
|
|
||||||
|
|
||||||
pub fn override_source(profile_uid: &str, config: &Mapping) -> Result<Option<String>, serde_json::Error> {
|
|
||||||
let Some(dns) = config.get("dns").and_then(Value::as_mapping) else {
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
let fields: Mapping = PROVIDER_DNS_FIELDS
|
|
||||||
.iter()
|
|
||||||
.filter_map(|key| {
|
|
||||||
let value = dns.get(*key)?;
|
|
||||||
let nonempty = match value {
|
|
||||||
Value::Sequence(values) => !values.is_empty(),
|
|
||||||
Value::Mapping(values) => !values.is_empty(),
|
|
||||||
Value::String(value) => !value.trim().is_empty(),
|
|
||||||
_ => false,
|
|
||||||
};
|
|
||||||
nonempty.then(|| (Value::from(*key), value.clone()))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
if fields.is_empty() {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut canonical = serde_json::to_value(fields)?;
|
|
||||||
canonical.sort_all_objects();
|
|
||||||
let mut digest = Sha256::new();
|
|
||||||
digest.update(profile_uid.as_bytes());
|
|
||||||
digest.update([0]);
|
|
||||||
digest.update(serde_json::to_vec(&canonical)?);
|
|
||||||
Ok(Some(hex_encode(&digest.finalize()).into()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hex_encode(bytes: &[u8]) -> std::string::String {
|
|
||||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
|
||||||
let mut out = std::string::String::with_capacity(bytes.len() * 2);
|
|
||||||
for &byte in bytes {
|
|
||||||
out.push(HEX[usize::from(byte >> 4)] as char);
|
|
||||||
out.push(HEX[usize::from(byte & 0x0f)] as char);
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
// Without the placeholder, a LAN resolver is reached outside TUN and fake-ip is bypassed.
|
|
||||||
pub fn needs_public_dns(config: &Mapping) -> bool {
|
|
||||||
let section = |name: &str| config.get(name).and_then(Value::as_mapping);
|
|
||||||
let enabled = |name: &str| {
|
|
||||||
section(name)
|
|
||||||
.and_then(|map| map.get("enable"))
|
|
||||||
.and_then(Value::as_bool)
|
|
||||||
.unwrap_or(false)
|
|
||||||
};
|
|
||||||
enabled("tun")
|
|
||||||
&& enabled("dns")
|
|
||||||
&& section("dns")
|
|
||||||
.and_then(|dns| dns.get("enhanced-mode"))
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
== Some("fake-ip")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[allow(clippy::expect_used)]
|
|
||||||
mod tests {
|
|
||||||
use super::{needs_public_dns, override_source};
|
|
||||||
use serde_yaml_ng::Mapping;
|
|
||||||
|
|
||||||
fn mapping(yaml: &str) -> Mapping {
|
|
||||||
serde_yaml_ng::from_str(yaml).expect("valid fixture")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn override_source_detects_each_original_field_but_not_empty_placeholders() -> Result<(), serde_json::Error> {
|
|
||||||
for field in [
|
|
||||||
"proxy-server-nameserver: [https://doh.pub/dns-query]",
|
|
||||||
"proxy-server-nameserver-policy: {'www.yournode.com': '114.114.114.114'}",
|
|
||||||
"nameserver-policy: {'+.quandao.com': ['https://doh.dohcore.com:2096/dns-query/#skip-cert-verify=true']}",
|
|
||||||
] {
|
|
||||||
assert!(override_source("profile", &mapping(&format!("dns: {{{field}}}")))?.is_some());
|
|
||||||
assert!(override_source("profile", &mapping(field))?.is_none());
|
|
||||||
}
|
|
||||||
for yaml in [
|
|
||||||
"{}",
|
|
||||||
"dns: {nameserver: [1.1.1.1]}",
|
|
||||||
"dns: {proxy-server-nameserver: [], proxy-server-nameserver-policy: null, nameserver-policy: {}}",
|
|
||||||
] {
|
|
||||||
assert!(override_source("profile", &mapping(yaml))?.is_none());
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn override_source_ignores_order_and_key_order_but_not_the_profile() -> Result<(), serde_json::Error> {
|
|
||||||
let a = mapping("dns:\n nameserver-policy:\n a.example: 1.1.1.1\n b.example: [8.8.8.8]\n");
|
|
||||||
let b = mapping("dns:\n nameserver-policy:\n b.example: [8.8.8.8]\n a.example: 1.1.1.1\n port: 7890\n");
|
|
||||||
assert_eq!(override_source("one", &a)?, override_source("one", &b)?);
|
|
||||||
assert_ne!(override_source("one", &a)?, override_source("two", &a)?);
|
|
||||||
assert!(override_source("one", &a)?.is_some());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn fake_ip_under_tun_with_dns_needs_public_dns() {
|
|
||||||
assert!(needs_public_dns(&mapping(
|
|
||||||
"tun: {enable: true}\ndns: {enable: true, enhanced-mode: fake-ip}"
|
|
||||||
)));
|
|
||||||
assert!(!needs_public_dns(&mapping(
|
|
||||||
"tun: {enable: true}\ndns: {enable: true, enhanced-mode: redir-host}"
|
|
||||||
)));
|
|
||||||
assert!(!needs_public_dns(&mapping(
|
|
||||||
"dns: {enable: true, enhanced-mode: fake-ip}"
|
|
||||||
)));
|
|
||||||
assert!(!needs_public_dns(&mapping(
|
|
||||||
"tun: {enable: true}\ndns: {enable: false, enhanced-mode: fake-ip}"
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn override_source_accepts_a_string_field_only_when_it_has_content() -> Result<(), serde_json::Error> {
|
|
||||||
let config = mapping("dns: {proxy-server-nameserver: ' 1.1.1.1 '}");
|
|
||||||
assert!(override_source("profile", &config)?.is_some());
|
|
||||||
let config = mapping("dns: {nameserver-policy: ' '}");
|
|
||||||
assert!(override_source("profile", &config)?.is_none());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +1,10 @@
|
|||||||
mod dns;
|
|
||||||
mod field;
|
mod field;
|
||||||
mod merge;
|
mod merge;
|
||||||
mod script;
|
mod script;
|
||||||
mod seq;
|
mod seq;
|
||||||
mod tun;
|
mod tun;
|
||||||
mod tunnels;
|
|
||||||
mod yaml;
|
|
||||||
|
|
||||||
pub use dns::{needs_public_dns, override_source};
|
|
||||||
pub use seq::SeqMap;
|
pub use seq::SeqMap;
|
||||||
pub use tunnels::sanitize_tunnels_proxy;
|
|
||||||
pub use yaml::{parse_short_id_safe, serialize_for_export};
|
|
||||||
|
|
||||||
use self::{
|
use self::{
|
||||||
field::{lowercase_config_keys, use_lowercase, use_sort},
|
field::{lowercase_config_keys, use_lowercase, use_sort},
|
||||||
|
|||||||
@@ -1,120 +0,0 @@
|
|||||||
use serde_yaml_ng::{Mapping, Value};
|
|
||||||
use std::collections::HashSet;
|
|
||||||
use tristr::alias::String;
|
|
||||||
|
|
||||||
pub fn sanitize_tunnels_proxy(config: &mut Mapping) {
|
|
||||||
if !config
|
|
||||||
.get("tunnels")
|
|
||||||
.and_then(|v| v.as_sequence())
|
|
||||||
.is_some_and(|t| tunnels_need_validation(t))
|
|
||||||
{
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut valid: HashSet<String> = HashSet::with_capacity(64);
|
|
||||||
collect_names(config, "proxies", &mut valid);
|
|
||||||
collect_names(config, "proxy-groups", &mut valid);
|
|
||||||
|
|
||||||
valid.insert("DIRECT".into());
|
|
||||||
valid.insert("REJECT".into());
|
|
||||||
|
|
||||||
let Some(tunnels) = config.get_mut("tunnels").and_then(|v| v.as_sequence_mut()) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
for item in tunnels {
|
|
||||||
let Some(tunnel) = item.as_mapping_mut() else { continue };
|
|
||||||
|
|
||||||
let Some(proxy_name) = tunnel.get("proxy").and_then(|v| v.as_str()) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
|
|
||||||
if proxy_name == "DIRECT" || proxy_name == "REJECT" {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if !valid.contains(proxy_name) {
|
|
||||||
tunnel.remove("proxy");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tunnels_need_validation(tunnels: &[Value]) -> bool {
|
|
||||||
tunnels.iter().any(|item| {
|
|
||||||
item.as_mapping()
|
|
||||||
.and_then(|t| t.get("proxy"))
|
|
||||||
.and_then(|p| p.as_str())
|
|
||||||
.is_some_and(|name| name != "DIRECT" && name != "REJECT")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collect_names(config: &Mapping, list_key: &str, out: &mut HashSet<String>) {
|
|
||||||
let Some(Value::Sequence(seq)) = config.get(list_key) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
for item in seq {
|
|
||||||
let Value::Mapping(map) = item else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if let Some(Value::String(n)) = map.get("name")
|
|
||||||
&& !n.is_empty()
|
|
||||||
{
|
|
||||||
out.insert(n.into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[allow(clippy::expect_used)]
|
|
||||||
mod tests {
|
|
||||||
use super::sanitize_tunnels_proxy;
|
|
||||||
use serde_yaml_ng::Mapping;
|
|
||||||
|
|
||||||
fn mapping(yaml: &str) -> Mapping {
|
|
||||||
serde_yaml_ng::from_str(yaml).expect("valid fixture")
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tunnels_reference_only_existing_proxies_or_builtin_names() {
|
|
||||||
let mut config = mapping(
|
|
||||||
"proxies: [{name: a}]\nproxy-groups: [{name: b}]\ntunnels: [{proxy: a}, {proxy: b}, {proxy: DIRECT}, {proxy: REJECT}, {proxy: missing}]",
|
|
||||||
);
|
|
||||||
sanitize_tunnels_proxy(&mut config);
|
|
||||||
let tunnels = config["tunnels"].as_sequence().expect("sequence");
|
|
||||||
assert_eq!(tunnels[0]["proxy"], "a");
|
|
||||||
assert_eq!(tunnels[1]["proxy"], "b");
|
|
||||||
assert_eq!(tunnels[3]["proxy"], "REJECT");
|
|
||||||
assert!(tunnels[4].get("proxy").is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn non_string_proxy_fields_are_left_alone() {
|
|
||||||
let mut config = mapping("proxies: [{name: a}]\ntunnels: [{proxy: 1}, {proxy: true}, {proxy: [a]}]");
|
|
||||||
sanitize_tunnels_proxy(&mut config);
|
|
||||||
assert_eq!(config["tunnels"][0]["proxy"], 1);
|
|
||||||
assert_eq!(config["tunnels"][1]["proxy"], true);
|
|
||||||
assert!(config["tunnels"][2]["proxy"].is_sequence());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tunnels_without_named_proxies_are_left_alone() {
|
|
||||||
let mut config = mapping("proxies: [{name: a}]\ntunnels: [{proxy: DIRECT}, {network: [tcp]}]");
|
|
||||||
sanitize_tunnels_proxy(&mut config);
|
|
||||||
assert_eq!(
|
|
||||||
config["tunnels"],
|
|
||||||
mapping("tunnels: [{proxy: DIRECT}, {network: [tcp]}]")["tunnels"]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn names_come_only_from_mapping_items_with_non_empty_string_name() {
|
|
||||||
let mut config = mapping(
|
|
||||||
"proxies: [{name: ''}, 7, {name: a}]\nproxy-groups: not-a-list\ntunnels: [7, {proxy: a}, {proxy: ''}]",
|
|
||||||
);
|
|
||||||
sanitize_tunnels_proxy(&mut config);
|
|
||||||
assert_eq!(config["tunnels"][0], 7);
|
|
||||||
assert_eq!(config["tunnels"][1]["proxy"], "a");
|
|
||||||
assert!(config["tunnels"][2].get("proxy").is_none());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,262 +0,0 @@
|
|||||||
use clash_verge_logging::{Type, logging};
|
|
||||||
use serde::Serialize;
|
|
||||||
use serde_yaml_ng::Value;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
/// A float like `1234e123` loses its hex text, so retry with short-ids quoted and keep that only if nothing else changed.
|
|
||||||
pub fn parse_short_id_safe(yaml: &str, path: &Path) -> serde_yaml_ng::Result<Value> {
|
|
||||||
let value = serde_yaml_ng::from_str::<Value>(yaml)?;
|
|
||||||
if !has_numeric_short_id(&value) {
|
|
||||||
return Ok(value);
|
|
||||||
}
|
|
||||||
match serde_yaml_ng::from_str::<Value>("e_short_ids(yaml)) {
|
|
||||||
Ok(quoted) if same_except_short_id(&value, "ed) => Ok(quoted),
|
|
||||||
_ => {
|
|
||||||
logging!(warn, Type::Config, "kept numeric short-id in {}", path.display());
|
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn quote_short_ids(yaml: &str) -> String {
|
|
||||||
let mut quoted = String::with_capacity(yaml.len());
|
|
||||||
let mut rest = yaml;
|
|
||||||
while let Some((head, tail)) = rest.split_once("short-id:") {
|
|
||||||
let (gap, value) = tail.split_at(tail.len() - tail.trim_start_matches([' ', '\t']).len());
|
|
||||||
let (id, after) = value.split_at(value.bytes().take_while(u8::is_ascii_hexdigit).count());
|
|
||||||
quoted.push_str(head);
|
|
||||||
quoted.push_str("short-id:");
|
|
||||||
quoted.push_str(gap);
|
|
||||||
if !id.is_empty() && (after.is_empty() || after.starts_with([' ', '\t', '\r', '\n', ',', '}'])) {
|
|
||||||
quoted.push('"');
|
|
||||||
quoted.push_str(id);
|
|
||||||
quoted.push('"');
|
|
||||||
} else {
|
|
||||||
quoted.push_str(id);
|
|
||||||
}
|
|
||||||
rest = after;
|
|
||||||
}
|
|
||||||
quoted.push_str(rest);
|
|
||||||
quoted
|
|
||||||
}
|
|
||||||
|
|
||||||
fn has_numeric_short_id(value: &Value) -> bool {
|
|
||||||
match value {
|
|
||||||
Value::Mapping(map) => map
|
|
||||||
.iter()
|
|
||||||
.any(|(key, value)| (is_short_id(key) && matches!(value, Value::Number(_))) || has_numeric_short_id(value)),
|
|
||||||
Value::Sequence(seq) => seq.iter().any(has_numeric_short_id),
|
|
||||||
_ => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn same_except_short_id(old: &Value, new: &Value) -> bool {
|
|
||||||
match (old, new) {
|
|
||||||
(Value::Mapping(old), Value::Mapping(new)) => {
|
|
||||||
old.len() == new.len()
|
|
||||||
&& old.iter().zip(new).all(|((key, old), (new_key, new))| {
|
|
||||||
key == new_key
|
|
||||||
&& (same_except_short_id(old, new)
|
|
||||||
|| (is_short_id(key) && matches!((old, new), (Value::Number(_), Value::String(_)))))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
(Value::Sequence(old), Value::Sequence(new)) => {
|
|
||||||
old.len() == new.len() && old.iter().zip(new).all(|(old, new)| same_except_short_id(old, new))
|
|
||||||
}
|
|
||||||
_ => old == new,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_short_id(key: &Value) -> bool {
|
|
||||||
key.as_str() == Some("short-id")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn serialize_for_export<T: Serialize>(data: &T) -> serde_yaml_ng::Result<String> {
|
|
||||||
Ok(quote_fake_ip_filter_wildcards(&serde_yaml_ng::to_string(data)?))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
|
|
||||||
let mut result = String::with_capacity(yaml.len());
|
|
||||||
let mut in_fake_ip_filter = false;
|
|
||||||
let mut fake_ip_filter_indent = 0;
|
|
||||||
|
|
||||||
for line in yaml.lines() {
|
|
||||||
let indent = line.len() - line.trim_start_matches(' ').len();
|
|
||||||
let trimmed = &line[indent..];
|
|
||||||
|
|
||||||
if in_fake_ip_filter && indent <= fake_ip_filter_indent && !trimmed.starts_with("- ") {
|
|
||||||
in_fake_ip_filter = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if !in_fake_ip_filter && trimmed == "fake-ip-filter:" {
|
|
||||||
in_fake_ip_filter = true;
|
|
||||||
fake_ip_filter_indent = indent;
|
|
||||||
}
|
|
||||||
|
|
||||||
if in_fake_ip_filter
|
|
||||||
&& indent >= fake_ip_filter_indent
|
|
||||||
&& let Some(item) = trimmed.strip_prefix("- ")
|
|
||||||
&& needs_quotes(item)
|
|
||||||
{
|
|
||||||
result.push_str(&line[..indent + 2]);
|
|
||||||
push_quoted(&mut result, item);
|
|
||||||
} else {
|
|
||||||
result.push_str(line);
|
|
||||||
}
|
|
||||||
result.push('\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
fn needs_quotes(item: &str) -> bool {
|
|
||||||
!item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.']))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn push_quoted(output: &mut String, item: &str) {
|
|
||||||
output.push('\'');
|
|
||||||
for (index, part) in item.split('\'').enumerate() {
|
|
||||||
if index != 0 {
|
|
||||||
output.push_str("''");
|
|
||||||
}
|
|
||||||
output.push_str(part);
|
|
||||||
}
|
|
||||||
output.push('\'');
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
#[allow(clippy::expect_used)]
|
|
||||||
mod tests {
|
|
||||||
use super::{parse_short_id_safe, serialize_for_export};
|
|
||||||
use serde_yaml_ng::Value;
|
|
||||||
use std::path::Path;
|
|
||||||
|
|
||||||
fn roundtrip(input: &str) -> Value {
|
|
||||||
let value: Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
|
||||||
let output = serialize_for_export(&value).expect("yaml should serialize");
|
|
||||||
let reparsed: Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse");
|
|
||||||
|
|
||||||
assert_eq!(reparsed, value);
|
|
||||||
reparsed
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn quotes_fake_ip_filter_wildcards_without_changing_values() {
|
|
||||||
let input = r#"
|
|
||||||
dns:
|
|
||||||
fake-ip-filter:
|
|
||||||
- "*.lan"
|
|
||||||
- "+.market.xiaomi.com"
|
|
||||||
- ".example.com"
|
|
||||||
- "time.*.com"
|
|
||||||
- "plain.example.com"
|
|
||||||
"#;
|
|
||||||
|
|
||||||
roundtrip(input);
|
|
||||||
|
|
||||||
let value: Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
|
||||||
let output = serialize_for_export(&value).expect("yaml should serialize");
|
|
||||||
|
|
||||||
assert!(output.contains("- '*.lan'"));
|
|
||||||
assert!(output.contains("- '+.market.xiaomi.com'"));
|
|
||||||
assert!(output.contains("- '.example.com'"));
|
|
||||||
assert!(output.contains("- 'time.*.com'"));
|
|
||||||
assert!(output.contains("- plain.example.com"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nested_multiline_strings_roundtrip() {
|
|
||||||
roundtrip(
|
|
||||||
r"
|
|
||||||
items:
|
|
||||||
- name: demo
|
|
||||||
desc: |
|
|
||||||
line1
|
|
||||||
line2
|
|
||||||
",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn short_id_quoting_changing_other_values_is_dropped() {
|
|
||||||
let profile = "\
|
|
||||||
proxies:
|
|
||||||
- name: a
|
|
||||||
reality-opts:
|
|
||||||
short-id: 1234e123
|
|
||||||
note: |
|
|
||||||
short-id: 1234e123
|
|
||||||
";
|
|
||||||
let today = serde_yaml_ng::from_str::<Value>(profile).expect("profile should parse");
|
|
||||||
let value = parse_short_id_safe(profile, Path::new("profile.yaml")).expect("profile should parse");
|
|
||||||
assert_eq!(value, today);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn numeric_short_ids_parse_as_text() {
|
|
||||||
let value =
|
|
||||||
parse_short_id_safe("tunnels: [{short-id: 1234e123}, {short-id: 0e5}]", Path::new("p.yaml")).expect("yaml");
|
|
||||||
let tunnels = value["tunnels"].as_sequence().expect("sequence");
|
|
||||||
assert_eq!(tunnels[0]["short-id"], Value::String("1234e123".into()));
|
|
||||||
assert_eq!(tunnels[1]["short-id"], Value::String("0e5".into()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn already_quoted_short_ids_are_left_alone() {
|
|
||||||
let yaml = "tunnels: [{short-id: \"1234e123\"}]";
|
|
||||||
assert_eq!(
|
|
||||||
parse_short_id_safe(yaml, Path::new("p.yaml")).expect("yaml"),
|
|
||||||
serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn crlf_yaml_still_gets_quoted_wildcards_and_roundtrips() {
|
|
||||||
let yaml =
|
|
||||||
"dns:\r\n fake-ip-filter:\r\n - '*.lan'\r\n - +.market.xiaomi.com\r\n - plain.example.com\r\n";
|
|
||||||
let out = serialize_for_export(&serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")).expect("yaml");
|
|
||||||
assert_eq!(roundtrip(&out), roundtrip(yaml));
|
|
||||||
assert!(out.contains("'+.market.xiaomi.com'"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn unchanged_scalars_beside_a_numeric_short_id_keep_the_quoted_result() {
|
|
||||||
let value = parse_short_id_safe(
|
|
||||||
"proxies:\n - name: a\n reality-opts:\n short-id: 1234e123\n",
|
|
||||||
Path::new("profile.yaml"),
|
|
||||||
)
|
|
||||||
.expect("profile should parse");
|
|
||||||
let proxy = &value["proxies"].as_sequence().expect("sequence")[0];
|
|
||||||
assert_eq!(proxy["name"], Value::String("a".into()));
|
|
||||||
assert_eq!(proxy["reality-opts"]["short-id"], Value::String("1234e123".into()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn wider_whitespace_and_empty_short_ids_do_not_disturb_the_quoting() {
|
|
||||||
let value = parse_short_id_safe(
|
|
||||||
"tunnels:\n - short-id: 1234e123\n - short-id:\t\n - short-id: 0e5\n",
|
|
||||||
Path::new("p.yaml"),
|
|
||||||
)
|
|
||||||
.expect("yaml");
|
|
||||||
let tunnels = value["tunnels"].as_sequence().expect("sequence");
|
|
||||||
assert_eq!(tunnels[0]["short-id"], Value::String("1234e123".into()));
|
|
||||||
assert_eq!(tunnels[1]["short-id"], Value::Null);
|
|
||||||
assert_eq!(tunnels[2]["short-id"], Value::String("0e5".into()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn wildcards_outside_fake_ip_filter_are_left_alone() {
|
|
||||||
let yaml = "\ndns:\n fake-ip-filter:\n - .example.com\n fake-ip-filter-mode: blacklist\nsniffer:\n skip-domain:\n - +.push.apple.com\n";
|
|
||||||
let out = serialize_for_export(&serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")).expect("yaml");
|
|
||||||
assert_eq!(roundtrip(&out), roundtrip(yaml));
|
|
||||||
assert!(out.contains(" - '.example.com'\n"), "{out}");
|
|
||||||
assert!(out.contains(" - +.push.apple.com\n"), "{out}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn quoting_follows_the_block_indentation() {
|
|
||||||
let yaml = "\nwrap:\n dns:\n fake-ip-filter:\n - +.market.xiaomi.com\n";
|
|
||||||
let out = serialize_for_export(&serde_yaml_ng::from_str::<Value>(yaml).expect("yaml")).expect("yaml");
|
|
||||||
assert!(out.contains(" - '+.market.xiaomi.com'\n"), "{out}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,10 +5,10 @@ edition = "2024"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
http = "1"
|
http = "1.6.0"
|
||||||
percent-encoding = "2.3.2"
|
percent-encoding = "2.3.2"
|
||||||
serde_yaml_ng = { workspace = true }
|
serde_yaml_ng = { workspace = true }
|
||||||
url = "2.5"
|
url = "2.5.9"
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ publish = false
|
|||||||
futures = { workspace = true }
|
futures = { workspace = true }
|
||||||
parking_lot = { workspace = true }
|
parking_lot = { workspace = true }
|
||||||
tokio = { workspace = true }
|
tokio = { workspace = true }
|
||||||
tokio-util = { workspace = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tokio = { workspace = true, features = ["test-util"] }
|
tokio = { workspace = true, features = ["test-util"] }
|
||||||
|
|||||||
@@ -3,5 +3,4 @@
|
|||||||
pub mod countdown;
|
pub mod countdown;
|
||||||
pub mod retry;
|
pub mod retry;
|
||||||
pub mod scheduled_task;
|
pub mod scheduled_task;
|
||||||
pub mod timers;
|
|
||||||
pub mod watch_task;
|
pub mod watch_task;
|
||||||
|
|||||||
@@ -1,179 +0,0 @@
|
|||||||
//! Keyed timers whose runs never overlap per key.
|
|
||||||
|
|
||||||
use futures::StreamExt as _;
|
|
||||||
use std::{borrow::Borrow, collections::HashMap, hash::Hash, time::Duration};
|
|
||||||
use tokio_util::time::{DelayQueue, delay_queue::Key};
|
|
||||||
|
|
||||||
/// When a timer fires.
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub struct TimerPlan {
|
|
||||||
/// Delay until the first fire, or until the next fire after the interval changed.
|
|
||||||
pub first_delay: Duration,
|
|
||||||
/// Delay from one finished run to the next fire.
|
|
||||||
pub interval: Duration,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What applying a schedule changed, removals first.
|
|
||||||
#[derive(Debug, PartialEq, Eq)]
|
|
||||||
pub enum TimerChange<K> {
|
|
||||||
/// Removed while its run was in flight; dropped once the run reports back.
|
|
||||||
Retired(K),
|
|
||||||
Removed(K),
|
|
||||||
Added(K),
|
|
||||||
Updated(K),
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TaskState {
|
|
||||||
key: Option<Key>,
|
|
||||||
interval: Duration,
|
|
||||||
running: bool,
|
|
||||||
/// Disabled mid-update. Entry outlives removal so re-enabling reuses the `running` guard
|
|
||||||
/// instead of building a fresh state that would fire a second update at zero delay.
|
|
||||||
retired: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One timer per key. A key whose run is in flight does not fire again until it reports back.
|
|
||||||
pub struct KeyedTimers<K> {
|
|
||||||
queue: DelayQueue<K>,
|
|
||||||
tasks: HashMap<K, TaskState>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<K: Eq + Hash + Clone> Default for KeyedTimers<K> {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<K: Eq + Hash + Clone> KeyedTimers<K> {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
queue: DelayQueue::new(),
|
|
||||||
tasks: HashMap::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Forgets every timer; a run still in flight reports back to nothing.
|
|
||||||
pub fn clear(&mut self) {
|
|
||||||
self.queue = DelayQueue::new();
|
|
||||||
self.tasks.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Replaces the schedule. Timers that stay keep their next fire unless their interval
|
|
||||||
/// changed: an idle timer then restarts from the new plan's `first_delay`, while one whose
|
|
||||||
/// run is in flight is re-armed with the new interval by `finish`.
|
|
||||||
pub fn apply(&mut self, schedule: HashMap<K, TimerPlan>) -> Vec<TimerChange<K>> {
|
|
||||||
let Self { queue, tasks } = self;
|
|
||||||
let mut changes = Vec::new();
|
|
||||||
|
|
||||||
tasks.retain(|key, state| {
|
|
||||||
if schedule.contains_key(key) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(entry) = state.key.take() {
|
|
||||||
queue.remove(&entry);
|
|
||||||
}
|
|
||||||
|
|
||||||
if state.running {
|
|
||||||
state.retired = true;
|
|
||||||
changes.push(TimerChange::Retired(key.clone()));
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
changes.push(TimerChange::Removed(key.clone()));
|
|
||||||
false
|
|
||||||
});
|
|
||||||
|
|
||||||
for (key, plan) in schedule {
|
|
||||||
match tasks.get_mut(&key) {
|
|
||||||
None => {
|
|
||||||
let entry = queue.insert(key.clone(), plan.first_delay);
|
|
||||||
tasks.insert(
|
|
||||||
key.clone(),
|
|
||||||
TaskState {
|
|
||||||
key: Some(entry),
|
|
||||||
interval: plan.interval,
|
|
||||||
running: false,
|
|
||||||
retired: false,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
changes.push(TimerChange::Added(key));
|
|
||||||
}
|
|
||||||
Some(state) => {
|
|
||||||
// Re-enabled before retirement took effect; finish re-arms it.
|
|
||||||
state.retired = false;
|
|
||||||
|
|
||||||
if state.interval == plan.interval {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
state.interval = plan.interval;
|
|
||||||
|
|
||||||
if let Some(entry) = state.key.as_ref() {
|
|
||||||
queue.reset(entry, plan.first_delay);
|
|
||||||
} else if !state.running {
|
|
||||||
state.key = Some(queue.insert(key.clone(), plan.first_delay));
|
|
||||||
}
|
|
||||||
|
|
||||||
changes.push(TimerChange::Updated(key));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
changes
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolves with the next due key, or `None` once the queue is empty.
|
|
||||||
pub async fn next_expired(&mut self) -> Option<K> {
|
|
||||||
self.queue.next().await.map(|expired| expired.into_inner())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Marks the key running; `false` when the key is unknown or a run is already in flight.
|
|
||||||
/// Only a key that `next_expired` returned may be started: starting any other key forgets
|
|
||||||
/// its queue handle and leaves the entry armed.
|
|
||||||
pub fn start(&mut self, key: &K) -> bool {
|
|
||||||
let Some(state) = self.tasks.get_mut(key) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
state.key = None;
|
|
||||||
if state.running {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
state.running = true;
|
|
||||||
true
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reports that the run finished and re-arms the timer. Returns `true` when the timer was
|
|
||||||
/// retired meanwhile and is now dropped.
|
|
||||||
pub fn finish(&mut self, key: &K) -> bool {
|
|
||||||
let Some(state) = self.tasks.get_mut(key) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
state.running = false;
|
|
||||||
|
|
||||||
if state.retired {
|
|
||||||
self.tasks.remove(key);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
|
|
||||||
// counting from it would retry at zero delay and spin.
|
|
||||||
state.key = Some(self.queue.insert(key.clone(), state.interval));
|
|
||||||
false
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The interval of a timer that is not retired, running or not; `None` for an unknown or
|
|
||||||
/// retired key. Takes any borrowed form of the key, so a `&str` lookup needs no owned key.
|
|
||||||
pub fn interval<Q>(&self, key: &Q) -> Option<Duration>
|
|
||||||
where
|
|
||||||
K: Borrow<Q>,
|
|
||||||
Q: Eq + Hash + ?Sized,
|
|
||||||
{
|
|
||||||
self.tasks
|
|
||||||
.get(key)
|
|
||||||
.filter(|state| !state.retired)
|
|
||||||
.map(|state| state.interval)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,225 +0,0 @@
|
|||||||
use clash_verge_task::timers::{KeyedTimers, TimerChange, TimerPlan};
|
|
||||||
use std::{collections::HashMap, task::Poll, time::Duration};
|
|
||||||
|
|
||||||
const MINUTE: Duration = Duration::from_secs(60);
|
|
||||||
|
|
||||||
const fn plan(first_delay: Duration, interval: Duration) -> TimerPlan {
|
|
||||||
TimerPlan { first_delay, interval }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Polled, not awaited: a not-yet-due entry would park the test on the paused clock.
|
|
||||||
async fn take_expired(timers: &mut KeyedTimers<String>) -> Option<String> {
|
|
||||||
match futures::poll!(Box::pin(timers.next_expired())) {
|
|
||||||
Poll::Ready(Some(key)) => Some(key),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Empty queue reports `Ready(None)`, not `Pending`, so both count as "nothing due".
|
|
||||||
async fn nothing_due(timers: &mut KeyedTimers<String>) -> bool {
|
|
||||||
matches!(
|
|
||||||
futures::poll!(Box::pin(timers.next_expired())),
|
|
||||||
Poll::Pending | Poll::Ready(None)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn queue_fires_at_the_remaining_time_then_waits_a_whole_interval() {
|
|
||||||
let mut timers = KeyedTimers::new();
|
|
||||||
// 1439min into a 1440min interval: due in a minute, not a day.
|
|
||||||
timers.apply(HashMap::from([("remote".to_owned(), plan(MINUTE, 1440 * MINUTE))]));
|
|
||||||
|
|
||||||
tokio::time::advance(Duration::from_secs(61)).await;
|
|
||||||
assert_eq!(
|
|
||||||
take_expired(&mut timers).await.as_deref(),
|
|
||||||
Some("remote"),
|
|
||||||
"the raised interval must fire one minute in, not a full day in"
|
|
||||||
);
|
|
||||||
|
|
||||||
// After it reports back, the next one is a whole interval away.
|
|
||||||
assert!(timers.start(&"remote".to_owned()));
|
|
||||||
assert!(!timers.finish(&"remote".to_owned()));
|
|
||||||
|
|
||||||
tokio::time::advance(Duration::from_secs(1439 * 60)).await;
|
|
||||||
assert!(
|
|
||||||
nothing_due(&mut timers).await,
|
|
||||||
"a finished task waits the whole interval, not the remainder of the old one"
|
|
||||||
);
|
|
||||||
|
|
||||||
tokio::time::advance(Duration::from_secs(120)).await;
|
|
||||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("remote"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn disabling_a_profile_mid_update_cannot_start_a_second_one() {
|
|
||||||
let mut timers = KeyedTimers::new();
|
|
||||||
// Overdue: every re-insert would land at zero delay.
|
|
||||||
let overdue = || plan(Duration::ZERO, 60 * MINUTE);
|
|
||||||
|
|
||||||
timers.apply(HashMap::from([("local".to_owned(), overdue())]));
|
|
||||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("local"));
|
|
||||||
assert!(timers.start(&"local".to_owned()));
|
|
||||||
|
|
||||||
// Toggled off then on while the run is still in flight.
|
|
||||||
assert_eq!(
|
|
||||||
timers.apply(HashMap::new()),
|
|
||||||
vec![TimerChange::Retired("local".to_owned())]
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
timers
|
|
||||||
.apply(HashMap::from([("local".to_owned(), overdue())]))
|
|
||||||
.is_empty(),
|
|
||||||
"the entry must survive the toggle so the in-flight run is still accounted for"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
!timers.start(&"local".to_owned()),
|
|
||||||
"a second run while the first is in flight is refused"
|
|
||||||
);
|
|
||||||
assert!(
|
|
||||||
nothing_due(&mut timers).await,
|
|
||||||
"re-enabling must not queue a second run alongside the one already going"
|
|
||||||
);
|
|
||||||
|
|
||||||
// Original run reports back, re-arms exactly once.
|
|
||||||
assert!(!timers.finish(&"local".to_owned()));
|
|
||||||
tokio::time::advance(Duration::from_secs(3601)).await;
|
|
||||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("local"));
|
|
||||||
assert!(nothing_due(&mut timers).await, "exactly one key, no orphan");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn a_profile_disabled_mid_update_is_dropped_when_it_reports_back() {
|
|
||||||
let mut timers = KeyedTimers::new();
|
|
||||||
|
|
||||||
timers.apply(HashMap::from([("local".to_owned(), plan(Duration::ZERO, 60 * MINUTE))]));
|
|
||||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("local"));
|
|
||||||
assert!(timers.start(&"local".to_owned()));
|
|
||||||
|
|
||||||
assert_eq!(
|
|
||||||
timers.apply(HashMap::new()),
|
|
||||||
vec![TimerChange::Retired("local".to_owned())]
|
|
||||||
);
|
|
||||||
assert_eq!(timers.interval("local"), None, "a retired timer reports no deadline");
|
|
||||||
assert!(
|
|
||||||
timers.finish(&"local".to_owned()),
|
|
||||||
"a task retired mid-update must not outlive the update"
|
|
||||||
);
|
|
||||||
assert_eq!(timers.interval(&"local".to_owned()), None);
|
|
||||||
|
|
||||||
tokio::time::advance(Duration::from_secs(7200)).await;
|
|
||||||
assert!(nothing_due(&mut timers).await, "and must never be scheduled again");
|
|
||||||
// Re-enabling starts from scratch; a leftover entry would report no change.
|
|
||||||
assert_eq!(
|
|
||||||
timers.apply(HashMap::from([("local".to_owned(), plan(Duration::ZERO, 60 * MINUTE))])),
|
|
||||||
vec![TimerChange::Added("local".to_owned())]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn an_idle_timer_with_a_changed_interval_fires_after_the_new_first_delay() {
|
|
||||||
let mut timers = KeyedTimers::new();
|
|
||||||
timers.apply(HashMap::from([("a".to_owned(), plan(60 * MINUTE, 60 * MINUTE))]));
|
|
||||||
assert_eq!(
|
|
||||||
timers.apply(HashMap::from([("a".to_owned(), plan(MINUTE, 90 * MINUTE))])),
|
|
||||||
vec![TimerChange::Updated("a".to_owned())]
|
|
||||||
);
|
|
||||||
assert!(nothing_due(&mut timers).await, "a changed timer does not fire at once");
|
|
||||||
tokio::time::advance(MINUTE).await;
|
|
||||||
assert_eq!(
|
|
||||||
take_expired(&mut timers).await.as_deref(),
|
|
||||||
Some("a"),
|
|
||||||
"the old fire time an hour out must not survive the change"
|
|
||||||
);
|
|
||||||
assert!(nothing_due(&mut timers).await);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn apply_reports_removals_first_and_reenable_changes_nothing() {
|
|
||||||
let mut timers = KeyedTimers::new();
|
|
||||||
timers.apply(HashMap::from([
|
|
||||||
("a".to_owned(), plan(MINUTE, MINUTE)),
|
|
||||||
("b".to_owned(), plan(MINUTE, 2 * MINUTE)),
|
|
||||||
("c".to_owned(), plan(10 * MINUTE, 3 * MINUTE)),
|
|
||||||
]));
|
|
||||||
let mut tail = timers.apply(HashMap::from([
|
|
||||||
("a".to_owned(), plan(2 * MINUTE, 2 * MINUTE)),
|
|
||||||
("c".to_owned(), plan(10 * MINUTE, 3 * MINUTE)),
|
|
||||||
("d".to_owned(), plan(4 * MINUTE, MINUTE)),
|
|
||||||
]));
|
|
||||||
assert_eq!(tail.remove(0), TimerChange::Removed("b".to_owned()));
|
|
||||||
assert_eq!(tail.len(), 2); // HashMap order decides which of these comes first
|
|
||||||
assert!(tail.contains(&TimerChange::Added("d".to_owned())));
|
|
||||||
assert!(tail.contains(&TimerChange::Updated("a".to_owned())));
|
|
||||||
tokio::time::advance(2 * MINUTE).await;
|
|
||||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
|
|
||||||
assert!(timers.start(&"a".to_owned()));
|
|
||||||
let retired = timers.apply(HashMap::from([("c".to_owned(), plan(10 * MINUTE, 3 * MINUTE))]));
|
|
||||||
assert_eq!(retired.len(), 2, "the running key is retired and the idle one removed");
|
|
||||||
assert!(retired.contains(&TimerChange::Retired("a".to_owned())));
|
|
||||||
assert!(retired.contains(&TimerChange::Removed("d".to_owned())));
|
|
||||||
assert!(
|
|
||||||
timers
|
|
||||||
.apply(HashMap::from([
|
|
||||||
("a".to_owned(), plan(2 * MINUTE, 2 * MINUTE)),
|
|
||||||
("c".to_owned(), plan(10 * MINUTE, 3 * MINUTE)),
|
|
||||||
]))
|
|
||||||
.is_empty()
|
|
||||||
);
|
|
||||||
assert!(!timers.finish(&"a".to_owned()));
|
|
||||||
assert_eq!(timers.interval(&"a".to_owned()), Some(2 * MINUTE));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn interval_queries_answer_before_initialization() {
|
|
||||||
let mut timers = KeyedTimers::new();
|
|
||||||
timers.apply(HashMap::from([("a".to_owned(), plan(MINUTE, MINUTE))]));
|
|
||||||
assert_eq!(timers.interval(&"a".to_owned()), Some(MINUTE));
|
|
||||||
assert_eq!(timers.interval("a"), Some(MINUTE));
|
|
||||||
assert_eq!(timers.interval("b"), None);
|
|
||||||
assert_eq!(timers.apply(HashMap::new()), vec![TimerChange::Removed("a".to_owned())]);
|
|
||||||
assert_eq!(timers.interval("a"), None);
|
|
||||||
assert!(nothing_due(&mut timers).await);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn finishing_an_unknown_or_cleared_key_does_nothing() {
|
|
||||||
let mut timers = KeyedTimers::new();
|
|
||||||
assert!(!timers.finish(&"missing".to_owned()));
|
|
||||||
timers.apply(HashMap::from([("a".to_owned(), plan(MINUTE, MINUTE))]));
|
|
||||||
tokio::time::advance(MINUTE).await;
|
|
||||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
|
|
||||||
assert!(timers.start(&"a".to_owned()));
|
|
||||||
timers.clear();
|
|
||||||
assert!(!timers.finish(&"a".to_owned()));
|
|
||||||
assert_eq!(timers.interval(&"a".to_owned()), None);
|
|
||||||
tokio::time::advance(24 * 60 * MINUTE).await;
|
|
||||||
assert!(nothing_due(&mut timers).await);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
|
||||||
async fn an_interval_changed_during_a_run_is_reported_and_used_on_finish() {
|
|
||||||
let mut timers = KeyedTimers::new();
|
|
||||||
timers.apply(HashMap::from([("a".to_owned(), plan(Duration::ZERO, MINUTE))]));
|
|
||||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
|
|
||||||
assert!(timers.start(&"a".to_owned()));
|
|
||||||
assert_eq!(
|
|
||||||
timers.apply(HashMap::from([("a".to_owned(), plan(5 * MINUTE, 5 * MINUTE))])),
|
|
||||||
vec![TimerChange::Updated("a".to_owned())]
|
|
||||||
);
|
|
||||||
assert!(nothing_due(&mut timers).await);
|
|
||||||
assert_eq!(timers.interval(&"a".to_owned()), Some(5 * MINUTE));
|
|
||||||
|
|
||||||
// The new plan's first delay is not a fire time while the run is still in flight.
|
|
||||||
tokio::time::advance(5 * MINUTE).await;
|
|
||||||
assert!(
|
|
||||||
nothing_due(&mut timers).await,
|
|
||||||
"a changed interval must not queue a second run beside the one in flight"
|
|
||||||
);
|
|
||||||
|
|
||||||
assert!(!timers.finish(&"a".to_owned()));
|
|
||||||
tokio::time::advance(5 * MINUTE - Duration::from_secs(1)).await;
|
|
||||||
assert!(nothing_due(&mut timers).await);
|
|
||||||
tokio::time::advance(Duration::from_secs(1)).await;
|
|
||||||
assert_eq!(take_expired(&mut timers).await.as_deref(), Some("a"));
|
|
||||||
assert!(nothing_due(&mut timers).await, "exactly one run after the change");
|
|
||||||
}
|
|
||||||
@@ -6,8 +6,7 @@ import { createRoot } from 'react-dom/client'
|
|||||||
import { SWRConfig } from 'swr'
|
import { SWRConfig } from 'swr'
|
||||||
|
|
||||||
import { VirtualList } from '../../src/components/base/virtual-list'
|
import { VirtualList } from '../../src/components/base/virtual-list'
|
||||||
import { ConnectionRowItem } from '../../src/components/connection/connection-row-item'
|
import { VisibleConnectionRowItem } from '../../src/components/connection/connection-row-item'
|
||||||
import { useConnectionRowViews } from '../../src/components/connection/connection-row-view'
|
|
||||||
import LogItem from '../../src/components/log/log-item'
|
import LogItem from '../../src/components/log/log-item'
|
||||||
import { initializeLanguage } from '../../src/services/i18n'
|
import { initializeLanguage } from '../../src/services/i18n'
|
||||||
import { setPreloadConfig } from '../../src/services/preload'
|
import { setPreloadConfig } from '../../src/services/preload'
|
||||||
@@ -35,10 +34,9 @@ export function Components() {
|
|||||||
}),
|
}),
|
||||||
[],
|
[],
|
||||||
)
|
)
|
||||||
const rows = useConnectionRowViews(connections)
|
|
||||||
return (
|
return (
|
||||||
<VirtualList
|
<VirtualList
|
||||||
count={scenario === 'logs' ? logs.length : rows.length}
|
count={scenario === 'logs' ? logs.length : connections.length}
|
||||||
estimateSize={scenario === 'logs' ? 50 : 56}
|
estimateSize={scenario === 'logs' ? 50 : 56}
|
||||||
style={{ height: 640, margin: 24 }}
|
style={{ height: 640, margin: 24 }}
|
||||||
renderItem={(index) =>
|
renderItem={(index) =>
|
||||||
@@ -48,8 +46,8 @@ export function Components() {
|
|||||||
searchState={searchState}
|
searchState={searchState}
|
||||||
/>
|
/>
|
||||||
) : (
|
) : (
|
||||||
<ConnectionRowItem
|
<VisibleConnectionRowItem
|
||||||
row={rows[index]}
|
connection={connections[index]}
|
||||||
closed={false}
|
closed={false}
|
||||||
onShowDetail={() => {}}
|
onShowDetail={() => {}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -86,6 +86,7 @@ flate2 = "1.1.11"
|
|||||||
reqwest_dav = "0.4.0"
|
reqwest_dav = "0.4.0"
|
||||||
aes-gcm = { version = "0.11.1" }
|
aes-gcm = { version = "0.11.1" }
|
||||||
base64 = "0.23.1"
|
base64 = "0.23.1"
|
||||||
|
sha2 = { workspace = true }
|
||||||
getrandom = "0.4.3"
|
getrandom = "0.4.3"
|
||||||
futures = { workspace = true }
|
futures = { workspace = true }
|
||||||
gethostname = "1.1.0"
|
gethostname = "1.1.0"
|
||||||
@@ -99,11 +100,11 @@ async-trait = "0.1.92"
|
|||||||
clash_verge_service_ipc = { workspace = true, features = ["client"] }
|
clash_verge_service_ipc = { workspace = true, features = ["client"] }
|
||||||
arc-swap = "1.9.5"
|
arc-swap = "1.9.5"
|
||||||
tokio-rustls = "0.26.6"
|
tokio-rustls = "0.26.6"
|
||||||
rustls = { version = "0.23.47", features = ["ring"] }
|
rustls = { version = "0.23.48", features = ["aws_lc_rs"] }
|
||||||
webpki-roots = "1.0.12"
|
webpki-roots = "1.0.12"
|
||||||
dark-light = "3.0.0"
|
dark-light = "3.0.0"
|
||||||
bytes = "1.12.2"
|
bytes = "1.12.2"
|
||||||
tokio-util = { workspace = true }
|
tokio-util = { version = "0.7.20", features = ["time"] }
|
||||||
specta = { workspace = true, features = ["derive", "function", "serde_json"] }
|
specta = { workspace = true, features = ["derive", "function", "serde_json"] }
|
||||||
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
|
tauri-specta = { version = "=2.0.0-rc.26", features = ["derive", "typescript"] }
|
||||||
specta-typescript = "=0.0.13"
|
specta-typescript = "=0.0.13"
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::feat;
|
|||||||
use crate::utils::dirs;
|
use crate::utils::dirs;
|
||||||
use crate::{
|
use crate::{
|
||||||
cmd::StringifyErr as _,
|
cmd::StringifyErr as _,
|
||||||
config::{ClashInfo, Config, profiles::save_committed_profiles},
|
config::{ClashInfo, Config, mihomo_yaml, profiles::save_committed_profiles},
|
||||||
constants,
|
constants,
|
||||||
core::{
|
core::{
|
||||||
CoreManager, handle,
|
CoreManager, handle,
|
||||||
@@ -132,7 +132,7 @@ pub async fn save_dns_config(dns_config: crate::ipc::YamlMapping) -> CmdResult {
|
|||||||
|
|
||||||
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
|
let dns_path = dirs::app_home_dir().stringify_err()?.join(constants::files::DNS_CONFIG);
|
||||||
|
|
||||||
let yaml_str = clash_verge_config_render::serialize_for_export(&dns_config.0).stringify_err()?;
|
let yaml_str = mihomo_yaml::serialize_for_export(&dns_config.0).stringify_err()?;
|
||||||
fs::write(&dns_path, yaml_str).await.stringify_err()?;
|
fs::write(&dns_path, yaml_str).await.stringify_err()?;
|
||||||
logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
|
logging!(info, Type::Config, "DNS config saved to {dns_path:?}");
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
use super::CmdResult;
|
use super::CmdResult;
|
||||||
use crate::{cmd::StringifyErr as _, config::Config, core::CoreManager};
|
use crate::{
|
||||||
|
cmd::StringifyErr as _,
|
||||||
|
config::{Config, mihomo_yaml},
|
||||||
|
core::CoreManager,
|
||||||
|
};
|
||||||
use anyhow::{Context as _, anyhow};
|
use anyhow::{Context as _, anyhow};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
@@ -24,9 +28,7 @@ pub async fn get_runtime_yaml() -> CmdResult<std::string::String> {
|
|||||||
let config = runtime.config.as_ref();
|
let config = runtime.config.as_ref();
|
||||||
config
|
config
|
||||||
.ok_or_else(|| anyhow!("failed to parse config to yaml file"))
|
.ok_or_else(|| anyhow!("failed to parse config to yaml file"))
|
||||||
.and_then(|config| {
|
.and_then(|config| mihomo_yaml::serialize_for_export(config).context("failed to convert config to yaml"))
|
||||||
clash_verge_config_render::serialize_for_export(config).context("failed to convert config to yaml")
|
|
||||||
})
|
|
||||||
.stringify_err()
|
.stringify_err()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,7 +91,7 @@ pub async fn get_runtime_proxy_chain_config(
|
|||||||
|
|
||||||
config.insert("proxies".into(), proxies_chain);
|
config.insert("proxies".into(), proxies_chain);
|
||||||
|
|
||||||
clash_verge_config_render::serialize_for_export(&config)
|
mihomo_yaml::serialize_for_export(&config)
|
||||||
.context("YAML generation failed")
|
.context("YAML generation failed")
|
||||||
.stringify_err()
|
.stringify_err()
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use super::mihomo_yaml;
|
||||||
use crate::constants::{network, tun as tun_const};
|
use crate::constants::{network, tun as tun_const};
|
||||||
use crate::utils::dirs::{path_to_str, sidecar_ipc_path};
|
use crate::utils::dirs::{path_to_str, sidecar_ipc_path};
|
||||||
use crate::utils::{dirs, help};
|
use crate::utils::{dirs, help};
|
||||||
@@ -151,7 +152,7 @@ impl IClashTemp {
|
|||||||
|
|
||||||
pub async fn save_config(&self) -> Result<()> {
|
pub async fn save_config(&self) -> Result<()> {
|
||||||
let path = dirs::clash_path()?;
|
let path = dirs::clash_path()?;
|
||||||
let yaml = serde_yaml_ng::to_string(&self.0)?;
|
let yaml = mihomo_yaml::serialize(&self.0)?;
|
||||||
help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await
|
help::save_yaml_str(&path, &yaml, Some("# Generated by Clash Verge")).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use super::{IClashTemp, IProfiles, IVerge, MixedPort};
|
use super::{IClashTemp, IProfiles, IVerge, MixedPort, mihomo_yaml};
|
||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
@@ -20,11 +20,11 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use anyhow::{Result, anyhow};
|
use anyhow::{Result, anyhow};
|
||||||
use backon::{ExponentialBuilder, Retryable as _};
|
use backon::{ExponentialBuilder, Retryable as _};
|
||||||
use clash_verge_config_render::sanitize_tunnels_proxy;
|
|
||||||
use clash_verge_draft::Draft;
|
use clash_verge_draft::Draft;
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
use clash_verge_logging::{Type, logging, logging_error};
|
||||||
use clash_verge_runtime_bundle::resolve_provider_path_conflicts;
|
use clash_verge_runtime_bundle::resolve_provider_path_conflicts;
|
||||||
use std::path::PathBuf;
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
|
use std::{collections::HashSet, path::PathBuf};
|
||||||
use tokio::sync::{Mutex, MutexGuard, OnceCell};
|
use tokio::sync::{Mutex, MutexGuard, OnceCell};
|
||||||
use tokio::time::sleep;
|
use tokio::time::sleep;
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
@@ -230,7 +230,7 @@ impl Config {
|
|||||||
{
|
{
|
||||||
return Ok(std::sync::Arc::clone(cached));
|
return Ok(std::sync::Arc::clone(cached));
|
||||||
}
|
}
|
||||||
let yaml_str = std::sync::Arc::new(serde_yaml_ng::to_string(config)?);
|
let yaml_str = std::sync::Arc::new(mihomo_yaml::serialize(config)?);
|
||||||
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
|
*RUNTIME_YAML_CACHE.lock() = Some((key, std::sync::Arc::clone(&yaml_str)));
|
||||||
Ok(yaml_str)
|
Ok(yaml_str)
|
||||||
})
|
})
|
||||||
@@ -321,3 +321,66 @@ impl Config {
|
|||||||
logging!(info, Type::Config, "save all draft data finished");
|
logging!(info, Type::Config, "save all draft data finished");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn sanitize_tunnels_proxy(config: &mut Mapping) {
|
||||||
|
if !config
|
||||||
|
.get("tunnels")
|
||||||
|
.and_then(|v| v.as_sequence())
|
||||||
|
.is_some_and(|t| tunnels_need_validation(t))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut valid: HashSet<String> = HashSet::with_capacity(64);
|
||||||
|
collect_names(config, "proxies", &mut valid);
|
||||||
|
collect_names(config, "proxy-groups", &mut valid);
|
||||||
|
|
||||||
|
valid.insert("DIRECT".into());
|
||||||
|
valid.insert("REJECT".into());
|
||||||
|
|
||||||
|
let Some(tunnels) = config.get_mut("tunnels").and_then(|v| v.as_sequence_mut()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
for item in tunnels {
|
||||||
|
let Some(tunnel) = item.as_mapping_mut() else { continue };
|
||||||
|
|
||||||
|
let Some(proxy_name) = tunnel.get("proxy").and_then(|v| v.as_str()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
if proxy_name == "DIRECT" || proxy_name == "REJECT" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !valid.contains(proxy_name) {
|
||||||
|
tunnel.remove("proxy");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tunnels_need_validation(tunnels: &[Value]) -> bool {
|
||||||
|
tunnels.iter().any(|item| {
|
||||||
|
item.as_mapping()
|
||||||
|
.and_then(|t| t.get("proxy"))
|
||||||
|
.and_then(|p| p.as_str())
|
||||||
|
.is_some_and(|name| name != "DIRECT" && name != "REJECT")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_names(config: &Mapping, list_key: &str, out: &mut HashSet<String>) {
|
||||||
|
let Some(Value::Sequence(seq)) = config.get(list_key) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
for item in seq {
|
||||||
|
let Value::Mapping(map) = item else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
if let Some(Value::String(n)) = map.get("name")
|
||||||
|
&& !n.is_empty()
|
||||||
|
{
|
||||||
|
out.insert(n.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
|
use crate::utils::help;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clash_verge_draft::DraftTransaction;
|
use clash_verge_draft::DraftTransaction;
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
use clash_verge_logging::{Type, logging, logging_error};
|
||||||
use clash_verge_task::scheduled_task::{self, CoalescingJob};
|
use clash_verge_task::scheduled_task::{self, CoalescingJob};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
|
use sha2::{Digest as _, Sha256};
|
||||||
use std::sync::{
|
use std::sync::{
|
||||||
LazyLock,
|
LazyLock,
|
||||||
atomic::{AtomicBool, Ordering},
|
atomic::{AtomicBool, Ordering},
|
||||||
@@ -19,6 +22,42 @@ pub(crate) fn take_dns_override_notice() -> bool {
|
|||||||
PENDING_DNS_OVERRIDE_NOTICE.swap(false, Ordering::Relaxed)
|
PENDING_DNS_OVERRIDE_NOTICE.swap(false, Ordering::Relaxed)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const PROVIDER_DNS_FIELDS: [&str; 3] = [
|
||||||
|
"proxy-server-nameserver",
|
||||||
|
"proxy-server-nameserver-policy",
|
||||||
|
"nameserver-policy",
|
||||||
|
];
|
||||||
|
|
||||||
|
pub(crate) fn dns_override_source(profile_uid: &str, config: &Mapping) -> Result<Option<String>> {
|
||||||
|
let Some(dns) = config.get("dns").and_then(Value::as_mapping) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let fields: Mapping = PROVIDER_DNS_FIELDS
|
||||||
|
.iter()
|
||||||
|
.filter_map(|key| {
|
||||||
|
let value = dns.get(*key)?;
|
||||||
|
let nonempty = match value {
|
||||||
|
Value::Sequence(values) => !values.is_empty(),
|
||||||
|
Value::Mapping(values) => !values.is_empty(),
|
||||||
|
Value::String(value) => !value.trim().is_empty(),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
nonempty.then(|| (Value::from(*key), value.clone()))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if fields.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut canonical = serde_json::to_value(fields)?;
|
||||||
|
canonical.sort_all_objects();
|
||||||
|
let mut digest = Sha256::new();
|
||||||
|
digest.update(profile_uid.as_bytes());
|
||||||
|
digest.update([0]);
|
||||||
|
digest.update(serde_json::to_vec(&canonical)?);
|
||||||
|
Ok(Some(help::hex_encode(&digest.finalize()).into()))
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub(crate) struct DnsOverrideState {
|
pub(crate) struct DnsOverrideState {
|
||||||
profile_uid: String,
|
profile_uid: String,
|
||||||
@@ -128,27 +167,46 @@ impl Config {
|
|||||||
#[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, ProfileDnsSettings};
|
use super::{DnsOverrideState, ProfileDnsSettings, dns_override_source};
|
||||||
use crate::config::IVerge;
|
use crate::config::IVerge;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clash_verge_config_render::override_source;
|
|
||||||
use serde_yaml_ng::Mapping;
|
use serde_yaml_ng::Mapping;
|
||||||
|
|
||||||
fn mapping(yaml: &str) -> Mapping {
|
fn mapping(yaml: &str) -> Mapping {
|
||||||
serde_yaml_ng::from_str(yaml).expect("valid fixture")
|
serde_yaml_ng::from_str(yaml).expect("valid fixture")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dns_override_detects_each_original_field_but_not_empty_placeholders() -> Result<()> {
|
||||||
|
for field in [
|
||||||
|
"proxy-server-nameserver: [https://doh.pub/dns-query]",
|
||||||
|
"proxy-server-nameserver-policy: {'www.yournode.com': '114.114.114.114'}",
|
||||||
|
"nameserver-policy: {'+.quandao.com': ['https://doh.dohcore.com:2096/dns-query/#skip-cert-verify=true']}",
|
||||||
|
] {
|
||||||
|
assert!(dns_override_source("profile", &mapping(&format!("dns: {{{field}}}")))?.is_some());
|
||||||
|
assert!(dns_override_source("profile", &mapping(field))?.is_none());
|
||||||
|
}
|
||||||
|
for yaml in [
|
||||||
|
"{}",
|
||||||
|
"dns: {nameserver: [1.1.1.1]}",
|
||||||
|
"dns: {proxy-server-nameserver: [], proxy-server-nameserver-policy: null, nameserver-policy: {}}",
|
||||||
|
] {
|
||||||
|
assert!(dns_override_source("profile", &mapping(yaml))?.is_none());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn dns_override_confirmation_survives_formatting_but_not_a_different_source() -> Result<()> {
|
fn dns_override_confirmation_survives_formatting_but_not_a_different_source() -> Result<()> {
|
||||||
let original = mapping("dns: {nameserver-policy: {a.example: 1.1.1.1, b.example: [8.8.8.8]}}");
|
let original = mapping("dns: {nameserver-policy: {a.example: 1.1.1.1, b.example: [8.8.8.8]}}");
|
||||||
let source = override_source("one", &original)?;
|
let source = dns_override_source("one", &original)?;
|
||||||
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, override_source("one", &reordered)?);
|
assert_eq!(source, dns_override_source("one", &reordered)?);
|
||||||
assert!(DnsOverrideState::new("one", source.clone(), true, source.clone()).enabled);
|
assert!(DnsOverrideState::new("one", source.clone(), true, source.clone()).enabled);
|
||||||
assert!(!DnsOverrideState::new("two", 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("one", override_source("one", &changed)?, true, source).enabled);
|
assert!(!DnsOverrideState::new("one", dns_override_source("one", &changed)?, true, source).enabled);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
use serde::Serialize;
|
||||||
|
use serde_yaml_ng::Result;
|
||||||
|
|
||||||
|
pub(crate) use serde_yaml_ng::to_string as serialize;
|
||||||
|
|
||||||
|
pub(crate) fn serialize_for_export<T: Serialize>(data: &T) -> Result<String> {
|
||||||
|
Ok(quote_fake_ip_filter_wildcards(&serialize(data)?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn quote_fake_ip_filter_wildcards(yaml: &str) -> String {
|
||||||
|
let mut result = String::with_capacity(yaml.len());
|
||||||
|
let mut in_fake_ip_filter = false;
|
||||||
|
let mut fake_ip_filter_indent = 0;
|
||||||
|
|
||||||
|
for line in yaml.lines() {
|
||||||
|
let indent = line.len() - line.trim_start_matches(' ').len();
|
||||||
|
let trimmed = &line[indent..];
|
||||||
|
|
||||||
|
if in_fake_ip_filter && indent <= fake_ip_filter_indent && !trimmed.starts_with("- ") {
|
||||||
|
in_fake_ip_filter = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !in_fake_ip_filter && trimmed == "fake-ip-filter:" {
|
||||||
|
in_fake_ip_filter = true;
|
||||||
|
fake_ip_filter_indent = indent;
|
||||||
|
}
|
||||||
|
|
||||||
|
if in_fake_ip_filter
|
||||||
|
&& indent >= fake_ip_filter_indent
|
||||||
|
&& let Some(item) = trimmed.strip_prefix("- ")
|
||||||
|
&& needs_quotes(item)
|
||||||
|
{
|
||||||
|
result.push_str(&line[..indent + 2]);
|
||||||
|
push_quoted(&mut result, item);
|
||||||
|
} else {
|
||||||
|
result.push_str(line);
|
||||||
|
}
|
||||||
|
result.push('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn needs_quotes(item: &str) -> bool {
|
||||||
|
!item.starts_with(['"', '\'']) && (item.contains('*') || item.starts_with(['+', '.']))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_quoted(output: &mut String, item: &str) {
|
||||||
|
output.push('\'');
|
||||||
|
for (index, part) in item.split('\'').enumerate() {
|
||||||
|
if index != 0 {
|
||||||
|
output.push_str("''");
|
||||||
|
}
|
||||||
|
output.push_str(part);
|
||||||
|
}
|
||||||
|
output.push('\'');
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::expect_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::serialize_for_export;
|
||||||
|
|
||||||
|
fn roundtrip(input: &str) {
|
||||||
|
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
||||||
|
let output = serialize_for_export(&value).expect("yaml should serialize");
|
||||||
|
let reparsed: serde_yaml_ng::Value = serde_yaml_ng::from_str(&output).expect("serialized yaml should parse");
|
||||||
|
|
||||||
|
assert_eq!(reparsed, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn quotes_fake_ip_filter_wildcards_without_changing_values() {
|
||||||
|
let input = r#"
|
||||||
|
dns:
|
||||||
|
fake-ip-filter:
|
||||||
|
- "*.lan"
|
||||||
|
- "+.market.xiaomi.com"
|
||||||
|
- ".example.com"
|
||||||
|
- "time.*.com"
|
||||||
|
- "plain.example.com"
|
||||||
|
"#;
|
||||||
|
|
||||||
|
roundtrip(input);
|
||||||
|
|
||||||
|
let value: serde_yaml_ng::Value = serde_yaml_ng::from_str(input).expect("input yaml should parse");
|
||||||
|
let output = serialize_for_export(&value).expect("yaml should serialize");
|
||||||
|
|
||||||
|
assert!(output.contains("- '*.lan'"));
|
||||||
|
assert!(output.contains("- '+.market.xiaomi.com'"));
|
||||||
|
assert!(output.contains("- '.example.com'"));
|
||||||
|
assert!(output.contains("- 'time.*.com'"));
|
||||||
|
assert!(output.contains("- plain.example.com"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nested_multiline_strings_roundtrip() {
|
||||||
|
roundtrip(
|
||||||
|
r"
|
||||||
|
items:
|
||||||
|
- name: demo
|
||||||
|
desc: |
|
||||||
|
line1
|
||||||
|
line2
|
||||||
|
",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ mod clash;
|
|||||||
mod config;
|
mod config;
|
||||||
pub(crate) mod dns;
|
pub(crate) mod dns;
|
||||||
mod encrypt;
|
mod encrypt;
|
||||||
|
pub(crate) mod mihomo_yaml;
|
||||||
mod mixed_port;
|
mod mixed_port;
|
||||||
mod port;
|
mod port;
|
||||||
mod prfitem;
|
mod prfitem;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode};
|
|||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::core::service::StageRequest;
|
use crate::core::service::StageRequest;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime},
|
config::{Config, IProfiles, mihomo_yaml, profiles::save_profiles, runtime::IRuntime},
|
||||||
constants::timing,
|
constants::timing,
|
||||||
core::{
|
core::{
|
||||||
handle,
|
handle,
|
||||||
@@ -170,7 +170,7 @@ impl CoreManager {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let yaml = serde_yaml_ng::to_string(clash_config)?;
|
let yaml = mihomo_yaml::serialize(clash_config)?;
|
||||||
help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?;
|
help::save_yaml_str(&runtime_path, &yaml, Some("# Clash Verge Runtime")).await?;
|
||||||
handle::Handle::notice(status, message);
|
handle::Handle::notice(status, message);
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error {
|
|||||||
|
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
||||||
|
use crate::config::mihomo_yaml;
|
||||||
use serde_yaml_ng::{Mapping, Value};
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
|
|
||||||
let mut config: Mapping = serde_yaml_ng::from_str(yaml)?;
|
let mut config: Mapping = serde_yaml_ng::from_str(yaml)?;
|
||||||
@@ -47,7 +48,7 @@ fn sidecar_config_without_tun(yaml: &str) -> Result<std::string::String> {
|
|||||||
tun.as_mapping_mut()
|
tun.as_mapping_mut()
|
||||||
.context("invalid Sidecar TUN configuration")?
|
.context("invalid Sidecar TUN configuration")?
|
||||||
.insert(Value::from("enable"), Value::Bool(false));
|
.insert(Value::from("enable"), Value::Bool(false));
|
||||||
Ok(serde_yaml_ng::to_string(&config)?)
|
Ok(mihomo_yaml::serialize(&config)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
|
const SIDECAR_READINESS_ATTEMPTS: usize = 30;
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::utils::dirs;
|
use crate::utils::dirs;
|
||||||
use crate::{
|
use crate::{
|
||||||
config::{Config, runtime::IRuntime},
|
config::{Config, mihomo_yaml, runtime::IRuntime},
|
||||||
constants,
|
constants,
|
||||||
core::{
|
core::{
|
||||||
CoreManager,
|
CoreManager,
|
||||||
@@ -613,7 +613,7 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result<RuntimeBun
|
|||||||
let bin_path = service_core_path(&clash_core, bin_ext)?;
|
let bin_path = service_core_path(&clash_core, bin_ext)?;
|
||||||
let plan = collect_runtime_bundle(config_file).await?;
|
let plan = collect_runtime_bundle(config_file).await?;
|
||||||
Ok(RuntimeBundle {
|
Ok(RuntimeBundle {
|
||||||
yaml: serde_yaml_ng::to_string(&plan.config).context("failed to serialize service runtime config")?,
|
yaml: mihomo_yaml::serialize(&plan.config).context("failed to serialize service runtime config")?,
|
||||||
assets: plan
|
assets: plan
|
||||||
.assets
|
.assets
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
|||||||
+263
-48
@@ -9,13 +9,13 @@ use anyhow::{Context as _, Result};
|
|||||||
use clash_verge_draft::Draft;
|
use clash_verge_draft::Draft;
|
||||||
use clash_verge_logging::{Type, logging, logging_error};
|
use clash_verge_logging::{Type, logging, logging_error};
|
||||||
use clash_verge_profile::SubscriptionSchedule as TaskSchedule;
|
use clash_verge_profile::SubscriptionSchedule as TaskSchedule;
|
||||||
use clash_verge_task::timers::{KeyedTimers, TimerChange, TimerPlan};
|
use futures::{FutureExt as _, StreamExt as _};
|
||||||
use futures::FutureExt as _;
|
|
||||||
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
|
use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration};
|
||||||
use tokio::{
|
use tokio::{
|
||||||
sync::{mpsc, oneshot},
|
sync::{mpsc, oneshot},
|
||||||
time::{sleep, timeout},
|
time::{sleep, timeout},
|
||||||
};
|
};
|
||||||
|
use tokio_util::time::{DelayQueue, delay_queue::Key};
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
|
|
||||||
enum TimerCommand {
|
enum TimerCommand {
|
||||||
@@ -25,6 +25,15 @@ enum TimerCommand {
|
|||||||
TaskFinished(String),
|
TaskFinished(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct TaskState {
|
||||||
|
key: Option<Key>,
|
||||||
|
interval_minutes: u64,
|
||||||
|
running: bool,
|
||||||
|
/// Disabled mid-update. Entry outlives removal so re-enabling reuses the `running` guard
|
||||||
|
/// instead of building a fresh state that would fire a second update at zero delay.
|
||||||
|
retired: bool,
|
||||||
|
}
|
||||||
|
|
||||||
async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Finished, Completed, Output>(
|
async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Finished, Completed, Output>(
|
||||||
update_started: Started,
|
update_started: Started,
|
||||||
update_profile: Update,
|
update_profile: Update,
|
||||||
@@ -43,6 +52,17 @@ async fn run_timer_profile_update_transition<Started, Update, UpdateFuture, Fini
|
|||||||
update_completed();
|
update_completed();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl TaskState {
|
||||||
|
const fn new(key: Option<Key>, interval_minutes: u64) -> Self {
|
||||||
|
Self {
|
||||||
|
key,
|
||||||
|
interval_minutes,
|
||||||
|
running: false,
|
||||||
|
retired: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct Timer {
|
pub struct Timer {
|
||||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||||
}
|
}
|
||||||
@@ -96,15 +116,15 @@ impl Timer {
|
|||||||
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||||
profiles: Draft<IProfiles>,
|
profiles: Draft<IProfiles>,
|
||||||
) {
|
) {
|
||||||
let mut timers = KeyedTimers::<String>::new();
|
let mut queue = DelayQueue::new();
|
||||||
|
let mut tasks = HashMap::new();
|
||||||
let mut initialized = false;
|
let mut initialized = false;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
tokio::select! {
|
tokio::select! {
|
||||||
Some(expired) = timers.next_expired(), if initialized => {
|
Some(expired) = queue.next(), if initialized => {
|
||||||
if timers.start(&expired) {
|
let uid = expired.into_inner();
|
||||||
Self::spawn_update_task(expired, command_tx.clone());
|
Self::run_expired_task(&mut tasks, uid, command_tx.clone());
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
command = command_rx.recv() => {
|
command = command_rx.recv() => {
|
||||||
@@ -115,8 +135,8 @@ impl Timer {
|
|||||||
// timestamps when the queue first becomes eligible to fire.
|
// timestamps when the queue first becomes eligible to fire.
|
||||||
let profiles = profiles.data_arc();
|
let profiles = profiles.data_arc();
|
||||||
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), true);
|
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), true);
|
||||||
timers.clear();
|
tasks.clear();
|
||||||
Self::log_changes(&schedule, timers.apply(Self::plans(&schedule)));
|
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
|
||||||
initialized = true;
|
initialized = true;
|
||||||
logging!(info, Type::Timer, "Timer initialization completed");
|
logging!(info, Type::Timer, "Timer initialization completed");
|
||||||
}
|
}
|
||||||
@@ -126,20 +146,21 @@ impl Timer {
|
|||||||
let profiles = profiles.data_arc();
|
let profiles = profiles.data_arc();
|
||||||
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), false);
|
let schedule = Self::gen_map_from_items(profiles.items.as_deref().unwrap_or_default(), false);
|
||||||
if initialized {
|
if initialized {
|
||||||
Self::log_changes(&schedule, timers.apply(Self::plans(&schedule)));
|
Self::apply_timer_map(&mut queue, &mut tasks, schedule);
|
||||||
} else {
|
} else {
|
||||||
timers.apply(Self::plans(&schedule));
|
tasks = schedule
|
||||||
|
.into_iter()
|
||||||
|
.map(|(uid, schedule)| (uid, TaskState::new(None, schedule.interval_minutes)))
|
||||||
|
.collect();
|
||||||
}
|
}
|
||||||
let _ = reply.send(());
|
let _ = reply.send(());
|
||||||
}
|
}
|
||||||
Some(TimerCommand::NextUpdateTime(uid, reply)) => {
|
Some(TimerCommand::NextUpdateTime(uid, reply)) => {
|
||||||
let next = Self::next_update_time(&timers, &profiles.latest_arc(), &uid);
|
let next = Self::next_update_time(&tasks, &profiles.latest_arc(), &uid);
|
||||||
let _ = reply.send(next);
|
let _ = reply.send(next);
|
||||||
}
|
}
|
||||||
Some(TimerCommand::TaskFinished(uid)) => {
|
Some(TimerCommand::TaskFinished(uid)) => {
|
||||||
if timers.finish(&uid) {
|
Self::finish_task(&mut queue, &mut tasks, uid);
|
||||||
logging!(debug, Type::Timer, "Dropped retired timer task now that its update finished: uid={uid}");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
None => break,
|
None => break,
|
||||||
}
|
}
|
||||||
@@ -148,39 +169,59 @@ impl Timer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn plans(schedule: &HashMap<String, TaskSchedule>) -> HashMap<String, TimerPlan> {
|
fn apply_timer_map(
|
||||||
schedule
|
queue: &mut DelayQueue<String>,
|
||||||
.iter()
|
tasks: &mut HashMap<String, TaskState>,
|
||||||
.map(|(uid, schedule)| {
|
new_map: HashMap<String, TaskSchedule>,
|
||||||
(
|
) {
|
||||||
uid.clone(),
|
tasks.retain(|uid, state| {
|
||||||
TimerPlan {
|
if new_map.contains_key(uid) {
|
||||||
first_delay: schedule.first_delay,
|
return true;
|
||||||
interval: TaskSchedule::interval_duration(schedule.interval_minutes),
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn log_changes(schedule: &HashMap<String, TaskSchedule>, changes: Vec<TimerChange<String>>) {
|
if let Some(key) = state.key.take() {
|
||||||
for change in changes {
|
queue.remove(&key);
|
||||||
match change {
|
}
|
||||||
TimerChange::Retired(uid) => {
|
|
||||||
|
if state.running {
|
||||||
|
state.retired = true;
|
||||||
logging!(
|
logging!(
|
||||||
debug,
|
debug,
|
||||||
Type::Timer,
|
Type::Timer,
|
||||||
"Retiring timer task once its in-flight update reports back: uid={}",
|
"Retiring timer task once its in-flight update reports back: uid={}",
|
||||||
uid
|
uid
|
||||||
);
|
);
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
TimerChange::Removed(uid) => {
|
|
||||||
logging!(debug, Type::Timer, "Removed timer task for uid={}", uid);
|
logging!(debug, Type::Timer, "Removed timer task for uid={}", uid);
|
||||||
}
|
false
|
||||||
TimerChange::Added(uid) => {
|
});
|
||||||
let Some(schedule) = schedule.get(&uid) else {
|
|
||||||
|
for (uid, schedule) in new_map {
|
||||||
|
let Some(state) = tasks.get_mut(&uid) else {
|
||||||
|
Self::insert_task(queue, tasks, uid, &schedule);
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Re-enabled before retirement took effect; finish_task re-arms it.
|
||||||
|
state.retired = false;
|
||||||
|
|
||||||
|
if state.interval_minutes == schedule.interval_minutes {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Self::update_task_interval(queue, &uid, state, &schedule);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_task(
|
||||||
|
queue: &mut DelayQueue<String>,
|
||||||
|
tasks: &mut HashMap<String, TaskState>,
|
||||||
|
uid: String,
|
||||||
|
schedule: &TaskSchedule,
|
||||||
|
) {
|
||||||
|
let key = Self::schedule_task(queue, &uid, schedule.first_delay);
|
||||||
logging!(
|
logging!(
|
||||||
debug,
|
debug,
|
||||||
Type::Timer,
|
Type::Timer,
|
||||||
@@ -189,11 +230,18 @@ impl Timer {
|
|||||||
schedule.interval_minutes,
|
schedule.interval_minutes,
|
||||||
schedule.first_delay.as_secs()
|
schedule.first_delay.as_secs()
|
||||||
);
|
);
|
||||||
|
tasks.insert(uid, TaskState::new(Some(key), schedule.interval_minutes));
|
||||||
}
|
}
|
||||||
TimerChange::Updated(uid) => {
|
|
||||||
let Some(schedule) = schedule.get(&uid) else {
|
fn update_task_interval(queue: &mut DelayQueue<String>, uid: &str, state: &mut TaskState, schedule: &TaskSchedule) {
|
||||||
continue;
|
state.interval_minutes = schedule.interval_minutes;
|
||||||
};
|
|
||||||
|
if let Some(key) = state.key.as_ref() {
|
||||||
|
queue.reset(key, schedule.first_delay);
|
||||||
|
} else if !state.running {
|
||||||
|
state.key = Some(Self::schedule_task(queue, uid, schedule.first_delay));
|
||||||
|
}
|
||||||
|
|
||||||
logging!(
|
logging!(
|
||||||
debug,
|
debug,
|
||||||
Type::Timer,
|
Type::Timer,
|
||||||
@@ -203,8 +251,46 @@ impl Timer {
|
|||||||
schedule.first_delay.as_secs()
|
schedule.first_delay.as_secs()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn run_expired_task(
|
||||||
|
tasks: &mut HashMap<String, TaskState>,
|
||||||
|
uid: String,
|
||||||
|
command_tx: mpsc::UnboundedSender<TimerCommand>,
|
||||||
|
) {
|
||||||
|
let Some(state) = tasks.get_mut(&uid) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
state.key = None;
|
||||||
|
if state.running {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
state.running = true;
|
||||||
|
Self::spawn_update_task(uid, command_tx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn finish_task(queue: &mut DelayQueue<String>, tasks: &mut HashMap<String, TaskState>, uid: String) {
|
||||||
|
let Some(state) = tasks.get_mut(&uid) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
state.running = false;
|
||||||
|
|
||||||
|
if state.retired {
|
||||||
|
tasks.remove(&uid);
|
||||||
|
logging!(
|
||||||
|
debug,
|
||||||
|
Type::Timer,
|
||||||
|
"Dropped retired timer task now that its update finished: uid={}",
|
||||||
|
uid
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full interval, not from `updated`: a failed run leaves `updated` in the past, so
|
||||||
|
// counting from it would retry at zero delay and spin.
|
||||||
|
let key = Self::schedule_task(queue, &uid, TaskSchedule::interval_duration(state.interval_minutes));
|
||||||
|
state.key = Some(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn spawn_update_task(uid: String, command_tx: mpsc::UnboundedSender<TimerCommand>) {
|
fn spawn_update_task(uid: String, command_tx: mpsc::UnboundedSender<TimerCommand>) {
|
||||||
@@ -216,6 +302,10 @@ impl Timer {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn schedule_task(queue: &mut DelayQueue<String>, uid: &str, delay: Duration) -> Key {
|
||||||
|
queue.insert(String::from(uid), delay)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn get_next_update_time(&self, uid: &str) -> Option<i64> {
|
pub async fn get_next_update_time(&self, uid: &str) -> Option<i64> {
|
||||||
let (reply, result) = oneshot::channel();
|
let (reply, result) = oneshot::channel();
|
||||||
self.command_tx
|
self.command_tx
|
||||||
@@ -224,15 +314,10 @@ impl Timer {
|
|||||||
result.await.ok().flatten()
|
result.await.ok().flatten()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn next_update_time(timers: &KeyedTimers<String>, profiles: &IProfiles, uid: &str) -> Option<i64> {
|
fn next_update_time(tasks: &HashMap<String, TaskState>, profiles: &IProfiles, uid: &str) -> Option<i64> {
|
||||||
|
let task = tasks.get(uid).filter(|task| !task.retired)?;
|
||||||
let updated = profiles.get_item(uid).ok()?.updated;
|
let updated = profiles.get_item(uid).ok()?.updated;
|
||||||
TaskSchedule::reported_deadline(Self::minutes(timers.interval(uid)?)?, updated)
|
TaskSchedule::reported_deadline(task.interval_minutes, updated)
|
||||||
}
|
|
||||||
|
|
||||||
/// A saturated interval is not a whole number of minutes, so the query stays unanswered as before.
|
|
||||||
const fn minutes(interval: Duration) -> Option<u64> {
|
|
||||||
let secs = interval.as_secs();
|
|
||||||
if secs.is_multiple_of(60) { Some(secs / 60) } else { None }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn emit_update_event(uid: &str, is_start: bool) {
|
fn emit_update_event(uid: &str, is_start: bool) {
|
||||||
@@ -279,7 +364,9 @@ impl Timer {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::{TaskSchedule, Timer, run_timer_profile_update_transition};
|
use super::{TaskSchedule, Timer, run_timer_profile_update_transition};
|
||||||
use crate::config::{PrfItem, PrfOption};
|
use crate::config::{PrfItem, PrfOption};
|
||||||
|
use futures::StreamExt as _;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
use std::collections::HashMap;
|
||||||
use std::{
|
use std::{
|
||||||
sync::{
|
sync::{
|
||||||
Arc,
|
Arc,
|
||||||
@@ -289,6 +376,8 @@ mod tests {
|
|||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
use tokio::sync::Barrier;
|
use tokio::sync::Barrier;
|
||||||
|
use tokio_util::time::DelayQueue;
|
||||||
|
use tristr::alias::String;
|
||||||
|
|
||||||
struct CancellationProbe {
|
struct CancellationProbe {
|
||||||
cancelled: Arc<AtomicBool>,
|
cancelled: Arc<AtomicBool>,
|
||||||
@@ -380,6 +469,132 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Polled, not awaited: a not-yet-due entry would park the test on the paused clock.
|
||||||
|
async fn take_expired(queue: &mut DelayQueue<String>) -> Option<String> {
|
||||||
|
match futures::poll!(Box::pin(queue.next())) {
|
||||||
|
Poll::Ready(Some(expired)) => Some(expired.into_inner()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What `run_expired_task` does, minus spawning the real update.
|
||||||
|
fn mark_running(tasks: &mut HashMap<String, super::TaskState>, uid: &str) {
|
||||||
|
assert!(tasks.contains_key(uid), "task {uid} must exist before it can run");
|
||||||
|
|
||||||
|
if let Some(state) = tasks.get_mut(uid) {
|
||||||
|
state.key = None;
|
||||||
|
state.running = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Empty queue reports `Ready(None)`, not `Pending`, so both count as "nothing due".
|
||||||
|
async fn nothing_due(queue: &mut DelayQueue<String>) -> bool {
|
||||||
|
matches!(
|
||||||
|
futures::poll!(Box::pin(queue.next())),
|
||||||
|
Poll::Pending | Poll::Ready(None)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(start_paused = true)]
|
||||||
|
async fn queue_fires_at_the_remaining_time_then_waits_a_whole_interval() {
|
||||||
|
const NOW: i64 = 1_700_000_000;
|
||||||
|
|
||||||
|
let mut queue = DelayQueue::new();
|
||||||
|
let mut tasks = HashMap::new();
|
||||||
|
|
||||||
|
// 1439min into a 1440min interval: due in a minute, not a day.
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
map.insert(
|
||||||
|
String::from("uid"),
|
||||||
|
TaskSchedule::new(1440, Some((NOW - 1439 * 60) as usize), NOW),
|
||||||
|
);
|
||||||
|
Timer::apply_timer_map(&mut queue, &mut tasks, map);
|
||||||
|
|
||||||
|
tokio::time::advance(Duration::from_secs(61)).await;
|
||||||
|
assert_eq!(
|
||||||
|
take_expired(&mut queue).await.as_deref(),
|
||||||
|
Some("uid"),
|
||||||
|
"the raised interval must fire one minute in, not a full day in"
|
||||||
|
);
|
||||||
|
|
||||||
|
// After it reports back, the next one is a whole interval away.
|
||||||
|
mark_running(&mut tasks, "uid");
|
||||||
|
Timer::finish_task(&mut queue, &mut tasks, String::from("uid"));
|
||||||
|
|
||||||
|
tokio::time::advance(Duration::from_secs(1439 * 60)).await;
|
||||||
|
assert!(
|
||||||
|
nothing_due(&mut queue).await,
|
||||||
|
"a finished task waits the whole interval, not the remainder of the old one"
|
||||||
|
);
|
||||||
|
|
||||||
|
tokio::time::advance(Duration::from_secs(120)).await;
|
||||||
|
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(start_paused = true)]
|
||||||
|
async fn disabling_a_profile_mid_update_cannot_start_a_second_one() {
|
||||||
|
const NOW: i64 = 1_700_000_000;
|
||||||
|
|
||||||
|
let mut queue = DelayQueue::new();
|
||||||
|
let mut tasks = HashMap::new();
|
||||||
|
// Overdue: every re-insert would land at zero delay.
|
||||||
|
let schedule = || TaskSchedule::new(60, Some((NOW - 7200) as usize), NOW);
|
||||||
|
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
map.insert(String::from("uid"), schedule());
|
||||||
|
Timer::apply_timer_map(&mut queue, &mut tasks, map);
|
||||||
|
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
|
||||||
|
mark_running(&mut tasks, "uid");
|
||||||
|
|
||||||
|
// Toggled off then on while the run is still in flight.
|
||||||
|
Timer::apply_timer_map(&mut queue, &mut tasks, HashMap::new());
|
||||||
|
let mut back_on = HashMap::new();
|
||||||
|
back_on.insert(String::from("uid"), schedule());
|
||||||
|
Timer::apply_timer_map(&mut queue, &mut tasks, back_on);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
tasks.get("uid").is_some_and(|state| state.running),
|
||||||
|
"the entry must survive the toggle so the in-flight run is still accounted for"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
nothing_due(&mut queue).await,
|
||||||
|
"re-enabling must not queue a second run alongside the one already going"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Original run reports back, re-arms exactly once.
|
||||||
|
Timer::finish_task(&mut queue, &mut tasks, String::from("uid"));
|
||||||
|
tokio::time::advance(Duration::from_secs(3601)).await;
|
||||||
|
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
|
||||||
|
assert!(nothing_due(&mut queue).await, "exactly one key, no orphan");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test(start_paused = true)]
|
||||||
|
async fn a_profile_disabled_mid_update_is_dropped_when_it_reports_back() {
|
||||||
|
const NOW: i64 = 1_700_000_000;
|
||||||
|
|
||||||
|
let mut queue = DelayQueue::new();
|
||||||
|
let mut tasks = HashMap::new();
|
||||||
|
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
map.insert(
|
||||||
|
String::from("uid"),
|
||||||
|
TaskSchedule::new(60, Some((NOW - 7200) as usize), NOW),
|
||||||
|
);
|
||||||
|
Timer::apply_timer_map(&mut queue, &mut tasks, map);
|
||||||
|
assert_eq!(take_expired(&mut queue).await.as_deref(), Some("uid"));
|
||||||
|
mark_running(&mut tasks, "uid");
|
||||||
|
|
||||||
|
Timer::apply_timer_map(&mut queue, &mut tasks, HashMap::new());
|
||||||
|
Timer::finish_task(&mut queue, &mut tasks, String::from("uid"));
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
tasks.is_empty(),
|
||||||
|
"a task retired mid-update must not outlive the update"
|
||||||
|
);
|
||||||
|
tokio::time::advance(Duration::from_secs(7200)).await;
|
||||||
|
assert!(nothing_due(&mut queue).await, "and must never be scheduled again");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test(start_paused = true)]
|
#[tokio::test(start_paused = true)]
|
||||||
async fn timer_profile_update_runs_past_former_deadline_and_pairs_events() -> anyhow::Result<()> {
|
async fn timer_profile_update_runs_past_former_deadline_and_pairs_events() -> anyhow::Result<()> {
|
||||||
let calls = Arc::new(Mutex::new(Vec::new()));
|
let calls = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
mod chain;
|
mod chain;
|
||||||
|
|
||||||
use self::chain::load_chain_item;
|
use self::chain::load_chain_item;
|
||||||
use crate::config::dns::DnsOverrideState;
|
use crate::config::dns::{DnsOverrideState, dns_override_source};
|
||||||
use crate::core::handle::Handle;
|
use crate::core::handle::Handle;
|
||||||
use crate::core::notify::NoticeStatus;
|
use crate::core::notify::NoticeStatus;
|
||||||
use crate::utils::dirs;
|
use crate::utils::dirs;
|
||||||
@@ -12,7 +12,7 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use anyhow::{Context as _, Result};
|
use anyhow::{Context as _, Result};
|
||||||
use clash_verge_config_render::{
|
use clash_verge_config_render::{
|
||||||
ChainItem, ChainType, RenderProfile, RenderSettings, RenderedConfig, ResultLog, SeqMap, override_source, render,
|
ChainItem, ChainType, RenderProfile, RenderSettings, RenderedConfig, ResultLog, SeqMap, render,
|
||||||
};
|
};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use serde_yaml_ng::Mapping;
|
use serde_yaml_ng::Mapping;
|
||||||
@@ -253,7 +253,7 @@ pub async fn render_runtime_config(
|
|||||||
let profile = collect_profile_items(profiles).await?;
|
let profile = collect_profile_items(profiles).await?;
|
||||||
let dns_override = DnsOverrideState::new(
|
let dns_override = DnsOverrideState::new(
|
||||||
profile_uid,
|
profile_uid,
|
||||||
override_source(profile_uid, &profile.config)?,
|
dns_override_source(profile_uid, &profile.config)?,
|
||||||
settings.enable_dns_settings,
|
settings.enable_dns_settings,
|
||||||
settings.dns_override_confirmation,
|
settings.dns_override_confirmation,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
use crate::core::notify::{Refresh, announce};
|
use crate::core::notify::{Refresh, announce};
|
||||||
use anyhow::{Result, ensure};
|
use anyhow::{Result, ensure};
|
||||||
use clash_verge_config_render::override_source;
|
|
||||||
use clash_verge_draft::DraftTransaction;
|
use clash_verge_draft::DraftTransaction;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use tristr::alias::String;
|
use tristr::alias::String;
|
||||||
@@ -8,7 +7,7 @@ use tristr::alias::String;
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::{
|
config::{
|
||||||
Config,
|
Config,
|
||||||
dns::ProfileDnsSettings,
|
dns::{ProfileDnsSettings, dns_override_source},
|
||||||
profiles::{PROFILE_WRITE_LOCK, current_mapping},
|
profiles::{PROFILE_WRITE_LOCK, current_mapping},
|
||||||
},
|
},
|
||||||
constants::files::DNS_CONFIG,
|
constants::files::DNS_CONFIG,
|
||||||
@@ -35,7 +34,7 @@ pub async fn set_dns_override(
|
|||||||
profiles.current.as_ref() == Some(&profile_uid),
|
profiles.current.as_ref() == Some(&profile_uid),
|
||||||
"The active profile changed; retry the DNS setting"
|
"The active profile changed; retry the DNS setting"
|
||||||
);
|
);
|
||||||
let source = override_source(
|
let source = dns_override_source(
|
||||||
profiles.current.as_deref().unwrap_or_default(),
|
profiles.current.as_deref().unwrap_or_default(),
|
||||||
¤t_mapping(&profiles).await?,
|
¤t_mapping(&profiles).await?,
|
||||||
)?;
|
)?;
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ pub async fn read_mapping(path: &Path) -> Result<Mapping> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
|
fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
|
||||||
match clash_verge_config_render::parse_short_id_safe(&yaml_str, &path) {
|
match parse_short_id_text(&yaml_str, &path) {
|
||||||
Ok(mut val) => {
|
Ok(mut val) => {
|
||||||
val.apply_merge()
|
val.apply_merge()
|
||||||
.with_context(|| format!("failed to apply merge \"{}\"", path.display()))?;
|
.with_context(|| format!("failed to apply merge \"{}\"", path.display()))?;
|
||||||
@@ -65,6 +65,74 @@ fn parse_mapping(yaml_str: String, path: PathBuf) -> Result<Mapping> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A float like `1234e123` loses its hex text, so retry with short-ids quoted and keep that only if nothing else changed.
|
||||||
|
fn parse_short_id_text(yaml: &str, path: &Path) -> serde_yaml_ng::Result<Value> {
|
||||||
|
let value = serde_yaml_ng::from_str::<Value>(yaml)?;
|
||||||
|
if !has_numeric_short_id(&value) {
|
||||||
|
return Ok(value);
|
||||||
|
}
|
||||||
|
match serde_yaml_ng::from_str::<Value>("e_short_ids(yaml)) {
|
||||||
|
Ok(quoted) if same_except_short_id(&value, "ed) => Ok(quoted),
|
||||||
|
_ => {
|
||||||
|
logging!(warn, Type::Config, "kept numeric short-id in {}", path.display());
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn quote_short_ids(yaml: &str) -> String {
|
||||||
|
let mut quoted = String::with_capacity(yaml.len());
|
||||||
|
let mut rest = yaml;
|
||||||
|
while let Some((head, tail)) = rest.split_once("short-id:") {
|
||||||
|
let (gap, value) = tail.split_at(tail.len() - tail.trim_start_matches([' ', '\t']).len());
|
||||||
|
let (id, after) = value.split_at(value.bytes().take_while(u8::is_ascii_hexdigit).count());
|
||||||
|
quoted.push_str(head);
|
||||||
|
quoted.push_str("short-id:");
|
||||||
|
quoted.push_str(gap);
|
||||||
|
if !id.is_empty() && (after.is_empty() || after.starts_with([' ', '\t', '\r', '\n', ',', '}'])) {
|
||||||
|
quoted.push('"');
|
||||||
|
quoted.push_str(id);
|
||||||
|
quoted.push('"');
|
||||||
|
} else {
|
||||||
|
quoted.push_str(id);
|
||||||
|
}
|
||||||
|
rest = after;
|
||||||
|
}
|
||||||
|
quoted.push_str(rest);
|
||||||
|
quoted
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_numeric_short_id(value: &Value) -> bool {
|
||||||
|
match value {
|
||||||
|
Value::Mapping(map) => map
|
||||||
|
.iter()
|
||||||
|
.any(|(key, value)| (is_short_id(key) && matches!(value, Value::Number(_))) || has_numeric_short_id(value)),
|
||||||
|
Value::Sequence(seq) => seq.iter().any(has_numeric_short_id),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn same_except_short_id(old: &Value, new: &Value) -> bool {
|
||||||
|
match (old, new) {
|
||||||
|
(Value::Mapping(old), Value::Mapping(new)) => {
|
||||||
|
old.len() == new.len()
|
||||||
|
&& old.iter().zip(new).all(|((key, old), (new_key, new))| {
|
||||||
|
key == new_key
|
||||||
|
&& (same_except_short_id(old, new)
|
||||||
|
|| (is_short_id(key) && matches!((old, new), (Value::Number(_), Value::String(_)))))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
(Value::Sequence(old), Value::Sequence(new)) => {
|
||||||
|
old.len() == new.len() && old.iter().zip(new).all(|(old, new)| same_except_short_id(old, new))
|
||||||
|
}
|
||||||
|
_ => old == new,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_short_id(key: &Value) -> bool {
|
||||||
|
key.as_str() == Some("short-id")
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
|
pub async fn save_yaml<T: Serialize + Sync>(path: &Path, data: &T, prefix: Option<&str>) -> Result<()> {
|
||||||
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
|
let data_str = with_encryption(|| async { serde_yaml_ng::to_string(data) }).await?;
|
||||||
|
|
||||||
@@ -143,6 +211,16 @@ pub fn get_uid(prefix: &str) -> String {
|
|||||||
format!("{prefix}{id}")
|
format!("{prefix}{id}")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn hex_encode(bytes: &[u8]) -> String {
|
||||||
|
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||||
|
let mut out = String::with_capacity(bytes.len() * 2);
|
||||||
|
for &byte in bytes {
|
||||||
|
out.push(HEX[usize::from(byte >> 4)] as char);
|
||||||
|
out.push(HEX[usize::from(byte & 0x0f)] as char);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// Masks query values and token-like path segments for logging.
|
/// Masks query values and token-like path segments for logging.
|
||||||
pub fn mask_url(url: &str) -> String {
|
pub fn mask_url(url: &str) -> String {
|
||||||
let (path_part, query_part) = match url.find('?') {
|
let (path_part, query_part) = match url.find('?') {
|
||||||
@@ -302,8 +380,9 @@ pub fn snapshot_path(original_path: &Path) -> Result<PathBuf> {
|
|||||||
#[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::parse_mapping;
|
use super::{parse_mapping, parse_short_id_text};
|
||||||
use std::path::PathBuf;
|
use serde_yaml_ng::Value;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn plain_short_id_stays_text() {
|
fn plain_short_id_stays_text() {
|
||||||
@@ -319,4 +398,19 @@ proxies:
|
|||||||
assert!(output.contains("short-id: '1234e123'"), "{output}");
|
assert!(output.contains("short-id: '1234e123'"), "{output}");
|
||||||
assert!(output.contains("short-id: '0e5'"), "{output}");
|
assert!(output.contains("short-id: '0e5'"), "{output}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn short_id_quoting_changing_other_values_is_dropped() {
|
||||||
|
let profile = "\
|
||||||
|
proxies:
|
||||||
|
- name: a
|
||||||
|
reality-opts:
|
||||||
|
short-id: 1234e123
|
||||||
|
note: |
|
||||||
|
short-id: 1234e123
|
||||||
|
";
|
||||||
|
let today = serde_yaml_ng::from_str::<Value>(profile).expect("profile should parse");
|
||||||
|
let value = parse_short_id_text(profile, Path::new("profile.yaml")).expect("profile should parse");
|
||||||
|
assert_eq!(value, today);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,9 +49,10 @@ enum TlsRootMode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// ALPN stays unset: raw TLS connectors offer none, while reqwest needs the h2 offer.
|
/// ALPN stays unset: raw TLS connectors offer none, while reqwest needs the h2 offer.
|
||||||
|
/// The provider is passed explicitly: both rustls providers are compiled in, so the process default may vary.
|
||||||
pub(crate) fn build_webpki_rooted_tls_config() -> Result<rustls::ClientConfig> {
|
pub(crate) fn build_webpki_rooted_tls_config() -> Result<rustls::ClientConfig> {
|
||||||
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::aws_lc_rs::default_provider()))
|
||||||
.with_safe_default_protocol_versions()?
|
.with_safe_default_protocol_versions()?
|
||||||
.with_root_certificates(root_store)
|
.with_root_certificates(root_store)
|
||||||
.with_no_client_auth();
|
.with_no_client_auth();
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
use anyhow::{Context as _, bail, ensure};
|
use anyhow::{Context as _, bail, ensure};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
|
use serde_yaml_ng::{Mapping, Value};
|
||||||
use std::{
|
use std::{
|
||||||
io::Read as _,
|
io::Read as _,
|
||||||
os::unix::process::CommandExt as _,
|
os::unix::process::CommandExt as _,
|
||||||
@@ -23,6 +24,23 @@ fn dns_state_dir() -> anyhow::Result<PathBuf> {
|
|||||||
Ok(dir)
|
Ok(dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Without the placeholder, a LAN resolver is reached outside TUN and fake-ip is bypassed.
|
||||||
|
fn needs_public_dns(config: &Mapping) -> bool {
|
||||||
|
let section = |name: &str| config.get(name).and_then(Value::as_mapping);
|
||||||
|
let enabled = |name: &str| {
|
||||||
|
section(name)
|
||||||
|
.and_then(|map| map.get("enable"))
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false)
|
||||||
|
};
|
||||||
|
enabled("tun")
|
||||||
|
&& enabled("dns")
|
||||||
|
&& section("dns")
|
||||||
|
.and_then(|dns| dns.get("enhanced-mode"))
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
== Some("fake-ip")
|
||||||
|
}
|
||||||
|
|
||||||
/// Sets the placeholder DNS while the running config needs it, and restores the system DNS otherwise.
|
/// Sets the placeholder DNS while the running config needs it, and restores the system DNS otherwise.
|
||||||
#[allow(
|
#[allow(
|
||||||
clippy::significant_drop_tightening,
|
clippy::significant_drop_tightening,
|
||||||
@@ -41,12 +59,7 @@ pub async fn sync_public_dns() {
|
|||||||
}
|
}
|
||||||
let core_running = !matches!(*CoreManager::global().get_running_mode(), RunningMode::NotRunning);
|
let core_running = !matches!(*CoreManager::global().get_running_mode(), RunningMode::NotRunning);
|
||||||
let runtime = Config::runtime().await.latest_arc();
|
let runtime = Config::runtime().await.latest_arc();
|
||||||
if core_running
|
if core_running && runtime.config.as_ref().is_some_and(needs_public_dns) {
|
||||||
&& runtime
|
|
||||||
.config
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(clash_verge_config_render::needs_public_dns)
|
|
||||||
{
|
|
||||||
set_public_dns(guard).await;
|
set_public_dns(guard).await;
|
||||||
} else {
|
} else {
|
||||||
let _ = unset_public_dns(guard).await;
|
let _ = unset_public_dns(guard).await;
|
||||||
|
|||||||
@@ -1,12 +1,15 @@
|
|||||||
import { CloseRounded } from '@mui/icons-material'
|
import { CloseRounded } from '@mui/icons-material'
|
||||||
import { IconButton } from '@mui/material'
|
import { IconButton } from '@mui/material'
|
||||||
import { useLockFn } from 'ahooks'
|
import { useLockFn } from 'ahooks'
|
||||||
import { memo, useCallback } from 'react'
|
import { memo, useCallback, useMemo } from 'react'
|
||||||
import { useTranslation } from 'react-i18next'
|
import { useTranslation } from 'react-i18next'
|
||||||
import { closeConnection } from 'tauri-plugin-mihomo-api'
|
import { closeConnection } from 'tauri-plugin-mihomo-api'
|
||||||
|
|
||||||
import { RelativeTime } from './connection-relative-time'
|
import { RelativeTime } from './connection-relative-time'
|
||||||
import type { ConnectionRowView } from './connection-row-view'
|
import {
|
||||||
|
createConnectionRowView,
|
||||||
|
type ConnectionRowView,
|
||||||
|
} from './connection-row-view'
|
||||||
import type { ConnectionRuleKind } from './connection-rule'
|
import type { ConnectionRuleKind } from './connection-rule'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -70,7 +73,7 @@ const actionStyle = {
|
|||||||
transform: 'translateY(-50%)',
|
transform: 'translateY(-50%)',
|
||||||
} as const
|
} as const
|
||||||
|
|
||||||
export const ConnectionRowItem = memo(
|
const ConnectionRowItem = memo(
|
||||||
function ConnectionRowItem({ row, closed, onShowDetail }: Props) {
|
function ConnectionRowItem({ row, closed, onShowDetail }: Props) {
|
||||||
const { t } = useTranslation()
|
const { t } = useTranslation()
|
||||||
const onDelete = useLockFn(async () => closeConnection(row.id))
|
const onDelete = useLockFn(async () => closeConnection(row.id))
|
||||||
@@ -129,3 +132,11 @@ export const ConnectionRowItem = memo(
|
|||||||
prev.closed === next.closed &&
|
prev.closed === next.closed &&
|
||||||
prev.onShowDetail === next.onShowDetail,
|
prev.onShowDetail === next.onShowDetail,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
export const VisibleConnectionRowItem = memo(function VisibleConnectionRowItem({
|
||||||
|
connection,
|
||||||
|
...props
|
||||||
|
}: Omit<Props, 'row'> & { connection: IConnectionsItem }) {
|
||||||
|
const row = useMemo(() => createConnectionRowView(connection), [connection])
|
||||||
|
return <ConnectionRowItem row={row} {...props} />
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import { useMemo, useRef } from 'react'
|
|
||||||
|
|
||||||
const TRAFFIC_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
|
const TRAFFIC_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
|
||||||
|
|
||||||
export interface ConnectionRowView {
|
export interface ConnectionRowView {
|
||||||
@@ -85,7 +83,7 @@ export const getConnectionTypeLabel = (connection: IConnectionsItem) => {
|
|||||||
export const getConnectionStartTime = (connection: IConnectionsItem) =>
|
export const getConnectionStartTime = (connection: IConnectionsItem) =>
|
||||||
Date.parse(connection.start || '') || 0
|
Date.parse(connection.start || '') || 0
|
||||||
|
|
||||||
const createConnectionRowView = (connection: IConnectionsItem) => {
|
export const createConnectionRowView = (connection: IConnectionsItem) => {
|
||||||
const uploadSpeed = connection.curUpload ?? 0
|
const uploadSpeed = connection.curUpload ?? 0
|
||||||
const downloadSpeed = connection.curDownload ?? 0
|
const downloadSpeed = connection.curDownload ?? 0
|
||||||
|
|
||||||
@@ -114,66 +112,3 @@ const createConnectionRowView = (connection: IConnectionsItem) => {
|
|||||||
searchableProcess: connection.metadata.process || '',
|
searchableProcess: connection.metadata.process || '',
|
||||||
} satisfies ConnectionRowView
|
} satisfies ConnectionRowView
|
||||||
}
|
}
|
||||||
|
|
||||||
const sameConnectionRowView = (
|
|
||||||
left: ConnectionRowView,
|
|
||||||
right: ConnectionRowView,
|
|
||||||
) =>
|
|
||||||
left.host === right.host &&
|
|
||||||
left.process === right.process &&
|
|
||||||
left.network === right.network &&
|
|
||||||
left.type === right.type &&
|
|
||||||
left.chains === right.chains &&
|
|
||||||
left.rule === right.rule &&
|
|
||||||
left.time === right.time &&
|
|
||||||
left.source === right.source &&
|
|
||||||
left.destination === right.destination &&
|
|
||||||
left.uploadText === right.uploadText &&
|
|
||||||
left.downloadText === right.downloadText &&
|
|
||||||
left.uploadSpeedText === right.uploadSpeedText &&
|
|
||||||
left.downloadSpeedText === right.downloadSpeedText &&
|
|
||||||
left.upload === right.upload &&
|
|
||||||
left.download === right.download &&
|
|
||||||
left.uploadSpeed === right.uploadSpeed &&
|
|
||||||
left.downloadSpeed === right.downloadSpeed &&
|
|
||||||
left.searchableHost === right.searchableHost &&
|
|
||||||
left.searchableDestinationIP === right.searchableDestinationIP &&
|
|
||||||
left.searchableProcess === right.searchableProcess
|
|
||||||
|
|
||||||
export const useConnectionRowViews = (connections: IConnectionsItem[]) => {
|
|
||||||
const previousRowsRef = useRef(new Map<string, ConnectionRowView>())
|
|
||||||
const previousConnectionsRef = useRef(new Map<string, IConnectionsItem>())
|
|
||||||
|
|
||||||
return useMemo(() => {
|
|
||||||
const previousRows = previousRowsRef.current
|
|
||||||
const previousConnections = previousConnectionsRef.current
|
|
||||||
const nextRows = new Map<string, ConnectionRowView>()
|
|
||||||
const nextConnections = new Map<string, IConnectionsItem>()
|
|
||||||
const rows: ConnectionRowView[] = []
|
|
||||||
|
|
||||||
connections.forEach((connection) => {
|
|
||||||
nextConnections.set(connection.id, connection)
|
|
||||||
|
|
||||||
const previousRow = previousRows.get(connection.id)
|
|
||||||
const previousConnection = previousConnections.get(connection.id)
|
|
||||||
|
|
||||||
let row: ConnectionRowView
|
|
||||||
if (previousRow && previousConnection === connection) {
|
|
||||||
row = previousRow
|
|
||||||
} else {
|
|
||||||
const nextRow = createConnectionRowView(connection)
|
|
||||||
row =
|
|
||||||
previousRow && sameConnectionRowView(previousRow, nextRow)
|
|
||||||
? previousRow
|
|
||||||
: nextRow
|
|
||||||
}
|
|
||||||
|
|
||||||
nextRows.set(connection.id, row)
|
|
||||||
rows.push(row)
|
|
||||||
})
|
|
||||||
|
|
||||||
previousRowsRef.current = nextRows
|
|
||||||
previousConnectionsRef.current = nextConnections
|
|
||||||
return rows
|
|
||||||
}, [connections])
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -232,11 +232,51 @@ const getConnectionCellValue = (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const compareConnectionCellValue = (
|
type TrafficSortField = 'download' | 'upload' | 'dlSpeed' | 'ulSpeed'
|
||||||
field: ColumnField,
|
type DisplaySortField = Exclude<ColumnField, TrafficSortField>
|
||||||
|
|
||||||
|
const connectionSortKey = (field: DisplaySortField, row: IConnectionsItem) => {
|
||||||
|
switch (field) {
|
||||||
|
case 'host':
|
||||||
|
return getConnectionHost(row)
|
||||||
|
case 'process':
|
||||||
|
return getConnectionProcess(row)
|
||||||
|
case 'source':
|
||||||
|
return getConnectionSource(row)
|
||||||
|
case 'remoteDestination':
|
||||||
|
return getConnectionDestination(row)
|
||||||
|
case 'chains':
|
||||||
|
return formatConnectionChains(row.chains)
|
||||||
|
case 'rule':
|
||||||
|
return getConnectionRule(row)
|
||||||
|
case 'type':
|
||||||
|
return getConnectionTypeLabel(row)
|
||||||
|
case 'time':
|
||||||
|
return getConnectionStartTime(row)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortByConnectionKey = (
|
||||||
|
connections: IConnectionsItem[],
|
||||||
|
field: DisplaySortField,
|
||||||
|
direction: number,
|
||||||
|
) => {
|
||||||
|
return connections
|
||||||
|
.map((row) => ({ row, key: connectionSortKey(field, row) }))
|
||||||
|
.sort((a, b) => {
|
||||||
|
const order =
|
||||||
|
typeof a.key === 'number'
|
||||||
|
? (Number(a.key) || 0) - (Number(b.key) || 0)
|
||||||
|
: String(a.key).localeCompare(String(b.key))
|
||||||
|
return order * direction
|
||||||
|
})
|
||||||
|
.map(({ row }) => row)
|
||||||
|
}
|
||||||
|
|
||||||
|
const compareConnectionTraffic = (
|
||||||
|
field: TrafficSortField,
|
||||||
left: IConnectionsItem,
|
left: IConnectionsItem,
|
||||||
right: IConnectionsItem,
|
right: IConnectionsItem,
|
||||||
getSnapshot: (row: IConnectionsItem) => TableRowSnapshot,
|
|
||||||
) => {
|
) => {
|
||||||
switch (field) {
|
switch (field) {
|
||||||
case 'download':
|
case 'download':
|
||||||
@@ -248,14 +288,6 @@ const compareConnectionCellValue = (
|
|||||||
case 'ulSpeed':
|
case 'ulSpeed':
|
||||||
return (left.curUpload ?? 0) - (right.curUpload ?? 0)
|
return (left.curUpload ?? 0) - (right.curUpload ?? 0)
|
||||||
}
|
}
|
||||||
const leftValue = getConnectionCellValue(field, getSnapshot(left))
|
|
||||||
const rightValue = getConnectionCellValue(field, getSnapshot(right))
|
|
||||||
|
|
||||||
if (typeof leftValue === 'number' || typeof rightValue === 'number') {
|
|
||||||
return (Number(leftValue) || 0) - (Number(rightValue) || 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
return String(leftValue ?? '').localeCompare(String(rightValue ?? ''))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const renderCell = (
|
const renderCell = (
|
||||||
@@ -589,13 +621,21 @@ export const ConnectionTable = (props: Props) => {
|
|||||||
const sortedConnections = useMemo(() => {
|
const sortedConnections = useMemo(() => {
|
||||||
if (!sorting) return connections
|
if (!sorting) return connections
|
||||||
|
|
||||||
const direction = sorting.desc ? -1 : 1
|
const { id, desc } = sorting
|
||||||
|
const direction = desc ? -1 : 1
|
||||||
|
if (
|
||||||
|
id === 'download' ||
|
||||||
|
id === 'upload' ||
|
||||||
|
id === 'dlSpeed' ||
|
||||||
|
id === 'ulSpeed'
|
||||||
|
) {
|
||||||
return [...connections].sort(
|
return [...connections].sort(
|
||||||
(left, right) =>
|
(left, right) => compareConnectionTraffic(id, left, right) * direction,
|
||||||
compareConnectionCellValue(sorting.id, left, right, getRowSnapshot) *
|
|
||||||
direction,
|
|
||||||
)
|
)
|
||||||
}, [connections, sorting, getRowSnapshot])
|
}
|
||||||
|
|
||||||
|
return sortByConnectionKey(connections, id, direction)
|
||||||
|
}, [connections, sorting])
|
||||||
|
|
||||||
const tableWidth = useMemo(
|
const tableWidth = useMemo(
|
||||||
() => visibleColumns.reduce((total, column) => total + column.size, 0),
|
() => visibleColumns.reduce((total, column) => total + column.size, 0),
|
||||||
|
|||||||
@@ -118,7 +118,7 @@ export const TunnelsViewer = forwardRef<TunnelsViewerRef>((_, ref) => {
|
|||||||
})
|
})
|
||||||
}, [draftTunnels])
|
}, [draftTunnels])
|
||||||
|
|
||||||
const { proxyView } = useProxiesData()
|
const { proxyView } = useProxiesData(open)
|
||||||
|
|
||||||
const proxyGroups = useMemo(() => proxyView?.groups ?? [], [proxyView])
|
const proxyGroups = useMemo(() => proxyView?.groups ?? [], [proxyView])
|
||||||
|
|
||||||
|
|||||||
@@ -30,11 +30,8 @@ import {
|
|||||||
ConnectionDetail,
|
ConnectionDetail,
|
||||||
ConnectionDetailRef,
|
ConnectionDetailRef,
|
||||||
} from '@/components/connection/connection-detail'
|
} from '@/components/connection/connection-detail'
|
||||||
import { ConnectionRowItem } from '@/components/connection/connection-row-item'
|
import { VisibleConnectionRowItem } from '@/components/connection/connection-row-item'
|
||||||
import {
|
import { getConnectionStartTime } from '@/components/connection/connection-row-view'
|
||||||
getConnectionStartTime,
|
|
||||||
useConnectionRowViews,
|
|
||||||
} from '@/components/connection/connection-row-view'
|
|
||||||
import type { ConnectionRuleKind } from '@/components/connection/connection-rule'
|
import type { ConnectionRuleKind } from '@/components/connection/connection-rule'
|
||||||
import { ConnectionTable } from '@/components/connection/connection-table'
|
import { ConnectionTable } from '@/components/connection/connection-table'
|
||||||
import { useConnectionData } from '@/hooks/use-connection-data'
|
import { useConnectionData } from '@/hooks/use-connection-data'
|
||||||
@@ -145,10 +142,6 @@ const ConnectionsPage = () => {
|
|||||||
curOrderOpt,
|
curOrderOpt,
|
||||||
])
|
])
|
||||||
|
|
||||||
const displayRows = useConnectionRowViews(
|
|
||||||
isTableLayout ? EMPTY_CONNECTIONS : filterConn,
|
|
||||||
)
|
|
||||||
|
|
||||||
const detailRef = useRef<ConnectionDetailRef>(null!)
|
const detailRef = useRef<ConnectionDetailRef>(null!)
|
||||||
|
|
||||||
const selectConnectionsType = useCallback(
|
const selectConnectionsType = useCallback(
|
||||||
@@ -339,11 +332,11 @@ const ConnectionsPage = () => {
|
|||||||
) : (
|
) : (
|
||||||
<VirtualList
|
<VirtualList
|
||||||
key={connectionsType}
|
key={connectionsType}
|
||||||
count={displayRows.length}
|
count={filterConn.length}
|
||||||
estimateSize={56}
|
estimateSize={56}
|
||||||
renderItem={(i) => (
|
renderItem={(i) => (
|
||||||
<ConnectionRowItem
|
<VisibleConnectionRowItem
|
||||||
row={displayRows[i]}
|
connection={filterConn[i]}
|
||||||
closed={connectionsType === 'closed'}
|
closed={connectionsType === 'closed'}
|
||||||
onShowDetail={showDetailById}
|
onShowDetail={showDetailById}
|
||||||
/>
|
/>
|
||||||
|
|||||||
+8
-10
@@ -52,21 +52,16 @@ const LogPage = () => {
|
|||||||
})
|
})
|
||||||
}, [logData, logState, match, searchState.text])
|
}, [logData, logState, match, searchState.text])
|
||||||
|
|
||||||
const filteredLogs = useMemo(
|
|
||||||
() => (isDescending ? [...filterLogs].reverse() : filterLogs),
|
|
||||||
[filterLogs, isDescending],
|
|
||||||
)
|
|
||||||
|
|
||||||
const scrollRef = useRef({ isNearBottom: true })
|
const scrollRef = useRef({ isNearBottom: true })
|
||||||
const virtuosoRef = useRef<VirtualListHandle>(null)
|
const virtuosoRef = useRef<VirtualListHandle>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isDescending && scrollRef.current.isNearBottom) {
|
if (!isDescending && scrollRef.current.isNearBottom) {
|
||||||
virtuosoRef.current?.scrollToIndex(filteredLogs.length - 1, {
|
virtuosoRef.current?.scrollToIndex(filterLogs.length - 1, {
|
||||||
behavior: 'smooth',
|
behavior: 'smooth',
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}, [isDescending, filteredLogs.length])
|
}, [isDescending, filterLogs.length])
|
||||||
|
|
||||||
const handleLogLevelChange = (newLevel: LogFilter) => {
|
const handleLogLevelChange = (newLevel: LogFilter) => {
|
||||||
setClashLog((pre) => ({ ...pre!, logFilter: newLevel }))
|
setClashLog((pre) => ({ ...pre!, logFilter: newLevel }))
|
||||||
@@ -176,13 +171,16 @@ const LogPage = () => {
|
|||||||
/>
|
/>
|
||||||
</Box>
|
</Box>
|
||||||
|
|
||||||
{filteredLogs.length > 0 ? (
|
{filterLogs.length > 0 ? (
|
||||||
<VirtualList
|
<VirtualList
|
||||||
ref={virtuosoRef}
|
ref={virtuosoRef}
|
||||||
count={filteredLogs.length}
|
count={filterLogs.length}
|
||||||
estimateSize={50}
|
estimateSize={50}
|
||||||
renderItem={(i) => (
|
renderItem={(i) => (
|
||||||
<LogItem value={filteredLogs[i]} searchState={searchState} />
|
<LogItem
|
||||||
|
value={filterLogs[isDescending ? filterLogs.length - 1 - i : i]}
|
||||||
|
searchState={searchState}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
onScroll={(event) => {
|
onScroll={(event) => {
|
||||||
const element = event.currentTarget as HTMLDivElement
|
const element = event.currentTarget as HTMLDivElement
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Context, createContext, use } from 'react'
|
import { Context, createContext, use, useEffect } from 'react'
|
||||||
import { BaseConfig, Rule, RuleProvider } from 'tauri-plugin-mihomo-api'
|
import { BaseConfig, Rule, RuleProvider } from 'tauri-plugin-mihomo-api'
|
||||||
|
|
||||||
import type { ProxyViewV1 } from '@/types/proxy-view'
|
import type { ProxyViewV1 } from '@/types/proxy-view'
|
||||||
@@ -39,7 +39,9 @@ export interface RefreshersContextType {
|
|||||||
refreshAll: () => Promise<unknown>
|
refreshAll: () => Promise<unknown>
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ProxiesContext = createContext<ProxiesContextType | null>(null)
|
export const ProxiesContext = createContext<
|
||||||
|
(ProxiesContextType & { registerConsumer: () => () => void }) | null
|
||||||
|
>(null)
|
||||||
export const RulesContext = createContext<RulesContextType | null>(null)
|
export const RulesContext = createContext<RulesContextType | null>(null)
|
||||||
export const ClashConfigContext = createContext<ClashConfigContextType | null>(
|
export const ClashConfigContext = createContext<ClashConfigContextType | null>(
|
||||||
null,
|
null,
|
||||||
@@ -57,8 +59,16 @@ const useCtx = <T>(ctx: Context<T | null>, hookName: string): T => {
|
|||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
|
|
||||||
export const useProxiesData = (): ProxiesContextType =>
|
export const useProxiesData = (active = true): ProxiesContextType => {
|
||||||
useCtx(ProxiesContext, 'useProxiesData')
|
const data = useCtx(ProxiesContext, 'useProxiesData')
|
||||||
|
const { registerConsumer } = data
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (active) return registerConsumer()
|
||||||
|
}, [active, registerConsumer])
|
||||||
|
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|
||||||
export const useRulesData = () => {
|
export const useRulesData = () => {
|
||||||
const { rules, ruleProviders } = useCtx(RulesContext, 'useRulesData')
|
const { rules, ruleProviders } = useCtx(RulesContext, 'useRulesData')
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import React, { useCallback, useMemo, useRef } from 'react'
|
import React, { useCallback, useMemo, useRef, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
getBaseConfig,
|
getBaseConfig,
|
||||||
getRuleProviders,
|
getRuleProviders,
|
||||||
@@ -53,6 +53,11 @@ export const AppDataProvider = ({
|
|||||||
const { verge } = useVerge()
|
const { verge } = useVerge()
|
||||||
const { data: runtimeConfig } = useRuntimeConfig()
|
const { data: runtimeConfig } = useRuntimeConfig()
|
||||||
const { clashInfo } = useClashInfo()
|
const { clashInfo } = useClashInfo()
|
||||||
|
const [proxyViewConsumers, setProxyViewConsumers] = useState(0)
|
||||||
|
const registerProxyViewConsumer = useCallback(() => {
|
||||||
|
setProxyViewConsumers((count) => count + 1)
|
||||||
|
return () => setProxyViewConsumers((count) => count - 1)
|
||||||
|
}, [])
|
||||||
|
|
||||||
const {
|
const {
|
||||||
data: proxyView,
|
data: proxyView,
|
||||||
@@ -62,7 +67,7 @@ export const AppDataProvider = ({
|
|||||||
} = useQuery({
|
} = useQuery({
|
||||||
queryKey: ['getProxyView'],
|
queryKey: ['getProxyView'],
|
||||||
queryFn: getProxyView,
|
queryFn: getProxyView,
|
||||||
refetchInterval: 15000,
|
refetchInterval: proxyViewConsumers > 0 ? 15000 : false,
|
||||||
refetchIntervalInBackground: false,
|
refetchIntervalInBackground: false,
|
||||||
...TQ_MIHOMO,
|
...TQ_MIHOMO,
|
||||||
})
|
})
|
||||||
@@ -128,8 +133,9 @@ export const AppDataProvider = ({
|
|||||||
proxyView,
|
proxyView,
|
||||||
isProxyViewPending,
|
isProxyViewPending,
|
||||||
isProxyViewError: Boolean(proxyViewError),
|
isProxyViewError: Boolean(proxyViewError),
|
||||||
|
registerConsumer: registerProxyViewConsumer,
|
||||||
}),
|
}),
|
||||||
[proxyView, isProxyViewPending, proxyViewError],
|
[proxyView, isProxyViewPending, proxyViewError, registerProxyViewConsumer],
|
||||||
)
|
)
|
||||||
|
|
||||||
const rulesValue = useMemo(
|
const rulesValue = useMemo(
|
||||||
|
|||||||
Reference in New Issue
Block a user