Skip to content

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

feat(storage): add import claim tracking for concurrent imports

Steven Enamakel50e4e1430f9c
diff --git a/crates/openhuman-core/src/storage/import_claim.rs b/crates/openhuman-core/src/storage/import_claim.rs
deleted file mode 100644
index a99e89f633..0000000000
--- a/crates/openhuman-core/src/storage/import_claim.rs
+++ /dev/null
@@ -1,206 +0,0 @@
-//! A short lease that serialises the one-time legacy importers across
-//! processes.
-//!
-//! Every importer already writes its records with `Precondition::Absent` and
-//! its completion marker the same way, so two processes importing one
-//! workspace converge on the same documents. What the marker alone cannot
-//! prevent is both of them doing the whole read-and-copy at the same time.
-//! [`with_claim`] puts a claim document beside the marker (`<marker>#claim`)
-//! with `Precondition::Absent` before the import starts; the process that
-//! loses the race waits, then re-checks the marker (the winner wrote it)
-//! instead of repeating the import. A claim is released when the import ends, success or failure,
-//! and a claim older than [`CLAIM_TTL_MS`] (its owner crashed) is taken over
-//! with a version-checked write, so a dead process never blocks the import.
-//! The owner renews the claim while it works; a process that finds a live
-//! claim waits for it instead of proceeding.
-
-use anyhow::Result;
-use serde_json::json;
-use tinystoragedrivers::{ErrorKind, Precondition};
-
-use super::documents::Repo;
-
-/// How long a claim blocks other processes before it counts as abandoned.
-pub const CLAIM_TTL_MS: i64 = 10 * 60 * 1000;
-
-const LOG_PREFIX: &str = "[storage::import_claim]";
-
-/// The claim document id for a marker id.
-pub fn claim_id(marker: &str) -> String {
- format!("{marker}#claim")
-}
-
-/// How often a waiting process re-tries a claim another process holds.
-const WAIT_POLL: std::time::Duration = std::time::Duration::from_millis(100);
-
-/// Runs `body` while holding the claim for `marker` in `collection`, which
-/// `repo` must declare.
-///
-/// A live claim held by another process is waited out (up to [`CLAIM_TTL_MS`]),
-/// so a caller never proceeds while the winner is still copying; once the
-/// claim is free `body` runs, and it must re-check its completion marker
-/// because the winner has usually finished the work by then. Returns `None`
-/// only when the claim stays held for the whole wait.
-///
-/// The claim is renewed while `body` runs, so a long import is not mistaken
-/// for a crashed one.
-///
-/// # Errors
-///
-/// A storage error while claiming, or whatever `body` returns. The claim is
-/// released either way.
-pub fn with_claim<T>(
- repo: &Repo,
- collection: &'static str,
- marker: &str,
- body: impl FnOnce() -> Result<T>,
-) -> Result<Option<T>> {
- // `with_claim_at` only runs the closure once it holds the claim.
- let mut body = Some(body);
- let started = std::time::Instant::now();
- loop {
- let now = chrono::Utc::now().timestamp_millis();
- if let Some(ran) = with_claim_at(repo, collection, marker, now, CLAIM_TTL_MS, || {
- (body.take().expect("import body runs once"))()
- })? {
- return Ok(Some(ran));
- }
- if started.elapsed().as_millis() as i64 >= CLAIM_TTL_MS {
- return Ok(None);
- }
- std::thread::sleep(WAIT_POLL);
- }
-}
-
-/// One attempt of [`with_claim`] with an explicit clock and lease length, for
-/// tests: returns `None` without running `body` or waiting when another live
-/// process holds the claim.
-pub fn with_claim_at<T>(
- repo: &Repo,
- collection: &'static str,
- marker: &str,
- now_ms: i64,
- ttl_ms: i64,
- body: impl FnOnce() -> Result<T>,
-) -> Result<Option<T>> {
- let id = claim_id(marker);
- let Some(held) = acquire(repo, collection, &id, now_ms, ttl_ms)? else {
- tracing::debug!(
- target: "openhuman::storage_import",
- claim = %id,
- "{LOG_PREFIX} another process holds the import claim"
- );
- return Ok(None);
- };
- let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
- let heartbeat = {
- let (repo, id) = (repo.clone(), id.clone());
- let interval = std::time::Duration::from_millis((ttl_ms / 3).max(1) as u64);
- // A bare OS thread on purpose (baselined in the SaaS ambient ratchet):
- // the heartbeat reads no ambient state, only the `repo` handed to it,
- // and is joined below before this returns. `with_claim` is synchronous
- // and may run outside a tokio runtime, so `DispatchCtx::spawn_blocking`
- // (which needs `Handle::current()`) is not available here.
- std::thread::spawn(move || {
- let started = std::time::Instant::now();
- let mut version = held;
- while let Err(std::sync::mpsc::RecvTimeoutError::Timeout) =
- stop_rx.recv_timeout(interval)
- {
- let at = now_ms.saturating_add(started.elapsed().as_millis() as i64);
- let renew_id = id.clone();
- let renewed = repo.run(move |docs| async move {
- docs.put(
- collection,
- &renew_id,
- json!({ "claimed_at_ms": at, "pid": std::process::id() }),
- Precondition::Version(version),
- )
- .await
- });
- match renewed {
- Ok(next) => version = next,
- Err(error) => {
- tracing::warn!(
- target: "openhuman::storage_import",
- claim = %id,
- error = %format!("{error:#}"),
- "{LOG_PREFIX} could not renew the import claim"
- );
- break;
- }
- }
- }
- version
- })
- };
- let result = body();
- let _ = stop_tx.send(());
- let held = heartbeat.join().unwrap_or(held);
- let release_id = id.clone();
- let released = repo.run(move |docs| async move {
- docs.delete(collection, &release_id, Precondition::Version(held))
- .await
- });
- if let Err(error) = released {
- // The lease expires on its own; releasing is an optimisation.
- tracing::warn!(
- target: "openhuman::storage_import",
- claim = %id,
- error = %format!("{error:#}"),
- "{LOG_PREFIX} could not release the import claim; it expires on its own"
- );
- }
- result.map(Some)
-}
-
-/// Takes the claim, returning the version of the claim document, or `None`
-/// when a live claim belongs to someone else.
-fn acquire(
- repo: &Repo,
- collection: &'static str,
- id: &str,
- now_ms: i64,
- ttl_ms: i64,
-) -> Result<Option<tinystoragedrivers::Version>> {
- let id = id.to_string();
- repo.run(move |docs| async move {
- let doc = json!({ "claimed_at_ms": now_ms, "pid": std::process::id() });
- // A few rounds cover a claim that is released between our two reads.
- for _ in 0..4 {
- match docs
- .put(collection, &id, doc.clone(), Precondition::Absent)
- .await
- {
- Ok(version) => return Ok(Some(version)),
- Err(error) if error.kind() == ErrorKind::Conflict => {}
- Err(error) => return Err(error),
- }
- let Some(stored) = docs.get(collection, &id).await? else {
- continue;
- };
- let claimed = stored
- .doc
- .get("claimed_at_ms")
- .and_then(serde_json::Value::as_i64)
- .unwrap_or(0);
- if now_ms.saturating_sub(claimed) < ttl_ms {
- return Ok(None);
- }
- match docs
- .put(collection, &id, doc.clone(), stored.unchanged())
- .await
- {
- Ok(version) => return Ok(Some(version)),
- // Someone else took the stale claim first.
- Err(error) if error.kind() == ErrorKind::Conflict => return Ok(None),
- Err(error) => return Err(error),
- }
- }
- Ok(None)
- })
-}
-
-#[cfg(test)]
-#[path = "import_claim_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/storage/import_claim_tests.rs b/crates/openhuman-core/src/storage/import_claim_tests.rs
deleted file mode 100644
index 219428581a..0000000000
--- a/crates/openhuman-core/src/storage/import_claim_tests.rs
+++ /dev/null
@@ -1,188 +0,0 @@
-use super::*;
-use crate::storage::{MemoryStorage, Scope, StorageBackend};
-use std::sync::mpsc;
-use std::sync::Arc;
-use tinystoragedrivers::CollectionSpec;
-
-const COLLECTION: &str = "claims_test";
-
-fn spec() -> Vec<CollectionSpec> {
- vec![CollectionSpec::new(COLLECTION)]
-}
-
-fn repo() -> Repo {
- let backend: Arc<dyn StorageBackend> = Arc::new(MemoryStorage::new());
- Repo::on(&backend, &Scope::local(), "claim-test", spec).unwrap()
-}
-
-fn claim_exists(repo: &Repo, marker: &str) -> bool {
- let id = claim_id(marker);
- repo.run(move |docs| async move { docs.get(COLLECTION, &id).await })
- .unwrap()
- .is_some()
-}
-
-#[test]
-fn claim_runs_the_body_and_releases() {
- let repo = repo();
- let ran = with_claim(&repo, COLLECTION, "m", || Ok(7)).unwrap();
- assert_eq!(ran, Some(7));
- assert!(!claim_exists(&repo, "m"));
-}
-
-#[test]
-fn claim_is_released_when_the_body_fails() {
- let repo = repo();
- let result: Result<Option<()>> =
- with_claim(&repo, COLLECTION, "m", || Err(anyhow::anyhow!("boom")));
- assert!(result.is_err());
- assert!(!claim_exists(&repo, "m"));
- assert_eq!(
- with_claim(&repo, COLLECTION, "m", || Ok(1)).unwrap(),
- Some(1)
- );
-}
-
-#[test]
-fn a_second_process_skips_while_the_first_is_importing() {
- let repo = repo();
- let (started_tx, started_rx) = mpsc::channel::<()>();
- let (finish_tx, finish_rx) = mpsc::channel::<()>();
- let holder_repo = repo.clone();
- let holder = std::thread::spawn(move || {
- with_claim(&holder_repo, COLLECTION, "m", || {
- started_tx.send(()).unwrap();
- finish_rx.recv().unwrap();
- Ok("first")
- })
- .unwrap()
- });
- started_rx.recv().unwrap();
-
- let mut second_ran = false;
- let now = chrono::Utc::now().timestamp_millis();
- let second = with_claim_at(&repo, COLLECTION, "m", now, CLAIM_TTL_MS, || {
- second_ran = true;
- Ok("second")
- })
- .unwrap();
- assert_eq!(second, None);
- assert!(!second_ran);
-
- finish_tx.send(()).unwrap();
- assert_eq!(holder.join().unwrap(), Some("first"));
- assert_eq!(
- with_claim(&repo, COLLECTION, "m", || Ok("third")).unwrap(),
- Some("third")
- );
-}
-
-#[test]
-fn many_racing_processes_run_the_body_once_at_a_time() {
- let repo = repo();
- let active = Arc::new(std::sync::atomic::AtomicUsize::new(0));
- let overlap = Arc::new(std::sync::atomic::AtomicBool::new(false));
- let barrier = Arc::new(std::sync::Barrier::new(8));
- let handles: Vec<_> = (0..8)
- .map(|_| {
- let (repo, active, overlap, barrier) = (
- repo.clone(),
- Arc::clone(&active),
- Arc::clone(&overlap),
- Arc::clone(&barrier),
- );
- std::thread::spawn(move || {
- barrier.wait();
- with_claim(&repo, COLLECTION, "m", || {
- use std::sync::atomic::Ordering::SeqCst;
- if active.fetch_add(1, SeqCst) != 0 {
- overlap.store(true, SeqCst);
- }
- std::thread::sleep(std::time::Duration::from_millis(30));
- active.fetch_sub(1, SeqCst);
- Ok(())
- })
- .unwrap()
- .is_some()
- })
- })
- .collect();
- let ran = handles
- .into_iter()
- .map(|h| h.join().unwrap())
- .filter(|r| *r)
- .count();
- assert!(ran >= 1, "somebody imports");
- assert!(
- !overlap.load(std::sync::atomic::Ordering::SeqCst),
- "two bodies held the claim at once"
- );
-}
-
-#[test]
-fn a_stale_claim_is_taken_over() {
- let repo = repo();
- let id = claim_id("m");
- let seeded = id.clone();
- repo.run(move |docs| async move {
- docs.put(
- COLLECTION,
- &seeded,
- serde_json::json!({ "claimed_at_ms": 1_000 }),
- Precondition::Absent,
- )
- .await
- .map(|_| ())
- })
- .unwrap();
-
- // Fresh: still held.
- let held = with_claim_at(&repo, COLLECTION, "m", 1_000 + 10, 100, || Ok(())).unwrap();
- assert_eq!(held, None);
- // Past the lease: taken over, run, released.
- let taken = with_claim_at(&repo, COLLECTION, "m", 1_000 + 200, 100, || Ok(())).unwrap();
- assert_eq!(taken, Some(()));
- assert!(!claim_exists(&repo, "m"));
-}
-
-#[test]
-fn a_waiting_process_runs_once_the_holder_releases() {
- let repo = repo();
- let (started_tx, started_rx) = mpsc::channel::<()>();
- let holder_repo = repo.clone();
- let holder = std::thread::spawn(move || {
- with_claim(&holder_repo, COLLECTION, "m", || {
- started_tx.send(()).unwrap();
- std::thread::sleep(std::time::Duration::from_millis(400));
- Ok("first")
- })
- .unwrap()
- });
- started_rx.recv().unwrap();
- let began = std::time::Instant::now();
- let second = with_claim(&repo, COLLECTION, "m", || Ok("second")).unwrap();
- assert_eq!(second, Some("second"));
- assert!(began.elapsed() >= std::time::Duration::from_millis(200));
- assert_eq!(holder.join().unwrap(), Some("first"));
-}
-
-#[test]
-fn a_long_import_keeps_its_claim_alive() {
- let repo = repo();
- let now = chrono::Utc::now().timestamp_millis();
- // 90ms lease, body runs 400ms: without renewal a rival would take over.
- let rival_repo = repo.clone();
- let rival_ran = with_claim_at(&repo, COLLECTION, "m", now, 90, || {
- let mut took_over = false;
- for _ in 0..8 {
- std::thread::sleep(std::time::Duration::from_millis(50));
- let at = chrono::Utc::now().timestamp_millis();
- took_over |= with_claim_at(&rival_repo, COLLECTION, "m", at, 90, || Ok(()))
- .unwrap()
- .is_some();
- }
- Ok(took_over)
- })
- .unwrap();
- assert_eq!(rival_ran, Some(false));
-}
diff --git a/crates/openhuman-core/src/storage/import_state.rs b/crates/openhuman-core/src/storage/import_state.rs
new file mode 100644
index 0000000000..5668854f74
--- /dev/null
+++ b/crates/openhuman-core/src/storage/import_state.rs
@@ -0,0 +1,305 @@
+//! Where a one-time legacy importer records that it finished, and the claim
+//! that keeps two processes from importing at once.
+//!
+//! Both are tsd primitives, not host collections:
+//!
+//! - **Completion** is a `tsd.migrations` entry ([`Migrations::mark_done`]) in
+//! the scope the importer writes to, keyed `(owner, step)`. This replaces
+//! the per-domain marker collections (`storage_import`, `threads_import`,
+//! `subagent_sessions_import`, `composio_state_import` and the module
+//! `*_host_import` ones). A marker row an older build wrote is honoured by
+//! [`migrate_legacy_markers`], which turns each into the same entry at boot,
+//! so an installed profile is never imported twice.
+//! - **The claim** is a [`Leases`] lease on `(owner, step)` in `tsd.leases`
+//! (schema-v2 section 5). The process that wins it copies the legacy
+//! records; the others wait it out, then re-check completion. The owner
+//! renews the lease while it works, and a lease that lapses (its owner
+//! crashed) is taken over by the next acquirer, so a dead process never
+//! blocks an import.
+//!
+//! A step is named `<kind>/<id>`: `kind` is the old marker collection name
+//! (`storage_import`) and `id` the old marker id (`approval@<workspace
+//! digest>`), so both the new check and the migrated entry derive from the
+//! same pair.
+
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use anyhow::{anyhow, Result};
+use tinystoragedrivers::schema::Migrations;
+use tinystoragedrivers::{
+ Capability, DocumentStore, DocumentStoreExt, Leases, Query, ScopedStorage, StorageError,
+};
+
+use super::documents::Repo;
+
+/// How long a claim blocks other processes before it counts as abandoned.
+pub const CLAIM_TTL_MS: i64 = 10 * 60 * 1000;
+
+/// The `tsd.leases` owner of import claims.
+const CLAIM_OWNER: &str = "import";
+
+const LOG_PREFIX: &str = "[storage::import_state]";
+
+/// How often a waiting process re-tries a claim another process holds.
+const WAIT_POLL: Duration = Duration::from_millis(100);
+
+/// The legacy marker collections and the `tsd.migrations` owner each moves
+/// under. A marker lived in the scope its importer wrote to, so every scope
+/// is swept.
+pub const LEGACY_MARKERS: &[(&str, &str)] = &[
+ ("storage_import", "storage"),
+ ("threads_import", "threads"),
+ ("subagent_sessions_import", "subagents"),
+ ("composio_state_import", "composio"),
+ ("channels_host_import", "host"),
+ ("tinybox_host_import", "host"),
+ ("tinyconnectors_host_import", "host"),
+ ("tinywallet_host_import", "host"),
+ ("tinyjuice_host_import", "host"),
+ ("mcp_host_import", "host"),
+];
+
+/// The step name of the importer that wrote marker `id` into `kind`.
+#[must_use]
+pub fn step_id(kind: &str, id: &str) -> String {
+ format!("{kind}/{id}")
+}
+
+/// Declares the primitives an import state needs, for a backend that did not
+/// go through the boot `prepare` (a test's, an embedder's).
+async fn declare(docs: &Arc<dyn DocumentStore>) -> Result<(), StorageError> {
+ for spec in tinystoragedrivers::primitives::collection_specs() {
+ docs.ensure_collection(&spec).await?;
+ }
+ Ok(())
+}
+
+/// Whether importer `step` of `owner` finished in `scoped`'s scope.
+///
+/// # Errors
+///
+/// A storage error.
+pub async fn done(scoped: &ScopedStorage, owner: &str, step: &str) -> Result<bool, StorageError> {
+ declare(scoped.documents()).await?;
+ Migrations::new(scoped).done(owner, step).await
+}
+
+/// Records importer `step` of `owner` as finished in `scoped`'s scope.
+///
+/// # Errors
+///
+/// A storage error.
+pub async fn mark_done(scoped: &ScopedStorage, owner: &str, step: &str) -> Result<(), StorageError> {
+ declare(scoped.documents()).await?;
+ Migrations::new(scoped).mark_done(owner, step).await
+}
+
+/// [`done`] from synchronous code, over the scope `repo` was opened on.
+///
+/// # Errors
+///
+/// A storage error.
+pub fn is_done(repo: &Repo, owner: &str, step: &str) -> Result<bool> {
+ let scoped = repo.scoped().clone();
+ let (owner, step) = (owner.to_owned(), step.to_owned());
+ repo.run(move |_| async move { done(&scoped, &owner, &step).await })
+}
+
+/// [`mark_done`] from synchronous code.
+///
+/// # Errors
+///
+/// A storage error.
+pub fn set_done(repo: &Repo, owner: &str, step: &str) -> Result<()> {
+ let scoped = repo.scoped().clone();
+ let (owner, step) = (owner.to_owned(), step.to_owned());
+ repo.run(move |_| async move { mark_done(&scoped, &owner, &step).await })
+}
+
+/// Runs `body` while holding the claim for `(owner, step)` in `repo`'s scope.
+///
+/// A live claim held by another process is waited out (up to
+/// [`CLAIM_TTL_MS`]); once it is free `body` runs, and it must re-check its
+/// completion because the winner has usually finished by then. Returns `None`
+/// only when the claim stays held for the whole wait. The claim is renewed
+/// while `body` runs, so a long import is not mistaken for a crashed one.
+///
+/// # Errors
+///
+/// A storage error while claiming, or whatever `body` returns. The claim is
+/// released either way.
+pub fn with_claim<T>(
+ repo: &Repo,
+ owner: &str,
+ step: &str,
+ body: impl FnOnce() -> Result<T>,
+) -> Result<Option<T>> {
+ // `with_claim_at` only runs the closure once it holds the claim.
+ let mut body = Some(body);
+ let started = Instant::now();
+ loop {
+ let now = chrono::Utc::now().timestamp_millis();
+ if let Some(ran) = with_claim_at(repo, owner, step, now, CLAIM_TTL_MS, || {
+ (body.take().expect("import body runs once"))()
+ })? {
+ return Ok(Some(ran));
+ }
+ if started.elapsed().as_millis() as i64 >= CLAIM_TTL_MS {
+ return Ok(None);
+ }
+ std::thread::sleep(WAIT_POLL);
+ }
+}
+
+/// One attempt of [`with_claim`] with an explicit clock and lease length, for
+/// tests: returns `None` without running `body` or waiting when another live
+/// process holds the claim.
+pub fn with_claim_at<T>(
+ repo: &Repo,
+ owner: &str,
+ step: &str,
+ now_ms: i64,
+ ttl_ms: i64,
+ body: impl FnOnce() -> Result<T>,
+) -> Result<Option<T>> {
+ let started = Instant::now();
+ let clock: tinystoragedrivers::Clock = Arc::new(move || {
+ (now_ms.max(0) as u64).saturating_add(started.elapsed().as_millis() as u64)
+ });
+ // A holder name unique to this attempt, so two threads of one process do
+ // not both "re-acquire" the same live lease.
+ let holder = format!("pid-{}-{}", std::process::id(), uuid::Uuid::new_v4());
+ let (claim_owner, claim_key) = (owner.to_owned(), step.to_owned());
+ let acquired = {
+ let (clock, holder) = (clock.clone(), holder.clone());
+ let (owner, key) = (claim_owner.clone(), claim_key.clone());
+ repo.run(move |docs| async move {
+ declare(&docs).await?;
+ Leases::new(&docs)
+ .with_clock(clock)
+ .acquire(CLAIM_OWNER, &lease_key(&owner, &key), &holder, ttl_ms)
+ .await
+ })?
+ };
+ let Some(mut held) = acquired else {
+ tracing::debug!(
+ target: "openhuman::storage_import",
+ owner,
+ step,
+ "{LOG_PREFIX} another process holds the import claim"
+ );
+ return Ok(None);
+ };
+ let epoch = held.epoch;
+ let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
+ let heartbeat = {
+ let (repo, clock, holder) = (repo.clone(), clock.clone(), holder.clone());
+ let key = lease_key(&claim_owner, &claim_key);
+ let interval = Duration::from_millis((ttl_ms / 3).max(1) as u64);
+ // A bare OS thread on purpose (baselined in the SaaS ambient ratchet):
+ // the heartbeat reads no ambient state, only the `repo` handed to it,
+ // and is joined below before this returns. `with_claim` is synchronous
+ // and may run outside a tokio runtime, so `DispatchCtx::spawn_blocking`
+ // (which needs `Handle::current()`) is not available here.
+ std::thread::spawn(move || {
+ while let Err(std::sync::mpsc::RecvTimeoutError::Timeout) =
+ stop_rx.recv_timeout(interval)
+ {
+ let (clock, holder, key) = (clock.clone(), holder.clone(), key.clone());
+ let renewed = repo.run(move |docs| async move {
+ Leases::new(&docs)
+ .with_clock(clock)
+ .renew(CLAIM_OWNER, &key, &holder, epoch, ttl_ms)
+ .await
+ });
+ match renewed {
+ Ok(Some(next)) => held = next,
+ Ok(None) | Err(_) => {
+ tracing::warn!(
+ target: "openhuman::storage_import",
+ "{LOG_PREFIX} could not renew the import claim"
+ );
+ break;
+ }
+ }
+ }
+ held.epoch
+ })
+ };
+ let result = body();
+ let _ = stop_tx.send(());
+ let epoch = heartbeat.join().unwrap_or(epoch);
+ let released = {
+ let key = lease_key(&claim_owner, &claim_key);
+ repo.run(move |docs| async move {
+ Leases::new(&docs)
+ .with_clock(clock)
+ .release(CLAIM_OWNER, &key, &holder, epoch)
+ .await
+ })
+ };
+ if let Err(error) = released {
+ // The lease expires on its own; releasing is an optimisation.
+ tracing::warn!(
+ target: "openhuman::storage_import",
+ error = %format!("{error:#}"),
+ "{LOG_PREFIX} could not release the import claim; it expires on its own"
+ );
+ }
+ result.map(Some)
+}
+
+fn lease_key(owner: &str, step: &str) -> String {
+ format!("{owner}/{step}")
+}
+
+/// Turns the marker rows older builds wrote ([`LEGACY_MARKERS`]) in `scoped`'s
+/// scope into `tsd.migrations` entries and removes the old collections, so an
+/// already imported profile is not imported again. Returns the markers moved.
+///
+/// Idempotent: a marker already moved is simply marked again, and a collection
+/// that is gone is skipped. A claim row (`<id>#claim`) is dropped with its
+/// collection.
+///
+/// # Errors
+///
+/// A storage error; the markers not yet moved stay in place for the next boot.
+pub async fn migrate_legacy_markers(scoped: &ScopedStorage) -> Result<usize, StorageError> {
+ let docs = scoped.documents();
+ if !docs.capabilities().contains(Capability::CollectionEnumeration) {
+ return Ok(0);
+ }
+ let present = docs.collections("").await?;
+ let mut moved = 0;
+ for (collection, owner) in LEGACY_MARKERS {
+ if !present.iter().any(|name| name == collection) {
+ continue;
+ }
+ declare(docs).await?;
+ for marker in docs.query_all(collection, &Query::all()).await? {
+ if marker.id.ends_with("#claim") {
+ continue;
+ }
+ mark_done(scoped, owner, &step_id(collection, &marker.id)).await?;
+ moved += 1;
+ }
+ docs.drop_collection(collection).await?;
+ tracing::info!(
+ target: "openhuman::storage",
+ collection,
+ owner,
+ "{LOG_PREFIX} legacy import markers moved to tsd.migrations"
+ );
+ }
+ Ok(moved)
+}
+
+/// A claim failure as an `anyhow` error naming the step.
+pub fn claim_error(step: &str, error: impl std::fmt::Display) -> anyhow::Error {
+ anyhow!("{LOG_PREFIX} claim {step}: {error}")
+}
+
+#[cfg(test)]
+#[path = "import_state_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/storage/mod.rs b/crates/openhuman-core/src/storage/mod.rs
index 31fc9d33d2..a401d51961 100644
--- a/crates/openhuman-core/src/storage/mod.rs
+++ b/crates/openhuman-core/src/storage/mod.rs
@@ -32,7 +32,7 @@ pub mod documents;
pub mod fence;
pub mod fenced_backend;
pub mod import;
-pub mod import_claim;
+pub mod import_state;
pub mod lease;
mod lease_documents;
mod lease_local;