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
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc};
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::{Context, Poll, Waker};
use parking_lot::Mutex;
use crate::cache::command::{CommandStatus, RejectionReason};

/// The execution of every write operation is returned a `CommandAcknowledgement` wrapped inside [`crate::cache::command::command_executor::CommandSendResult`].
/// `CommandAcknowledgement` provides a handle to the clients to perform `.await` to get the command status.
///
/// ```
/// use tinylfu_cached::cache::cached::CacheD;
/// use tinylfu_cached::cache::command::CommandStatus;
/// use tinylfu_cached::cache::config::ConfigBuilder;
/// #[tokio::main]
///  async fn main() {
///     let cached = CacheD::new(ConfigBuilder::new(100, 10, 100).build());
///     let status = cached.put("topic", "microservices").unwrap().handle().await;
///     assert_eq!(CommandStatus::Accepted, status);
///     let value = cached.get(&"topic");
///     assert_eq!(Some("microservices"), value);
/// }
/// ```
pub struct CommandAcknowledgement {
    handle: CommandAcknowledgementHandle,
}

/// CommandAcknowledgementHandle implements [`std::future::Future`] and returns a [`crate::cache::command::CommandStatus`]
///
/// The initial status in the `CommandAcknowledgementHandle` is `CommandStatus::Pending`
///
/// The status gets updated when the command is executed by the `crate::cache::command::command_executor::CommandExecutor`.
pub struct CommandAcknowledgementHandle {
    done: AtomicBool,
    status: Arc<Mutex<CommandStatus>>,
    waker_state: Arc<Mutex<WakerState>>,
}

pub(crate) struct WakerState {
    waker: Option<Waker>,
}

/// CommandAcknowledgement provides a `handle()` method  that returns a reference to the `CommandAcknowledgementHandle`
impl CommandAcknowledgement {
    pub(crate) fn new() -> Arc<CommandAcknowledgement> {
        Arc::new(
            CommandAcknowledgement {
                handle: CommandAcknowledgementHandle {
                    done: AtomicBool::new(false),
                    status: Arc::new(Mutex::new(CommandStatus::Pending)),
                    waker_state: Arc::new(Mutex::new(WakerState {
                        waker: None
                    })),
                },
            }
        )
    }
    pub(crate) fn accepted() -> Arc<CommandAcknowledgement> {
        Arc::new(
            CommandAcknowledgement {
                handle: CommandAcknowledgementHandle {
                    done: AtomicBool::new(true),
                    status: Arc::new(Mutex::new(CommandStatus::Accepted)),
                    waker_state: Arc::new(Mutex::new(WakerState {
                        waker: None
                    })),
                },
            }
        )
    }
    pub(crate) fn rejected(reason: RejectionReason) -> Arc<CommandAcknowledgement> {
        Arc::new(
            CommandAcknowledgement {
                handle: CommandAcknowledgementHandle {
                    done: AtomicBool::new(true),
                    status: Arc::new(Mutex::new(CommandStatus::Rejected(reason))),
                    waker_state: Arc::new(Mutex::new(WakerState {
                        waker: None
                    })),
                },
            }
        )
    }

    /// Invokes the `done()` method of `CommandAcknowledgementHandle` which changes the `CommandStatus`
    pub(crate) fn done(&self, status: CommandStatus) {
        self.handle.done(status);
    }

    pub fn handle(&self) -> &CommandAcknowledgementHandle {
        &self.handle
    }
}

impl CommandAcknowledgementHandle {
    /// Marks the flag to indicate that the command execution is done and changes the `CommandStatus`
    pub(crate) fn done(&self, status: CommandStatus) {
        self.done.store(true, Ordering::Release);
        *self.status.lock() = status;
        if let Some(waker) = &self.waker_state.lock().waker {
            waker.wake_by_ref();
        }
    }
}

/// Future implementation for CommandAcknowledgementHandle.
/// The future is complete when the the command is executed by the `crate::cache::command::command_executor::CommandExecutor`.
/// The completion of future returns [`CommandStatus`].
impl Future for &CommandAcknowledgementHandle {
    type Output = CommandStatus;

    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        let mut guard = self.waker_state.lock();
        match guard.waker.as_ref() {
            Some(waker) => {
                if !waker.will_wake(context.waker()) {
                    guard.waker = Some(context.waker().clone());
                }
            }
            None => {
                guard.waker = Some(context.waker().clone());
            }
        }
        if self.done.load(Ordering::Acquire) {
            return Poll::Ready(*self.status.lock());
        }
        Poll::Pending
    }
}

#[cfg(test)]
mod tests {
    use crate::cache::command::acknowledgement::CommandAcknowledgement;
    use crate::cache::command::{CommandStatus, RejectionReason};

    #[tokio::test]
    async fn acknowledge() {
        let acknowledgement = CommandAcknowledgement::new();
        tokio::spawn({
            let acknowledgement = acknowledgement.clone();
            async move {
                acknowledgement.done(CommandStatus::Accepted);
            }
        });

        let response = acknowledgement.handle().await;
        assert_eq!(CommandStatus::Accepted, response);
    }

    #[tokio::test]
    async fn accepted() {
        let acknowledgement = CommandAcknowledgement::accepted();
        let response = acknowledgement.handle().await;
        assert_eq!(CommandStatus::Accepted, response);
    }

    #[tokio::test]
    async fn rejected() {
        let acknowledgement = CommandAcknowledgement::rejected(RejectionReason::KeyAlreadyExists);
        let response = acknowledgement.handle().await;
        assert_eq!(CommandStatus::Rejected(RejectionReason::KeyAlreadyExists), response);
    }
}