Skip to content

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

feat(storage): add once_per_backend for one-time repo work

Steven Enamakelf53487a5460b
diff --git a/crates/openhuman-core/src/storage/documents.rs b/crates/openhuman-core/src/storage/documents.rs
index 095ea5c69f..ada3cab29c 100644
--- a/crates/openhuman-core/src/storage/documents.rs
+++ b/crates/openhuman-core/src/storage/documents.rs
@@ -63,6 +63,13 @@ fn mark_declared(backend: &Arc<dyn StorageBackend>, scope: &str, collection: &st
declared.insert(key, Arc::downgrade(backend));
}
+/// One-time work already done this process (a legacy import): `(backend
+/// address, scope, domain, key)`, with the same `Weak` guard as [`DECLARED`].
+type OnceKey = (usize, String, &'static str, String);
+
+static DONE_ONCE: LazyLock<Mutex<HashMap<OnceKey, Weak<dyn StorageBackend>>>> =
+ LazyLock::new(Mutex::default);
+
/// The backend and scope a [`Repo`] was opened on, for declaring its
/// collections once per process instead of on every call.
#[derive(Clone)]
@@ -122,6 +129,45 @@ impl Repo {
}
}
+ /// Runs `f` once per process for this repo's backend instance, scope and
+ /// `key` (a legacy import keyed by its source path). Calls are serialized,
+ /// and the run is recorded only when `f` succeeds, so a failed one is
+ /// retried by the next call. A replaced backend runs it afresh. A repo
+ /// opened with [`Repo::over`] has no backend identity and runs `f` on
+ /// every call, so `f` must be idempotent.
+ ///
+ /// # Errors
+ ///
+ /// Whatever `f` returns.
+ pub fn once_per_backend(&self, key: &str, f: impl FnOnce() -> Result<()>) -> Result<()> {
+ let Some(origin) = &self.origin else {
+ return f();
+ };
+ let once_key = (
+ backend_addr(&origin.backend),
+ origin.scope.clone(),
+ self.domain,
+ key.to_string(),
+ );
+ let mut done = DONE_ONCE.lock().unwrap_or_else(PoisonError::into_inner);
+ let already = done
+ .get(&once_key)
+ .and_then(Weak::upgrade)
+ .is_some_and(|alive| Arc::ptr_eq(&alive, &origin.backend));
+ if already {
+ return Ok(());
+ }
+ f()?;
+ done.retain(|_, weak| weak.strong_count() > 0);
+ done.insert(once_key, Arc::downgrade(&origin.backend));
+ log::debug!(
+ "[storage] {} one-time work done scope={} key={key}",
+ self.domain,
+ origin.scope
+ );
+ Ok(())
+ }
+
/// Runs `op` against the store from synchronous code, after declaring the
/// domain's collections (idempotent).
///