tinystore 0.12.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
//! A set of files kept in a database's file: a file and the row that names it
//! commit together or neither does, a rollback and a crash leave no bytes
//! behind, and a backup holds both.

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, UNIX_EPOCH};

use crate::blobs::fixture::bytes;
use crate::sql::Database;
use crate::{Error, ErrorKind, Options, Result, Store, TestClock, sql};

const PLUGINS: &str = "create table plugins (file text primary key) strict";
/// Bytes past what a database's files keep inline, so that they are an object.
const PACKAGE: usize = 100 << 10;

struct Fixture {
    store: Store,
    clock: Arc<TestClock>,
    // Last: fields drop in order, and Windows removes no file the store still holds.
    dir: tempfile::TempDir,
}

fn fixture() -> Fixture {
    let dir = tempfile::tempdir().unwrap();
    let clock = Arc::new(TestClock::new(UNIX_EPOCH + Duration::from_secs(1_800_000_000)));
    let store = open(dir.path(), &clock);
    Fixture { dir, store, clock }
}

fn open(dir: &Path, clock: &Arc<TestClock>) -> Store {
    Store::open(dir, Options { clock: Some(clock.clone()), background: false, ..Options::default() }).unwrap()
}

impl Fixture {
    fn app(&self) -> Database {
        app(&self.store)
    }

    fn reopen(&mut self) {
        self.store.close().unwrap();
        self.store = open(self.dir.path(), &self.clock);
    }

    /// The files of `sql/app.blobs/objects/`.
    fn objects(&self) -> Vec<PathBuf> {
        objects_in(&self.dir.path().join("sql/app.blobs/objects"))
    }
}

fn app(store: &Store) -> Database {
    store.database("app").migrations([("0001_plugins.sql", PLUGINS)]).open().unwrap()
}

fn objects_in(dir: &Path) -> Vec<PathBuf> {
    let mut found = Vec::new();
    for fan in std::fs::read_dir(dir).into_iter().flatten() {
        for file in std::fs::read_dir(fan.unwrap().path()).unwrap() {
            found.push(file.unwrap().path());
        }
    }
    found
}

fn installed(db: &Database, name: &str) -> bool {
    db.one::<String>(sql!("select file from plugins where file = ?", name)).unwrap().is_some()
}

// contract: DUR-06
#[test]
fn a_file_and_the_row_that_names_it_commit_together_or_neither_does() {
    let f = fixture();
    let db = f.app();
    let packages = db.files("packages").open().unwrap();
    db.tx(|tx| -> Result<()> {
        tx.exec(sql!("insert into plugins (file) values (?)", "stripe-1.0.0.js"))?;
        let info = tx.with(&packages).put("stripe-1.0.0.js", bytes(PACKAGE))?;
        assert_eq!(info.size, PACKAGE as u64);
        assert!(tx.with(&packages).head("stripe-1.0.0.js")?.is_some(), "the transaction sees its own file");
        tx.with(&packages).put("readme.md", b"a note kept inline")?;
        Ok(())
    })
    .unwrap();
    assert!(installed(&db, "stripe-1.0.0.js"));
    let mut stripe = packages.get("stripe-1.0.0.js").unwrap().expect("committed with its row");
    assert_eq!(stripe.read_all().unwrap(), bytes(PACKAGE));
    assert_eq!(packages.get("readme.md").unwrap().unwrap().read_all().unwrap(), b"a note kept inline");
    assert_eq!(f.objects().len(), 1, "the package's bytes, beside the database's file");

    let failed = db.tx(|tx| -> Result<()> {
        tx.exec(sql!("insert into plugins (file) values (?)", "slack-1.0.0.js"))?;
        tx.with(&packages).put("slack-1.0.0.js", bytes(PACKAGE + 1))?;
        Err(Error::invalid("the install changed its mind"))
    });
    assert_eq!(failed.unwrap_err().kind(), ErrorKind::Invalid);
    assert!(!installed(&db, "slack-1.0.0.js"));
    assert!(packages.get("slack-1.0.0.js").unwrap().is_none());
    assert_eq!(f.objects().len(), 1, "the bytes the rollback took are gone at once");
}

