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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
use std::sync::Arc;
use std::time::Duration;

use actix::{
    dev::{MessageResponse, ResponseChannel, ToEnvelope},
    Actor, Addr, Handler, Message,
};

use crate::dev::{Expiry, ExpiryStore, Store};
use crate::error::{Result, StorageError};

type Key = Arc<[u8]>;
type Value = Arc<[u8]>;

/// Actix message for [`Store`](../trait.Store.html) requests
///
/// Every store methods are mirrored to an enum variant of the same name, and should
/// result in its corresponding variant in [`StoreResponse`](enum.StoreResponse.html).
/// [`Store`](../trait.Store.html) is automatically implemented for actors handling
/// this message.
#[derive(Debug, Message)]
#[rtype(StoreResponse)]
pub enum StoreRequest {
    Get(Key),
    Set(Key, Value),
    Delete(Key),
    Contains(Key),
}

/// Actix message reply for [`Store`](../trait.Store.html) requests
///
/// Every store methods are mirrored to an enum variant of the same name, and should
/// be a result for its corresponding variant in [`StoreResponse`](enum.StoreResponse.html)
/// Returning anything beside the requested variant, will result in panic at runtime.
pub enum StoreResponse {
    Get(Result<Option<Value>>),
    Set(Result<()>),
    Delete(Result<()>),
    Contains(Result<bool>),
}

impl<A: Actor> MessageResponse<A, StoreRequest> for StoreResponse {
    fn handle<R: ResponseChannel<StoreRequest>>(self, _: &mut A::Context, tx: Option<R>) {
        if let Some(tx) = tx {
            tx.send(self)
        }
    }
}

#[async_trait::async_trait]
impl<T> Store for Addr<T>
where
    T: Actor + Handler<StoreRequest> + Sync + Send,
    T::Context: ToEnvelope<T, StoreRequest>,
{
    async fn set(&self, key: Key, value: Value) -> Result<()> {
        match self
            .send(StoreRequest::Set(key, value))
            .await
            .map_err(StorageError::custom)?
        {
            StoreResponse::Set(val) => val,
            _ => panic!(),
        }
    }

    async fn delete(&self, key: Key) -> Result<()> {
        match self
            .send(StoreRequest::Delete(key.to_owned()))
            .await
            .map_err(StorageError::custom)?
        {
            StoreResponse::Delete(val) => val,
            _ => panic!(),
        }
    }

    async fn contains_key(&self, key: Key) -> Result<bool> {
        match self
            .send(StoreRequest::Contains(key.to_owned()))
            .await
            .map_err(StorageError::custom)?
        {
            StoreResponse::Contains(val) => val,
            _ => panic!(),
        }
    }

    async fn get(&self, key: Key) -> Result<Option<Value>> {
        match self
            .send(StoreRequest::Get(key.to_owned()))
            .await
            .map_err(StorageError::custom)?
        {
            StoreResponse::Get(val) => val,
            _ => panic!(),
        }
    }
}

/// Actix message for [`Expiry`](../trait.Expiry.html) requests
///
/// Every store methods are mirrored to an enum variant of the same name, and should
/// result in its corresponding variant in [`ExpiryResponse`](enum.ExpiryResponse.html).
/// [`Expiry`](../trait.Expiry.html) is automatically implemented for actors handling
/// this message.
#[derive(Debug, Message)]
#[rtype(ExpiryResponse)]
pub enum ExpiryRequest {
    Set(Key, Duration),
    Persist(Key),
    Get(Key),
    Extend(Key, Duration),
}

/// Actix message reply for [`Expiry`](../trait.Expiry.html) requests
///
/// Every store methods are mirrored to an enum variant of the same name, and should
/// be a result for its corresponding variant in [`ExpiryRequest`](enum.ExpiryRequest.html)
/// Returning anything beside the requested variant, will result in panic at runtime.
pub enum ExpiryResponse {
    Set(Result<()>),
    Persist(Result<()>),
    Get(Result<Option<Duration>>),
    Extend(Result<()>),
}

impl<A: Actor> MessageResponse<A, ExpiryRequest> for ExpiryResponse {
    fn handle<R: ResponseChannel<ExpiryRequest>>(self, _: &mut A::Context, tx: Option<R>) {
        if let Some(tx) = tx {
            tx.send(self)
        }
    }
}

#[async_trait::async_trait]
impl<T> Expiry for Addr<T>
where
    T: Actor + Handler<ExpiryRequest> + Sync + Send,
    T::Context: ToEnvelope<T, ExpiryRequest>,
{
    async fn expire(&self, key: Key, expire_in: Duration) -> Result<()> {
        match self
            .send(ExpiryRequest::Set(key, expire_in))
            .await
            .map_err(StorageError::custom)?
        {
            ExpiryResponse::Set(val) => val,
            _ => panic!(),
        }
    }

    async fn persist(&self, key: Key) -> Result<()> {
        match self
            .send(ExpiryRequest::Persist(key))
            .await
            .map_err(StorageError::custom)?
        {
            ExpiryResponse::Persist(val) => val,
            _ => panic!(),
        }
    }

    async fn expiry(&self, key: Key) -> Result<Option<Duration>> {
        match self
            .send(ExpiryRequest::Get(key))
            .await
            .map_err(StorageError::custom)?
        {
            ExpiryResponse::Get(val) => val,
            _ => panic!(),
        }
    }

    async fn extend(&self, key: Key, expire_in: Duration) -> Result<()> {
        match self
            .send(ExpiryRequest::Extend(key, expire_in))
            .await
            .map_err(StorageError::custom)?
        {
            ExpiryResponse::Extend(val) => val,
            _ => panic!(),
        }
    }
}

