use std::convert::Infallible;
use async_trait::async_trait;
use moka::future::Cache;
use crate::{
session::{SessionId, SessionRecord},
Session, SessionStore,
};
#[derive(Debug, Clone)]
pub struct MokaStore {
cache: Cache<SessionId, SessionRecord>,
}
impl MokaStore {
pub fn new(max_capacity: Option<u64>) -> Self {
let cache_builder = match max_capacity {
Some(capacity) => Cache::builder().max_capacity(capacity),
None => Cache::builder(),
};
Self {
cache: cache_builder.build(),
}
}
}
#[async_trait]
impl SessionStore for MokaStore {
type Error = Infallible;
async fn save(&self, session_record: &SessionRecord) -> Result<(), Self::Error> {
self.cache
.insert(session_record.id(), session_record.clone())
.await;
Ok(())
}
async fn load(&self, session_id: &SessionId) -> Result<Option<Session>, Self::Error> {
Ok(self.cache.get(session_id).await.map(Into::into))
}
async fn delete(&self, session_id: &SessionId) -> Result<(), Self::Error> {
self.cache.invalidate(session_id).await;
Ok(())
}
}