mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-01 02:20:07 +08:00
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:
Generated
+1
-1
@@ -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",
|
||||
]
|
||||
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -10,7 +10,7 @@ harness = false
|
||||
|
||||
[dependencies]
|
||||
parking_lot = { workspace = true }
|
||||
anyhow = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -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, ()))
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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<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 {
|
||||
@@ -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<dyn std::error::Error>> {
|
||||
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])?;
|
||||
|
||||
@@ -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?;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user