1use crate::error::KitError;
2use std::fmt;
3#[cfg(feature = "sqlite")]
4use std::path::PathBuf;
5use std::sync::Arc;
6use troupekit_core::store::{CheckpointStore, UsageLedger};
7
8pub(crate) type Opened = (
9 Option<Arc<dyn CheckpointStore>>,
10 Option<Arc<dyn UsageLedger>>,
11);
12
13#[derive(Clone)]
17pub struct Storage(Kind);
18
19#[derive(Clone)]
20enum Kind {
21 Memory,
22 #[cfg(feature = "sqlite")]
23 Sqlite(PathBuf),
24 Custom(Arc<dyn CheckpointStore>),
25}
26
27impl Storage {
28 #[cfg(feature = "knowledge")]
29 pub(crate) fn sqlite_path(&self) -> Option<&std::path::Path> {
30 match &self.0 {
31 Kind::Sqlite(path) => Some(path),
32 _ => None,
33 }
34 }
35
36 pub fn memory() -> Self {
40 Storage(Kind::Memory)
41 }
42
43 #[cfg(feature = "sqlite")]
47 pub fn sqlite(path: impl Into<PathBuf>) -> Self {
48 Storage(Kind::Sqlite(path.into()))
49 }
50
51 pub fn custom(store: Arc<dyn CheckpointStore>) -> Self {
55 Storage(Kind::Custom(store))
56 }
57
58 pub(crate) async fn open(&self) -> Result<Opened, KitError> {
62 match &self.0 {
63 Kind::Memory => Ok((None, None)),
64 #[cfg(feature = "sqlite")]
65 Kind::Sqlite(path) => {
66 let store = Arc::new(troupekit_store_sqlite::SqliteStore::open(path).await?);
67 Ok((Some(store.clone()), Some(store)))
68 }
69 Kind::Custom(store) => Ok((Some(store.clone()), None)),
70 }
71 }
72}
73
74impl Default for Storage {
75 fn default() -> Self {
76 Storage::memory()
77 }
78}
79
80impl fmt::Debug for Storage {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 match &self.0 {
83 Kind::Memory => f.write_str("Storage::memory()"),
84 #[cfg(feature = "sqlite")]
85 Kind::Sqlite(path) => write!(f, "Storage::sqlite({path:?})"),
86 Kind::Custom(_) => f.write_str("Storage::custom(..)"),
87 }
88 }
89}