Skip to content

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

fix(storage): persist local storage writes to disk

Steven Enamakele5e0e3b58a8b
diff --git a/crates/openhuman-core/src/storage/local.rs b/crates/openhuman-core/src/storage/local.rs
index f672f90772..e7c81f05e8 100644
--- a/crates/openhuman-core/src/storage/local.rs
+++ b/crates/openhuman-core/src/storage/local.rs
@@ -1,81 +1,29 @@
-//! The default layout for the small stores: SQLite document tables inside the
-//! database file each store already had.
+//! The workspace default for code that runs with no backend installed.
//!
-//! Approvals, devices, notifications and task sources each keep one `.db`
-//! file (`<workspace>/approval/approval.db`, `devices/devices.db`,
-//! `notifications/notifications.db`, `task_sources/sources.db`). With no
-//! storage URL configured ([`super::config::StorageMode::Default`]) a store's
-//! first call opens that file with the SQLite storage driver, so its records
-//! live in the driver's generic document tables beside the old ones, and
-//! [`open`] runs a one-shot import of the old tables' rows.
+//! Hosts install a backend at startup ([`super::install_for_url`]) and every
+//! store reaches it through [`super::installed`]. A unit test, or an embedder
+//! that never ran the host boot, installs none; rather than keep a second,
+//! file-shaped implementation of each store for them, such a call opens **the
+//! same default a host would**: `sqlite:<workspace>/storage`
+//! ([`super::config::default_url`]), once per workspace for the life of the
+//! process. A different workspace is a different database, which is also what
+//! isolates tests that use a temp directory each.
//!
-//! # The import
+//! A SaaS process never gets this fallback: it has no workspace-local state,
+//! and its hosts refuse to start without an explicit backend, so an
+//! uninstalled call there is an error, not a bucket other tenants could share.
//!
-//! A store describes its old tables with an [`ImportPlan`]: the table names
-//! and a reader that turns their rows into documents shaped exactly as the
-//! store's own document code writes them. [`open`] then
-//!
-//! 1. does nothing unless one of the plan's tables exists in the file;
-//! 2. reads the rows (through the store's own legacy open path, so an old
-//! schema is migrated forward first);
-//! 3. writes each as a document that must not already exist, so a re-run
-//! after a crash never overwrites a record the new code has since changed;
-//! 4. renames every old table to `_legacy_<name>`, keeping its rows for one
-//! release, which is also what makes a second open a no-op.
-//!
-//! The writes and the rename are separate statements (the driver owns its
-//! own connection), so the import is resumable rather than a single
-//! transaction: a crash between 3 and 4 repeats 3 harmlessly.
-//!
-//! Records land under [`Scope::local`]: the file already belongs to one
-//! workspace, so the scope inside it carries no isolation.
-//!
-//! Nothing here runs when a backend is installed (the host's explicit URL; the
-//! store uses that backend and its scope as before), when the process opted
-//! out ([`super::config::CLASSIC`]), in SaaS mode, or in a build without
-//! `storage-sqlite`: those keep the legacy tables.
+//! The fallback imports nothing. The legacy per-domain files are read by
+//! [`super::import`] when a backend is installed at boot (and again when the
+//! workspace is rebound, [`super::rebind`]).
-use crate::storage::rusqlite;
-use std::path::Path;
-use std::sync::Arc;
-#[cfg(feature = "storage-sqlite")]
-use std::{
- collections::HashMap,
- path::PathBuf,
- sync::{LazyLock, Mutex, PoisonError},
-};
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use anyhow::{anyhow, Context, Result};
-use rusqlite::Connection;
-use serde_json::Value;
-use tinystoragedrivers::CollectionSpec;
-use super::config::{mode, StorageMode};
-use super::documents::Repo;
use super::{current_scope, installed, Scope, ScopedStorage, StorageBackend};
-use crate::config::Config;
-
-/// One legacy row as a document of the new layout.
-#[derive(Debug, Clone, PartialEq)]
-pub struct ImportDoc {
- /// The collection the store keeps it in.
- pub collection: &'static str,
- /// The document id.
- pub id: String,
- /// The document body.
- pub doc: Value,
-}
-
-/// What a store brings from its old tables.
-pub struct ImportPlan<'a> {
- /// Log prefix, e.g. `approval::store`.
- pub domain: &'static str,
- /// The old tables. Each present one is renamed to `_legacy_<name>` after
- /// the rows are copied.
- pub tables: &'static [&'static str],
- /// Reads the old rows. Called only when one of `tables` exists.
- pub read: &'a dyn Fn() -> Result<Vec<ImportDoc>>,
-}
/// A backend and the scope a store's records live under in it.
#[derive(Clone)]
@@ -99,437 +47,79 @@ impl Opened {
}
}
-/// A database this process has opened, and whether its import finished.
-#[cfg(feature = "storage-sqlite")]
-struct OpenedDb {
- backend: Arc<dyn StorageBackend>,
- /// The file the backend was opened on, so a deleted or replaced file (a
- /// data reset in the same process) is noticed and reopened.
- identity: Option<FileId>,
- imported: bool,
-}
-
-/// What names one file on disk, apart from its path.
-#[cfg(feature = "storage-sqlite")]
-type FileId = (u64, u64);
-
-#[cfg(all(feature = "storage-sqlite", unix))]
-fn file_id(path: &Path) -> Option<FileId> {
- use std::os::unix::fs::MetadataExt;
- let meta = std::fs::metadata(path).ok()?;
- Some((meta.dev(), meta.ino()))
-}
-
-#[cfg(all(feature = "storage-sqlite", not(unix)))]
-fn file_id(path: &Path) -> Option<FileId> {
- // No inode to compare: existence is the best available signal.
- path.exists().then_some((0, 0))
-}
+/// Default backends this process opened for workspaces with nothing
+/// installed, by workspace directory.
+static WORKSPACES: LazyLock<Mutex<HashMap<PathBuf, Arc<dyn StorageBackend>>>> =
+ LazyLock::new(Mutex::default);
-/// Databases opened by this process, by path.
-#[cfg(feature = "storage-sqlite")]
-static OPENED: LazyLock<Mutex<HashMap<PathBuf, OpenedDb>>> = LazyLock::new(Mutex::default);
-
-/// The storage a small store uses for this call, or `None` for its legacy
-/// tables.
-///
-/// With a backend installed that is the backend, under the acting agent's
-/// scope. Otherwise, in [`StorageMode::Default`], it is the SQLite file at
-/// `db_path` (opened once per process, its old tables imported first) under
-/// [`Scope::local`].
+/// The backend for `workspace_dir`: the installed one, else the workspace's
+/// own default, opened on first use.
///
/// # Errors
///
-/// When the scope cannot be resolved (SaaS mode with no acting agent), the
-/// file cannot be opened, or a configured import fails to read its source.
-pub fn open(
- config: &Config,
- db_path: &Path,
- collections: fn() -> Vec<CollectionSpec>,
- plan: &ImportPlan<'_>,
-) -> Result<Option<Opened>> {
+/// In SaaS mode with no backend installed, or when the default cannot be
+/// opened.
+pub fn backend_for(workspace_dir: &Path) -> Result<Arc<dyn StorageBackend>> {
if let Some(backend) = installed() {
- let scope = current_scope()
- .with_context(|| format!("[{}] resolve the storage scope", plan.domain))?;
- return Ok(Some(Opened { backend, scope }));
+ return Ok(backend);
}
- let selected = mode(config);
- if selected != StorageMode::Default {
- // A legacy call may recreate the old tables; the next default call
- // must open and import afresh instead of trusting an earlier import.
- #[cfg(feature = "storage-sqlite")]
- if selected == StorageMode::Classic {
- forget(db_path);
- }
- return Ok(None);
+ if crate::core::runtime::mode::is_saas() {
+ return Err(anyhow!(
+ "SaaS mode needs an explicit storage backend (OPENHUMAN_STORAGE_URL)"
+ ));
}
- 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,
- _collections: fn() -> Vec<CollectionSpec>,
- plan: &ImportPlan<'_>,
-) -> Result<Option<Opened>> {
- tracing::debug!(
- domain = plan.domain,
- "[storage::local] built without storage-sqlite; keeping the legacy tables"
- );
- Ok(None)
-}
-
-#[cfg(feature = "storage-sqlite")]
-fn open_default(
- db_path: &Path,
- collections: fn() -> Vec<CollectionSpec>,
- plan: &ImportPlan<'_>,
-) -> Result<Option<Opened>> {
- // Held across the import so two threads never both import one file.
- let mut opened = OPENED.lock().unwrap_or_else(PoisonError::into_inner);
- ensure_open(&mut opened, db_path, plan.domain)?;
- let entry = opened.get_mut(db_path).expect("inserted above");
- let handle = Opened {
- backend: Arc::clone(&entry.backend),
- scope: Scope::local(),
- };
- if entry.imported {
- return Ok(Some(handle));
+ let mut opened = WORKSPACES.lock().unwrap_or_else(PoisonError::into_inner);
+ if let Some(backend) = opened.get(workspace_dir) {
+ return Ok(Arc::clone(backend));
}
- let count = import(db_path, &handle, collections, plan).with_context(|| {
- format!(
- "[{}] importing the legacy tables failed; they are untouched and the import is \
- retried on the next call (set storage url `{}` to keep using them as they are)",
- plan.domain,
- super::config::CLASSIC
- )
- })?;
+ let url = super::config::default_url(workspace_dir);
+ std::fs::create_dir_all(workspace_dir.join(super::config::DEFAULT_DIR))
+ .with_context(|| format!("create the storage directory under {}", workspace_dir.display()))?;
tracing::debug!(
- domain = plan.domain,
- path = %db_path.display(),
- imported = count,
- "[storage::local] opened the default store"
+ target: "openhuman::storage",
+ workspace = %workspace_dir.display(),
+ "[storage::local] opening the workspace default backend (none installed)"
);
- entry.imported = true;
- Ok(Some(handle))
-}
-
-/// Opens `db_path` with the SQLite driver unless `opened` already holds a live
-/// handle on it. A file deleted or replaced since it was opened (a data reset
-/// in this process) is dropped, so its handle is released and the file is
-/// created afresh.
-#[cfg(feature = "storage-sqlite")]
-fn ensure_open(
- opened: &mut HashMap<PathBuf, OpenedDb>,
- db_path: &Path,
- domain: &'static str,
-) -> Result<()> {
- if opened
- .get(db_path)
- .is_some_and(|entry| entry.identity != file_id(db_path))
- {
- opened.remove(db_path);
- }
- if !opened.contains_key(db_path) {
- if let Some(parent) = db_path.parent() {
- std::fs::create_dir_all(parent)
- .with_context(|| format!("[{domain}] create the directory {}", parent.display()))?;
- }
- // Opened by path, not through a URL string, so a path that is not
- // UTF-8 keeps naming the file the legacy tables are in.
- let storage = tinystoragedrivers::sqlite::SqliteStorage::open(db_path)
- .map_err(|error| anyhow!("[{domain}] open {}: {error}", db_path.display()))?;
- opened.insert(
- db_path.to_path_buf(),
- OpenedDb {
- backend: Arc::new(storage),
- identity: file_id(db_path),
- imported: false,
- },
- );
- }
- Ok(())
+ let backend = super::block_on_anyhow({
+ let url = url.clone();
+ async move { Ok(super::open(&url).await?) }
+ })
+ .with_context(|| format!("open the default storage for {}", workspace_dir.display()))?;
+ opened.insert(workspace_dir.to_path_buf(), Arc::clone(&backend));
+ Ok(backend)
}
-/// Reads a standing store's legacy files into a freshly opened backend.
-/// Receives the backend, the scope its records live under and the config.
-pub type StandingImport<'a> = &'a dyn Fn(&Arc<dyn StorageBackend>, &Scope, &Config) -> Result<()>;
-
-/// The storage a store that has **no legacy tables** uses for this call.
-///
-/// Cron jobs, the flow catalog, flow state and checkpoints used to live in
-/// SQLite files owned by tinyflows (`jobs.db`, `flows.db`, `checkpoints.db`).
-/// tinyflows no longer has a storage backend, so these stores are always on the
-/// ports, whatever the storage URL says:
-///
-/// - with a backend installed, that backend under the acting scope (the legacy
-/// files were imported into it at boot, see [`super::import`]);
-/// - otherwise, a SQLite file at `db_path` of the store's own, opened once per
-/// process, whose first open runs `import` over the legacy files (read-only:
-/// they are copied before they are read, and never written). The classic
-/// opt-out has no meaning here and is treated like the default.
+/// The storage a store uses for this call: [`backend_for`] `workspace_dir`
+/// under the acting scope ([`current_scope`]).
///
/// # Errors
///
-/// In SaaS mode with no backend installed (a SaaS process always names an
-/// explicit backend), when the scope cannot be resolved, or when the file
-/// cannot be opened or imported.
-pub fn open_standing(
- db_path: &Path,
- domain: &'static str,
- config: &Config,
- import: StandingImport<'_>,
-) -> Result<Opened> {
- if let Some(backend) = installed() {
- let scope =
- current_scope().with_context(|| format!("[{domain}] resolve the storage scope"))?;
- return Ok(Opened { backend, scope });
- }
- if crate::core::runtime::mode::is_saas() {
- return Err(anyhow!(
- "[{domain}] SaaS mode needs an explicit storage backend (OPENHUMAN_STORAGE_URL)"
- ));
- }
- open_standing_local(db_path, domain, config, import)
-}
-
-#[cfg(feature = "storage-sqlite")]
-fn open_standing_local(
- db_path: &Path,
- domain: &'static str,
- config: &Config,
- import: StandingImport<'_>,
-) -> Result<Opened> {
- let mut opened = OPENED.lock().unwrap_or_else(PoisonError::into_inner);
- ensure_open(&mut opened, db_path, domain)?;
- let entry = opened.get_mut(db_path).expect("inserted above");
- let handle = Opened {
- backend: Arc::clone(&entry.backend),
- scope: Scope::local(),
- };
- if !entry.imported {
- import(&handle.backend, &handle.scope, config).with_context(|| {
- format!(
- "[{domain}] importing the legacy files failed; they are untouched and the \
- import is retried on the next call"
- )
- })?;
- tracing::debug!(
- domain,
- path = %db_path.display(),
- "[storage::local] opened the standing store"
- );
- entry.imported = true;
- }
- Ok(handle)
-}
-
-/// Without `storage-sqlite` the standing stores keep JSON files beside where
-/// the database would be, on the always-compiled file driver.
-#[cfg(not(feature = "storage-sqlite"))]
-fn open_standing_local(
- db_path: &Path,
- domain: &'static str,
- config: &Config,
- import: StandingImport<'_>,
-) -> Result<Opened> {
- static FILES: std::sync::LazyLock<
- std::sync::Mutex<std::collections::HashMap<std::path::PathBuf, Arc<dyn StorageBackend>>>,
- > = std::sync::LazyLock::new(Default::default);
- let mut opened = FILES
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner);
- let backend = match opened.get(db_path) {
- Some(backend) => Arc::clone(backend),
- None => {
- let dir = db_path.with_extension("files");
- let Some(dir_str) = dir.to_str() else {
- return Err(anyhow!(
- "[{domain}] the store path is not valid UTF-8 and cannot be named by a file: URL"
- ));
- };
- let url = format!("file:{dir_str}");
- let backend = super::block_on_anyhow(async move { Ok(super::open(&url).await?) })
- .with_context(|| format!("[{domain}] open {}", dir.display()))?;
- import(&backend, &Scope::local(), config).with_context(|| {
- format!("[{domain}] importing the legacy files failed; they are untouched")
- })?;
- opened.insert(db_path.to_path_buf(), Arc::clone(&backend));
- backend
- }
- };
- Ok(Opened {
- backend,
- scope: Scope::local(),
- })
-}
-
-/// Copies `plan`'s old rows into `handle` and retires the old tables.
-/// Returns how many documents were written.
-#[cfg(feature = "storage-sqlite")]
-fn import(
- db_path: &Path,
- handle: &Opened,
- collections: fn() -> Vec<CollectionSpec>,
- plan: &ImportPlan<'_>,
-) -> Result<usize> {
- if !db_path.exists() {
- return Ok(0);
- }
- if present_tables(db_path, plan.tables)?.is_empty() {
- return Ok(0);
- }
- let rows = (plan.read)().with_context(|| format!("[{}] read the legacy rows", plan.domain))?;
- // The reader brings an old schema forward, which can create tables that
- // were missing (empty); look again so every one is retired together and
- // none is left to trigger another import.
- let present = present_tables(db_path, plan.tables)?;
- let total = rows.len();
- let repo = Repo::on(&handle.backend, &handle.scope, plan.domain, collections)?;
- let written = repo.run(|docs| async move {
- let mut written = 0usize;
- for row in rows {
- match docs
- .put(
- row.collection,
- &row.id,
- row.doc,
- tinystoragedrivers::Precondition::Absent,
- )
- .await
- {
- Ok(_) => written += 1,
- // Already there (a resumed import, or newer than the row).
- Err(error) if error.kind() == tinystoragedrivers::ErrorKind::Conflict => {}
- Err(error) => return Err(error),
- }
- }
- Ok(written)
- })?;
- retire_tables(db_path, &present)?;
- tracing::info!(
- domain = plan.domain,
- rows = total,
- written,
- tables = ?present,
- "[storage::local] imported the legacy tables; kept as _legacy_<name>"
- );
- Ok(written)
-}
-
-/// Drops every cached default-store handle, so a data reset can delete the
-/// files (Windows refuses while a handle is open) and the next call opens
-/// and imports afresh.
-#[cfg(feature = "storage-sqlite")]
+/// When the backend cannot be had ([`backend_for`]) or the scope cannot be
+/// resolved (SaaS mode with no acting profile).
+pub fn open(domain: &'static str, workspace_dir: &Path) -> Result<Opened> {
+ let backend = backend_for(workspace_dir)
+ .with_context(|| format!("[{domain}] open the storage backend"))?;
+ let scope =
+ current_scope().with_context(|| format!("[{domain}] resolve the storage scope"))?;
+ Ok(Opened { backend, scope })
+}
+
+/// Drops every cached workspace default, so a data reset can delete the files
+/// (Windows refuses while a handle is open) and the next call opens afresh.
pub fn release_all() {
- OPENED
+ WORKSPACES
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
}
-/// Forgets that `db_path` was opened, so the next call opens (and imports)
-/// it afresh; also how a test models a restart.
-#[cfg(feature = "storage-sqlite")]
-pub(crate) fn forget(db_path: &Path) {
- OPENED
+/// Forgets the default opened for `workspace_dir`, so the next call opens it
+/// afresh; also how a test models a restart.
+pub fn forget(workspace_dir: &Path) {
+ WORKSPACES
.lock()
.unwrap_or_else(PoisonError::into_inner)
- .remove(db_path);
-}
-
-/// The names of `db_path`'s tables, sorted (test inspection).
-#[cfg(test)]
-pub(crate) fn table_names(db_path: &Path) -> Vec<String> {
- let conn = Connection::open(db_path).unwrap();
- let mut stmt = conn
- .prepare("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")
- .unwrap();
- stmt.query_map([], |row| row.get(0))
- .unwrap()
- .map(Result::unwrap)
- .collect()
-}
-
-/// Whether `table` exists on `conn`.
-pub fn table_exists(conn: &Connection, table: &str) -> rusqlite::Result<bool> {
- conn.query_row(
- "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?1)",
- [table],
- |row| row.get(0),
- )
-}
-
-#[cfg(feature = "storage-sqlite")]
-fn present_tables(db_path: &Path, tables: &[&'static str]) -> Result<Vec<&'static str>> {
- let conn = Connection::open(db_path)
- .with_context(|| format!("open {} to look for legacy tables", db_path.display()))?;
- conn.busy_timeout(std::time::Duration::from_secs(5))?;
- let mut present = Vec::new();
- for table in tables {
- if table_exists(&conn, table)? {
- present.push(*table);
- }
- }
- Ok(present)
-}
-
-/// Renames each table to `_legacy_<name>` (a numeric suffix if that name is
-/// taken, so an earlier retired copy is never overwritten).
-#[cfg(feature = "storage-sqlite")]
-fn retire_tables(db_path: &Path, tables: &[&str]) -> Result<()> {
- let mut conn = Connection::open(db_path)
- .with_context(|| format!("open {} to retire legacy tables", db_path.display()))?;
- conn.busy_timeout(std::time::Duration::from_secs(5))?;
- // Immediate, and each table is checked inside it: another process on the
- // same workspace may have retired it already.
- let tx = conn.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)?;
- for table in tables {
- if !table_exists(&tx, table)? {
- continue;
- }
- let mut target = format!("_legacy_{table}");
- let mut n = 1;
- while table_exists(&tx, &target)? {
- n += 1;
- target = format!("_legacy_{table}_{n}");
- }
- // Index names are database-global and survive a rename, which would
- // make a later `CREATE INDEX IF NOT EXISTS` on the recreated legacy
- // table a silent no-op; the archive does not need them.
- let indexes: Vec<String> = tx
- .prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = ?1 AND sql IS NOT NULL")?
- .query_map([table], |row| row.get(0))?
- .collect::<rusqlite::Result<_>>()?;
- for index in indexes {
- let quoted = index.replace('"', "\"\"");
- tx.execute_batch(&format!("DROP INDEX \"{quoted}\""))?;
- }
- tx.execute_batch(&format!("ALTER TABLE \"{table}\" RENAME TO \"{target}\""))
- .with_context(|| format!("rename {table} to {target}"))?;
- }
- // The schema these tables belonged to is gone; a legacy open must not
- // trust a version stamp that says it is initialized.
- tx.pragma_update(None, "user_version", 0)?;
- tx.commit()?;
- Ok(())
+ .remove(workspace_dir);
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/storage/local_tests.rs b/crates/openhuman-core/src/storage/local_tests.rs
index 0562162fdd..6241c2e569 100644
--- a/crates/openhuman-core/src/storage/local_tests.rs
+++ b/crates/openhuman-core/src/storage/local_tests.rs
@@ -1,215 +1,62 @@
use super::*;
use crate::storage::documents::Repo;
use serde_json::json;
-use tempfile::TempDir;
+use tinystoragedrivers::{CollectionSpec, Precondition};
-const TABLES: &[&str] = &["old_things"];
-
-fn collections() -> Vec<CollectionSpec> {
+fn things() -> Vec<CollectionSpec> {
vec![CollectionSpec::new("things")]
}
-fn legacy_file(dir: &TempDir) -> std::path::PathBuf {
- let path = dir.path().join("things.db");
- let conn = Connection::open(&path).unwrap();
- conn.execute_batch(
- "CREATE TABLE old_things (id TEXT PRIMARY KEY, n INTEGER);
- INSERT INTO old_things VALUES ('a', 1), ('b', 2);",
- )
- .unwrap();
- path
-}
-
-fn config(url: Option<&str>) -> Config {
- let mut config = Config::default();
- config.storage.url = url.map(str::to_string);
- config
-}
-
-fn plan(path: &std::path::Path) -> Vec<ImportDoc> {
- let conn = Connection::open(path).unwrap();
- let mut stmt = conn
- .prepare("SELECT id, n FROM old_things ORDER BY id")
- .unwrap();
- stmt.query_map([], |row| {
- Ok(ImportDoc {
- collection: "things",
- id: row.get(0)?,
- doc: json!({ "n": row.get::<_, i64>(1)? }),
- })
+fn put_thing(opened: &Opened, id: &'static str, n: i64) {
+ let repo = Repo::on(&opened.backend, &opened.scope, "things", things).unwrap();
+ repo.run(move |docs| async move {
+ docs.put("things", id, json!({ "n": n }), Precondition::None)
+ .await
+ .map(|_| ())
})
- .unwrap()
- .map(Result::unwrap)
- .collect()
-}
-
-fn open_things(config: &Config, path: &std::path::Path) -> Option<Opened> {
- let read = || Ok(plan(path));
- open(
- config,
- path,
- collections,
- &ImportPlan {
- domain: "things",
- tables: TABLES,
- read: &read,
- },
- )
- .unwrap()
-}
-
-#[test]
-fn the_default_imports_then_retires_the_old_table() {
- let dir = TempDir::new().unwrap();
- let path = legacy_file(&dir);
- let opened = open_things(&config(None), &path).expect("default mode opens the file");
- assert_eq!(opened.scope, Scope::local());
- let repo = Repo::on(&opened.backend, &opened.scope, "things", collections).unwrap();
- let got = repo
- .run(|docs| async move { docs.get("things", "b").await })
- .unwrap()
- .unwrap();
- assert_eq!(got.doc, json!({ "n": 2 }));
- let tables = table_names(&path);
- assert!(tables.contains(&"_legacy_old_things".to_string()));
- assert!(!tables.contains(&"old_things".to_string()));
+ .unwrap();
}
-#[test]
-fn a_retired_name_already_taken_gets_a_numeric_suffix() {
- let dir = TempDir::new().unwrap();
- let path = legacy_file(&dir);
- Connection::open(&path)
+fn get_thing(opened: &Opened, id: &'static str) -> Option<i64> {
+ let repo = Repo::on(&opened.backend, &opened.scope, "things", things).unwrap();
+ repo.run(move |docs| async move { docs.get("things", id).await })
.unwrap()
- .execute_batch("CREATE TABLE _legacy_old_things (x)")
- .unwrap();
- open_things(&config(None), &path).unwrap();
- let tables = table_names(&path);
- assert!(tables.contains(&"_legacy_old_things".to_string()));
- assert!(tables.contains(&"_legacy_old_things_2".to_string()));
+ .map(|stored| stored.doc["n"].as_i64().unwrap())
}
#[test]
-fn classic_and_the_empty_file_do_not_import() {
- let dir = TempDir::new().unwrap();
- let path = legacy_file(&dir);
- assert!(open_things(&config(Some("classic")), &path).is_none());
- assert!(table_names(&path).contains(&"old_things".to_string()));
- // An explicit URL that nothing installed keeps the legacy tables too.
- assert!(open_things(&config(Some("memory")), &path).is_none());
-
- let empty = dir.path().join("empty.db");
- assert!(open_things(&config(None), &empty).is_some());
-}
-
-#[test]
-fn an_import_that_cannot_read_is_an_error_and_is_retried() {
- let dir = TempDir::new().unwrap();
- let path = legacy_file(&dir);
- let fails = || -> Result<Vec<ImportDoc>> { Err(anyhow!("boom")) };
- let failing = ImportPlan {
- domain: "things",
- tables: TABLES,
- read: &fails,
- };
- let error = open(&config(None), &path, collections, &failing)
- .err()
- .expect("a failed import is reported, not hidden behind the legacy tables");
- assert!(format!("{error:#}").contains("boom"), "{error:#}");
+fn an_uninstalled_call_opens_the_default_for_its_workspace() {
+ let dir = tempfile::tempdir().unwrap();
+ let opened = open("things", dir.path()).unwrap();
+ assert_eq!(opened.backend.driver(), "sqlite");
+ put_thing(&opened, "a", 1);
assert!(
- table_names(&path).contains(&"old_things".to_string()),
- "the old table is untouched"
+ dir.path().join("storage").is_dir(),
+ "the default lives in <workspace>/storage"
);
- // The next call imports properly.
- assert!(open_things(&config(None), &path).is_some());
- assert!(table_names(&path).contains(&"_legacy_old_things".to_string()));
+ // The same workspace reuses the one backend.
+ let again = open("things", dir.path()).unwrap();
+ assert!(Arc::ptr_eq(&opened.backend, &again.backend));
+ assert_eq!(get_thing(&again, "a"), Some(1));
}
#[test]
-fn retiring_a_table_releases_its_index_names() {
- let dir = TempDir::new().unwrap();
- let path = legacy_file(&dir);
- Connection::open(&path)
- .unwrap()
- .execute_batch("CREATE INDEX idx_old_things_n ON old_things(n)")
- .unwrap();
- open_things(&config(None), &path).unwrap();
- let conn = Connection::open(&path).unwrap();
- // A recreated legacy table can index itself under the same name again.
- conn.execute_batch(
- "CREATE TABLE old_things (id TEXT PRIMARY KEY, n INTEGER);
- CREATE INDEX idx_old_things_n ON old_things(n)",
- )
- .unwrap();
+fn workspaces_do_not_share_a_default() {
+ let one = tempfile::tempdir().unwrap();
+ let two = tempfile::tempdir().unwrap();
+ let a = open("things", one.path()).unwrap();
+ let b = open("things", two.path()).unwrap();
+ put_thing(&a, "only-in-one", 7);
+ assert_eq!(get_thing(&b, "only-in-one"), None);
}
#[test]
-fn a_standing_store_opens_once_per_file_and_imports_once() {
- use std::sync::atomic::{AtomicUsize, Ordering};
-
- // No test in this binary installs a backend, so the slot is empty.
- assert!(installed().is_none());
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("sub/standing.db");
- let config = config(None);
- let imports = AtomicUsize::new(0);
- let import = |_: &Arc<dyn StorageBackend>, scope: &Scope, _: &Config| {
- assert_eq!(scope, &Scope::local());
- imports.fetch_add(1, Ordering::SeqCst);
- Ok(())
- };
-
- let first = open_standing(&path, "test::standing", &config, &import).unwrap();
- let repo = Repo::on(&first.backend, &first.scope, "test::standing", collections).unwrap();
- repo.run(|docs| async move {
- docs.put(
- "things",
- "a",
- json!({"n": 1}),
- tinystoragedrivers::Precondition::None,
- )
- .await
- })
- .unwrap();
-
- // The second call finds the same store with its record, and does not
- // import again.
- let second = open_standing(&path, "test::standing", &config, &import).unwrap();
- let repo = Repo::on(
- &second.backend,
- &second.scope,
- "test::standing",
- collections,
- )
- .unwrap();
- let found = repo
- .run(|docs| async move { docs.get("things", "a").await })
- .unwrap();
- assert!(found.is_some());
- assert_eq!(imports.load(Ordering::SeqCst), 1);
-}
-
-#[test]
-fn a_failed_standing_import_is_retried_on_the_next_call() {
- use std::sync::atomic::{AtomicUsize, Ordering};
-
- assert!(installed().is_none());
- let dir = TempDir::new().unwrap();
- let path = dir.path().join("retry.db");
- let config = config(None);
- let attempts = AtomicUsize::new(0);
- let import = |_: &Arc<dyn StorageBackend>, _: &Scope, _: &Config| {
- if attempts.fetch_add(1, Ordering::SeqCst) == 0 {
- Err(anyhow!("legacy file unreadable"))
- } else {
- Ok(())
- }
- };
-
- let error = open_standing(&path, "test::retry", &config, &import)
- .err()
- .expect("the first import fails");
- assert!(format!("{error:#}").contains("legacy file unreadable"));
- open_standing(&path, "test::retry", &config, &import).unwrap();
- assert_eq!(attempts.load(Ordering::SeqCst), 2);
+fn forgetting_a_workspace_reopens_the_same_data() {
+ let dir = tempfile::tempdir().unwrap();
+ let first = open("things", dir.path()).unwrap();
+ put_thing(&first, "kept", 3);
+ forget(dir.path());
+ let second = open("things", dir.path()).unwrap();
+ assert!(!Arc::ptr_eq(&first.backend, &second.backend));
+ assert_eq!(get_thing(&second, "kept"), Some(3), "a restart keeps the data");
}