//! `mail.db`: what the Mac has sent of each conversation, so a thread's row //! can say its first and latest email, how many it holds and who is in it. //! //! The object runs no engine for mail and the Mac reads nothing back, so the //! fold the old ingest made inside the store (`email_count`, `first_at`, //! `last_at`, the participants' climbing roles) is made here, over every //! email this Mac has sent. An email is counted once by its row id, so a //! re-read changes nothing. Deleting the file only forgets the fold: rows //! keep their ids, and a thread the object holds but this file does not is //! treated as one the Mac did not make (see [`Owned`]). use std::path::Path; use std::sync::Mutex; use rusqlite::{params, Connection, OptionalExtension}; /// Whether the object's row for a thread is the Mac's own fold. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Owned { /// Never sent from here. Unsent, /// The Mac created it: its aggregates are this file's, and are sent whole. Mine, /// The object held it before this Mac sent it (brought over from the old /// store, or this file was deleted): its count and first date are not /// known here, so only what cannot regress is sent. Foreign, } /// One thread's fold. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Thread { pub key: String, pub subject: Option, pub first_at: Option, pub last_at: Option, pub email_count: i64, pub owned: Owned, } /// One address in a thread: the highest role it has had and its first name. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Participant { pub email: String, pub display_name: Option, pub role: String, } pub fn role_rank(role: &str) -> i64 { match role { "from" => 3, "to" => 2, "cc" => 1, _ => 0, } } pub struct Tally { conn: Mutex, } impl Tally { 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 emails ( id TEXT PRIMARY KEY, thread_key TEXT NOT NULL, gmail_id TEXT ); CREATE INDEX IF NOT EXISTS emails_gmail ON emails (gmail_id); CREATE TABLE IF NOT EXISTS threads ( thread_key TEXT PRIMARY KEY, subject TEXT, first_at TEXT, last_at TEXT, email_count INTEGER NOT NULL DEFAULT 0, owned TEXT NOT NULL DEFAULT 'unsent' ); CREATE TABLE IF NOT EXISTS participants ( thread_key TEXT NOT NULL, email TEXT NOT NULL, display_name TEXT, role TEXT NOT NULL, PRIMARY KEY (thread_key, email) ); CREATE TABLE IF NOT EXISTS trash_on_arrival ( account TEXT NOT NULL, address TEXT NOT NULL, uid_validity INTEGER NOT NULL, since INTEGER NOT NULL, PRIMARY KEY (account, address) );", )?; Ok(Tally { conn: Mutex::new(conn) }) } fn conn(&self) -> std::sync::MutexGuard<'_, Connection> { self.conn.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) } /// `address` joins (or stays on) the senders of `account` whose mail goes to Trash as it arrives (his unsubscribe /// from a sender offering no one-click): from UID `since` on, in the numbering `uid_validity` names. pub fn listen(&self, account: &str, address: &str, uid_validity: u32, since: u32) -> rusqlite::Result<()> { self.conn() .execute( "INSERT INTO trash_on_arrival (account, address, uid_validity, since) VALUES (?1, ?2, ?3, ?4) ON CONFLICT (account, address) DO UPDATE SET uid_validity = excluded.uid_validity, since = excluded.since", params![account.trim().to_lowercase(), address, uid_validity, since], ) .map(|_| ()) } /// The senders of `account` on that list: (address, uid_validity, since). pub fn listened(&self, account: &str) -> rusqlite::Result> { let conn = self.conn(); let mut statement = conn.prepare("SELECT address, uid_validity, since FROM trash_on_arrival WHERE account = ?1 ORDER BY address")?; let rows = statement.query_map(params![account.trim().to_lowercase()], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?; rows.collect() } /// The email row id this Mac sent for a Gmail id. pub fn email_by_gmail_id(&self, gmail_id: &str) -> rusqlite::Result> { self.conn() .query_row("SELECT id FROM emails WHERE gmail_id = ?", params![gmail_id], |row| row.get(0)) .optional() } /// Every email this Mac counted that has a Gmail id: (row id, Gmail API id). How a launch finds the mail it /// counted that never reached the database (SYNC GAP, 25 Nov 2026). pub fn gmail_emails(&self) -> rusqlite::Result> { let conn = self.conn(); let mut statement = conn.prepare("SELECT id, gmail_id FROM emails WHERE gmail_id IS NOT NULL ORDER BY id")?; let rows = statement.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?; rows.collect() } /// Un-count an email whose push did not reach the object, so the next read sends it whole. Its thread keeps /// its dates and people (folding the email again gives the same ones) and loses one from its count. pub fn forget(&self, email_id: &str) -> rusqlite::Result<()> { let mut conn = self.conn(); let tx = conn.transaction()?; let thread: Option = tx.query_row("SELECT thread_key FROM emails WHERE id = ?1", params![email_id], |r| r.get(0)).optional()?; if let Some(thread) = thread { tx.execute("DELETE FROM emails WHERE id = ?1", params![email_id])?; tx.execute("UPDATE threads SET email_count = max(email_count - 1, 0) WHERE thread_key = ?1", params![thread])?; } tx.commit() } pub fn knows(&self, email_id: &str) -> rusqlite::Result { Ok(self .conn() .query_row("SELECT 1 FROM emails WHERE id = ?", params![email_id], |_| Ok(())) .optional()? .is_some()) } /// Fold one email into its thread; `false` when it was counted before. /// `subject` names a thread that has no name yet; `addresses` are /// (email, name, role) in the order the old ingest folded them. pub fn add( &self, email_id: &str, thread_key: &str, gmail_id: Option<&str>, sent_at: &str, subject: &str, addresses: &[(String, Option, &str)], ) -> rusqlite::Result { let mut conn = self.conn(); let tx = conn.transaction()?; let added = tx.execute( "INSERT OR IGNORE INTO emails (id, thread_key, gmail_id) VALUES (?1, ?2, ?3)", params![email_id, thread_key, gmail_id], )?; if added == 0 { return Ok(false); } tx.execute( "INSERT OR IGNORE INTO threads (thread_key) VALUES (?1)", params![thread_key], )?; tx.execute( "UPDATE threads SET email_count = email_count + 1, first_at = CASE WHEN first_at IS NULL OR ?2 < first_at THEN ?2 ELSE first_at END, last_at = CASE WHEN last_at IS NULL OR ?2 > last_at THEN ?2 ELSE last_at END, subject = COALESCE(subject, ?3) WHERE thread_key = ?1", params![thread_key, sent_at, (!subject.is_empty()).then_some(subject)], )?; for (email, name, role) in addresses { let held: Option<(Option, String)> = tx .query_row( "SELECT display_name, role FROM participants WHERE thread_key = ?1 AND email = ?2", params![thread_key, email], |row| Ok((row.get(0)?, row.get(1)?)), ) .optional()?; match held { None => { tx.execute( "INSERT INTO participants (thread_key, email, display_name, role) VALUES (?1, ?2, ?3, ?4)", params![thread_key, email, name, role], )?; } Some((held_name, held_role)) => { let role = if role_rank(role) > role_rank(&held_role) { role.to_string() } else { held_role }; let name = held_name.or_else(|| name.clone().filter(|n| !n.is_empty())); tx.execute( "UPDATE participants SET display_name = ?3, role = ?4 WHERE thread_key = ?1 AND email = ?2", params![thread_key, email, name, role], )?; } } } tx.commit()?; Ok(true) } pub fn thread(&self, thread_key: &str) -> rusqlite::Result> { self.conn() .query_row( "SELECT subject, first_at, last_at, email_count, owned FROM threads WHERE thread_key = ?", params![thread_key], |row| { let owned: String = row.get(4)?; Ok(Thread { key: thread_key.to_string(), subject: row.get(0)?, first_at: row.get(1)?, last_at: row.get(2)?, email_count: row.get(3)?, owned: match owned.as_str() { "mine" => Owned::Mine, "foreign" => Owned::Foreign, _ => Owned::Unsent, }, }) }, ) .optional() } pub fn set_owned(&self, thread_key: &str, owned: Owned) -> rusqlite::Result<()> { let value = match owned { Owned::Unsent => "unsent", Owned::Mine => "mine", Owned::Foreign => "foreign", }; self.conn().execute( "UPDATE threads SET owned = ?2 WHERE thread_key = ?1", params![thread_key, value], )?; Ok(()) } pub fn participants(&self, thread_key: &str) -> rusqlite::Result> { let conn = self.conn(); let mut statement = conn.prepare( "SELECT email, display_name, role FROM participants WHERE thread_key = ? ORDER BY rowid", )?; let rows = statement.query_map(params![thread_key], |row| { Ok(Participant { email: row.get(0)?, display_name: row.get(1)?, role: row.get(2)?, }) })?; rows.collect() } } #[cfg(test)] mod tests { use super::*; #[test] fn a_thread_folds_each_email_once_and_roles_only_climb() { let dir = tempfile::tempdir().unwrap(); let tally = Tally::open(&dir.path().join("mail.db")).unwrap(); let first = vec![ ("ada@example.org".to_string(), None, "to"), ("bo@example.net".to_string(), Some("Bo".to_string()), "from"), ]; assert!(tally.add("e2", "imap:root", None, "2026-10-05T10:00:00.000Z", "Plans", &first).unwrap()); assert!(!tally.add("e2", "imap:root", None, "2026-10-05T10:00:00.000Z", "Plans", &first).unwrap()); let second = vec![("ada@example.org".to_string(), Some("Ada".to_string()), "from")]; assert!(tally.add("e1", "imap:root", Some("abc"), "2026-10-05T09:00:00.000Z", "Re: Plans", &second).unwrap()); let thread = tally.thread("imap:root").unwrap().unwrap(); assert_eq!(thread.email_count, 2); assert_eq!(thread.first_at.as_deref(), Some("2026-10-05T09:00:00.000Z")); assert_eq!(thread.last_at.as_deref(), Some("2026-10-05T10:00:00.000Z")); assert_eq!(thread.subject.as_deref(), Some("Plans")); assert_eq!(thread.owned, Owned::Unsent); let people = tally.participants("imap:root").unwrap(); assert_eq!(people[0], Participant { email: "ada@example.org".into(), display_name: Some("Ada".into()), role: "from".into() }); assert_eq!(tally.email_by_gmail_id("abc").unwrap().as_deref(), Some("e1")); tally.set_owned("imap:root", Owned::Mine).unwrap(); assert_eq!(tally.thread("imap:root").unwrap().unwrap().owned, Owned::Mine); } }