// contract: DUR-06
#[test]
fn bytes_a_rollback_could_not_remove_go_without_those_of_the_next_file() {
    let f = fixture();
    let db = f.app();
    let packages = db.files("packages").open().unwrap();
    let mut placed = None;
    let failed = db.tx(|tx| -> Result<()> {
        tx.with(&packages).put("slack-1.0.0.js", bytes(PACKAGE))?;
        placed = f.objects().pop();
        Err(Error::invalid("the install changed its mind"))
    });
    assert_eq!(failed.unwrap_err().kind(), ErrorKind::Invalid);
    let left = placed.expect("the rollback's bytes were placed");
    let id = i64::from_str_radix(&left.file_name().unwrap().to_string_lossy(), 16).unwrap();
    // as a rollback leaves them when another program holds the file on Windows
    std::fs::write(&left, b"the rollback's bytes").unwrap();
    packages.blobs.ids.doubt(id);

    let stripe = bytes(PACKAGE + 1);
    db.tx(|tx| -> Result<()> {
        tx.with(&packages).put("stripe-1.0.0.js", &stripe)?;
        // maintenance settles the doubt before the transaction commits
        let blobs = Arc::clone(&packages.blobs);
        std::thread::spawn(move || blobs.ids.doubtful().into_iter().for_each(|id| blobs.resolve(id))).join().unwrap();
        Ok(())
    })
    .unwrap();
    let mut file = packages.get("stripe-1.0.0.js").unwrap().expect("committed with its row");
    assert_eq!(file.read_all().unwrap(), stripe, "the next file keeps its bytes");
    assert!(!left.exists(), "the rollback's bytes are gone");
    assert_eq!(f.objects().len(), 1);
}

/// A log of a database's commits on a full disk: it keeps none of them, so
/// that each is in the file and answers `outcome_unknown`.
#[cfg(feature = "replication")]
struct LogsNothing;

#[cfg(feature = "replication")]
impl crate::sqlite::Observe for LogsNothing {
    fn last(&self) -> Option<crate::sqlite::Position> {
        None
    }

    fn begin(&self, _: crate::sqlite::Position, _: u32) -> Result<()> {
        Ok(())
    }

    fn committed(&self, _: &crate::sqlite::Commit<'_>) -> Result<()> {
        Err(Error::io("append", std::io::Error::other("the disk is full")))
    }

    fn gap(&self, _: crate::sqlite::Position) -> Result<()> {
        Ok(())
    }

    fn sync(&self) -> Result<()> {
        Ok(())
    }
}

// contract: DUR-06
#[cfg(feature = "replication")]
#[test]
fn bytes_whose_commit_is_in_the_file_with_its_outcome_unknown_stay_with_the_row_that_names_them() {
    let mut f = fixture();
    let db = f.app();
    let packages = db.files("packages").open().unwrap();
    packages.blobs.file.become_home(Arc::new(LogsNothing)).unwrap();
    let unknown = db.tx(|tx| -> Result<()> {
        tx.exec(sql!("insert into plugins (file) values (?)", "stripe-1.0.0.js"))?;
        tx.with(&packages).put("stripe-1.0.0.js", bytes(PACKAGE)).map(drop)
    });
    assert_eq!(unknown.unwrap_err().kind(), ErrorKind::OutcomeUnknown);
    assert!(installed(&db, "stripe-1.0.0.js"), "the commit is in the file");
    let read = || packages.get("stripe-1.0.0.js").unwrap().expect("its row committed").read_all();
    assert_eq!(read().unwrap(), bytes(PACKAGE), "the row names bytes that are there");
    // maintenance asks the file about the bytes in doubt, which a row names
    packages.blobs.ids.doubtful().into_iter().for_each(|id| packages.blobs.resolve(id));
    assert_eq!(read().unwrap(), bytes(PACKAGE));

    f.reopen();
    let packages = f.app().files("packages").open().unwrap();
    let mut file = packages.get("stripe-1.0.0.js").unwrap().expect("its row committed");
    assert_eq!(file.read_all().unwrap(), bytes(PACKAGE), "and after the next open");
    assert_eq!(f.objects().len(), 1);
}

