use std::sync::Arc;
use rig_core::conversation::Conversation;
use rig_core::wasm_compat::{WasmBoxedFuture, WasmCompatSend, WasmCompatSync};
use rig_memory::{AsyncStore, SessionError, load_async, save_async};
#[derive(Clone)]
pub(crate) struct Memory(Arc<dyn Persist>);
trait Persist: WasmCompatSend + WasmCompatSync {
fn load<'a>(&'a self, log: &'a str) -> WasmBoxedFuture<'a, Result<Conversation, SessionError>>;
fn save<'a>(
&'a self,
log: &'a str,
conversation: &'a mut Conversation,
) -> WasmBoxedFuture<'a, Result<(), SessionError>>;
}
impl<S: AsyncStore + WasmCompatSend + WasmCompatSync> Persist for S {
fn load<'a>(&'a self, log: &'a str) -> WasmBoxedFuture<'a, Result<Conversation, SessionError>> {
Box::pin(load_async(self, log))
}
fn save<'a>(
&'a self,
log: &'a str,
conversation: &'a mut Conversation,
) -> WasmBoxedFuture<'a, Result<(), SessionError>> {
Box::pin(save_async(self, log, conversation))
}
}
impl Memory {
pub(crate) fn new(store: impl AsyncStore + WasmCompatSend + WasmCompatSync + 'static) -> Self {
Self(Arc::new(store))
}
pub(crate) async fn load(&self, log: &str) -> Result<Conversation, SessionError> {
self.0.load(log).await
}
pub(crate) async fn save(
&self,
log: &str,
conversation: &mut Conversation,
) -> Result<(), SessionError> {
self.0.save(log, conversation).await
}
}
#[cfg(test)]
mod tests;