use larust_core::AppError;
use larust_http::session::Session;
use serde::{Deserialize, Serialize};
const SESSION_KEY: &str = "__wire_components";
const MAX_COMPONENTS_PER_SESSION: usize = 50;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct StoredComponent {
pub(crate) name: String,
pub(crate) state: serde_json::Value,
}
pub(crate) async fn load_components(
session: &Session,
) -> Result<Vec<(String, StoredComponent)>, AppError> {
session
.get::<Vec<(String, StoredComponent)>>(SESSION_KEY)
.await
.map_err(|source| AppError::Internal(Box::new(source)))
.map(Option::unwrap_or_default)
}
pub(crate) async fn save_components(
session: &Session,
components: &[(String, StoredComponent)],
) -> Result<(), AppError> {
session
.insert(SESSION_KEY, components)
.await
.map_err(|source| AppError::Internal(Box::new(source)))
}
pub(crate) fn evict_oldest_if_over_cap(components: &mut Vec<(String, StoredComponent)>) {
while components.len() > MAX_COMPONENTS_PER_SESSION {
components.remove(0);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn dummy(name: &str) -> (String, StoredComponent) {
(
name.to_string(),
StoredComponent {
name: "test-component".to_string(),
state: serde_json::Value::Null,
},
)
}
#[test]
fn eviction_is_a_no_op_under_the_cap() {
let mut components: Vec<_> = (0..MAX_COMPONENTS_PER_SESSION)
.map(|i| dummy(&i.to_string()))
.collect();
evict_oldest_if_over_cap(&mut components);
assert_eq!(components.len(), MAX_COMPONENTS_PER_SESSION);
}
#[test]
fn eviction_drops_oldest_entries_first_when_over_the_cap() {
let mut components: Vec<_> = (0..MAX_COMPONENTS_PER_SESSION + 3)
.map(|i| dummy(&i.to_string()))
.collect();
evict_oldest_if_over_cap(&mut components);
assert_eq!(components.len(), MAX_COMPONENTS_PER_SESSION);
assert_eq!(components.first().unwrap().0, "3");
assert_eq!(
components.last().unwrap().0,
(MAX_COMPONENTS_PER_SESSION + 2).to_string()
);
}
}