// contract: DUR-06
#[test]
fn bytes_whose_commit_failed_with_its_outcome_unknown_stay_until_maintenance_finds_no_row_names_them() {
    let f = fixture();
    let db = f.app();
    let packages = db.files("packages").open().unwrap();
    let unknown = db.tx(|tx| -> Result<()> {
        let files = tx.with(&packages);
        files.put("stripe-1.0.0.js", bytes(PACKAGE))?;
        // SQLite rolls the commit back and fails it, as it may one the disk
        // failed; the hook takes the place of the writer's own for good
        let refused = std::sync::atomic::AtomicBool::new(false);
        files.tx.call(|raw| {
            let refuse_once = move || !refused.swap(true, std::sync::atomic::Ordering::SeqCst);
            raw.commit_hook(Some(refuse_once)).map_err(|error| crate::sqlite::sql_error("a commit hook", error))
        })
    });
    assert_eq!(unknown.unwrap_err().kind(), ErrorKind::OutcomeUnknown);
    assert!(packages.get("stripe-1.0.0.js").unwrap().is_none(), "no row names them");
    assert_eq!(f.objects().len(), 1, "the bytes stay, since a row might have named them");
    packages.blobs.maintain().unwrap();
    assert!(f.objects().is_empty(), "maintenance found that no row names them");
    packages.put("stripe-1.0.0.js", bytes(PACKAGE)).unwrap();
    assert_eq!(packages.get("stripe-1.0.0.js").unwrap().unwrap().read_all().unwrap(), bytes(PACKAGE));
}

#[test]
fn a_delete_a_copy_and_a_create_commit_with_the_rows_too() {
    let f = fixture();
    let db = f.app();
    let packages = db.files("packages").open().unwrap();
    packages.put("stripe-1.0.0.js", bytes(PACKAGE)).unwrap();
    db.tx(|tx| -> Result<()> {
        let packages = tx.with(&packages);
        packages.key("stripe-2.0.0.js").copy_from("stripe-1.0.0.js")?;
        packages.delete("stripe-1.0.0.js")?;
        assert!(!packages.create("stripe-2.0.0.js", b"another")?, "a create finds the copy");
        assert!(packages.key("upload.js").upload().is_err(), "an upload's bytes go in with a put");
        Ok(())
    })
    .unwrap();
    assert!(packages.head("stripe-1.0.0.js").unwrap().is_none());
    assert_eq!(packages.get("stripe-2.0.0.js").unwrap().unwrap().read_all().unwrap(), bytes(PACKAGE));
    let error = db.tx(|tx| tx.with(&f.store.files("avatars").open()?).put("a.png", b"png")).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Invalid, "files of blobs.db are outside a database's transaction: {error}");
}

