Skip to main content

aa_storage_memory/
session_store.rs

1//! In-memory [`SessionStore`] backed by a `DashMap`.
2
3use std::sync::Arc;
4
5use aa_storage::{Result, SessionId, SessionRecord, SessionStore, StorageError};
6use async_trait::async_trait;
7use dashmap::DashMap;
8
9/// A `DashMap`-backed [`SessionStore`] keyed by session id. Cloning shares the
10/// same underlying map.
11#[derive(Clone, Default)]
12pub struct MemorySessionStore {
13    sessions: Arc<DashMap<[u8; 16], SessionRecord>>,
14}
15
16impl MemorySessionStore {
17    /// Create an empty store.
18    pub fn new() -> Self {
19        Self::default()
20    }
21}
22
23#[async_trait]
24impl SessionStore for MemorySessionStore {
25    async fn save(&self, session: SessionRecord) -> Result<()> {
26        self.sessions.insert(*session.session_id.as_bytes(), session);
27        Ok(())
28    }
29
30    async fn load(&self, session_id: &SessionId) -> Result<SessionRecord> {
31        self.sessions
32            .get(session_id.as_bytes())
33            .map(|entry| entry.value().clone())
34            .ok_or_else(|| StorageError::NotFound(format!("session {:?}", session_id.as_bytes())))
35    }
36
37    async fn delete(&self, session_id: &SessionId) -> Result<()> {
38        self.sessions.remove(session_id.as_bytes());
39        Ok(())
40    }
41}