use anyhow::{Result, ensure}; use fs2::FileExt; use prost::Message; use rmm_protocol::Envelope; use rusqlite::{Connection, OptionalExtension, params}; use std::{fs::OpenOptions, path::Path}; pub struct Journal { db: Connection, _lock: std::fs::File, } impl Journal { pub fn open(directory: &Path) -> Result { ensure!(directory.is_dir(), "STATE_DIRECTORY_REQUIRED"); let lock = OpenOptions::new() .read(true) .write(true) .create(true) .truncate(false) .open(directory.join("agent.lock"))?; lock.try_lock_exclusive()?; let db = Connection::open(directory.join("telemetry.sqlite"))?; db.execute_batch( "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value INTEGER NOT NULL); INSERT OR IGNORE INTO metadata VALUES('sequence',0); CREATE TABLE IF NOT EXISTS events(id TEXT PRIMARY KEY,payload BLOB NOT NULL);", )?; ensure!( db.query_row("PRAGMA integrity_check", [], |r| r.get::<_, String>(0))? == "ok", "JOURNAL_INTEGRITY" ); Ok(Self { db, _lock: lock }) } pub fn next_sequence(&mut self) -> Result { let tx = self.db.transaction()?; let sequence: i64 = tx.query_row("SELECT value FROM metadata WHERE key='sequence'", [], |r| { r.get(0) })?; let next = sequence .checked_add(1) .ok_or_else(|| anyhow::anyhow!("SEQUENCE_EXHAUSTED"))?; tx.execute("UPDATE metadata SET value=?1 WHERE key='sequence'", [next])?; tx.commit()?; Ok(u64::try_from(next)?) } pub fn save(&self, envelope: &Envelope) -> Result<()> { // This slice never deletes a durable event to make room for telemetry. // At the fixed cap it stops collecting until concrete ACKs release room. ensure!(self.count()? < 8, "TELEMETRY_BACKPRESSURE"); ensure!( matches!( envelope.payload, Some(rmm_protocol::Payload::InventorySnapshot(_)) ), "PASSIVE_INVENTORY_ONLY" ); let bytes = envelope.encode_to_vec(); ensure!(bytes.len() <= 512 * 1024, "TELEMETRY_LIMIT"); self.db.execute( "INSERT INTO events(id,payload) VALUES(?1,?2)", params![envelope.message_id, bytes], )?; Ok(()) } pub fn events(&self) -> Result> { let mut q = self .db .prepare("SELECT payload FROM events ORDER BY rowid")?; q.query_map([], |r| r.get::<_, Vec>(0))? .map(|v| Ok(Envelope::decode(v?.as_slice())?)) .collect() } pub fn count(&self) -> Result { Ok(self .db .query_row("SELECT count(*) FROM events", [], |r| r.get(0))?) } pub fn ack(&self, message_id: &str) -> Result<()> { // Unknown IDs have no effect. An HTTP status never calls this function. self.db .execute("DELETE FROM events WHERE id=?1", [message_id])?; Ok(()) } pub fn pin_identity(&self, id: &str) -> Result<()> { self.db .execute_batch("CREATE TABLE IF NOT EXISTS identity(agent TEXT PRIMARY KEY)")?; let old: Option = self .db .query_row("SELECT agent FROM identity", [], |r| r.get(0)) .optional()?; if let Some(old) = old { ensure!(old == id, "JOURNAL_IDENTITY_MISMATCH"); } else { self.db.execute("INSERT INTO identity VALUES(?1)", [id])?; } Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn durable_reopen_ack_identity_and_single_process() { let directory = std::env::temp_dir().join(format!("rmm-windows-journal-{}", uuid::Uuid::new_v4())); std::fs::create_dir(&directory).unwrap(); let mut j = Journal::open(&directory).unwrap(); assert!(Journal::open(&directory).is_err()); j.pin_identity("a").unwrap(); assert!(j.pin_identity("b").is_err()); let first = j.next_sequence().unwrap(); let e = Envelope { message_id: uuid::Uuid::new_v4().to_string(), sequence: first, payload: Some(rmm_protocol::Payload::InventorySnapshot(Default::default())), ..Default::default() }; j.save(&e).unwrap(); drop(j); let mut j = Journal::open(&directory).unwrap(); assert!(j.next_sequence().unwrap() > first); assert_eq!(j.events().unwrap()[0].message_id, e.message_id); j.ack("unrelated").unwrap(); assert_eq!(j.count().unwrap(), 1); j.ack(&e.message_id).unwrap(); assert_eq!(j.count().unwrap(), 0); let heartbeat = Envelope { payload: Some(rmm_protocol::Payload::Heartbeat(Default::default())), ..Default::default() }; assert!(j.save(&heartbeat).is_err()); drop(j); std::fs::remove_dir_all(directory).unwrap(); } }