//! `importer.db`: the Mac's only state — where each source got to and what //! it last brought. Deleting it forgets the positions and nothing else: every //! row the Mac sends is keyed by its source's own id, so a re-read from the //! start writes nothing twice at the object. use std::path::Path; use std::sync::Mutex; use rusqlite::{params, Connection, OptionalExtension}; use serde::Serialize; #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)] #[serde(rename_all = "camelCase")] pub struct SourceRecord { pub source: String, pub cursor: Option, /// When a run last finished, ISO-8601. pub last_run_at: Option, /// Rows the last run that brought anything brought. pub last_brought: i64, /// When a run last brought anything. pub last_brought_at: Option, /// Every row ever brought. pub total: i64, /// The last run's failure, cleared by a run that succeeds. pub last_error: Option, pub paused: bool, } pub struct Store { conn: Mutex, } impl Store { pub fn open(path: &Path) -> rusqlite::Result { if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); } let conn = Connection::open(path)?; conn.execute_batch( "PRAGMA journal_mode = WAL; CREATE TABLE IF NOT EXISTS sources ( source TEXT PRIMARY KEY, cursor TEXT, last_run_at TEXT, last_brought INTEGER NOT NULL DEFAULT 0, last_brought_at TEXT, total INTEGER NOT NULL DEFAULT 0, last_error TEXT, paused INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS facts ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS hand_handed ( request_id TEXT NOT NULL, tbl TEXT NOT NULL, v INTEGER NOT NULL, PRIMARY KEY (request_id, tbl) ) WITHOUT ROWID;", )?; Ok(Store { conn: Mutex::new(conn) }) } /// What this Mac handed one grant to your Claude ([`crate::hand`]), by table: the newest version. pub fn hand_handed(&self, request_id: &str) -> rusqlite::Result> { let conn = self.conn(); let mut statement = conn.prepare("SELECT tbl, v FROM hand_handed WHERE request_id = ?1")?; let found = statement.query_map(params![request_id], |row| Ok((row.get::<_, String>(0)?, row.get::<_, u32>(1)?)))?.collect(); found } /// Note what this Mac handed a grant, each table at its version (a newer one replaces an older). pub fn note_hand_handed(&self, request_id: &str, versions: &[(String, u32)]) -> rusqlite::Result<()> { let conn = self.conn(); for (table, v) in versions { conn.execute("INSERT INTO hand_handed (request_id, tbl, v) VALUES (?1, ?2, ?3) ON CONFLICT (request_id, tbl) DO UPDATE SET v = max(v, excluded.v)", params![request_id, table, v])?; } Ok(()) } fn conn(&self) -> std::sync::MutexGuard<'_, Connection> { self.conn.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } pub fn record(&self, source: &str) -> rusqlite::Result { let conn = self.conn(); let found = conn .query_row( "SELECT cursor, last_run_at, last_brought, last_brought_at, total, last_error, paused FROM sources WHERE source = ?", params![source], |row| { Ok(SourceRecord { source: source.to_string(), cursor: row.get(0)?, last_run_at: row.get(1)?, last_brought: row.get(2)?, last_brought_at: row.get(3)?, total: row.get(4)?, last_error: row.get(5)?, paused: row.get::<_, i64>(6)? != 0, }) }, ) .optional()?; Ok(found.unwrap_or(SourceRecord { source: source.to_string(), ..SourceRecord::default() })) } pub fn cursor(&self, source: &str) -> rusqlite::Result> { Ok(self.record(source)?.cursor) } fn ensure(conn: &Connection, source: &str) -> rusqlite::Result<()> { conn.execute("INSERT OR IGNORE INTO sources (source) VALUES (?)", params![source])?; Ok(()) } /// A batch is safely at the object: move the cursor and count its rows. pub fn advance(&self, source: &str, cursor: Option<&str>, brought: i64, at: &str) -> rusqlite::Result<()> { let conn = self.conn(); Self::ensure(&conn, source)?; if let Some(cursor) = cursor { conn.execute("UPDATE sources SET cursor = ? WHERE source = ?", params![cursor, source])?; } if brought > 0 { conn.execute( "UPDATE sources SET total = total + ?1, last_brought_at = ?2 WHERE source = ?3", params![brought, at, source], )?; } Ok(()) } /// A run ended: `brought` rows in all, and the error if it failed. pub fn finish(&self, source: &str, brought: i64, error: Option<&str>, at: &str) -> rusqlite::Result<()> { let conn = self.conn(); Self::ensure(&conn, source)?; conn.execute( "UPDATE sources SET last_run_at = ?1, last_error = ?2 WHERE source = ?3", params![at, error, source], )?; if brought > 0 { conn.execute( "UPDATE sources SET last_brought = ?1 WHERE source = ?2", params![brought, source], )?; } Ok(()) } /// The source's count set to what is really there (counted in the importer's copy): it replaces a count the /// runs added up, which before build 5 counted every row a batch carried and every thing sent again. pub fn set_total(&self, source: &str, total: i64) -> rusqlite::Result<()> { let conn = self.conn(); Self::ensure(&conn, source)?; conn.execute("UPDATE sources SET total = ?1 WHERE source = ?2", params![total.max(0), source])?; Ok(()) } /// `bringAgain`: the next run reads the source from its start. Counts and what is at the object stay; the /// object keeps one row per id, so what comes in again lands on itself. pub fn forget_cursor(&self, source: &str) -> rusqlite::Result<()> { let conn = self.conn(); Self::ensure(&conn, source)?; conn.execute("UPDATE sources SET cursor = NULL WHERE source = ?", params![source])?; Ok(()) } pub fn set_paused(&self, source: &str, paused: bool) -> rusqlite::Result<()> { let conn = self.conn(); Self::ensure(&conn, source)?; conn.execute( "UPDATE sources SET paused = ? WHERE source = ?", params![paused as i64, source], )?; Ok(()) } pub fn fact(&self, key: &str) -> rusqlite::Result> { self.conn() .query_row("SELECT value FROM facts WHERE key = ?", params![key], |row| row.get(0)) .optional() } pub fn set_fact(&self, key: &str, value: Option<&str>) -> rusqlite::Result<()> { let conn = self.conn(); match value { Some(value) => conn.execute( "INSERT INTO facts (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", params![key, value], )?, None => conn.execute("DELETE FROM facts WHERE key = ?", params![key])?, }; Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn cursors_and_counts_survive_reopen() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("importer.db"); { let store = Store::open(&path).unwrap(); store.advance("calls", Some("pk:10"), 3, "2026-10-26T00:00:00.000Z").unwrap(); store.advance("calls", Some("pk:12"), 2, "2026-10-26T00:00:01.000Z").unwrap(); store.finish("calls", 5, None, "2026-10-26T00:00:02.000Z").unwrap(); store.set_paused("calls", true).unwrap(); store.set_fact("database_id", Some("db")).unwrap(); } let store = Store::open(&path).unwrap(); let record = store.record("calls").unwrap(); assert_eq!(record.cursor.as_deref(), Some("pk:12")); assert_eq!(record.total, 5); assert_eq!(record.last_brought, 5); assert!(record.paused); assert_eq!(store.fact("database_id").unwrap().as_deref(), Some("db")); assert_eq!(store.record("mail").unwrap().total, 0); } #[test] fn a_count_set_from_what_is_held_replaces_the_added_up_one() { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("importer.db")).unwrap(); store.advance("photos", Some("6"), 12, "2026-11-23T04:32:08.685Z").unwrap(); store.set_total("photos", 6).unwrap(); let record = store.record("photos").unwrap(); assert_eq!((record.total, record.cursor.as_deref()), (6, Some("6"))); store.set_total("calls", -1).unwrap(); assert_eq!(store.record("calls").unwrap().total, 0); } }