C12.3: ElyMail local store

SQLite index, content-addressed originals, rebuildable FTS5 search,
schema versions with a backup before each upgrade and read-only on
failure, and size reporting. Three review rounds; the round 3 fixes
are checked by tests, not reviewed again.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
ZacharyZhang-NYandClaude Opus 5.5 committed 2026-10-19 18:14:09 -04:00
1 parent fe90221c11
commit 7c5bf48589
20 files changed
+1767 -3

No files matched your search

+199
View File
@@ -0,0 +1,199 @@
use std::path::Path;
use ely_mail_engine::{Error, Fetched, Key, MailboxId, MessageId, Store};
use rusqlite::Connection;
use sha2::{Digest, Sha256};
/// The sample as a server sends it: CRLF lines.
fn sample() -> Vec<u8> {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/fixtures/mail/sample.eml"
);
let text = std::fs::read_to_string(path).unwrap();
text.replace("\r\n", "\n")
.replace('\n', "\r\n")
.into_bytes()
}
fn headers(raw: &[u8]) -> &[u8] {
let end = raw.windows(4).position(|w| w == b"\r\n\r\n").unwrap();
&raw[..end + 4]
}
fn inbox(dir: &Path) -> (Store, MailboxId) {
let store = Store::open(dir).unwrap();
let account = store.add_account("ann@example.com").unwrap();
let inbox = store.mailbox(account, "INBOX").unwrap();
(store, inbox)
}
fn imap(uidvalidity: u32, uid: u32) -> Key {
Key::Imap { uidvalidity, uid }
}
/// Rows whose index holds the phrase.
fn found(dir: &Path, phrase: &str) -> Vec<i64> {
let conn = Connection::open(dir.join("mail.db")).unwrap();
let mut rows = conn
.prepare("SELECT rowid FROM search WHERE search MATCH ?1 ORDER BY rowid")
.unwrap();
rows.query_map([format!("\"{phrase}\"")], |row| row.get(0))
.unwrap()
.map(Result::unwrap)
.collect()
}
fn original_path(dir: &Path, raw: &[u8]) -> std::path::PathBuf {
let hash: String = Sha256::digest(raw)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
dir.join("content").join(&hash[..2]).join(hash)
}
#[test]
fn a_whole_message_is_indexed_and_kept_by_its_hash() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let raw = sample();
let id = store
.put(inbox, &imap(7, 42), &["\\Seen"], Fetched::Whole(&raw))
.unwrap();
let stored = store.get(id).unwrap();
assert_eq!(stored.key, imap(7, 42));
assert_eq!(stored.subject.as_deref(), Some("Café report"));
assert_eq!(stored.from[0].email, "zhang@example.com");
assert_eq!(stored.message_id.as_deref(), Some("m1@example.com"));
assert_eq!(stored.flags, ["\\Seen"]);
assert_eq!(stored.attachments, Some(1));
assert!(stored.whole);
assert_eq!(store.original(id).unwrap().as_deref(), Some(raw.as_slice()));
assert_eq!(std::fs::read(original_path(dir.path(), &raw)).unwrap(), raw);
assert_eq!(found(dir.path(), "numbers"), [id.0]);
assert_eq!(found(dir.path(), "report.pdf"), [id.0]);
let sizes = store.sizes().unwrap();
assert_eq!(sizes.originals, raw.len() as u64);
assert!(sizes.search > 0 && sizes.index > 0, "{sizes:?}");
}
#[test]
fn headers_first_then_the_whole_message() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let raw = sample();
let key = imap(7, 42);
let id = store
.put(inbox, &key, &[], Fetched::Headers(headers(&raw)))
.unwrap();
let stored = store.get(id).unwrap();
assert_eq!(stored.subject.as_deref(), Some("Café report"));
assert_eq!((stored.whole, stored.attachments), (false, None));
assert_eq!(store.original(id).unwrap(), None);
assert_eq!(found(dir.path(), "report"), [id.0]);
assert!(found(dir.path(), "numbers").is_empty());
let again = store
.put(inbox, &key, &["\\Flagged"], Fetched::Headers(headers(&raw)))
.unwrap();
assert_eq!(again, id);
assert_eq!(store.get(id).unwrap().flags, ["\\Flagged"]);
assert_eq!(
store.put(inbox, &key, &[], Fetched::Whole(&raw)).unwrap(),
id
);
assert_eq!(store.get(id).unwrap().attachments, Some(1));
assert_eq!(found(dir.path(), "numbers"), [id.0]);
}
#[test]
fn uidvalidity_is_part_of_the_identity() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let raw = sample();
let old = store
.put(inbox, &imap(1, 5), &[], Fetched::Headers(headers(&raw)))
.unwrap();
let new = store
.put(inbox, &imap(2, 5), &[], Fetched::Headers(headers(&raw)))
.unwrap();
assert_ne!(old, new);
assert_eq!(store.find(inbox, &imap(1, 5)).unwrap(), Some(old));
let pop = Key::Pop { uidl: "abc".into() };
let id = store
.put(inbox, &pop, &[], Fetched::Headers(headers(&raw)))
.unwrap();
assert_eq!(store.get(id).unwrap().key, pop);
}
#[test]
fn a_shared_original_goes_with_its_last_message() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let raw = sample();
let file = original_path(dir.path(), &raw);
let one = store
.put(inbox, &imap(1, 1), &[], Fetched::Whole(&raw))
.unwrap();
let two = store
.put(inbox, &imap(1, 2), &[], Fetched::Whole(&raw))
.unwrap();
assert_eq!(store.sizes().unwrap().originals, raw.len() as u64);
store.remove(one).unwrap();
assert!(file.exists());
assert_eq!(found(dir.path(), "numbers"), [two.0]);
store.remove(two).unwrap();
assert!(!file.exists());
assert!(found(dir.path(), "numbers").is_empty());
let err = store.remove(MessageId(two.0)).unwrap_err();
assert!(
matches!(&err, Error::Store(text) if text.contains("no message")),
"{err}"
);
}
#[test]
fn a_damaged_original_is_refused() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let raw = sample();
let id = store
.put(inbox, &imap(1, 1), &[], Fetched::Whole(&raw))
.unwrap();
std::fs::write(original_path(dir.path(), &raw), b"not the message").unwrap();
let err = store.original(id).unwrap_err();
assert!(
matches!(&err, Error::Store(text) if text.contains("damaged")),
"{err}"
);
}
#[test]
fn the_search_index_rebuilds_from_the_store() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let whole = store
.put(inbox, &imap(1, 1), &[], Fetched::Whole(&sample()))
.unwrap();
let html = b"Subject: news\r\nContent-Type: text/html\r\n\r\n\
<style>.hidden{color:red}</style><p>Quarterly<b>results</b></p>\
<script>trackingpixel()</script>";
let page = store
.put(inbox, &imap(1, 2), &[], Fetched::Whole(html))
.unwrap();
assert_eq!(found(dir.path(), "results"), [page.0]);
assert!(found(dir.path(), "tracking").is_empty());
assert!(found(dir.path(), "hidden").is_empty());
assert!(found(dir.path(), "Quarterlyresults").is_empty());
Connection::open(dir.path().join("mail.db"))
.unwrap()
.execute("DELETE FROM search", [])
.unwrap();
assert!(found(dir.path(), "numbers").is_empty());
assert_eq!(store.rebuild_search().unwrap(), 2);
assert_eq!(found(dir.path(), "numbers"), [whole.0]);
assert_eq!(found(dir.path(), "zhang"), [whole.0]);
assert_eq!(found(dir.path(), "results"), [page.0]);
}
@@ -0,0 +1,72 @@
#![cfg(windows)]
use std::{fs::File, os::windows::fs::OpenOptionsExt, path::Path};
use ely_mail_engine::{Fetched, Key, MailboxId, Store};
use sha2::{Digest, Sha256};
const ONE: &[u8] = b"Subject: one\r\n\r\nfirst body\r\n";
const TWO: &[u8] = b"Subject: two\r\n\r\nsecond body\r\n";
fn inbox(dir: &Path) -> (Store, MailboxId) {
let store = Store::open(dir).unwrap();
let account = store.add_account("ann@example.com").unwrap();
let inbox = store.mailbox(account, "INBOX").unwrap();
(store, inbox)
}
fn imap() -> Key {
Key::Imap {
uidvalidity: 1,
uid: 1,
}
}
fn original_path(dir: &Path, raw: &[u8]) -> std::path::PathBuf {
let hash: String = Sha256::digest(raw)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
dir.join("content").join(&hash[..2]).join(hash)
}
/// Read sharing only: delete fails.
fn hold(path: &Path) -> File {
File::options().read(true).share_mode(1).open(path).unwrap()
}
#[test]
fn a_held_original_keeps_its_message_for_retry() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let id = store.put(inbox, &imap(), &[], Fetched::Whole(ONE)).unwrap();
let path = original_path(dir.path(), ONE);
let held = hold(&path);
assert!(store.remove(id).is_err());
assert_eq!(store.get(id).unwrap().subject.as_deref(), Some("one"));
assert_eq!(store.original(id).unwrap().as_deref(), Some(ONE));
drop(held);
store.remove(id).unwrap();
assert!(store.get(id).is_err());
assert!(!path.exists());
assert_eq!(store.sizes().unwrap().originals, 0);
}
#[test]
fn a_held_old_original_keeps_the_old_message() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let id = store.put(inbox, &imap(), &[], Fetched::Whole(ONE)).unwrap();
let old = original_path(dir.path(), ONE);
let new = original_path(dir.path(), TWO);
let held = hold(&old);
assert!(store.put(inbox, &imap(), &[], Fetched::Whole(TWO)).is_err());
assert_eq!(store.get(id).unwrap().subject.as_deref(), Some("one"));
assert_eq!(store.original(id).unwrap().as_deref(), Some(ONE));
assert!(!new.exists());
drop(held);
store.put(inbox, &imap(), &[], Fetched::Whole(TWO)).unwrap();
assert_eq!(store.original(id).unwrap().as_deref(), Some(TWO));
assert!(!old.exists());
assert_eq!(store.sizes().unwrap().originals, TWO.len() as u64);
}
@@ -0,0 +1,238 @@
use std::path::Path;
use ely_mail_engine::{Error, Fetched, Key, MailboxId, MessageId, Store};
use rusqlite::Connection;
use sha2::{Digest, Sha256};
fn sample() -> Vec<u8> {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/fixtures/mail/sample.eml"
);
let text = std::fs::read_to_string(path).unwrap();
text.replace("\r\n", "\n")
.replace('\n', "\r\n")
.into_bytes()
}
fn inbox(dir: &Path) -> (Store, MailboxId) {
let store = Store::open(dir).unwrap();
let account = store.add_account("ann@example.com").unwrap();
let inbox = store.mailbox(account, "INBOX").unwrap();
(store, inbox)
}
fn imap(uid: u32) -> Key {
Key::Imap {
uidvalidity: 1,
uid,
}
}
fn search(dir: &Path, phrase: &str) -> rusqlite::Result<Vec<i64>> {
let conn = Connection::open(dir.join("mail.db"))?;
let mut rows = conn.prepare("SELECT rowid FROM search WHERE search MATCH ?1")?;
rows.query_map([format!("\"{phrase}\"")], |row| row.get(0))?
.collect()
}
fn found(dir: &Path, phrase: &str) -> Vec<i64> {
search(dir, phrase).unwrap()
}
fn original_path(dir: &Path, raw: &[u8]) -> std::path::PathBuf {
let hash: String = Sha256::digest(raw)
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
dir.join("content").join(&hash[..2]).join(hash)
}
#[test]
fn a_corrupt_search_index_rebuilds() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let id = store
.put(inbox, &imap(1), &[], Fetched::Whole(&sample()))
.unwrap();
let damaged = Connection::open(dir.path().join("mail.db"))
.unwrap()
.execute("UPDATE search_data SET block = X'00' WHERE id > 10", [])
.unwrap();
assert!(damaged > 0);
assert!(search(dir.path(), "numbers").is_err());
assert_eq!(store.rebuild_search().unwrap(), 1);
assert_eq!(found(dir.path(), "numbers"), [id.0]);
drop(store);
Store::open(dir.path()).unwrap();
assert_eq!(found(dir.path(), "numbers"), [id.0]);
}
#[test]
fn a_damaged_original_is_rewritten_by_a_new_copy() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let raw = sample();
let id = store
.put(inbox, &imap(1), &[], Fetched::Whole(&raw))
.unwrap();
std::fs::write(original_path(dir.path(), &raw), b"damaged").unwrap();
store
.put(inbox, &imap(2), &[], Fetched::Whole(&raw))
.unwrap();
assert_eq!(store.original(id).unwrap().as_deref(), Some(raw.as_slice()));
std::fs::write(original_path(dir.path(), &raw), b"damaged").unwrap();
assert_eq!(
store
.put(inbox, &imap(1), &[], Fetched::Whole(&raw))
.unwrap(),
id
);
assert_eq!(store.original(id).unwrap().as_deref(), Some(raw.as_slice()));
}
#[test]
fn a_failed_write_keeps_no_new_original() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let raw = sample();
let nowhere = MailboxId(999);
assert!(
store
.put(nowhere, &imap(1), &[], Fetched::Whole(&raw))
.is_err()
);
assert_eq!(store.sizes().unwrap().originals, 0);
let id = store
.put(inbox, &imap(1), &[], Fetched::Whole(&raw))
.unwrap();
assert!(
store
.put(nowhere, &imap(2), &[], Fetched::Whole(&raw))
.is_err()
);
assert_eq!(store.original(id).unwrap().as_deref(), Some(raw.as_slice()));
}
#[test]
fn sizes_count_the_write_ahead_log() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let id = store
.put(inbox, &imap(1), &[], Fetched::Whole(&sample()))
.unwrap();
for turn in 0..600 {
let flag = if turn % 2 == 0 { "\\Seen" } else { "\\Flagged" };
store.set_flags(id, &[flag]).unwrap();
}
let disk: u64 = ["mail.db", "mail.db-wal", "mail.db-shm"]
.iter()
.map(|name| std::fs::metadata(dir.path().join(name)).unwrap().len())
.sum();
let sizes = store.sizes().unwrap();
assert!(disk > 1_000_000, "{disk}");
assert_eq!(sizes.index + sizes.search, disk);
}
#[test]
fn flags_for_a_missing_message_fail() {
let dir = tempfile::tempdir().unwrap();
let (mut store, _) = inbox(dir.path());
let err = store.set_flags(MessageId(5), &[]).unwrap_err();
assert!(
matches!(&err, Error::Store(text) if text.contains("no message")),
"{err}"
);
}
#[test]
fn html_text_follows_the_parser_states() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let html = b"Subject: page\r\nContent-Type: text/html\r\n\r\n\
<title>headline</title><script/>trackingpixel()</script>\
<textarea><script>ordinarycontent</script></textarea>\
<xmp><b>literalmarkup</b></xmp><iframe>fallbacktext</iframe>\
<svg><style/>vectorlabel<script>vectorcode()</script></svg>\
<svg><foreignObject><script/>trackingforeign()</script>\
<textarea><script>ordinaryforeign</script></textarea></foreignObject></svg>\
<math><annotation-xml encoding=\"text/html\"><script/>annotationcode()</script>\
</annotation-xml></math><p>closingword</p>";
let id = store
.put(inbox, &imap(1), &[], Fetched::Whole(html))
.unwrap();
for round in 0..2 {
for shown in [
"ordinarycontent",
"<b>literalmarkup",
"vectorlabel",
"<script>ordinaryforeign",
"closingword",
] {
assert_eq!(found(dir.path(), shown), [id.0], "{shown} {round}");
}
for hidden in [
"headline",
"trackingpixel",
"fallbacktext",
"vectorcode",
"trackingforeign",
"annotationcode",
] {
assert!(found(dir.path(), hidden).is_empty(), "{hidden} {round}");
}
store.rebuild_search().unwrap();
}
}
#[cfg(windows)]
#[test]
fn a_failed_publish_leaves_no_staged_copy() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let raw = sample();
let id = store
.put(inbox, &imap(1), &[], Fetched::Whole(&raw))
.unwrap();
let path = original_path(dir.path(), &raw);
std::fs::write(&path, b"damaged").unwrap();
let mut locked = std::fs::metadata(&path).unwrap().permissions();
locked.set_readonly(true);
std::fs::set_permissions(&path, locked.clone()).unwrap();
assert!(
store
.put(inbox, &imap(1), &[], Fetched::Whole(&raw))
.is_err()
);
#[allow(clippy::permissions_set_readonly_false)]
locked.set_readonly(false);
std::fs::set_permissions(&path, locked).unwrap();
store.remove(id).unwrap();
assert_eq!(store.sizes().unwrap().originals, 0);
let left: Vec<_> = std::fs::read_dir(path.parent().unwrap()).unwrap().collect();
assert!(left.is_empty(), "{left:?}");
}
#[test]
fn deep_html_stops_at_its_depth_limit() {
let dir = tempfile::tempdir().unwrap();
let (mut store, inbox) = inbox(dir.path());
let mut html = b"Subject: deep
Content-Type: text/html
"
.to_vec();
html.extend("<div>".repeat(500).bytes());
html.extend(b"shallowword");
html.extend("<div>".repeat(200_000).bytes());
html.extend(b"bottomword");
let started = std::time::Instant::now();
let id = store
.put(inbox, &imap(1), &[], Fetched::Whole(&html))
.unwrap();
assert!(started.elapsed().as_secs() < 5, "{:?}", started.elapsed());
assert_eq!(found(dir.path(), "shallowword"), [id.0]);
assert!(found(dir.path(), "bottomword").is_empty());
}