Skip to content

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

chore: files changed crates/openhuman-core/Cargo.toml,crates/openhuman-core/src/memory/import.rs,cra

Steven Enamakel81ff63ebe8d8
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index f9e963071b..dbae371c5e 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -217,7 +217,7 @@ tinytools-std = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinyto
# network readers), secret/PII scrubbing and the read-only v1 importer.
# `memory::` is the only module that names the engine side.
tinymemory-api = { path = "../../vendor/tinymemory/crates/tinymemory-api", features = ["local-safety"] }
-tinymemory-tools = { path = "../../vendor/tinymemory/crates/tinymemory-tools", features = ["schema"] }
+tinymemory-tools = { path = "../../vendor/tinymemory/crates/tinymemory-tools", features = ["schema", "fs-claim"] }
tinyredact = { path = "../../vendor/tinymemory/crates/tinyredact" }
tinymemory-integrations = { path = "../../vendor/tinymemory/crates/tinymemory-integrations", default-features = false, features = ["cortex", "brain", "sources-network", "safety", "legacy-import", "schema"] }
# tinyconnectors-bus — the OAuth connector wire contract
diff --git a/crates/openhuman-core/src/memory/import.rs b/crates/openhuman-core/src/memory/import.rs
index e54be80494..4592cea9cd 100644
--- a/crates/openhuman-core/src/memory/import.rs
+++ b/crates/openhuman-core/src/memory/import.rs
@@ -1,26 +1,23 @@
//! Importing a v1 memory store into the selected engine.
//!
-//! The driver (batching, checkpoints, backoff, failed-item list, retry) is
-//! `tinymemory_integrations::import::Importer`. This file is the host
-//! adapter around it: the consent gate, the one-run-per-workspace registry,
-//! the atomic state file `<workspace>/memory/import_state.json`, the tokio
-//! clock, the scheduler pause, the credits resume policy, and what follows a
-//! finished import (organizing the tree).
+//! TinyMemory owns import batching, checkpoints, retry and backoff. This host
+//! adapter keeps consent, the existing atomic checkpoint path, billing and
+//! scheduler policy, executor context, and post-import layout migration.
-use std::collections::HashSet;
use std::path::{Path, PathBuf};
-use std::sync::{Arc, LazyLock, Mutex};
+use std::sync::Arc;
use std::time::Duration;
use tinymemory_integrations::import::{
- Begun, CheckpointStore, ImportCounts as LegacyImportCounts, ImportError, ImportFile,
- ImportPhase, ImportState, Importer, Pacer,
+ CheckpointStore, ImportCounts as LegacyImportCounts, ImportError, ImportFile, ImportPhase,
+ ImportState, Importer, Pacer, ResumePlan,
};
use crate::config::Config;
use crate::security::secret_storage::file_store::write_atomic;
use super::engine;
+use super::run_slots::{self, BACKFILL, IMPORT, MIGRATION};
use super::types::{ImportCounts, ImportScanView};
use tinymemory_api::{Error, Result};
@@ -28,32 +25,9 @@ use tinymemory_api::{Error, Result};
/// before it starts and again before every batch it stores.
pub(crate) type PauseCheck = Arc<dyn Fn() -> bool + Send + Sync>;
-/// Whether memory work that uploads on its own, with no user action (an
-/// automatic import, or resuming one paused for credits), may run now.
+/// Whether memory work that uploads on its own may run now.
pub(crate) type BillingCheck = Arc<dyn Fn(&Config) -> bool + Send + Sync>;
-/// Imports running now, per workspace.
-static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
-
-/// Held while an import or a layout migration decides to start: each checks
-/// the other is not going, then registers itself, under this one lock, so
-/// neither can slip in between the other's check and its registration.
-pub(crate) static START_GATE: Mutex<()> = Mutex::new(());
-
-fn running(workspace_dir: &Path) -> bool {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .contains(workspace_dir)
-}
-
-fn release(workspace_dir: &Path) {
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .remove(workspace_dir);
-}
-
/// The state file, written atomically (staged, synced, renamed): a crash
/// mid-write leaves the previous state, never a torn file that reads back as
/// a fresh start and re-sends everything.
@@ -83,7 +57,6 @@ impl CheckpointStore for FileCheckpointStore {
}
}
-/// Backoff sleeps on the tokio clock.
struct TokioPacer;
#[async_trait::async_trait]
@@ -98,8 +71,7 @@ fn read_file(workspace_dir: &Path) -> ImportFile {
}
/// Whether the last import ended with its last batch not confirmed listed:
-/// the layout migration then forgets by id, never erasing scopes whole, and
-/// copies again before it finishes. Only an import that confirms clears it.
+/// the layout migration then forgets by id, never erasing scopes whole.
pub(crate) fn listed_unconfirmed(workspace_dir: &Path) -> bool {
read_file(workspace_dir).listed_unconfirmed
}
@@ -147,28 +119,29 @@ pub async fn scan(config: &Config) -> Result<ImportScanView> {
})
}
-/// Whether an import is unfinished: running now, interrupted (it resumes on
-/// its own), or paused for credits. The layout migration waits for it, so
-/// old local memory lands before the tree is reorganised.
+/// Whether an import blocks layout migration: a live import or one paused for
+/// credits. A persisted `Running` phase without a run slot is interrupted, not
+/// live work; the scheduler can resume it before migration starts.
#[must_use]
pub fn in_progress(config: &Config) -> bool {
- // A live import counts from its reservation, before its first state
- // write (the scan of the old store comes first).
- let file = read_file(&config.workspace_dir);
- running(&config.workspace_dir)
- || file.state.phase == ImportPhase::Running
- || file.paused_for_credits
+ IMPORT.is_running(&config.workspace_dir) || read_file(&config.workspace_dir).paused_for_credits
+}
+
+/// Whether this workspace has an import task right now.
+#[must_use]
+pub(crate) fn is_running(workspace_dir: &Path) -> bool {
+ IMPORT.is_running(&workspace_dir.to_path_buf())
}
/// `memory_import_status`.
#[must_use]
pub fn status(config: &Config) -> ImportState {
- let mut state = read_file(&config.workspace_dir).state;
- if state.phase == ImportPhase::Running && !running(&config.workspace_dir) {
+ let file = read_file(&config.workspace_dir);
+ let mut state = file.state;
+ if state.phase == ImportPhase::Running && !is_running(&config.workspace_dir) {
state.phase = ImportPhase::Error;
state.error = Some(state.error.unwrap_or_else(|| {
- "the import was interrupted; it resumes on its own within a few minutes, or resume \
- it now"
+ "the import was interrupted; it resumes on its own within a few minutes, or resume it now"
.to_string()
}));
}
@@ -184,85 +157,43 @@ pub(crate) fn scheduler_paused() -> bool {
}
/// Resumes an import the app quit in the middle of, if there is one, under
-/// the scheduler's pause. Called from memory's background job.
+/// the scheduler's pause and current billing policy.
pub async fn resume_interrupted(ctx: &crate::core::runtime::DispatchCtx, config: &Config) -> bool {
- // A credits pause resumes on its own only while memory work is free
- // (`billing::free_period_active`). The backend is asked only when such a
- // pause is waiting on it.
- let file = read_file(&config.workspace_dir);
- let free = file.state.phase == ImportPhase::Error
- && file.paused_for_credits
- && super::billing::free_period_active(config).await;
resume_interrupted_with(
ctx,
config,
Arc::new(scheduler_paused),
- Arc::new(move |_: &Config| free),
+ Arc::new(|config| futures::executor::block_on(super::billing::free_period_active(config))),
)
.await
}
/// Resumes an interrupted import unless `paused` says background work is
-/// paused.
-///
-/// Only a `Running` state with no live run counts: the user consented when
-/// it started. A paused-for-credits run resumes once `billing` allows. A
-/// resumed run asks `paused` again before every batch. An automatic resume
-/// that cannot start is persisted as stopped, so a failure that would recur
-/// does not loop. Returns whether a run was started.
+/// paused. A failed automatic start is recorded through Native's checkpoint
+/// helper so it cannot loop forever.
pub(crate) async fn resume_interrupted_with(
ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
paused: PauseCheck,
billing: BillingCheck,
) -> bool {
- let file = read_file(&config.workspace_dir);
- let resumable = match file.state.phase {
- ImportPhase::Running => true,
- ImportPhase::Error => file.paused_for_credits && billing(config),
- _ => false,
+ let store = FileCheckpointStore::new(&config.workspace_dir);
+ let file = store.load();
+ let plan = Importer::resume_plan(&file, billing(config), paused());
+ let mode = match plan {
+ ResumePlan::DoNotResume => return false,
+ ResumePlan::ResumeImport => Mode::Import,
+ ResumePlan::ResumeRetry => Mode::ResumeRetry,
};
- if !resumable || running(&config.workspace_dir) {
- return false;
- }
- if paused() {
- tracing::debug!("[memory:import] background paused; interrupted import left for later");
- return false;
- }
- let retrying = file.state.phase == ImportPhase::Running && file.retrying;
- let resumed = if retrying {
- launch(ctx, config, Mode::ResumeRetry, true, Some(paused)).await
- } else {
- launch(ctx, config, Mode::Import, true, Some(paused)).await
- };
- match resumed {
+ let paused_for_batches = Some(paused);
+ match launch(ctx, config, mode, true, paused_for_batches).await {
Ok(state) => {
- tracing::info!(
- imported = state.imported,
- total = state.total,
- "[memory:import] resuming an interrupted import"
- );
+ tracing::info!(imported = state.imported, total = state.total, "[memory:import] resuming an interrupted import");
true
}
Err(error) => {
- tracing::warn!(
- code = error.code(),
- "[memory:import] interrupted import could not resume; stopped"
- );
- let engine = engine::resolve(config).engine().map(|bound| bound.engine);
- // Without an engine the importer is only used for its store.
- if let Ok(engine) = engine {
- importer(config, engine, true, None).record_resume_failure(&error.to_string());
- } else {
- let store = FileCheckpointStore::new(&config.workspace_dir);
- let mut file = store.load();
- file.state.phase = ImportPhase::Error;
- file.state.error = Some(format!("the import could not resume: {error}"));
- file.paused_for_credits = false;
- if let Err(error) = store.save(&file) {
- tracing::warn!(%error, "[memory:import] writing import state failed");
- }
- }
+ tracing::warn!(code = error.code(), "[memory:import] interrupted import could not resume; stopped");
+ tinymemory_integrations::import::record_resume_failure(&store, &error.to_string());
false
}
}
@@ -293,7 +224,8 @@ enum Mode {
ResumeRetry,
}
-/// Claims the workspace, begins the run on the module's driver and spawns it.
+/// Claims the workspace, begins the Native run and transfers its slot guard
+/// into the context-carrying worker future.
async fn launch(
ctx: &crate::core::runtime::DispatchCtx,
config: &Config,
@@ -305,34 +237,22 @@ async fn launch(
return Err(import_error(&ImportError::ConsentRequired));
}
let bound = engine::resolve(config).engine()?;
- let workspace_dir = config.workspace_dir.clone();
- let claimed = {
- let _gate = START_GATE
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- // Items written to the legacy tree while it is being moved would be
- // left behind there.
- if super::layout_migration::service::is_running(config) {
- return Err(Error::InvalidRequest(
- (if mode == Mode::Import {
- "memory is being organized; import once that finishes"
- } else {
- "memory is being organized; retry once that finishes"
- })
- .into(),
- ));
+ let workspace = config.workspace_dir.clone();
+ let Some(guard) = run_slots::reserve(&IMPORT, &workspace, &[&BACKFILL, &MIGRATION]) else {
+ if is_running(&workspace) {
+ return Ok(status(config));
}
- RUNNING
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .insert(workspace_dir.clone())
+ let reason = if MIGRATION.is_running(&workspace) {
+ "memory is being organized; import once that finishes"
+ } else {
+ "a conversation backfill is running; import once it finishes"
+ };
+ return Err(Error::InvalidRequest(reason.into()));
};
- if !claimed {
- return Ok(status(config));
- }
let driver = importer(config, bound.engine, consent, paused);
let begin = {
let driver = driver.clone();
+ let mode = mode;
ctx.spawn_blocking(move || match mode {
Mode::Import => driver.begin(),
Mode::Retry => driver.begin_retry(),
@@ -340,42 +260,33 @@ async fn launch(
})
.await
};
- let begun: Begun = match begin {
+ let begun = match begin {
Ok(Ok(begun)) => begun,
- Ok(Err(error)) => {
- release(&workspace_dir);
- return Err(import_error(&error));
- }
- Err(error) => {
- release(&workspace_dir);
- return Err(Error::Engine(format!("import start failed: {error}")));
- }
+ Ok(Err(error)) => return Err(import_error(&error)),
+ Err(error) => return Err(Error::Engine(format!("import start failed: {error}"))),
};
let state = begun.state.clone();
- tracing::info!(
- total = state.total,
- retry = mode != Mode::Import,
- "[memory:import] run started"
- );
+ tracing::info!(total = state.total, retry = mode != Mode::Import, "[memory:import] run started");
let config = config.clone();
let task_ctx = ctx.clone();
- ctx.spawn(async move {
- if mode == Mode::Import {
- driver.run(begun).await;
- } else {
- driver.run_retry(begun).await;
+ task_ctx.spawn(async move {
+ {
+ let _guard = guard;
+ if mode == Mode::Import {
+ driver.run(begun).await;
+ } else {
+ driver.run_retry(begun).await;
+ }
}
- release(&workspace_dir);
- // Import first, then organize: the move starts here, on whatever
- // screen the user is, once the import is done.
+ // Import first, then organize. Migration's peer check sees the import
+ // slot released before it attempts its own atomic reservation.
+ let workspace_dir = config.workspace_dir.clone();
if mode == Mode::Import && read_file(&workspace_dir).state.phase == ImportPhase::Done {
+ let host = Arc::new(super::layout_migration::AppHost::new(config.clone()));
let started = super::layout_migration::start(
&task_ctx,
- config.clone(),
- Arc::new(super::layout_migration::AppHost::new(config)),
- // Migration is free: organizing follows a finished import
- // straight away. A shared self-hosted tree still waits for
- // the takeover consent.
+ config,
+ host,
super::layout_migration::Trigger::Manual { takeover: false },
Arc::new(scheduler_paused),
);
diff --git a/crates/openhuman-core/src/memory/layout_migration/mod.rs b/crates/openhuman-core/src/memory/layout_migration/mod.rs
index cf1c8d09a3..6e4ad78f08 100644
--- a/crates/openhuman-core/src/memory/layout_migration/mod.rs
+++ b/crates/openhuman-core/src/memory/layout_migration/mod.rs
@@ -1,28 +1,17 @@
//! Moving memory from the legacy CortexDB tree into the per-user tree.
//!
-//! The engine-to-engine migration (copy, placement, cleanup, the job and its
-//! service) lives in `tinymemory_tools::layout_migration`; this module is the
-//! OpenHuman host adapter over its two ports:
-//!
-//! - [`state`]: the file-backed [`MigrationStateStore`] under the workspace.
-//! - [`app_host`]: the [`LayoutHost`] for one account (engine binding,
-//! placement, the layout switch, the free period), with [`claim`] naming the
-//! account that takes a legacy tree several accounts share.
-//! - [`service`]: running in the background (one run per workspace, gated on
-//! the import) and mapping the module's errors to [`Error`].
-//!
-//! [`Error`]: tinymemory_api::Error
+//! TinyMemory owns the migration job and service. These modules bind the host
+//! ports, file-backed state, and RPC/background scheduler.
pub mod app_host;
-pub mod claim;
-pub mod service;
+pub mod ops;
pub mod state;
#[cfg(test)]
pub(crate) mod test_host;
pub use app_host::AppHost;
-pub use service::{retry, scan, start, status, tick, StartParams};
+pub use ops::{retry, scan, start, status, tick, StartParams};
pub use state::FileStateStore;
pub use tinymemory_tools::layout_migration::{
LayoutHost, MigrationState, MigrationStateStore, MigrationStatus, Outcome, Phase, ScanView,
diff --git a/crates/openhuman-core/src/memory/layout_migration/ops.rs b/crates/openhuman-core/src/memory/layout_migration/ops.rs
new file mode 100644
index 0000000000..9c69767f7b
--- /dev/null
+++ b/crates/openhuman-core/src/memory/layout_migration/ops.rs
@@ -0,0 +1,103 @@
+//! OpenHuman's scheduling and RPC adapter for Native layout migration.
+//!
+//! TinyMemory owns the migration job, policy, live slot and retry behavior.
+//! This module supplies the host executor, workspace key, cross-driver gate,
+//! billing-independent scheduler pause and wire error mapping.
+
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, LazyLock};
+
+use tinymemory_tools::layout_migration as lm;
+use tinymemory_tools::run_slots::{MigrationSpawner, MigrationTask, RunSlots};
+
+use super::app_host::{from_module, AppHost};
+use super::{LayoutHost, MigrationState, MigrationStatus, ScanView, Trigger};
+use crate::config::Config;
+use crate::core::runtime::DispatchCtx;
+use crate::memory::run_slots::{self, BACKFILL, IMPORT, MIGRATION};
+use tinymemory_api::Result;
+
+static MIGRATION_SLOTS: LazyLock<RunSlots<PathBuf>> = LazyLock::new(RunSlots::new);
+
+/// `memory_migration_start` params.
+#[derive(Debug, Clone, Default, serde::Deserialize)]
+pub struct StartParams {
+ /// The user's consent to take a legacy tree other accounts may share.
+ #[serde(default)]
+ pub takeover: bool,
+}
+
+struct ContextSpawner(DispatchCtx);
+
+impl MigrationSpawner for ContextSpawner {
+ fn spawn(&self, task: MigrationTask) -> std::result::Result<(), String> {
+ self.0.spawn(task);
+ Ok(())
+ }
+}
+
+fn service(ctx: &DispatchCtx) -> lm::MigrationService<tinymemory_tools::run_slots::RunStartGate, ContextSpawner> {
+ lm::MigrationService::new(
+ MIGRATION_SLOTS.clone(),
+ run_slots::START_GATE.clone(),
+ ContextSpawner(ctx.clone()),
+ )
+}
+
+/// Whether this workspace currently owns a migration task.
+pub(crate) fn is_running(config: &Config) -> bool {
+ MIGRATION_SLOTS.is_running(&config.workspace_dir)
+}
+
+/// Whether `host`'s account has legacy memory to move.
+pub async fn scan(host: &dyn LayoutHost) -> Result<ScanView> {
+ lm::scan(host).await.map_err(from_module)
+}
+
+/// The migration's progress for `config`'s workspace.
+pub fn status(config: &Config) -> Result<MigrationStatus> {
+ lm::status(&AppHost::new(config.clone()), is_running(config)).map_err(from_module)
+}
+
+/// Starts a migration; Native atomically checks peer activity and reserves the
+/// migration-only run slot under the shared start gate.
+pub fn start(
+ ctx: &DispatchCtx,
+ config: Config,
+ host: Arc<dyn LayoutHost>,
+ trigger: Trigger,
+ paused: Arc<dyn Fn() -> bool + Send + Sync>,
+) -> bool {
+ service(ctx).start(
+ config.workspace_dir.clone(),
+ host,
+ || IMPORT.is_running(&config.workspace_dir) || BACKFILL.is_running(&config.workspace_dir),
+ trigger,
+ paused,
+ )
+}
+
+/// Puts failed migration items back in line.
+pub fn retry(config: &Config) -> Result<MigrationState> {
+ lm::retry(&AppHost::new(config.clone()), is_running(config)).map_err(from_module)
+}
+
+/// Memory's background job: starts or resumes an automatic run unless the
+/// migration is done, paused, or already running.
+pub fn tick(
+ ctx: &DispatchCtx,
+ config: &Config,
+ host: Arc<dyn LayoutHost>,
+ paused: Arc<dyn Fn() -> bool + Send + Sync>,
+) -> bool {
+ service(ctx).tick(
+ config.workspace_dir.clone(),
+ host,
+ || IMPORT.is_running(&config.workspace_dir) || BACKFILL.is_running(&config.workspace_dir),
+ paused,
+ )
+}
+
+#[cfg(test)]
+#[path = "ops_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/memory/layout_migration/service_tests.rs b/crates/openhuman-core/src/memory/layout_migration/ops_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/memory/layout_migration/service_tests.rs
rename to crates/openhuman-core/src/memory/layout_migration/ops_tests.rs
diff --git a/crates/openhuman-core/src/memory/layout_migration/service.rs b/crates/openhuman-core/src/memory/layout_migration/service.rs
deleted file mode 100644
index c31160916d..0000000000
--- a/crates/openhuman-core/src/memory/layout_migration/service.rs
+++ /dev/null
@@ -1,157 +0,0 @@
-//! The migration as a service: what the RPCs and the background job call.
-//!
-//! - [`scan`]: whether there is anything to move (the UI shows nothing when
-//! there is not).
-//! - [`start`]: runs the migration in the background; at most one run per
-//! workspace at a time.
-//! - [`status`]: its progress, with a run the app quit in the middle of
-//! reported as interrupted.
-//! - [`retry`]: puts the items that could not be moved back in line.
-//! - [`tick`]: memory's background job, every few minutes. It starts or
-//! resumes an automatic run, which itself waits for a free period (and,
-//! on a shared legacy tree, for the user's consent).
-//!
-//! The state machine is the module's; this file owns the executor side: the
-//! spawned task, the run slot per workspace and the import gate.
-
-use std::collections::HashSet;
-use std::path::PathBuf;
-use std::sync::{Arc, LazyLock, Mutex, PoisonError};
-
-use tinymemory_tools::layout_migration as lm;
-
-use super::app_host::{from_module, AppHost};
-use super::{LayoutHost, MigrationState, MigrationStatus, ScanView, Trigger};
-use crate::config::Config;
-use tinymemory_api::Result;
-
-/// Workspaces with a migration running now.
-static RUNNING: LazyLock<Mutex<HashSet<PathBuf>>> = LazyLock::new(|| Mutex::new(HashSet::new()));
-
-/// `memory_migration_start` params.
-#[derive(Debug, Clone, Default, serde::Deserialize)]
-pub struct StartParams {
- /// The user's consent to take a legacy tree other accounts may share.
- #[serde(default)]
- pub takeover: bool,
-}
-
-/// Whether `host`'s account has legacy memory to move.
-///
-/// # Errors
-///
-/// When the state cannot be read, the engines cannot be bound, or the legacy
-/// tree cannot be read.
-pub async fn scan(host: &dyn LayoutHost) -> Result<ScanView> {
- lm::scan(host).await.map_err(from_module)
-}
-
-/// The migration's progress for `config`'s workspace.
-///
-/// # Errors
-///
-/// When the state file cannot be read.
-pub fn status(config: &Config) -> Result<MigrationStatus> {
- lm::status(&AppHost::new(config.clone()), is_running(config)).map_err(from_module)
-}
-
-pub(crate) fn is_running(config: &Config) -> bool {
- RUNNING
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .contains(&config.workspace_dir)
-}
-
-/// Releases the workspace's run slot when the run ends, however it ends.
-struct RunGuard(PathBuf);
-
-impl Drop for RunGuard {
- fn drop(&mut self) {
- RUNNING
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .remove(&self.0);
- }
-}
-
-/// Starts a run in the background. Returns `false`, starting nothing, when
-/// one is already running for this workspace, or while an import of old
-/// local memory is unfinished (import first, then reorganise).
-pub fn start(
- ctx: &crate::core::runtime::DispatchCtx,
- config: Config,
- host: Arc<dyn LayoutHost>,
- trigger: Trigger,
- paused: Arc<dyn Fn() -> bool + Send + Sync>,
-) -> bool {
- let _gate = crate::memory::import::START_GATE
- .lock()
- .unwrap_or_else(PoisonError::into_inner);
- if crate::memory::import::in_progress(&config) {
- tracing::info!("[memory:layout_migration] waiting for the import to finish");
- return false;
- }
- let workspace = config.workspace_dir.clone();
- if !RUNNING
- .lock()
- .unwrap_or_else(PoisonError::into_inner)
- .insert(workspace.clone())
- {
- return false;
- }
- let guard = RunGuard(workspace);
- ctx.spawn(async move {
- let _guard = guard;
- let outcome = lm::run(host.as_ref(), trigger, || {
- let paused = paused();
- async move { paused }
- })
- .await;
- match outcome {
- Ok(outcome) => {
- tracing::info!(?outcome, "[memory:layout_migration] run ended");
- }
- Err(error) => {
- tracing::warn!(code = error.code(), "[memory:layout_migration] run failed");
- lm::record_failure(host.as_ref(), &error);
- }
- }
- });
- true
-}
-
-/// Puts the items that could not be moved back in line: the next run copies
-/// again from the start (what was copied replays) and cleans up again.
-///
-/// # Errors
-///
-/// When the state cannot be read or saved, or a run is going now.
-pub fn retry(config: &Config) -> Result<MigrationState> {
- lm::retry(&AppHost::new(config.clone()), is_running(config)).map_err(from_module)
-}
-
-/// Memory's background job: starts or resumes an automatic run unless the
-/// migration is done or already running. Returns whether one started.
-pub fn tick(
- ctx: &crate::core::runtime::DispatchCtx,
- config: &Config,
- host: Arc<dyn LayoutHost>,
- paused: Arc<dyn Fn() -> bool + Send + Sync>,
-) -> bool {
- match lm::is_finished(host.as_ref()) {
- Ok(true) => false,
- Ok(false) if paused() || is_running(config) => false,
- Ok(false) => start(ctx, config.clone(), host, Trigger::Auto, paused),
- Err(error) => {
- tracing::warn!(
- code = error.code(),
- "[memory:layout_migration] state unreadable"
- );
- false
- }
- }
-}
-
-#[cfg(test)]
-#[path = "service_tests.rs"]
-mod tests;