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
use std::sync::Arc;
use std::time::Duration;

use super::{Expiry, Store};
use crate::error::Result;

/// It is usefull for when store and expiry are implemented for the same struct,
/// and should be implemented in those cases even if there can't be any optimization,
/// as it will prevent some runtime checks for expiry validity.
#[async_trait::async_trait]
pub trait ExpiryStore: Store + Expiry + Send + Sync {
    /// Set a key-value for a duration of time, if the key already exists, it should overwrite
    /// both the value and the expiry for that key.
    async fn set_expiring(
        &self,
        key: Arc<[u8]>,
        value: Arc<[u8]>,
        expire_in: Duration,
    ) -> Result<()> {
        self.set(key.clone(), value).await?;
        self.expire(key, expire_in).await
    }

    /// Get the value and expiry for a key, it is possible to return None if the key doesn't exist,
    /// or return None for the expiry if the key is persistent.
    async fn get_expiring(&self, key: Arc<[u8]>) -> Result<Option<(Arc<[u8]>, Option<Duration>)>> {
        let val = self.get(key.clone()).await?;
        match val {
            Some(val) => {
                let expiry = self.expiry(key).await?;
                Ok(Some((val, expiry)))
            }
            None => Ok(None),
        }
    }
}