Merge branch 'main' into feat/tui-msgid-join
All checks were successful
ci / test (pull_request) Successful in 4m10s

This commit is contained in:
sirius 2026-09-12 22:10:54 +00:00
commit 18ccab5464
16 changed files with 897 additions and 195 deletions

View file

@ -293,7 +293,14 @@ impl Node {
/// so this is about leaving less to replay (and less on disk) if the
/// process is killed right after teardown — not about correctness.
fn checkpoint(&self) {
if let Err(e) = checkpoint_wal(&self.home) {
let store = match self.store.lock() {
Ok(s) => s,
Err(e) => {
eprintln!("wal checkpoint: store lock poisoned: {e}");
return;
}
};
if let Err(e) = store.checkpoint_wal() {
eprintln!("wal checkpoint: {e}");
}
}
@ -1036,49 +1043,6 @@ fn spawn_flush_friend(outbox: Arc<Outbox>, friend_pk: Vec<u8>) {
});
}
/// Checkpoint the sqlite WAL into the main db file and truncate it.
///
/// `Store` owns the write connection and deliberately does not lend it out, and
/// a checkpoint is a property of the *database*, not of one connection — so a
/// short-lived second connection to the same file is the least invasive way to
/// reach it from the node without widening `Store`'s API.
///
/// That works because the connection needs no passphrase: it moves
/// already-committed pages, it does not decrypt them. It stops working the
/// moment the store is SQLCipher-encrypted (PR #43), because the key lives only
/// inside `Store` and a second connection cannot read the file at all. That case
/// is detected and reported as a skip rather than a failure: nothing is lost
/// (sqlite folds the WAL into the db when the last connection closes) — the
/// explicit truncation just has to move inside `Store` to happen here.
fn checkpoint_wal(home: &Path) -> Result<(), String> {
let db = home.join("onionwire.db");
if !db.exists() {
return Ok(());
}
let conn = rusqlite::Connection::open(&db).map_err(|e| format!("open {}: {e}", db.display()))?;
let (busy, log, checkpointed): (i64, i64, i64) = conn
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
})
.map_err(|e| {
let msg = e.to_string();
if msg.contains("not a database") {
// SQLCipher store: no key here, so this connection sees noise.
format!("store is SQLCipher-encrypted — skipped ({msg})")
} else {
format!("wal_checkpoint: {msg}")
}
})?;
if busy != 0 {
// Another connection is reading/writing: pages are still safe in the
// WAL, they just were not moved this time.
return Err(format!(
"busy ({checkpointed}/{log} pages moved, another connection active)"
));
}
Ok(())
}
fn next_hs_nickname(cur: &str) -> String {
let n = cur
.strip_prefix("ow")
@ -1122,56 +1086,3 @@ pub fn dir_contains_bytes(dir: &Path, needle: &[u8]) -> bool {
false
}
#[cfg(test)]
mod lifecycle_tests {
//! Offline half of the shutdown contract. The live-Tor half lives in
//! `tests/tor_lifecycle.rs` (ignored) — everything here runs in CI.
use super::*;
/// `checkpoint_wal` reaches the database through a *second* connection,
/// because `Store` owns the write one. That assumption is the whole reason
/// the helper can live in `node.rs`, so prove it against a real WAL.
#[test]
fn checkpoint_wal_truncates_a_live_wal() {
let root = tempfile::tempdir().expect("tempdir");
let home = root.path();
let db = home.join("onionwire.db");
let conn = rusqlite::Connection::open(&db).expect("open db");
let mode: String = conn
.query_row("PRAGMA journal_mode = WAL", [], |r| r.get(0))
.expect("wal mode");
assert_eq!(mode.to_lowercase(), "wal");
conn.execute_batch("CREATE TABLE t (id INTEGER PRIMARY KEY, v BLOB);")
.expect("create table");
for _ in 0..64 {
conn.execute("INSERT INTO t (v) VALUES (?1)", rusqlite::params![vec![7u8; 512]])
.expect("insert");
}
let wal = home.join("onionwire.db-wal");
let before = std::fs::metadata(&wal).expect("wal file").len();
assert!(before > 0, "expected pending WAL frames, got {before}");
checkpoint_wal(home).expect("checkpoint");
let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
assert_eq!(after, 0, "WAL not truncated ({before} bytes before)");
// The rows are still there — a checkpoint moves pages, it never drops
// committed data.
let n: i64 = conn
.query_row("SELECT COUNT(*) FROM t", [], |r| r.get(0))
.expect("count");
assert_eq!(n, 64);
}
/// A home directory with no store yet is not an error: `shutdown` and
/// `flush` are safe to call on a node whose db was never created (tests,
/// wiped installs).
#[test]
fn checkpoint_wal_is_a_no_op_without_a_database() {
let root = tempfile::tempdir().expect("tempdir");
checkpoint_wal(root.path()).expect("no db, no error");
}
}

View file

@ -1054,6 +1054,31 @@ impl Store {
Ok(out)
}
/// Fold the WAL into the main db file and truncate it.
///
/// Runs on this store's own keyed connection: a second, unkeyed connection
/// cannot even read a SQLCipher store (`SQLITE_NOTADB`), so the checkpoint
/// has to happen here, not from `node.rs`.
///
/// Best effort on purpose: WAL replay on open recovers everything committed,
/// so this is about leaving less to replay (and less on disk) if the process
/// is killed right after teardown — not about correctness.
pub fn checkpoint_wal(&self) -> Result<()> {
let (busy, log, checkpointed): (i64, i64, i64) =
self.conn
.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
})?;
if busy != 0 {
// Another connection is reading/writing: pages are still safe in the
// WAL, they just were not moved this time.
return Err(Error(format!(
"busy ({checkpointed}/{log} pages moved, another connection active)"
)));
}
Ok(())
}
/// Drop chat + payments history. Identity + friends stay.
/// Not a forensic erase: SSD wear-leveling can keep copies.
pub fn wipe_messages(&self) -> Result<()> {
@ -1065,7 +1090,7 @@ impl Store {
self.conn.execute("DELETE FROM messages", [])?;
self.conn.execute("DELETE FROM payments", [])?;
self.conn.execute_batch("VACUUM")?;
self.conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)")?;
self.checkpoint_wal()?;
Ok(())
}
@ -1379,6 +1404,33 @@ mod at_rest {
use super::*;
use zeroize::Zeroize;
/// `Node::shutdown`/`flush` checkpoint the WAL through this method, so it has
/// to run on the store's own keyed connection: a second, unkeyed one cannot
/// read a SQLCipher file at all (`SQLITE_NOTADB`) and the truncation silently
/// never happened.
#[test]
fn checkpoint_wal_truncates_an_encrypted_store_wal() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "checkpoint-pass").unwrap();
let pk = [3u8; 32];
store.upsert_friend(&pk, "peer.onion", None).unwrap();
for _ in 0..64 {
store.append_message(&pk, "out", &[7u8; 512]).unwrap();
}
let wal = dir.path().join("onionwire.db-wal");
let before = std::fs::metadata(&wal).expect("wal file").len();
assert!(before > 0, "expected pending WAL frames, got {before}");
store.checkpoint_wal().expect("checkpoint");
let after = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0);
assert_eq!(after, 0, "WAL not truncated ({before} bytes before)");
// A checkpoint moves pages into the db; it never drops committed data.
assert_eq!(store.list_messages(&pk).unwrap().len(), 64);
}
#[test]
fn store_data_key_is_a_zeroizing_wrapper_that_wipes() {
let dir = tempfile::tempdir().unwrap();