Skip to content

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

fix(storage): let claimed imports declare collections on MongoDB (#8424)

CodeGhost21546cb2b10004
diff --git a/crates/openhuman-core/src/storage/claim_bound.rs b/crates/openhuman-core/src/storage/claim_bound.rs
new file mode 100644
index 0000000000..d1da7d44e2
--- /dev/null
+++ b/crates/openhuman-core/src/storage/claim_bound.rs
@@ -0,0 +1,151 @@
+//! Storage bound to an import claim that can still declare its collections.
+//!
+//! An importer writes inside a claim ([`super::import_state::with_claim`]),
+//! through storage whose writes carry the claim's `WriteCondition`, so a
+//! process that lost its claim cannot write records. Declaring a collection
+//! is not such a write: it is an idempotent merge of schema metadata, and a
+//! stale process declaring one harms nothing.
+//!
+//! Drivers disagree on whether a conditioned handle may declare a
+//! collection. The memory, file and SQLite drivers allow it; MongoDB refuses
+//! with `Unsupported(ConditionalWrites)` ("conditioned MongoDB handles cannot
+//! mutate collection declarations"). On MongoDB every claimed import that
+//! declared a collection therefore failed, at every boot (#8422).
+//!
+//! [`claim_bound`] opens the conditioned storage with one change: its
+//! document handle declares and validates collections through the scope's
+//! unconditioned handle. Every other document operation, and every other
+//! port, stays under the claim.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use serde_json::Value;
+use tinystoragedrivers::{Scope, WriteCondition};
+use tinystoragedrivers_api::{DocumentStore, DocumentWatch, Storage};
+use tinystoragedrivers_types::{
+ Capabilities, CollectionSpec, Filter, Page, Precondition, Query, ReadCheck, Result, SearchHit,
+ Sort, Version, Versioned, WatchOptions, WriteOp, WriteOptions, WriteResult,
+};
+
+use super::StorageBackend;
+
+/// `backend`'s storage for `scope` with every write bound to `condition`,
+/// except collection declarations, which go through the scope's plain
+/// handle.
+///
+/// # Errors
+///
+/// The error from opening either the conditioned or the plain handle, such
+/// as `Unsupported(ConditionalWrites)` from a backend without conditioned
+/// writes.
+pub(crate) fn claim_bound(
+ backend: &dyn StorageBackend,
+ scope: &Scope,
+ condition: &WriteCondition,
+) -> Result<Storage> {
+ let claimed = backend.for_scope_conditioned(scope, condition)?;
+ let plain = backend.for_scope(scope)?;
+ Ok(Storage::new(
+ Arc::new(ClaimBoundDocuments {
+ claimed: Arc::clone(claimed.documents()),
+ plain: Arc::clone(plain.documents()),
+ }),
+ Arc::clone(claimed.streams()),
+ Arc::clone(claimed.kv()),
+ Arc::clone(claimed.blobs()),
+ Arc::clone(claimed.queues()),
+ Arc::clone(claimed.secrets()),
+ ))
+}
+
+/// A claim-bound document handle that declares collections unconditioned.
+struct ClaimBoundDocuments {
+ /// Every read and write, under the claim.
+ claimed: Arc<dyn DocumentStore>,
+ /// Collection declarations and their validation only.
+ plain: Arc<dyn DocumentStore>,
+}
+
+impl std::fmt::Debug for ClaimBoundDocuments {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("ClaimBoundDocuments")
+ .finish_non_exhaustive()
+ }
+}
+
+#[async_trait]
+impl DocumentStore for ClaimBoundDocuments {
+ fn capabilities(&self) -> Capabilities {
+ self.claimed.capabilities()
+ }
+ async fn watch(&self, c: &str, f: &Filter, o: &WatchOptions) -> Result<Box<dyn DocumentWatch>> {
+ self.claimed.watch(c, f, o).await
+ }
+ async fn ensure_collection(&self, s: &CollectionSpec) -> Result<()> {
+ self.plain.ensure_collection(s).await
+ }
+ async fn validate_collection_spec(&self, s: &CollectionSpec) -> Result<()> {
+ self.plain.validate_collection_spec(s).await
+ }
+ async fn get(&self, c: &str, id: &str) -> Result<Option<Versioned<Value>>> {
+ self.claimed.get(c, id).await
+ }
+ async fn put(&self, c: &str, id: &str, v: Value, p: Precondition) -> Result<Version> {
+ self.claimed.put(c, id, v, p).await
+ }
+ async fn put_with(
+ &self,
+ c: &str,
+ id: &str,
+ v: Value,
+ p: Precondition,
+ o: WriteOptions,
+ ) -> Result<Version> {
+ self.claimed.put_with(c, id, v, p, o).await
+ }
+ async fn delete(&self, c: &str, id: &str, p: Precondition) -> Result<bool> {
+ self.claimed.delete(c, id, p).await
+ }
+ async fn query(&self, c: &str, q: &Query) -> Result<Page<Versioned<Value>>> {
+ self.claimed.query(c, q).await
+ }
+ async fn count(&self, c: &str, f: &Filter) -> Result<u64> {
+ self.claimed.count(c, f).await
+ }
+ async fn delete_where(&self, c: &str, f: &Filter) -> Result<u64> {
+ self.claimed.delete_where(c, f).await
+ }
+ async fn claim(
+ &self,
+ c: &str,
+ f: &Filter,
+ s: &[Sort],
+ p: &Value,
+ ) -> Result<Option<Versioned<Value>>> {
+ self.claimed.claim(c, f, s, p).await
+ }
+ async fn atomic_batch(&self, o: Vec<WriteOp>) -> Result<Vec<WriteResult>> {
+ self.claimed.atomic_batch(o).await
+ }
+ async fn atomic_batch_checked(
+ &self,
+ c: Vec<ReadCheck>,
+ o: Vec<WriteOp>,
+ ) -> Result<Vec<WriteResult>> {
+ self.claimed.atomic_batch_checked(c, o).await
+ }
+ async fn search(&self, c: &str, t: &str, l: usize) -> Result<Vec<SearchHit>> {
+ self.claimed.search(c, t, l).await
+ }
+ async fn drop_collection(&self, c: &str) -> Result<()> {
+ self.claimed.drop_collection(c).await
+ }
+ async fn collections(&self, p: &str) -> Result<Vec<String>> {
+ self.claimed.collections(p).await
+ }
+}
+
+#[cfg(all(test, feature = "storage-sqlite"))]
+#[path = "claim_bound_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/storage/claim_bound_tests.rs b/crates/openhuman-core/src/storage/claim_bound_tests.rs
new file mode 100644
index 0000000000..4862c76718
--- /dev/null
+++ b/crates/openhuman-core/src/storage/claim_bound_tests.rs
@@ -0,0 +1,186 @@
+//! A claim-bound handle declares its collections even on a backend whose
+//! conditioned handles refuse to, as MongoDB's do (#8422), while a claim
+//! that was lost still cannot write.
+
+use super::*;
+
+use serde_json::json;
+use tinystoragedrivers_types::{
+ CollectionSpec, Filter, Precondition, Query, StorageError, WatchOptions, WriteOptions,
+};
+
+use crate::storage::documents::Repo;
+use crate::storage::import_state;
+use crate::storage::test_support::refusing_conditioned_declarations;
+use crate::storage::Scope;
+
+const OWNER: &str = "claim_bound_test";
+const ROWS: &str = "legacy_rows";
+
+/// The refusing backend over a fresh SQLite database, and a repo on it.
+fn refusing_repo() -> (tempfile::TempDir, Arc<dyn StorageBackend>, Repo) {
+ let dir = tempfile::tempdir().unwrap();
+ let url = format!("sqlite:{}", dir.path().join("claims.sqlite").display());
+ let sqlite = crate::storage::block_on(async move { crate::storage::open(&url).await }).unwrap();
+ let backend = refusing_conditioned_declarations(sqlite);
+ let repo = Repo::on(&backend, &Scope::local(), "claim-bound-test", Vec::new).unwrap();
+ (dir, backend, repo)
+}
+
+/// Declares [`ROWS`] and writes one row named `id` through `docs`.
+async fn declare_and_write(docs: Arc<dyn DocumentStore>, id: &'static str) -> Result<()> {
+ docs.ensure_collection(&CollectionSpec::new(ROWS)).await?;
+ docs.put(ROWS, id, json!({ "imported": true }), Precondition::Absent)
+ .await
+ .map(|_| ())
+}
+
+fn row(repo: &Repo, id: &'static str) -> Option<Versioned<Value>> {
+ repo.run(move |docs| async move { docs.get(ROWS, id).await })
+ .unwrap()
+}
+
+#[test]
+fn the_test_backend_refuses_conditioned_declarations_like_mongodb() {
+ let (_dir, backend, repo) = refusing_repo();
+ let refused = import_state::with_claim(&repo, OWNER, "sanity", |condition| {
+ let storage = backend.for_scope_conditioned(&Scope::local(), condition)?;
+ let docs = Arc::clone(storage.documents());
+ Ok(crate::storage::block_on(async move {
+ docs.ensure_collection(&CollectionSpec::new(ROWS)).await
+ }))
+ })
+ .unwrap()
+ .expect("the claim is free");
+ let error = refused.expect_err("a conditioned declaration is refused");
+ assert!(
+ error
+ .to_string()
+ .contains("cannot mutate collection declarations"),
+ "{error}"
+ );
+}
+
+#[test]
+fn a_claimed_repo_declares_its_collections_and_writes() {
+ let (_dir, _backend, repo) = refusing_repo();
+ import_state::with_claim(&repo, OWNER, "repo", |condition| {
+ repo.conditioned(condition)?
+ .run(|docs| declare_and_write(docs, "via-repo"))
+ })
+ .unwrap()
+ .expect("the claim is free");
+ assert!(row(&repo, "via-repo").is_some());
+}
+
+#[test]
+fn a_claim_bound_backend_declares_its_collections_and_writes() {
+ let (_dir, backend, repo) = refusing_repo();
+ import_state::with_claim(&repo, OWNER, "backend", |condition| {
+ let bound = import_state::backend_with_condition(Arc::clone(&backend), condition.clone());
+ let docs = Arc::clone(bound.for_scope(&Scope::local())?.documents());
+ crate::storage::block_on(declare_and_write(docs, "via-backend"))?;
+ let composed = bound.for_scope_conditioned(&Scope::local(), condition)?;
+ let docs = Arc::clone(composed.documents());
+ crate::storage::block_on(declare_and_write(docs, "via-composed"))?;
+ Ok(())
+ })
+ .unwrap()
+ .expect("the claim is free");
+ assert!(row(&repo, "via-backend").is_some());
+ assert!(row(&repo, "via-composed").is_some());
+}
+
+#[test]
+fn a_lost_claim_may_declare_but_never_writes() {
+ let (_dir, backend, repo) = refusing_repo();
+ let stale = import_state::with_claim(&repo, OWNER, "lost", |condition| Ok(condition.clone()))
+ .unwrap()
+ .expect("the claim is free");
+ // Released: its condition no longer holds.
+ let docs = Arc::clone(
+ claim_bound(backend.as_ref(), &Scope::local(), &stale)
+ .unwrap()
+ .documents(),
+ );
+ let (declared, written) = crate::storage::block_on(async move {
+ let declared = docs.ensure_collection(&CollectionSpec::new(ROWS)).await;
+ let written = docs
+ .put(ROWS, "stale", json!({}), Precondition::Absent)
+ .await
+ .map(|_| ());
+ Ok::<_, StorageError>((declared, written))
+ })
+ .unwrap();
+ declared.expect("a lost claim may still declare a collection");
+ assert!(written.is_err(), "a stale claim cannot write");
+ assert!(row(&repo, "stale").is_none());
+}
+
+#[test]
+fn every_other_document_operation_stays_under_the_claim() {
+ let (_dir, backend, repo) = refusing_repo();
+ import_state::with_claim(&repo, OWNER, "passthrough", |condition| {
+ let storage = claim_bound(backend.as_ref(), &Scope::local(), condition)?;
+ let docs = Arc::clone(storage.documents());
+ assert!(format!("{docs:?}").contains("ClaimBoundDocuments"));
+ let claimed = backend.for_scope_conditioned(&Scope::local(), condition)?;
+ assert_eq!(docs.capabilities(), claimed.documents().capabilities());
+ let claimed = Arc::clone(claimed.documents());
+ crate::storage::block_on(async move {
+ let spec = CollectionSpec::new(ROWS);
+ docs.ensure_collection(&spec).await?;
+ docs.validate_collection_spec(&spec).await?;
+ docs.put(ROWS, "a", json!({ "n": 1 }), Precondition::Absent)
+ .await?;
+ docs.put_with(
+ ROWS,
+ "b",
+ json!({ "n": 2 }),
+ Precondition::Absent,
+ WriteOptions::new(),
+ )
+ .await?;
+ assert!(docs.get(ROWS, "a").await?.is_some());
+ assert_eq!(docs.count(ROWS, &Filter::All).await?, 2);
+ assert_eq!(docs.query(ROWS, &Query::all()).await?.items.len(), 2);
+ assert!(docs.delete(ROWS, "a", Precondition::None).await?);
+ let _ = docs
+ .claim(ROWS, &Filter::All, &[], &json!({ "n": 3 }))
+ .await;
+ // The optional operations answer exactly as the claimed handle does.
+ assert_eq!(
+ docs.atomic_batch(Vec::new()).await.is_ok(),
+ claimed.atomic_batch(Vec::new()).await.is_ok()
+ );
+ assert_eq!(
+ docs.atomic_batch_checked(Vec::new(), Vec::new())
+ .await
+ .is_ok(),
+ claimed
+ .atomic_batch_checked(Vec::new(), Vec::new())
+ .await
+ .is_ok()
+ );
+ assert_eq!(
+ docs.search(ROWS, "n", 1).await.is_ok(),
+ claimed.search(ROWS, "n", 1).await.is_ok()
+ );
+ assert_eq!(
+ docs.collections("").await.is_ok(),
+ claimed.collections("").await.is_ok()
+ );
+ let watch = WatchOptions::default();
+ assert_eq!(
+ docs.watch(ROWS, &Filter::All, &watch).await.is_ok(),
+ claimed.watch(ROWS, &Filter::All, &watch).await.is_ok()
+ );
+ assert_eq!(docs.delete_where(ROWS, &Filter::All).await?, 1);
+ docs.drop_collection(ROWS).await?;
+ Ok::<_, StorageError>(())
+ })?;
+ Ok(())
+ })
+ .unwrap()
+ .expect("the claim is free");
+}
diff --git a/crates/openhuman-core/src/storage/documents.rs b/crates/openhuman-core/src/storage/documents.rs
index 55aa66733a..662a84408e 100644
--- a/crates/openhuman-core/src/storage/documents.rs
+++ b/crates/openhuman-core/src/storage/documents.rs
@@ -215,7 +215,8 @@ impl Repo {
/// Opens the same owner scope with an additional storage-driver write
/// condition. The backend remains responsible for composing any host
- /// profile fence with `condition` atomically.
+ /// profile fence with `condition` atomically. Collection declarations
+ /// are not bound to it (see `claim_bound`).
///
/// Repos made with [`Repo::over`] have no backend/scope origin and cannot
/// be rebound safely; callers must use an explicitly opened repo for
@@ -229,9 +230,7 @@ impl Repo {
})?;
let scope = Scope::new(&origin.scope)
.with_context(|| format!("[{}] parse the storage scope", self.domain))?;
- let scoped = origin
- .backend
- .for_scope_conditioned(&scope, condition)
+ let scoped = super::claim_bound::claim_bound(origin.backend.as_ref(), &scope, condition)
.with_context(|| {
format!("[{}] bind the import claim to storage writes", self.domain)
})?;
diff --git a/crates/openhuman-core/src/storage/fenced_backend.rs b/crates/openhuman-core/src/storage/fenced_backend.rs
index 1354ce7811..6a0199024b 100644
--- a/crates/openhuman-core/src/storage/fenced_backend.rs
+++ b/crates/openhuman-core/src/storage/fenced_backend.rs
@@ -91,6 +91,17 @@ impl FencedBackend {
.map_err(|error| error.into_storage())?;
Ok(Some((fence.clone(), fence.write_condition())))
}
+
+ /// The handle `scope`'s collections are declared through: the inner
+ /// backend's, without the lease's driver condition, which MongoDB will
+ /// not declare under (#8422). The fence still checks its lease locally
+ /// before each declaration.
+ fn declarations(
+ &self,
+ scope: &Scope,
+ ) -> Result<Arc<dyn tinystoragedrivers_api::DocumentStore>, StorageError> {
+ Ok(Arc::clone(self.inner.for_scope(scope)?.documents()))
+ }
}
/// Wrap the process backend with its shared fence registry.
@@ -106,12 +117,20 @@ impl StorageBackend for FencedBackend {
fn for_scope(&self, scope: &Scope) -> Result<Storage, StorageError> {
match self.condition_for(scope)? {
Some((fence, condition)) => {
- let storage = match condition {
- Some(condition) => self.inner.for_scope_conditioned(scope, &condition)?,
- None => self.inner.for_scope(scope)?,
+ let (storage, declarations) = match condition {
+ Some(condition) => (
+ self.inner.for_scope_conditioned(scope, &condition)?,
+ self.declarations(scope)?,
+ ),
+ None => {
+ let storage = self.inner.for_scope(scope)?;
+ let declarations = Arc::clone(storage.documents());
+ (storage, declarations)
+ }
};
Ok(super::fenced_ports::wrap(
storage,
+ declarations,
fence,
Arc::clone(self.registry.as_ref().expect("fenced backend has a clock")),
))
@@ -135,6 +154,7 @@ impl StorageBackend for FencedBackend {
};
Ok(super::fenced_ports::wrap(
storage,
+ self.declarations(scope)?,
fence,
Arc::clone(self.registry.as_ref().expect("fenced backend has a clock")),
))
diff --git a/crates/openhuman-core/src/storage/fenced_backend_tests.rs b/crates/openhuman-core/src/storage/fenced_backend_tests.rs
index 1d6cc7676b..9246b5d44f 100644
--- a/crates/openhuman-core/src/storage/fenced_backend_tests.rs
+++ b/crates/openhuman-core/src/storage/fenced_backend_tests.rs
@@ -315,3 +315,89 @@ async fn captured_profile_sweeps_cannot_follow_a_replacement_epoch() {
#[path = "fenced_backend_upstream_tests.rs"]
mod upstream_tests;
+
+#[tokio::test]
+async fn fenced_handles_declare_collections_on_a_backend_that_refuses_conditioned_declarations() {
+ // Leases kept in the backend put a driver condition on every profile
+ // handle; MongoDB refuses to declare collections under one (#8422).
+ let shared = shared();
+ let refusing = crate::storage::test_support::refusing_conditioned_declarations(Arc::clone(
+ &shared.backend,
+ ));
+ let node = Node::new("node-a", Arc::clone(&refusing));
+ let (_grant, fence) = node.acquire("alice").await;
+ assert!(
+ fence.write_condition().is_some(),
+ "a lease kept in the backend has a driver condition"
+ );
+ let storage = node.storage();
+ let spec = CollectionSpec::new("declared_under_lease");
+ storage.documents().ensure_collection(&spec).await.unwrap();
+ storage
+ .documents()
+ .validate_collection_spec(&spec)
+ .await
+ .unwrap();
+ storage
+ .documents()
+ .put(
+ "declared_under_lease",
+ "row",
+ json!({}),
+ Precondition::Absent,
+ )
+ .await
+ .unwrap();
+
+ // An import claim on top of the lease (an admitted profile's import),
+ // taken through the fenced backend and released before it is used, so
+ // its condition no longer holds.
+ let profile = Scope::new("profile:alice").unwrap();
+ let fenced: Arc<dyn StorageBackend> = Arc::new(FencedBackend::new(
+ Arc::clone(&refusing),
+ Arc::clone(&node.fences),
+ ));
+ let claims = crate::storage::documents::Repo::on(
+ &fenced,
+ &crate::storage::Scope::from(profile.clone()),
+ "fence-claim-test",
+ Vec::new,
+ )
+ .unwrap();
+ let stale = tokio::task::spawn_blocking(move || {
+ crate::storage::import_state::with_claim(&claims, "fence_test", "import", |condition| {
+ Ok(condition.clone())
+ })
+ })
+ .await
+ .unwrap()
+ .unwrap()
+ .expect("the claim is free");
+
+ let conditioned = node
+ .backend
+ .for_scope_conditioned(&profile, &stale)
+ .unwrap();
+ let docs = conditioned.documents();
+ docs.ensure_collection(&CollectionSpec::new("declared_under_claim"))
+ .await
+ .expect("a lease and a lost claim may still declare a collection");
+ let written = docs
+ .put(
+ "declared_under_claim",
+ "stale",
+ json!({}),
+ Precondition::Absent,
+ )
+ .await;
+ assert!(
+ written.is_err(),
+ "a lost claim cannot write under the lease"
+ );
+ assert!(storage
+ .documents()
+ .get("declared_under_claim", "stale")
+ .await
+ .unwrap()
+ .is_none());
+}
diff --git a/crates/openhuman-core/src/storage/fenced_ports.rs b/crates/openhuman-core/src/storage/fenced_ports.rs
index 7ea23e0490..48a2788143 100644
--- a/crates/openhuman-core/src/storage/fenced_ports.rs
+++ b/crates/openhuman-core/src/storage/fenced_ports.rs
@@ -47,10 +47,21 @@ async fn classify_driver_refusal<T>(
}
}
-pub(super) fn wrap(storage: Storage, fence: Arc<LeaseFence>, clock: Arc<FenceRegistry>) -> Storage {
+/// `storage` guarded by `fence`. Collection declarations go through
+/// `declarations`, a handle without the lease's driver condition: a
+/// declaration is idempotent schema metadata, and drivers disagree on
+/// whether a conditioned handle may make one (MongoDB refuses, #8422). They
+/// still pass the fence's local lease check first.
+pub(super) fn wrap(
+ storage: Storage,
+ declarations: Arc<dyn DocumentStore>,
+ fence: Arc<LeaseFence>,
+ clock: Arc<FenceRegistry>,
+) -> Storage {
Storage::new(
Arc::new(GuardedDocuments {
inner: Arc::clone(storage.documents()),
+ declarations,
fence: Arc::clone(&fence),
clock: Arc::clone(&clock),
}),
@@ -80,6 +91,8 @@ pub(super) fn wrap(storage: Storage, fence: Arc<LeaseFence>, clock: Arc<FenceReg
struct GuardedDocuments {
inner: Arc<dyn DocumentStore>,
+ /// Collection declarations only, without the lease's driver condition.
+ declarations: Arc<dyn DocumentStore>,
fence: Arc<LeaseFence>,
clock: Arc<FenceRegistry>,
}
@@ -99,14 +112,14 @@ impl DocumentStore for GuardedDocuments {
async fn ensure_collection(&self, s: &CollectionSpec) -> Result<()> {
check(&self.fence, &self.clock)?;
classify_driver_refusal(
- self.inner.ensure_collection(s).await,
+ self.declarations.ensure_collection(s).await,
&self.fence,
&self.clock,
)
.await
}
async fn validate_collection_spec(&self, s: &CollectionSpec) -> Result<()> {
- self.inner.validate_collection_spec(s).await
+ self.declarations.validate_collection_spec(s).await
}
async fn get(&self, c: &str, id: &str) -> Result<Option<Versioned<Value>>> {
self.inner.get(c, id).await
diff --git a/crates/openhuman-core/src/storage/import_state.rs b/crates/openhuman-core/src/storage/import_state.rs
index e264c83dc4..2ba4ecd88d 100644
--- a/crates/openhuman-core/src/storage/import_state.rs
+++ b/crates/openhuman-core/src/storage/import_state.rs
@@ -53,9 +53,11 @@ pub fn step_id(kind: &str, id: &str) -> String {
/// The owner name used by module importers.
pub const HOST_OWNER: &str = "host";
-/// Returns a backend whose scope handles carry `condition` on every write.
-/// Calling `for_scope_conditioned` on the wrapped backend composes the
-/// condition with any profile-level condition before opening the target.
+/// Returns a backend whose scope handles carry `condition` on every write,
+/// except collection declarations, which every driver must accept from an
+/// importer (see `claim_bound`). Calling `for_scope_conditioned` on the
+/// wrapped backend composes the condition with any profile-level condition
+/// before opening the target.
pub(crate) fn backend_with_condition(
backend: std::sync::Arc<dyn StorageBackend>,
condition: WriteCondition,
@@ -82,7 +84,7 @@ impl StorageBackend for ClaimBoundBackend {
}
fn for_scope(&self, scope: &tinystoragedrivers::Scope) -> Result<Storage, StorageError> {
- self.backend.for_scope_conditioned(scope, &self.condition)
+ super::claim_bound::claim_bound(self.backend.as_ref(), scope, &self.condition)
}
fn for_scope_conditioned(
@@ -95,7 +97,7 @@ impl StorageBackend for ClaimBoundBackend {
.clone()
.and(condition.clone())
.map_err(|error| StorageError::invalid_input(error.to_string()))?;
- self.backend.for_scope_conditioned(scope, &condition)
+ super::claim_bound::claim_bound(self.backend.as_ref(), scope, &condition)
}
}
diff --git a/crates/openhuman-core/src/storage/mod.rs b/crates/openhuman-core/src/storage/mod.rs
index f106741cdb..bca183e74e 100644
--- a/crates/openhuman-core/src/storage/mod.rs
+++ b/crates/openhuman-core/src/storage/mod.rs
@@ -27,6 +27,7 @@
pub mod agents;
pub mod blob_sweep;
pub mod boot;
+mod claim_bound;
pub mod config;
pub mod documents;
pub mod fence;
diff --git a/crates/openhuman-core/src/storage/test_support.rs b/crates/openhuman-core/src/storage/test_support.rs
index 484b0d4282..136d05ef52 100644
--- a/crates/openhuman-core/src/storage/test_support.rs
+++ b/crates/openhuman-core/src/storage/test_support.rs
@@ -168,3 +168,139 @@ pub fn sqlite_backend_in(
url,
})
}
+
+/// `inner`, but with conditioned document handles that refuse collection
+/// declarations the way MongoDB's driver does (#8422), so storage tests
+/// reproduce MongoDB without a server.
+pub(crate) fn refusing_conditioned_declarations(
+ inner: Arc<dyn StorageBackend>,
+) -> Arc<dyn StorageBackend> {
+ Arc::new(RefusesConditionedDeclarations(inner))
+}
+
+#[derive(Debug)]
+struct RefusesConditionedDeclarations(Arc<dyn StorageBackend>);
+
+impl StorageBackend for RefusesConditionedDeclarations {
+ fn capabilities(&self) -> tinystoragedrivers_types::Capabilities {
+ self.0.capabilities()
+ }
+
+ fn for_scope(
+ &self,
+ scope: &tinystoragedrivers::Scope,
+ ) -> Result<tinystoragedrivers_api::Storage, tinystoragedrivers::StorageError> {
+ self.0.for_scope(scope)
+ }
+
+ fn for_scope_conditioned(
+ &self,
+ scope: &tinystoragedrivers::Scope,
+ condition: &tinystoragedrivers::WriteCondition,
+ ) -> Result<tinystoragedrivers_api::Storage, tinystoragedrivers::StorageError> {
+ let storage = self.0.for_scope_conditioned(scope, condition)?;
+ Ok(tinystoragedrivers_api::Storage::new(
+ Arc::new(RefusingDeclarations(Arc::clone(storage.documents()))),
+ Arc::clone(storage.streams()),
+ Arc::clone(storage.kv()),
+ Arc::clone(storage.blobs()),
+ Arc::clone(storage.queues()),
+ Arc::clone(storage.secrets()),
+ ))
+ }
+}
+
+/// A conditioned document handle that refuses declarations and passes
+/// everything else through.
+#[derive(Debug)]
+struct RefusingDeclarations(Arc<dyn tinystoragedrivers_api::DocumentStore>);
+
+mod refusing_declarations {
+ use serde_json::Value;
+ use tinystoragedrivers_api::{DocumentStore, DocumentWatch};
+ use tinystoragedrivers_types::{
+ Capabilities, Capability, CollectionSpec, Filter, Page, Precondition, Query, ReadCheck,
+ Result, SearchHit, Sort, StorageError, Version, Versioned, WatchOptions, WriteOp,
+ WriteOptions, WriteResult,
+ };
+
+ #[async_trait::async_trait]
+ impl DocumentStore for super::RefusingDeclarations {
+ fn capabilities(&self) -> Capabilities {
+ self.0.capabilities()
+ }
+ async fn ensure_collection(&self, _: &CollectionSpec) -> Result<()> {
+ Err(StorageError::unsupported(
+ Capability::ConditionalWrites,
+ "conditioned MongoDB handles cannot mutate collection declarations",
+ ))
+ }
+ async fn get(&self, c: &str, id: &str) -> Result<Option<Versioned<Value>>> {
+ self.0.get(c, id).await
+ }
+ async fn put(&self, c: &str, id: &str, v: Value, p: Precondition) -> Result<Version> {
+ self.0.put(c, id, v, p).await
+ }
+ async fn put_with(
+ &self,
+ c: &str,
+ id: &str,
+ v: Value,
+ p: Precondition,
+ o: WriteOptions,
+ ) -> Result<Version> {
+ self.0.put_with(c, id, v, p, o).await
+ }
+ async fn delete(&self, c: &str, id: &str, p: Precondition) -> Result<bool> {
+ self.0.delete(c, id, p).await
+ }
+ async fn query(&self, c: &str, q: &Query) -> Result<Page<Versioned<Value>>> {
+ self.0.query(c, q).await
+ }
+ async fn count(&self, c: &str, f: &Filter) -> Result<u64> {
+ self.0.count(c, f).await
+ }
+ async fn delete_where(&self, c: &str, f: &Filter) -> Result<u64> {
+ self.0.delete_where(c, f).await
+ }
+ async fn claim(
+ &self,
+ c: &str,
+ f: &Filter,
+ s: &[Sort],
+ p: &Value,
+ ) -> Result<Option<Versioned<Value>>> {
+ self.0.claim(c, f, s, p).await
+ }
+ async fn atomic_batch(&self, o: Vec<WriteOp>) -> Result<Vec<WriteResult>> {
+ self.0.atomic_batch(o).await
+ }
+ async fn atomic_batch_checked(
+ &self,
+ c: Vec<ReadCheck>,
+ o: Vec<WriteOp>,
+ ) -> Result<Vec<WriteResult>> {
+ self.0.atomic_batch_checked(c, o).await
+ }
+ async fn validate_collection_spec(&self, s: &CollectionSpec) -> Result<()> {
+ self.0.validate_collection_spec(s).await
+ }
+ async fn search(&self, c: &str, t: &str, l: usize) -> Result<Vec<SearchHit>> {
+ self.0.search(c, t, l).await
+ }
+ async fn collections(&self, p: &str) -> Result<Vec<String>> {
+ self.0.collections(p).await
+ }
+ async fn watch(
+ &self,
+ c: &str,
+ f: &Filter,
+ o: &WatchOptions,
+ ) -> Result<Box<dyn DocumentWatch>> {
+ self.0.watch(c, f, o).await
+ }
+ async fn drop_collection(&self, c: &str) -> Result<()> {
+ self.0.drop_collection(c).await
+ }
+ }
+}