use crate::error::ContextError;
use std::sync::Arc;
use troupekit_core::error::CoreError;
use troupekit_core::store::BlobStore;
const SUMMARY_PREFIX: &str = "summary/";
pub struct SessionSummary {
blobs: Arc<dyn BlobStore>,
}
impl SessionSummary {
pub fn new(blobs: Arc<dyn BlobStore>) -> Self {
Self { blobs }
}
pub async fn set(&self, session: &str, text: &str) -> Result<(), ContextError> {
let path = path_of(session)?;
self.blobs.put(&path, text.as_bytes().to_vec()).await?;
Ok(())
}
pub async fn get(&self, session: &str) -> Result<Option<String>, ContextError> {
let path = path_of(session)?;
match self.blobs.get(&path).await {
Ok(bytes) => {
let text = String::from_utf8(bytes).map_err(|_| CoreError::Store(format!("corrupt summary at {path}")))?;
Ok(Some(text))
}
Err(CoreError::NotFound(_)) => Ok(None),
Err(e) => Err(e.into()),
}
}
}
fn path_of(session: &str) -> Result<String, ContextError> {
if session.trim().is_empty() {
return Err(ContextError::Invalid("session must not be empty".into()));
}
Ok(format!("{SUMMARY_PREFIX}{session}"))
}
#[cfg(test)]
mod tests {
use super::*;
use troupekit_core::inmem::InMemBlobs;
#[tokio::test]
async fn set_replaces_and_get_reads_back() {
let s = SessionSummary::new(Arc::new(InMemBlobs::default()));
assert_eq!(s.get("s1").await.unwrap(), None);
s.set("s1", "first").await.unwrap();
s.set("s1", "second").await.unwrap();
assert_eq!(s.get("s1").await.unwrap().as_deref(), Some("second"));
assert_eq!(s.get("s2").await.unwrap(), None);
assert!(matches!(s.set(" ", "x").await, Err(ContextError::Invalid(_))));
}
}