File size: 4,038 Bytes
f8975ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
//! 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<T> = Result<T, Box<dyn Error>>;

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<String> = 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);
    }
}