/// Actix message for [`ExpiryStore`](../trait.ExpiryStore.html) requests
///
/// Every store methods are mirrored to an enum variant of the same name, and should
/// result in its corresponding variant in [`ExpiryStoreResponse`](enum.ExpiryStoreResponse.html).
/// [`ExpiryStore`](../trait.ExpiryStore.html) is automatically implemented for actors handling
/// this message.
#[derive(Debug, Message)]
#[rtype(ExpiryStoreResponse)]
pub enum ExpiryStoreRequest {
    SetExpiring(Key, Value, Duration),
    GetExpiring(Key),
}

/// Actix message reply for [`ExpiryStore`](../trait.ExpiryStore.html) requests
///
/// Every store methods are mirrored to an enum variant of the same name, and should
/// be a result for its corresponding variant in [`ExpiryStoreResponse`](enum.ExpiryStoreResponse.html)
/// Returning anything beside the requested variant, will result in panic at runtime.
pub enum ExpiryStoreResponse {
    SetExpiring(Result<()>),
    GetExpiring(Result<Option<(Value, Option<Duration>)>>),
}

impl<A: Actor> MessageResponse<A, ExpiryStoreRequest> for ExpiryStoreResponse {
    fn handle<R: ResponseChannel<ExpiryStoreRequest>>(self, _: &mut A::Context, tx: Option<R>) {
        if let Some(tx) = tx {
            tx.send(self)
        }
    }
}

#[async_trait::async_trait]
impl<T> ExpiryStore for Addr<T>
where
    T: Actor
        + Handler<ExpiryStoreRequest>
        + Handler<ExpiryRequest>
        + Handler<StoreRequest>
        + Sync
        + Send,
    T::Context: ToEnvelope<T, ExpiryStoreRequest>
        + ToEnvelope<T, ExpiryRequest>
        + ToEnvelope<T, StoreRequest>,
{
    async fn set_expiring(&self, key: Key, value: Value, expire_in: Duration) -> Result<()> {
        match self
            .send(ExpiryStoreRequest::SetExpiring(key, value, expire_in))
            .await
            .map_err(StorageError::custom)?
        {
            ExpiryStoreResponse::SetExpiring(val) => val,
            _ => panic!(),
        }
    }

    async fn get_expiring(&self, key: Key) -> Result<Option<(Value, Option<Duration>)>> {
        match self
            .send(ExpiryStoreRequest::GetExpiring(key))
            .await
            .map_err(StorageError::custom)?
        {
            ExpiryStoreResponse::GetExpiring(val) => val,
            _ => panic!(),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;
    use crate::dev::*;
    use actix::prelude::*;

    #[derive(Default)]
    struct TestActor;

    impl Actor for TestActor {
        type Context = Context<Self>;
    }

    impl Handler<StoreRequest> for TestActor {
        type Result = StoreResponse;
        fn handle(&mut self, msg: StoreRequest, _: &mut Self::Context) -> Self::Result {
            match msg {
                StoreRequest::Get(_) => StoreResponse::Get(Ok(None)),
                StoreRequest::Set(_, _) => StoreResponse::Set(Ok(())),
                StoreRequest::Delete(_) => StoreResponse::Get(Ok(None)),
                StoreRequest::Contains(_) => StoreResponse::Contains(Ok(true)),
            }
        }
    }

    impl Handler<ExpiryRequest> for TestActor {
        type Result = ExpiryResponse;
        fn handle(&mut self, msg: ExpiryRequest, _: &mut Self::Context) -> Self::Result {
            match msg {
                ExpiryRequest::Get(_) => ExpiryResponse::Get(Ok(None)),
                ExpiryRequest::Set(_, _) => ExpiryResponse::Set(Ok(())),
                ExpiryRequest::Persist(_) => ExpiryResponse::Persist(Ok(())),
                ExpiryRequest::Extend(_, _) => ExpiryResponse::Extend(Ok(())),
            }
        }
    }

    impl Handler<ExpiryStoreRequest> for TestActor {
        type Result = ExpiryStoreResponse;
        fn handle(&mut self, msg: ExpiryStoreRequest, _: &mut Self::Context) -> Self::Result {
            match msg {
                ExpiryStoreRequest::SetExpiring(_, _, _) => {
                    ExpiryStoreResponse::SetExpiring(Ok(()))
                }
                ExpiryStoreRequest::GetExpiring(_) => ExpiryStoreResponse::GetExpiring(Ok(None)),
            }
        }
    }

    #[actix_rt::test]
    #[should_panic(expected = "explicit panic")]
    async fn test_actor() {
        let actor = TestActor::start_default();
        let key: Arc<[u8]> = "key".as_bytes().into();
        let val: Arc<[u8]> = "val".as_bytes().into();
        let dur = Duration::from_secs(1);
        assert!(actor.set(key.clone(), val.clone()).await.is_ok());
        assert!(actor.get(key.clone()).await.is_ok());
        assert!(actor.contains_key(key.clone()).await.is_ok());
        assert!(actor.expire(key.clone(), dur).await.is_ok());
        assert!(actor.expiry(key.clone()).await.is_ok());
        assert!(actor.persist(key.clone()).await.is_ok());
        assert!(actor.extend(key.clone(), dur).await.is_ok());
        assert!(actor.set_expiring(key.clone(), val, dur).await.is_ok());
        assert!(actor.get_expiring(key.clone()).await.is_ok());
        // should panic here
        actor.delete(key).await.unwrap();
    }
}