Expand description
A session backend for managing session state.
This crate provides the ability to use custom backends for session
management by implementing the SessionStore
trait. This trait defines
the necessary operations for creating, saving, loading, and deleting session
records.
§Implementing a Custom Store
Below is an example of implementing a custom session store using an
in-memory [HashMap
]. This example is for illustration purposes only; you
can use the provided [MemoryStore
] directly without implementing it
yourself.
use std::{collections::HashMap, sync::Arc};
use async_trait::async_trait;
use time::OffsetDateTime;
use tokio::sync::Mutex;
use tower_sessions_core::{
session::{Id, Record},
session_store, SessionStore,
};
#[derive(Clone, Debug, Default)]
pub struct MemoryStore(Arc<Mutex<HashMap<Id, Record>>>);
#[async_trait]
impl SessionStore for MemoryStore {
async fn create(&self, record: &mut Record) -> session_store::Result<()> {
let mut store_guard = self.0.lock().await;
while store_guard.contains_key(&record.id) {
// Session ID collision mitigation.
record.id = Id::default();
}
store_guard.insert(record.id, record.clone());
Ok(())
}
async fn save(&self, record: &Record) -> session_store::Result<()> {
self.0.lock().await.insert(record.id, record.clone());
Ok(())
}
async fn load(&self, session_id: &Id) -> session_store::Result<Option<Record>> {
Ok(self
.0
.lock()
.await
.get(session_id)
.filter(|Record { expiry_date, .. }| is_active(*expiry_date))
.cloned())
}
async fn delete(&self, session_id: &Id) -> session_store::Result<()> {
self.0.lock().await.remove(session_id);
Ok(())
}
}
fn is_active(expiry_date: OffsetDateTime) -> bool {
expiry_date > OffsetDateTime::now_utc()
}
§Session Store Trait
The SessionStore
trait defines the interface for session management.
Implementations must handle session creation, saving, loading, and deletion.
§CachingSessionStore
The CachingSessionStore
provides a layered caching mechanism with a
cache as the frontend and a store as the backend. This can improve read
performance by reducing the need to access the backend store for frequently
accessed sessions.
§ExpiredDeletion
The ExpiredDeletion
trait provides a method for deleting expired
sessions. Implementations can optionally provide a method for continuously
deleting expired sessions at a specified interval.
Structs§
- Caching
Session Store - Provides a layered caching mechanism with a cache as the frontend and a store as the backend..
Enums§
- Error
- Stores must map any errors that might occur during their use to this type.
Traits§
- Expired
Deletion - Provides a method for deleting expired sessions.
- Session
Store - Defines the interface for session management.