use std::path::PathBuf;
use async_trait::async_trait;
use super::{Session, SessionError, SessionId, SessionService};
use crate::events::Event;
#[derive(Debug, Clone)]
pub struct SqliteSessionConfig {
pub db_path: PathBuf,
}
impl SqliteSessionConfig {
pub fn in_memory() -> Self {
Self {
db_path: PathBuf::from(":memory:"),
}
}
}
pub struct SqliteSessionService {
config: SqliteSessionConfig,
inner: super::InMemorySessionService,
}
impl SqliteSessionService {
pub fn new(config: SqliteSessionConfig) -> Self {
Self {
config,
inner: super::InMemorySessionService::new(),
}
}
pub fn db_path(&self) -> &std::path::Path {
&self.config.db_path
}
}
#[async_trait]
impl SessionService for SqliteSessionService {
async fn create_session(&self, app_name: &str, user_id: &str) -> Result<Session, SessionError> {
self.inner.create_session(app_name, user_id).await
}
async fn get_session(&self, id: &SessionId) -> Result<Option<Session>, SessionError> {
self.inner.get_session(id).await
}
async fn list_sessions(
&self,
app_name: &str,
user_id: &str,
) -> Result<Vec<Session>, SessionError> {
self.inner.list_sessions(app_name, user_id).await
}
async fn delete_session(&self, id: &SessionId) -> Result<(), SessionError> {
self.inner.delete_session(id).await
}
async fn append_event(&self, id: &SessionId, event: Event) -> Result<(), SessionError> {
self.inner.append_event(id, event).await
}
async fn get_events(&self, id: &SessionId) -> Result<Vec<Event>, SessionError> {
self.inner.get_events(id).await
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn create_and_get() {
let svc = SqliteSessionService::new(SqliteSessionConfig::in_memory());
let session = svc.create_session("app", "user").await.unwrap();
let fetched = svc.get_session(&session.id).await.unwrap();
assert!(fetched.is_some());
}
#[test]
fn db_path() {
let svc = SqliteSessionService::new(SqliteSessionConfig {
db_path: PathBuf::from("/tmp/test.db"),
});
assert_eq!(svc.db_path(), std::path::Path::new("/tmp/test.db"));
}
#[test]
fn in_memory_config() {
let config = SqliteSessionConfig::in_memory();
assert_eq!(config.db_path, PathBuf::from(":memory:"));
}
}