Skip to content

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

feat(composio): add per-user scope storage

Steven Enamakel69f8edffcdd3
diff --git a/crates/openhuman-core/src/integrations/composio/file_store.rs b/crates/openhuman-core/src/integrations/composio/file_store.rs
index a515f4ccf9..1fbdc1058f 100644
--- a/crates/openhuman-core/src/integrations/composio/file_store.rs
+++ b/crates/openhuman-core/src/integrations/composio/file_store.rs
@@ -72,6 +72,43 @@ where
})
}
+/// Applies `change` to the value at `path` and writes it back when `change`
+/// reports a change, returning its result.
+///
+/// With a storage backend this is a compare-and-swap loop, so two cores that
+/// share the scope never lose each other's update (`change` is retried on a
+/// conflict and must be repeatable). Without one it is the process-wide
+/// [`lock`] around a load and a save.
+///
+/// # Errors
+///
+/// The value cannot be read or written.
+pub(crate) async fn update<T, R>(
+ path: &Path,
+ change: impl Fn(&mut T) -> (R, bool) + Send + 'static,
+) -> Result<R, String>
+where
+ T: DeserializeOwned + Serialize + Default + 'static,
+ R: Send + 'static,
+{
+ if let Some(docs) =
+ super::file_store_documents::current().map_err(|e| format!("[composio:store] {e:#}"))?
+ {
+ let owned = path.to_path_buf();
+ return tokio::task::spawn_blocking(move || docs.update(&owned, change))
+ .await
+ .map_err(|error| format!("[composio:store] updating {} failed: {error}", path.display()))?
+ .map_err(|error| format!("[composio:store] updating {} failed: {error:#}", path.display()));
+ }
+ let _guard = lock().await;
+ let mut value: T = load(path).await?;
+ let (result, changed) = change(&mut value);
+ if changed {
+ save(path, &value).await?;
+ }
+ Ok(result)
+}
+
/// Writes `value` to `path` atomically (temp file, then rename).
///
/// # Errors
diff --git a/crates/openhuman-core/src/integrations/composio/file_store_documents.rs b/crates/openhuman-core/src/integrations/composio/file_store_documents.rs
index 599ecce3d8..9e52d792d7 100644
--- a/crates/openhuman-core/src/integrations/composio/file_store_documents.rs
+++ b/crates/openhuman-core/src/integrations/composio/file_store_documents.rs
@@ -19,7 +19,7 @@ use anyhow::{anyhow, Result};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::json;
-use tinystoragedrivers::{CollectionSpec, Precondition};
+use tinystoragedrivers::{CollectionSpec, ErrorKind, Precondition, StorageError};
use crate::storage::documents::Repo;
@@ -72,6 +72,59 @@ impl Docs {
}
}
+ /// Read-modify-write of the value for the file `path` names, under
+ /// compare-and-swap so two cores sharing the scope never lose each other's
+ /// change. `change` returns its result and whether it changed the value
+ /// (an unchanged value is not written); it is retried on a conflict, so it
+ /// must be repeatable.
+ pub(super) fn update<T, R>(
+ &self,
+ path: &Path,
+ change: impl Fn(&mut T) -> (R, bool) + Send + 'static,
+ ) -> Result<R>
+ where
+ T: DeserializeOwned + Serialize + Default,
+ R: Send + 'static,
+ {
+ let id = id_of(path)?;
+ self.0.run(|docs| async move {
+ for _ in 0..crate::storage::documents::CAS_ATTEMPTS {
+ let stored = docs.get(STATE, &id).await?;
+ let (mut value, precondition) = match &stored {
+ Some(stored) => (
+ stored
+ .doc
+ .get("value")
+ .cloned()
+ .map(serde_json::from_value)
+ .transpose()
+ .map_err(|e| StorageError::invalid_input(e.to_string()))?
+ .unwrap_or_default(),
+ stored.unchanged(),
+ ),
+ None => (T::default(), Precondition::Absent),
+ };
+ let (result, changed) = change(&mut value);
+ if !changed {
+ return Ok(result);
+ }
+ let doc = json!({
+ "value": serde_json::to_value(&value)
+ .map_err(|e| StorageError::invalid_input(e.to_string()))?
+ });
+ match docs.put(STATE, &id, doc, precondition).await {
+ Ok(_) => return Ok(result),
+ Err(error) if error.kind() == ErrorKind::Conflict => {}
+ Err(error) => return Err(error),
+ }
+ }
+ Err(StorageError::conflict(format!(
+ "{STATE}/{id} kept changing under {} attempts",
+ crate::storage::documents::CAS_ATTEMPTS
+ )))
+ })
+ }
+
pub(super) fn save<T: Serialize>(&self, path: &Path, value: &T) -> Result<()> {
let id = id_of(path)?;
let doc = json!({ "value": serde_json::to_value(value)? });
diff --git a/crates/openhuman-core/src/integrations/composio/identity_store.rs b/crates/openhuman-core/src/integrations/composio/identity_store.rs
index 818df8d8a9..f2a9377083 100644
--- a/crates/openhuman-core/src/integrations/composio/identity_store.rs
+++ b/crates/openhuman-core/src/integrations/composio/identity_store.rs
@@ -43,38 +43,40 @@ pub async fn persist_provider_profile(
}
let path = file_store::path(config, IDENTITIES_FILE);
- let _guard = file_store::lock().await;
- let mut identities: Vec<ConnectedIdentity> = file_store::load(&path).await?;
- let index = match identities
- .iter()
- .position(|id| id.source == toolkit && id.identifier == identifier)
- {
- Some(index) => index,
- None => {
- identities.push(ConnectedIdentity {
- source: toolkit.clone(),
- identifier: identifier.clone(),
- ..ConnectedIdentity::default()
- });
- identities.len() - 1
- }
- };
- let entry = &mut identities[index];
let written = rows.len();
- for (kind, value) in rows {
- let slot = match kind {
- IdentityKind::DisplayName => &mut entry.display_name,
- IdentityKind::Email => &mut entry.email,
- IdentityKind::Handle => &mut entry.handle,
- IdentityKind::Phone => &mut entry.phone,
- IdentityKind::UserId => &mut entry.user_id,
- IdentityKind::AvatarUrl => &mut entry.avatar_url,
- IdentityKind::ProfileUrl => &mut entry.profile_url,
+ let (key_source, key_identifier) = (toolkit.clone(), identifier.clone());
+ file_store::update(&path, move |identities: &mut Vec<ConnectedIdentity>| {
+ let index = match identities
+ .iter()
+ .position(|id| id.source == key_source && id.identifier == key_identifier)
+ {
+ Some(index) => index,
+ None => {
+ identities.push(ConnectedIdentity {
+ source: key_source.clone(),
+ identifier: key_identifier.clone(),
+ ..ConnectedIdentity::default()
+ });
+ identities.len() - 1
+ }
};
- *slot = Some(value);
- }
- identities.sort_by(|a, b| (&a.source, &a.identifier).cmp(&(&b.source, &b.identifier)));
- file_store::save(&path, &identities).await?;
+ let entry = &mut identities[index];
+ for (kind, value) in rows.iter().cloned() {
+ let slot = match kind {
+ IdentityKind::DisplayName => &mut entry.display_name,
+ IdentityKind::Email => &mut entry.email,
+ IdentityKind::Handle => &mut entry.handle,
+ IdentityKind::Phone => &mut entry.phone,
+ IdentityKind::UserId => &mut entry.user_id,
+ IdentityKind::AvatarUrl => &mut entry.avatar_url,
+ IdentityKind::ProfileUrl => &mut entry.profile_url,
+ };
+ *slot = Some(value);
+ }
+ identities.sort_by(|a, b| (&a.source, &a.identifier).cmp(&(&b.source, &b.identifier)));
+ ((), true)
+ })
+ .await?;
tracing::debug!(
toolkit = %toolkit,
@@ -157,21 +159,19 @@ pub async fn delete_connected_identity_facets(
let identifier = normalize_connection_identifier(identifier);
let path = file_store::path(config, IDENTITIES_FILE);
- let _guard = file_store::lock().await;
- let mut identities: Vec<ConnectedIdentity> = file_store::load(&path).await?;
- let mut deleted = 0usize;
- identities.retain(|id| {
- if id.source == source && id.identifier == identifier {
- deleted += field_count(id);
- false
- } else {
- true
- }
- });
- if deleted > 0 {
- file_store::save(&path, &identities).await?;
- }
- Ok(deleted)
+ file_store::update(&path, move |identities: &mut Vec<ConnectedIdentity>| {
+ let mut deleted = 0usize;
+ identities.retain(|id| {
+ if id.source == source && id.identifier == identifier {
+ deleted += field_count(id);
+ false
+ } else {
+ true
+ }
+ });
+ (deleted, deleted > 0)
+ })
+ .await
}
/// How many identity fields an identity carries.
diff --git a/crates/openhuman-core/src/integrations/composio/ops/user_scopes.rs b/crates/openhuman-core/src/integrations/composio/ops/user_scopes.rs
index 847a7c0743..a293a73b36 100644
--- a/crates/openhuman-core/src/integrations/composio/ops/user_scopes.rs
+++ b/crates/openhuman-core/src/integrations/composio/ops/user_scopes.rs
@@ -89,10 +89,12 @@ pub(crate) async fn save(
return Err("user_scopes: toolkit must not be empty".to_string());
}
let path = file_store::path(config, USER_SCOPES_FILE);
- let _guard = file_store::lock().await;
- let mut prefs: ScopeFile = file_store::load(&path).await?;
- prefs.insert(key.clone(), pref);
- file_store::save(&path, &prefs).await?;
+ let entry_key = key.clone();
+ file_store::update(&path, move |prefs: &mut ScopeFile| {
+ prefs.insert(entry_key.clone(), pref);
+ ((), true)
+ })
+ .await?;
tracing::info!(
toolkit = %key,