The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(storage): add storage module with tests
Steven Enamakele02c46b3e086
diff --git a/crates/openhuman-core/src/storage/mod.rs b/crates/openhuman-core/src/storage/mod.rsnew file mode 100644index 0000000000..917092faca--- /dev/null+++ b/crates/openhuman-core/src/storage/mod.rs@@ -0,0 +1,102 @@+//! The process's storage backend on the `tinystoragedrivers` ports.+//!+//! One URL picks where durable state that has moved onto the storage ports+//! lives: `OPENHUMAN_STORAGE_URL`, else `[storage] url` in `config.toml`+//! ([`crate::config::StorageConfig`]). With neither set — the desktop default —+//! nothing here is opened and every domain keeps the classic on-disk layout+//! under the workspace.+//!+//! When a URL is set, the host opens it once at startup ([`open`]) and+//! installs it ([`install`]); domains reach it through [`installed`] and bind+//! their records to an agent with [`scope_for_agent`]. The first consumer is+//! the session store: the host installs TinyAgents' `DriverSessionStores`+//! over this backend, so transcripts, turn states, records and journals live+//! in it, one scope per agent.+//!+//! Drivers are Cargo features of this crate: `storage-sqlite`,+//! `storage-mongodb`, `storage-file` (memory is always available). A URL for a+//! driver the build does not carry fails at [`open`] naming the feature, so a+//! misconfigured deployment stops at boot instead of at its first write.++use std::sync::{Arc, LazyLock, RwLock};++pub use tinystoragedrivers::{+ Scope, ScopedStorage, StorageBackend, StorageConfig as StorageUrl, StorageError,+};++use crate::config::Config;+use crate::config::schema::storage::redact_url;++/// The environment variable that overrides `[storage] url`.+pub const STORAGE_URL_VAR: &str = "OPENHUMAN_STORAGE_URL";++static BACKEND: LazyLock<RwLock<Option<Arc<dyn StorageBackend>>>> =+ LazyLock::new(|| RwLock::new(None));++/// The storage URL in effect: [`STORAGE_URL_VAR`], else `config`'s+/// `[storage] url`. Blank values count as unset. `None` keeps the classic+/// on-disk layout.+pub fn configured_url(config: &Config) -> Option<String> {+ url_from(std::env::var(STORAGE_URL_VAR).ok(), config)+}++/// [`configured_url`] with the environment read made explicit, so the rule+/// is testable without mutating process-wide state.+pub fn url_from(env: Option<String>, config: &Config) -> Option<String> {+ env.into_iter()+ .chain(config.storage.url.clone())+ .map(|url| url.trim().to_string())+ .find(|url| !url.is_empty())+}++/// Parses and opens the backend `url` names.+///+/// # Errors+///+/// An unparseable URL, a driver this build was compiled without (the error+/// names the Cargo feature), or a backend that cannot be reached.+pub async fn open(url: &str) -> Result<Arc<dyn StorageBackend>, StorageError> {+ let parsed = StorageUrl::parse(url)?;+ tracing::info!(+ target: "openhuman::storage",+ driver = parsed.driver(),+ url = %redact_url(url),+ "[storage] opening the configured backend"+ );+ tinystoragedrivers::open(&parsed).await+}++/// Makes `backend` the process's storage backend; returns the previous one.+pub fn install(backend: Arc<dyn StorageBackend>) -> Option<Arc<dyn StorageBackend>> {+ let mut slot = BACKEND+ .write()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ slot.replace(backend)+}++/// The installed backend, when the host configured one.+pub fn installed() -> Option<Arc<dyn StorageBackend>> {+ BACKEND+ .read()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .clone()+}++/// Removes the installed backend; returns whether there was one.+pub fn clear() -> bool {+ BACKEND+ .write()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .take()+ .is_some()+}++/// The storage scope agent `agent_id`'s records live under — the same+/// mapping the session store uses, so every domain agrees on it.+pub fn scope_for_agent(agent_id: &str) -> Scope {+ tinyagents_session::DriverSessionStores::scope_for(agent_id)+}++#[cfg(test)]+#[path = "mod_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/storage/mod_tests.rs b/crates/openhuman-core/src/storage/mod_tests.rsnew file mode 100644index 0000000000..445070154d--- /dev/null+++ b/crates/openhuman-core/src/storage/mod_tests.rs@@ -0,0 +1,57 @@+use super::*;++fn config_with(url: Option<&str>) -> Config {+ let mut config = Config::default();+ config.storage.url = url.map(str::to_string);+ config+}++#[test]+fn the_environment_wins_over_the_config_file() {+ let config = config_with(Some("sqlite:/from/config"));+ assert_eq!(+ url_from(Some("memory".into()), &config).as_deref(),+ Some("memory")+ );+ assert_eq!(+ url_from(None, &config).as_deref(),+ Some("sqlite:/from/config")+ );+}++#[test]+fn blank_values_keep_the_classic_layout() {+ assert_eq!(url_from(None, &config_with(None)), None);+ assert_eq!(url_from(Some(" ".into()), &config_with(Some(""))), None);+ assert_eq!(+ url_from(Some(" ".into()), &config_with(Some(" memory "))).as_deref(),+ Some("memory"),+ "a blank override falls through to the file"+ );+}++#[tokio::test]+async fn opens_memory_and_refuses_garbage() {+ let backend = open("memory").await.unwrap();+ assert_eq!(backend.driver(), "memory");+ assert!(open("ftp://nope").await.is_err());+}++#[test]+fn install_installed_and_clear() {+ // One test owns the process slot, so it cannot race another.+ clear();+ assert!(installed().is_none());+ let backend: Arc<dyn StorageBackend> = Arc::new(tinystoragedrivers::MemoryStorage::new());+ assert!(install(Arc::clone(&backend)).is_none());+ assert!(installed().is_some_and(|got| Arc::ptr_eq(&got, &backend)));+ assert!(install(Arc::new(tinystoragedrivers::MemoryStorage::new())).is_some());+ assert!(clear());+ assert!(!clear());+}++#[test]+fn agent_scopes_match_the_session_store() {+ assert_eq!(scope_for_agent("agent-7").as_str(), "agent-7");+ assert!(scope_for_agent("has a space").as_str().starts_with("sha256:"));+}