use std::fmt;
use std::future::ready;
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use tokio::sync::OwnedMutexGuard;
use crate::conditional::{
CommitError, CommitFuture, DeferredFailure, RollbackFuture, SetMode, SetScope, SetScopeId,
SetScopeRequest, current_set_scope,
};
pub struct ScopeGate {
lock: Arc<tokio::sync::Mutex<()>>,
owner: Mutex<Option<(SetScopeId, SetMode)>>,
}
impl ScopeGate {
pub fn new() -> Arc<Self> {
Arc::new(Self {
lock: Arc::new(tokio::sync::Mutex::new(())),
owner: Mutex::new(None),
})
}
fn owner(&self) -> Option<(SetScopeId, SetMode)> {
*self.owner.lock().unwrap_or_else(PoisonError::into_inner)
}
fn set_owner(&self, owner: Option<(SetScopeId, SetMode)>) {
*self.owner.lock().unwrap_or_else(PoisonError::into_inner) = owner;
}
fn owned_by_current(&self) -> Option<SetMode> {
let current = current_set_scope()?;
self.owner()
.and_then(|(id, mode)| (id == current).then_some(mode))
}
}
impl fmt::Debug for ScopeGate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ScopeGate")
.field("owner", &self.owner())
.finish_non_exhaustive()
}
}
pub struct ScopedGuard<'a, T>(MutexGuard<'a, T>);
impl<T> Deref for ScopedGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for ScopedGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T: fmt::Debug> fmt::Debug for ScopedGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
type Validate<T> = Box<dyn FnOnce(&T, &T) -> Vec<DeferredFailure> + Send>;
pub struct ScopedState<T> {
value: Arc<Mutex<T>>,
gate: Arc<ScopeGate>,
}
impl<T> Clone for ScopedState<T> {
fn clone(&self) -> Self {
Self {
value: Arc::clone(&self.value),
gate: Arc::clone(&self.gate),
}
}
}
impl<T: Default> Default for ScopedState<T> {
fn default() -> Self {
Self::new(T::default())
}
}
impl<T: fmt::Debug> fmt::Debug for ScopedState<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ScopedState")
.field("value", &self.value)
.field("gate", &self.gate)
.finish()
}
}
impl<T> ScopedState<T> {
pub fn new(value: T) -> Self {
Self::with_gate(value, ScopeGate::new())
}
pub fn with_gate(value: T, gate: Arc<ScopeGate>) -> Self {
Self {
value: Arc::new(Mutex::new(value)),
gate,
}
}
pub fn gate(&self) -> &Arc<ScopeGate> {
&self.gate
}
pub async fn lock(&self) -> ScopedGuard<'_, T> {
if self.gate.owned_by_current().is_none() {
let _gate = self.gate.lock.lock().await;
return self.lock_unscoped();
}
self.lock_unscoped()
}
pub fn lock_unscoped(&self) -> ScopedGuard<'_, T> {
ScopedGuard(self.value.lock().unwrap_or_else(PoisonError::into_inner))
}
pub fn deferring(&self) -> bool {
self.gate.owned_by_current() == Some(SetMode::Atomic)
}
}
impl<T: Clone + Send + 'static> ScopedState<T> {
pub async fn open<V>(&self, request: SetScopeRequest<'_>, validate: V) -> Box<dyn SetScope>
where
V: FnOnce(&T, &T) -> Vec<DeferredFailure> + Send + 'static,
{
let held = self.gate.owner().is_some_and(|(id, _)| id == request.scope);
let permit = if held {
None
} else {
let permit = Arc::clone(&self.gate.lock).lock_owned().await;
self.gate.set_owner(Some((request.scope, request.mode)));
Some(permit)
};
let atomic = request.mode == SetMode::Atomic;
let snapshot = atomic.then(|| self.lock_unscoped().clone());
Box::new(StateScope {
value: Arc::clone(&self.value),
gate: Arc::clone(&self.gate),
permit,
snapshot,
validate: atomic.then(|| Box::new(validate) as Validate<T>),
})
}
}
struct StateScope<T> {
value: Arc<Mutex<T>>,
gate: Arc<ScopeGate>,
permit: Option<OwnedMutexGuard<()>>,
snapshot: Option<T>,
validate: Option<Validate<T>>,
}
impl<T> StateScope<T> {
fn restore(&mut self) {
if let Some(before) = self.snapshot.take() {
*self.value.lock().unwrap_or_else(PoisonError::into_inner) = before;
}
}
}
impl<T: Send + 'static> SetScope for StateScope<T> {
fn commit(mut self: Box<Self>) -> CommitFuture {
let failures = match (self.snapshot.as_ref(), self.validate.take()) {
(Some(before), Some(validate)) => {
let after = self.value.lock().unwrap_or_else(PoisonError::into_inner);
validate(before, &after)
}
_ => Vec::new(),
};
let result = if failures.is_empty() {
self.snapshot = None;
Ok(())
} else {
self.restore();
Err(CommitError::Rejected(failures))
};
drop(self);
Box::pin(ready(result))
}
fn rollback(self: Box<Self>) -> RollbackFuture {
drop(self);
Box::pin(ready(()))
}
}
impl<T> Drop for StateScope<T> {
fn drop(&mut self) {
self.restore();
if let Some(permit) = self.permit.take() {
self.gate.set_owner(None);
drop(permit);
}
}
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
use jmap_types::{Id, SetError};
use serde_json::Value;
use super::*;
use crate::SetErrorType;
use crate::conditional::{SetOp, in_set_scope};
#[derive(Debug, Clone, Default, PartialEq)]
struct Store {
names: BTreeMap<String, String>,
state: u64,
log: Vec<String>,
}
impl Store {
fn write(&mut self, id: &str, name: &str) {
self.names.insert(id.to_owned(), name.to_owned());
self.state += 1;
self.log.push(id.to_owned());
}
}
fn seeded() -> ScopedState<Store> {
let state = ScopedState::<Store>::default();
state.lock_unscoped().write("a", "one");
state
}
fn now<F: Future>(fut: F) -> F::Output {
let mut cx = Context::from_waker(Waker::noop());
match pin!(fut).poll(&mut cx) {
Poll::Ready(out) => out,
Poll::Pending => panic!("waited, but nothing should block"),
}
}
fn waits<F: Future>(fut: F) -> bool {
let mut cx = Context::from_waker(Waker::noop());
pin!(fut).poll(&mut cx).is_pending()
}
fn request(mode: SetMode) -> SetScopeRequest<'static> {
SetScopeRequest::new("Probe/set", "Probe", None, mode, &Value::Null)
}
fn no_checks(_: &Store, _: &Store) -> Vec<DeferredFailure> {
Vec::new()
}
#[test]
fn lock_never_waits_with_no_scope_open() {
let state = seeded();
assert_eq!(now(state.lock()).names["a"], "one");
let scope = now(state.open(request(SetMode::Atomic), no_checks));
now(scope.commit()).unwrap();
now(state.lock()).write("b", "two");
assert_eq!(state.lock_unscoped().names.len(), 2);
}
#[tokio::test]
async fn unscoped_read_and_write_wait_for_another_tasks_scope() {
let state = seeded();
let req = request(SetMode::Atomic);
let scope = state.open(req, no_checks).await;
in_set_scope(req.scope, async { state.lock().await.write("a", "scoped") }).await;
let reader = state.clone();
let read = tokio::spawn(async move { reader.lock().await.names["a"].clone() });
let writer = state.clone();
let write = tokio::spawn(async move { writer.lock().await.write("b", "outside") });
for _ in 0..10 {
tokio::task::yield_now().await;
}
assert!(!read.is_finished(), "a read must not see the open scope");
assert!(!write.is_finished(), "a write must wait for the open scope");
scope.rollback().await;
assert_eq!(read.await.unwrap(), "one");
write.await.unwrap();
let after = state.lock_unscoped();
assert_eq!(after.names["a"], "one");
assert_eq!(after.names["b"], "outside");
assert_eq!(after.log, ["a", "b"]);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn unscoped_writes_racing_rolled_back_scopes_are_kept() {
const WRITES: u64 = 2000;
let state = ScopedState::new(0_u64);
let writers: Vec<_> = (0..2)
.map(|_| {
let state = state.clone();
tokio::spawn(async move {
for _ in 0..WRITES {
*state.lock().await += 1;
tokio::task::yield_now().await;
}
})
})
.collect();
let scoper = {
let state = state.clone();
tokio::spawn(async move {
for _ in 0..WRITES {
let req = request(SetMode::Atomic);
let scope = state.open(req, |_: &u64, _: &u64| Vec::new()).await;
in_set_scope(req.scope, async { *state.lock().await += 1_000_000 }).await;
scope.rollback().await;
}
})
};
for w in writers {
w.await.unwrap();
}
scoper.await.unwrap();
assert_eq!(*state.lock_unscoped(), 2 * WRITES);
}
#[test]
fn scope_owner_reenters_without_waiting() {
let state = seeded();
let req = request(SetMode::Isolated);
let _scope = now(state.open(req, no_checks));
let len = now(in_set_scope(req.scope, async {
state.lock().await.write("b", "two");
state.lock().await.write("c", "three");
state.lock().await.names.len()
}));
assert_eq!(len, 3);
assert!(waits(state.lock()));
}
#[test]
fn states_sharing_a_gate_do_not_deadlock() {
let a = seeded();
let b = ScopedState::with_gate(Store::default(), Arc::clone(a.gate()));
let req = request(SetMode::Atomic);
let scope_a = now(a.open(req, no_checks));
let scope_b = now(b.open(req, no_checks));
now(in_set_scope(req.scope, async {
a.lock().await.write("a", "changed");
b.lock().await.write("x", "new");
a.lock().await.write("a", "again");
}));
assert!(waits(b.lock()), "b is gated by a's scope");
now(scope_b.rollback());
assert_eq!(*b.lock_unscoped(), Store::default());
assert!(waits(a.lock()));
now(scope_a.commit()).unwrap();
assert_eq!(now(a.lock()).names["a"], "again");
assert_eq!(*now(b.lock()), Store::default());
}
#[test]
fn rollback_restores_state_and_change_log() {
let state = seeded();
let before = state.lock_unscoped().clone();
let req = request(SetMode::Atomic);
let scope = now(state.open(req, no_checks));
now(in_set_scope(req.scope, async {
let mut s = state.lock().await;
s.write("a", "renamed");
s.write("b", "created");
}));
assert_eq!(state.lock_unscoped().state, 3);
now(scope.rollback());
assert_eq!(*state.lock_unscoped(), before);
assert_eq!(before.state, 1);
assert_eq!(before.log, ["a"]);
}
#[test]
fn dropping_a_scope_rolls_back_and_frees_the_gate() {
let state = seeded();
let before = state.lock_unscoped().clone();
let req = request(SetMode::Atomic);
let scope = now(state.open(req, no_checks));
now(in_set_scope(req.scope, async {
state.lock().await.write("b", "two")
}));
drop(scope);
assert_eq!(*now(state.lock()), before);
}
#[test]
fn commit_keeps_changes_validated_against_the_final_state() {
let state = seeded();
let req = request(SetMode::Atomic);
let scope = now(state.open(req, |before: &Store, after: &Store| {
assert_eq!(before.names["a"], "one");
assert_eq!(after.names["a"], "two");
Vec::new()
}));
now(in_set_scope(req.scope, async {
state.lock().await.write("a", "two")
}));
now(scope.commit()).unwrap();
let after = state.lock_unscoped();
assert_eq!((after.names["a"].as_str(), after.state), ("two", 2));
}
#[test]
fn rejected_commit_restores_and_reports_the_failures() {
let state = seeded();
let before = state.lock_unscoped().clone();
let req = request(SetMode::Atomic);
let scope = now(state.open(req, |_: &Store, after: &Store| {
let mut seen = BTreeMap::new();
after
.names
.iter()
.filter(|(_, name)| seen.insert(name.as_str(), ()).is_some())
.map(|(id, _)| {
DeferredFailure::new(
SetOp::Update(Id::new_validated(id).unwrap()),
SetError::new(SetErrorType::AlreadyExists),
)
})
.collect()
}));
now(in_set_scope(req.scope, async {
state.lock().await.write("b", "one")
}));
let Err(CommitError::Rejected(failures)) = now(scope.commit()) else {
panic!("a duplicate name must reject the commit");
};
assert_eq!(failures.len(), 1);
assert_eq!(
failures[0].op,
SetOp::Update(Id::new_validated("b").unwrap())
);
assert_eq!(
*now(state.lock()),
before,
"rejected: rolled back, gate free"
);
}
#[test]
fn isolated_scope_keeps_its_writes_and_skips_validate() {
let state = seeded();
let req = request(SetMode::Isolated);
let scope = now(
state.open(req, |_: &Store, _: &Store| -> Vec<DeferredFailure> {
panic!("an isolated scope has no final-state check")
}),
);
now(in_set_scope(req.scope, async {
assert!(!state.deferring());
state.lock().await.write("b", "two");
}));
now(scope.commit()).unwrap();
assert_eq!(now(state.lock()).names.len(), 2);
let req = request(SetMode::Isolated);
let scope = now(state.open(req, no_checks));
now(in_set_scope(req.scope, async {
state.lock().await.write("c", "three")
}));
now(scope.rollback());
assert_eq!(now(state.lock()).names.len(), 3);
}
#[test]
fn deferring_only_inside_the_running_atomic_scope() {
let state = seeded();
assert!(!state.deferring());
let req = request(SetMode::Atomic);
let scope = now(state.open(req, no_checks));
assert!(!state.deferring(), "not in the scope");
assert!(now(in_set_scope(req.scope, async { state.deferring() })));
let other = SetScopeId::next();
assert!(!now(in_set_scope(other, async { state.deferring() })));
drop(scope);
assert!(!now(in_set_scope(req.scope, async { state.deferring() })));
}
}