use std::sync::Arc;
use std::time::Duration;
use nedb_engine::Db;
const COLL: &str = "demo";
const ID: &str = "sentinel";
fn main() {
let args: Vec<String> = std::env::args().collect();
let mode = args.get(1).map(String::as_str).unwrap_or("write");
let dir = args.get(2).cloned().unwrap_or_else(|| "/tmp/nedb_exit_flush_demo".into());
match mode {
"write" => write_and_wait(&dir),
"check" => check(&dir),
other => {
eprintln!("usage: exit_flush_demo <write|check> <dir> (got mode '{other}')");
std::process::exit(2);
}
}
}
fn write_and_wait(dir: &str) {
let db = Arc::new(Db::open(std::path::Path::new(dir), None).expect("open durable db"));
Db::install_exit_flush(Arc::clone(&db));
db.put(
COLL,
ID,
serde_json::json!({ "armed": true, "pid": std::process::id() }),
vec![],
None,
None,
)
.expect("stage write");
println!("READY pid={} dir={}", std::process::id(), dir);
use std::io::Write;
let _ = std::io::stdout().flush();
loop {
std::thread::sleep(Duration::from_secs(3600));
}
}
fn check(dir: &str) {
let db = Db::open(std::path::Path::new(dir), None).expect("reopen durable db");
match db.get(COLL, ID) {
Some(node) if node.data.get("armed").and_then(|v| v.as_bool()) == Some(true) => {
println!("OK — sentinel survived exit flush (seq={})", node.seq);
}
_ => {
println!("MISSING — write was lost (no exit flush)");
std::process::exit(1);
}
}
}