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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use std::{
    borrow::Borrow,
    fmt::Debug,
    hash::Hash,
    sync::{
        atomic::{AtomicU8, Ordering},
        Arc,
    },
    task::{Poll, Waker},
};

use dashmap::DashMap;
use hala_sync::{AsyncGuardMut, AsyncLockable};

#[derive(Debug, thiserror::Error, PartialEq)]
pub enum EventMapError {
    #[error("Waiting operation canceled by user")]
    Cancel,
    #[error("Waiting operation canceled by EventMap to drop `EventMap` self")]
    Destroy,
}

/// waiter wakeup reason.
#[derive(Debug, Clone, Copy)]
pub enum Reason {
    /// Wakeup reason is unset.
    None,
    /// Waiting event on
    On,
    /// Cancel by user.
    Cancel,
    /// EventMap is dropping.
    Destroy,
}

impl From<Reason> for u8 {
    fn from(value: Reason) -> Self {
        match value {
            Reason::None => 0,
            Reason::On => 1,
            Reason::Cancel => 2,
            Reason::Destroy => 3,
        }
    }
}

#[derive(Debug)]
struct WakerWithReason {
    waker: Waker,
    reason: Arc<AtomicU8>,
}

impl WakerWithReason {
    fn wake(self, reason: Reason) {
        self.reason.store(reason.into(), Ordering::Release);
        self.waker.wake();
    }

    fn wake_by_ref(&self, reason: Reason) {
        self.reason.store(reason.into(), Ordering::Release);
        self.waker.wake_by_ref();
    }
}

/// The mediator of event notify for futures-aware enviroment.
#[derive(Debug)]
pub struct EventMap<E>
where
    E: Send + Eq + Hash,
{
    wakers: DashMap<E, WakerWithReason>,
}

impl<E> Drop for EventMap<E>
where
    E: Send + Eq + Hash,
{
    fn drop(&mut self) {
        for entry in self.wakers.iter() {
            entry.value().wake_by_ref(Reason::Destroy);
        }
    }
}

impl<E> Default for EventMap<E>
where
    E: Send + Eq + Hash,
{
    fn default() -> Self {
        Self {
            wakers: DashMap::new(),
        }
    }
}

impl<E> EventMap<E>
where
    E: Send + Eq + Hash + Debug + Clone,
{
    /// Only remove event waker, without wakeup it.
    pub fn wait_cancel<Q>(&self, event: Q)
    where
        Q: Borrow<E>,
    {
        self.wakers.remove(event.borrow());
    }

    /// Notify one event `E` on.
    #[inline(always)]
    pub fn notify_one<Q>(&self, event: Q, reason: Reason) -> bool
    where
        Q: Borrow<E>,
    {
        if let Some((_, waker)) = self.wakers.remove(event.borrow()) {
            log::trace!("{:?} wakeup", event.borrow());
            waker.wake(reason);
            true
        } else {
            log::trace!("{:?} wakeup -- not found", event.borrow());
            false
        }
    }

    /// Notify all event on in the providing `events` list
    #[inline(always)]
    pub fn notify_all<L: AsRef<[E]>>(&self, events: L, reason: Reason) {
        for event in events.as_ref() {
            self.notify_one(event, reason);
        }
    }

    /// Notify all event on in the providing `events` list
    #[inline(always)]
    pub fn notify_any(&self, reason: Reason) {
        let events = self
            .wakers
            .iter()
            .map(|pair| pair.key().clone())
            .collect::<Vec<_>>();

        self.notify_all(&events, reason);
    }

    #[inline(always)]
    pub fn wait<'a, Q, G>(&'a self, event: Q, guard: G) -> Wait<'a, E, G>
    where
        G: AsyncGuardMut<'a> + 'a,
        Q: Borrow<E>,
    {
        Wait {
            event: event.borrow().clone(),
            guard: Some(guard),
            event_map: self,
            reason: Arc::new(AtomicU8::new(Reason::None.into())),
        }
    }
}

pub struct Wait<'a, E, G>
where
    E: Send + Eq + Hash,
    G: AsyncGuardMut<'a> + 'a,
{
    event: E,
    guard: Option<G>,
    event_map: &'a EventMap<E>,
    reason: Arc<AtomicU8>,
}

impl<'a, E, G> std::future::Future for Wait<'a, E, G>
where
    E: Send + Eq + Hash + Clone + Unpin + Debug,
    G: AsyncGuardMut<'a> + Unpin + 'a,
{
    type Output = Result<(), EventMapError>;

    #[inline(always)]
    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        if let Some(guard) = self.guard.take() {
            // insert waker into waiting map.
            self.event_map.wakers.insert(
                self.event.clone(),
                WakerWithReason {
                    waker: cx.waker().clone(),
                    reason: self.reason.clone(),
                },
            );

            G::Locker::unlock(guard);
        }

        // Check reason to avoid unexpected `poll` calling.
        // For example, calling `wait` function in `futures::select!` block

        let reason = self.reason.load(Ordering::SeqCst);

        if reason == Reason::None.into() {
            return Poll::Pending;
        } else if reason == Reason::Cancel.into() {
            return Poll::Ready(Err(EventMapError::Cancel));
        } else if reason == Reason::Destroy.into() {
            return Poll::Ready(Err(EventMapError::Destroy));
        } else {
            return Poll::Ready(Ok(()));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use futures::{executor::ThreadPool, task::SpawnExt};
    use hala_sync::AsyncSpinMutex;

    #[futures_test::test]
    async fn test_across_suspend_point() {
        let local_pool = ThreadPool::builder().pool_size(10).create().unwrap();

        let mediator = Arc::new(EventMap::<i32>::default());

        let shared = Arc::new(AsyncSpinMutex::new(1));

        let mediator_cloned = mediator.clone();

        let handle = local_pool
            .spawn_with_handle(async move {
                let shared = shared.lock().await;

                mediator_cloned.wait(1, shared).await.unwrap();
            })
            .unwrap();

        while !mediator.notify_one(1, Reason::On) {}

        handle.await;
    }
}