Skip to content

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

feat(profiles): add storage schema for profile registry

Steven Enamakelee7f81be853a
diff --git a/crates/openhuman-core/src/profiles/registry.rs b/crates/openhuman-core/src/profiles/registry.rs
index 09d210af7a..21007d40e2 100644
--- a/crates/openhuman-core/src/profiles/registry.rs
+++ b/crates/openhuman-core/src/profiles/registry.rs
@@ -3,7 +3,8 @@
//! With a storage backend installed, every node of a deployment reads one
//! registry: collection [`REGISTRY_COLLECTION`] of the shared
//! [`CLUSTER_SCOPE`](crate::storage::lease::CLUSTER_SCOPE), one
-//! [`ProfileMeta`] document per profile. Without one it is the
+//! document per profile (`{profile_id, layout_version}`, the creation time in
+//! the record's metadata; [`super::storage_schema`]). Without one it is the
//! `profile.toml` file beside each profile's state
//! (`<root>/users/<id>/profile.toml`), as before.
//!
@@ -14,21 +15,42 @@
use std::path::PathBuf;
use std::sync::Arc;
-use tinystoragedrivers::{CollectionSpec, DocumentStoreExt, ErrorKind, Precondition, Query, Scope};
+use tinystoragedrivers::{
+ CollectionSpec, DocumentStoreExt, ErrorKind, Precondition, Query, Scope, ScopedStorage,
+ Versioned, WriteOptions,
+};
use super::layout::{self, ProfileLayout};
use super::types::{ProfileId, ProfileMeta};
+use super::storage_schema::migrate_cluster;
+pub use super::storage_schema::REGISTRY_COLLECTION;
use crate::storage::lease::CLUSTER_SCOPE;
+use crate::storage::schema_support::key_of;
use crate::storage::{DocumentStore, StorageBackend};
-/// The collection the profile records live in, under the cluster scope.
-pub const REGISTRY_COLLECTION: &str = "profiles";
+/// The profile a registry document holds: the body's fields, and the creation
+/// time (Unix seconds) from the record's metadata.
+fn meta_of(stored: &Versioned<serde_json::Value>) -> Result<ProfileMeta, serde_json::Error> {
+ let mut doc = stored.doc.clone();
+ doc["created_at"] = (stored.meta.created_ms.max(0) / 1000).into();
+ serde_json::from_value(doc)
+}
+
+/// The body a profile is stored as: its fields without the creation time.
+fn body_of(meta: &ProfileMeta) -> Result<serde_json::Value, serde_json::Error> {
+ let mut doc = serde_json::to_value(meta)?;
+ if let Some(fields) = doc.as_object_mut() {
+ fields.remove("created_at");
+ }
+ Ok(doc)
+}
/// Where provisioned profiles are recorded. See the module docs.
pub enum ProfileRegistry {
/// One document per profile in the shared backend.
Documents {
docs: Arc<dyn DocumentStore>,
+ scoped: ScopedStorage,
declared: tokio::sync::OnceCell<()>,
},
/// `profile.toml` under each profile's directory below `root`.
@@ -63,6 +85,7 @@ impl ProfileRegistry {
let scoped = backend.for_scope(&scope).map_err(|e| e.to_string())?;
Ok(Self::Documents {
docs: Arc::clone(scoped.documents()),
+ scoped,
declared: tokio::sync::OnceCell::new(),
})
}
@@ -73,13 +96,20 @@ impl ProfileRegistry {
}
async fn docs(&self) -> Result<Option<&Arc<dyn DocumentStore>>, String> {
- let Self::Documents { docs, declared } = self else {
+ let Self::Documents {
+ docs,
+ scoped,
+ declared,
+ } = self
+ else {
return Ok(None);
};
declared
.get_or_try_init(|| async {
docs.ensure_collection(&CollectionSpec::new(REGISTRY_COLLECTION))
- .await
+ .await?;
+ // The cluster scope is outside boot's per-tenant migration.
+ migrate_cluster(scoped).await
})
.await
.map_err(|e| format!("profile registry: {e}"))?;
@@ -93,14 +123,15 @@ impl ProfileRegistry {
/// When the record cannot be read or parsed.
pub async fn get(&self, id: &ProfileId) -> Result<Option<ProfileMeta>, String> {
if let Some(docs) = self.docs().await? {
+ let key = key_of(id.as_str()).map_err(|e| format!("profile {id}: {e}"))?;
let Some(stored) = docs
- .get(REGISTRY_COLLECTION, id.as_str())
+ .get(REGISTRY_COLLECTION, &key)
.await
.map_err(|e| format!("reading profile {id}: {e}"))?
else {
return Ok(None);
};
- return serde_json::from_value(stored.doc)
+ return meta_of(&stored)
.map(Some)
.map_err(|e| format!("parsing profile {id}: {e}"));
}
@@ -119,10 +150,19 @@ impl ProfileRegistry {
pub async fn create(&self, meta: &ProfileMeta) -> Result<bool, String> {
let id = &meta.profile_id;
if let Some(docs) = self.docs().await? {
- let doc =
- serde_json::to_value(meta).map_err(|e| format!("encoding profile {id}: {e}"))?;
+ let doc = body_of(meta).map_err(|e| format!("encoding profile {id}: {e}"))?;
+ let key = key_of(id.as_str()).map_err(|e| format!("profile {id}: {e}"))?;
+ let created_ms = i64::try_from(meta.created_at)
+ .unwrap_or(i64::MAX / 1000)
+ .saturating_mul(1000);
return match docs
- .put(REGISTRY_COLLECTION, id.as_str(), doc, Precondition::Absent)
+ .put_with(
+ REGISTRY_COLLECTION,
+ &key,
+ doc,
+ Precondition::Absent,
+ WriteOptions::new().created_ms(created_ms),
+ )
.await
{
Ok(_) => Ok(true),
@@ -152,8 +192,9 @@ impl ProfileRegistry {
/// When the record cannot be removed.
pub async fn remove(&self, id: &ProfileId) -> Result<bool, String> {
if let Some(docs) = self.docs().await? {
+ let key = key_of(id.as_str()).map_err(|e| format!("profile {id}: {e}"))?;
return docs
- .delete(REGISTRY_COLLECTION, id.as_str(), Precondition::None)
+ .delete(REGISTRY_COLLECTION, &key, Precondition::None)
.await
.map_err(|e| format!("forgetting profile {id}: {e}"));
}
@@ -174,7 +215,7 @@ impl ProfileRegistry {
.await
.map_err(|e| format!("listing profiles: {e}"))?;
for doc in stored {
- match serde_json::from_value::<ProfileMeta>(doc.doc) {
+ match meta_of(&doc) {
Ok(meta) => found.push(meta),
Err(error) => {
log::warn!("[profiles][registry] skipping record {}: {error}", doc.id);
diff --git a/crates/openhuman-core/src/profiles/storage_schema.rs b/crates/openhuman-core/src/profiles/storage_schema.rs
new file mode 100644
index 0000000000..195c3cd02a
--- /dev/null
+++ b/crates/openhuman-core/src/profiles/storage_schema.rs
@@ -0,0 +1,87 @@
+//! The `profiles` owner's storage schema: the registry of provisioned
+//! profiles, kept in the shared `cluster` scope.
+//!
+//! | v1 | v2 | scope |
+//! |---|---|---|
+//! | `profiles` (`{profile_id, created_at (seconds), layout_version}`) | `profiles.registry` (`{profile_id, layout_version}`; creation time in tsd metadata) | cluster |
+//!
+//! The cluster scope is not a tenant, so boot's per-tenant migration never
+//! visits it; [`migrate_cluster`] runs this owner's steps over it, the first
+//! time a registry opens the shared backend.
+
+use serde_json::Value;
+use tinystoragedrivers::schema::{
+ MigrateOptions, Registry, Schema, ScopeClass, SourceRecord, Step, TargetRecord,
+};
+use tinystoragedrivers::{CollectionSpec, Result, ScopedStorage};
+
+use crate::storage::schema_support::{key_of, owner, Body};
+
+/// The v2 collection: one document per profile.
+pub const REGISTRY_COLLECTION: &str = "profiles.registry";
+/// The v1 name.
+pub(super) const LEGACY_REGISTRY_COLLECTION: &str = "profiles";
+const SCHEMA: u32 = 2;
+
+/// What the profile registry keeps and the step from the v1 collection.
+#[must_use]
+pub fn storage_schema() -> Schema {
+ Schema::new(owner("profiles"))
+ .collection_with(
+ SCHEMA,
+ CollectionSpec::new(REGISTRY_COLLECTION),
+ ScopeClass::Cluster,
+ )
+ .step(
+ Step::new("registry_v2", REGISTRY_COLLECTION, 1, SCHEMA, registry_v2)
+ .source(LEGACY_REGISTRY_COLLECTION),
+ )
+}
+
+fn registry_v2(batch: Vec<SourceRecord>) -> Result<Vec<TargetRecord>> {
+ batch
+ .into_iter()
+ .map(|record| {
+ let old = &record.body;
+ let body = Body::new()
+ .copy(old, "profile_id")
+ .set(
+ "layout_version",
+ old.get("layout_version")
+ .and_then(Value::as_u64)
+ .unwrap_or_default(),
+ )
+ .build();
+ // Unix seconds become the record's creation time.
+ let created_ms = old
+ .get("created_at")
+ .and_then(Value::as_i64)
+ .map_or(record.meta.created_ms, |secs| secs.saturating_mul(1000));
+ Ok(
+ TargetRecord::new(REGISTRY_COLLECTION, key_of(&record.id)?, body)
+ .created_ms(created_ms),
+ )
+ })
+ .collect()
+}
+
+/// Runs this owner's steps over the cluster scope `scoped`. Idempotent: a
+/// finished step is skipped.
+///
+/// # Errors
+///
+/// A storage error; the registry then reads the unmigrated records as absent
+/// until the next open retries.
+pub async fn migrate_cluster(scoped: &ScopedStorage) -> Result<()> {
+ let registry = Registry::compose([storage_schema()])?;
+ scoped
+ .documents()
+ .ensure_collection(&CollectionSpec::new(REGISTRY_COLLECTION))
+ .await?;
+ registry.migrate(scoped, &MigrateOptions::new()).await?;
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "storage_schema_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/profiles/storage_schema_tests.rs b/crates/openhuman-core/src/profiles/storage_schema_tests.rs
new file mode 100644
index 0000000000..905b6039c3
--- /dev/null
+++ b/crates/openhuman-core/src/profiles/storage_schema_tests.rs
@@ -0,0 +1,43 @@
+use super::*;
+use serde_json::json;
+use tinystoragedrivers::{DocumentStoreExt, Meta, MemoryStorage, Precondition, Scope, StorageBackend};
+
+#[test]
+fn a_registry_row_loses_its_seconds_field_and_keeps_its_creation_time() {
+ let out = registry_v2(vec![SourceRecord {
+ id: "alice".into(),
+ body: json!({ "profile_id": "alice", "created_at": 1_700_000_000_u64, "layout_version": 2 }),
+ meta: Meta::unknown(),
+ }])
+ .unwrap();
+ assert_eq!(out[0].collection, REGISTRY_COLLECTION);
+ assert_eq!(out[0].id, "alice");
+ assert_eq!(out[0].body, json!({ "profile_id": "alice", "layout_version": 2 }));
+ assert_eq!(out[0].created_ms, Some(1_700_000_000_000));
+}
+
+#[tokio::test]
+async fn migrate_cluster_moves_the_v1_registry_into_the_v2_collection() {
+ let backend = MemoryStorage::new();
+ let scoped = backend.for_scope(&Scope::cluster()).unwrap();
+ let docs = scoped.documents();
+ docs.ensure_collection(&CollectionSpec::new("profiles")).await.unwrap();
+ docs.put(
+ "profiles",
+ "alice",
+ json!({ "profile_id": "alice", "created_at": 5, "layout_version": 2 }),
+ Precondition::Absent,
+ )
+ .await
+ .unwrap();
+ migrate_cluster(&scoped).await.unwrap();
+ migrate_cluster(&scoped).await.unwrap();
+ let moved = docs.get(REGISTRY_COLLECTION, "alice").await.unwrap().unwrap();
+ assert_eq!(moved.doc, json!({ "profile_id": "alice", "layout_version": 2 }));
+ assert_eq!(moved.meta.created_ms, 5000);
+}
+
+#[test]
+fn the_schema_composes_under_its_owner() {
+ tinystoragedrivers::schema::Registry::compose([storage_schema()]).unwrap();
+}