// contract: BLOB-25
#[test]
fn a_folder_is_listed_and_cleared_inside_a_transaction_as_the_transaction_left_it() {
    let f = fixture();
    let db = f.app();
    let packs = db.files("packs").open().unwrap();
    let paths = |page: crate::blobs::Page| page.files.into_iter().map(|file| file.path).collect::<Vec<_>>();
    db.tx(|tx| -> Result<()> {
        let packs = tx.with(&packs);
        packs.put("brands/icons/youtube.svg", b"<svg/>")?;
        packs.put("brands/icons/vimeo.svg", bytes(PACKAGE))?;
        packs.put("flags/fi.svg", b"<svg/>")?;
        assert_eq!(
            paths(packs.list().prefix("brands/").page()?),
            ["brands/icons/vimeo.svg", "brands/icons/youtube.svg"]
        );
        tx.exec(sql!("insert into plugins (file) values ('brands')")).map(drop)
    })
    .unwrap();
    // version 2 of the pack holds one icon fewer: the folder is replaced whole
    db.tx(|tx| -> Result<()> {
        let brands = packs.folder("brands");
        let brands = tx.with(&brands);
        brands.clear()?;
        assert_eq!(paths(brands.list().page()?), [""; 0], "a list sees the clear before its commit");
        brands.put("icons/youtube.svg", b"<svg version=\"2\"/>")?;
        assert_eq!(paths(brands.list().limit(1).page()?), ["icons/youtube.svg"], "and the put after it");
        Ok(())
    })
    .unwrap();
    assert_eq!(paths(packs.list().page().unwrap()), ["brands/icons/youtube.svg", "flags/fi.svg"]);
    let rolled_back = db.tx(|tx| -> Result<()> {
        tx.with(&packs).clear()?;
        Err(Error::invalid("the row it went with was refused"))
    });
    assert_eq!(rolled_back.unwrap_err().kind(), ErrorKind::Invalid);
    assert_eq!(paths(packs.list().page().unwrap()), ["brands/icons/youtube.svg", "flags/fi.svg"], "a clear rolls back");
    assert_eq!(packs.get("brands/icons/youtube.svg").unwrap().unwrap().read_all().unwrap(), b"<svg version=\"2\"/>");
}

// contract: DUR-06
#[test]
fn bytes_a_crash_left_past_what_the_file_reserved_go_at_the_next_open() {
    let mut f = fixture();
    let packages = f.app().files("packages").open().unwrap();
    packages.put("stripe-1.0.0.js", bytes(PACKAGE)).unwrap();
    // what a transaction that placed its bytes and died before its commit leaves
    let left = f.dir.path().join("sql/app.blobs/objects/fa1/fa1000");
    std::fs::create_dir_all(left.parent().unwrap()).unwrap();
    std::fs::write(&left, b"bytes no row names").unwrap();
    f.reopen();
    let packages = f.app().files("packages").open().unwrap();
    assert!(!left.exists());
    assert_eq!(packages.get("stripe-1.0.0.js").unwrap().unwrap().read_all().unwrap(), bytes(PACKAGE));
    assert_eq!(f.objects().len(), 1);
}

#[test]
fn a_databases_files_live_in_its_file_and_the_folder_beside_it() {
    let f = fixture();
    let db = f.app();
    let packages = db.files("packages").open().unwrap();
    packages.key("stripe-1.0.0.js").content_type("text/javascript").put(bytes(PACKAGE)).unwrap();
    assert!(!f.dir.path().join("blobs").exists(), "no blobs.db");
    let listed = packages.list().page().unwrap();
    assert_eq!(listed.files.iter().map(|file| file.path.as_str()).collect::<Vec<_>>(), ["stripe-1.0.0.js"]);
    let tables: i64 =
        db.scalar(sql!("select count(*) from sqlite_schema where name like '_tinystore_blobs_%'")).unwrap();
    assert!(tables > 0, "its tables beside the database's own");
}

// contract: BAK-01
#[cfg(feature = "backup")]
#[test]
fn a_backup_holds_a_databases_files_with_the_rows_that_name_them() {
    let f = fixture();
    let db = f.app();
    let packages = db.files("packages").open().unwrap();
    db.tx(|tx| -> Result<()> {
        tx.exec(sql!("insert into plugins (file) values (?)", "stripe-1.0.0.js"))?;
        tx.with(&packages).put("stripe-1.0.0.js", bytes(PACKAGE)).map(drop)
    })
    .unwrap();
    let zip = f.dir.path().with_extension("zip");
    f.store.backup().write(&zip).unwrap();
    let restored = tempfile::tempdir().unwrap();
    crate::backup::restore(&zip, restored.path().join("data")).unwrap();
    let again = open(&restored.path().join("data"), &f.clock);
    let db = app(&again);
    assert!(installed(&db, "stripe-1.0.0.js"));
    let mut stripe = db.files("packages").open().unwrap().get("stripe-1.0.0.js").unwrap().unwrap();
    assert_eq!(stripe.read_all().unwrap(), bytes(PACKAGE));
    let _ = std::fs::remove_file(&zip);
}