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

use actix_storage::{dev::Store, Result};
use dashmap::DashMap;

type ScopeMap = DashMap<Arc<[u8]>, Arc<[u8]>>;
type InternalMap = DashMap<Arc<[u8]>, ScopeMap>;

/// A simple implementation of [`Store`](actix_storage::dev::Store) based on DashMap
///
/// This provider doesn't support key expiration thus Storage will return errors when trying to use methods
/// that require expiration functionality if there is no expiry provided.
///
/// ## Example
/// ```no_run
/// use actix_storage::Storage;
/// use actix_storage_dashmap::DashMapStore;
/// use actix_web::{App, HttpServer};
///
/// #[actix_web::main]
/// async fn main() -> std::io::Result<()> {
///     let storage = Storage::build().store(DashMapStore::new()).finish();
///     let server = HttpServer::new(move || {
///         App::new()
///             .data(storage.clone())
///     });
///     server.bind("localhost:5000")?.run().await
/// }
/// ```
#[derive(Debug, Default)]
pub struct DashMapStore {
    map: InternalMap,
}

impl DashMapStore {
    /// Make a new store, with default capacity of 0
    pub fn new() -> Self {
        Self::default()
    }

    /// Make a new store, with specified capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            map: DashMap::with_capacity(capacity),
        }
    }

    /// Make a new store from a hashmap
    pub fn from_dashmap(map: InternalMap) -> Self {
        Self { map }
    }
}

#[async_trait::async_trait]
impl Store for DashMapStore {
    async fn set(&self, scope: Arc<[u8]>, key: Arc<[u8]>, value: Arc<[u8]>) -> Result<()> {
        self.map.entry(scope).or_default().insert(key, value);
        Ok(())
    }

    async fn get(&self, scope: Arc<[u8]>, key: Arc<[u8]>) -> Result<Option<Arc<[u8]>>> {
        let value = if let Some(scope_map) = self.map.get(&scope) {
            scope_map.get(&key).map(|v| v.clone())
        } else {
            None
        };
        Ok(value)
    }

    async fn delete(&self, scope: Arc<[u8]>, key: Arc<[u8]>) -> Result<()> {
        self.map
            .get_mut(&scope)
            .and_then(|scope_map| scope_map.remove(&key));
        Ok(())
    }

    async fn contains_key(&self, scope: Arc<[u8]>, key: Arc<[u8]>) -> Result<bool> {
        Ok(self
            .map
            .get(&scope)
            .map(|scope_map| scope_map.contains_key(&key))
            .unwrap_or(false))
    }
}

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

    #[test]
    fn test_dashmap_basic_store() {
        test_store(Box::pin(async { DashMapStore::default() }));
    }

    #[test]
    fn test_dashmap_basic_formats() {
        impl Clone for DashMapStore {
            fn clone(&self) -> Self {
                Self {
                    map: self.map.clone(),
                }
            }
        }
        test_all_formats(Box::pin(async { DashMapStore::default() }));
    }
}