Skip to content

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

feat(storage): default document stores to local sqlite backend

Steven Enamakel3f6fcbf2635d
diff --git a/crates/openhuman-core/src/desktop/notifications/store.rs b/crates/openhuman-core/src/desktop/notifications/store.rs
index a9dc1c08e3..c124b5a5fe 100644
--- a/crates/openhuman-core/src/desktop/notifications/store.rs
+++ b/crates/openhuman-core/src/desktop/notifications/store.rs
@@ -69,11 +69,18 @@ CREATE INDEX IF NOT EXISTS idx_core_notifications_ts
/// Open (and migrate) the notifications DB, then call `f` with the live
/// connection. Mirrors the `with_connection` helper in `cron/store.rs`.
-fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
- let db_path = config
+pub(super) fn db_path(config: &Config) -> std::path::PathBuf {
+ config
.workspace_dir
.join("notifications")
- .join("notifications.db");
+ .join("notifications.db")
+}
+
+pub(super) fn with_connection<T>(
+ config: &Config,
+ f: impl FnOnce(&Connection) -> Result<T>,
+) -> Result<T> {
+ let db_path = db_path(config);
tracing::trace!(
path = %db_path.display(),
@@ -702,6 +709,8 @@ pub fn get_settings(config: &Config, provider: &str) -> Result<NotificationSetti
}
mod store_rows;
+#[path = "store_import.rs"]
+pub(super) mod import;
use store_rows::rows_to_notifications;
#[cfg(test)]
diff --git a/crates/openhuman-core/src/desktop/notifications/store_documents.rs b/crates/openhuman-core/src/desktop/notifications/store_documents.rs
index f03983a6eb..16d7bd2dff 100644
--- a/crates/openhuman-core/src/desktop/notifications/store_documents.rs
+++ b/crates/openhuman-core/src/desktop/notifications/store_documents.rs
@@ -39,13 +39,15 @@ use super::types::{
CoreNotificationEvent, IntegrationNotification, NotificationSettings, NotificationStats,
NotificationStatus,
};
+use crate::config::Config;
use crate::storage::documents::{compare_and_swap, text, Repo, CAS_ATTEMPTS};
+use crate::storage::local::{self, ImportPlan};
use crate::storage::{DocumentStore, DocumentStoreExt, StorageError};
-const NOTIFICATIONS: &str = "integration_notifications";
+pub(super) const NOTIFICATIONS: &str = "integration_notifications";
const DEDUP: &str = "notification_dedup";
-const SETTINGS: &str = "notification_settings";
-const CORE: &str = "core_notifications";
+pub(super) const SETTINGS: &str = "notification_settings";
+pub(super) const CORE: &str = "core_notifications";
const DOMAIN: &str = "notifications::store";
/// How long identical content counts as a duplicate.
@@ -65,9 +67,17 @@ fn collections() -> Vec<CollectionSpec> {
]
}
-/// The document store for this call, when the host configured one.
-pub(super) fn current() -> Result<Option<Docs>> {
- Ok(Repo::current(DOMAIN, collections)?.map(Docs))
+/// The document store for this call: the host's configured backend or, by
+/// default, the document tables in `notifications.db` (the legacy tables
+/// imported on first open). `None` keeps the legacy tables.
+pub(super) fn current(config: &Config) -> Result<Option<Docs>> {
+ let plan = ImportPlan {
+ domain: DOMAIN,
+ tables: super::store::import::TABLES,
+ read: &|| super::store::import::read(config),
+ };
+ let db_path = super::store::db_path(config);
+ Ok(local::repo(config, &db_path, DOMAIN, collections, &plan)?.map(Docs))
}
fn status_of(raw: Option<&str>) -> NotificationStatus {
@@ -83,7 +93,7 @@ fn parse_time(raw: Option<&str>) -> Option<DateTime<Utc>> {
raw.and_then(|value| value.parse().ok())
}
-fn to_doc(n: &IntegrationNotification) -> Value {
+pub(super) fn to_doc(n: &IntegrationNotification) -> Value {
let mut doc = Map::new();
doc.insert("provider".into(), json!(n.provider));
doc.insert("title".into(), json!(n.title));
@@ -223,7 +233,7 @@ async fn release_content(
/// The core-notification document id: the workspace is part of the key, since
/// each workspace's events are persisted separately in the SQL store (one
/// database per workspace) and event ids repeat across them.
-fn core_id(workspace: &str, event_id: &str) -> String {
+pub(super) fn core_id(workspace: &str, event_id: &str) -> String {
format!("{}:{workspace}/{event_id}", workspace.len())
}
diff --git a/crates/openhuman-core/src/desktop/notifications/store_import.rs b/crates/openhuman-core/src/desktop/notifications/store_import.rs
index 7a96fa34af..d229afd3f5 100644
--- a/crates/openhuman-core/src/desktop/notifications/store_import.rs
+++ b/crates/openhuman-core/src/desktop/notifications/store_import.rs
@@ -18,21 +18,21 @@ use anyhow::{Context, Result};
use rusqlite::Connection;
use serde_json::json;
-use super::store_documents::{core_id, to_doc, CORE, NOTIFICATIONS, SETTINGS};
+use super::super::store_documents::{core_id, to_doc, CORE, NOTIFICATIONS, SETTINGS};
use crate::config::Config;
use crate::storage::local::{table_exists, ImportDoc};
/// The legacy tables this import retires.
-pub(super) const TABLES: &[&str] = &[
+pub(crate) const TABLES: &[&str] = &[
"integration_notifications",
"notification_settings",
"core_notifications",
];
/// Reads every legacy row.
-pub(super) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
+pub(crate) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
let workspace = config.workspace_dir.to_string_lossy().into_owned();
- super::store::with_connection(config, |conn| read_rows(conn, &workspace))
+ super::with_connection(config, |conn| read_rows(conn, &workspace))
}
fn read_rows(conn: &Connection, workspace: &str) -> Result<Vec<ImportDoc>> {
@@ -49,7 +49,7 @@ fn read_rows(conn: &Connection, workspace: &str) -> Result<Vec<ImportDoc>> {
let rows = stmt
.query(())
.context("[notifications::import] query integration_notifications")?;
- for notification in super::store::rows_to_notifications(rows)? {
+ for notification in super::rows_to_notifications(rows)? {
docs.push(ImportDoc {
collection: NOTIFICATIONS,
id: notification.id.clone(),
diff --git a/crates/openhuman-core/src/integrations/task_sources/store.rs b/crates/openhuman-core/src/integrations/task_sources/store.rs
index 38eb584222..d0557be340 100644
--- a/crates/openhuman-core/src/integrations/task_sources/store.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/store.rs
@@ -444,6 +444,8 @@ pub fn clear_all(config: &Config) -> Result<usize> {
mod store_rows;
use store_rows::{map_source_row, SELECT_SOURCE_COLUMNS};
+#[path = "store_import.rs"]
+pub(super) mod import;
/// Tracks which task_sources database files have already had their schema DDL
/// (the `CREATE TABLE`/`CREATE INDEX` batch plus the `add_column_if_missing`
@@ -640,8 +642,15 @@ fn init_schema(conn: &mut Connection) -> Result<()> {
Ok(())
}
-fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
- let db_path = config.workspace_dir.join("task_sources").join("sources.db");
+pub(super) fn db_path(config: &Config) -> PathBuf {
+ config.workspace_dir.join("task_sources").join("sources.db")
+}
+
+pub(super) fn with_connection<T>(
+ config: &Config,
+ f: impl FnOnce(&Connection) -> Result<T>,
+) -> Result<T> {
+ let db_path = db_path(config);
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent).with_context(|| {
format!(
diff --git a/crates/openhuman-core/src/integrations/task_sources/store_documents.rs b/crates/openhuman-core/src/integrations/task_sources/store_documents.rs
index ab2f476856..6188391488 100644
--- a/crates/openhuman-core/src/integrations/task_sources/store_documents.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/store_documents.rs
@@ -27,11 +27,13 @@ use super::types::{
FetchReason, FilterSpec, ProviderSlug, SourceTarget, TaskSource, TaskSourcePatch,
};
use crate::integrations::composio::providers::NormalizedTask;
+use crate::config::Config;
use crate::storage::documents::{compare_and_swap, text, Repo};
+use crate::storage::local::{self, ImportPlan};
use crate::storage::{DocumentStoreExt, StorageError};
-const SOURCES: &str = "task_sources";
-const INGESTED: &str = "ingested_tasks";
+pub(super) const SOURCES: &str = "task_sources";
+pub(super) const INGESTED: &str = "ingested_tasks";
const DOMAIN: &str = "task_sources::store";
fn collections() -> Vec<CollectionSpec> {
@@ -42,18 +44,26 @@ fn collections() -> Vec<CollectionSpec> {
]
}
-/// The document store for this call, when the host configured one.
-pub(super) fn current() -> Result<Option<Docs>> {
- Ok(Repo::current(DOMAIN, collections)?.map(Docs))
+/// The document store for this call: the host's configured backend or, by
+/// default, the document tables in `sources.db` (the legacy tables imported
+/// on first open). `None` keeps the legacy tables.
+pub(super) fn current(config: &Config) -> Result<Option<Docs>> {
+ let plan = ImportPlan {
+ domain: DOMAIN,
+ tables: super::store::import::TABLES,
+ read: &|| super::store::import::read(config),
+ };
+ let db_path = super::store::db_path(config);
+ Ok(local::repo(config, &db_path, DOMAIN, collections, &plan)?.map(Docs))
}
/// The ledger id for one `(source, external task)`; the length prefix keeps
/// `("a/b", "c")` and `("a", "b/c")` apart.
-fn ingested_id(source_id: &str, external_id: &str) -> String {
+pub(super) fn ingested_id(source_id: &str, external_id: &str) -> String {
format!("{}:{source_id}/{external_id}", source_id.len())
}
-fn to_doc(source: &TaskSource) -> Result<Value> {
+pub(super) fn to_doc(source: &TaskSource) -> Result<Value> {
let mut doc = Map::new();
doc.insert("provider".into(), json!(source.provider.as_str()));
doc.insert("enabled".into(), json!(source.enabled));
diff --git a/crates/openhuman-core/src/integrations/task_sources/store_import.rs b/crates/openhuman-core/src/integrations/task_sources/store_import.rs
index e8e8e09998..9c4d86affe 100644
--- a/crates/openhuman-core/src/integrations/task_sources/store_import.rs
+++ b/crates/openhuman-core/src/integrations/task_sources/store_import.rs
@@ -12,16 +12,16 @@ use chrono::DateTime;
use rusqlite::Connection;
use serde_json::{json, Map, Value};
-use super::store_documents::{ingested_id, to_doc, INGESTED, SOURCES};
+use super::super::store_documents::{ingested_id, to_doc, INGESTED, SOURCES};
use crate::config::Config;
use crate::storage::local::{table_exists, ImportDoc};
/// The legacy tables this import retires.
-pub(super) const TABLES: &[&str] = &["task_sources", "ingested_tasks"];
+pub(crate) const TABLES: &[&str] = &["task_sources", "ingested_tasks"];
/// Reads every legacy row, after bringing an old schema forward.
-pub(super) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
- super::store::with_connection(config, read_rows)
+pub(crate) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
+ super::with_connection(config, read_rows)
}
fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {
@@ -30,11 +30,11 @@ fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {
let mut stmt = conn
.prepare(&format!(
"{} ORDER BY created_at ASC, id ASC",
- super::store::SELECT_SOURCE_COLUMNS
+ super::SELECT_SOURCE_COLUMNS
))
.context("[task_sources::import] prepare task_sources")?;
let rows = stmt
- .query_map([], super::store::map_source_row)
+ .query_map([], super::map_source_row)
.context("[task_sources::import] query task_sources")?;
for row in rows {
match row {
diff --git a/crates/openhuman-core/src/security/approval/store_import.rs b/crates/openhuman-core/src/security/approval/store_import.rs
index c55243f263..b514c04b88 100644
--- a/crates/openhuman-core/src/security/approval/store_import.rs
+++ b/crates/openhuman-core/src/security/approval/store_import.rs
@@ -19,10 +19,10 @@ use crate::config::Config;
use crate::storage::local::{table_exists, ImportDoc};
/// The legacy tables this import retires.
-pub(super) const TABLES: &[&str] = &["pending_approvals", "flow_tool_trust"];
+pub(crate) const TABLES: &[&str] = &["pending_approvals", "flow_tool_trust"];
/// Reads every legacy row, after bringing an old schema forward.
-pub(super) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
+pub(crate) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
super::with_connection(config, read_rows)
}
diff --git a/crates/openhuman-core/src/security/devices/store.rs b/crates/openhuman-core/src/security/devices/store.rs
index 326f1ede3c..31014b1354 100644
--- a/crates/openhuman-core/src/security/devices/store.rs
+++ b/crates/openhuman-core/src/security/devices/store.rs
@@ -129,8 +129,15 @@ fn map_device_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<PairedDevice> {
})
}
-fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
- let db_path = config.workspace_dir.join("devices").join("devices.db");
+pub(super) fn db_path(config: &Config) -> std::path::PathBuf {
+ config.workspace_dir.join("devices").join("devices.db")
+}
+
+pub(super) fn with_connection<T>(
+ config: &Config,
+ f: impl FnOnce(&Connection) -> Result<T>,
+) -> Result<T> {
+ let db_path = db_path(config);
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("create devices dir: {}", parent.display()))?;
@@ -161,6 +168,9 @@ fn with_connection<T>(config: &Config, f: impl FnOnce(&Connection) -> Result<T>)
f(&conn)
}
+#[path = "store_import.rs"]
+pub(super) mod import;
+
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
diff --git a/crates/openhuman-core/src/security/devices/store_documents.rs b/crates/openhuman-core/src/security/devices/store_documents.rs
index 3f58ba80aa..a51e5a444d 100644
--- a/crates/openhuman-core/src/security/devices/store_documents.rs
+++ b/crates/openhuman-core/src/security/devices/store_documents.rs
@@ -16,19 +16,29 @@ use serde_json::{json, Value};
use tinystoragedrivers::{CollectionSpec, Filter, IndexSpec, Precondition, Query, Sort, Versioned};
use crate::security::devices::types::PairedDevice;
+use crate::config::Config;
use crate::storage::documents::{compare_and_swap, text, Repo};
+use crate::storage::local::{self, ImportPlan};
use crate::storage::DocumentStoreExt;
-const DEVICES: &str = "paired_devices";
+pub(super) const DEVICES: &str = "paired_devices";
const DOMAIN: &str = "devices::store";
fn collections() -> Vec<CollectionSpec> {
vec![CollectionSpec::new(DEVICES).index(IndexSpec::new("by_active", ["revoked", "created_at"]))]
}
-/// The document store for this call, when the host configured one.
-pub(super) fn current() -> Result<Option<Docs>> {
- Ok(Repo::current(DOMAIN, collections)?.map(Docs))
+/// The document store for this call: the host's configured backend or, by
+/// default, the document tables in `devices.db` (the legacy table imported on
+/// first open). `None` keeps the legacy table.
+pub(super) fn current(config: &Config) -> Result<Option<Docs>> {
+ let plan = ImportPlan {
+ domain: DOMAIN,
+ tables: super::store::import::TABLES,
+ read: &|| super::store::import::read(config),
+ };
+ let db_path = super::store::db_path(config);
+ Ok(local::repo(config, &db_path, DOMAIN, collections, &plan)?.map(Docs))
}
fn to_device(stored: &Versioned<Value>) -> PairedDevice {
diff --git a/crates/openhuman-core/src/security/devices/store_import.rs b/crates/openhuman-core/src/security/devices/store_import.rs
index fa257fccd0..f695e26a25 100644
--- a/crates/openhuman-core/src/security/devices/store_import.rs
+++ b/crates/openhuman-core/src/security/devices/store_import.rs
@@ -9,16 +9,16 @@ use anyhow::{Context, Result};
use rusqlite::Connection;
use serde_json::{json, Value};
-use super::store_documents::DEVICES;
+use super::super::store_documents::DEVICES;
use crate::config::Config;
use crate::storage::local::{table_exists, ImportDoc};
/// The legacy tables this import retires.
-pub(super) const TABLES: &[&str] = &["paired_devices"];
+pub(crate) const TABLES: &[&str] = &["paired_devices"];
/// Reads every legacy row.
-pub(super) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
- super::store::with_connection(config, read_rows)
+pub(crate) fn read(config: &Config) -> Result<Vec<ImportDoc>> {
+ super::with_connection(config, read_rows)
}
fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {
diff --git a/crates/openhuman-core/src/storage/local.rs b/crates/openhuman-core/src/storage/local.rs
index 3ed61f9801..7f73d7bd6c 100644
--- a/crates/openhuman-core/src/storage/local.rs
+++ b/crates/openhuman-core/src/storage/local.rs
@@ -132,6 +132,23 @@ pub fn open(
open_default(db_path, collections, plan)
}
+/// [`open`] as a [`Repo`] for the stores built on one.
+///
+/// # Errors
+///
+/// As [`open`].
+pub fn repo(
+ config: &Config,
+ db_path: &Path,
+ domain: &'static str,
+ collections: fn() -> Vec<CollectionSpec>,
+ plan: &ImportPlan<'_>,
+) -> Result<Option<Repo>> {
+ open(config, db_path, collections, plan)?
+ .map(|opened| Repo::on(&opened.backend, &opened.scope, domain, collections))
+ .transpose()
+}
+
#[cfg(not(feature = "storage-sqlite"))]
fn open_default(
_db_path: &Path,