The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(task_sources): import tasks from store documents
Steven Enamakel9e141440b3fe
diff --git a/crates/openhuman-core/src/desktop/notifications/mod.rs b/crates/openhuman-core/src/desktop/notifications/mod.rsindex f30ac8644b..f88f5c23a0 100644--- a/crates/openhuman-core/src/desktop/notifications/mod.rs+++ b/crates/openhuman-core/src/desktop/notifications/mod.rs@@ -26,8 +26,10 @@ pub mod bus;pub mod rpc;pub mod schemas;pub mod store;+mod storage_schema;mod store_documents;mod store_import;+pub(crate) use storage_schema::storage_schema;pub(crate) use store_documents::import_source;pub mod types;diff --git a/crates/openhuman-core/src/desktop/notifications/store_import.rs b/crates/openhuman-core/src/desktop/notifications/store_import.rsindex 1ee1d0e11b..6eda8532a9 100644--- a/crates/openhuman-core/src/desktop/notifications/store_import.rs+++ b/crates/openhuman-core/src/desktop/notifications/store_import.rs@@ -24,6 +24,7 @@ mod store_rows;use store_rows::rows_to_notifications;use super::storage_schema::{LEGACY_CORE, LEGACY_NOTIFICATIONS, LEGACY_SETTINGS};+use super::types::IntegrationNotification;use crate::config::Config;use crate::storage::import::{table_exists, ImportDoc};diff --git a/crates/openhuman-core/src/integrations/task_sources/storage_schema.rs b/crates/openhuman-core/src/integrations/task_sources/storage_schema.rsnew file mode 100644index 0000000000..c752169160--- /dev/null+++ b/crates/openhuman-core/src/integrations/task_sources/storage_schema.rs@@ -0,0 +1,129 @@+//! The `task_sources` owner's storage schema: the configured sources and the+//! ingestion ledger, with the steps that bring the v1 collections forward.+//!+//! | v1 | v2 | change |+//! |---|---|---|+//! | `task_sources` | `task_sources.sources` | `created_at` dropped (`created_ms` kept), `last_fetch_at` becomes `last_fetch_ms` |+//! | `ingested_tasks` (id `<len>:<source>/<external>`) | `task_sources.ingested` (id `Key::of([source_id, external_id])`) | `ingested_at` and `ingested_ns` dropped |+//!+//! `filter`, `target` and the task `payload` stay JSON text: they carry+//! provider-defined documents whose keys a document-store driver (MongoDB)+//! must never see as field names.++use serde_json::Value;+use tinystoragedrivers::schema::{Schema, ScopeClass, SourceRecord, Step, TargetRecord};+use tinystoragedrivers::{CollectionSpec, IndexSpec, Key, Result};++use crate::storage::schema_support::{key_of, owner, time_ms, Body};++pub(super) const SOURCES: &str = "task_sources.sources";+pub(super) const INGESTED: &str = "task_sources.ingested";+pub(super) const LEGACY_SOURCES: &str = "task_sources";+pub(super) const LEGACY_INGESTED: &str = "ingested_tasks";+const SCHEMA: u32 = 2;++/// What the task-source store keeps and the steps from the v1 collections.+#[must_use]+pub fn storage_schema() -> Schema {+ let [sources, ingested] = specs();+ Schema::new(owner("task_sources"))+ .collection_with(SCHEMA, sources, ScopeClass::Tenant)+ .collection_with(SCHEMA, ingested, ScopeClass::Tenant)+ .step(Step::new("sources_v2", SOURCES, 1, SCHEMA, sources_v2).source(LEGACY_SOURCES))+ .step(Step::new("ingested_v2", INGESTED, 1, SCHEMA, ingested_v2).source(LEGACY_INGESTED))+}++/// The two v2 collections with their indexes.+pub(super) fn specs() -> [CollectionSpec; 2] {+ [+ CollectionSpec::new(SOURCES).index(IndexSpec::new("by_created", ["created_ms"])),+ CollectionSpec::new(INGESTED)+ .index(IndexSpec::new("by_source", ["source_id", "ingested_ms"])),+ ]+}++/// The v1 collections as the legacy importer declares them.+pub(super) fn legacy_collections() -> Vec<CollectionSpec> {+ vec![+ CollectionSpec::new(LEGACY_SOURCES).index(IndexSpec::new("by_created", ["created_ms"])),+ CollectionSpec::new(LEGACY_INGESTED)+ .index(IndexSpec::new("by_source", ["source_id", "ingested_ms"])),+ ]+}++/// The ledger id for one `(source, external task)`.+///+/// # Panics+///+/// Never in practice: a two-part key is valid.+pub(super) fn ingested_id(source_id: &str, external_id: &str) -> String {+ #[allow(clippy::expect_used)]+ Key::of([source_id, external_id])+ .expect("a two-part key is valid")+ .as_str()+ .to_owned()+}++fn sources_v2(batch: Vec<SourceRecord>) -> Result<Vec<TargetRecord>> {+ batch+ .into_iter()+ .map(|record| {+ let old = &record.body;+ let created_ms = old+ .get("created_ms")+ .and_then(Value::as_i64)+ .or_else(|| time_ms(old, "created_at"))+ .unwrap_or(record.meta.created_ms);+ let last_fetch_ms = old+ .get("last_fetch_ms")+ .and_then(Value::as_i64)+ .or_else(|| time_ms(old, "last_fetch_at"));+ let body = Body::new()+ .copy(old, "provider")+ .copy(old, "enabled")+ .copy(old, "filter")+ .copy(old, "interval_secs")+ .copy(old, "target")+ .copy(old, "max_tasks_per_fetch")+ .copy(old, "connection_id")+ .copy(old, "name")+ .copy(old, "last_status")+ .set("created_ms", created_ms)+ .set_some("last_fetch_ms", last_fetch_ms)+ .build();+ Ok(TargetRecord::new(SOURCES, key_of(&record.id)?, body).created_ms(created_ms))+ })+ .collect()+}++fn ingested_v2(batch: Vec<SourceRecord>) -> Result<Vec<TargetRecord>> {+ Ok(batch+ .into_iter()+ .filter_map(|record| {+ let old = &record.body;+ let source_id = old.get("source_id").and_then(Value::as_str)?;+ let external_id = old.get("external_id").and_then(Value::as_str)?;+ let ingested_ms = old+ .get("ingested_ms")+ .and_then(Value::as_i64)+ .or_else(|| time_ms(old, "ingested_at"))+ .unwrap_or(record.meta.created_ms);+ let body = Body::new()+ .set("source_id", source_id)+ .set("external_id", external_id)+ .copy(old, "content_hash")+ .copy(old, "title")+ .copy(old, "payload")+ .set("ingested_ms", ingested_ms)+ .build();+ Some(+ TargetRecord::new(INGESTED, ingested_id(source_id, external_id), body)+ .created_ms(ingested_ms),+ )+ })+ .collect())+}++#[cfg(test)]+#[path = "storage_schema_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/integrations/task_sources/storage_schema_tests.rs b/crates/openhuman-core/src/integrations/task_sources/storage_schema_tests.rsnew file mode 100644index 0000000000..a8f582c0eb--- /dev/null+++ b/crates/openhuman-core/src/integrations/task_sources/storage_schema_tests.rs@@ -0,0 +1,72 @@+use super::*;+use serde_json::json;+use tinystoragedrivers::Meta;++fn source(id: &str, body: Value) -> SourceRecord {+ SourceRecord {+ id: id.to_string(),+ body,+ meta: Meta::unknown(),+ }+}++#[test]+fn a_source_keeps_its_settings_and_drops_formatted_times() {+ let out = sources_v2(vec![source(+ "s1",+ json!({+ "provider": "linear", "enabled": true, "filter": "{}", "interval_secs": 300,+ "target": "{}", "max_tasks_per_fetch": 5, "name": "mine",+ "created_at": "1970-01-01T00:00:01Z", "created_ms": 1000,+ "last_fetch_at": "1970-01-01T00:00:02Z", "last_status": "ok",+ }),+ )])+ .unwrap();+ assert_eq!(out[0].collection, SOURCES);+ assert_eq!(out[0].id, "s1");+ let body = &out[0].body;+ assert!(body.get("created_at").is_none());+ assert!(body.get("last_fetch_at").is_none());+ assert_eq!(body["created_ms"], 1000);+ assert_eq!(body["last_fetch_ms"], 2000);+ assert_eq!(body["interval_secs"], 300);+}++#[test]+fn a_source_from_the_pre_ms_shape_gets_its_creation_time_from_the_text() {+ let out = sources_v2(vec![source(+ "s2",+ json!({ "provider": "x", "created_at": "1970-01-01T00:00:05Z" }),+ )])+ .unwrap();+ assert_eq!(out[0].body["created_ms"], 5000);+ assert!(out[0].body.get("last_fetch_ms").is_none());+}++#[test]+fn a_ledger_entry_is_rekeyed_by_source_and_external_id() {+ let out = ingested_v2(vec![source(+ "3:a/b/c",+ json!({+ "source_id": "a/b", "external_id": "c", "content_hash": "h", "title": "t",+ "payload": "{}", "ingested_at": "1970-01-01T00:00:01Z",+ "ingested_ms": 1000, "ingested_ns": 1_000_000_000_i64,+ }),+ )])+ .unwrap();+ assert_eq!(out[0].collection, INGESTED);+ assert_eq!(out[0].id, ingested_id("a/b", "c"));+ assert_eq!(out[0].id, "a%2Fb/c");+ assert_eq!(+ out[0].body,+ json!({+ "source_id": "a/b", "external_id": "c", "content_hash": "h", "title": "t",+ "payload": "{}", "ingested_ms": 1000,+ })+ );+}++#[test]+fn the_schema_composes_under_its_owner() {+ tinystoragedrivers::schema::Registry::compose([storage_schema()]).unwrap();+}diff --git a/crates/openhuman-core/src/integrations/task_sources/store_documents.rs b/crates/openhuman-core/src/integrations/task_sources/store_documents.rsindex 36648026a3..7486ff6e8f 100644--- a/crates/openhuman-core/src/integrations/task_sources/store_documents.rs+++ b/crates/openhuman-core/src/integrations/task_sources/store_documents.rs@@ -9,8 +9,10 @@//!//! | Collection | Document id | Holds |//! | --- | --- | --- |-//! | `task_sources` | source id | one configured source |-//! | `ingested_tasks` | `(source_id, external_id)` | one dedup ledger entry |+//! | `task_sources.sources` | source id | one configured source |+//! | `task_sources.ingested` | `Key::of([source_id, external_id])` | one dedup ledger entry |+//!+//! The shapes and the v1 -> v2 steps are in [`super::storage_schema`].//!//! `filter`, `target` and the task `payload` are JSON strings, as in SQLite,//! so a MongoDB-backed port never meets an arbitrary key. Epoch-millisecond@@ -31,27 +33,25 @@ use crate::integrations::composio::contract::NormalizedTask;use crate::storage::documents::{compare_and_swap, text, Repo};use crate::storage::{DocumentStoreExt, StorageError};-pub(super) const SOURCES: &str = "task_sources";-pub(super) const INGESTED: &str = "ingested_tasks";+pub(super) use super::storage_schema::{ingested_id, INGESTED, SOURCES};+use super::storage_schema::{legacy_collections, specs};+use crate::storage::schema_support::{key_of, ms_rfc3339};const DOMAIN: &str = "task_sources::store";/// The legacy `sources.db`, as the storage importer reads it.pub(crate) fn import_source() -> crate::storage::import::Source {crate::storage::import::Source {domain: "task_sources",+ owner: "task_sources",db: "task_sources/sources.db",- collections,+ collections: legacy_collections,read_legacy: |scratch, _real| super::store_import::read(scratch),rekey: |record, _config| record,}}fn collections() -> Vec<CollectionSpec> {- vec![- CollectionSpec::new(SOURCES).index(IndexSpec::new("by_created", ["created_ms"])),- CollectionSpec::new(INGESTED)- .index(IndexSpec::new("by_source", ["source_id", "ingested_ms"])),- ]+ specs().into()}/// The document store for this call: the storage backend, in the acting scope.@@ -63,12 +63,6 @@ pub(super) fn current(config: &Config) -> Result<Docs> {)?))}-/// The ledger id for one `(source, external task)`; the length prefix keeps-/// `("a/b", "c")` and `("a", "b/c")` apart.-pub(super) fn ingested_id(source_id: &str, external_id: &str) -> String {- format!("{}:{source_id}/{external_id}", source_id.len())-}-pub(super) fn to_doc(source: &TaskSource) -> Result<Value> {let mut doc = Map::new();doc.insert("provider".into(), json!(source.provider.as_str()));@@ -86,7 +80,6 @@ pub(super) fn to_doc(source: &TaskSource) -> Result<Value> {"max_tasks_per_fetch".into(),json!(source.max_tasks_per_fetch),);- doc.insert("created_at".into(), json!(source.created_at.to_rfc3339()));doc.insert("created_ms".into(),json!(source.created_at.timestamp_millis()),@@ -94,10 +87,6 @@ pub(super) fn to_doc(source: &TaskSource) -> Result<Value> {let optional = [("connection_id", source.connection_id.clone()),("name", source.name.clone()),- (- "last_fetch_at",- source.last_fetch_at.map(|at| at.to_rfc3339()),- ),("last_status", source.last_status.clone()),];for (field, value) in optional {@@ -105,13 +94,24 @@ pub(super) fn to_doc(source: &TaskSource) -> Result<Value> {doc.insert(field.into(), json!(value));}}+ if let Some(at) = source.last_fetch_at {+ doc.insert("last_fetch_ms".into(), json!(at.timestamp_millis()));+ }Ok(Value::Object(doc))}-fn parse_time(raw: &str) -> Result<DateTime<Utc>> {- Ok(DateTime::parse_from_rfc3339(raw)- .with_context(|| format!("invalid RFC3339 timestamp in task source: {raw}"))?- .with_timezone(&Utc))+fn from_ms(ms: i64) -> Result<DateTime<Utc>> {+ DateTime::from_timestamp_millis(ms)+ .ok_or_else(|| anyhow!("timestamp out of range in task source: {ms}"))+}++/// The source id a document id was built from (`Key::of` of it).+fn source_id_of(id: &str) -> String {+ tinystoragedrivers::Key::new(id)+ .ok()+ .and_then(|key| key.split())+ .and_then(|mut parts| (parts.len() == 1).then(|| parts.remove(0)))+ .unwrap_or_else(|| id.to_string())}fn to_source(stored: &Versioned<Value>) -> Result<TaskSource> {@@ -123,7 +123,7 @@ fn to_source(stored: &Versioned<Value>) -> Result<TaskSource> {.ok_or_else(|| anyhow!("task source missing {name}"))};Ok(TaskSource {- id: stored.id.clone(),+ id: source_id_of(&stored.id),provider: ProviderSlug::parse(field("provider")?).map_err(|error| anyhow!(error))?,connection_id: text(doc, "connection_id").map(str::to_string),name: text(doc, "name").map(str::to_string),@@ -135,8 +135,16 @@ fn to_source(stored: &Versioned<Value>) -> Result<TaskSource> {.context("invalid target json")?,max_tasks_per_fetch: u32::try_from(number("max_tasks_per_fetch")?).context("invalid max_tasks_per_fetch")?,- created_at: parse_time(field("created_at")?)?,- last_fetch_at: text(doc, "last_fetch_at").map(parse_time).transpose()?,+ created_at: from_ms(+ doc.get("created_ms")+ .and_then(Value::as_i64)+ .ok_or_else(|| anyhow!("task source missing created_ms"))?,+ )?,+ last_fetch_at: doc+ .get("last_fetch_ms")+ .and_then(Value::as_i64)+ .map(from_ms)+ .transpose()?,last_status: text(doc, "last_status").map(str::to_string),})}@@ -156,7 +164,7 @@ impl Docs {}pub(super) fn add_source(&self, source: &TaskSource) -> Result<TaskSource> {- let id = source.id.clone();+ let id = key_of(&source.id)?;let doc = to_doc(source)?;self.0.run(|docs| async move {docs.put(SOURCES, &id, doc, Precondition::Absent)@@ -167,7 +175,7 @@ impl Docs {}pub(super) fn get_source(&self, id: &str) -> Result<TaskSource> {- let key = id.to_string();+ let key = key_of(id)?;let stored = self.0.run(|docs| async move { docs.get(SOURCES, &key).await })?@@ -189,7 +197,7 @@ impl Docs {// Validate against the current source first, so a mismatched filter// is reported as the SQL store reports it.apply_patch(&mut self.get_source(id)?, patch.clone())?;- let key = id.to_string();+ let key = key_of(id)?;let updated = self.0.run(|docs| async move {compare_and_swap(&docs, SOURCES, &key, |doc| {let stored = Versioned {@@ -208,12 +216,13 @@ impl Docs {}pub(super) fn remove_source(&self, id: &str) -> Result<()> {- let key = id.to_string();+ let key = key_of(id)?;+ let source_id = id.to_string();let removed = self.0.run(|docs| async move {// Ledger first: if the source delete then fails, the source is// still there (and merely re-ingests), instead of a ledger with no// owner that a later source with the same id would inherit.- docs.delete_where(INGESTED, &Filter::eq("source_id", key.clone()))+ docs.delete_where(INGESTED, &Filter::eq("source_id", source_id)).await?;docs.delete(SOURCES, &key, Precondition::None).await})?;@@ -231,13 +240,13 @@ impl Docs {reason: FetchReason,status: &str,) -> Result<()> {- let key = id.to_string();+ let key = key_of(id)?;let line = format!("{}: {status}", reason.as_str());- let finished = finished_at.to_rfc3339();+ let finished = finished_at.timestamp_millis();self.0.run(|docs| async move {compare_and_swap(&docs, SOURCES, &key, |doc| {let mut next = doc.clone();- next["last_fetch_at"] = json!(finished);+ next["last_fetch_ms"] = json!(finished);next["last_status"] = json!(line);Some(next)})@@ -288,10 +297,7 @@ impl Docs {"content_hash": content_hash(task),"title": task.title,"payload": serde_json::to_string(task).context("serialize ingested task payload")?,- "ingested_at": now.to_rfc3339(),"ingested_ms": now.timestamp_millis(),- // Breaks ties between arrivals in one millisecond.- "ingested_ns": now.timestamp_nanos_opt().unwrap_or(i64::MAX),});self.0.run(|docs| async move {docs.put(INGESTED, &key, doc, Precondition::None)@@ -303,7 +309,6 @@ impl Docs {pub(super) fn list_ingested_refs(&self, source_id: &str) -> Result<Vec<IngestedTaskRef>> {let query = Query::filter(Filter::eq("source_id", source_id)).sort(Sort::asc("ingested_ms"))- .sort(Sort::asc("ingested_ns")).sort(Sort::asc("external_id"));self.0.run(|docs| async move {Ok(docs@@ -333,7 +338,7 @@ impl Docs {let query =Query::filter(Filter::eq("source_id", source_id).and(Filter::exists("payload", true))).sort(Sort::desc("ingested_ms"))- .sort(Sort::desc("ingested_ns"))+ .sort(Sort::desc("external_id")).limit(limit.max(1));self.0.run(|docs| async move {let page = docs.query(INGESTED, &query).await?;diff --git a/crates/openhuman-core/src/integrations/task_sources/store_import.rs b/crates/openhuman-core/src/integrations/task_sources/store_import.rsindex 4f13818412..c1c4546ab7 100644--- a/crates/openhuman-core/src/integrations/task_sources/store_import.rs+++ b/crates/openhuman-core/src/integrations/task_sources/store_import.rs@@ -17,7 +17,8 @@ use chrono::DateTime;use rusqlite::Connection;use serde_json::{json, Map, Value};-use super::store_documents::{ingested_id, to_doc, INGESTED, SOURCES};+use super::storage_schema::{LEGACY_INGESTED, LEGACY_SOURCES};+use super::store_documents::to_doc;use crate::config::Config;use crate::storage::import::{table_exists, ImportDoc};@@ -44,7 +45,7 @@ fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {// table is not retired with a source missing from the new one.let source = row.context("[task_sources::import] decode a task_sources row")?;docs.push(ImportDoc {- collection: SOURCES,+ collection: LEGACY_SOURCES,id: source.id.clone(),doc: to_doc(&source)?,});@@ -82,8 +83,8 @@ fn read_rows(conn: &Connection) -> Result<Vec<ImportDoc>> {doc.insert("ingested_ms".into(), json!(ingested.timestamp_millis()));doc.insert("ingested_at".into(), json!(ingested_at));Ok(ImportDoc {- collection: INGESTED,- id: ingested_id(&source_id, &external_id),+ collection: LEGACY_INGESTED,+ id: format!("{}:{source_id}/{external_id}", source_id.len()),doc: Value::Object(doc),})})