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 config loading into source modules
Steven Enamakel7cb10b263e1d
diff --git a/crates/openhuman-core/src/config/schema/load/impl_load.rs b/crates/openhuman-core/src/config/schema/load/impl_load.rsindex f71841d858..ff9af2cb41 100644--- a/crates/openhuman-core/src/config/schema/load/impl_load.rs+++ b/crates/openhuman-core/src/config/schema/load/impl_load.rs@@ -482,87 +482,11 @@ impl Config {let toml_str =toml::to_string_pretty(&config_to_save).context("Failed to serialize config")?;- let parent_dir = self- .config_path- .parent()- .context("Config path must have a parent directory")?;-- fs::create_dir_all(parent_dir).await.with_context(|| {- format!(- "Failed to create config directory: {}",- parent_dir.display()- )- })?;-- let file_name = self- .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"));-- let mut temp_file = OpenOptions::new()- .create_new(true)- .write(true)- .open(&temp_path)- .await- .with_context(|| {- format!(- "Failed to create temporary config file: {}",- temp_path.display()- )- })?;-- // Harden BEFORE any secret bytes are written. `create_new` opens at- // `0o666 & ~umask` (0644 under the usual 022), and the atomic rename- // below carries the *temp file's* mode onto the live config — so- // without this every save silently re-widened a config that holds- // `enc2:` provider keys and channel tokens back to world-readable, and- // `fs::copy` propagated the same mode onto `config.toml.bak`. The- // load-time auto-fix only ever repaired it on the next startup.- // Same pattern as `keyring::backend`.- //- // Non-fatal by design: filesystems that do not implement chmod- // (CIFS/SMB, exFAT, some FUSE mounts) would otherwise turn a save that- // has always worked into a hard failure. A failed hardening leaves the- // file exactly as permissive as it was before this call existed, so- // warn and continue rather than regress writability — matching the- // best-effort `let _ = set_permissions(..)` on the first-init path.- #[cfg(unix)]- {- use std::{fs::Permissions, os::unix::fs::PermissionsExt};- if let Err(e) = fs::set_permissions(&temp_path, Permissions::from_mode(0o600)).await {- tracing::warn!(- path = %temp_path.display(),- error = %e,- "[security][config] could not restrict config file to 0600; \- it may be readable by other local users"- );- }- }-- 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")?;- drop(temp_file);-- // Everything above can still fail with the live config untouched.- // `commit_replacement` owns the swap, and returns `Err` only while the- // old config is still in place — see its docs for why callers that roll- // back on `Err` depend on that.- super::atomic_commit::commit_replacement(- &temp_path,- &self.config_path,- parent_dir,- &backup_path,- )- .await?;+ // Where the text lives is the source's business: the file (atomic+ // replace with a `.bak`) or, on a shared backend, the config document.+ let source = super::source::for_config(&self.config_path);+ tracing::debug!(source = source.label(), "[config] saving config");+ source.write(&toml_str).await?;Ok(())}diff --git a/crates/openhuman-core/src/config/schema/load/mod.rs b/crates/openhuman-core/src/config/schema/load/mod.rsindex 951f393a81..e492f771fa 100644--- a/crates/openhuman-core/src/config/schema/load/mod.rs+++ b/crates/openhuman-core/src/config/schema/load/mod.rs@@ -10,6 +10,7 @@ mod migrate;mod parse;mod saas_scope;mod secrets;+pub(crate) mod source;pub use active_workspace::active_workspace_dir_cached;pub(crate) use active_workspace::invalidate_active_workspace;@@ -62,7 +63,7 @@ pub(crate) use parse::config_from_toml_str;#[cfg(test)]pub(crate) use std::path::PathBuf;-mod atomic_commit;+pub(super) mod atomic_commit;#[cfg(unix)]pub(super) async fn sync_directory(path: &std::path::Path) -> anyhow::Result<()> {diff --git a/crates/openhuman-core/src/config/schema/load/source/document.rs b/crates/openhuman-core/src/config/schema/load/source/document.rsnew file mode 100644index 0000000000..c57afd5707--- /dev/null+++ b/crates/openhuman-core/src/config/schema/load/source/document.rs@@ -0,0 +1,111 @@+//! [`DocumentConfigSource`]: the config as the `config/{scope}` document.++use std::sync::Arc;++use anyhow::{Context, Result};+use async_trait::async_trait;+use serde_json::json;+use tinystoragedrivers::{CollectionSpec, DocumentStore, Precondition};++use super::{apply_bootstrap, strip_bootstrap, ConfigRead, ConfigSource, FileConfigSource};++/// The collection holding one config document per scope.+pub(crate) const CONFIG_COLLECTION: &str = "config";++/// The document field holding the TOML body.+const BODY_FIELD: &str = "toml";++/// A config kept as one document, `config/{scope}`, on the storage backend.+///+/// The document body is the TOML text without its bootstrap tables+/// ([`super::BOOTSTRAP_TABLES`]); reads re-apply those from the `file`+/// fallback. When the scope has no document yet, reads fall back to the file+/// (a first run seeds from the bootstrap file), and the next write creates it.+pub(crate) struct DocumentConfigSource {+ docs: Arc<dyn DocumentStore>,+ scope: String,+ file: FileConfigSource,+}++impl DocumentConfigSource {+ pub(crate) fn new(docs: Arc<dyn DocumentStore>, scope: String, file: FileConfigSource) -> Self {+ Self { docs, scope, file }+ }++ async fn stored_body(&self) -> Result<Option<String>> {+ self.docs+ .ensure_collection(&CollectionSpec::new(CONFIG_COLLECTION))+ .await+ .context("declare the config collection")?;+ let stored = self+ .docs+ .get(CONFIG_COLLECTION, &self.scope)+ .await+ .context("read the config document")?;+ Ok(stored.and_then(|versioned| {+ versioned+ .doc+ .get(BODY_FIELD)+ .and_then(|body| body.as_str())+ .map(str::to_string)+ }))+ }+}++#[async_trait]+impl ConfigSource for DocumentConfigSource {+ fn label(&self) -> &'static str {+ "document"+ }++ async fn exists(&self) -> bool {+ match self.stored_body().await {+ Ok(Some(_)) => true,+ _ => self.file.exists().await,+ }+ }++ async fn read(&self) -> Result<ConfigRead> {+ let Some(body) = self.stored_body().await? else {+ tracing::debug!(scope = %self.scope, "[config] no config document; reading the file");+ return self.file.read().await;+ };+ // Bootstrap tables come from the file, whatever the document says.+ let file_text = tokio::fs::read_to_string(self.file.path()).await.ok();+ match apply_bootstrap(&body, file_text.as_deref()) {+ Ok(contents) => Ok(ConfigRead {+ contents,+ recovered: false,+ }),+ Err(error) => {+ // A body that does not parse is handed to the loader as-is so+ // its parse recovery (defaults, loud log) applies as it does to+ // a corrupt file; the document is not rewritten here.+ tracing::warn!(scope = %self.scope, error = %error, "[config] config document is not valid TOML");+ Ok(ConfigRead {+ contents: body,+ recovered: false,+ })+ }+ }+ }++ async fn write(&self, toml: &str) -> Result<()> {+ let body = strip_bootstrap(toml).context("strip bootstrap tables from the config")?;+ self.docs+ .ensure_collection(&CollectionSpec::new(CONFIG_COLLECTION))+ .await+ .context("declare the config collection")?;+ self.docs+ .put(+ CONFIG_COLLECTION,+ &self.scope,+ json!({ BODY_FIELD: body }),+ Precondition::None,+ )+ .await+ .context("write the config document")?;+ tracing::debug!(scope = %self.scope, "[config] wrote the config document");+ Ok(())+ }+}diff --git a/crates/openhuman-core/src/config/schema/load/source/file.rs b/crates/openhuman-core/src/config/schema/load/source/file.rsnew file mode 100644index 0000000000..3dda7bb3da--- /dev/null+++ b/crates/openhuman-core/src/config/schema/load/source/file.rs@@ -0,0 +1,129 @@+//! [`FileConfigSource`]: the config as `config.toml`.++use std::path::{Path, PathBuf};++use anyhow::{Context, Result};+use async_trait::async_trait;+use tokio::fs::{self, OpenOptions};+use tokio::io::AsyncWriteExt;++use super::{ConfigRead, ConfigSource};+use crate::config::schema::load::atomic_commit::commit_replacement;+use crate::config::schema::load::impl_load::read_config_with_recovery_or_default;++/// A config at a `config.toml` path.+///+/// Reads keep the file's corruption recovery (non-UTF-8 content is renamed+/// aside and the `.bak` tried). Writes stage a `0600` temp file, fsync it, and+/// hand it to [`commit_replacement`], which keeps the previous config as+/// `.bak`. The file stays hand-editable TOML.+#[derive(Debug, Clone)]+pub(crate) struct FileConfigSource {+ path: PathBuf,+}++impl FileConfigSource {+ pub(crate) fn new(path: &Path) -> Self {+ Self {+ path: path.to_path_buf(),+ }+ }++ pub(crate) fn path(&self) -> &Path {+ &self.path+ }+}++#[async_trait]+impl ConfigSource for FileConfigSource {+ fn label(&self) -> &'static str {+ "file"+ }++ async fn exists(&self) -> bool {+ self.path.exists()+ }++ async fn read(&self) -> Result<ConfigRead> {+ let (contents, recovered) = read_config_with_recovery_or_default(&self.path).await?;+ Ok(ConfigRead {+ contents,+ recovered,+ })+ }++ async fn write(&self, toml_str: &str) -> Result<()> {+ let config_path = &self.path;+ let parent_dir = config_path+ .parent()+ .context("Config path must have a parent directory")?;++ fs::create_dir_all(parent_dir).await.with_context(|| {+ format!(+ "Failed to create config directory: {}",+ parent_dir.display()+ )+ })?;++ 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"));++ let mut temp_file = OpenOptions::new()+ .create_new(true)+ .write(true)+ .open(&temp_path)+ .await+ .with_context(|| {+ format!(+ "Failed to create temporary config file: {}",+ temp_path.display()+ )+ })?;++ // Harden BEFORE any secret bytes are written. `create_new` opens at+ // `0o666 & ~umask` (0644 under the usual 022), and the atomic rename+ // below carries the *temp file's* mode onto the live config — so+ // without this every save silently re-widened a config that holds+ // `enc2:` provider keys and channel tokens back to world-readable, and+ // `fs::copy` propagated the same mode onto `config.toml.bak`. The+ // load-time auto-fix only ever repaired it on the next startup.+ //+ // Non-fatal by design: filesystems that do not implement chmod+ // (CIFS/SMB, exFAT, some FUSE mounts) would otherwise turn a save that+ // has always worked into a hard failure. A failed hardening leaves the+ // file exactly as permissive as it was before this call existed, so+ // warn and continue rather than regress writability.+ #[cfg(unix)]+ {+ use std::{fs::Permissions, os::unix::fs::PermissionsExt};+ if let Err(e) = fs::set_permissions(&temp_path, Permissions::from_mode(0o600)).await {+ tracing::warn!(+ path = %temp_path.display(),+ error = %e,+ "[security][config] could not restrict config file to 0600; \+ it may be readable by other local users"+ );+ }+ }++ 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")?;+ drop(temp_file);++ // Everything above can still fail with the live config untouched.+ // `commit_replacement` owns the swap, and returns `Err` only while the+ // old config is still in place — see its docs for why callers that roll+ // back on `Err` depend on that.+ commit_replacement(&temp_path, config_path, parent_dir, &backup_path).await+ }+}diff --git a/crates/openhuman-core/src/config/schema/load/source/mod.rs b/crates/openhuman-core/src/config/schema/load/source/mod.rsnew file mode 100644index 0000000000..0bf35d5185--- /dev/null+++ b/crates/openhuman-core/src/config/schema/load/source/mod.rs@@ -0,0 +1,167 @@+//! Where a config's TOML text lives: the [`ConfigSource`] port.+//!+//! The loader and `Config::save` work on TOML *text*; this port is the only+//! thing that knows where that text is kept, so the codec, the migrations, the+//! secret encryption and the corruption recovery are one code path for every+//! deployment.+//!+//! | Source | Where | Used |+//! | --- | --- | --- |+//! | [`FileConfigSource`] | `config.toml`, replaced atomically (`atomic_commit`) with a `.bak` | desktop, CLI, and always at boot |+//! | [`DocumentConfigSource`] | the `config/{scope}` document on the storage backend | a shared (multi-tenant) backend, for saves and snapshot reloads |+//!+//! # Bootstrap config never comes from storage+//!+//! The `[storage]` table decides which backend exists, so it cannot be read+//! from one (and its URL can carry a database password). [`BOOTSTRAP_TABLES`]+//! are therefore stripped before a document is written and re-applied from the+//! file on every document read. The first load of a process (`load_or_init`)+//! always reads the file: it runs before any backend is installed.+//!+//! # Why text, not a JSON tree+//!+//! A document holds the TOML body as one string field. That is lossless+//! (a JSON tree would not round-trip every TOML value), keeps one parser, and+//! keeps the file hand-editable on desktop. The desktop file source keeps+//! `atomic_commit` and its `.bak`, `0600` and fsync guarantees, which the file+//! driver's blob API does not offer.++mod document;+mod file;++use anyhow::Result;+use async_trait::async_trait;+use std::path::Path;++pub(crate) use document::DocumentConfigSource;+pub(crate) use file::FileConfigSource;++/// Top-level TOML tables that are bootstrap configuration: always read from+/// the file or environment, never stored in (or read from) a storage backend.+pub(crate) const BOOTSTRAP_TABLES: &[&str] = &["storage"];++/// What a source read returned.+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ConfigRead {+ /// The TOML text. Empty when the content was unreadable and recovery found+ /// nothing (the caller then falls back to defaults).+ pub contents: String,+ /// The source recovered from corruption (a `.bak`, or defaults).+ pub recovered: bool,+}++/// A place a config's TOML text is read from and written to.+#[async_trait]+pub(crate) trait ConfigSource: Send + Sync {+ /// A short, stable name for logs: `file` or `document`.+ fn label(&self) -> &'static str;++ /// Whether the source holds a config at all.+ async fn exists(&self) -> bool;++ /// Read the config text, recovering from corruption where the source can.+ async fn read(&self) -> Result<ConfigRead>;++ /// Replace the config text. Returns `Err` only while the previous config is+ /// still the live one, so callers may roll back in-memory state on `Err`.+ async fn write(&self, toml: &str) -> Result<()>;+}++/// The source for the config at `config_path`.+///+/// 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> {+ 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,+ file,+ ));+ }+ if !crate::storage::installed_is_shared() {+ return Box::new(file);+ }+ match 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),+ Err(error) => {+ tracing::debug!(+ error = %error,+ "[config] no storage scope for the config document; using the file"+ );+ Box::new(file)+ }+ }+}++/// `toml` without its [`BOOTSTRAP_TABLES`].+pub(crate) fn strip_bootstrap(toml_text: &str) -> Result<String> {+ let mut table: toml::Table = toml::from_str(toml_text)?;+ for name in BOOTSTRAP_TABLES {+ table.remove(*name);+ }+ Ok(toml::to_string_pretty(&table)?)+}++/// `stored` with its bootstrap tables replaced by those of `bootstrap_text`+/// (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();+ for name in BOOTSTRAP_TABLES {+ table.remove(*name);+ if let Some(value) = bootstrap.get(*name) {+ table.insert((*name).to_string(), value.clone());+ }+ }+ Ok(toml::to_string_pretty(&table)?)+}++#[cfg(test)]+pub(crate) mod tests_support {+ //! 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;++ thread_local! {+ static FORCED: RefCell<Option<(ScopedStorage, String)>> = const { RefCell::new(None) };+ }++ pub(crate) fn forced_document_scope() -> Option<(ScopedStorage, String)> {+ FORCED.with(|forced| forced.borrow().clone())+ }++ /// Forces the document source on this thread until the guard drops.+ pub(crate) struct ForcedDocumentSource;++ impl ForcedDocumentSource {+ pub(crate) fn new(scoped: ScopedStorage, scope: &str) -> Self {+ FORCED.with(|forced| *forced.borrow_mut() = Some((scoped, scope.to_string())));+ Self+ }+ }++ impl Drop for ForcedDocumentSource {+ fn drop(&mut self) {+ FORCED.with(|forced| *forced.borrow_mut() = None);+ }+ }+}++#[cfg(test)]+#[path = "mod_tests.rs"]+mod tests;