Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(storage): skip redundant collection declarations per process

Steven Enamakela3e1535de6e4
diff --git a/crates/openhuman-core/src/storage/documents.rs b/crates/openhuman-core/src/storage/documents.rs
index 2343d6d901..9b0f1b7390 100644
--- a/crates/openhuman-core/src/storage/documents.rs
+++ b/crates/openhuman-core/src/storage/documents.rs
@@ -8,24 +8,68 @@
//! processes on one database never both apply a change that requires a
//! particular prior state.
+use std::collections::HashMap;
use std::future::Future;
-use std::sync::Arc;
+use std::sync::{Arc, LazyLock, Mutex, PoisonError, Weak};
use anyhow::{anyhow, Context, Result};
use serde_json::Value;
use tinystoragedrivers::{CollectionSpec, ErrorKind, Versioned};
-use super::{block_on, current_scoped, DocumentStore, ScopedStorage, StorageError};
+use super::{
+ block_on, current_scope, installed, DocumentStore, ScopedStorage, StorageBackend, StorageError,
+};
/// Compare-and-swap attempts before a contended update gives up.
pub const CAS_ATTEMPTS: usize = 32;
+/// Collections already declared, per process: `(backend address, scope,
+/// collection)`. The `Weak` guards against an address reused by a later
+/// backend, so a replaced backend is declared afresh.
+type DeclaredKey = (usize, String, String);
+
+static DECLARED: LazyLock<Mutex<HashMap<DeclaredKey, Weak<dyn StorageBackend>>>> =
+ LazyLock::new(Mutex::default);
+
+fn backend_addr(backend: &Arc<dyn StorageBackend>) -> usize {
+ Arc::as_ptr(backend).cast::<()>() as usize
+}
+
+/// Whether `collection` was already declared on `backend` under `scope`.
+fn is_declared(backend: &Arc<dyn StorageBackend>, scope: &str, collection: &str) -> bool {
+ let key = (backend_addr(backend), scope.to_string(), collection.to_string());
+ DECLARED
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .get(&key)
+ .and_then(Weak::upgrade)
+ .is_some_and(|alive| Arc::ptr_eq(&alive, backend))
+}
+
+/// Records that `collection` is declared on `backend` under `scope`, and
+/// forgets entries whose backend is gone.
+fn mark_declared(backend: &Arc<dyn StorageBackend>, scope: &str, collection: &str) {
+ let key = (backend_addr(backend), scope.to_string(), collection.to_string());
+ let mut declared = DECLARED.lock().unwrap_or_else(PoisonError::into_inner);
+ declared.retain(|_, weak| weak.strong_count() > 0);
+ declared.insert(key, Arc::downgrade(backend));
+}
+
+/// The backend and scope a [`Repo`] was opened on, for declaring its
+/// collections once per process instead of on every call.
+#[derive(Clone)]
+struct Origin {
+ backend: Arc<dyn StorageBackend>,
+ scope: String,
+}
+
/// One domain's document store under one storage scope.
#[derive(Clone)]
pub struct Repo {
docs: Arc<dyn DocumentStore>,
domain: &'static str,
collections: fn() -> Vec<CollectionSpec>,
+ origin: Option<Origin>,
}
impl Repo {
@@ -40,9 +84,20 @@ impl Repo {
domain: &'static str,
collections: fn() -> Vec<CollectionSpec>,
) -> Result<Option<Self>> {
- Ok(current_scoped()
- .with_context(|| format!("[{domain}] resolve the storage scope"))?
- .map(|scoped| Self::over(&scoped, domain, collections)))
+ let Some(backend) = installed() else {
+ return Ok(None);
+ };
+ let scope =
+ current_scope().with_context(|| format!("[{domain}] resolve the storage scope"))?;
+ let scoped = backend
+ .for_scope(&scope)
+ .with_context(|| format!("[{domain}] open the storage scope"))?;
+ let mut repo = Self::over(&scoped, domain, collections);
+ repo.origin = Some(Origin {
+ backend,
+ scope: scope.as_str().to_string(),
+ });
+ Ok(Some(repo))
}
/// The repo over an already scoped handle (tests, explicit scopes).
@@ -55,6 +110,7 @@ impl Repo {
docs: Arc::clone(scoped.documents()),
domain,
collections,
+ origin: None,
}
}
@@ -71,12 +127,23 @@ impl Repo {
T: Send + 'static,
{
let docs = Arc::clone(&self.docs);
- let specs = (self.collections)();
+ let origin = self.origin.clone();
+ let specs: Vec<CollectionSpec> = (self.collections)()
+ .into_iter()
+ .filter(|spec| {
+ origin.as_ref().is_none_or(|origin| {
+ !is_declared(&origin.backend, &origin.scope, spec.name())
+ })
+ })
+ .collect();
let future = op(Arc::clone(&docs));
let domain = self.domain;
block_on(async move {
for spec in &specs {
docs.ensure_collection(spec).await?;
+ if let Some(origin) = &origin {
+ mark_declared(&origin.backend, &origin.scope, spec.name());
+ }
}
future.await
})