1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use std::cmp::Eq;
use std::collections::{hash_map::Entry, HashMap};
use std::future::Future;
use std::hash::Hash;
use std::sync::{Arc, Mutex};

struct ReenterCaller<T>
where
    T: Send + 'static + Clone,
{
    result: Option<T>,
}

impl<T> ReenterCaller<T>
where
    T: Send + 'static + Clone,
{
    pub fn new() -> Self {
        Self { result: None }
    }
}

#[derive(Clone)]
pub struct ReenterCallManager<K, T>
where
    K: Hash + Eq + ToOwned<Owned = K>,
    T: Send + 'static + Clone,
{
    call_list: Arc<Mutex<HashMap<K, Arc<async_std::sync::Mutex<ReenterCaller<T>>>>>>,
}

impl<K, T> ReenterCallManager<K, T>
where
    K: Hash + Eq + ToOwned<Owned = K>,
    T: Send + 'static + Clone,
{
    pub fn new() -> Self {
        Self {
            call_list: Arc::new(Mutex::new(HashMap::new())),
        }
    }
}

impl<K, T> ReenterCallManager<K, T>
where
    K: Hash + Eq + ToOwned<Owned = K>,
    T: Send + 'static + Clone,
{
    pub async fn call<F>(&self, key: &K, future: F) -> T
    where
        F: Future<Output = T> + Send + 'static,
    {
        // debug!("will reenter call: key={}", key);

        let caller = {
            let mut list = self.call_list.lock().unwrap();
            match list.entry(key.to_owned()) {
                Entry::Occupied(o) => o.get().clone(),
                Entry::Vacant(v) => {
                    let caller = ReenterCaller::new();
                    let item = Arc::new(async_std::sync::Mutex::new(caller));
                    v.insert(item.clone());
                    item
                }
            }
        };

        // 这里必须使用异步锁,来保证调用中不重入
        let mut item = caller.lock().await;

        // 第一个进来的result一定为空,需要锁住并执行目标闭包
        if item.result.is_none() {
            let ret = future.await;

            // 移除
            {
                let mut list = self.call_list.lock().unwrap();
                list.remove(key);
            }

            // 如果引用计数>1, 说明有重入的操作在等待,需要缓存闭包的返回值
            let ref_count = Arc::strong_count(&caller);
            if ref_count > 1 {
                assert!(item.result.is_none());
                item.result = Some(ret.clone());
            }
            ret
        } else {
            assert!(item.result.is_some());
            item.result.as_ref().unwrap().clone()
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use cyfs_base::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    #[derive(Clone)]
    struct TestReneterCaller {
        caller_manager: ReenterCallManager<String, BuckyResult<u32>>,
        next_value: Arc<AtomicU32>,
    }

    impl TestReneterCaller {
        pub fn new() -> Self {
            Self {
                caller_manager: ReenterCallManager::new(),
                next_value: Arc::new(AtomicU32::new(0)),
            }
        }

        pub async fn call(&self, key: &str) -> BuckyResult<u32> {
            let this = self.clone();
            let owned_key = key.to_owned();
            self.caller_manager
                .call(&key.to_owned(), async move {
                    println!(
                        "will exec call... key={}, next={:?}",
                        owned_key, this.next_value
                    );
                    async_std::task::sleep(std::time::Duration::from_secs(5)).await;
                    println!(
                        "end exec call... key={}, next={:?}",
                        owned_key, this.next_value
                    );

                    let v = this.next_value.fetch_add(1, Ordering::SeqCst);
                    Ok(v)
                })
                .await
        }
    }

    #[async_std::test]
    async fn test_enter_caller_once() {
        let tester = TestReneterCaller::new();
        for i in 0..10 {
            let tester = tester.clone();
            async_std::task::spawn(async move {
                let ret = tester.call("xxxx").await.unwrap();
                assert_eq!(ret, 0);
                println!("caller complete: index={}, ret={}", i, ret);
            });
        }
        async_std::task::sleep(std::time::Duration::from_secs(10)).await;
    }
    #[async_std::test]
    async fn test_enter_caller() {
        let tester = TestReneterCaller::new();
        for i in 0..100 {
            let tester = tester.clone();
            async_std::task::spawn(async move {
                async_std::task::sleep(std::time::Duration::from_secs(i)).await;
                let ret = tester.call("xxxx").await.unwrap();
                println!("caller complete: index={}, ret={}", i, ret);
            });
        }
        async_std::task::sleep(std::time::Duration::from_secs(100)).await;
    }
}