diff --git a/AGENTS.md b/AGENTS.md index e64505af7..d4c227efd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,6 +60,10 @@ the ownership evidence the AI-slop review evaluates (see - For development and bug fixes, follow the [development workflow](CONTRIBUTING.md#development-workflow). +- For Rust backend changes that affect capability ownership or dependency + boundaries, follow [Workspace Crate Architecture](crates/AGENTS.md). + For Tauri commands and desktop integration, also follow + [Backend Architecture Guardrails](src-tauri/AGENTS.md). - For code review and verification of review fixes, follow [REVIEW.md](REVIEW.md). Review is read-only unless changes are authorized; findings do not expand that authorization to unrelated fixes, commits, pushes, or GitHub updates. diff --git a/Cargo.lock b/Cargo.lock index 520ee55c3..2012fa485 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1109,12 +1109,15 @@ dependencies = [ "boa_engine", "bytes", "chrono", + "clash-verge-backup-archive", "clash-verge-draft", "clash-verge-i18n", "clash-verge-limiter", "clash-verge-logging", "clash-verge-media-unlock", + "clash-verge-profile", "clash-verge-signal", + "clash-verge-subscription", "clash-verge-task", "clash_verge_service_ipc", "dark-light", @@ -1184,13 +1187,21 @@ dependencies = [ "zip", ] +[[package]] +name = "clash-verge-backup-archive" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.20", + "zip", +] + [[package]] name = "clash-verge-draft" version = "0.1.0" dependencies = [ - "anyhow", "criterion", "parking_lot 0.13.0", + "thiserror 2.0.20", "tokio", ] @@ -1214,10 +1225,10 @@ dependencies = [ name = "clash-verge-logging" version = "0.1.0" dependencies = [ - "anyhow", "flexi_logger", "log", "parking_lot 0.13.0", + "thiserror 2.0.20", "tracing-estuary", ] @@ -1236,6 +1247,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "clash-verge-profile" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "serde_yaml_ng", + "specta", + "thiserror 2.0.20", + "tristr", +] + [[package]] name = "clash-verge-signal" version = "0.1.0" @@ -1245,6 +1268,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "clash-verge-subscription" +version = "0.1.0" +dependencies = [ + "http", + "percent-encoding", + "serde_yaml_ng", + "thiserror 2.0.20", + "url", +] + [[package]] name = "clash-verge-task" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index e6208cdce..2b211583e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,9 @@ members = [ "crates/tauri-plugin-clash-verge-sysinfo", "crates/clash-verge-i18n", "crates/clash-verge-limiter", + "crates/clash-verge-subscription", + "crates/clash-verge-profile", + "crates/clash-verge-backup-archive", ] resolver = "2" @@ -60,6 +63,9 @@ clash-verge-logging = { path = "crates/clash-verge-logging" } clash-verge-signal = { path = "crates/clash-verge-signal" } clash-verge-i18n = { path = "crates/clash-verge-i18n" } clash-verge-limiter = { path = "crates/clash-verge-limiter" } +clash-verge-subscription = { path = "crates/clash-verge-subscription" } +clash-verge-profile = { path = "crates/clash-verge-profile" } +clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" } tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" } tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" } tracing = "0.1.44" @@ -68,6 +74,8 @@ tauri = { version = "2.13.0" } tauri-plugin-clipboard-manager = "2.5.0" parking_lot = "0.13.0" anyhow = "1.0.105" +thiserror = "2.0.20" +zip = "9.9.0" futures = "0.3.34" loom = "0.7.3" proptest = "1.12.0" @@ -94,6 +102,7 @@ serde = { version = "1.0.229" } tristr = { git = "https://github.com/Tunglies/tristr", rev = "d849e5cff47a570849c2e1bada0a2b6481cf3378", default-features = false, features = ["serde", "specta"] } serde_json = { version = "1.0.154" } serde_yaml_ng = { version = "0.10.0" } +specta = "=2.0.0-rc.26" socket2 = "0.6.5" # *** For Windows platform only *** @@ -130,7 +139,6 @@ copy_iterator = "deny" correctness = { level = "deny", priority = -1 } dbg_macro = "warn" equatable_if_let = "deny" -expect_used = "warn" expl_impl_clone_on_copy = "deny" future_not_send = "deny" iter_on_empty_collections = "deny" @@ -169,7 +177,6 @@ unnecessary_self_imports = "deny" unnecessary_wraps = "deny" unused_async = "deny" unused_trait_names = "deny" -unwrap_used = "warn" use_self = "deny" useless_let_if_seq = "deny" wildcard_imports = "deny" diff --git a/Changelog.md b/Changelog.md index 50b0d60e6..3d500e11d 100644 --- a/Changelog.md +++ b/Changelog.md @@ -33,6 +33,7 @@ - 修复检测更新后又发布新版时,应用内更新失败 - 修复关闭「自动检查更新」后,手动检查更新时弹窗空白 - 修复订阅响应过大导致内存占用过高,限制单次下载为 4 MiB +- 修复服务端文件名无效时导入的订阅名称为空 - 修复全局模式默认停在 `DIRECT` 或 `REJECT` 导致流量未经代理,现自动切换到第一个策略组 - 修复订阅中未加引号的 REALITY `short-id`(如 `1234e123`)被误读为数字,导致订阅无法启用 - 修复订阅中唯一的代理组名为 `GLOBAL` 或没有代理组时,规则模式下代理页面显示「未获取到代理信息」 diff --git a/crates/.clippy.toml b/crates/.clippy.toml new file mode 100644 index 000000000..6853f759c --- /dev/null +++ b/crates/.clippy.toml @@ -0,0 +1,5 @@ +# Clippy loads a single configuration file, so repeat the workspace defaults. +avoid-breaking-exported-api = true +allow-unwrap-in-tests = true +cognitive-complexity-threshold = 25 +excessive-nesting-threshold = 5 diff --git a/crates/AGENTS.md b/crates/AGENTS.md index 5436a3d04..f6fc71da3 100644 --- a/crates/AGENTS.md +++ b/crates/AGENTS.md @@ -2,19 +2,34 @@ ## Choose the boundary +- Apply Functional Core, Imperative Shell and Ports and Adapters. Keep domain + types, invariants, parsing, validation, and deterministic transitions + independent of Tauri, concrete OS APIs, and implicit application state. +- Keep use cases, async coordination, cancellation, and timeouts in + framework-independent application modules. Pass dependencies explicitly. + Define ports where an external effect needs a contract. Adapters implement + the contracts owned by their consumers. Keep filesystem, network, IPC, process, + and OS-specific operations in their adapters. - Extract a capability whose invariants can be owned behind a small API. Before creating a crate, identify its owner, what callers supply, and what can be - verified through the crate API. Keep a module when the proposed boundary only - relocates implementation or introduces a pass-through API. -- Keep the dependency direction from the app to the crate. Resolve app paths, - read product settings, start app-owned tasks, and publish UI events in the app. - Pass the values, resources, or callbacks the crate needs. For example, + verified through the crate API. Extract a crate when it provides a useful + dependency, portability, testing, or ownership boundary. Keep a module when + the proposed boundary only relocates implementation or introduces a + pass-through API. +- Keep capability crates independent by default. Compose peer capabilities in + the application and pass inputs or callbacks through the consumer's API. + Depend on another workspace crate for foundational mechanisms such as logging + and task primitives, or for a shared domain contract required to enforce the + same invariant. Keep tightly coupled rules together when separating them + would duplicate that contract or split its ownership. +- Keep dependencies pointing toward domain and application contracts. Resolve + app paths and read current settings at the application boundary. Pass in the + required values, resources, or callbacks. For example, [logging](clash-verge-logging/src/lib.rs) owns its pipeline and writers while the app supplies directories and limits through `LoggerConfig`. -- Keep framework and platform dependencies scoped to the capability that needs - them. Runtime-independent logic should be runnable without the desktop app. - A platform adapter can own runtime startup when its resource lifetime requires - it, as [signal](clash-verge-signal/src/lib.rs) does for Linux shutdown. +- Run framework-independent tests without starting the desktop app. A platform + adapter can own runtime startup when its resource lifetime requires it, as + [signal](clash-verge-signal/src/lib.rs) does for Linux shutdown. ## Design the API @@ -31,6 +46,14 @@ workspace lints. Reuse workspace dependencies where available and declare only the features the crate needs. +## Handle fallible input + +- Define crate-owned error types with `thiserror` in a dedicated `error` module. + Re-export public errors through their established import paths. +- Crates may use `unwrap()` or `expect()` for internal invariants. Propagate + errors from required external data and use defaults only when the input + contract gives the default a meaning. + ## Own background work - Give ordered start, replacement, and cleanup to one task owner. Reuse @@ -43,6 +66,20 @@ transaction boundaries and keep the reply path free of locks held by the waiting caller. Cancel only at safe boundaries and own issued effects through completion or explicit reconciliation. +- Distinguish requested effects from completed effects in typed outcomes. + Define how failures, cancellation, and timeouts affect publication, retry, + rollback, or reconciliation. + +## Validate new crates + +- Fuzz the public boundary before tuning. Exercise malformed input, fallback + behavior, and failures that can affect user data. Preserve the corpus and + record the baseline revision and dependency resolution. +- Try at least one targeted performance improvement. Compare the baseline and + candidate on the same workload and build settings. Record stable gains, flat + cases, and regressions, and justify which changes to keep. +- Fuzz the final candidate again. Use the baseline corpus and compare outputs, + diagnostics, and errors with the baseline where behavior should be preserved. Verify the extracted contract through its public API when practical. Use `cargo test -p ` for focused tests and keep native behavior checks at the diff --git a/crates/clash-verge-backup-archive/Cargo.toml b/crates/clash-verge-backup-archive/Cargo.toml new file mode 100644 index 000000000..47ec0396b --- /dev/null +++ b/crates/clash-verge-backup-archive/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "clash-verge-backup-archive" +version = "0.1.0" +edition = "2024" + +[dependencies] +thiserror = { workspace = true } +zip = { workspace = true } + +[lints] +workspace = true diff --git a/crates/clash-verge-backup-archive/src/error.rs b/crates/clash-verge-backup-archive/src/error.rs new file mode 100644 index 000000000..d675c75fb --- /dev/null +++ b/crates/clash-verge-backup-archive/src/error.rs @@ -0,0 +1,7 @@ +#[derive(Debug, thiserror::Error)] +pub enum ArchiveError { + #[error(transparent)] + Zip(#[from] zip::result::ZipError), + #[error(transparent)] + Io(#[from] std::io::Error), +} diff --git a/crates/clash-verge-backup-archive/src/lib.rs b/crates/clash-verge-backup-archive/src/lib.rs new file mode 100644 index 000000000..27a00ff15 --- /dev/null +++ b/crates/clash-verge-backup-archive/src/lib.rs @@ -0,0 +1,65 @@ +mod error; + +pub use error::ArchiveError; + +use std::io::{Seek, Write}; +use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions}; + +pub struct BackupWriter { + zip: ZipWriter, + options: SimpleFileOptions, +} + +impl BackupWriter { + pub fn new(target: W) -> Result { + let mut zip = ZipWriter::new(target); + zip.add_directory("profiles/", SimpleFileOptions::default())?; + let options = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); + Ok(Self { zip, options }) + } + + pub fn start_profile<'a>(&'a mut self, filename: &str) -> Result, ArchiveError> { + self.start_file(&format!("profiles/{filename}")) + } + + pub fn start_file<'a>(&'a mut self, name: &str) -> Result, ArchiveError> { + self.zip.start_file_with_options(self.options.name(name.as_bytes()))?; + Ok(&mut self.zip) + } + + pub fn finish(self) -> Result { + Ok(self.zip.finish()?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{Cursor, Read as _}; + use zip::ZipArchive; + + #[test] + fn writes_the_backup_layout() -> Result<(), ArchiveError> { + let mut writer = BackupWriter::new(Cursor::new(Vec::new()))?; + writer.start_profile("example.yaml")?.write_all(b"proxies: []\n")?; + writer.start_file("profiles.yaml")?.write_all(b"items: []\n")?; + let source = writer.finish()?; + + let mut zip = ZipArchive::new(source)?; + assert_eq!(zip.len(), 3); + assert_eq!(zip.by_index(0)?.name()?, "profiles/"); + let profile_time = { + let mut entry = zip.by_index(1)?; + assert_eq!(entry.name()?, "profiles/example.yaml"); + assert_eq!(entry.compression(), CompressionMethod::Stored); + let mut contents = Vec::new(); + entry.read_to_end(&mut contents)?; + assert_eq!(contents, b"proxies: []\n"); + entry.last_modified() + }; + let index = zip.by_index(2)?; + assert_eq!(index.name()?, "profiles.yaml"); + assert_eq!(index.last_modified(), profile_time); + Ok(()) + } +} diff --git a/crates/clash-verge-draft/Cargo.toml b/crates/clash-verge-draft/Cargo.toml index 40351c26a..f82611ea6 100644 --- a/crates/clash-verge-draft/Cargo.toml +++ b/crates/clash-verge-draft/Cargo.toml @@ -10,7 +10,7 @@ harness = false [dependencies] parking_lot = { workspace = true } -anyhow = { workspace = true } +thiserror = { workspace = true } tokio = { workspace = true } [dev-dependencies] diff --git a/crates/clash-verge-draft/bench/benche_me.rs b/crates/clash-verge-draft/bench/benche_me.rs index 6c1af9e49..f06702937 100644 --- a/crates/clash-verge-draft/bench/benche_me.rs +++ b/crates/clash-verge-draft/bench/benche_me.rs @@ -2,7 +2,7 @@ use criterion::{Criterion, criterion_group, criterion_main}; use std::hint::black_box; use tokio::runtime::Runtime; -use clash_verge_draft::Draft; +use clash_verge_draft::{Draft, DraftConflict}; #[derive(Default, Clone, Debug)] struct IVerge { @@ -99,8 +99,8 @@ pub fn bench_draft(c: &mut Criterion) { group.bench_function("with_data_modify_async", |b| { b.to_async(&rt).iter(|| async { let draft = black_box(make_draft()); - let _: Result<(), anyhow::Error> = draft - .with_data_modify::<_, _, _>(|mut box_data| async move { + let _: Result<(), DraftConflict> = draft + .with_data_modify(|mut box_data| async move { box_data.enable_auto_launch = Some(!box_data.enable_auto_launch.unwrap_or(false)); Ok((box_data, ())) }) diff --git a/crates/clash-verge-draft/src/error.rs b/crates/clash-verge-draft/src/error.rs new file mode 100644 index 000000000..4fb2f4afc --- /dev/null +++ b/crates/clash-verge-draft/src/error.rs @@ -0,0 +1,12 @@ +/// Committed data changed before an asynchronous edit could publish. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +#[error("Optimistic lock failed: Committed data has changed during async operation")] +pub struct DraftConflict; + +/// Another transaction is already staging a change to one of the layers asked for. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("configuration layer {layer} is being changed elsewhere")] +pub struct DraftBusy { + /// The layer that was already claimed. + pub layer: &'static str, +} diff --git a/crates/clash-verge-draft/src/lib.rs b/crates/clash-verge-draft/src/lib.rs index d1a968cb2..42bd650d9 100644 --- a/crates/clash-verge-draft/src/lib.rs +++ b/crates/clash-verge-draft/src/lib.rs @@ -1,3 +1,7 @@ +mod error; + +pub use error::{DraftBusy, DraftConflict}; + use parking_lot::Mutex; use std::sync::Arc; use std::sync::atomic::{ @@ -91,14 +95,16 @@ impl Draft { } /// Optimistically replaces committed data after an asynchronous edit. + /// The caller's error type carries both edit failures and publication conflicts. #[inline] - pub async fn with_data_modify(&self, f: F) -> Result + pub async fn with_data_modify(&self, f: F) -> Result where T: Send + Sync + 'static, F: FnOnce(T) -> Fut + Send, - Fut: std::future::Future> + Send, + Fut: std::future::Future> + Send, + E: From, { - let _permit = self.acquire_data_modify_permit().await; + let permit = self.acquire_data_modify_permit().await; let (local, original_arc) = { let guard = self.inner.data.lock(); let arc = Arc::clone(&guard.0); @@ -108,9 +114,9 @@ impl Draft { let (new_local, res) = f(local).await?; let mut guard = self.inner.data.lock(); if !Arc::ptr_eq(&guard.0, &original_arc) { - return Err(anyhow::anyhow!( - "Optimistic lock failed: Committed data has changed during async operation" - )); + drop(guard); + drop(permit); + return Err(DraftConflict.into()); } guard.0 = Arc::new(Box::new(new_local)); drop(guard); @@ -191,25 +197,6 @@ impl DraftLayer for Draft { } } -/// Another transaction is already staging a change to one of the layers asked for. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct DraftBusy { - /// The layer that was already claimed. - pub layer: &'static str, -} - -impl std::fmt::Display for DraftBusy { - fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - formatter, - "configuration layer {} is being changed elsewhere", - self.layer - ) - } -} - -impl std::error::Error for DraftBusy {} - /// Exclusively claims several draft layers and rolls them all back unless committed. /// /// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected. diff --git a/crates/clash-verge-draft/tests/test_me.rs b/crates/clash-verge-draft/tests/test_me.rs index 44c95c99e..301291a3e 100644 --- a/crates/clash-verge-draft/tests/test_me.rs +++ b/crates/clash-verge-draft/tests/test_me.rs @@ -7,7 +7,7 @@ use std::{ task::{Context, Poll, Wake, Waker}, }; -use clash_verge_draft::{Draft, DraftTransaction}; +use clash_verge_draft::{Draft, DraftBusy, DraftConflict, DraftTransaction}; use tokio::sync::{Notify, oneshot}; #[derive(Clone, Debug, Default, PartialEq)] @@ -35,14 +35,19 @@ fn edits_can_be_committed_or_discarded() { } #[tokio::test] -async fn async_updates_are_serialized() -> anyhow::Result<()> { +async fn async_updates_are_serialized() -> Result<(), Box> { let draft = Arc::new(Draft::new(0_u8)); let mut updates = Vec::new(); for _ in 0..16 { let draft = Arc::clone(&draft); updates.push(tokio::spawn(async move { - draft.with_data_modify(|value| async move { Ok((value + 1, ())) }).await + draft + .with_data_modify(|value| async move { + tokio::task::yield_now().await; + Ok::<_, DraftConflict>((value + 1, ())) + }) + .await })); } for update in updates { @@ -54,7 +59,7 @@ async fn async_updates_are_serialized() -> anyhow::Result<()> { } #[tokio::test] -async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> { +async fn async_update_rejects_a_changed_committed_value() -> Result<(), Box> { let draft = Arc::new(Draft::new(Config::default())); let started = Arc::new(Notify::new()); let finish = Arc::new(Notify::new()); @@ -68,7 +73,7 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> started.notify_one(); finish.notified().await; config.enabled = true; - Ok((config, ())) + Ok::<_, DraftConflict>((config, ())) }) .await }) @@ -79,7 +84,7 @@ async fn async_update_rejects_a_changed_committed_value() -> anyhow::Result<()> draft.apply(); finish.notify_one(); - assert!(update.await?.is_err()); + assert_eq!(update.await?, Err(DraftConflict)); assert!(!draft.data_arc().enabled); assert_eq!(draft.data_arc().port, 7897); Ok(()) @@ -99,8 +104,8 @@ fn parked_async_update_is_woken_after_optimistic_conflict() { let draft = Draft::new(1); let (finish, finished) = oneshot::channel(); let mut owner = pin!(draft.with_data_modify(|value| async move { - finished.await?; - Ok((value + 10, ())) + finished.await.expect("owner completion signal"); + Ok::<_, DraftConflict>((value + 10, ())) })); let mut owner_context = Context::from_waker(Waker::noop()); assert!(owner.as_mut().poll(&mut owner_context).is_pending()); @@ -108,7 +113,7 @@ fn parked_async_update_is_woken_after_optimistic_conflict() { let wake_flag = Arc::new(WakeFlag::default()); let waker = Waker::from(Arc::clone(&wake_flag)); let mut waiter_context = Context::from_waker(&waker); - let mut waiter = pin!(draft.with_data_modify(|value| async move { Ok((value + 1, value)) })); + let mut waiter = pin!(draft.with_data_modify(|value| async move { Ok::<_, DraftConflict>((value + 1, value)) })); // The fast retry wakes once before the waiter parks on Notify. assert!(waiter.as_mut().poll(&mut waiter_context).is_pending()); @@ -127,7 +132,7 @@ fn parked_async_update_is_woken_after_optimistic_conflict() { } #[test] -fn transaction_commits_every_layer() -> anyhow::Result<()> { +fn transaction_commits_every_layer() -> Result<(), DraftBusy> { let first = Draft::new(1_u8); let second = Draft::new(String::from("a")); let transaction = DraftTransaction::begin(vec![&first, &second])?; @@ -142,7 +147,7 @@ fn transaction_commits_every_layer() -> anyhow::Result<()> { } #[test] -fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> { +fn dropped_transaction_rolls_every_layer_back() -> Result<(), DraftBusy> { let first = Draft::new(1_u8); let second = Draft::new(String::from("a")); @@ -158,14 +163,14 @@ fn dropped_transaction_rolls_every_layer_back() -> anyhow::Result<()> { } #[test] -fn transaction_claims_are_exclusive_and_release_partial_claims() -> anyhow::Result<()> { +fn transaction_claims_are_exclusive_and_release_partial_claims() -> Result<(), DraftBusy> { let first = Draft::new(1_u8); let second = Draft::new(2_u16); let held = DraftTransaction::begin(vec![&second])?; let busy = DraftTransaction::begin(vec![&first, &second]) .err() - .ok_or_else(|| anyhow::anyhow!("transaction claimed an already-held layer"))?; + .expect("transaction claimed an already-held layer"); let layer = std::any::type_name::(); assert_eq!(busy.layer, layer); assert!(busy.to_string().contains(layer)); diff --git a/crates/clash-verge-logging/Cargo.toml b/crates/clash-verge-logging/Cargo.toml index c6d9feb20..c0c193e77 100644 --- a/crates/clash-verge-logging/Cargo.toml +++ b/crates/clash-verge-logging/Cargo.toml @@ -6,7 +6,7 @@ edition = "2024" [dependencies] log = { workspace = true } parking_lot = { workspace = true } -anyhow = { workspace = true } +thiserror = { workspace = true } flexi_logger = { workspace = true } tracing-estuary = { workspace = true } diff --git a/crates/clash-verge-logging/src/error.rs b/crates/clash-verge-logging/src/error.rs new file mode 100644 index 000000000..a95a4db9f --- /dev/null +++ b/crates/clash-verge-logging/src/error.rs @@ -0,0 +1,11 @@ +#[derive(Debug, thiserror::Error)] +pub enum LoggerError { + #[error(transparent)] + Pipeline(Box), + #[error(transparent)] + Sidecar(#[from] flexi_logger::FlexiLoggerError), + #[error("failed to get tracing pipeline, make sure it init")] + PipelineUnavailable, + #[error("failed to reset log writer: {0}")] + ResetWriter(String), +} diff --git a/crates/clash-verge-logging/src/lib.rs b/crates/clash-verge-logging/src/lib.rs index ee8df5c53..e3bbc6eec 100644 --- a/crates/clash-verge-logging/src/lib.rs +++ b/crates/clash-verge-logging/src/lib.rs @@ -1,3 +1,7 @@ +mod error; + +pub use error::LoggerError; + use std::{ collections::VecDeque, fmt, @@ -10,7 +14,6 @@ use std::{ time::Duration, }; -use anyhow::{Result, bail}; use flexi_logger::{ Cleanup, Criterion, DeferredNow, FileSpec, Naming, writers::{FileLogWriter, FileLogWriterBuilder, LogWriter as _}, @@ -177,7 +180,7 @@ impl Logger { /// Installs the global tracing pipeline. `RUST_LOG` (parsed as a bare /// level) overrides the configured level. - pub fn init(&self, cfg: &LoggerConfig) -> Result<()> { + pub fn init(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> { let log_level = std::env::var("RUST_LOG") .ok() .and_then(|v| LevelFilter::from_str(v.trim()).ok()) @@ -186,14 +189,15 @@ impl Logger { let pipeline = tracing_estuary::PipelineBuilder::new() .default_level(log_level) .file_writer(self.generate_file_log_writer()) - .init()?; + .init() + .map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?; self.pipeline.set(pipeline).ok(); Ok(()) } /// Installs the sidecar file writer and the panic hook. Safe to call when /// the pipeline is owned elsewhere (e.g. a devtools-provided subscriber). - pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<()> { + pub fn init_sidecar(&self, cfg: &LoggerConfig) -> Result<(), LoggerError> { self.store_config(cfg); self.ensure_sidecar_writer(self.generate_sidecar_builder())?; @@ -245,7 +249,7 @@ impl Logger { /// Ensures the sidecar writer exists and points at `builder`'s config: /// built once, then reset in place — flexi's flusher thread cannot be /// stopped, so every dropped writer would leak a thread and an fd. - fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<()> { + fn ensure_sidecar_writer(&self, builder: FileLogWriterBuilder) -> Result<(), LoggerError> { let sidecar = self.sidecar_file_writer.write(); match sidecar.as_ref() { Some(writer) => { @@ -296,27 +300,29 @@ impl Logger { } /// only update app log level - pub fn update_log_level(&self, level: LevelFilter) -> Result<()> { + pub fn update_log_level(&self, level: LevelFilter) -> Result<(), LoggerError> { if let Some(pipeline) = self.pipeline.get() { - pipeline.filter.set_default_level(level)?; + pipeline + .filter + .set_default_level(level) + .map_err(|error| LoggerError::Pipeline(error.into_boxed_dyn_error()))?; } else { - bail!("failed to get tracing pipeline, make sure it init"); + return Err(LoggerError::PipelineUnavailable); }; Ok(()) } /// Rebuilds both file writers with the new limits. - pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<()> { + pub fn update_log_config(&self, log_max_size: u64, log_max_count: usize) -> Result<(), LoggerError> { self.log_max_size.store(log_max_size, Ordering::SeqCst); self.log_max_count.store(log_max_count, Ordering::SeqCst); if let Some(pipeline) = self.pipeline.get() { let log_file_writer = self.generate_file_log_writer(); if let Some(sink) = pipeline.sink.as_ref() { - sink.reset(log_file_writer) - .map_err(|error| anyhow::anyhow!("failed to reset log writer: {error}"))?; + sink.reset(log_file_writer).map_err(LoggerError::ResetWriter)?; } } else { - bail!("failed to get tracing pipeline, make sure it init"); + return Err(LoggerError::PipelineUnavailable); }; self.ensure_sidecar_writer(self.generate_sidecar_builder())?; Ok(()) diff --git a/crates/clash-verge-profile/Cargo.toml b/crates/clash-verge-profile/Cargo.toml new file mode 100644 index 000000000..173234b11 --- /dev/null +++ b/crates/clash-verge-profile/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "clash-verge-profile" +version = "0.1.0" +edition = "2024" + +[dependencies] +serde = { workspace = true, features = ["derive"] } +specta = { workspace = true, features = ["derive"] } +thiserror = { workspace = true } +tristr = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } +serde_yaml_ng = { workspace = true } + +[lints] +workspace = true diff --git a/crates/clash-verge-profile/src/error.rs b/crates/clash-verge-profile/src/error.rs new file mode 100644 index 000000000..0c5a27812 --- /dev/null +++ b/crates/clash-verge-profile/src/error.rs @@ -0,0 +1,5 @@ +#[derive(Debug, thiserror::Error)] +#[error("failed to get the profile item \"uid:{uid}\"")] +pub struct ProfileNotFound { + pub(super) uid: String, +} diff --git a/crates/clash-verge-profile/src/lib.rs b/crates/clash-verge-profile/src/lib.rs new file mode 100644 index 000000000..8a56d1ae9 --- /dev/null +++ b/crates/clash-verge-profile/src/lib.rs @@ -0,0 +1,397 @@ +mod error; +pub mod selected_nodes; +mod subscription_schedule; + +pub use error::ProfileNotFound; +pub use subscription_schedule::SubscriptionSchedule; + +use serde::{Deserialize, Serialize}; +use tristr::alias::String; + +macro_rules! patch_opt_field { + ($lv:expr, $rv:expr, $key:tt) => { + if ($rv.$key).is_some() { + $lv.$key = $rv.$key.clone(); + } + }; +} + +#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)] +#[serde(default)] +pub struct PrfItem { + pub uid: Option, + /// enum value: remote | local | script | merge + #[serde(rename = "type")] + pub itype: Option, + pub name: Option, + pub file: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub desc: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub selected: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub extra: Option, + pub updated: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub option: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub home: Option, + #[serde(skip)] + pub file_data: Option, +} + +#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] +#[serde(default)] +pub struct PrfSelected { + pub name: Option, + pub now: Option, +} + +#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)] +pub struct PrfExtra { + pub upload: u64, + pub download: u64, + pub total: u64, + pub expire: u64, +} + +#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] +#[serde(default)] +pub struct PrfOption { + #[serde(skip_serializing_if = "Option::is_none")] + pub user_agent: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub with_proxy: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub self_proxy: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub update_interval: Option, + /// HTTP request timeout in seconds + /// default is 60 seconds + #[serde(skip_serializing_if = "Option::is_none")] + pub timeout_seconds: Option, + /// default is `false` + #[serde(skip_serializing_if = "Option::is_none")] + pub danger_accept_invalid_certs: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub allow_auto_update: Option, + pub merge: Option, + pub script: Option, + pub rules: Option, + pub proxies: Option, + pub groups: Option, +} + +impl PrfOption { + pub fn merge(one: Option<&Self>, other: Option<&Self>) -> Option { + match (one, other) { + (Some(a_ref), Some(b_ref)) => { + let mut result = a_ref.clone(); + patch_opt_field!(result, b_ref, user_agent); + patch_opt_field!(result, b_ref, with_proxy); + patch_opt_field!(result, b_ref, self_proxy); + patch_opt_field!(result, b_ref, danger_accept_invalid_certs); + patch_opt_field!(result, b_ref, allow_auto_update); + patch_opt_field!(result, b_ref, update_interval); + patch_opt_field!(result, b_ref, merge); + patch_opt_field!(result, b_ref, script); + patch_opt_field!(result, b_ref, rules); + patch_opt_field!(result, b_ref, proxies); + patch_opt_field!(result, b_ref, groups); + patch_opt_field!(result, b_ref, timeout_seconds); + Some(result) + } + (Some(a_ref), None) => Some(a_ref.clone()), + (None, Some(b_ref)) => Some(b_ref.clone()), + (None, None) => None, + } + } +} + +macro_rules! current_field { + ($name:ident, $field:ident) => { + pub fn $name(&self) -> Option<&String> { + self.option.as_ref().and_then(|o| o.$field.as_ref()) + } + }; +} + +impl PrfItem { + current_field!(current_merge, merge); + current_field!(current_script, script); + current_field!(current_rules, rules); + current_field!(current_proxies, proxies); + current_field!(current_groups, groups); +} + +/// Define the `profiles.yaml` schema +#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] +#[serde(default)] +pub struct IProfiles { + pub current: Option, + pub items: Option>, +} + +pub struct IProfilePreview<'a> { + pub uid: &'a String, + pub name: &'a String, + pub is_current: bool, +} + +pub struct ProfileDeletePlan { + pub deleting_current: bool, + pub files: Vec, +} + +impl IProfiles { + pub fn patch_current(&mut self, current: Option<&String>) { + let items = self.items.get_or_insert_with(Vec::new); + if let Some(current) = current + && items.iter().any(|item| item.uid.as_ref() == Some(current)) + { + self.current = Some(current.clone()); + } + } + + pub fn get_item(&self, uid: impl AsRef) -> Result<&PrfItem, ProfileNotFound> { + let uid = uid.as_ref(); + self.items + .iter() + .flatten() + .find(|item| item.uid.as_deref() == Some(uid)) + .ok_or_else(|| ProfileNotFound { uid: uid.to_owned() }) + } + + pub fn get_item_mut(&mut self, uid: &str) -> Result<&mut PrfItem, ProfileNotFound> { + self.items + .iter_mut() + .flatten() + .find(|item| item.uid.as_deref() == Some(uid)) + .ok_or_else(|| ProfileNotFound { uid: uid.to_owned() }) + } + + /// Inserts a prepared entry after any required body write. + pub fn append_item(&mut self, item: &PrfItem) { + if self.current.is_none() && matches!(item.itype.as_deref(), Some("remote" | "local")) { + self.current = item.uid.clone(); + } + + self.items.get_or_insert_with(Vec::new).push(item.clone()); + } + + /// Returns true if both IDs were found, including when the item stayed at its old position. + pub fn reorder(&mut self, active_id: &str, over_id: &str) -> bool { + let Some(items) = self.items.as_mut() else { + return false; + }; + let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id)); + let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id)); + let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else { + return false; + }; + let item = items.remove(old_idx); + items.insert(new_idx, item); + true + } + + pub fn plan_delete_item(&mut self, uid: &str) -> Result { + let deleting_current = self.current.as_deref().is_none_or(|current| current == uid); + let missing_profile = || ProfileNotFound { uid: uid.to_owned() }; + let items = self.items.as_mut().ok_or_else(missing_profile)?; + let profile = remove_item(items, Some(uid)).ok_or_else(missing_profile)?; + let mut files = Vec::from_iter(profile.file); + if let Some(options) = profile.option { + for companion_uid in [ + options.merge, + options.script, + options.rules, + options.proxies, + options.groups, + ] { + if let Some(file) = remove_item(items, companion_uid.as_deref()).and_then(|item| item.file) { + files.push(file); + } + } + } + + if deleting_current { + self.current = items + .iter() + .find(|item| matches!(item.itype.as_deref(), Some("remote" | "local"))) + .and_then(|item| item.uid.clone()); + } + Ok(ProfileDeletePlan { + deleting_current, + files, + }) + } + + pub fn profiles_preview(&self) -> Option>> { + self.items.as_ref().map(|items| { + items + .iter() + .filter_map(|e| { + if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) { + let is_current = self.current.as_ref() == Some(uid); + let preview = IProfilePreview { uid, name, is_current }; + Some(preview) + } else { + None + } + }) + .collect() + }) + } +} + +fn remove_item(items: &mut Vec, target_uid: Option<&str>) -> Option { + let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?; + Some(items.remove(index)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn old_index_preserves_missing_and_explicit_values() -> Result<(), Box> { + let mut profiles: IProfiles = serde_yaml_ng::from_str( + r#" +current: first +items: + - uid: first + type: remote + option: {allow_auto_update: false, update_interval: 0, merge: ""} + file_data: ignored + - uid: second + name: "" +"#, + )?; + let first = profiles.get_item("first")?; + assert!(first.file_data.is_none()); + assert_eq!(first.current_merge().map(String::as_str), Some("")); + assert!(first.current_script().is_none()); + if let Some(items) = profiles.items.as_mut() { + items[0].file_data = Some("in memory".into()); + } + assert_eq!( + serde_json::to_value(&profiles)?, + serde_json::json!({ + "current": "first", + "items": [ + {"uid": "first", "type": "remote", "name": null, "file": null, "updated": null, + "option": {"allow_auto_update": false, "update_interval": 0, "merge": "", + "script": null, "rules": null, "proxies": null, "groups": null}}, + {"uid": "second", "type": null, "name": "", "file": null, "updated": null} + ] + }) + ); + assert_eq!( + serde_json::to_value(serde_yaml_ng::from_str::("{}")?)?, + serde_json::json!({"current": null, "items": null}) + ); + Ok(()) + } + + #[test] + fn merge_overrides_only_explicit_values() { + let base = PrfOption { + user_agent: Some("original".into()), + allow_auto_update: Some(true), + update_interval: Some(60), + merge: Some("original-merge".into()), + ..Default::default() + }; + let overrides = PrfOption { + user_agent: Some("".into()), + allow_auto_update: Some(false), + update_interval: Some(0), + ..Default::default() + }; + let expected = PrfOption { + merge: base.merge.clone(), + ..overrides.clone() + }; + assert_eq!(PrfOption::merge(Some(&base), Some(&overrides)), Some(expected)); + assert_eq!(PrfOption::merge(None, None), None); + assert_eq!( + PrfOption::merge(None, Some(&PrfOption::default())), + Some(PrfOption::default()) + ); + } + + #[test] + fn lookup_preview_and_reorder_preserve_duplicate_uid_rules() -> Result<(), Box> { + let mut profiles: IProfiles = serde_yaml_ng::from_str( + r#" +current: duplicate +items: + - {uid: duplicate, name: first} + - {uid: duplicate, name: last} + - {uid: target, name: ""} + - {name: no UID} +"#, + )?; + assert_eq!(profiles.get_item("duplicate")?.name.as_deref(), Some("first")); + assert!(!profiles.reorder("missing", "target")); + assert!(!profiles.reorder("duplicate", "missing")); + assert!(profiles.reorder("duplicate", "duplicate")); + assert!(profiles.reorder("duplicate", "target")); + let preview = profiles.profiles_preview().unwrap_or_default(); + let names: Vec<_> = preview + .iter() + .map(|item| (item.name.as_str(), item.is_current)) + .collect(); + assert_eq!(names, [("first", true), ("", false), ("last", true)]); + Ok(()) + } + + #[test] + fn current_patch_initializes_missing_items_and_only_selects_an_existing_uid() { + let mut profiles = IProfiles::default(); + profiles.patch_current(None); + assert!(matches!(&profiles.items, Some(items) if items.is_empty())); + assert!(profiles.current.is_none()); + profiles.append_item(&PrfItem { + uid: Some("script".into()), + itype: Some("script".into()), + ..Default::default() + }); + assert!(profiles.current.is_none()); + profiles.append_item(&PrfItem { + uid: Some("local".into()), + itype: Some("local".into()), + ..Default::default() + }); + assert_eq!(profiles.current.as_deref(), Some("local")); + profiles.patch_current(None); + profiles.patch_current(Some(&String::from("missing"))); + assert_eq!(profiles.current.as_deref(), Some("local")); + profiles.patch_current(Some(&String::from("script"))); + assert_eq!(profiles.current.as_deref(), Some("script")); + } + + #[test] + fn delete_plan_preserves_file_order_and_legacy_missing_uid_matching() -> Result<(), Box> { + let mut profiles: IProfiles = serde_yaml_ng::from_str( + r" +items: + - {uid: active, type: remote, file: first.yaml, option: {merge: owned}} + - {uid: owned, type: merge, file: owned.yaml} + - {type: script, file: missing-uid.js} + - {uid: next, type: local, file: next.yaml} +", + )?; + let plan = profiles.plan_delete_item("active")?; + assert!(plan.deleting_current); + assert_eq!( + plan.files, + ["first.yaml", "owned.yaml", "missing-uid.js"].map(String::from) + ); + assert_eq!(profiles.current.as_deref(), Some("next")); + assert!(profiles.get_item("owned").is_err()); + Ok(()) + } +} diff --git a/crates/clash-verge-profile/src/selected_nodes.rs b/crates/clash-verge-profile/src/selected_nodes.rs new file mode 100644 index 000000000..a9d1c9cd5 --- /dev/null +++ b/crates/clash-verge-profile/src/selected_nodes.rs @@ -0,0 +1,147 @@ +use super::PrfSelected; +use std::collections::HashSet; +use tristr::alias::String; + +pub struct SelectedGroup<'a> { + pub members: Option<&'a [std::string::String]>, + pub current: Option<&'a str>, + pub selectable: bool, +} + +#[derive(Debug, PartialEq, Eq)] +pub struct SelectedNodesPlan { + pub selected: Vec, + pub activations: Vec<(String, String)>, + pub repaired_count: usize, +} + +fn node_is_available(available_nodes: &[std::string::String], node: &str) -> bool { + available_nodes.iter().any(|available| available == node) +} + +pub fn selected_nodes_need_confirmation<'a, Snapshot>( + selected: &[PrfSelected], + snapshot: &'a Snapshot, + lookup: impl Fn(&'a Snapshot, &str) -> Option>, +) -> bool { + selected.iter().any(|selected_item| { + let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else { + return false; + }; + let Some(group) = lookup(snapshot, group_name) else { + return true; + }; + let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else { + return true; + }; + !node_is_available(available_nodes, node) + }) +} + +pub fn reconcile_selected_nodes<'a, Snapshot>( + selected: &[PrfSelected], + previous: Option<&'a Snapshot>, + current: &'a Snapshot, + lookup: impl Fn(&'a Snapshot, &str) -> Option>, +) -> SelectedNodesPlan { + let mut plan = SelectedNodesPlan { + selected: Vec::with_capacity(selected.len()), + activations: Vec::new(), + repaired_count: 0, + }; + let mut seen_groups = HashSet::new(); + let mut unique_selected = selected + .iter() + .rev() + .filter(|item| item.name.as_deref().is_some_and(|name| seen_groups.insert(name))) + .collect::>(); + unique_selected.reverse(); + plan.repaired_count += selected.len() - unique_selected.len(); + + for selected_item in unique_selected { + let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else { + plan.repaired_count += 1; + continue; + }; + let Some(group) = lookup(current, group_name) else { + if previous.is_some_and(|snapshot| lookup(snapshot, group_name).is_none()) { + plan.repaired_count += 1; + } else { + plan.selected.push(selected_item.clone()); + } + continue; + }; + let Some(available_nodes) = group.members.filter(|nodes| !nodes.is_empty()) else { + // Provider-backed groups can be temporarily incomplete immediately after a reload. + plan.selected.push(selected_item.clone()); + continue; + }; + if !group.selectable { + let preferred_node = group + .current + .filter(|current| node_is_available(available_nodes, current)) + .or_else(|| node_is_available(available_nodes, node).then_some(node.as_str())); + let Some(preferred_node) = preferred_node else { + plan.repaired_count += 1; + continue; + }; + plan.repaired_count += usize::from(preferred_node != node.as_str()); + plan.selected.push(PrfSelected { + name: Some(group_name.clone()), + now: Some(preferred_node.into()), + }); + continue; + } + + if node_is_available(available_nodes, node) { + plan.selected.push(selected_item.clone()); + if group.current != Some(node.as_str()) { + plan.activations.push((group_name.clone(), node.clone())); + } + continue; + } + + let missing_was_confirmed = previous + .and_then(|snapshot| lookup(snapshot, group_name)) + .and_then(|group| group.members) + .filter(|nodes| !nodes.is_empty()) + .is_some_and(|nodes| !node_is_available(nodes, node)); + if !missing_was_confirmed { + plan.selected.push(selected_item.clone()); + continue; + } + + plan.repaired_count += 1; + if let Some(current_node) = group + .current + .filter(|current| node_is_available(available_nodes, current)) + { + plan.selected.push(PrfSelected { + name: Some(group_name.clone()), + now: Some(current_node.into()), + }); + } + } + + plan +} + +/// Returns recorded selections whose groups have not reached the requested node. +pub fn unsettled_selections<'a, Snapshot>( + selected: &[PrfSelected], + snapshot: &'a Snapshot, + lookup: impl Fn(&'a Snapshot, &str) -> Option>, +) -> Vec { + selected + .iter() + .filter_map(|item| { + let (Some(group_name), Some(node)) = (&item.name, &item.now) else { + return None; + }; + match lookup(snapshot, group_name) { + Some(group) if group.current == Some(node.as_str()) => None, + _ => Some(group_name.clone()), + } + }) + .collect() +} diff --git a/crates/clash-verge-profile/src/subscription_schedule.rs b/crates/clash-verge-profile/src/subscription_schedule.rs new file mode 100644 index 000000000..1276e5ba4 --- /dev/null +++ b/crates/clash-verge-profile/src/subscription_schedule.rs @@ -0,0 +1,49 @@ +use super::PrfItem; +use std::time::Duration; + +/// Scheduling policy for a Profile, independent of the task queue and clock. +#[derive(Debug, PartialEq, Eq)] +pub struct SubscriptionSchedule { + pub interval_minutes: u64, + pub first_delay: Duration, +} + +impl SubscriptionSchedule { + pub fn for_profile(item: &PrfItem, initializing: bool, now: i64) -> Option { + let option = item.option.as_ref()?; + let interval = option.update_interval.filter(|interval| *interval > 0)?; + if !option.allow_auto_update.unwrap_or(true) { + return None; + } + + let mut schedule = Self::new(interval, item.updated, now); + // Startup historically treats an explicit zero timestamp as overdue. + if initializing && item.updated == Some(0) { + schedule.first_delay = Duration::ZERO; + } + Some(schedule) + } + + pub fn new(interval_minutes: u64, updated: Option, now: i64) -> Self { + let full = Self::interval_duration(interval_minutes); + let elapsed = updated + .filter(|updated| *updated > 0) + .map_or(0, |updated| (now.max(0) as u64).saturating_sub(updated as u64)); + + Self { + interval_minutes, + first_delay: full.saturating_sub(Duration::from_secs(elapsed)), + } + } + + pub const fn interval_duration(interval_minutes: u64) -> Duration { + Duration::from_secs(interval_minutes.saturating_mul(60)) + } + + /// The UI deadline is based on the last saved update. The queue can delay retries further. + pub fn reported_deadline(interval_minutes: u64, updated: Option) -> Option { + let updated = i64::try_from(updated.filter(|updated| *updated > 0)?).ok()?; + let interval = i64::try_from(interval_minutes).ok()?.checked_mul(60)?; + updated.checked_add(interval) + } +} diff --git a/crates/clash-verge-signal/Cargo.toml b/crates/clash-verge-signal/Cargo.toml index f8a03ac48..12c5b124f 100644 --- a/crates/clash-verge-signal/Cargo.toml +++ b/crates/clash-verge-signal/Cargo.toml @@ -4,7 +4,7 @@ version = "0.1.0" edition = "2024" rust-version = "1.91" -[dependencies] +[target.'cfg(target_os = "linux")'.dependencies] clash-verge-logging = { workspace = true } log = { workspace = true } tokio = { workspace = true, features = ["signal"] } diff --git a/crates/clash-verge-subscription/Cargo.toml b/crates/clash-verge-subscription/Cargo.toml new file mode 100644 index 000000000..ed4a95730 --- /dev/null +++ b/crates/clash-verge-subscription/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "clash-verge-subscription" +version = "0.1.0" +edition = "2024" + +[dependencies] +thiserror = { workspace = true } +http = "1" +percent-encoding = "2.3.2" +serde_yaml_ng = { workspace = true } +url = "2.5" + +[lints] +workspace = true diff --git a/crates/clash-verge-subscription/src/deep_link.rs b/crates/clash-verge-subscription/src/deep_link.rs new file mode 100644 index 000000000..dc38f3492 --- /dev/null +++ b/crates/clash-verge-subscription/src/deep_link.rs @@ -0,0 +1,84 @@ +use percent_encoding::percent_decode_str; +use std::borrow::Cow; +use url::Url; + +pub struct SubscriptionLink<'a> { + pub url: Cow<'a, str>, + pub name: Option>, +} + +pub fn decode_subscription_link(link: &Url) -> Option> { + if !matches!(link.scheme(), "clash" | "clash-verge") { + return None; + } + + // The embedded URL can contain unescaped query separators of its own. + let query = link.query()?; + let raw_url = query + .strip_prefix("url=") + .or_else(|| query.split_once("&url=").map(|(_, url)| url))? + .trim(); + let name = link.query_pairs().find(|(key, _)| key == "name").map(|(_, name)| name); + Some(SubscriptionLink { + url: decode_subscription_url(raw_url), + name, + }) +} + +fn decode_subscription_url(raw_url: &str) -> Cow<'_, str> { + if Url::parse(raw_url).is_ok() { + return Cow::Borrowed(raw_url); + } + // Only the outer name has meaning here. Partly encoded URLs can still contain literal path and query delimiters. + let mut candidate = Cow::Borrowed( + raw_url + .split_once("&name=") + .filter(|(value, _)| !value.contains(['/', '?', '&'])) + .map_or(raw_url, |(value, _)| value), + ); + + for _ in 0..2 { + let decoded = percent_decode_str(&candidate).decode_utf8_lossy(); + if decoded == candidate { + break; + } + candidate = Cow::Owned(decoded.into_owned()); + if Url::parse(&candidate).is_ok() { + break; + } + } + candidate +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn preserves_nested_query_separators_and_decodes_wrapped_links() -> Result<(), url::ParseError> { + let plain = Url::parse("clash://install-config?name=Work%20VPN&url=https://example.invalid/sub?a=1&b=2")?; + let link = decode_subscription_link(&plain).expect("plain subscription link"); + assert_eq!(link.name.as_deref(), Some("Work VPN")); + assert!(matches!(link.url, Cow::Borrowed("https://example.invalid/sub?a=1&b=2"))); + + let partial = Url::parse("clash://install-config?url=https%3A%2F%2Fexample.invalid/a&b/file?token=abc")?; + assert_eq!( + decode_subscription_link(&partial).expect("partially encoded link").url, + "https://example.invalid/a&b/file?token=abc" + ); + + let missing = Url::parse("clash://install-config?name=myurl=notes")?; + assert!(decode_subscription_link(&missing).is_none()); + let named = Url::parse("clash://install-config?name=myurl=notes&url=https://example.invalid/work")?; + assert_eq!( + decode_subscription_link(&named).expect("named link").url, + "https://example.invalid/work" + ); + + let encoded = + Url::parse("clash-verge://install-config?url=https%253A%252F%252Fexample.invalid%252Fsub&name=Work")?; + let link = decode_subscription_link(&encoded).expect("double-encoded subscription link"); + assert_eq!(link.url, "https://example.invalid/sub"); + Ok(()) + } +} diff --git a/crates/clash-verge-subscription/src/error.rs b/crates/clash-verge-subscription/src/error.rs new file mode 100644 index 000000000..b34147872 --- /dev/null +++ b/crates/clash-verge-subscription/src/error.rs @@ -0,0 +1,7 @@ +#[derive(Debug, thiserror::Error)] +pub enum SubscriptionError { + #[error("the remote profile data is invalid yaml")] + InvalidYaml(#[source] serde_yaml_ng::Error), + #[error("profile does not contain `proxies` or `proxy-providers`")] + MissingProviders, +} diff --git a/crates/clash-verge-subscription/src/lib.rs b/crates/clash-verge-subscription/src/lib.rs new file mode 100644 index 000000000..76f0959d5 --- /dev/null +++ b/crates/clash-verge-subscription/src/lib.rs @@ -0,0 +1,244 @@ +mod deep_link; +mod error; + +pub use deep_link::{SubscriptionLink, decode_subscription_link}; +pub use error::SubscriptionError; + +use http::HeaderMap; +use percent_encoding::percent_decode_str; +use serde_yaml_ng::Mapping; +use url::Url; + +pub struct SubscriptionDocument<'a> { + pub body: &'a str, + pub filename: Option, + pub usage: Option, + pub update_interval_minutes: Option, + pub home: Option, +} + +pub struct SubscriptionUsage { + pub upload: u64, + pub download: u64, + pub total: u64, + pub expire: u64, +} + +pub fn decode_subscription<'a>( + url: &Url, + headers: &HeaderMap, + body: &'a str, +) -> Result, SubscriptionError> { + let body = body.trim_start_matches('\u{feff}'); + let yaml = serde_yaml_ng::from_str::(body).map_err(SubscriptionError::InvalidYaml)?; + + if !yaml.contains_key("proxies") && !yaml.contains_key("proxy-providers") { + return Err(SubscriptionError::MissingProviders); + } + + let usage = headers.iter().find_map(|(name, value)| { + let prefix = name.as_str().strip_suffix("subscription-userinfo")?; + if !prefix.is_empty() && !prefix.ends_with('-') { + return None; + } + + let value = value.to_str().unwrap_or(""); + Some(SubscriptionUsage { + upload: find_field(value, "upload", |field| field.parse().ok()).unwrap_or(0), + download: find_field(value, "download", |field| field.parse().ok()).unwrap_or(0), + total: find_field(value, "total", |field| field.parse().ok()).unwrap_or(0), + expire: find_field(value, "expire", |field| field.parse().ok()).unwrap_or(0), + }) + }); + let update_interval_minutes = headers.get("profile-update-interval").and_then(|value| { + let hours = value.to_str().ok()?.parse::().ok()?; + hours.checked_mul(60) + }); + let home = headers + .get("profile-web-page-url") + .and_then(|value| value.to_str().ok()) + .and_then(normalize_profile_home_url); + + Ok(SubscriptionDocument { + body, + filename: subscription_filename(url, headers), + usage, + update_interval_minutes, + home, + }) +} + +fn subscription_filename(url: &Url, headers: &HeaderMap) -> Option { + if let Some(filename) = headers.get("content-disposition").and_then(disposition_filename) { + return Some(filename); + } + let filename = url.path().rsplit('/').next()?; + let filename = percent_decode_str(filename).decode_utf8_lossy(); + if filename.trim().is_empty() { + return None; + } + Some(filename.into_owned()) +} + +fn disposition_filename(header: &http::HeaderValue) -> Option { + let mut quoted = false; + let mut escaped = false; + let fields = header.as_bytes().split(|&byte| { + if escaped { + escaped = false; + } else if quoted && byte == b'\\' { + escaped = true; + } else if byte == b'"' { + quoted = !quoted; + } else if !quoted && byte == b';' { + return true; + } + false + }); + + let mut plain = None; + for field in fields { + let Some((key, value)) = std::str::from_utf8(field).ok().and_then(|s| s.split_once('=')) else { + continue; + }; + let value = value.trim(); + if key.trim().eq_ignore_ascii_case("filename*") { + let encoded = value.splitn(3, '\'').nth(2).unwrap_or(value); + if let Ok(name) = percent_decode_str(encoded).decode_utf8() + && !name.trim().is_empty() + { + return Some(name.into_owned()); + } + } else if plain.is_none() && key.trim().eq_ignore_ascii_case("filename") { + let name = unquote_filename(value); + if !name.trim().is_empty() { + plain = Some(name); + } + } + } + plain +} + +fn unquote_filename(value: &str) -> String { + let Some(inner) = value.strip_prefix('"').and_then(|s| s.strip_suffix('"')) else { + return value.to_owned(); + }; + let mut chars = inner.chars(); + let mut name = String::with_capacity(inner.len()); + while let Some(ch) = chars.next() { + name.push(if ch == '\\' { chars.next().unwrap_or(ch) } else { ch }); + } + name +} + +pub fn normalize_profile_home_url(raw: &str) -> Option { + let url = Url::parse(raw.trim()).ok()?; + + if !matches!(url.scheme(), "http" | "https") { + return None; + } + + url.host_str()?; + Some(url.as_str().into()) +} + +fn find_field<'a, T>(target: &'a str, key: &str, mut parse: impl FnMut(&'a str) -> Option) -> Option { + target.split(';').map(str::trim).find_map(|s| { + let (name, value) = s.split_once('=')?; + if name != key { + return None; + } + + parse(value) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use http::HeaderValue; + + #[test] + fn decodes_metadata_and_preserves_provider_only_yaml() -> Result<(), Box> { + let url = Url::parse("https://example.com/fallback.yaml")?; + let mut headers = HeaderMap::new(); + headers.insert( + "content-disposition", + HeaderValue::from_static("attachment; filename*=UTF-8''My%20Profile.yaml; filename=fallback.yaml"), + ); + headers.insert( + "x-amz-meta-subscription-userinfo", + HeaderValue::from_static("upload=1; download=2; total=3; expire=4"), + ); + headers.insert("profile-update-interval", HeaderValue::from_static("2")); + headers.insert( + "profile-web-page-url", + HeaderValue::from_static(" https://example.com "), + ); + let yaml = "# keep this comment\nproxy-providers: {}\n"; + let body = format!("\u{feff}{yaml}"); + + let document = decode_subscription(&url, &headers, &body)?; + assert_eq!(document.body, yaml); + assert_eq!(document.filename.as_deref(), Some("My Profile.yaml")); + assert_eq!(document.update_interval_minutes, Some(120)); + assert_eq!(document.home.as_deref(), Some("https://example.com/")); + let usage = document.usage.ok_or("missing subscription usage")?; + assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4)); + Ok(()) + } + + #[test] + fn falls_back_when_suggested_filename_is_invalid_or_empty() -> Result<(), Box> { + let url = Url::parse("https://example.com/url.yaml?token=value")?; + let root_url = Url::parse("https://example.com/")?; + for (disposition, url, expected) in [ + ( + "attachment; filename*=UTF-8''%FF; filename=valid.yaml", + &url, + Some("valid.yaml"), + ), + ( + "attachment; filename*=UTF-8''; filename=valid.yaml", + &url, + Some("valid.yaml"), + ), + ("attachment; filename*=UTF-8''%FF", &url, Some("url.yaml")), + ("attachment; filename=", &root_url, None), + ] { + let mut headers = HeaderMap::new(); + headers.insert("content-disposition", HeaderValue::from_static(disposition)); + let document = decode_subscription(url, &headers, "proxies: []")?; + assert_eq!(document.filename.as_deref(), expected); + } + Ok(()) + } + + #[test] + fn reads_filename_parameters_before_falling_back_to_the_url_path() -> Result<(), Box> { + let url = Url::parse("https://example.invalid/sub.yaml#my/notes")?; + for (disposition, expected) in [ + (r#"attachment; FileName="My; \"Work\".yaml""#, r#"My; "Work".yaml"#), + ("attachment; filename*=UTF-8'en'Work%27%27s.yaml", "Work''s.yaml"), + ("attachment", "sub.yaml"), + ] { + let mut headers = HeaderMap::new(); + headers.insert("content-disposition", HeaderValue::from_static(disposition)); + let document = decode_subscription(&url, &headers, "proxies: []")?; + assert_eq!(document.filename.as_deref(), Some(expected)); + } + Ok(()) + } + + #[test] + fn ignores_overflowing_server_interval() -> Result<(), Box> { + let url = Url::parse("https://example.com/My%20Profile.yaml?token=value")?; + let mut headers = HeaderMap::new(); + headers.insert("profile-update-interval", HeaderValue::from_str(&u64::MAX.to_string())?); + + let document = decode_subscription(&url, &headers, "proxies: []")?; + assert_eq!(document.update_interval_minutes, None); + assert_eq!(document.filename.as_deref(), Some("My Profile.yaml")); + Ok(()) + } +} diff --git a/crates/clash-verge-task/src/lib.rs b/crates/clash-verge-task/src/lib.rs index 890fb4a33..e3c369b22 100644 --- a/crates/clash-verge-task/src/lib.rs +++ b/crates/clash-verge-task/src/lib.rs @@ -1,5 +1,6 @@ -//! Single-owner task drivers with caller-managed runtime and cancellation. +//! Task drivers and retry primitives with caller-managed runtime and cancellation. pub mod countdown; +pub mod retry; pub mod scheduled_task; pub mod watch_task; diff --git a/src-tauri/src/utils/retry.rs b/crates/clash-verge-task/src/retry.rs similarity index 67% rename from src-tauri/src/utils/retry.rs rename to crates/clash-verge-task/src/retry.rs index 72c79017b..730c3b3d6 100644 --- a/src-tauri/src/utils/retry.rs +++ b/crates/clash-verge-task/src/retry.rs @@ -21,25 +21,29 @@ pub enum RetryError { Stop(E), } +impl RetryError { + fn into_inner(self) -> E { + match self { + Self::Retry(error) | Self::Stop(error) => error, + } + } +} + pub async fn retry>> + Send>( policy: RetryPolicy, mut operation: impl FnMut(usize) -> Fut + Send, ) -> Result { let mut result = operation(0).await; for (index, delay) in policy.delays().enumerate() { - match result { - Ok(_) | Err(RetryError::Stop(_)) => break, - Err(RetryError::Retry(_)) => { - if !delay.is_zero() { - tokio::time::sleep(delay).await; - } - } + if !matches!(result, Err(RetryError::Retry(_))) { + break; + } + if !delay.is_zero() { + tokio::time::sleep(delay).await; } result = operation(index + 1).await; } - result.map_err(|error| match error { - RetryError::Retry(error) | RetryError::Stop(error) => error, - }) + result.map_err(RetryError::into_inner) } pub async fn try_strategies< @@ -53,15 +57,14 @@ pub async fn try_strategies< rest: [S; N], mut operation: impl FnMut(S) -> Fut + Send, ) -> Result<(S, T), E> { - retry( - RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(N), Duration::ZERO), - move |attempt| { - let strategy = if attempt == 0 { first } else { rest[attempt - 1] }; - let future = operation(strategy); - async move { future.await.map(|value| (strategy, value)).map_err(RetryError::Retry) } - }, - ) - .await + let mut result = operation(first).await.map(|value| (first, value)); + for strategy in rest { + if result.is_ok() { + break; + } + result = operation(strategy).await.map(|value| (strategy, value)); + } + result } pub async fn retry_with_state( @@ -71,19 +74,15 @@ pub async fn retry_with_state( ) -> Result { let mut result = operation(&mut state, 0).await; for (index, delay) in policy.delays().enumerate() { - match result { - Ok(_) | Err(RetryError::Stop(_)) => break, - Err(RetryError::Retry(_)) => { - if !delay.is_zero() { - tokio::time::sleep(delay).await; - } - } + if !matches!(result, Err(RetryError::Retry(_))) { + break; + } + if !delay.is_zero() { + tokio::time::sleep(delay).await; } result = operation(&mut state, index + 1).await; } - result.map_err(|error| match error { - RetryError::Retry(error) | RetryError::Stop(error) => error, - }) + result.map_err(RetryError::into_inner) } pub fn retry_sync( @@ -92,41 +91,39 @@ pub fn retry_sync( ) -> Result { let mut result = operation(0); for (index, delay) in policy.delays().enumerate() { - match result { - Ok(_) | Err(RetryError::Stop(_)) => break, - Err(RetryError::Retry(_)) => { - if !delay.is_zero() { - std::thread::sleep(delay); - } - } + if !matches!(result, Err(RetryError::Retry(_))) { + break; + } + if !delay.is_zero() { + std::thread::sleep(delay); } result = operation(index + 1); } - result.map_err(|error| match error { - RetryError::Retry(error) | RetryError::Stop(error) => error, - }) + result.map_err(RetryError::into_inner) } #[cfg(test)] mod tests { use super::*; + use std::future::ready; - #[tokio::test] + #[tokio::test(start_paused = true)] async fn retries_stop_at_success_terminal_error_or_attempt_limit() { - let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), Duration::ZERO); + let delay = Duration::from_millis(50); + let policy = RetryPolicy::fixed(NonZeroUsize::MIN.saturating_add(2), delay); + let started = tokio::time::Instant::now(); let mut calls = 0; let success = retry(policy, |attempt| { calls += 1; - async move { - if attempt == 1 { - Ok(7) - } else { - Err(RetryError::Retry(attempt)) - } - } + ready(if attempt == 1 { + Ok(7) + } else { + Err(RetryError::Retry(attempt)) + }) }) .await; assert_eq!((success, calls), (Ok(7), 2)); + assert_eq!(started.elapsed(), delay); calls = 0; let stopped = retry(policy, |_| { calls += 1; @@ -134,6 +131,7 @@ mod tests { }) .await; assert_eq!((stopped, calls), (Err("terminal"), 1)); + assert_eq!(started.elapsed(), delay); calls = 0; let exhausted = retry(policy, |attempt| { calls += 1; @@ -141,6 +139,7 @@ mod tests { }) .await; assert_eq!((exhausted, calls), (Err(2), 3)); + assert_eq!(started.elapsed(), delay * 3); } #[tokio::test] @@ -161,11 +160,9 @@ mod tests { let result = retry_with_state(policy, Vec::new(), |visited, attempt| { Box::pin(async move { visited.push(attempt); - if visited.len() == 3 { - Ok(visited.clone()) - } else { - Err(RetryError::Retry(())) - } + (visited.len() == 3) + .then(|| visited.clone()) + .ok_or(RetryError::Retry(())) }) }) .await; diff --git a/src-tauri/AGENTS.md b/src-tauri/AGENTS.md index af2554807..5be7ee572 100644 --- a/src-tauri/AGENTS.md +++ b/src-tauri/AGENTS.md @@ -1,10 +1,17 @@ # Backend Architecture Guardrails -Use [Workspace Crate Architecture](../crates/AGENTS.md) when extracting backend -capabilities or changing background task ownership. +Follow [Workspace Crate Architecture](../crates/AGENTS.md) when changing +backend capability boundaries, reusable orchestration, or background task +ownership. +- **Tauri adapter.** Commands validate transport input, delegate to application + use cases, and map results and errors to IPC. Tauri wires dependencies and + owns desktop lifecycle, window and tray integration, and event delivery. + Keep domain validation and reusable orchestration independent of command + handlers and framework state. - **Configuration and effects.** `config` owns source configuration, drafts, and - persistence. The effects layer classifies every Verge patch field, including + persistence coordination. Persistence adapters perform storage and recovery. + The effects layer classifies every Verge patch field, including fields without effects and platform-specific fields, and reconciles requested state in dependency order. Publish rollbackable state after persistence and commit. On failure, preserve already applied runtime effects, independently diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 10f66b1dd..da77a5232 100755 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -36,6 +36,9 @@ clash-verge-media-unlock = { workspace = true } clash-verge-logging = { workspace = true } clash-verge-i18n = { workspace = true } clash-verge-limiter = { workspace = true } +clash-verge-subscription = { workspace = true } +clash-verge-profile = { workspace = true } +clash-verge-backup-archive = { workspace = true } tauri-plugin-clash-verge-sysinfo = { workspace = true } tauri-plugin-clipboard-manager = { workspace = true } tauri = { workspace = true, features = [ @@ -75,7 +78,7 @@ tauri-plugin-dialog = { version = "2.9.0", default-features = false, features = tauri-plugin-fs = "2.8.0" tauri-plugin-deep-link = "2.6.3" tauri-plugin-window-state = "2.5.1" -zip = "9.9.0" +zip = { workspace = true } flate2 = "1.1.11" reqwest_dav = "0.4.0" aes-gcm = { version = "0.11.1" } diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 13df77750..1f67c509e 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -1,3 +1,5 @@ +#![deny(clippy::expect_used, clippy::unwrap_used)] + fn main() -> Result<(), Box> { if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") && std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") diff --git a/src-tauri/examples/frontend-contract.rs b/src-tauri/examples/frontend-contract.rs index 933b424fe..045f596d3 100644 --- a/src-tauri/examples/frontend-contract.rs +++ b/src-tauri/examples/frontend-contract.rs @@ -1,3 +1,5 @@ +#![deny(clippy::expect_used, clippy::unwrap_used)] + // Dev-only target: Tauri ships everything under src/bin/ to /usr/bin in deb/rpm // bundles (PR #8131), so this generator must stay an example, never a bin. fn main() -> Result<(), Box> { diff --git a/src-tauri/src/cmd/clash.rs b/src-tauri/src/cmd/clash.rs index 8c6468955..0a9720719 100644 --- a/src-tauri/src/cmd/clash.rs +++ b/src-tauri/src/cmd/clash.rs @@ -4,7 +4,7 @@ use crate::feat; use crate::utils::{dirs, yaml_emitter}; use crate::{ cmd::StringifyErr as _, - config::{ClashInfo, Config, profiles::profiles_save_file_safe}, + config::{ClashInfo, Config, profiles::save_committed_profiles}, constants, core::{ CoreManager, handle, @@ -59,7 +59,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult { - logging_error!(Type::Core, profiles_save_file_safe().await); + logging_error!(Type::Core, save_committed_profiles().await); match CoreManager::global().restart_core().await { Ok(_) => { @@ -88,7 +88,7 @@ pub async fn change_clash_core(clash_core: std::string::String) -> CmdResult CmdResult { - logging_error!(Type::Core, profiles_save_file_safe().await); + logging_error!(Type::Core, save_committed_profiles().await); let result = CoreManager::global() .restart_core() .await diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index 5c43c1508..3e6283ff9 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -5,12 +5,12 @@ use crate::core::notify::NoticeStatus; use crate::utils::window_manager::WindowManager; use crate::{ config::{ - Config, IProfiles, PrfItem, PrfOption, + Config, IProfiles, PrfItem, PrfOption, build_remote_profile, profiles::{ - PROFILE_WRITE_LOCK, profiles_append_item_with_filedata_safe, profiles_patch_item_safe, - profiles_reorder_safe, profiles_save_file_safe, + PROFILE_WRITE_LOCK, append_profile, cleanup_profile_files, patch_profile_item, reorder_profiles, + save_committed_profiles, save_profiles, }, - profiles_append_item_safe, + read_profile_item_file, }, core::{CoreManager, handle, timer::Timer, tray::Tray, validate::ValidationOutcome}, feat, @@ -45,7 +45,7 @@ pub async fn get_profiles() -> CmdResult> { #[tauri::command] #[specta::specta] pub async fn enhance_profiles() -> CmdResult { - match feat::enhance_profiles().await { + match CoreManager::global().update_config_forced().await { Ok(outcome) if outcome.is_valid() => { handle::Handle::refresh_clash(); Ok(outcome) @@ -71,7 +71,7 @@ pub async fn enhance_profiles() -> CmdResult { #[tracing::instrument(skip_all, level = "info", fields(url = %help::mask_url(&url), uid = tracing::field::Empty))] #[specta::specta] pub async fn import_profile(url: std::string::String, option: Option) -> CmdResult { - let item = &mut match PrfItem::from_url(&url, None, None, option.as_ref()).await { + let item = &mut match build_remote_profile(&url, None, None, option.as_ref()).await { Ok(it) => it, Err(e) => { logging!(error, Type::Cmd, "[导入订阅] 下载失败: {e:#}"); @@ -79,12 +79,12 @@ pub async fn import_profile(url: std::string::String, option: Option) } }; - if let Err(e) = profiles_append_item_safe(item).await { + if let Err(e) = append_profile(item).await { logging!(error, Type::Cmd, "[导入订阅] 保存配置失败: {e:#}"); return Err(coded_error("PROFILE_IMPORT_FAILED", e)); } - if let Err(e) = profiles_save_file_safe().await { + if let Err(e) = save_committed_profiles().await { logging!(error, Type::Cmd, "[导入订阅] 保存配置文件失败: {e:#}"); return Err(coded_error("PROFILE_IMPORT_FAILED", e)); } @@ -103,7 +103,7 @@ pub async fn import_profile(url: std::string::String, option: Option) pub async fn reorder_profile(active_id: std::string::String, over_id: std::string::String) -> CmdResult { let active_id: String = active_id.into(); let over_id: String = over_id.into(); - match profiles_reorder_safe(&active_id, &over_id).await { + match reorder_profiles(&active_id, &over_id).await { Ok(_) => { logging!(info, Type::Cmd, "重新排序配置文件: {} -> {}", active_id, over_id); Ok(()) @@ -126,9 +126,9 @@ pub async fn reorder_profile(active_id: std::string::String, over_id: std::strin pub async fn create_profile(item: ProfileCreate, file_data: Option) -> CmdResult { let item: PrfItem = item.into(); let file_data = file_data.map(String::from); - match profiles_append_item_with_filedata_safe(&item, file_data).await { + match profiles::create_profile(&item, file_data).await { Ok(_) => { - profiles_save_file_safe() + save_committed_profiles() .await .with_error_code("PROFILE_CREATE_FAILED")?; logging_error!(Type::Timer, Timer::global().refresh().await); @@ -159,9 +159,10 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult { let profiles = Config::profiles().await; let result = profiles - .with_data_modify(|mut candidate| async move { + .with_data_modify::<_, _, _, anyhow::Error>(|mut candidate| async move { let original = candidate.clone(); - let (should_update, plan) = candidate.plan_delete_item(&index)?; + let plan = candidate.plan_delete_item(&index)?; + let should_update = plan.deleting_current; let guard = if should_update { match CoreManager::global() .update_config_forced_with_profiles(&candidate, &original) @@ -171,11 +172,11 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult { Err(outcome) => return Ok((original, Err(outcome))), } } else { - candidate.save_file().await?; + save_profiles(&candidate).await?; None }; let current = candidate.current.clone(); - plan.cleanup().await; + cleanup_profile_files(plan.files).await; Ok((candidate, Ok((should_update, current, guard)))) }) .await @@ -210,18 +211,14 @@ pub async fn delete_profile(index: std::string::String) -> CmdResult { Ok(()) } -async fn restore_previous_profile(prev_profile: &str) -> CmdResult<()> { +async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> { logging!(info, Type::Cmd, "尝试恢复到之前的配置: {}", prev_profile); - let restore_profiles = IProfiles { - current: Some(prev_profile.into()), - items: None, - }; Config::profiles() .await - .edit_draft(|d| d.patch_config(&restore_profiles)); + .edit_draft(|d| d.patch_current(Some(prev_profile))); Config::profiles().await.apply(); crate::process::AsyncHandler::spawn(|| async move { - if let Err(e) = profiles_save_file_safe().await { + if let Err(e) = save_committed_profiles().await { logging!(warn, Type::Cmd, "异步保存恢复配置文件失败: {e:#}"); } }); @@ -236,10 +233,7 @@ async fn commit_current_profile(profiles: &Draft, current: Option) -> CmdResult CmdResult // Prevent an in-flight restore from overwriting a newer UI or chain selection. let records_a_selection = profile.selected.is_some(); - profiles_patch_item_safe(&index, &profile) + patch_profile_item(&index, &profile) .await .with_error_code("PROFILE_UPDATE_FAILED")?; @@ -492,20 +482,17 @@ pub async fn view_profile(index: std::string::String) -> CmdResult { #[tauri::command] #[specta::specta] pub async fn read_profile_file(index: std::string::String) -> CmdResult { - let item = { + let file = { let profiles = Config::profiles().await; let profiles_ref = profiles.latest_arc(); - PrfItem { - file: profiles_ref - .get_item(&index) - .with_error_code("PROFILE_READ_FAILED")? - .file - .to_owned(), - ..Default::default() - } + profiles_ref + .get_item(&index) + .with_error_code("PROFILE_READ_FAILED")? + .file + .clone() }; - if let Some(file) = item.file.as_ref() { + if let Some(file) = file.as_ref() { let path = dirs::app_profiles_dir() .with_error_code("PROFILE_READ_FAILED")? .join(file.as_str()); @@ -521,7 +508,9 @@ pub async fn read_profile_file(index: std::string::String) -> CmdResult((committed, ())) }) .await?; diff --git a/src-tauri/src/cmd/save_profile.rs b/src-tauri/src/cmd/save_profile.rs index 93e65b0b8..35fc4fe78 100644 --- a/src-tauri/src/cmd/save_profile.rs +++ b/src-tauri/src/cmd/save_profile.rs @@ -2,7 +2,7 @@ use super::CmdResult; use crate::{ cmd::StringifyErr as _, cmd::validate::{ValidationNoticeTarget, handle_validation_notice}, - config::{Config, IProfiles, PrfItem}, + config::{Config, IProfiles, read_profile_item_file}, core::auto_backup::{self, AutoBackupTrigger}, core::{ CoreManager, handle, @@ -58,13 +58,7 @@ pub async fn save_profile_file( )) })?; let original_content = if original_existed { - PrfItem { - file: Some(rel_path.clone()), - ..Default::default() - } - .read_file() - .await - .stringify_err()? + read_profile_item_file(Some(rel_path.as_str())).await.stringify_err()? } else { String::new() }; diff --git a/src-tauri/src/config/config.rs b/src-tauri/src/config/config.rs index 93c2b8a67..240d66636 100644 --- a/src-tauri/src/config/config.rs +++ b/src-tauri/src/config/config.rs @@ -1,7 +1,11 @@ use super::{IClashTemp, IProfiles, IVerge, MixedPort}; use crate::core::notify::NoticeStatus; use crate::{ - config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime}, + config::{ + prfitem::{build_merge_profile, build_script_profile}, + profiles::{append_to_profile_index, load_profiles, save_profiles}, + runtime::IRuntime, + }, constants::{files, timing}, core::{ CoreManager, @@ -45,7 +49,7 @@ impl Config { Self { clash_config: Draft::new(IClashTemp::new().await), verge_config: Draft::new(IVerge::new().await), - profiles_config: Draft::new(IProfiles::new().await), + profiles_config: Draft::new(load_profiles().await), runtime_config: Draft::new(IRuntime::default()), } }) @@ -137,12 +141,12 @@ impl Config { } if profiles.latest_arc().get_item("Merge").is_err() { - let merge_item = &mut PrfItem::from_merge(Some("Merge".into())); - profiles_append_item_to_safe(&profiles, merge_item).await?; + let merge_item = &mut build_merge_profile(Some("Merge".into())); + append_to_profile_index(&profiles, merge_item).await?; } if profiles.latest_arc().get_item("Script").is_err() { - let script_item = &mut PrfItem::from_script(Some("Script".into())); - profiles_append_item_to_safe(&profiles, script_item).await?; + let script_item = &mut build_script_profile(Some("Script".into())); + append_to_profile_index(&profiles, script_item).await?; } Ok(()) } @@ -310,7 +314,7 @@ impl Config { let _profile_write = super::profiles::PROFILE_WRITE_LOCK.lock().await; let profiles = Self::profiles().await; profiles.apply(); - logging_error!(Type::Config, profiles.data_arc().save_file().await); + logging_error!(Type::Config, save_profiles(&profiles.data_arc()).await); }); let _ = tokio::join!(save_clash_task, save_verge_task, save_profiles_task); diff --git a/src-tauri/src/config/mod.rs b/src-tauri/src/config/mod.rs index 1be472f88..21335bad7 100644 --- a/src-tauri/src/config/mod.rs +++ b/src-tauri/src/config/mod.rs @@ -12,7 +12,11 @@ pub(crate) mod snapshot; mod verge; pub(crate) use self::config::Config; -pub use self::{clash::*, encrypt::*, mixed_port::*, prfitem::*, profiles::*, verge::*}; +pub(crate) use self::prfitem::{ + build_remote_profile, download_subscription, prepare_remote_refresh, read_profile_item_file, subscription_proxy, +}; +pub use self::{clash::*, encrypt::*, mixed_port::*, profiles::*, verge::*}; +pub use clash_verge_profile::{PrfExtra, PrfItem, PrfOption, PrfSelected}; macro_rules! patch_opt_field { ($lv:expr, $rv:expr, $key:tt) => { diff --git a/src-tauri/src/config/prfitem.rs b/src-tauri/src/config/prfitem.rs index 94a3c0252..2eb1fb608 100644 --- a/src-tauri/src/config/prfitem.rs +++ b/src-tauri/src/config/prfitem.rs @@ -1,4 +1,4 @@ -use super::patch_opt_field; +use super::{PrfExtra, PrfItem, PrfOption}; use crate::{ config::profiles, @@ -9,8 +9,7 @@ use crate::{ }, }; use anyhow::{Context as _, Result, bail}; -use serde::{Deserialize, Serialize}; -use serde_yaml_ng::Mapping; +use clash_verge_subscription::decode_subscription; use std::time::Duration; use tokio::fs; use tristr::alias::String; @@ -18,476 +17,285 @@ use tristr::alias::String; use reqwest_dav::re_exports::url::form_urlencoded; use tauri::Url; -pub(super) fn normalize_profile_home_url(raw: &str) -> Option { - let url = Url::parse(raw.trim()).ok()?; - - if !matches!(url.scheme(), "http" | "https") { - return None; - } - - url.host_str()?; - Some(url.as_str().into()) -} - -#[derive(Debug, Clone, Deserialize, Serialize, Default, specta::Type)] -#[serde(default)] -pub struct PrfItem { - pub uid: Option, - - /// enum value: remote | local | script | merge - #[serde(rename = "type")] - pub itype: Option, - pub name: Option, - pub file: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub desc: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub url: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub selected: Option>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub extra: Option, - - pub updated: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub option: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub home: Option, - - #[serde(skip)] - pub file_data: Option, -} - -#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] -#[serde(default)] -pub struct PrfSelected { - pub name: Option, - pub now: Option, -} - -#[derive(Default, Debug, Clone, Copy, Deserialize, Serialize, specta::Type)] -pub struct PrfExtra { - pub upload: u64, - pub download: u64, - pub total: u64, - pub expire: u64, -} - -#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq, specta::Type)] -#[serde(default)] -pub struct PrfOption { - #[serde(skip_serializing_if = "Option::is_none")] - pub user_agent: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub with_proxy: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub self_proxy: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub update_interval: Option, - - /// HTTP request timeout in seconds - /// default is 60 seconds - #[serde(skip_serializing_if = "Option::is_none")] - pub timeout_seconds: Option, - - /// default is `false` - #[serde(skip_serializing_if = "Option::is_none")] - pub danger_accept_invalid_certs: Option, - - #[serde(skip_serializing_if = "Option::is_none")] - pub allow_auto_update: Option, - pub merge: Option, - pub script: Option, - pub rules: Option, - pub proxies: Option, - pub groups: Option, -} - -impl PrfOption { - pub(crate) fn merge(one: Option<&Self>, other: Option<&Self>) -> Option { - match (one, other) { - (Some(a_ref), Some(b_ref)) => { - let mut result = a_ref.clone(); - patch_opt_field!(result, b_ref, user_agent); - patch_opt_field!(result, b_ref, with_proxy); - patch_opt_field!(result, b_ref, self_proxy); - patch_opt_field!(result, b_ref, danger_accept_invalid_certs); - patch_opt_field!(result, b_ref, allow_auto_update); - patch_opt_field!(result, b_ref, update_interval); - patch_opt_field!(result, b_ref, merge); - patch_opt_field!(result, b_ref, script); - patch_opt_field!(result, b_ref, rules); - patch_opt_field!(result, b_ref, proxies); - patch_opt_field!(result, b_ref, groups); - patch_opt_field!(result, b_ref, timeout_seconds); - Some(result) - } - (Some(a_ref), None) => Some(a_ref.clone()), - (None, Some(b_ref)) => Some(b_ref.clone()), - (None, None) => None, +/// Builds an item from a partial value that must include `itype`. +pub(super) async fn build_profile(item: &PrfItem, file_data: Option) -> Result { + let itype = item + .itype + .as_ref() + .ok_or_else(|| anyhow::anyhow!("type should not be null"))?; + match itype.as_str() { + "remote" => { + let url = item + .url + .as_ref() + .ok_or_else(|| anyhow::anyhow!("url should not be null"))?; + let name = item.name.as_ref(); + let desc = item.desc.as_ref(); + let option = item.option.as_ref(); + build_remote_profile(url, name, desc, option).await } + "local" => { + let name = item.name.clone().unwrap_or_else(|| "Local File".into()); + let desc = item.desc.clone().unwrap_or_else(|| "".into()); + let option = item.option.as_ref(); + from_local(name, desc, file_data, option).await + } + typ => bail!("invalid profile item type \"{typ}\""), } } -impl PrfItem { - /// Builds an item from a partial value that must include `itype`. - pub(super) async fn from(item: &Self, file_data: Option) -> Result { - let itype = item - .itype - .as_ref() - .ok_or_else(|| anyhow::anyhow!("type should not be null"))?; - match itype.as_str() { - "remote" => { - let url = item - .url - .as_ref() - .ok_or_else(|| anyhow::anyhow!("url should not be null"))?; - let name = item.name.as_ref(); - let desc = item.desc.as_ref(); - let option = item.option.as_ref(); - Self::from_url(url, name, desc, option).await - } - "local" => { - let name = item.name.clone().unwrap_or_else(|| "Local File".into()); - let desc = item.desc.clone().unwrap_or_else(|| "".into()); - let option = item.option.as_ref(); - Self::from_local(name, desc, file_data, option).await - } - typ => bail!("invalid profile item type \"{typ}\""), - } +async fn append_companion_item(item: &mut PrfItem) -> Result { + profiles::append_profile(item).await?; + item.uid + .clone() + .ok_or_else(|| anyhow::anyhow!("appended companion item has no uid")) +} + +async fn prepare_profile_options(source: Option<&PrfOption>) -> Result { + let mut options = PrfOption { + update_interval: source.and_then(|options| options.update_interval), + merge: source.and_then(|options| options.merge.clone()), + script: source.and_then(|options| options.script.clone()), + rules: source.and_then(|options| options.rules.clone()), + proxies: source.and_then(|options| options.proxies.clone()), + groups: source.and_then(|options| options.groups.clone()), + ..PrfOption::default() + }; + if options.merge.is_none() { + options.merge = Some(append_companion_item(&mut build_merge_profile(None)).await?); } - - async fn append_companion_item(item: &mut Self) -> Result { - profiles::profiles_append_item_safe(item).await?; - item.uid - .clone() - .ok_or_else(|| anyhow::anyhow!("appended companion item has no uid")) + if options.script.is_none() { + options.script = Some(append_companion_item(&mut build_script_profile(None)).await?); } - - async fn ensure_companion_items( - merge: &mut Option, - script: &mut Option, - rules: &mut Option, - proxies: &mut Option, - groups: &mut Option, - ) -> Result<()> { - if merge.is_none() { - *merge = Some(Self::append_companion_item(&mut Self::from_merge(None)).await?); - } - if script.is_none() { - *script = Some(Self::append_companion_item(&mut Self::from_script(None)).await?); - } - if rules.is_none() { - *rules = Some(Self::append_companion_item(&mut Self::from_rules()).await?); - } - if proxies.is_none() { - *proxies = Some(Self::append_companion_item(&mut Self::from_proxies()).await?); - } - if groups.is_none() { - *groups = Some(Self::append_companion_item(&mut Self::from_groups()).await?); - } - Ok(()) + if options.rules.is_none() { + options.rules = Some(append_companion_item(&mut from_rules()).await?); } - - async fn from_local( - name: String, - desc: String, - file_data: Option, - option: Option<&PrfOption>, - ) -> Result { - let uid = help::get_uid("L").into(); - let file = format!("{uid}.yaml").into(); - let opt_ref = option.as_ref(); - let update_interval = opt_ref.and_then(|o| o.update_interval); - let mut merge = opt_ref.and_then(|o| o.merge.clone()); - let mut script = opt_ref.and_then(|o| o.script.clone()); - let mut rules = opt_ref.and_then(|o| o.rules.clone()); - let mut proxies = opt_ref.and_then(|o| o.proxies.clone()); - let mut groups = opt_ref.and_then(|o| o.groups.clone()); - - Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?; - Ok(Self { - uid: Some(uid), - itype: Some("local".into()), - name: Some(name), - desc: Some(desc), - file: Some(file), - url: None, - selected: None, - extra: None, - option: Some(PrfOption { - update_interval, - merge, - script, - rules, - proxies, - groups, - ..PrfOption::default() - }), - home: None, - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())), - }) + if options.proxies.is_none() { + options.proxies = Some(append_companion_item(&mut from_proxies()).await?); } - - pub(crate) async fn from_url( - url: &str, - name: Option<&String>, - desc: Option<&String>, - option: Option<&PrfOption>, - ) -> Result { - let with_proxy = option.is_some_and(|o| o.with_proxy.unwrap_or(false)); - let self_proxy = option.is_some_and(|o| o.self_proxy.unwrap_or(false)); - let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false)); - let allow_auto_update = Some(allow_auto_update_enabled(option)); - let user_agent = option.and_then(|o| o.user_agent.clone()); - let update_interval = option.and_then(|o| o.update_interval); - let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20); - let mut merge = option.and_then(|o| o.merge.clone()); - let mut script = option.and_then(|o| o.script.clone()); - let mut rules = option.and_then(|o| o.rules.clone()); - let mut proxies = option.and_then(|o| o.proxies.clone()); - let mut groups = option.and_then(|o| o.groups.clone()); - - let proxy_type = if self_proxy { - ProxyType::Localhost - } else if with_proxy { - ProxyType::System - } else { - ProxyType::None - }; - - let url = fix_dirty_url(url)?; - - let resp = match NetworkManager::new() - .get( - url.as_str(), - proxy_type, - Some(timeout), - user_agent.clone(), - accept_invalid_certs, - ) - .await - { - Ok(r) => r, - Err(e) => { - tokio::time::sleep(Duration::from_millis(100)).await; - return Err(e).context("failed to fetch remote profile"); - } - }; - - let status_code = resp.status(); - if !status_code.is_success() { - bail!("failed to fetch remote profile with status {status_code}") - } - - let header = resp.headers(); - - let extra; - 'extra: { - for (k, v) in header.iter() { - let key_lower = k.as_str().to_ascii_lowercase(); - // Accept standard custom-metadata prefixes (x-amz-meta-, x-obs-meta-, x-cos-meta-, etc.). - if key_lower - .strip_suffix("subscription-userinfo") - .is_some_and(|prefix| prefix.is_empty() || prefix.ends_with('-')) - { - let sub_info = v.to_str().unwrap_or(""); - extra = Some(PrfExtra { - upload: help::parse_str(sub_info, "upload").unwrap_or(0), - download: help::parse_str(sub_info, "download").unwrap_or(0), - total: help::parse_str(sub_info, "total").unwrap_or(0), - expire: help::parse_str(sub_info, "expire").unwrap_or(0), - }); - break 'extra; - } - } - extra = None; - } - - let filename = match header.get("Content-Disposition") { - Some(value) => { - let filename = format!("{value:?}"); - let filename = filename.trim_matches('"'); - match help::parse_str::(filename, "filename*") { - Some(filename) => { - let iter = percent_encoding::percent_decode(filename.as_bytes()); - let filename = iter.decode_utf8().unwrap_or_default(); - filename.split("''").last().map(|s| s.into()) - } - None => match help::parse_str::(filename, "filename") { - Some(filename) => { - let filename = filename.trim_matches('"'); - Some(filename.into()) - } - None => None, - }, - } - } - None => { - Some(crate::utils::help::get_last_part_and_decode(url.as_str()).unwrap_or_else(|| "Remote File".into())) - } - }; - let update_interval = match update_interval { - Some(val) => Some(val), - None => match header.get("profile-update-interval") { - Some(value) => match value.to_str().unwrap_or("").parse::() { - Ok(val) => Some(val * 60), // hour -> min - Err(_) => None, - }, - None => None, - }, - }; - - let home = header - .get("profile-web-page-url") - .and_then(|value| value.to_str().ok()) - .and_then(normalize_profile_home_url); - - let uid = help::get_uid("R").into(); - let file = format!("{uid}.yaml").into(); - let name = name.map_or_else( - || filename.map_or_else(|| "Remote File".into(), |s| s.into()), - |s| s.to_owned(), - ); - let data = resp.text(); - - let data = data.trim_start_matches('\u{feff}'); - - let yaml = serde_yaml_ng::from_str::(data).context("the remote profile data is invalid yaml")?; - - if !yaml.contains_key("proxies") && !yaml.contains_key("proxy-providers") { - bail!("profile does not contain `proxies` or `proxy-providers`"); - } - - Self::ensure_companion_items(&mut merge, &mut script, &mut rules, &mut proxies, &mut groups).await?; - - Ok(Self { - uid: Some(uid), - itype: Some("remote".into()), - name: Some(name), - desc: desc.cloned(), - file: Some(file), - url: Some(url.as_str().into()), - selected: None, - extra, - option: Some(PrfOption { - update_interval, - merge, - script, - rules, - proxies, - groups, - allow_auto_update, - ..PrfOption::default() - }), - home, - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(data.into()), - }) + if options.groups.is_none() { + options.groups = Some(append_companion_item(&mut from_groups()).await?); } + Ok(options) +} - pub(super) fn from_merge(uid: Option) -> Self { - let (id, template) = if let Some(uid) = uid { - (uid, tmpl::ITEM_MERGE.into()) - } else { - (help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into()) - }; - let file = format!("{id}.yaml").into(); +async fn from_local( + name: String, + desc: String, + file_data: Option, + option: Option<&PrfOption>, +) -> Result { + let uid = help::get_uid("L").into(); + let file = format!("{uid}.yaml").into(); + let options = prepare_profile_options(option).await?; + Ok(PrfItem { + uid: Some(uid), + itype: Some("local".into()), + name: Some(name), + desc: Some(desc), + file: Some(file), + url: None, + selected: None, + extra: None, + option: Some(options), + home: None, + updated: Some(chrono::Local::now().timestamp() as usize), + file_data: Some(file_data.unwrap_or_else(|| tmpl::ITEM_LOCAL.into())), + }) +} - Self { - uid: Some(id), - itype: Some("merge".into()), - file: Some(file), - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(template), - ..Default::default() - } - } +pub(crate) struct DownloadedSubscription { + url: Url, + suggested_name: Option, + extra: Option, + update_interval_minutes: Option, + home: Option, + body: String, +} - pub(super) fn from_script(uid: Option) -> Self { - let id = if let Some(uid) = uid { - uid - } else { - help::get_uid("s").into() - }; - let file = format!("{id}.js").into(); // js ext - Self { - uid: Some(id), - itype: Some("script".into()), - file: Some(file), - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(tmpl::ITEM_SCRIPT.into()), - ..Default::default() - } - } +pub(crate) struct RemoteProfileRefresh { + pub(super) extra: Option, + pub(super) home: Option, + pub(super) updated: usize, + pub(super) option: PrfOption, + pub(super) body: String, +} - fn new_seq_item(prefix: &str, itype: &str, template: &str) -> Self { - let uid = help::get_uid(prefix).into(); - let file = format!("{uid}.yaml").into(); // yaml ext +pub(crate) async fn build_remote_profile( + url: &str, + name: Option<&String>, + desc: Option<&String>, + option: Option<&PrfOption>, +) -> Result { + let mut downloaded = download_subscription(url, option, subscription_proxy(option)).await?; + let uid: String = help::get_uid("R").into(); + let file = format!("{uid}.yaml").into(); + let name = name + .cloned() + .or_else(|| downloaded.suggested_name.take().map(Into::into)) + .unwrap_or_else(|| "Remote File".into()); + let url = downloaded.url.as_str().into(); + let RemoteProfileRefresh { + extra, + home, + updated, + option, + body, + } = prepare_remote_refresh(downloaded, option).await?; - Self { - uid: Some(uid), - itype: Some(itype.into()), - file: Some(file), - updated: Some(chrono::Local::now().timestamp() as usize), - file_data: Some(template.into()), - ..Default::default() - } - } + Ok(PrfItem { + uid: Some(uid), + itype: Some("remote".into()), + name: Some(name), + desc: desc.cloned(), + file: Some(file), + url: Some(url), + selected: None, + extra, + option: Some(option), + home, + updated: Some(updated), + file_data: Some(body), + }) +} - fn from_rules() -> Self { - Self::new_seq_item("r", "rules", tmpl::ITEM_RULES) - } - - fn from_proxies() -> Self { - Self::new_seq_item("p", "proxies", tmpl::ITEM_PROXIES) - } - - fn from_groups() -> Self { - Self::new_seq_item("g", "groups", tmpl::ITEM_GROUPS) - } - - pub(crate) async fn read_file(&self) -> Result { - let file = self - .file - .as_ref() - .ok_or_else(|| anyhow::anyhow!("could not find the file"))?; - let path = dirs::app_profiles_dir()?.join(file.as_str()); - let content = fs::read_to_string(&path) - .await - .with_context(|| format!("failed to read the file \"{}\"", path.display()))?; - Ok(content.into()) +pub(crate) fn subscription_proxy(options: Option<&PrfOption>) -> ProxyType { + if options.and_then(|options| options.self_proxy) == Some(true) { + ProxyType::Localhost + } else if options.and_then(|options| options.with_proxy) == Some(true) { + ProxyType::System + } else { + ProxyType::None } } -macro_rules! current_field { - ($name:ident, $field:ident) => { - pub(crate) fn $name(&self) -> Option<&String> { - self.option.as_ref().and_then(|o| o.$field.as_ref()) +pub(crate) async fn download_subscription( + url: &str, + option: Option<&PrfOption>, + proxy: ProxyType, +) -> Result { + let accept_invalid_certs = option.is_some_and(|o| o.danger_accept_invalid_certs.unwrap_or(false)); + let user_agent = option.and_then(|o| o.user_agent.clone()); + let timeout = option.and_then(|o| o.timeout_seconds).unwrap_or(20); + let url = fix_dirty_url(url)?; + + let resp = match NetworkManager::new() + .get(url.as_str(), proxy, Some(timeout), user_agent, accept_invalid_certs) + .await + { + Ok(r) => r, + Err(e) => { + tokio::time::sleep(Duration::from_millis(100)).await; + return Err(e).context("failed to fetch remote profile"); } }; + + let status_code = resp.status(); + if !status_code.is_success() { + bail!("failed to fetch remote profile with status {status_code}") + } + + let document = decode_subscription(&url, resp.headers(), resp.text())?; + let extra = document.usage.map(|usage| PrfExtra { + upload: usage.upload, + download: usage.download, + total: usage.total, + expire: usage.expire, + }); + Ok(DownloadedSubscription { + suggested_name: document.filename, + update_interval_minutes: document.update_interval_minutes, + home: document.home.map(Into::into), + body: document.body.into(), + url, + extra, + }) } -impl PrfItem { - current_field!(current_merge, merge); - current_field!(current_script, script); - current_field!(current_rules, rules); - current_field!(current_proxies, proxies); - current_field!(current_groups, groups); +pub(crate) async fn prepare_remote_refresh( + downloaded: DownloadedSubscription, + option: Option<&PrfOption>, +) -> Result { + let mut options = prepare_profile_options(option).await?; + options.update_interval = options.update_interval.or(downloaded.update_interval_minutes); + options.allow_auto_update = Some(option.and_then(|options| options.allow_auto_update).unwrap_or(true)); + Ok(RemoteProfileRefresh { + extra: downloaded.extra, + home: downloaded.home, + updated: chrono::Local::now().timestamp() as usize, + option: options, + body: downloaded.body, + }) } -fn allow_auto_update_enabled(option: Option<&PrfOption>) -> bool { - option.and_then(|o| o.allow_auto_update).unwrap_or(true) +pub(super) fn build_merge_profile(uid: Option) -> PrfItem { + let (id, template) = if let Some(uid) = uid { + (uid, tmpl::ITEM_MERGE.into()) + } else { + (help::get_uid("m").into(), tmpl::ITEM_MERGE_EMPTY.into()) + }; + let file = format!("{id}.yaml").into(); + + PrfItem { + uid: Some(id), + itype: Some("merge".into()), + file: Some(file), + updated: Some(chrono::Local::now().timestamp() as usize), + file_data: Some(template), + ..Default::default() + } +} + +pub(super) fn build_script_profile(uid: Option) -> PrfItem { + let id = if let Some(uid) = uid { + uid + } else { + help::get_uid("s").into() + }; + let file = format!("{id}.js").into(); // js ext + PrfItem { + uid: Some(id), + itype: Some("script".into()), + file: Some(file), + updated: Some(chrono::Local::now().timestamp() as usize), + file_data: Some(tmpl::ITEM_SCRIPT.into()), + ..Default::default() + } +} + +fn new_seq_item(prefix: &str, itype: &str, template: &str) -> PrfItem { + let uid = help::get_uid(prefix).into(); + let file = format!("{uid}.yaml").into(); // yaml ext + + PrfItem { + uid: Some(uid), + itype: Some(itype.into()), + file: Some(file), + updated: Some(chrono::Local::now().timestamp() as usize), + file_data: Some(template.into()), + ..Default::default() + } +} + +fn from_rules() -> PrfItem { + new_seq_item("r", "rules", tmpl::ITEM_RULES) +} + +fn from_proxies() -> PrfItem { + new_seq_item("p", "proxies", tmpl::ITEM_PROXIES) +} + +fn from_groups() -> PrfItem { + new_seq_item("g", "groups", tmpl::ITEM_GROUPS) +} + +pub(crate) async fn read_profile_item_file(file: Option<&str>) -> Result { + let file = file.ok_or_else(|| anyhow::anyhow!("could not find the file"))?; + let path = dirs::app_profiles_dir()?.join(file); + let content = fs::read_to_string(&path) + .await + .with_context(|| format!("failed to read the file \"{}\"", path.display()))?; + Ok(content.into()) } /// Fix URLs where query parameters are incorrectly appended to the path segment @@ -518,3 +326,84 @@ fn fix_dirty_url(input: &str) -> Result { Ok(url) } + +#[cfg(test)] +mod tests { + use super::*; + use tokio::{ + io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader}, + net::TcpListener, + }; + + #[tokio::test] + async fn import_and_refresh_share_subscription_decoding() -> Result<()> { + const BODY: &str = "# keep this comment\nproxies: []\n"; + let listener = TcpListener::bind("127.0.0.1:0").await?; + let url = format!("http://{}/subscription", listener.local_addr()?); + let server = tokio::spawn(async move { + let response = format!( + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\ + Content-Disposition: attachment; filename=remote.yaml\r\n\ + Profile-Update-Interval: 2\r\n\ + Profile-Web-Page-Url: https://example.invalid/\r\n\ + Subscription-Userinfo: upload=1; download=2; total=3; expire=4\r\n\r\n{BODY}", + BODY.len() + ); + for _ in 0..2 { + let (socket, _) = listener.accept().await?; + let mut socket = BufReader::new(socket); + let mut line = std::string::String::new(); + loop { + line.clear(); + if socket.read_line(&mut line).await? == 0 || line == "\r\n" { + break; + } + } + socket.get_mut().write_all(response.as_bytes()).await?; + } + Ok::<_, std::io::Error>(()) + }); + let option = PrfOption { + update_interval: Some(0), + allow_auto_update: Some(false), + timeout_seconds: Some(5), + merge: Some("test-merge".into()), + script: Some("test-script".into()), + rules: Some("test-rules".into()), + proxies: Some("test-proxies".into()), + groups: Some("test-groups".into()), + ..Default::default() + }; + let item: clash_verge_profile::PrfItem = build_remote_profile(&url, None, None, Some(&option)).await?; + let refresh_option = PrfOption { + update_interval: None, + ..option + }; + let downloaded = download_subscription(&url, Some(&refresh_option), ProxyType::None).await?; + let refresh = prepare_remote_refresh(downloaded, Some(&refresh_option)).await?; + server.await??; + assert_eq!(item.itype.as_deref(), Some("remote")); + assert_eq!(item.name.as_deref(), Some("remote.yaml")); + assert_eq!(item.home.as_deref(), Some("https://example.invalid/")); + assert_eq!(item.file_data.as_deref(), Some(BODY)); + assert_eq!(item.current_merge().map(String::as_str), Some("test-merge")); + let usage = item.extra.context("expected decoded usage")?; + assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4)); + let fetched_option = item.option.context("expected profile options")?; + assert_eq!(fetched_option.update_interval, Some(0)); + assert_eq!(fetched_option.allow_auto_update, Some(false)); + + assert_eq!(refresh.body.as_str(), BODY); + assert_eq!(refresh.home, item.home); + let usage = refresh.extra.context("expected refresh usage")?; + assert_eq!((usage.upload, usage.download, usage.total, usage.expire), (1, 2, 3, 4)); + assert_eq!( + refresh.option, + PrfOption { + update_interval: Some(120), + ..fetched_option + } + ); + Ok(()) + } +} diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 2c11e2c7a..121cbe78f 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -1,9 +1,8 @@ use super::{ - PrfOption, patch_opt_field, - prfitem::{PrfItem, PrfSelected, normalize_profile_home_url}, + PrfItem, PrfOption, PrfSelected, patch_opt_field, + prfitem::{RemoteProfileRefresh, build_profile}, }; use crate::core::notify::{Refresh, announce}; -use crate::utils::retry::{RetryError, RetryPolicy, retry, retry_with_state}; use crate::{ core::{handle, tray::Tray}, process::AsyncHandler, @@ -15,12 +14,17 @@ use crate::{ use anyhow::{Context as _, Result, bail}; use clash_verge_draft::Draft; use clash_verge_logging::{Type, logging}; +use clash_verge_profile::selected_nodes::{ + SelectedGroup, reconcile_selected_nodes, selected_nodes_need_confirmation, unsettled_selections, +}; +pub use clash_verge_profile::{IProfilePreview, IProfiles}; +use clash_verge_subscription::normalize_profile_home_url; +use clash_verge_task::retry::{RetryError, RetryPolicy, retry, retry_with_state}; use futures::FutureExt as _; -use serde::{Deserialize, Serialize}; use serde_yaml_ng::Mapping; use std::num::NonZeroUsize; use std::{ - collections::{HashMap, HashSet}, + collections::HashMap, panic::AssertUnwindSafe, path::{Component, Path}, sync::OnceLock, @@ -48,368 +52,190 @@ const SELECTED_NODES_SETTLE_INTERVAL: Duration = Duration::from_secs(1); /// Bounds startup waiting; remaining selections continue restoring in the background. const SELECTED_NODES_FIRST_PASS_BUDGET: Duration = Duration::from_secs(3); -/// Define the `profiles.yaml` schema -#[derive(Default, Debug, Clone, Deserialize, Serialize, specta::Type)] -#[serde(default)] -pub struct IProfiles { - pub current: Option, - - pub items: Option>, -} - -pub struct IProfilePreview<'a> { - pub uid: &'a String, - pub name: &'a String, - pub is_current: bool, -} - -pub(crate) struct ProfileDeletePlan { - files: Vec, -} - -impl ProfileDeletePlan { - pub(crate) async fn cleanup(self) { - let Ok(dir) = dirs::app_profiles_dir() else { - return; - }; - for file in self.files { - let path = dir.join(file.as_str()); - if let Err(error) = path.remove_if_exists().await { - logging!( - warn, - Type::Config, - "Failed to remove deleted profile file {}: {error:#}", - path.display() - ); - } +pub(crate) async fn cleanup_profile_files(files: Vec) { + let Ok(dir) = dirs::app_profiles_dir() else { + return; + }; + for file in files { + let path = dir.join(file.as_str()); + if let Err(error) = path.remove_if_exists().await { + logging!( + warn, + Type::Config, + "Failed to remove deleted profile file {}: {error:#}", + path.display() + ); } } } -impl IProfiles { - fn take_item_file_by_uid(items: &mut Vec, target_uid: Option<&str>) -> Option { - let index = items.iter().position(|item| item.uid.as_deref() == target_uid)?; - items.remove(index).file - } +pub(crate) async fn load_profiles() -> IProfiles { + let path = match dirs::profiles_path() { + Ok(p) => p, + Err(err) => { + logging!(error, Type::Config, "failed to get profiles path: {err:#}"); + return IProfiles::default(); + } + }; - pub async fn new() -> Self { - let path = match dirs::profiles_path() { - Ok(p) => p, - Err(err) => { - logging!(error, Type::Config, "failed to get profiles path: {err:#}"); - return Self::default(); - } - }; - - match help::read_yaml::(&path).await { - Ok(mut profiles) => { - let items = profiles.items.get_or_insert_with(Vec::new); - let mut home_changed = false; - for item in items.iter_mut() { - if item.uid.is_none() { - item.uid = Some(help::get_uid("d").into()); - } - if item.itype.as_deref() == Some("remote") { - item.option - .get_or_insert_with(PrfOption::default) - .allow_auto_update - .get_or_insert(true); - } - - if item - .home - .as_deref() - .is_some_and(|home| normalize_profile_home_url(home).is_none()) - { - item.home = None; - home_changed = true; - } + match help::read_yaml::(&path).await { + Ok(mut profiles) => { + let items = profiles.items.get_or_insert_with(Vec::new); + let mut home_changed = false; + for item in items.iter_mut() { + if item.uid.is_none() { + item.uid = Some(help::get_uid("d").into()); + } + if item.itype.as_deref() == Some("remote") { + item.option + .get_or_insert_with(PrfOption::default) + .allow_auto_update + .get_or_insert(true); } - if home_changed && let Err(err) = profiles.save_file().await { - logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}"); - } - profiles - } - Err(err) => { - logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}"); - Self::default() - } - } - } - - pub async fn save_file(&self) -> Result<()> { - help::save_yaml(&dirs::profiles_path()?, self, Some("# Profiles Config for Clash Verge")).await - } - - /// 只修改current,valid和chain - pub fn patch_config(&mut self, patch: &Self) { - if self.items.is_none() { - self.items = Some(vec![]); - } - - if let Some(current) = &patch.current - && let Some(items) = self.items.as_ref() - { - let some_uid = Some(current); - if items.iter().any(|e| e.uid.as_ref() == some_uid) { - self.current = some_uid.cloned(); - } - } - } - - pub fn get_item(&self, uid: impl AsRef) -> Result<&PrfItem> { - let uid_str = uid.as_ref(); - - if let Some(items) = self.items.as_ref() { - for each in items.iter() { - if let Some(uid_val) = &each.uid - && uid_val.as_str() == uid_str + if item + .home + .as_deref() + .is_some_and(|home| normalize_profile_home_url(home).is_none()) { - return Ok(each); + item.home = None; + home_changed = true; } } - } - bail!("failed to get the profile item \"uid:{}\"", uid_str); - } - - async fn append_item(&mut self, item: &mut PrfItem) -> Result<()> { - let uid = &item.uid; - if uid.is_none() { - bail!("the uid should not be null"); - } - - if let Some(file_data) = item.file_data.take() { - if item.file.is_none() { - bail!("the file should not be null"); + if home_changed && let Err(err) = save_profiles(&profiles).await { + logging!(error, Type::Config, "无法保存已清理的 profiles.yaml: {err:#}"); } - - let file = item - .file - .clone() - .ok_or_else(|| anyhow::anyhow!("file field is required when file_data is provided"))?; - let path = dirs::app_profiles_dir()?.join(file.as_str()); - - fs::write(&path, file_data.as_bytes()) - .await - .with_context(|| format!("failed to write to file \"{file}\""))?; + profiles } - - if self.current.is_none() && (item.itype == Some("remote".into()) || item.itype == Some("local".into())) { - self.current = uid.to_owned(); + Err(err) => { + logging!(error, Type::Config, "failed to read profiles.yaml: {err:#}"); + IProfiles::default() } + } +} - if self.items.is_none() { - self.items = Some(vec![]); - } +pub(crate) async fn save_profiles(profiles: &IProfiles) -> Result<()> { + help::save_yaml( + &dirs::profiles_path()?, + profiles, + Some("# Profiles Config for Clash Verge"), + ) + .await +} - if let Some(items) = self.items.as_mut() { - items.push(item.to_owned()); - } - - Ok(()) +async fn append_item(profiles: &mut IProfiles, item: &mut PrfItem) -> Result<()> { + if item.uid.is_none() { + bail!("the uid should not be null"); } - async fn reorder(&mut self, active_id: &str, over_id: &str) -> Result<()> { + if let Some(file_data) = item.file_data.take() { + if item.file.is_none() { + bail!("the file should not be null"); + } + + let file = item + .file + .clone() + .ok_or_else(|| anyhow::anyhow!("file field is required when file_data is provided"))?; + let path = dirs::app_profiles_dir()?.join(file.as_str()); + + fs::write(&path, file_data.as_bytes()) + .await + .with_context(|| format!("failed to write to file \"{file}\""))?; + } + + profiles.append_item(item); + Ok(()) +} + +async fn patch_item(profiles: &mut IProfiles, uid: &str, item: &PrfItem) -> Result<()> { + if let Some(file) = &item.file { + validate_profile_file(file)?; + } + + let mut items = profiles.items.take().unwrap_or_default(); + + for each in items.iter_mut() { + if each.uid.as_deref() == Some(uid) { + patch_opt_field!(each, item, itype); + patch_opt_field!(each, item, name); + patch_opt_field!(each, item, desc); + patch_opt_field!(each, item, file); + patch_opt_field!(each, item, url); + patch_opt_field!(each, item, selected); + patch_opt_field!(each, item, extra); + patch_opt_field!(each, item, updated); + patch_opt_field!(each, item, option); + + profiles.items = Some(items); + return save_profiles(profiles).await; + } + } + + profiles.items = Some(items); + bail!("failed to find the profile item \"uid:{uid}\"") +} + +fn validate_profile_file(file: &str) -> Result<()> { + let mut components = Path::new(file).components(); + if file.is_empty() + || file.contains('/') + || file.contains('\\') + || !matches!( + (components.next(), components.next()), + (Some(Component::Normal(_)), None) + ) + { + bail!("profile file must be a single filename"); + } + + Ok(()) +} + +/// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone. +/// Returns how many changed so the caller can skip a pointless write. +pub(crate) fn raise_short_update_intervals(profiles: &mut IProfiles, min_minutes: u64) -> usize { + let mut raised = 0; + + for item in profiles.items.iter_mut().flatten() { + let Some(option) = item.option.as_mut() else { + continue; + }; + if option + .update_interval + .is_some_and(|interval| (1..min_minutes).contains(&interval)) { - let Some(items) = self.items.as_mut() else { - return Ok(()); - }; - let old_index = items.iter().rposition(|item| item.uid.as_deref() == Some(active_id)); - let new_index = items.iter().rposition(|item| item.uid.as_deref() == Some(over_id)); - let (Some(old_idx), Some(new_idx)) = (old_index, new_index) else { - return Ok(()); - }; - let item = items.remove(old_idx); - items.insert(new_idx, item); + option.update_interval = Some(min_minutes); + raised += 1; } - self.save_file().await } - async fn patch_item(&mut self, uid: &str, item: &PrfItem) -> Result<()> { - if let Some(file) = &item.file { - Self::validate_profile_file(file)?; - } + raised +} - let mut items = self.items.take().unwrap_or_default(); - - for each in items.iter_mut() { - if each.uid.as_deref() == Some(uid) { - patch_opt_field!(each, item, itype); - patch_opt_field!(each, item, name); - patch_opt_field!(each, item, desc); - patch_opt_field!(each, item, file); - patch_opt_field!(each, item, url); - patch_opt_field!(each, item, selected); - patch_opt_field!(each, item, extra); - patch_opt_field!(each, item, updated); - patch_opt_field!(each, item, option); - - self.items = Some(items); - return self.save_file().await; +pub(crate) async fn current_mapping(profiles: &IProfiles) -> Result { + match (profiles.current.as_ref(), profiles.items.as_ref()) { + (Some(current), Some(items)) => { + if let Some(item) = items.iter().find(|e| e.uid.as_ref() == Some(current)) { + let file_path = match item.file.as_ref() { + Some(file) => dirs::app_profiles_dir()?.join(file.as_str()), + None => bail!("failed to get the file field"), + }; + return help::read_mapping(&file_path).await; } + bail!("failed to find the current profile \"uid:{current}\""); } - - self.items = Some(items); - bail!("failed to find the profile item \"uid:{uid}\"") - } - - fn validate_profile_file(file: &str) -> Result<()> { - let mut components = Path::new(file).components(); - if file.is_empty() - || file.contains('/') - || file.contains('\\') - || !matches!( - (components.next(), components.next()), - (Some(Component::Normal(_)), None) - ) - { - bail!("profile file must be a single filename"); - } - - Ok(()) - } - - /// Updates fields returned by a remote profile refresh. - async fn update_item(&mut self, uid: &str, item: &mut PrfItem) -> Result<()> { - if self.items.is_none() { - self.items = Some(vec![]); - } - - let _ = self.get_item(uid)?; - - if let Some(items) = self.items.as_mut() { - for each in items.iter_mut() { - if each.uid.as_deref() == Some(uid) { - each.extra = item.extra; - each.updated = item.updated; - each.home = item.home.to_owned(); - each.option = PrfOption::merge(each.option.as_ref(), item.option.as_ref()); - if let Some(file_data) = item.file_data.take() { - let file = each.file.take(); - let file = - file.unwrap_or_else(|| item.file.take().unwrap_or_else(|| format!("{}.yaml", uid).into())); - - each.file = Some(file.clone()); - - let path = dirs::app_profiles_dir()?.join(file.as_str()); - - fs::write(&path, file_data.as_bytes()) - .await - .with_context(|| format!("failed to write to file \"{file}\""))?; - } - - break; - } - } - } - - self.save_file().await - } - - /// Raise intervals below `min_minutes`. `None`/`0` mean "never auto-update", left alone. - /// Returns how many changed so the caller can skip a pointless write. - pub fn raise_short_update_intervals(&mut self, min_minutes: u64) -> usize { - let mut raised = 0; - - for item in self.items.iter_mut().flatten() { - let Some(option) = item.option.as_mut() else { - continue; - }; - if option - .update_interval - .is_some_and(|interval| (1..min_minutes).contains(&interval)) - { - option.update_interval = Some(min_minutes); - raised += 1; - } - } - - raised - } - - pub(crate) fn plan_delete_item(&mut self, uid: &str) -> Result<(bool, ProfileDeletePlan)> { - let deleting_current = self.current.as_deref().is_none_or(|current| current == uid); - let delete_uids = self.get_item(uid)?.option.as_ref().map_or_else(Vec::new, |op| { - [ - op.merge.clone(), - op.script.clone(), - op.rules.clone(), - op.proxies.clone(), - op.groups.clone(), - ] - .into_iter() - .collect::>() - }); - let mut items = self.items.take().unwrap_or_default(); - let mut files = Vec::new(); - - if let Some(file) = Self::take_item_file_by_uid(&mut items, Some(uid)) { - files.push(file); - } - - for delete_uid in delete_uids { - if let Some(file) = Self::take_item_file_by_uid(&mut items, delete_uid.as_deref()) { - files.push(file); - } - } - - if deleting_current { - self.current = None; - for item in items.iter() { - if item.itype == Some("remote".into()) || item.itype == Some("local".into()) { - self.current = item.uid.clone(); - break; - } - } - } - - self.items = Some(items); - Ok((deleting_current, ProfileDeletePlan { files })) - } - - /// 获取current指向的订阅内容 - pub async fn current_mapping(&self) -> Result { - match (self.current.as_ref(), self.items.as_ref()) { - (Some(current), Some(items)) => { - if let Some(item) = items.iter().find(|e| e.uid.as_ref() == Some(current)) { - let file_path = match item.file.as_ref() { - Some(file) => dirs::app_profiles_dir()?.join(file.as_str()), - None => bail!("failed to get the file field"), - }; - return help::read_mapping(&file_path).await; - } - bail!("failed to find the current profile \"uid:{current}\""); - } - _ => Ok(Mapping::new()), - } - } - - pub fn profiles_preview(&self) -> Option>> { - self.items.as_ref().map(|items| { - items - .iter() - .filter_map(|e| { - if let (Some(uid), Some(name)) = (e.uid.as_ref(), e.name.as_ref()) { - let is_current = self.current.as_ref() == Some(uid); - let preview = IProfilePreview { uid, name, is_current }; - Some(preview) - } else { - None - } - }) - .collect() - }) + _ => Ok(Mapping::new()), } } // These helpers serialize asynchronous operations against committed profile data. use crate::config::Config; -pub(crate) async fn profiles_append_item_with_filedata_safe(item: &PrfItem, file_data: Option) -> Result<()> { - let item = &mut PrfItem::from(item, file_data).await?; - profiles_append_item_safe(item).await +pub(crate) async fn create_profile(item: &PrfItem, file_data: Option) -> Result<()> { + let item = &mut build_profile(item, file_data).await?; + append_profile(item).await } /// Applies `edit` to the committed profiles; commits only when the edit succeeds. @@ -427,155 +253,76 @@ where .await } -pub(crate) async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()> { +pub(crate) async fn append_profile(item: &mut PrfItem) -> Result<()> { let profiles = Config::profiles().await; - profiles_append_item_to_safe(&profiles, item).await + append_to_profile_index(&profiles, item).await } -pub(super) async fn profiles_append_item_to_safe(profiles: &Draft, item: &mut PrfItem) -> Result<()> { +pub(super) async fn append_to_profile_index(profiles: &Draft, item: &mut PrfItem) -> Result<()> { profiles .with_data_modify(|mut profiles| async move { - profiles.append_item(item).await?; + append_item(&mut profiles, item).await?; Ok((profiles, ())) }) .await } -pub(crate) async fn profiles_patch_item_safe(index: &str, item: &PrfItem) -> Result<()> { - with_profiles_edit(|mut profiles| async move { profiles.patch_item(index, item).await.map(|_| profiles) }).await -} - -pub(crate) async fn profiles_reorder_safe(active_id: &str, over_id: &str) -> Result<()> { - with_profiles_edit(|mut profiles| async move { profiles.reorder(active_id, over_id).await.map(|_| profiles) }).await -} - -pub(crate) async fn profiles_save_file_safe() -> Result<()> { - with_profiles_edit(|profiles| async move { profiles.save_file().await.map(|_| profiles) }).await -} - -pub(crate) async fn profiles_update_item_safe(index: &str, item: &mut PrfItem) -> Result<()> { - with_profiles_edit(|mut profiles| async move { profiles.update_item(index, item).await.map(|_| profiles) }).await -} - -#[derive(Debug, PartialEq, Eq)] -struct SelectedNodesPlan { - selected: Vec, - activations: Vec<(String, String)>, - repaired_count: usize, -} - -fn node_is_available(available_nodes: &[std::string::String], node: &str) -> bool { - available_nodes.iter().any(|available| available == node) -} - -fn selected_nodes_need_confirmation(selected: &[PrfSelected], proxies: &Proxies) -> bool { - selected.iter().any(|selected_item| { - let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else { - return false; - }; - let Some(group) = proxies.proxies.get(group_name.as_str()) else { - return true; - }; - let Some(available_nodes) = group.all.as_deref().filter(|nodes| !nodes.is_empty()) else { - return true; - }; - !node_is_available(available_nodes, node) +pub(crate) async fn patch_profile_item(index: &str, item: &PrfItem) -> Result<()> { + with_profiles_edit(|mut profiles| async move { + patch_item(&mut profiles, index, item).await?; + Ok(profiles) }) + .await } -fn reconcile_selected_nodes( - selected: &[PrfSelected], - previous: Option<&Proxies>, - proxies: &Proxies, -) -> SelectedNodesPlan { - let mut plan = SelectedNodesPlan { - selected: Vec::with_capacity(selected.len()), - activations: Vec::new(), - repaired_count: 0, - }; - let mut seen_groups = HashSet::new(); - let mut unique_selected = selected - .iter() - .rev() - .filter(|item| item.name.as_ref().is_some_and(|name| seen_groups.insert(name.clone()))) - .collect::>(); - unique_selected.reverse(); - plan.repaired_count += selected.len() - unique_selected.len(); +pub(crate) async fn reorder_profiles(active_id: &str, over_id: &str) -> Result<()> { + with_profiles_edit(|mut profiles| async move { + if profiles.reorder(active_id, over_id) { + save_profiles(&profiles).await?; + } + Ok(profiles) + }) + .await +} - for selected_item in unique_selected { - let (Some(group_name), Some(node)) = (&selected_item.name, &selected_item.now) else { - plan.repaired_count += 1; - continue; - }; - let Some(group) = proxies.proxies.get(group_name.as_str()) else { - if previous.is_some_and(|snapshot| !snapshot.proxies.contains_key(group_name.as_str())) { - plan.repaired_count += 1; - } else { - plan.selected.push(selected_item.clone()); - } - continue; - }; - let Some(available_nodes) = group.all.as_deref().filter(|nodes| !nodes.is_empty()) else { - // Provider-backed groups can be temporarily incomplete immediately after a reload. - plan.selected.push(selected_item.clone()); - continue; - }; - let is_selectable_group = matches!( - &group.proxy_type, - ProxyType::Selector | ProxyType::URLTest | ProxyType::Fallback | ProxyType::LoadBalance +pub(crate) async fn save_committed_profiles() -> Result<()> { + with_profiles_edit(|profiles| async move { save_profiles(&profiles).await.map(|_| profiles) }).await +} + +pub(crate) async fn save_remote_refresh(uid: &str, url: &str, refresh: RemoteProfileRefresh) -> Result<()> { + with_profiles_edit(|mut profiles| async move { + let profile = profiles.get_item_mut(uid)?; + anyhow::ensure!( + profile.itype.as_deref() == Some("remote") && profile.url.as_deref() == Some(url), + "profile source changed during refresh" ); - if !is_selectable_group { - let preferred_node = group - .now - .as_deref() - .filter(|current| node_is_available(available_nodes, current)) - .or_else(|| node_is_available(available_nodes, node).then_some(node.as_str())); - if let Some(preferred_node) = preferred_node { - if preferred_node != node.as_str() { - plan.repaired_count += 1; - } - plan.selected.push(PrfSelected { - name: Some(group_name.clone()), - now: Some(preferred_node.into()), - }); - } else { - plan.repaired_count += 1; - } - continue; - } + profile.extra = refresh.extra; + profile.updated = Some(refresh.updated); + profile.home = refresh.home; + profile.option = PrfOption::merge(profile.option.as_ref(), Some(&refresh.option)); + let file = profile + .file + .get_or_insert_with(|| format!("{}.yaml", help::get_uid("R")).into()); + let path = dirs::app_profiles_dir()?.join(file.as_str()); + fs::write(&path, refresh.body.as_bytes()) + .await + .with_context(|| format!("failed to write to file \"{file}\""))?; + save_profiles(&profiles).await?; + Ok(profiles) + }) + .await +} - if node_is_available(available_nodes, node) { - plan.selected.push(selected_item.clone()); - if group.now.as_deref() != Some(node.as_str()) { - plan.activations.push((group_name.clone(), node.clone())); - } - continue; - } - - let missing_was_confirmed = previous - .and_then(|snapshot| snapshot.proxies.get(group_name.as_str())) - .and_then(|group| group.all.as_deref()) - .filter(|nodes| !nodes.is_empty()) - .is_some_and(|nodes| !node_is_available(nodes, node)); - if !missing_was_confirmed { - plan.selected.push(selected_item.clone()); - continue; - } - - plan.repaired_count += 1; - if let Some(current_node) = group - .now - .as_deref() - .filter(|current| node_is_available(available_nodes, current)) - { - plan.selected.push(PrfSelected { - name: Some(group_name.clone()), - now: Some(current_node.into()), - }); - } - } - - plan +fn selected_group<'a>(snapshot: &'a Proxies, name: &str) -> Option> { + let group = snapshot.proxies.get(name)?; + Some(SelectedGroup { + members: group.all.as_deref(), + current: group.now.as_deref(), + selectable: matches!( + group.proxy_type, + ProxyType::Selector | ProxyType::URLTest | ProxyType::Fallback | ProxyType::LoadBalance + ), + }) } /// Cancels restoration so it cannot overwrite a newer selection or profile snapshot. @@ -783,7 +530,7 @@ pub(crate) async fn record_selected_node(group_name: &str, node: &str) -> Result now: Some(node.into()), }), } - profiles.save_file().await?; + save_profiles(&profiles).await?; Ok((profiles, true)) }) .await @@ -812,7 +559,7 @@ pub(crate) async fn forget_selected_node(group_name: &str) -> Result<()> { if !selected.is_empty() { item.selected = Some(selected); } - profiles.save_file().await?; + save_profiles(&profiles).await?; Ok((profiles, true)) }) .await @@ -843,28 +590,12 @@ async fn persist_reconciled_selected( } profile.selected = (!selected.is_empty()).then_some(selected); - profiles.save_file().await?; + save_profiles(&profiles).await?; Ok((profiles, true)) }) .await } -/// Returns recorded selections whose groups have not reached the requested node. -fn unsettled_selections(selected: &[PrfSelected], proxies: &Proxies) -> Vec { - selected - .iter() - .filter_map(|item| { - let (Some(group_name), Some(node)) = (&item.name, &item.now) else { - return None; - }; - match proxies.proxies.get(group_name.as_str()) { - Some(group) if group.now.as_deref() == Some(node.as_str()) => None, - _ => Some(group_name.clone()), - } - }) - .collect() -} - /// Retries selections while provider-backed groups finish loading. async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut HashMap, generation: u64) { let deadline = Instant::now() + SELECTED_NODES_SETTLE_DEADLINE; @@ -891,7 +622,7 @@ async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut Has if !is_activation_current(*generation) { return Ok(()); } - let pending = unsettled_selections(selected, &snapshot); + let pending = unsettled_selections(selected, &snapshot, selected_group); if pending.is_empty() { return Ok(()); } @@ -905,7 +636,7 @@ async fn settle_pending_selections(selected: &[PrfSelected], completed: &mut Has ); return Ok(()); } - let plan = reconcile_selected_nodes(selected, None, &snapshot); + let plan = reconcile_selected_nodes(selected, None, &snapshot, selected_group); if apply_activations(&plan.activations, completed, *generation) .await .is_none() @@ -933,8 +664,8 @@ async fn activate_selected_nodes_worker( return Ok(()); } - let needs_confirmation = selected_nodes_need_confirmation(&selected, &first_snapshot); - let immediate_plan = reconcile_selected_nodes(&selected, None, &first_snapshot); + let needs_confirmation = selected_nodes_need_confirmation(&selected, &first_snapshot, selected_group); + let immediate_plan = reconcile_selected_nodes(&selected, None, &first_snapshot, selected_group); logging!( debug, Type::Config, @@ -962,7 +693,8 @@ async fn activate_selected_nodes_worker( if !is_activation_current(generation) { return Ok(()); } - let confirmed_plan = reconcile_selected_nodes(&selected, Some(&first_snapshot), &second_snapshot); + let confirmed_plan = + reconcile_selected_nodes(&selected, Some(&first_snapshot), &second_snapshot, selected_group); logging!( debug, Type::Config, @@ -1127,19 +859,6 @@ mod tests { use super::*; use tauri_plugin_mihomo::models::Proxy; - fn deletion_item(uid: &str, kind: &str, file: &str, merge: Option<&str>) -> PrfItem { - PrfItem { - uid: Some(uid.into()), - itype: Some(kind.into()), - file: Some(file.into()), - option: merge.map(|uid| PrfOption { - merge: Some(uid.into()), - ..PrfOption::default() - }), - ..PrfItem::default() - } - } - fn interval_item(uid: &str, update_interval: Option) -> PrfItem { PrfItem { uid: Some(uid.into()), @@ -1152,43 +871,6 @@ mod tests { } } - #[tokio::test] - async fn missing_reorder_ids_preserve_ordered_items() -> Result<()> { - let mut profiles = IProfiles { - current: Some("a".into()), - items: Some(vec![ - PrfItem { - uid: Some("a".into()), - ..PrfItem::default() - }, - PrfItem { - uid: Some("b".into()), - ..PrfItem::default() - }, - PrfItem { - uid: Some("c".into()), - ..PrfItem::default() - }, - ]), - }; - let expected = Some(vec![Some("a"), Some("b"), Some("c")]); - - profiles.reorder("missing", "b").await?; - let ordered_uids = profiles - .items - .as_ref() - .map(|items| items.iter().map(|item| item.uid.as_deref()).collect::>()); - assert_eq!(ordered_uids, expected); - - profiles.reorder("a", "missing").await?; - let ordered_uids = profiles - .items - .as_ref() - .map(|items| items.iter().map(|item| item.uid.as_deref()).collect::>()); - assert_eq!(ordered_uids, expected); - Ok(()) - } - #[test] fn raising_intervals_only_touches_those_scheduled_too_often() { let mut profiles = IProfiles { @@ -1209,7 +891,7 @@ mod tests { ]), }; - assert_eq!(profiles.raise_short_update_intervals(1440), 2); + assert_eq!(raise_short_update_intervals(&mut profiles, 1440), 2); let intervals: Vec> = profiles .items @@ -1223,32 +905,12 @@ mod tests { ); assert_eq!( - profiles.raise_short_update_intervals(1440), + raise_short_update_intervals(&mut profiles, 1440), 0, "a second pass must be a no-op, so re-running the migration cannot churn the file" ); } - #[test] - fn delete_plan_defers_files_and_selects_replacement() -> Result<()> { - let mut profiles = IProfiles { - current: Some("a".into()), - items: Some(vec![ - deletion_item("a", "remote", "a.yaml", Some("owned")), - deletion_item("owned", "merge", "owned.yaml", None), - deletion_item("b", "local", "b.yaml", None), - ]), - }; - - let (should_update, plan) = profiles.plan_delete_item("a")?; - - assert!(should_update); - assert_eq!(profiles.current.as_deref(), Some("b")); - assert_eq!(plan.files, vec![String::from("a.yaml"), String::from("owned.yaml")]); - assert!(profiles.get_item("owned").is_err()); - Ok(()) - } - fn selected(group: &str, node: &str) -> PrfSelected { PrfSelected { name: Some(group.into()), @@ -1302,13 +964,13 @@ mod tests { let unloaded = proxies(vec![("provider-group", &[], None)]); assert!( - reconcile_selected_nodes(&saved, Some(&unloaded), &unloaded) + reconcile_selected_nodes(&saved, Some(&unloaded), &unloaded, selected_group) .activations .is_empty(), "nothing can be activated while the group is empty" ); assert_eq!( - unsettled_selections(&saved, &unloaded), + unsettled_selections(&saved, &unloaded, selected_group), vec![String::from("provider-group")], "so the restore must keep looking rather than call it done" ); @@ -1320,7 +982,7 @@ mod tests { let loaded = proxies(vec![("Proxy", &["Node A", "Node B"], Some("Node A"))]); assert!( - unsettled_selections(&saved, &loaded).is_empty(), + unsettled_selections(&saved, &loaded, selected_group).is_empty(), "a group already on its node needs nothing, even though it produces no activation" ); } @@ -1332,7 +994,10 @@ mod tests { let saved = vec![selected("Proxy", "Node A")]; let wrong = proxies(vec![("Proxy", &["Node A", "Node B"], Some("Node B"))]); - assert_eq!(unsettled_selections(&saved, &wrong), vec![String::from("Proxy")]); + assert_eq!( + unsettled_selections(&saved, &wrong, selected_group), + vec![String::from("Proxy")] + ); } #[test] @@ -1350,7 +1015,7 @@ mod tests { }, ]; - assert!(unsettled_selections(&malformed, &proxies(vec![])).is_empty()); + assert!(unsettled_selections(&malformed, &proxies(vec![]), selected_group).is_empty()); } #[test] @@ -1362,7 +1027,7 @@ mod tests { let saved = vec![selected("provider-group", "saved")]; let empty = proxies(vec![]); - let plan = reconcile_selected_nodes(&saved, Some(&empty), &empty); + let plan = reconcile_selected_nodes(&saved, Some(&empty), &empty, selected_group); assert!( plan.selected.is_empty(), @@ -1379,7 +1044,7 @@ mod tests { let had_it = proxies(vec![("provider-group", &["saved"], Some("saved"))]); let lost_it = proxies(vec![]); - let plan = reconcile_selected_nodes(&saved, Some(&had_it), &lost_it); + let plan = reconcile_selected_nodes(&saved, Some(&had_it), &lost_it, selected_group); assert_eq!(plan.selected, saved); assert_eq!(plan.repaired_count, 0); @@ -1405,6 +1070,7 @@ mod tests { &saved, None, &proxies(vec![("group", &["current", "saved"], Some("current"))]), + selected_group, ); assert_eq!(plan.selected, saved); @@ -1415,7 +1081,12 @@ mod tests { #[test] fn replaces_missing_node_with_valid_current_node() { let snapshot = proxies(vec![("group", &["current"], Some("current"))]); - let plan = reconcile_selected_nodes(&[selected("group", "renamed-node")], Some(&snapshot), &snapshot); + let plan = reconcile_selected_nodes( + &[selected("group", "renamed-node")], + Some(&snapshot), + &snapshot, + selected_group, + ); assert_eq!(plan.selected, vec![selected("group", "current")]); assert!(plan.activations.is_empty()); @@ -1428,7 +1099,12 @@ mod tests { ("group", &["current"], Some("current")), ("other-node", &[], None), ]); - let plan = reconcile_selected_nodes(&[selected("group", "other-node")], Some(&snapshot), &snapshot); + let plan = reconcile_selected_nodes( + &[selected("group", "other-node")], + Some(&snapshot), + &snapshot, + selected_group, + ); assert_eq!(plan.selected, vec![selected("group", "current")]); assert!(plan.activations.is_empty()); @@ -1450,7 +1126,7 @@ mod tests { )]), }; - let plan = reconcile_selected_nodes(&[selected("group", "saved")], None, &snapshot); + let plan = reconcile_selected_nodes(&[selected("group", "saved")], None, &snapshot, selected_group); assert_eq!(plan.selected, vec![selected("group", "current")]); assert!(plan.activations.is_empty()); @@ -1468,6 +1144,7 @@ mod tests { ], Some(&snapshot), &snapshot, + selected_group, ); assert!(plan.selected.is_empty()); @@ -1481,8 +1158,8 @@ mod tests { let incomplete = proxies(vec![("group", &[], None)]); let complete = proxies(vec![("group", &["current"], Some("current"))]); - let incomplete_plan = reconcile_selected_nodes(&saved, None, &incomplete); - let one_snapshot_plan = reconcile_selected_nodes(&saved, None, &complete); + let incomplete_plan = reconcile_selected_nodes(&saved, None, &incomplete, selected_group); + let one_snapshot_plan = reconcile_selected_nodes(&saved, None, &complete, selected_group); assert_eq!(incomplete_plan.selected, saved); assert_eq!(incomplete_plan.repaired_count, 0); @@ -1496,7 +1173,7 @@ mod tests { let incomplete = Proxies::default(); let complete = proxies(vec![("group", &["current", "saved"], Some("current"))]); - let plan = reconcile_selected_nodes(&saved, Some(&incomplete), &complete); + let plan = reconcile_selected_nodes(&saved, Some(&incomplete), &complete, selected_group); assert_eq!(plan.selected, saved); assert_eq!(plan.activations, vec![("group".into(), "saved".into())]); @@ -1508,7 +1185,7 @@ mod tests { let saved = vec![selected("group", "old"), selected("group", "new")]; let snapshot = proxies(vec![("group", &["old", "new"], Some("old"))]); - let plan = reconcile_selected_nodes(&saved, None, &snapshot); + let plan = reconcile_selected_nodes(&saved, None, &snapshot, selected_group); assert_eq!(plan.selected, vec![selected("group", "new")]); assert_eq!(plan.activations, vec![("group".into(), "new".into())]); @@ -1523,8 +1200,12 @@ mod tests { ("stale-group", &["fallback"], Some("fallback")), ]); - assert!(selected_nodes_need_confirmation(&saved, &first_snapshot)); - let immediate_plan = reconcile_selected_nodes(&saved, None, &first_snapshot); + assert!(selected_nodes_need_confirmation( + &saved, + &first_snapshot, + selected_group + )); + let immediate_plan = reconcile_selected_nodes(&saved, None, &first_snapshot, selected_group); assert_eq!(immediate_plan.selected, saved); assert_eq!(immediate_plan.activations, vec![("valid-group".into(), "saved".into())]); diff --git a/src-tauri/src/core/backup.rs b/src-tauri/src/core/backup.rs index d0d40ca67..64d8f9485 100644 --- a/src-tauri/src/core/backup.rs +++ b/src-tauri/src/core/backup.rs @@ -3,6 +3,7 @@ use crate::{config::Config, process::AsyncHandler, utils::dirs}; use anyhow::Error; use arc_swap::{ArcSwap, ArcSwapOption}; use backon::{ConstantBuilder, Retryable as _}; +use clash_verge_backup_archive::BackupWriter; use clash_verge_logging::{Type, logging}; use reqwest_dav::list_cmd::{ListEntity, ListFile, ListMultiStatus}; use std::{ @@ -15,7 +16,6 @@ use std::{ }; use tokio::{fs, time::timeout}; use tristr::alias::String; -use zip::write::SimpleFileOptions; const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -275,9 +275,7 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> { let value = zip_path.clone(); let file = AsyncHandler::spawn_blocking(move || std::fs::File::create(&value)).await??; - let mut zip = zip::ZipWriter::new(file); - zip.add_directory("profiles/", SimpleFileOptions::default())?; - let options = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + let mut archive = BackupWriter::new(file)?; if let Ok(mut entries) = fs::read_dir(dirs::app_profiles_dir()?).await { while let Some(entry) = entries.next_entry().await? { @@ -287,15 +285,16 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> { let file_name = file_name_os .to_str() .ok_or_else(|| anyhow::Error::msg("Invalid file name encoding"))?; - let backup_path = format!("profiles/{}", file_name); - zip.start_file(backup_path, options)?; + let mut entry = archive.start_profile(file_name)?; let file_content = fs::read(&path).await?; - zip.write_all(&file_content)?; + entry.write_all(&file_content)?; } } } - zip.start_file(dirs::CLASH_CONFIG, options)?; - zip.write_all(fs::read(dirs::clash_path()?).await?.as_slice())?; + + archive + .start_file(dirs::CLASH_CONFIG)? + .write_all(&fs::read(dirs::clash_path()?).await?)?; let verge_text = fs::read_to_string(dirs::verge_path()?).await?; let mut verge_config: serde_json::Value = serde_yaml_ng::from_str(&verge_text)?; @@ -304,17 +303,20 @@ pub async fn create_backup() -> Result<(String, PathBuf), Error> { obj.remove("webdav_password"); obj.remove("webdav_url"); } - zip.start_file(dirs::VERGE_CONFIG, options)?; - zip.write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?; + archive + .start_file(dirs::VERGE_CONFIG)? + .write_all(serde_yaml_ng::to_string(&verge_config)?.as_bytes())?; let dns_config_path = dirs::app_home_dir()?.join(DNS_CONFIG); if dns_config_path.exists() { - zip.start_file(DNS_CONFIG, options)?; - zip.write_all(fs::read(&dns_config_path).await?.as_slice())?; + archive + .start_file(DNS_CONFIG)? + .write_all(&fs::read(&dns_config_path).await?)?; } - zip.start_file(dirs::PROFILE_YAML, options)?; - zip.write_all(fs::read(dirs::profiles_path()?).await?.as_slice())?; - zip.finish()?; + archive + .start_file(dirs::PROFILE_YAML)? + .write_all(&fs::read(dirs::profiles_path()?).await?)?; + archive.finish()?; Ok((zip_file_name, zip_path)) } diff --git a/src-tauri/src/core/hotkey.rs b/src-tauri/src/core/hotkey.rs index 5ecff74dc..b3ad13315 100755 --- a/src-tauri/src/core/hotkey.rs +++ b/src-tauri/src/core/hotkey.rs @@ -3,7 +3,11 @@ use crate::process::AsyncHandler; use crate::singleton; use crate::utils::notification::{NotificationEvent, notify_event}; use crate::utils::window_manager::WindowManager; -use crate::{config::Config, core::handle, core::lightweight::entry_lightweight_mode, feat}; +use crate::{ + config::Config, + core::{CoreManager, handle, lightweight::entry_lightweight_mode}, + feat, +}; use anyhow::{Result, bail}; use arc_swap::ArcSwap; use clash_verge_logging::{Type, logging}; @@ -165,7 +169,7 @@ impl Hotkey { }); } HotkeyFunction::ReactivateProfiles => { - AsyncHandler::spawn(async move || match feat::enhance_profiles().await { + AsyncHandler::spawn(async move || match CoreManager::global().update_config_forced().await { Ok(outcome) if outcome.is_valid() => { handle::Handle::refresh_clash(); notify_event(NotificationEvent::ProfilesReactivated).await; diff --git a/src-tauri/src/core/manager/config.rs b/src-tauri/src/core/manager/config.rs index c97ba5df4..7dd783758 100644 --- a/src-tauri/src/core/manager/config.rs +++ b/src-tauri/src/core/manager/config.rs @@ -2,7 +2,7 @@ use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode}; use crate::core::notify::NoticeStatus; use crate::core::service::StageRequest; use crate::{ - config::{Config, IProfiles, runtime::IRuntime}, + config::{Config, IProfiles, profiles::save_profiles, runtime::IRuntime}, constants::timing, core::{ handle, @@ -243,7 +243,7 @@ impl CoreManager { crate::config::profiles::restore_selected_nodes().await; return Ok(Err(outcome)); } - match candidate.save_file().await { + match save_profiles(candidate).await { Ok(()) => { tracing::Span::current().record("outcome", "committed"); Ok(Ok(guard)) diff --git a/src-tauri/src/core/manager/mod.rs b/src-tauri/src/core/manager/mod.rs index ca95ad073..6a1747463 100644 --- a/src-tauri/src/core/manager/mod.rs +++ b/src-tauri/src/core/manager/mod.rs @@ -235,7 +235,7 @@ impl CoreManager { anyhow::bail!("core startup blocked after mixed proxy port fallback failure: {reason}"); } - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; retry( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(MAX_PORT_FALLBACK_RETRIES), diff --git a/src-tauri/src/core/manager/state.rs b/src-tauri/src/core/manager/state.rs index 85a3d43de..538212ca5 100644 --- a/src-tauri/src/core/manager/state.rs +++ b/src-tauri/src/core/manager/state.rs @@ -1,7 +1,6 @@ #[cfg(test)] use super::claim_core_readiness_generation; use super::{CoreManager, PROFILE_SELECTIONS_PENDING_COMMIT, RunningMode}; -use crate::utils::retry::{RetryError, RetryPolicy, retry}; use crate::{ AsyncHandler, config::Config, @@ -11,6 +10,7 @@ use crate::{ }; use anyhow::{Context as _, Result}; use clash_verge_logging::Type; +use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; use futures::{ FutureExt as _, future::{Map, Shared}, diff --git a/src-tauri/src/core/proxy_control.rs b/src-tauri/src/core/proxy_control.rs index f012b2d47..38befc063 100644 --- a/src-tauri/src/core/proxy_control.rs +++ b/src-tauri/src/core/proxy_control.rs @@ -555,7 +555,7 @@ pub async fn clear() -> Result<()> { /// A failed system call is usually a transient RPC hiccup, so give it a few tries. async fn clear_with_retry() -> Result<()> { - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; retry( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add((CLEAR_ATTEMPTS - 1) as usize), diff --git a/src-tauri/src/core/runstate/mod.rs b/src-tauri/src/core/runstate/mod.rs index b6e5dd29c..097e0f527 100644 --- a/src-tauri/src/core/runstate/mod.rs +++ b/src-tauri/src/core/runstate/mod.rs @@ -135,7 +135,7 @@ impl RunStateStore { /// Retries transport failures but stops at the first readable reply, including a rejection. pub async fn await_ready(&self, attempts: usize, interval: Duration) -> Result { - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; let attempts = std::num::NonZeroUsize::new(attempts).ok_or_else(|| { ReadyWaitError::Unreachable(anyhow::anyhow!( "service readiness wait was configured with no attempts" diff --git a/src-tauri/src/core/service.rs b/src-tauri/src/core/service.rs index b2763578a..b405e635d 100644 --- a/src-tauri/src/core/service.rs +++ b/src-tauri/src/core/service.rs @@ -1282,7 +1282,7 @@ async fn create_sync_temp(target: &Path) -> Result<(PathBuf, tokio::fs::File)> { .with_context(|| format!("failed to create provider cache directory {}", parent.display()))?; } let name = target.file_name().map_or_default(|name| name.to_string_lossy()); - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; retry( RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(7), std::time::Duration::ZERO), |_| async { @@ -1699,7 +1699,7 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) { } async fn clear_proxy_after_owner_loss() { - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; let result = retry( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(2), diff --git a/src-tauri/src/core/timer.rs b/src-tauri/src/core/timer.rs index d1051b3cd..bae8efb21 100644 --- a/src-tauri/src/core/timer.rs +++ b/src-tauri/src/core/timer.rs @@ -8,6 +8,7 @@ use crate::{ use anyhow::{Context as _, Result}; use clash_verge_draft::Draft; use clash_verge_logging::{Type, logging, logging_error}; +use clash_verge_profile::SubscriptionSchedule as TaskSchedule; use futures::{FutureExt as _, StreamExt as _}; use std::{collections::HashMap, panic::AssertUnwindSafe, time::Duration}; use tokio::{ @@ -24,28 +25,6 @@ enum TimerCommand { TaskFinished(String), } -/// Next update is due at `updated + interval`, but the queue only takes a delay from now. -#[derive(Debug, PartialEq, Eq)] -struct TaskSchedule { - interval_minutes: u64, - first_delay: Duration, -} - -impl TaskSchedule { - /// No recorded `updated` -> full interval. Deadline already past -> `ZERO`, fires at once. - fn new(interval_minutes: u64, updated: Option, now: i64) -> Self { - let full = Timer::interval_duration(interval_minutes); - let elapsed = updated - .filter(|updated| *updated > 0) - .map_or(0, |updated| now.saturating_sub(updated as i64).max(0) as u64); - - Self { - interval_minutes, - first_delay: full.saturating_sub(Duration::from_secs(elapsed)), - } - } -} - struct TaskState { key: Option, interval_minutes: u64, @@ -122,16 +101,9 @@ impl Timer { let mut new_map = HashMap::new(); for item in items { - if let Some(option) = item.option.as_ref() - && let (Some(interval), Some(uid)) = (option.update_interval, &item.uid) - && option.allow_auto_update.unwrap_or(true) - && interval > 0 + if let Some(uid) = &item.uid + && let Some(schedule) = TaskSchedule::for_profile(item, initializing, now) { - let mut schedule = TaskSchedule::new(interval, item.updated, now); - // Startup historically treats an explicit zero timestamp as overdue. - if initializing && item.updated == Some(0) { - schedule.first_delay = Duration::ZERO; - } new_map.insert(uid.clone(), schedule); } } @@ -317,7 +289,7 @@ impl Timer { // Full interval, not from `updated`: a failed run leaves `updated` in the past, so // counting from it would retry at zero delay and spin. - let key = Self::schedule_task(queue, &uid, Self::interval_duration(state.interval_minutes)); + let key = Self::schedule_task(queue, &uid, TaskSchedule::interval_duration(state.interval_minutes)); state.key = Some(key); } @@ -330,10 +302,6 @@ impl Timer { }); } - const fn interval_duration(interval_minutes: u64) -> Duration { - Duration::from_secs(interval_minutes.saturating_mul(60)) - } - fn schedule_task(queue: &mut DelayQueue, uid: &str, delay: Duration) -> Key { queue.insert(String::from(uid), delay) } @@ -348,10 +316,8 @@ impl Timer { fn next_update_time(tasks: &HashMap, profiles: &IProfiles, uid: &str) -> Option { let task = tasks.get(uid).filter(|task| !task.retired)?; - let updated = profiles.get_item(uid).ok()?.updated.filter(|updated| *updated > 0)?; - let updated = i64::try_from(updated).ok()?; - let interval = i64::try_from(task.interval_minutes).ok()?.checked_mul(60)?; - updated.checked_add(interval) + let updated = profiles.get_item(uid).ok()?.updated; + TaskSchedule::reported_deadline(task.interval_minutes, updated) } fn emit_update_event(uid: &str, is_start: bool) { diff --git a/src-tauri/src/enhance/mod.rs b/src-tauri/src/enhance/mod.rs index ed541cf4f..766775ded 100644 --- a/src-tauri/src/enhance/mod.rs +++ b/src-tauri/src/enhance/mod.rs @@ -18,7 +18,7 @@ use crate::config::dns::{DnsOverrideState, dns_override_source}; use crate::core::handle::Handle; use crate::utils::dirs; use crate::{ - config::{Config, IProfiles, IVerge, PrfItem}, + config::{Config, IProfiles, IVerge, PrfItem, profiles::current_mapping}, constants, utils::tmpl, }; @@ -174,8 +174,7 @@ async fn collect_profile_items(profiles: &IProfiles) -> Result { None => return Ok(ProfileItems::default()), }; - let current = profiles - .current_mapping() + let current = current_mapping(profiles) .await .with_context(|| format!("failed to read current profile \"{current_profile_uid}\""))?; diff --git a/src-tauri/src/feat/backup.rs b/src-tauri/src/feat/backup.rs index 934ee28e7..21dafb1f5 100644 --- a/src-tauri/src/feat/backup.rs +++ b/src-tauri/src/feat/backup.rs @@ -1,5 +1,5 @@ use crate::{ - config::{Config, IClashTemp, IProfiles, IVerge}, + config::{Config, IClashTemp, IVerge, profiles::load_profiles}, core::{CoreManager, auto_backup, backup, proxy_control, proxy_control::SystemProxyStateUnknown}, process::AsyncHandler, utils::{ @@ -46,7 +46,7 @@ async fn finalize_restored_verge_config( }); clash_draft.apply(); - let restored_profiles = IProfiles::new().await; + let restored_profiles = load_profiles().await; let profiles_draft = Config::profiles().await; profiles_draft.edit_draft(|d| { *d = restored_profiles; diff --git a/src-tauri/src/feat/core_upgrade.rs b/src-tauri/src/feat/core_upgrade.rs index 645274ec1..7d265777b 100644 --- a/src-tauri/src/feat/core_upgrade.rs +++ b/src-tauri/src/feat/core_upgrade.rs @@ -349,7 +349,7 @@ fn stage_core(target: &Path, package: &[u8], version: &str) -> Result Result<(PathBuf, File)> { - use crate::utils::retry::{RetryError, RetryPolicy, retry_sync}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync}; retry_sync( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(31), diff --git a/src-tauri/src/feat/dns.rs b/src-tauri/src/feat/dns.rs index 0bb2dd624..8c3edf5f4 100644 --- a/src-tauri/src/feat/dns.rs +++ b/src-tauri/src/feat/dns.rs @@ -8,7 +8,7 @@ use crate::{ config::{ Config, dns::{ProfileDnsSettings, dns_override_source}, - profiles::PROFILE_WRITE_LOCK, + profiles::{PROFILE_WRITE_LOCK, current_mapping}, }, constants::files::DNS_CONFIG, core::CoreManager, @@ -36,7 +36,7 @@ pub async fn set_dns_override( ); let source = dns_override_source( profiles.current.as_deref().unwrap_or_default(), - &profiles.current_mapping().await?, + ¤t_mapping(&profiles).await?, )?; if enabled && let Some(source) = source.as_ref().filter(|source| Some(*source) != confirmation.as_ref()) { return Ok(DnsOverrideOutcome::ConfirmationRequired { source: source.clone() }); diff --git a/src-tauri/src/feat/mod.rs b/src-tauri/src/feat/mod.rs index 6cf5fcb8c..f9ce00d87 100644 --- a/src-tauri/src/feat/mod.rs +++ b/src-tauri/src/feat/mod.rs @@ -9,6 +9,7 @@ mod icon; mod listener; mod profile; mod proxy; +mod subscription; mod tun; mod window; @@ -22,5 +23,6 @@ pub use icon::*; pub use listener::*; pub use profile::*; pub use proxy::*; +pub use subscription::update_profile; pub use tun::*; pub use window::*; diff --git a/src-tauri/src/feat/profile.rs b/src-tauri/src/feat/profile.rs index a12c060b4..cfd9e5e69 100644 --- a/src-tauri/src/feat/profile.rs +++ b/src-tauri/src/feat/profile.rs @@ -1,13 +1,11 @@ -use crate::core::notify::NoticeStatus; use crate::core::notify::{Refresh, announce}; use crate::{ cmd, - config::{Config, PrfItem, PrfOption, profiles::profiles_update_item_safe}, - core::{CoreManager, handle, tray, validate::ValidationOutcome}, + config::Config, + core::{handle, tray}, process::AsyncHandler, - utils::help::{mask_err, mask_url}, }; -use anyhow::{Result, bail}; +use anyhow::Result; use clash_verge_logging::{Type, logging}; use std::collections::{HashMap, HashSet}; use tauri_plugin_mihomo::models::{Proxy, ProxyType, Rule}; @@ -201,184 +199,6 @@ async fn finish_proxy_switch(stale_proxies: Vec) { } } -async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result)>> { - let profiles = Config::profiles().await; - let profiles = profiles.latest_arc(); - let item = profiles.get_item(uid)?; - let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote"); - - if !is_remote { - logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新"); - Ok(None) - } else if item.url.is_none() { - logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新"); - bail!("failed to get the profile item url"); - } else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) { - logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新"); - Ok(None) - } else { - logging!( - info, - Type::Config, - "[订阅更新] 远程订阅,URL: {}", - mask_url( - item.url - .as_ref() - .ok_or_else(|| anyhow::anyhow!("Profile URL is None"))? - ) - ); - Ok(Some(( - item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?, - item.option.clone(), - ))) - } -} - -#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))] -async fn perform_profile_update( - uid: &str, - url: &str, - opt: Option<&PrfOption>, - option: Option<&PrfOption>, - is_mannual_trigger: bool, -) -> Result<()> { - let merged_opt = PrfOption::merge(opt, option); - let profiles = Config::profiles().await; - let profiles_arc = profiles.latest_arc(); - let profile_name = profiles_arc - .get_item(uid) - .ok() - .and_then(|item| item.name.clone()) - .unwrap_or_else(|| String::from("UnKnown Profile")); - - #[derive(Clone, Copy)] - enum Strategy { - Configured, - Clash, - System, - } - - let result = - crate::utils::retry::try_strategies(Strategy::Configured, [Strategy::Clash, Strategy::System], |strategy| { - let mut options = merged_opt.clone(); - async move { - let (name, success, failure) = match strategy { - Strategy::Configured => ( - "configured", - "[订阅更新] 更新订阅配置成功", - "[订阅更新] 直接更新失败: {},尝试使用Clash代理更新", - ), - Strategy::Clash => ( - "clash", - "[订阅更新] 使用 Clash代理 更新订阅配置成功", - "[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新", - ), - Strategy::System => ( - "system", - "[订阅更新] 使用 系统代理 更新订阅配置成功", - "[订阅更新] 系统代理更新失败: {},所有重试均已失败", - ), - }; - match strategy { - Strategy::Configured => {} - Strategy::Clash | Strategy::System => { - let option = options.get_or_insert_with(PrfOption::default); - option.self_proxy = Some(matches!(strategy, Strategy::Clash)); - option.with_proxy = Some(matches!(strategy, Strategy::System)); - } - } - tracing::Span::current().record("strategy", name); - let started = std::time::Instant::now(); - let result = PrfItem::from_url(url, None, None, options.as_ref()).await; - let elapsed_field = match strategy { - Strategy::Configured => "configured_elapsed", - Strategy::Clash => "clash_elapsed", - Strategy::System => "system_elapsed", - }; - tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed())); - match &result { - Ok(_) => logging!(info, Type::Config, "{success}"), - Err(error) => logging!( - warn, - Type::Config, - "{}", - failure.replace("{}", &mask_err(&format!("{error:#}"))) - ), - } - result - } - }) - .await; - let last_err = match result { - Ok((strategy, mut item)) => { - // A persistence error must not replay a successful download with another transport. - profiles_update_item_safe(uid, &mut item).await?; - if !matches!(strategy, Strategy::Configured) { - handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str()); - } - return Ok(()); - } - Err(error) => error, - }; - - let last_err = mask_err(&last_err.to_string()); - if is_mannual_trigger { - handle::Handle::notice( - NoticeStatus::UpdateFailedEvenWithClash, - format!("{profile_name} - {last_err}"), - ); - } - bail!(last_err) -} - -#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_mannual_trigger))] -pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_mannual_trigger: bool) -> Result<()> { - let url_opt = should_update_profile(uid, is_mannual_trigger).await?; - - let profile_persisted = match url_opt { - Some((url, opt)) => { - perform_profile_update(uid, &url, opt.as_ref(), option, is_mannual_trigger).await?; - true - } - None => false, - }; - let profiles = Config::profiles().await; - let is_current = profiles.latest_arc().current.as_deref() == Some(uid); - let should_refresh = is_current || (!profile_persisted && is_mannual_trigger); - - if should_refresh { - logging!(debug, Type::Config, "[订阅更新] 更新内核配置"); - match CoreManager::global().update_config_with_force(is_mannual_trigger).await { - Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash), - Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_mannual_trigger => { - logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome); - } - result => { - let message = match result { - Ok(outcome) => outcome.to_string(), - Err(err) => err.to_string(), - }; - let message = mask_err(&message); - let message = if profile_persisted { - format!("订阅已保存,但未能确认已应用到内核: {message}") - } else { - message - }; - logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message); - handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str()); - bail!(message); - } - } - } - - Ok(()) -} - -/// 增强配置 -pub async fn enhance_profiles() -> Result { - CoreManager::global().update_config_forced().await -} - #[cfg(test)] mod tests { use super::*; diff --git a/src-tauri/src/feat/subscription.rs b/src-tauri/src/feat/subscription.rs new file mode 100644 index 000000000..906dff649 --- /dev/null +++ b/src-tauri/src/feat/subscription.rs @@ -0,0 +1,194 @@ +use crate::{ + config::{ + Config, PrfOption, download_subscription, prepare_remote_refresh, profiles::save_remote_refresh, + subscription_proxy, + }, + core::{ + CoreManager, handle, + notify::{NoticeStatus, Refresh, announce}, + validate::ValidationOutcome, + }, + utils::{ + help::{mask_err, mask_url}, + network::ProxyType, + }, +}; +use anyhow::{Result, bail}; +use clash_verge_logging::{Type, logging}; +use tristr::alias::String; + +async fn should_update_profile(uid: &str, ignore_auto_update: bool) -> Result)>> { + let profiles = Config::profiles().await; + let profiles = profiles.latest_arc(); + let item = profiles.get_item(uid)?; + let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote"); + + if !is_remote { + logging!(info, Type::Config, "[订阅更新] 不是远程订阅,跳过更新"); + Ok(None) + } else if item.url.is_none() { + logging!(warn, Type::Config, "[订阅更新] 缺少URL,无法更新"); + bail!("failed to get the profile item url"); + } else if !ignore_auto_update && !item.option.as_ref().and_then(|o| o.allow_auto_update).unwrap_or(true) { + logging!(info, Type::Config, "[订阅更新] 禁止自动更新,跳过更新"); + Ok(None) + } else { + logging!( + info, + Type::Config, + "[订阅更新] 远程订阅,URL: {}", + mask_url( + item.url + .as_ref() + .ok_or_else(|| anyhow::anyhow!("Profile URL is None"))? + ) + ); + Ok(Some(( + item.url.clone().ok_or_else(|| anyhow::anyhow!("Profile URL is None"))?, + item.option.clone(), + ))) + } +} + +#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))] +async fn perform_profile_update( + uid: &str, + url: &str, + profile_options: Option<&PrfOption>, + overrides: Option<&PrfOption>, + is_manual_trigger: bool, +) -> Result<()> { + let options = PrfOption::merge(profile_options, overrides); + let options = options.as_ref(); + let configured_proxy = subscription_proxy(options); + let profiles = Config::profiles().await; + let profiles_arc = profiles.latest_arc(); + let profile_name = profiles_arc + .get_item(uid) + .ok() + .and_then(|item| item.name.clone()) + .unwrap_or_else(|| String::from("UnKnown Profile")); + + #[derive(Clone, Copy)] + enum Strategy { + Configured, + Clash, + System, + } + + let result = clash_verge_task::retry::try_strategies( + Strategy::Configured, + [Strategy::Clash, Strategy::System], + |strategy| async move { + let (name, proxy, elapsed_field, success, failure) = match strategy { + Strategy::Configured => ( + "configured", + configured_proxy, + "configured_elapsed", + "[订阅更新] 更新订阅配置成功", + "[订阅更新] 直接更新失败: {},尝试使用Clash代理更新", + ), + Strategy::Clash => ( + "clash", + ProxyType::Localhost, + "clash_elapsed", + "[订阅更新] 使用 Clash代理 更新订阅配置成功", + "[订阅更新] Clash代理更新失败: {},尝试使用系统代理更新", + ), + Strategy::System => ( + "system", + ProxyType::System, + "system_elapsed", + "[订阅更新] 使用 系统代理 更新订阅配置成功", + "[订阅更新] 系统代理更新失败: {},所有重试均已失败", + ), + }; + tracing::Span::current().record("strategy", name); + let started = std::time::Instant::now(); + let result = download_subscription(url, options, proxy).await; + tracing::Span::current().record(elapsed_field, tracing::field::debug(started.elapsed())); + match &result { + Ok(_) => logging!(info, Type::Config, "{success}"), + Err(error) => logging!( + warn, + Type::Config, + "{}", + failure.replace("{}", &mask_err(&format!("{error:#}"))) + ), + } + result + }, + ) + .await; + let last_err = match result { + Ok((strategy, downloaded)) => { + // A persistence error must not replay a successful download with another transport. + let profiles = Config::profiles().await; + let snapshot = profiles.latest_arc(); + let current = snapshot.get_item(uid)?; + anyhow::ensure!( + current.itype.as_deref() == Some("remote") && current.url.as_deref() == Some(url), + "profile source changed during refresh" + ); + let refresh = prepare_remote_refresh(downloaded, options).await?; + save_remote_refresh(uid, url, refresh).await?; + if !matches!(strategy, Strategy::Configured) { + handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name.as_str()); + } + return Ok(()); + } + Err(error) => error, + }; + + let last_err = mask_err(&last_err.to_string()); + if is_manual_trigger { + handle::Handle::notice( + NoticeStatus::UpdateFailedEvenWithClash, + format!("{profile_name} - {last_err}"), + ); + } + bail!(last_err) +} + +#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))] +pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_trigger: bool) -> Result<()> { + let subscription = should_update_profile(uid, is_manual_trigger).await?; + + let profile_persisted = match subscription { + Some((url, profile_options)) => { + perform_profile_update(uid, &url, profile_options.as_ref(), option, is_manual_trigger).await?; + true + } + None => false, + }; + let profiles = Config::profiles().await; + let is_current = profiles.latest_arc().current.as_deref() == Some(uid); + let should_refresh = is_current || (!profile_persisted && is_manual_trigger); + + if should_refresh { + logging!(debug, Type::Config, "[订阅更新] 更新内核配置"); + match CoreManager::global().update_config_with_force(is_manual_trigger).await { + Ok(outcome) if outcome.is_valid() => announce(Refresh::Clash), + Ok(outcome @ (ValidationOutcome::Skipped { .. } | ValidationOutcome::Busy)) if !is_manual_trigger => { + logging!(info, Type::Config, "[订阅更新] 本次配置刷新已跳过: {}", outcome); + } + result => { + let message = match result { + Ok(outcome) => outcome.to_string(), + Err(err) => err.to_string(), + }; + let message = mask_err(&message); + let message = if profile_persisted { + format!("订阅已保存,但未能确认已应用到内核: {message}") + } else { + message + }; + logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message); + handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str()); + bail!(message); + } + } + } + + Ok(()) +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 61382454d..7a6905602 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1,4 +1,5 @@ #![allow(non_snake_case)] +#![deny(clippy::expect_used, clippy::unwrap_used)] #![recursion_limit = "512"] mod cmd; diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 20f54300e..25ead2a49 100755 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -1,4 +1,5 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +#![deny(clippy::expect_used, clippy::unwrap_used)] use std::process::ExitCode; #[cfg(not(all(feature = "perf-harness", target_os = "macos")))] diff --git a/src-tauri/src/utils/help.rs b/src-tauri/src/utils/help.rs index b77655a6d..53b7346e8 100644 --- a/src-tauri/src/utils/help.rs +++ b/src-tauri/src/utils/help.rs @@ -8,7 +8,6 @@ use serde_yaml_ng::{Mapping, Value}; use std::{ mem::DropGuard, path::{Path, PathBuf}, - str::FromStr, }; use tokio::io::AsyncWriteExt as _; @@ -212,16 +211,6 @@ pub fn get_uid(prefix: &str) -> String { format!("{prefix}{id}") } -pub fn parse_str(target: &str, key: &str) -> Option { - target.split(';').map(str::trim).find_map(|s| { - let mut parts = s.splitn(2, '='); - match (parts.next(), parts.next()) { - (Some(k), Some(v)) if k == key => v.parse::().ok(), - _ => None, - } - }) -} - pub fn hex_encode(bytes: &[u8]) -> String { const HEX: &[u8; 16] = b"0123456789abcdef"; let mut out = String::with_capacity(bytes.len() * 2); @@ -307,18 +296,6 @@ pub fn mask_err(err: &str) -> String { result } -pub fn get_last_part_and_decode(url: &str) -> Option { - let path = url.split('?').next().unwrap_or(""); - let segments: Vec<&str> = path.split('/').collect(); - let last_segment = segments.last()?; - - Some( - percent_encoding::percent_decode_str(last_segment) - .decode_utf8_lossy() - .to_string(), - ) -} - pub fn open_file(path: PathBuf) -> Result<()> { open::that_detached(path.as_os_str())?; Ok(()) diff --git a/src-tauri/src/utils/init.rs b/src-tauri/src/utils/init.rs index 927fc797f..d0ba10f94 100644 --- a/src-tauri/src/utils/init.rs +++ b/src-tauri/src/utils/init.rs @@ -1,5 +1,8 @@ use crate::{ - config::{Config, IClashTemp, IProfiles, IVerge}, + config::{ + Config, IClashTemp, IProfiles, IVerge, + profiles::{raise_short_update_intervals, save_profiles}, + }, constants, core::handle, logging, @@ -266,9 +269,9 @@ pub async fn migrate_short_update_intervals() -> Result<()> { if profiles.items.is_none() { anyhow::bail!("profiles.yaml was not loaded; refusing to record the migration as done"); } - let raised = profiles.raise_short_update_intervals(min); + let raised = raise_short_update_intervals(&mut profiles, min); if raised > 0 { - profiles.save_file().await?; + save_profiles(&profiles).await?; } Ok((profiles, raised)) }) diff --git a/src-tauri/src/utils/macos_launch_guard.rs b/src-tauri/src/utils/macos_launch_guard.rs index 761438634..896fa7c62 100644 --- a/src-tauri/src/utils/macos_launch_guard.rs +++ b/src-tauri/src/utils/macos_launch_guard.rs @@ -109,7 +109,7 @@ fn current_user_home() -> anyhow::Result { } .max(1024); - use crate::utils::retry::{RetryError, RetryPolicy, retry_sync}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry_sync}; retry_sync( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(11), diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rs index e190227cb..106ec4669 100644 --- a/src-tauri/src/utils/mod.rs +++ b/src-tauri/src/utils/mod.rs @@ -11,7 +11,6 @@ pub(crate) mod network; pub use crate::core::notify::desktop as notification; pub mod port; pub mod resolve; -pub mod retry; #[cfg(target_os = "windows")] pub mod schtasks; pub mod server; diff --git a/src-tauri/src/utils/resolve/scheme.rs b/src-tauri/src/utils/resolve/scheme.rs index 86aa598fd..5ff14ac56 100644 --- a/src-tauri/src/utils/resolve/scheme.rs +++ b/src-tauri/src/utils/resolve/scheme.rs @@ -1,15 +1,15 @@ use crate::core::notify::NoticeStatus; use anyhow::Result; -use percent_encoding::percent_decode_str; use tauri::Url; use tristr::alias::String; use crate::{ - config::{Config, PrfItem, profiles}, + config::{Config, PrfItem, build_remote_profile, profiles}, core::{CoreManager, handle, timer::Timer}, utils::help, }; use clash_verge_logging::{Type, logging, logging_error}; +use clash_verge_subscription::decode_subscription_link; pub(super) async fn resolve_scheme(param: &str) -> Result<()> { let param_str = if param.starts_with("[") && param.len() > 4 { @@ -26,7 +26,7 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> { let link_parsed = Url::parse(param_str) .map_err(|e| anyhow::anyhow!("failed to parse deep link: {e:?}, param: {masked_deep_link}"))?; - let Some((url, name)) = extract_subscription_info(&link_parsed) else { + let Some(link) = decode_subscription_link(&link_parsed) else { logging!( warn, Type::Config, @@ -35,51 +35,11 @@ pub(super) async fn resolve_scheme(param: &str) -> Result<()> { return Ok(()); }; - import_subscription(&url, name.as_ref()).await; + let name = link.name.map(String::from); + import_subscription(&link.url, name.as_ref()).await; Ok(()) } -fn extract_subscription_info(link_parsed: &Url) -> Option<(std::string::String, Option)> { - if !matches!(link_parsed.scheme(), "clash" | "clash-verge") { - return None; - } - - let name = link_parsed - .query_pairs() - .find(|(key, _)| key == "name") - .map(|(_, value)| value.into()); - let url = extract_subscription_url(link_parsed)?; - Some((url, name)) -} - -fn extract_subscription_url(link_parsed: &Url) -> Option { - let query = link_parsed.query()?; - let prefix = "url="; - let pos = query.find(prefix)?; - let raw_url = query[pos + prefix.len()..].trim(); - Some(decode_subscription_url(raw_url)) -} - -fn decode_subscription_url(raw_url: &str) -> std::string::String { - // Avoid double-decoding nested subscription URLs; decode only when needed. - if Url::parse(raw_url).is_ok() { - return raw_url.to_string(); - } - - let mut candidate = raw_url.to_string(); - for _ in 0..2 { - let next = percent_decode_str(&candidate).decode_utf8_lossy().to_string(); - if next == candidate { - break; - } - candidate = next; - if Url::parse(&candidate).is_ok() { - break; - } - } - candidate -} - async fn import_subscription(url: &str, name: Option<&String>) { let had_current_profile = { let profiles = Config::profiles().await; @@ -91,14 +51,14 @@ async fn import_subscription(url: &str, name: Option<&String>) { }; let uid = item.uid.clone().unwrap_or_default(); - if let Err(e) = profiles::profiles_append_item_safe(&mut item).await { + if let Err(e) = profiles::append_profile(&mut item).await { logging!(error, Type::Config, "failed to import subscription url: {:?}", e); Config::profiles().await.discard(); handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string()); return; } - if let Err(e) = profiles::profiles_save_file_safe().await { + if let Err(e) = profiles::save_committed_profiles().await { logging!(error, Type::Config, "failed to save imported subscription: {e:#}"); handle::Handle::notice(NoticeStatus::ImportSubUrlError, e.to_string()); return; @@ -113,7 +73,7 @@ async fn import_subscription(url: &str, name: Option<&String>) { } async fn fetch_profile_item(url: &str, name: Option<&String>) -> Option { - match PrfItem::from_url(url, name, None, None).await { + match build_remote_profile(url, name, None, None).await { Ok(item) => Some(item), Err(e) => { logging!(error, Type::Config, "failed to parse profile from url: {:?}", e); diff --git a/src-tauri/src/utils/server.rs b/src-tauri/src/utils/server.rs index bb3577947..fb9052db8 100644 --- a/src-tauri/src/utils/server.rs +++ b/src-tauri/src/utils/server.rs @@ -52,7 +52,7 @@ pub async fn check_singleton() -> Result { .context("failed to initialize singleton lock")?; if !try_lock_instance(&lock).context("failed to acquire singleton lock")? { let deadline = std::time::Instant::now() + Duration::from_secs(20); - use crate::utils::retry::{RetryError, RetryPolicy, retry}; + use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; let secondary = retry( RetryPolicy::fixed( std::num::NonZeroUsize::MIN.saturating_add(400),