use std::sync::Arc;
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::{Map, Value};
use crate::error::SessionError;
use crate::event::Event;
pub const KEY_PREFIX_APP: &str = "app:";
pub const KEY_PREFIX_TEMP: &str = "temp:";
pub const KEY_PREFIX_USER: &str = "user:";
#[async_trait]
pub trait SessionService: Send + Sync {
async fn create(&self, req: CreateRequest) -> Result<Arc<dyn Session>, SessionError>;
async fn get(&self, req: GetRequest) -> Result<Arc<dyn Session>, SessionError>;
async fn list(&self, req: ListRequest) -> Result<Vec<Arc<dyn Session>>, SessionError>;
async fn delete(&self, req: DeleteRequest) -> Result<(), SessionError>;
async fn append_event(
&self,
session: &dyn Session,
event: &mut Event,
) -> Result<(), SessionError>;
}
pub trait Session: Send + Sync {
fn id(&self) -> &str;
fn app_name(&self) -> &str;
fn user_id(&self) -> &str;
fn state(&self) -> &dyn State;
fn events(&self) -> Vec<Event>;
fn last_update_time(&self) -> DateTime<Utc>;
fn as_any(&self) -> &dyn std::any::Any;
}
pub fn compare_by_last_update(a: &dyn Session, b: &dyn Session) -> std::cmp::Ordering {
a.last_update_time()
.cmp(&b.last_update_time())
.then_with(|| a.user_id().cmp(b.user_id()))
.then_with(|| a.id().cmp(b.id()))
}
pub trait State: Send + Sync {
fn get(&self, key: &str) -> Result<Value, SessionError>;
fn set(&self, key: &str, value: Value) -> Result<(), SessionError>;
fn all(&self) -> Vec<(String, Value)>;
}
pub trait ReadonlyState: Send + Sync {
fn get(&self, key: &str) -> Result<Value, SessionError>;
fn all(&self) -> Vec<(String, Value)>;
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct CreateRequest {
pub app_name: String,
pub user_id: String,
pub session_id: Option<String>,
pub state: Option<Map<String, Value>>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GetRequest {
pub app_name: String,
pub user_id: String,
pub session_id: String,
pub num_recent_events: usize,
pub after: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ListRequest {
pub app_name: String,
pub user_id: String,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct DeleteRequest {
pub app_name: String,
pub user_id: String,
pub session_id: String,
}