use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use futures::future::BoxFuture;
use rig_core::message::Message;
use rig_memory::{AsyncStore, SessionError, load_async, save_async};
pub const DEFAULT_MAX_CONTEXTS: usize = 1_000;
pub const DEFAULT_HISTORY_TOKENS: usize = 32_000;
const MAX_CONTEXT_ID: usize = 128;
const SAVE_ATTEMPTS: usize = 3;
pub(crate) type HistoryError = Box<dyn std::error::Error + Send + Sync>;
pub(crate) trait HistoryStore: Send + Sync + 'static {
fn load<'a>(
&'a self,
context: &'a str,
) -> BoxFuture<'a, Result<Vec<Arc<Message>>, HistoryError>>;
fn append<'a>(
&'a self,
context: &'a str,
messages: Vec<Message>,
) -> BoxFuture<'a, Result<(), HistoryError>>;
}
pub(crate) fn valid_context_id(context: &str) -> bool {
!context.is_empty()
&& context.len() <= MAX_CONTEXT_ID
&& context
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_')
}
pub(crate) struct InMemory(Mutex<Bounded>);
struct Bounded {
by_context: HashMap<String, Vec<Arc<Message>>>,
started: VecDeque<String>,
max: usize,
}
impl InMemory {
pub(crate) fn new(max: usize) -> Self {
Self(Mutex::new(Bounded {
by_context: HashMap::new(),
started: VecDeque::new(),
max: max.max(1),
}))
}
fn lock(&self) -> MutexGuard<'_, Bounded> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl HistoryStore for InMemory {
fn load<'a>(
&'a self,
context: &'a str,
) -> BoxFuture<'a, Result<Vec<Arc<Message>>, HistoryError>> {
let messages = self
.lock()
.by_context
.get(context)
.cloned()
.unwrap_or_default();
Box::pin(async move { Ok(messages) })
}
fn append<'a>(
&'a self,
context: &'a str,
messages: Vec<Message>,
) -> BoxFuture<'a, Result<(), HistoryError>> {
let mut bounded = self.lock();
if !bounded.by_context.contains_key(context) {
bounded.started.push_back(context.to_owned());
while bounded.started.len() > bounded.max {
if let Some(oldest) = bounded.started.pop_front() {
bounded.by_context.remove(&oldest);
}
}
}
bounded
.by_context
.entry(context.to_owned())
.or_default()
.extend(messages.into_iter().map(Arc::new));
Box::pin(async { Ok(()) })
}
}
pub(crate) struct Persistent<S>(pub(crate) S);
impl<S> Persistent<S> {
fn log(context: &str) -> String {
format!("mcp-{context}")
}
}
impl<S> HistoryStore for Persistent<S>
where
S: AsyncStore + Send + Sync + 'static,
{
fn load<'a>(
&'a self,
context: &'a str,
) -> BoxFuture<'a, Result<Vec<Arc<Message>>, HistoryError>> {
Box::pin(async move {
let conversation = load_async(&self.0, &Self::log(context)).await?;
Ok(conversation.messages().to_vec())
})
}
fn append<'a>(
&'a self,
context: &'a str,
messages: Vec<Message>,
) -> BoxFuture<'a, Result<(), HistoryError>> {
Box::pin(async move {
let log = Self::log(context);
let mut attempt = 1;
loop {
let mut conversation = load_async(&self.0, &log).await?;
conversation.extend(messages.iter().cloned());
match save_async(&self.0, &log, &mut conversation).await {
Ok(()) => return Ok(()),
Err(SessionError::Changed { .. }) if attempt < SAVE_ATTEMPTS => attempt += 1,
Err(error) => return Err(error.into()),
}
}
})
}
}
#[cfg(test)]
mod tests;