use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use super::wx_session::WxSession;
#[derive(Debug)]
pub struct StandardSession {
id: String,
attributes: Mutex<HashMap<String, String>>,
created: Instant,
last_access: Mutex<Instant>,
max_inactive_interval: Duration,
valid: Mutex<bool>,
}
impl StandardSession {
pub fn new(id: impl Into<String>, max_inactive_interval: Option<Duration>) -> Self {
Self {
id: id.into(),
attributes: Mutex::new(HashMap::new()),
created: Instant::now(),
last_access: Mutex::new(Instant::now()),
max_inactive_interval: max_inactive_interval.unwrap_or(Duration::from_secs(30 * 60)),
valid: Mutex::new(true),
}
}
}
impl WxSession for StandardSession {
fn id(&self) -> &str {
&self.id
}
fn get_attribute(&self, name: &str) -> Option<String> {
if !self.is_valid() {
return None;
}
self.attributes.lock().unwrap().get(name).cloned()
}
fn set_attribute(&self, name: &str, value: String) {
if !self.is_valid() {
return;
}
self.attributes
.lock()
.unwrap()
.insert(name.to_string(), value);
*self.last_access.lock().unwrap() = Instant::now();
}
fn remove_attribute(&self, name: &str) {
if !self.is_valid() {
return;
}
self.attributes.lock().unwrap().remove(name);
*self.last_access.lock().unwrap() = Instant::now();
}
fn is_valid(&self) -> bool {
let valid = *self.valid.lock().unwrap();
if !valid {
return false;
}
let last = *self.last_access.lock().unwrap();
last.elapsed() < self.max_inactive_interval
}
fn invalidate(&self) {
*self.valid.lock().unwrap() = false;
self.attributes.lock().unwrap().clear();
}
fn attribute_names(&self) -> Vec<String> {
if !self.is_valid() {
return Vec::new();
}
self.attributes.lock().unwrap().keys().cloned().collect()
}
}
impl StandardSession {
pub(crate) fn is_expired(&self) -> bool {
!self.is_valid()
}
pub(crate) fn touch_access(&self) {
*self.last_access.lock().unwrap() = Instant::now();
}
pub fn clone_session(&self) -> StandardSession {
StandardSession {
id: self.id.clone(),
attributes: Mutex::new(self.attributes.lock().unwrap().clone()),
created: self.created,
last_access: Mutex::new(*self.last_access.lock().unwrap()),
max_inactive_interval: self.max_inactive_interval,
valid: Mutex::new(*self.valid.lock().unwrap()),
}
}
}