From 1c7bc3200b774f486acd0df0df1e29db8a432220 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:13:47 +0800 Subject: [PATCH] refactor(draft): type async publication conflicts Return typed conflicts for async Draft edits. Release the lock and edit permit before converting the error, and exercise overlapping updates. --- Cargo.lock | 2 +- Cargo.toml | 1 + crates/clash-verge-draft/Cargo.toml | 2 +- crates/clash-verge-draft/bench/benche_me.rs | 6 ++-- crates/clash-verge-draft/src/error.rs | 12 +++++++ crates/clash-verge-draft/src/lib.rs | 37 +++++++-------------- crates/clash-verge-draft/tests/test_me.rs | 23 ++++++++----- src-tauri/src/cmd/profile.rs | 4 +-- 8 files changed, 46 insertions(+), 41 deletions(-) create mode 100644 crates/clash-verge-draft/src/error.rs diff --git a/Cargo.lock b/Cargo.lock index c47f34fc7..b54f6789f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1170,9 +1170,9 @@ dependencies = [ name = "clash-verge-draft" version = "0.1.0" dependencies = [ - "anyhow", "criterion", "parking_lot 0.13.0", + "thiserror 2.0.20", "tokio", ] diff --git a/Cargo.toml b/Cargo.toml index 8efb47932..b1a001d8f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,7 @@ tauri = { version = "2.12.7" } tauri-plugin-clipboard-manager = "2.5.0" parking_lot = "0.13.0" anyhow = "1.0.105" +thiserror = "2.0.20" futures = "0.3.34" chrono = "0.4.45" criterion = { version = "0.8.2", features = ["async_tokio"] } 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 af0e403ec..96f828b3e 100644 --- a/crates/clash-verge-draft/tests/test_me.rs +++ b/crates/clash-verge-draft/tests/test_me.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use clash_verge_draft::{Draft, DraftTransaction}; +use clash_verge_draft::{Draft, DraftBusy, DraftConflict, DraftTransaction}; use tokio::sync::Notify; #[derive(Clone, Debug, Default, PartialEq)] @@ -28,14 +28,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 { @@ -47,7 +52,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()); @@ -61,7 +66,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 }) @@ -72,14 +77,14 @@ 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(()) } #[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])?; @@ -94,7 +99,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")); @@ -110,7 +115,7 @@ 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_u8); let held = DraftTransaction::begin(vec![&second])?; diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index 5c43c1508..47e968483 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -159,7 +159,7 @@ 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 guard = if should_update { @@ -584,7 +584,7 @@ mod tests { profiles .with_data_modify(|mut committed| async move { committed.items.get_or_insert_with(Vec::new).push(profile("new")); - Ok((committed, ())) + Ok::<_, clash_verge_draft::DraftConflict>((committed, ())) }) .await?;