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(storage_host): remove duplicated storage host implementation
Steven Enamakela9a0516ff304
diff --git a/crates/openhuman-core/src/modules/storage_host.rs b/crates/openhuman-core/src/modules/storage_host.rsindex cc838b6802..d51f3a8a6b 100644--- a/crates/openhuman-core/src/modules/storage_host.rs+++ b/crates/openhuman-core/src/modules/storage_host.rs@@ -47,9 +47,9 @@ use tinystoragedrivers_bus::{StorageFailure, StorageKind, STORAGE_INTERFACE};use tinystoragedrivers_client::{Admission, StorageServer};use super::storage_grants::{- authorize, declared, filter_reply, Denied, Object, Plan, StorageGrant,+ authorize, declared, filter_reply, Object, Plan, StorageGrant,};-use crate::storage::{DocumentStore, Scope, StorageBackend, StorageError};+use crate::storage::{Scope, StorageBackend, StorageError};/// Where the four objects are served: `<root>/<Object>`.const OBJECT_ROOT: &str = "/ai/tinyhumans/tinystorage";@@ -489,426 +489,6 @@ impl Environment for Live {module_scope(tenant.profile.as_deref(), &base, module_id)}- fn grant(&self, module_id: &str) -> Option<StorageGrant>;- /// The key provider for module secrets.- fn keys(&self) -> Result<Arc<dyn KeyProvider>, StorageError>;-}--/// One line of the audit trail. Carries no payload by construction.-#[derive(Clone, Debug, PartialEq, Eq)]-pub(crate) struct AuditRecord {- pub module: String,- pub scope: String,- pub object: &'static str,- pub op: String,- pub target: String,- pub outcome: &'static str,-}--/// Receives every audit record.-pub(crate) trait AuditSink: Send + Sync {- fn record(&self, record: &AuditRecord);-}--struct LogAudit;--impl AuditSink for LogAudit {- fn record(&self, record: &AuditRecord) {- tracing::info!(- target: "openhuman::storage_host",- module = %record.module,- scope = %record.scope,- object = record.object,- op = %record.op,- target = %record.target,- outcome = record.outcome,- "[storage_host] module storage call"- );- }-}--/// How a call failed, before it becomes a bus error.-#[derive(Debug, PartialEq, Eq)]-pub(crate) enum HostError {- /// Not allowed; the label says why and holds no request content.- Denied(&'static str),- /// The backend refused or failed, as a content-free category.- Storage(StorageFailure),-}--impl From<HostError> for tinybus::Error {- fn from(error: HostError) -> Self {- match error {- HostError::Denied(label) => tinybus::Error::MethodFailed {- name: ERROR_DENIED.to_string(),- message: label.to_string(),- },- HostError::Storage(failure) => tinybus::Error::MethodFailed {- name: ERROR_STORAGE.to_string(),- message: serde_json::to_value(failure.kind)- .ok()- .and_then(|kind| kind.as_str().map(str::to_owned))- .unwrap_or_else(|| "backend".to_string()),- },- }- }-}--fn failure(kind: StorageKind) -> HostError {- HostError::Storage(StorageFailure { kind })-}--/// A module's scope under the host's current tenant.-///-/// * For a profile (SaaS): `<profile>~module:<id>`, with the profile escaped-/// as a session key is. That sits under the profile's session-key prefix,-/// so the profile's lease fence ([`crate::profiles`]) guards a module's-/// writes exactly as it guards the profile's transcripts. Too long to be a-/// scope is an error, never a hash, because a hash would fall outside the-/// fence.-/// * Otherwise: `module:<id>@<base>`, or a hash of both when that is not a-/// valid scope or the id could make the form ambiguous.-///-/// Either way two modules never share a scope, and nothing the module sends-/// takes part.-pub(crate) fn module_scope(- profile: Option<&str>,- base: &Scope,- module_id: &str,-) -> Result<Scope, StorageError> {- let plain = !module_id.is_empty()- && module_id- .bytes()- .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');- if let Some(profile) = profile {- if !plain {- return Err(StorageError::invalid_input("module id is not a plain name"));- }- let prefix = crate::core::runtime::session_key_prefix(profile);- return Scope::new(format!("{prefix}module:{module_id}"));- }- if plain {- if let Ok(scope) = Scope::new(format!("module:{module_id}@{}", base.as_str())) {- return Ok(scope);- }- }- use sha2::Digest;- let mut digest = sha2::Sha256::new();- digest.update(module_id.as_bytes());- digest.update([0]);- digest.update(base.as_str().as_bytes());- Scope::new(format!("module-sha256:{}", hex::encode(digest.finalize())))-}--/// A module bound to a scope: its grant and the server that answers it.-struct Binding {- backend: Arc<dyn StorageBackend>,- grant: StorageGrant,- server: StorageServer,-}--pub(crate) struct StorageHost {- directory: Arc<dyn CallerDirectory>,- environment: Arc<dyn Environment>,- audit: Arc<dyn AuditSink>,- bindings: tokio::sync::Mutex<HashMap<(String, String), Arc<Binding>>>,-}--impl StorageHost {- pub(crate) fn new(- directory: Arc<dyn CallerDirectory>,- environment: Arc<dyn Environment>,- audit: Arc<dyn AuditSink>,- ) -> Self {- Self {- directory,- environment,- audit,- bindings: tokio::sync::Mutex::new(HashMap::new()),- }- }-- /// Decides and answers one call.- ///- /// `sender` is the authenticated sender the bus delivered, never anything- /// from the request. `admission` is `Confidential` only for a call the bus- /// delivered on a confidential route.- pub(crate) async fn handle(- &self,- object: Object,- selector: &str,- request: Value,- sender: Option<&BusName>,- admission: Admission,- ) -> Result<Value, HostError> {- let Some(sender) = sender else {- tracing::warn!(- target: "openhuman::storage_host",- object = object.as_str(),- op = selector,- "[storage_host] refused a call with no authenticated sender"- );- return Err(HostError::Denied("unauthenticated-caller"));- };- let Some(module) = self.directory.module_for(sender).await else {- tracing::warn!(- target: "openhuman::storage_host",- object = object.as_str(),- op = selector,- "[storage_host] refused a call from a peer that is not a registry module"- );- return Err(HostError::Denied("unknown-caller"));- };- let scope = self.environment.module_scope(&module);- let scope_text = scope- .as_ref()- .map_or_else(|_| "-".to_string(), |scope| scope.as_str().to_string());- let audit = |target: &str, outcome: &'static str| {- self.audit.record(&AuditRecord {- module: module.clone(),- scope: scope_text.clone(),- object: object.as_str(),- op: selector.to_string(),- target: target.to_string(),- outcome,- });- };-- let scope = match scope {- Ok(scope) => scope,- Err(_) => {- audit("", "no-scope");- return Err(HostError::Denied("no-scope"));- }- };- let binding = match self.bind(&module, scope).await {- Ok(binding) => binding,- Err(error) => {- audit("", error.label());- return Err(error.into_host());- }- };- let plan = match authorize(&binding.grant, object, selector, &request) {- Ok(plan) => plan,- Err(denied) => {- audit("", denied.label());- return Err(HostError::Denied(denied.label()));- }- };- match plan {- Plan::Answer(reply) => {- audit("", "answered-by-host");- Ok(reply)- }- Plan::Forward { target, filter } => {- match binding- .server- .handle(admission, object.as_str(), selector, request)- .await- {- Ok(reply) => {- audit(&target, "ok");- Ok(filter_reply(&binding.grant, filter, reply))- }- Err(failed) => {- audit(&target, "storage-error");- Err(HostError::Storage(failed))- }- }- }- }- }-- /// The module's binding for `scope`, built on first use and again when the- /// installed backend changed. The host runs the declared schema here.- async fn bind(&self, module: &str, scope: Scope) -> Result<Arc<Binding>, BindError> {- let backend = self.environment.backend().ok_or(BindError::NoBackend)?;- let key = (module.to_string(), scope.as_str().to_string());- let mut bindings = self.bindings.lock().await;- if let Some(existing) = bindings.get(&key) {- if Arc::ptr_eq(&existing.backend, &backend) {- return Ok(Arc::clone(existing));- }- }- let grant = self.environment.grant(module).ok_or(BindError::NoGrant)?;- grant.validate().map_err(|reason| {- tracing::error!(- target: "openhuman::storage_host",- module,- reason,- "[storage_host] refused an invalid storage grant"- );- BindError::BadGrant- })?;- let storage = backend- .for_scope(&scope)- .map_err(|_| BindError::Backend(StorageKind::Backend))?;- for spec in grant.specs() {- storage- .documents()- .ensure_collection(spec)- .await- .map_err(|_| BindError::Backend(StorageKind::Backend))?;- }- let mut server = StorageServer::new(storage.clone());- if !grant.secret_prefixes.is_empty() {- match self.environment.keys() {- Ok(keys) => {- server = server.with_secrets(Arc::new(DocumentSecrets::new(&storage, keys)));- }- Err(_) => tracing::warn!(- target: "openhuman::storage_host",- module,- "[storage_host] no master key; module secrets stay unavailable"- ),- }- }- let binding = Arc::new(Binding {- backend,- grant,- server,- });- bindings.insert(key, Arc::clone(&binding));- Ok(binding)- }-}--enum BindError {- NoBackend,- NoGrant,- BadGrant,- Backend(StorageKind),-}--impl BindError {- fn label(&self) -> &'static str {- match self {- Self::NoBackend => "no-backend",- Self::NoGrant => "no-grant-declared",- Self::BadGrant => "invalid-grant",- Self::Backend(_) => "backend-error",- }- }-- fn into_host(self) -> HostError {- match self {- Self::NoBackend => failure(StorageKind::Unavailable),- Self::NoGrant => HostError::Denied("no-grant-declared"),- Self::BadGrant => HostError::Denied("invalid-grant"),- Self::Backend(kind) => failure(kind),- }- }-}--/// One storage object on the bus.-struct ObjectService {- object: Object,- host: Arc<StorageHost>,-}--fn selectors(object: Object) -> &'static [&'static str] {- use tinystoragedrivers_bus as wire;- match object {- Object::Documents => &wire::DOCUMENTS_SELECTORS,- Object::Streams => &wire::STREAMS_SELECTORS,- Object::Blobs => &wire::BLOBS_SELECTORS,- Object::Secrets => &wire::SECRETS_SELECTORS,- }-}--/// The request out of positional bus arguments: none is `null`, one is itself.-fn request_of(args: Value) -> tinybus::Result<Value> {- match args {- Value::Array(mut items) if items.len() <= 1 => Ok(items.pop().unwrap_or(Value::Null)),- Value::Null => Ok(Value::Null),- _ => Err(tinybus::Error::failed(- "a storage call takes one request argument",- )),- }-}--#[async_trait]-impl tinybus::Interface for ObjectService {- fn name(&self) -> InterfaceName {- InterfaceName::new(STORAGE_INTERFACE).unwrap_or_else(|_| unreachable!("a fixed name"))- }-- fn members(&self) -> Vec<MemberName> {- selectors(self.object)- .iter()- .filter_map(|selector| MemberName::new(*selector).ok())- .collect()- }-- fn requires_confidential(&self, _member: &MemberName) -> bool {- self.object == Object::Secrets- }-- async fn call(&self, _member: &MemberName, _args: Value) -> tinybus::Result<Value> {- // Without the broker's context there is no caller to authorize.- Err(HostError::Denied("unauthenticated-caller").into())- }-- async fn call_with_context(- &self,- member: &MemberName,- args: Value,- context: &CallContext,- ) -> tinybus::Result<Value> {- let admission = if self.object == Object::Secrets {- Admission::Confidential- } else {- Admission::Private- };- self.host- .handle(- self.object,- member.as_str(),- request_of(args)?,- context.authenticated_sender(),- admission,- )- .await- .map_err(Into::into)- }-}--/// Production wiring: the broker's name owners, the installed backend, the-/// host's scope rule and the compiled grants.-struct Live {- connection: tinybus::Connection,-}--#[async_trait]-impl CallerDirectory for Live {- async fn module_for(&self, sender: &BusName) -> Option<String> {- for record in super::registry::ALL {- if let Ok(Some(owner)) = self.connection.name_owner(record.bus_name).await {- if &owner == sender {- return Some(record.id.to_string());- }- }- }- None- }-}--impl Environment for Live {- fn backend(&self) -> Option<Arc<dyn StorageBackend>> {- crate::storage::installed()- }-- fn base_scope(&self) -> Result<Scope, StorageError> {- let saas = crate::core::runtime::mode::is_saas();- match crate::core::runtime::current_tenant() {- Ok(tenant) => {- crate::storage::scope_from(tenant.profile.as_deref(), tenant.agent.as_deref(), saas)- }- // A module call arrives on the module bus, outside any turn.- Err(_) => crate::storage::scope_from(None, None, saas),- }- }-fn grant(&self, module_id: &str) -> Option<StorageGrant> {declared(module_id)}diff --git a/crates/openhuman-core/src/modules/storage_host_tests.rs b/crates/openhuman-core/src/modules/storage_host_tests.rsindex 46aa4c6990..1f753d8175 100644--- a/crates/openhuman-core/src/modules/storage_host_tests.rs+++ b/crates/openhuman-core/src/modules/storage_host_tests.rs@@ -545,7 +545,7 @@ fn a_profiles_module_scope_sits_under_its_lease_fence() {"tinymcp",).unwrap();- let covered = crate::profiles::fence::scopes_of(&crate::profiles::ProfileId::new(profile).unwrap());+ let covered = crate::profiles::fence::scopes_of(&crate::profiles::ProfileId::parse(profile).unwrap());assert!(covered.iter().any(|matcher| match matcher {crate::storage::fence::ScopeMatch::Prefix(prefix) => scope.as_str().starts_with(prefix.as_str()),@@ -589,7 +589,7 @@ async fn a_module_write_under_a_stale_lease_is_fenced_by_the_host() {grant_a.epoch,grant_a.expires_at_ms,5_000,- crate::profiles::fence::scopes_of(&crate::profiles::ProfileId::new("acme").unwrap()),+ crate::profiles::fence::scopes_of(&crate::profiles::ProfileId::parse("acme").unwrap()),)));let fenced: Arc<dyn StorageBackend> = Arc::new(FencedBackend::new(shared, fences));