use crate::error::KitError;
use std::fmt;
#[cfg(feature = "sqlite")]
use std::path::PathBuf;
use std::sync::Arc;
use troupekit_core::store::{CheckpointStore, UsageLedger};
pub(crate) type Opened = (
Option<Arc<dyn CheckpointStore>>,
Option<Arc<dyn UsageLedger>>,
);
#[derive(Clone)]
pub struct Storage(Kind);
#[derive(Clone)]
enum Kind {
Memory,
#[cfg(feature = "sqlite")]
Sqlite(PathBuf),
Custom(Arc<dyn CheckpointStore>),
}
impl Storage {
#[cfg(feature = "knowledge")]
pub(crate) fn sqlite_path(&self) -> Option<&std::path::Path> {
match &self.0 {
Kind::Sqlite(path) => Some(path),
_ => None,
}
}
pub fn memory() -> Self {
Storage(Kind::Memory)
}
#[cfg(feature = "sqlite")]
pub fn sqlite(path: impl Into<PathBuf>) -> Self {
Storage(Kind::Sqlite(path.into()))
}
pub fn custom(store: Arc<dyn CheckpointStore>) -> Self {
Storage(Kind::Custom(store))
}
pub(crate) async fn open(&self) -> Result<Opened, KitError> {
match &self.0 {
Kind::Memory => Ok((None, None)),
#[cfg(feature = "sqlite")]
Kind::Sqlite(path) => {
let store = Arc::new(troupekit_store_sqlite::SqliteStore::open(path).await?);
Ok((Some(store.clone()), Some(store)))
}
Kind::Custom(store) => Ok((Some(store.clone()), None)),
}
}
}
impl Default for Storage {
fn default() -> Self {
Storage::memory()
}
}
impl fmt::Debug for Storage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
Kind::Memory => f.write_str("Storage::memory()"),
#[cfg(feature = "sqlite")]
Kind::Sqlite(path) => write!(f, "Storage::sqlite({path:?})"),
Kind::Custom(_) => f.write_str("Storage::custom(..)"),
}
}
}