Skip to content

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

feat(composio): add document file store for composio integrations

Steven Enamakel1310748ebeb0
diff --git a/crates/openhuman-core/src/integrations/composio/file_store.rs b/crates/openhuman-core/src/integrations/composio/file_store.rs
index 27421cac04..23c48277f4 100644
--- a/crates/openhuman-core/src/integrations/composio/file_store.rs
+++ b/crates/openhuman-core/src/integrations/composio/file_store.rs
@@ -1,187 +1,85 @@
-//! Small JSON files under the workspace for the Composio host state that is
-//! not memory: connected-account identities and per-toolkit scope prefs.
+//! Composio host state that is not memory: connected-account identities and
+//! per-toolkit scope prefs.
//!
-//! Each file holds one serde value. A read of a missing file is the default
-//! value; a write goes to a sibling temp file first and is renamed over the
-//! target, so a crash mid-write leaves the previous file intact. Every
-//! read-modify-write runs under [`lock`], one process-wide async mutex, so two
-//! concurrent updates cannot lose each other's change.
-
-use std::path::{Path, PathBuf};
+//! Each named value is one serde value in the `composio_state` collection of
+//! the storage backend ([`super::file_store_documents`]), under the acting
+//! agent's scope: the installed backend, or the workspace default when the
+//! host installed none ([`crate::storage::local`]). A read of a missing value
+//! is the default value; every read-modify-write is a compare-and-swap loop,
+//! so two cores that share the scope never lose each other's change.
use serde::de::DeserializeOwned;
use serde::Serialize;
-use tokio::sync::{Mutex, MutexGuard};
use crate::config::Config;
-/// Directory under the workspace holding the integration state files.
-const DIR: &str = "integrations";
-
-/// Connected-account identities file name.
+/// Connected-account identities value name.
pub(crate) const IDENTITIES_FILE: &str = "composio_identities.json";
-/// Per-toolkit agent scope prefs file name.
+/// Per-toolkit agent scope prefs value name.
pub(crate) const USER_SCOPES_FILE: &str = "composio_user_scopes.json";
-/// `<workspace>/integrations/<file>`.
-pub(crate) fn path(config: &Config, file: &str) -> PathBuf {
- config.workspace_dir.join(DIR).join(file)
-}
-
-/// Serialises read-modify-write cycles over the integration state files.
-pub(crate) async fn lock() -> MutexGuard<'static, ()> {
- static LOCK: Mutex<()> = Mutex::const_new(());
- LOCK.lock().await
-}
-
-/// The value stored at `path`, or `T::default()` when the file does not exist.
+/// The value stored under `name`, or `T::default()` when there is none.
///
/// # Errors
///
-/// The file exists but cannot be read or does not parse as `T`.
-pub(crate) async fn load<T>(path: &Path) -> Result<T, String>
+/// The value cannot be read or does not parse as `T`.
+pub(crate) async fn load<T>(config: &Config, name: &'static str) -> Result<T, String>
where
T: DeserializeOwned + Default + Send + 'static,
{
- if let Some(docs) =
- super::file_store_documents::current().map_err(|e| format!("[composio:store] {e:#}"))?
- {
- // The document port is reached through a blocking bridge; keep it off
- // the async worker, under the caller's context.
- let owned = path.to_path_buf();
- return crate::core::runtime::spawn_blocking_scoped(move || docs.load(&owned))
- .await
- .map_err(|error| {
- format!(
- "[composio:store] reading {} failed: {error}",
- path.display()
- )
- })?
- .map_err(|error| {
- format!(
- "[composio:store] reading {} failed: {error:#}",
- path.display()
- )
- });
- }
- let bytes = match tokio::fs::read(path).await {
- Ok(bytes) => bytes,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(T::default()),
- Err(error) => {
- return Err(format!(
- "[composio:store] reading {} failed: {error}",
- path.display()
- ))
- }
- };
- serde_json::from_slice(&bytes).map_err(|error| {
- format!(
- "[composio:store] parsing {} failed: {error}",
- path.display()
- )
- })
+ let docs = super::file_store_documents::current(&config.workspace_dir)
+ .map_err(|e| format!("[composio:store] {e:#}"))?;
+ // The document port is reached through a blocking bridge; keep it off the
+ // async worker, under the caller's context.
+ crate::core::runtime::spawn_blocking_scoped(move || docs.load(name))
+ .await
+ .map_err(|error| format!("[composio:store] reading {name} failed: {error}"))?
+ .map_err(|error| format!("[composio:store] reading {name} failed: {error:#}"))
}
-/// 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.
+/// Applies `change` to the value under `name` and writes it back when
+/// `change` reports a change, returning its result. `change` is retried on a
+/// conflict and must be repeatable.
///
/// # Errors
///
/// The value cannot be read or written.
pub(crate) async fn update<T, R>(
- path: &Path,
+ config: &Config,
+ name: &'static str,
change: impl Fn(&mut T) -> (R, bool) + Send + 'static,
) -> Result<R, String>
where
T: DeserializeOwned + Serialize + Default + Send + '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 crate::core::runtime::spawn_blocking_scoped(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)
+ let docs = super::file_store_documents::current(&config.workspace_dir)
+ .map_err(|e| format!("[composio:store] {e:#}"))?;
+ crate::core::runtime::spawn_blocking_scoped(move || docs.update(name, change))
+ .await
+ .map_err(|error| format!("[composio:store] updating {name} failed: {error}"))?
+ .map_err(|error| format!("[composio:store] updating {name} failed: {error:#}"))
}
-/// Writes `value` to `path` atomically (temp file, then rename).
+/// Replaces the value under `name` with `value`.
///
/// # Errors
///
-/// The directory cannot be created, or the write or rename fails.
-pub(crate) async fn save<T>(path: &Path, value: &T) -> Result<(), String>
+/// The value cannot be serialized or written.
+#[cfg(test)]
+pub(crate) async fn save<T>(config: &Config, name: &'static str, value: &T) -> Result<(), String>
where
T: Serialize,
{
- if let Some(docs) =
- super::file_store_documents::current().map_err(|e| format!("[composio:store] {e:#}"))?
- {
- let owned = path.to_path_buf();
- let value = serde_json::to_value(value)
- .map_err(|error| format!("[composio:store] serializing failed: {error}"))?;
- return crate::core::runtime::spawn_blocking_scoped(move || docs.save(&owned, &value))
- .await
- .map_err(|error| {
- format!(
- "[composio:store] writing {} failed: {error}",
- path.display()
- )
- })?
- .map_err(|error| {
- format!(
- "[composio:store] writing {} failed: {error:#}",
- path.display()
- )
- });
- }
- let bytes = serde_json::to_vec_pretty(value)
+ let docs = super::file_store_documents::current(&config.workspace_dir)
+ .map_err(|e| format!("[composio:store] {e:#}"))?;
+ let value = serde_json::to_value(value)
.map_err(|error| format!("[composio:store] serializing failed: {error}"))?;
- if let Some(dir) = path.parent() {
- tokio::fs::create_dir_all(dir).await.map_err(|error| {
- format!(
- "[composio:store] creating {} failed: {error}",
- dir.display()
- )
- })?;
- }
- let tmp = path.with_extension("json.tmp");
- tokio::fs::write(&tmp, &bytes)
+ crate::core::runtime::spawn_blocking_scoped(move || docs.save(name, &value))
.await
- .map_err(|error| format!("[composio:store] writing {} failed: {error}", tmp.display()))?;
- tokio::fs::rename(&tmp, path).await.map_err(|error| {
- format!(
- "[composio:store] replacing {} failed: {error}",
- path.display()
- )
- })?;
- tracing::debug!(path = %path.display(), bytes = bytes.len(), "[composio:store] saved");
- Ok(())
+ .map_err(|error| format!("[composio:store] writing {name} failed: {error}"))?
+ .map_err(|error| format!("[composio:store] writing {name} failed: {error:#}"))
}
#[cfg(test)]
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 882a05499f..8928d8d446 100644
--- a/crates/openhuman-core/src/integrations/composio/file_store_documents.rs
+++ b/crates/openhuman-core/src/integrations/composio/file_store_documents.rs
@@ -1,9 +1,8 @@
//! The Composio host state files on the `tinystoragedrivers` document port.
//!
-//! Used instead of `<workspace>/integrations/<file>.json` when the host
-//! configured a storage backend ([`crate::storage`]); `file_store.rs` picks it
-//! per call, so the state lives under the acting agent's storage scope
-//! (`local` on a single-user host). These are the connected-account identities
+//! `file_store.rs` opens it per call, so the state lives under the acting
+//! agent's storage scope (`local` on a single-user host) in the installed
+//! backend, or the workspace default when none is installed. These are the connected-account identities
//! and the per-toolkit agent scope preferences: user data, so unlike a cache
//! they must follow the user to a shared backend.
//!
@@ -11,11 +10,11 @@
//!
//! | Collection | Document id | Holds |
//! | --- | --- | --- |
-//! | `composio_state` | the file name (`composio_identities.json`, ...) | `value`: the serde value the file held |
+//! | `composio_state` | the value name (`composio_identities.json`, ...) | `value`: the serde value |
use std::path::Path;
-use anyhow::{anyhow, Result};
+use anyhow::Result;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::json;
@@ -30,13 +29,14 @@ fn collections() -> Vec<CollectionSpec> {
vec![CollectionSpec::new(STATE)]
}
-/// The document store for this call, when the host configured one.
-pub(super) fn current() -> Result<Option<Docs>> {
+/// The document store for this call: the installed backend, else the
+/// workspace default, in the acting scope.
+pub(super) fn current(workspace_dir: &Path) -> Result<Docs> {
#[cfg(test)]
if let Some(docs) = TEST_OVERRIDE.with(|slot| slot.borrow().clone()) {
- return Ok(Some(docs));
+ return Ok(docs);
}
- Ok(Repo::current(DOMAIN, collections)?.map(Docs))
+ Ok(Docs(Repo::current_for(workspace_dir, DOMAIN, collections)?))
}
#[cfg(test)]
@@ -44,12 +44,6 @@ thread_local! {
static TEST_OVERRIDE: std::cell::RefCell<Option<Docs>> = const { std::cell::RefCell::new(None) };
}
-fn id_of(path: &Path) -> Result<String> {
- path.file_name()
- .map(|name| name.to_string_lossy().into_owned())
- .ok_or_else(|| anyhow!("composio state path {} has no file name", path.display()))
-}
-
/// The composio state over one scoped document handle.
#[derive(Clone)]
pub(super) struct Docs(Repo);
@@ -60,9 +54,9 @@ impl Docs {
Self(Repo::over(scoped, DOMAIN, collections))
}
- /// The value stored for the file `path` names, or `T::default()`.
- pub(super) fn load<T: DeserializeOwned + Default>(&self, path: &Path) -> Result<T> {
- let id = id_of(path)?;
+ /// The value stored stored under `name`, or `T::default()`.
+ pub(super) fn load<T: DeserializeOwned + Default>(&self, name: &str) -> Result<T> {
+ let id = name.to_string();
let stored = self
.0
.run(|docs| async move { docs.get(STATE, &id).await })?;
@@ -72,21 +66,21 @@ impl Docs {
}
}
- /// Read-modify-write of the value for the file `path` names, under
+ /// Read-modify-write of the value stored under `name`, 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,
+ name: &str,
change: impl Fn(&mut T) -> (R, bool) + Send + 'static,
) -> Result<R>
where
T: DeserializeOwned + Serialize + Default + Send + 'static,
R: Send + 'static,
{
- let id = id_of(path)?;
+ let id = name.to_string();
self.0.run(|docs| async move {
for _ in 0..crate::storage::documents::CAS_ATTEMPTS {
let stored = docs.get(STATE, &id).await?;
@@ -125,8 +119,9 @@ impl Docs {
})
}
- pub(super) fn save<T: Serialize>(&self, path: &Path, value: &T) -> Result<()> {
- let id = id_of(path)?;
+ #[cfg(test)]
+ pub(super) fn save<T: Serialize>(&self, name: &str, value: &T) -> Result<()> {
+ let id = name.to_string();
let doc = json!({ "value": serde_json::to_value(value)? });
log::debug!("[composio:store] document save id={id}");
self.0.run(|docs| async move {