use crate::error::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, SystemTime};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionData {
pub data: HashMap<String, String>,
pub created_at: SystemTime,
pub expires_at: SystemTime,
}
impl SessionData {
pub fn new(ttl: Duration) -> Self {
let now = SystemTime::now();
Self {
data: HashMap::new(),
created_at: now,
expires_at: now + ttl,
}
}
pub fn is_expired(&self) -> bool {
SystemTime::now() > self.expires_at
}
pub fn get(&self, key: &str) -> Option<&String> {
self.data.get(key)
}
pub fn set(&mut self, key: String, value: String) {
self.data.insert(key, value);
}
pub fn remove(&mut self, key: &str) -> Option<String> {
self.data.remove(key)
}
pub fn extend(&mut self, ttl: Duration) {
self.expires_at = SystemTime::now() + ttl;
}
}
#[async_trait]
#[allow(async_fn_in_trait)] pub trait SessionStore: Send + Sync {
async fn load(&self, session_id: &str) -> Result<Option<SessionData>>;
async fn save(&self, session_id: &str, data: SessionData) -> Result<()>;
async fn delete(&self, session_id: &str) -> Result<()>;
async fn cleanup_expired(&self) -> Result<usize>;
fn is_healthy(&self) -> bool;
}