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(storage): add import module for storage data
Steven Enamakelb534b67ef366
diff --git a/crates/openhuman-core/src/storage/import/mod.rs b/crates/openhuman-core/src/storage/import/mod.rsindex 1dcc36a531..d127ba74be 100644--- a/crates/openhuman-core/src/storage/import/mod.rs+++ b/crates/openhuman-core/src/storage/import/mod.rs@@ -29,10 +29,12 @@//! older build wrote is honoured (it becomes the same entry at boot,//! [`super::import_state::migrate_legacy_markers`]). A failed import//! records nothing and is retried on the next boot.-//! - **v1 shapes, then the owner's steps.** The legacy readers write the v1-//! collections the domain used before schema v2; the importer then runs the-//! domain owner's steps over them ([`super::boot::remigrate_owner`]), so the-//! records land in the v2 collections and shapes.+//! - **v1 shapes, then the owner's steps.** The legacy readers produce the v1+//! records the domain used before schema v2; [`upgrade`] runs the domain+//! owner's step functions over them in memory, so the records are written+//! to the v2 collections in the v2 shapes with `Precondition::Absent`. A+//! record the new code already wrote is therefore left alone, the way it+//! was before schema v2, instead of stopping a migration step.//!//! Records land under [`super::scope::tenant_scope`] of no profile//! (`local`), the one scope every unprofiled reader resolves to@@ -268,6 +270,66 @@ pub fn run_with(.collect()}+/// Runs `owner`'s document steps over the v1 `records`, in memory, and returns+/// the v2 records they produce (in input order) with the collection specs to+/// declare. A record in a collection no step reads passes through unchanged.+fn upgrade(owner: &str, records: Vec<Record>) -> Result<(Vec<Record>, Vec<CollectionSpec>)> {+ use tinystoragedrivers::schema::{Item, SourceRecord, StepBody};+ use tinystoragedrivers::Meta;+ let schema = super::schema::owner_schemas()+ .into_iter()+ .find(|schema| schema.owner.as_str() == owner)+ .ok_or_else(|| anyhow!("no storage schema for owner `{owner}`"))?;+ let specs = schema+ .items+ .iter()+ .filter_map(|item| match item {+ Item::Collection { spec, .. } => Some(spec.clone()),+ _ => None,+ })+ .collect();+ let mut upgraded = Vec::with_capacity(records.len());+ let mut by_collection: Vec<(String, Vec<SourceRecord>)> = Vec::new();+ for record in records {+ match by_collection+ .iter_mut()+ .find(|(collection, _)| *collection == record.collection)+ {+ Some((_, batch)) => batch,+ None => {+ by_collection.push((record.collection.clone(), Vec::new()));+ &mut by_collection.last_mut().expect("just pushed").1+ }+ }+ .push(SourceRecord {+ id: record.id,+ body: record.doc,+ meta: Meta::unknown(),+ });+ }+ for (collection, batch) in by_collection {+ let step = schema.steps.iter().find(|step| {+ matches!(step.run, StepBody::Documents(_)) && step.source.unwrap_or(step.item) == collection+ });+ let Some(StepBody::Documents(run)) = step.map(|step| &step.run) else {+ upgraded.extend(batch.into_iter().map(|r| Record {+ collection: collection.clone(),+ id: r.id,+ doc: r.body,+ }));+ continue;+ };+ for target in run(batch)? {+ upgraded.push(Record {+ collection: target.collection,+ id: target.id,+ doc: target.body,+ });+ }+ }+ Ok((upgraded, specs))+}+/// The marker id for `source` in `workspace`: a backend shared by several/// workspaces keeps one marker per workspace.pub(crate) fn marker_id(domain: &str, workspace: &Path) -> String {@@ -290,11 +352,13 @@ fn import_one(source: &Source,) -> Result<Outcome> {let domain = source.domain;+ // The v2 collections are declared by the write itself (`upgrade` names+ // them); the v1 specs only tell the snapshot which document tables to read.let repo = Repo::on(backend,&super::scope::tenant_scope(None),domain,- source.collections,+ Vec::new,)?;let markers = Repo::on(backend,@@ -341,7 +405,12 @@ fn import_one();let total = found.len();+ let (found, specs) = upgrade(source.owner, found)+ .with_context(|| format!("[{domain}] bring the legacy records to schema v2"))?;let written = repo.run(move |docs| async move {+ for spec in &specs {+ docs.ensure_collection(spec).await?;+ }let mut written = 0usize;for record in found {match docs@@ -361,19 +430,6 @@ fn import_one(Ok(written)})?;- // The v1 records become the owner's v2 collections and shapes.- if written > 0 {- let scope = super::scope::tenant_scope(None);- let owner = source.owner;- let backend = Arc::clone(backend);- block_on_anyhow(async move {- super::boot::remigrate_owner(&backend, &scope, owner)- .await- .map(|_| ())- .map_err(Into::into)- })- .with_context(|| format!("[{domain}] migrate the imported records"))?;- }super::import_state::set_done(&markers, MARKER_OWNER, &step)?;Ok(Outcome::Imported {found: total,diff --git a/crates/openhuman-core/src/storage/import/mod_tests.rs b/crates/openhuman-core/src/storage/import/mod_tests.rsindex 2e38585f8e..b7ead05995 100644--- a/crates/openhuman-core/src/storage/import/mod_tests.rs+++ b/crates/openhuman-core/src/storage/import/mod_tests.rs@@ -53,12 +53,11 @@ fn dump(collection: &str,) -> BTreeMap<String, serde_json::Value> {let docs = Arc::clone(backend.for_scope(&Scope::local()).unwrap().documents());- let specs = (source.collections)();+ let _ = source;let collection = collection.to_string();crate::storage::block_on(async move {- for spec in &specs {- docs.ensure_collection(spec).await?;- }+ docs.ensure_collection(&tinystoragedrivers::CollectionSpec::new(&collection))+ .await?;let found = docs.query_all(&collection, &Query::all()).await?;Ok(found.into_iter().map(|d| (d.id, d.doc)).collect())})@@ -115,7 +114,7 @@ fn devices_move_into_the_backend_and_the_legacy_file_is_untouched() {let (found, written) = imported(run_with(&backend, &config, &[source]));assert_eq!((found, written), (3, 3));- let found = dump(&backend, &source, "paired_devices");+ let found = dump(&backend, &source, "devices.paired");assert_eq!(found["chan-a"]["label"], "Phone");assert_eq!(found["chan-a"]["core_session_token_hash"], "hash");assert_eq!(found["chan-a"]["revoked"], false);@@ -140,7 +139,7 @@ fn a_finished_import_does_not_run_again_or_resurrect_deleted_records() {// The user removes a record; the untouched legacy file still has it.let docs = Arc::clone(backend.for_scope(&Scope::local()).unwrap().documents());crate::storage::block_on(async move {- docs.delete("paired_devices", "chan-b", Precondition::None)+ docs.delete("devices.paired", "chan-b", Precondition::None).await}).unwrap();@@ -149,7 +148,7 @@ fn a_finished_import_does_not_run_again_or_resurrect_deleted_records() {outcome(run_with(&backend, &config, &[source])),Outcome::AlreadyDone);- assert!(!dump(&backend, &source, "paired_devices").contains_key("chan-b"));+ assert!(!dump(&backend, &source, "devices.paired").contains_key("chan-b"));}#[test]@@ -160,41 +159,23 @@ fn an_import_claimed_by_another_process_waits_for_it_and_does_not_repeat_it() {let source = devices();// Another process holds the claim for this domain and workspace, and- // finishes (marker written, claim released) shortly after we start.+ // finishes (marked done, claim released) shortly after we start.let markers = Repo::on(&backend, &Scope::local(), "storage::import", marker_spec).unwrap();- let marker = marker_id(source.domain, &config.workspace_dir);- let claim = crate::storage::import_claim::claim_id(&marker);- let held_claim = claim.clone();- let version = markers- .run(move |docs| async move {- docs.put(- MARKER_COLLECTION,- &held_claim,- json!({ "claimed_at_ms": chrono::Utc::now().timestamp_millis() }),- Precondition::Absent,- )- .await- })- .unwrap();+ let step = marker_step(source.domain, &config.workspace_dir);+ let (held_tx, held_rx) = std::sync::mpsc::channel::<()>();let finisher = {- let markers = markers.clone();+ let (markers, step) = (markers.clone(), step.clone());std::thread::spawn(move || {- std::thread::sleep(std::time::Duration::from_millis(400));- markers- .run(move |docs| async move {- docs.put(- MARKER_COLLECTION,- &marker,- json!({ "version": MARKER_VERSION, "found": 1, "written": 1 }),- Precondition::Absent,- )- .await?;- docs.delete(MARKER_COLLECTION, &claim, Precondition::Version(version))- .await- })- .unwrap();+ crate::storage::import_state::with_claim(&markers, MARKER_OWNER, &step.clone(), || {+ held_tx.send(()).unwrap();+ std::thread::sleep(std::time::Duration::from_millis(400));+ crate::storage::import_state::set_done(&markers, MARKER_OWNER, &step)+ })+ .unwrap()+ .expect("the first claimant runs");})};+ held_rx.recv().unwrap();let started = std::time::Instant::now();assert_eq!(@@ -206,7 +187,42 @@ fn an_import_claimed_by_another_process_waits_for_it_and_does_not_repeat_it() {"the loser must not proceed while the claim is held");finisher.join().unwrap();- assert!(dump(&backend, &source, "paired_devices").is_empty());+ assert!(dump(&backend, &source, "devices.paired").is_empty());+}++#[test]+fn a_marker_row_an_older_build_wrote_counts_as_a_finished_import() {+ let (_dir, config) = workspace();+ legacy_device(&config, "chan-a", "Phone", false);+ let backend = backend();+ let source = devices();+ let marker = marker_id(source.domain, &config.workspace_dir);+ let scoped = backend.for_scope(&Scope::local()).unwrap();+ let docs = Arc::clone(scoped.documents());+ crate::storage::block_on(async move {+ docs.ensure_collection(&tinystoragedrivers::CollectionSpec::new(MARKER_KIND))+ .await?;+ docs.put(+ MARKER_KIND,+ &marker,+ serde_json::json!({ "version": 1, "found": 1, "written": 1 }),+ Precondition::Absent,+ )+ .await+ })+ .unwrap();+ // Boot moves the marker row into `tsd.migrations`.+ crate::storage::block_on(async {+ crate::storage::import_state::migrate_legacy_markers(&scoped).await+ })+ .unwrap();++ assert!(is_done(&backend, &config, &source).unwrap());+ assert_eq!(+ outcome(run_with(&backend, &config, &[source])),+ Outcome::AlreadyDone+ );+ assert!(dump(&backend, &source, "devices.paired").is_empty());}#[test]@@ -246,7 +262,7 @@ fn processes_importing_one_workspace_at_once_import_it_once() {})));assert!(is_done(&backend, &config, &source).unwrap());- assert_eq!(dump(&backend, &source, "paired_devices").len(), 20);+ assert_eq!(dump(&backend, &source, "devices.paired").len(), 20);}#[test]@@ -259,10 +275,10 @@ fn an_existing_record_is_never_overwritten() {// A record the new code already wrote (a resumed import).let docs = Arc::clone(backend.for_scope(&Scope::local()).unwrap().documents());crate::storage::block_on(async move {- docs.ensure_collection(&(source.collections)().remove(0))+ docs.ensure_collection(&tinystoragedrivers::CollectionSpec::new("devices.paired")).await?;docs.put(- "paired_devices",+ "devices.paired","chan-a",serde_json::json!({ "label": "newer" }),Precondition::Absent,@@ -275,7 +291,7 @@ fn an_existing_record_is_never_overwritten() {assert_eq!((found, written), (2, 1));assert_eq!(- dump(&backend, &source, "paired_devices")["chan-a"]["label"],+ dump(&backend, &source, "devices.paired")["chan-a"]["label"],"newer");}@@ -356,7 +372,7 @@ fn records_the_previous_release_wrote_as_documents_are_imported_and_win_over_leg// chan-a from the document table (newer copy) and the legacy row with the// same id (skipped), plus chan-d.assert_eq!((found, written), (3, 2));- let devices = dump(&backend, &source, "paired_devices");+ let devices = dump(&backend, &source, "devices.paired");assert_eq!(devices["chan-a"]["label"], "Renamed");assert_eq!(devices["chan-a"]["revoked"], true);assert_eq!(devices["chan-d"]["label"], "Only a document");@@ -385,7 +401,7 @@ fn rows_still_in_the_write_ahead_log_are_read() {assert_eq!((found, written), (1, 1));assert_eq!(- dump(&backend, &source, "paired_devices")["wal-chan"]["label"],+ dump(&backend, &source, "devices.paired")["wal-chan"]["label"],"In the log");drop(conn);