Skip to main content

troupekit_kit/
storage.rs

1use crate::error::KitError;
2use std::fmt;
3#[cfg(feature = "sqlite")]
4use std::path::PathBuf;
5use std::sync::Arc;
6use troupekit_core::store::CheckpointStore;
7
8/// Where an agent or graph keeps run checkpoints.
9/// `memory()` (the default) uses a fresh in-memory store per run, so
10/// nothing grows; `sqlite(path)` and `custom(store)` keep runs for `resume`.
11#[derive(Clone)]
12pub struct Storage(Kind);
13
14#[derive(Clone)]
15enum Kind {
16    Memory,
17    #[cfg(feature = "sqlite")]
18    Sqlite(PathBuf),
19    Custom(Arc<dyn CheckpointStore>),
20}
21
22impl Storage {
23    #[cfg(feature = "knowledge")]
24    pub(crate) fn sqlite_path(&self) -> Option<&std::path::Path> {
25        match &self.0 {
26            Kind::Sqlite(path) => Some(path),
27            _ => None,
28        }
29    }
30
31    /// Keeps each run's checkpoints in memory, dropped when the run ends.
32    /// Runs cannot be resumed. This is the default.
33    /// Costs nothing at `build`.
34    pub fn memory() -> Self {
35        Storage(Kind::Memory)
36    }
37
38    /// Keeps checkpoints in the SQLite file at `path`, opened at `build`.
39    /// Enables `resume(run_id)`, also from a later process.
40    /// Needs the `sqlite` feature, on by default.
41    #[cfg(feature = "sqlite")]
42    pub fn sqlite(path: impl Into<PathBuf>) -> Self {
43        Storage(Kind::Sqlite(path.into()))
44    }
45
46    /// Keeps checkpoints in `store`, shared by every run.
47    /// Enables `resume(run_id)`.
48    /// Use it for a store the host already opened.
49    pub fn custom(store: Arc<dyn CheckpointStore>) -> Self {
50        Storage(Kind::Custom(store))
51    }
52
53    pub(crate) async fn open(&self) -> Result<Option<Arc<dyn CheckpointStore>>, KitError> {
54        match &self.0 {
55            Kind::Memory => Ok(None),
56            #[cfg(feature = "sqlite")]
57            Kind::Sqlite(path) => {
58                let store = troupekit_store_sqlite::SqliteStore::open(path).await?;
59                Ok(Some(Arc::new(store)))
60            }
61            Kind::Custom(store) => Ok(Some(store.clone())),
62        }
63    }
64}
65
66impl Default for Storage {
67    fn default() -> Self {
68        Storage::memory()
69    }
70}
71
72impl fmt::Debug for Storage {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        match &self.0 {
75            Kind::Memory => f.write_str("Storage::memory()"),
76            #[cfg(feature = "sqlite")]
77            Kind::Sqlite(path) => write!(f, "Storage::sqlite({path:?})"),
78            Kind::Custom(_) => f.write_str("Storage::custom(..)"),
79        }
80    }
81}