Skip to main content

krabka_client_streams/store/
backend.rs

1//! Which storage engine backs the state stores.
2//!
3//! `InMemory` is the test default and is also a valid production option. `Turso`
4//! persists the state under a state directory, and it is a native database
5//! engine, so the variant exists only on native targets.
6use crate::store::byte::{ByteKeyValueStore, InMemoryBytes};
7
8#[derive(Clone, Debug, Default)]
9pub enum StoreBackend {
10    #[default]
11    InMemory,
12    #[cfg(not(target_family = "wasm"))]
13    Turso { state_dir: std::path::PathBuf },
14}
15
16impl StoreBackend {
17    /// Open a byte backend for one store. `app_id` and `store` form the Turso
18    /// file path.
19    #[tracing::instrument(
20        name = "streams.store.backend_open",
21        level = "info",
22        skip_all,
23        fields(app_id = %app_id, store = %store),
24    )]
25    pub(crate) async fn open(&self, app_id: &str, store: &str) -> Box<dyn ByteKeyValueStore> {
26        match self {
27            Self::InMemory => Box::new(InMemoryBytes::default()),
28            #[cfg(not(target_family = "wasm"))]
29            Self::Turso { state_dir } => {
30                let dir = state_dir.join(app_id);
31                std::fs::create_dir_all(&dir).expect("create state dir");
32                let path = dir.join(format!("{store}.db"));
33                Box::new(
34                    crate::store::turso::TursoBytes::open(path.to_str().expect("utf8 path")).await,
35                )
36            }
37        }
38    }
39}