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
refactor(config): split file source loading into its own module
Steven Enamakel7b6b586353c5
diff --git a/crates/openhuman-core/src/config/schema/load/source/file.rs b/crates/openhuman-core/src/config/schema/load/source/file.rsindex 3dda7bb3da..f02ec65500 100644--- a/crates/openhuman-core/src/config/schema/load/source/file.rs+++ b/crates/openhuman-core/src/config/schema/load/source/file.rs@@ -40,8 +40,8 @@ impl ConfigSource for FileConfigSource {"file"}- async fn exists(&self) -> bool {- self.path.exists()+ async fn exists(&self) -> Result<bool> {+ Ok(self.path.exists())}async fn read(&self) -> Result<ConfigRead> {@@ -65,12 +65,19 @@ impl ConfigSource for FileConfigSource {)})?;+ // Built from the original `OsStr`, so a non-UTF-8 file name keeps its+ // own temp and backup names instead of collapsing onto `config.toml`.let file_name = config_path.file_name()- .and_then(|v| v.to_str())- .unwrap_or("config.toml");- let temp_path = parent_dir.join(format!(".{file_name}.tmp-{}", uuid::Uuid::new_v4()));- let backup_path = parent_dir.join(format!("{file_name}.bak"));+ .unwrap_or_else(|| std::ffi::OsStr::new("config.toml"));+ let with_name = |prefix: &str, suffix: String| {+ let mut name = std::ffi::OsString::from(prefix);+ name.push(file_name);+ name.push(suffix);+ parent_dir.join(name)+ };+ let temp_path = with_name(".", format!(".tmp-{}", uuid::Uuid::new_v4()));+ let backup_path = with_name("", ".bak".to_string());let mut temp_file = OpenOptions::new().create_new(true)@@ -110,15 +117,24 @@ impl ConfigSource for FileConfigSource {}}- temp_file- .write_all(toml_str.as_bytes())- .await- .context("Failed to write temporary config contents")?;- temp_file- .sync_all()- .await- .context("Failed to fsync temporary config file")?;+ // The staged file holds the whole config, secrets included: remove it+ // on every failure before the commit instead of leaving it behind.+ let staged = async {+ temp_file+ .write_all(toml_str.as_bytes())+ .await+ .context("Failed to write temporary config contents")?;+ temp_file+ .sync_all()+ .await+ .context("Failed to fsync temporary config file")+ }+ .await;drop(temp_file);+ if let Err(error) = staged {+ let _ = fs::remove_file(&temp_path).await;+ return Err(error);+ }// Everything above can still fail with the live config untouched.// `commit_replacement` owns the swap, and returns `Err` only while thediff --git a/crates/openhuman-core/src/config/schema/load/source/mod.rs b/crates/openhuman-core/src/config/schema/load/source/mod.rsindex 0fc21fa0b5..9aa583522f 100644--- a/crates/openhuman-core/src/config/schema/load/source/mod.rs+++ b/crates/openhuman-core/src/config/schema/load/source/mod.rs@@ -29,7 +29,7 @@mod document;mod file;-use anyhow::Result;+use anyhow::{Context, Result};use async_trait::async_trait;use std::path::Path;@@ -57,7 +57,19 @@ pub(crate) trait ConfigSource: Send + Sync {fn label(&self) -> &'static str;/// Whether the source holds a config at all.- async fn exists(&self) -> bool;+ ///+ /// # Errors+ ///+ /// A backend failure. It is never folded into "absent": a transient+ /// outage must not make the loader fall back to defaults.+ async fn exists(&self) -> Result<bool>;++ /// Whether the source encrypts the whole body itself, so `Config::save`+ /// must not also encrypt individual fields under the process-local key+ /// (which another node could not decrypt).+ fn encrypts_body(&self) -> bool {+ false+ }/// Read the config text, recovering from corruption where the source can.async fn read(&self) -> Result<ConfigRead>;@@ -71,36 +83,50 @@ pub(crate) trait ConfigSource: Send + Sync {////// The document source when the host installed a shared (multi-tenant)/// backend and the current scope resolves; the file otherwise, which includes-/// every desktop build and SaaS calls with no resolvable scope.-pub(crate) fn for_config(config_path: &Path) -> Box<dyn ConfigSource> {+/// every desktop build and SaaS calls with no resolvable scope. The scope is+/// the ambient one, as for every other storage-backed domain.+///+/// # Errors+///+/// On a shared backend with a scope, when no master key can derive the+/// scope's data key: the config then fails closed instead of falling back to+/// a file that would hold the same settings unprotected.+pub(crate) fn for_config(config_path: &Path) -> Result<Box<dyn ConfigSource>> {let file = FileConfigSource::new(config_path);#[cfg(test)]- if let Some((scoped, scope)) = tests_support::forced_document_scope() {- return Box::new(DocumentConfigSource::new(- std::sync::Arc::clone(scoped.documents()),- scope,+ if let Some(forced) = tests_support::forced_document_scope() {+ return Ok(Box::new(DocumentConfigSource::new(+ std::sync::Arc::clone(forced.scoped.documents()),+ forced.scope,+ forced.keys,file,- ));+ )));}if !crate::storage::installed_is_shared() {- return Box::new(file);+ return Ok(Box::new(file));}- match crate::storage::current_scoped().and_then(|scoped| {+ let resolved = crate::storage::current_scoped().and_then(|scoped| {let scope = crate::storage::current_scope()?;Ok(scoped.map(|scoped| (scoped, scope)))- }) {- Ok(Some((scoped, scope))) => Box::new(DocumentConfigSource::new(- std::sync::Arc::clone(scoped.documents()),- scope.as_str().to_string(),- file,- )),- Ok(None) => Box::new(file),+ });+ match resolved {+ Ok(Some((scoped, scope))) => {+ let keys = crate::storage::secrets::keys()+ .map_err(|error| anyhow::anyhow!("config document key: {error}"))?;+ Ok(Box::new(DocumentConfigSource::new(+ std::sync::Arc::clone(scoped.documents()),+ scope,+ keys,+ file,+ )))+ }+ Ok(None) => Ok(Box::new(file)),Err(error) => {tracing::debug!(error = %error,"[config] no storage scope for the config document; using the file");- Box::new(file)+ Ok(Box::new(file))}}}@@ -118,9 +144,12 @@ pub(crate) fn strip_bootstrap(toml_text: &str) -> Result<String> {/// (the file's), or removed when the file has none.pub(crate) fn apply_bootstrap(stored: &str, bootstrap_text: Option<&str>) -> Result<String> {let mut table: toml::Table = toml::from_str(stored)?;- let bootstrap: toml::Table = bootstrap_text- .and_then(|text| toml::from_str(text).ok())- .unwrap_or_default();+ // A bootstrap file that does not parse is an error, not an empty file:+ // treating it as empty would silently drop the storage table.+ let bootstrap: toml::Table = match bootstrap_text {+ Some(text) => toml::from_str(text).context("the bootstrap config file is not valid TOML")?,+ None => toml::Table::default(),+ };for name in BOOTSTRAP_TABLES {table.remove(*name);if let Some(value) = bootstrap.get(*name) {diff --git a/crates/openhuman-core/src/config/schema/load/source/tests_support.rs b/crates/openhuman-core/src/config/schema/load/source/tests_support.rsindex 965ad449da..60d45efce5 100644--- a/crates/openhuman-core/src/config/schema/load/source/tests_support.rs+++ b/crates/openhuman-core/src/config/schema/load/source/tests_support.rs@@ -1,28 +1,50 @@//! Test seam: force the document source for the current thread without//! installing a process-wide backend that every other test would see.-use crate::storage::ScopedStorage;use std::cell::RefCell;+use std::sync::Arc;++use tinystoragedrivers::secrets::KeyProvider;++use crate::storage::{Scope, ScopedStorage};++/// What a forced document source is built from.+#[derive(Clone)]+pub(crate) struct Forced {+ pub scoped: ScopedStorage,+ pub scope: Scope,+ pub keys: Arc<dyn KeyProvider>,+}thread_local! {- static FORCED: RefCell<Option<(ScopedStorage, String)>> = const { RefCell::new(None) };+ static FORCED: RefCell<Option<Forced>> = const { RefCell::new(None) };}-pub(crate) fn forced_document_scope() -> Option<(ScopedStorage, String)> {+pub(crate) fn forced_document_scope() -> Option<Forced> {FORCED.with(|forced| forced.borrow().clone())}-/// Forces the document source on this thread until the guard drops.-pub(crate) struct ForcedDocumentSource;+/// Forces the document source on this thread until the guard drops, then+/// restores whatever was forced before (guards nest).+pub(crate) struct ForcedDocumentSource {+ previous: Option<Forced>,+}impl ForcedDocumentSource {- pub(crate) fn new(scoped: ScopedStorage, scope: &str) -> Self {- FORCED.with(|forced| *forced.borrow_mut() = Some((scoped, scope.to_string())));- Self+ pub(crate) fn new(scoped: ScopedStorage, scope: Scope, keys: Arc<dyn KeyProvider>) -> Self {+ let previous = FORCED.with(|forced| {+ forced.borrow_mut().replace(Forced {+ scoped,+ scope,+ keys,+ })+ });+ Self { previous }}}impl Drop for ForcedDocumentSource {fn drop(&mut self) {- FORCED.with(|forced| *forced.borrow_mut() = None);+ let previous = self.previous.take();+ FORCED.with(|forced| *forced.borrow_mut() = previous);}}diff --git a/crates/openhuman-core/src/storage/secrets.rs b/crates/openhuman-core/src/storage/secrets.rsindex 7a4862799c..9b16c0e61e 100644--- a/crates/openhuman-core/src/storage/secrets.rs+++ b/crates/openhuman-core/src/storage/secrets.rs@@ -24,7 +24,7 @@ use zeroize::Zeroizing;use super::{current_scoped, ScopedStorage, StorageError};/// The key provider every scope's secrets use, built once per process.-fn keys() -> Result<Arc<dyn KeyProvider>, StorageError> {+pub(crate) fn keys() -> Result<Arc<dyn KeyProvider>, StorageError> {// Only a built provider is cached; a failed key load is retried next call.static KEYS: OnceLock<Arc<dyn KeyProvider>> = OnceLock::new();if let Some(keys) = KEYS.get() {