Skip to main content

serenade_session/
memory.rs

1//! In-memory [`SessionStore`](crate::SessionStore).
2
3use std::collections::HashMap;
4use std::sync::{Mutex, MutexGuard};
5
6use crate::{SessionError, SessionStore};
7
8/// Process-local session store (tests and single-node dev).
9#[derive(Default)]
10pub struct MemorySessionStore {
11    inner: Mutex<HashMap<String, HashMap<String, String>>>,
12}
13
14impl MemorySessionStore {
15    /// Creates an empty store.
16    #[must_use]
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    fn lock(&self) -> MutexGuard<'_, HashMap<String, HashMap<String, String>>> {
22        self.inner
23            .lock()
24            .expect("serenade-session MemorySessionStore mutex poisoned")
25    }
26}
27
28impl SessionStore for MemorySessionStore {
29    fn load(&self, id: &str) -> Result<Option<HashMap<String, String>>, SessionError> {
30        validate_id(id)?;
31        Ok(self.lock().get(id).cloned())
32    }
33
34    fn save(&self, id: &str, attributes: &HashMap<String, String>) -> Result<(), SessionError> {
35        validate_id(id)?;
36        self.lock().insert(id.to_owned(), attributes.clone());
37        Ok(())
38    }
39
40    fn delete(&self, id: &str) -> Result<(), SessionError> {
41        validate_id(id)?;
42        self.lock().remove(id);
43        Ok(())
44    }
45}
46
47fn validate_id(id: &str) -> Result<(), SessionError> {
48    if id.is_empty() {
49        return Err(SessionError::InvalidId {
50            message: "id must not be empty".to_owned(),
51        });
52    }
53    Ok(())
54}