//! dspike: the core a durability module needs, small enough to compare two languages on. //! //! dspike append FILE TEXT one line appended and on the disk before it returns //! dspike replace FILE TEXT the file replaced atomically: never half, never lost //! dspike stage SRC DST a consistent copy of a live SQLite database, checked //! dspike checkpoint DB every committed change into the main file, the log emptied use std::error::Error; use std::fs::{self, File, OpenOptions}; use std::io::Write; use std::path::{Path, PathBuf}; use std::time::Duration; use rusqlite::{backup::Backup, Connection, OpenFlags}; type Res = Result>; fn append_line(path: &Path, text: &str) -> Res<()> { let mut f = OpenOptions::new().append(true).create(true).open(path)?; f.write_all(text.as_bytes())?; f.write_all(b"\n")?; f.sync_data()?; // fdatasync: the data and the size, not the timestamps Ok(()) } fn sync_dir(dir: &Path) -> Res<()> { File::open(dir)?.sync_all()?; Ok(()) } fn parent(path: &Path) -> PathBuf { match path.parent() { Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(), _ => PathBuf::from("."), } } /// Removes the temporary file unless told the rename happened: a half file never stays. struct Tmp { path: PathBuf, keep: bool, } impl Drop for Tmp { fn drop(&mut self) { if !self.keep { let _ = fs::remove_file(&self.path); } } } fn replace(path: &Path, text: &str) -> Res<()> { let dir = parent(path); let name = format!("{}.tmp{}", path.file_name().ok_or("no file name")?.to_string_lossy(), std::process::id()); let mut tmp = Tmp { path: dir.join(name), keep: false }; let mut f = OpenOptions::new().write(true).create_new(true).open(&tmp.path)?; f.write_all(text.as_bytes())?; f.sync_all()?; drop(f); fs::rename(&tmp.path, path)?; tmp.keep = true; sync_dir(&dir) // the rename itself is on the disk only after this } fn stage(src: &Path, dst: &Path) -> Res<()> { let mut tmp = Tmp { path: PathBuf::from(format!("{}.tmp", dst.display())), keep: false }; let _ = fs::remove_file(&tmp.path); let from = Connection::open_with_flags(src, OpenFlags::SQLITE_OPEN_READ_ONLY)?; from.busy_timeout(Duration::from_secs(30))?; { let mut to = Connection::open(&tmp.path)?; // one step of all pages. `run_to_completion` panics on -1 (its wrapper wants a positive page count), // which the first version of this file found out at run time. Backup::new(&from, &mut to)?.step(-1)?; let check: String = to.query_row("PRAGMA quick_check", [], |r| r.get(0))?; if check != "ok" { return Err(format!("the copy does not pass quick_check: {check}").into()); } } File::open(&tmp.path)?.sync_all()?; fs::rename(&tmp.path, dst)?; tmp.keep = true; sync_dir(&parent(dst)) } fn checkpoint(path: &Path) -> Res<()> { let db = Connection::open(path)?; db.busy_timeout(Duration::from_secs(5))?; let busy: i64 = db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get(0))?; if busy != 0 { return Err("the database still has a writer".into()); } println!("checkpointed {}", path.display()); Ok(()) } fn main() { let a: Vec = std::env::args().skip(1).collect(); let a: Vec<&str> = a.iter().map(String::as_str).collect(); let done = match a.as_slice() { ["append", file, text] => append_line(Path::new(file), text), ["replace", file, text] => replace(Path::new(file), text), ["stage", src, dst] => stage(Path::new(src), Path::new(dst)), ["checkpoint", db] => checkpoint(Path::new(db)), _ => { eprintln!("usage: dspike append FILE TEXT | replace FILE TEXT | stage SRC DST | checkpoint DB"); std::process::exit(2); } }; if let Err(e) = done { eprintln!("dspike: {e}"); std::process::exit(1); } }