a_mutex/
lib.rs

1pub mod local;
2pub mod redis;
3
4use std::ops::Deref;
5
6use async_trait::async_trait;
7use auto_impl::auto_impl;
8
9pub type Result<T> = anyhow::Result<T>;
10
11#[async_trait]
12#[auto_impl(&, &mut, Box, Arc)]
13pub trait MutexProvider<T, K>: Send + Sync {
14    type Mutex: Send + Mutex<T>;
15    async fn get(&self, key: K) -> Result<Self::Mutex>
16    where
17        K: 'async_trait;
18}
19
20pub trait GuardLt<'a, T> {
21    type Guard: Guard<T>;
22}
23
24#[async_trait]
25pub trait Mutex<T>: Send + Sync {
26    type Guard: for<'a> GuardLt<'a, T>;
27    async fn lock<'s>(&'s self) -> Result<<Self::Guard as GuardLt<'s, T>>::Guard>;
28}
29
30pub trait DerefLt<'a, T> {
31    type Deref: Deref<Target = Option<T>>;
32}
33
34#[async_trait]
35pub trait Guard<T>: Send + Sync {
36    type D: for<'a> DerefLt<'a, T>;
37    async fn store(&mut self, data: T) -> Result<()>;
38    async fn load<'s>(&'s self) -> Result<<Self::D as DerefLt<'s, T>>::Deref>;
39    async fn clear(&mut self) -> Result<()>;
40}
41
42pub struct Empty;
43
44#[cfg(test)]
45pub mod spec {
46    use std::{
47        sync::{atomic::AtomicI32, Arc},
48        time::Duration,
49    };
50
51    use tokio::spawn;
52
53    use crate::Empty;
54
55    use super::{Guard, Mutex, MutexProvider};
56
57    pub async fn check_empty(m: impl MutexProvider<Empty, &str> + 'static) {
58        let count = Arc::new(AtomicI32::new(0));
59        let m = Arc::new(m);
60        let lock_key = "my_lock";
61        let mut handles = vec![];
62        for _ in 0..100 {
63            let count = count.clone();
64            let m = m.clone();
65            handles.push(spawn(async move {
66                let mutex = m.get(lock_key).await.unwrap();
67                let _guard = mutex.lock().await.unwrap();
68                let copy = count.load(std::sync::atomic::Ordering::Relaxed);
69                tokio::time::sleep(Duration::from_millis(1)).await;
70                count.store(copy + 1, std::sync::atomic::Ordering::Relaxed);
71            }));
72        }
73        for handle in handles {
74            handle.await.unwrap();
75        }
76        assert_eq!(100, count.load(std::sync::atomic::Ordering::Relaxed));
77    }
78
79    pub async fn check_val(m: impl MutexProvider<u64, &str> + 'static) {
80        let m = Arc::new(m);
81        let lock_key = "my_counter_lock";
82        let mut handles = vec![];
83        for _ in 0..100 {
84            let m = m.clone();
85            handles.push(spawn(async move {
86                let mutex = m.get(lock_key).await.unwrap();
87                let mut guard = mutex.lock().await.unwrap();
88                let val = {
89                    let val = guard.load().await.unwrap();
90                    val.clone()
91                };
92                if let Some(val) = val {
93                    guard.store(val + 1).await.unwrap();
94                } else {
95                    guard.store(1).await.unwrap();
96                }
97            }));
98        }
99        for handle in handles {
100            handle.await.unwrap();
101        }
102        let mutex = m.get(lock_key).await.unwrap();
103        let guard = mutex.lock().await.unwrap();
104        assert_eq!(
105            100,
106            *guard
107                .load()
108                .await
109                .unwrap()
110                .as_ref()
111                .expect("no value found")
112        );
113    }
114}