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.
This commit is contained in:
Tunglies
2026-12-03 17:20:32 +08:00
parent 03ff4f846c
commit 72e7201abc
8 changed files with 50 additions and 45 deletions
Generated
+1 -1
View File
@@ -1188,9 +1188,9 @@ dependencies = [
name = "clash-verge-draft"
version = "0.1.0"
dependencies = [
"anyhow",
"criterion",
"parking_lot 0.13.0",
"thiserror 2.0.20",
"tokio",
]
+1
View File
@@ -68,6 +68,7 @@ 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"
futures = "0.3.34"
loom = "0.7.3"
proptest = "1.12.0"
+1 -1
View File
@@ -10,7 +10,7 @@ harness = false
[dependencies]
parking_lot = { workspace = true }
anyhow = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
[dev-dependencies]
+3 -3
View File
@@ -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, ()))
})
+12
View File
@@ -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,
}
+12 -25
View File
@@ -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<T: Clone> Draft<T> {
}
/// Optimistically replaces committed data after an asynchronous edit.
/// The caller's error type carries both edit failures and publication conflicts.
#[inline]
pub async fn with_data_modify<F, Fut, R>(&self, f: F) -> Result<R, anyhow::Error>
pub async fn with_data_modify<F, Fut, R, E>(&self, f: F) -> Result<R, E>
where
T: Send + Sync + 'static,
F: FnOnce(T) -> Fut + Send,
Fut: std::future::Future<Output = Result<(T, R), anyhow::Error>> + Send,
Fut: std::future::Future<Output = Result<(T, R), E>> + Send,
E: From<DraftConflict>,
{
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<T: Clone> Draft<T> {
let (new_local, res) = f(local).await?;
let mut guard = self.inner.data.lock();
if !Arc::ptr_eq(&guard.0, &original_arc) {
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<T: Clone + Send + Sync> DraftLayer for Draft<T> {
}
}
/// Another transaction is already staging a change to one of the layers asked for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DraftBusy {
/// The layer that was already claimed.
pub layer: &'static str,
}
impl std::fmt::Display for DraftBusy {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"configuration layer {} is being changed elsewhere",
self.layer
)
}
}
impl std::error::Error for DraftBusy {}
/// Exclusively claims several draft layers and rolls them all back unless committed.
///
/// A layer has one draft slot, so concurrent transactions cannot be isolated and are rejected.
+18 -13
View File
@@ -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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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::<u16>();
assert_eq!(busy.layer, layer);
assert!(busy.to_string().contains(layer));
+2 -2
View File
@@ -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?;