use serde::{Deserialize, Serialize};
use crate::core::event::Event;
use crate::core::state::State;
pub type SessionId = String;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Session {
pub id: SessionId,
pub app_name: String,
pub user_id: String,
#[serde(default)]
pub state: State,
#[serde(default)]
pub events: Vec<Event>,
#[serde(default)]
pub last_update_time: f64,
}
impl Session {
pub fn new(
app_name: impl Into<String>,
user_id: impl Into<String>,
id: impl Into<String>,
) -> Self {
Self {
id: id.into(),
app_name: app_name.into(),
user_id: user_id.into(),
state: State::default(),
events: Vec::new(),
last_update_time: now_secs(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SessionMeta {
pub id: SessionId,
pub app_name: String,
pub user_id: String,
pub last_update_time: f64,
}
pub fn now_secs() -> f64 {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
let secs = now.as_secs() as f64;
let nanos = f64::from(now.subsec_nanos()) / 1_000_000_000.0;
secs + nanos
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn session_round_trips() {
let s = Session::new("a", "u", "sess");
let j = serde_json::to_value(&s).unwrap();
let back: Session = serde_json::from_value(j).unwrap();
assert_eq!(s, back);
}
}