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

+5
View File
@@ -9,6 +9,7 @@ publish.workspace = true
[dependencies]
base64.workspace = true
getrandom.workspace = true
html5ever.workspace = true
imap-proto.workspace = true
log.workspace = true
mail-builder.workspace = true
@@ -17,6 +18,10 @@ mail-send.workspace = true
nom.workspace = true
rustls.workspace = true
rustls-platform-verifier.workspace = true
rusqlite.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
smtp-proto = "0.2"
tokio.workspace = true
tokio-rustls.workspace = true
+18
View File
@@ -21,6 +21,10 @@ pub enum Error {
Invalid(String),
/// A message that cannot be read or written.
Mime(String),
/// The local store failed: database, disk or damage.
Store(String),
/// The store refuses writes; the reason says why.
ReadOnly(String),
}
impl fmt::Display for Error {
@@ -34,8 +38,22 @@ impl fmt::Display for Error {
Self::Timeout(step) => write!(f, "no answer while {step}"),
Self::Invalid(text) => write!(f, "cannot be sent: {text}"),
Self::Mime(text) => write!(f, "unreadable message: {text}"),
Self::Store(text) => write!(f, "local store failed: {text}"),
Self::ReadOnly(text) => write!(f, "local store is read-only: {text}"),
}
}
}
impl std::error::Error for Error {}
impl From<rusqlite::Error> for Error {
fn from(err: rusqlite::Error) -> Self {
Self::Store(err.to_string())
}
}
impl From<serde_json::Error> for Error {
fn from(err: serde_json::Error) -> Self {
Self::Store(format!("a stored field: {err}"))
}
}
+2
View File
@@ -6,6 +6,7 @@ mod mime;
mod net;
mod pop;
mod smtp;
mod store;
mod wire;
pub use error::{Error, Result};
@@ -14,4 +15,5 @@ pub use mime::{Built, Draft, Mail, Mailbox, Part, build, read};
pub use net::{Login, Secret, Security, Server, system_tls};
pub use pop::Pop;
pub use smtp::Smtp;
pub use store::{AccountId, Fetched, Key, MailboxId, MessageId, Sizes, Store, Stored};
pub use tokio_rustls::TlsConnector;
+2 -1
View File
@@ -4,12 +4,13 @@ use mail_builder::{
mime::MimePart,
};
use mail_parser::{Address, HeaderValue, MessageParser};
use serde::{Deserialize, Serialize};
use crate::{Error, Result, smtp::mailbox};
mod walk;
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Mailbox {
pub name: Option<String>,
pub email: String,
+228
View File
@@ -0,0 +1,228 @@
//! The local index, the originals and the search index.
use std::{
fs, io,
path::{Path, PathBuf},
time::{SystemTime, UNIX_EPOCH},
};
use rusqlite::{Connection, OpenFlags, OptionalExtension, params};
use crate::{Error, Result};
mod html;
mod messages;
mod schema;
mod search;
#[cfg(test)]
mod tests;
pub use messages::{Fetched, Key, Stored};
const DB: &str = "mail.db";
const CONTENT: &str = "content";
const BACKUPS: &str = "backups";
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct AccountId(pub i64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MailboxId(pub i64);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MessageId(pub i64);
/// Bytes on disk per kind.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Sizes {
pub index: u64,
pub search: u64,
pub originals: u64,
}
pub struct Store {
conn: Connection,
dir: PathBuf,
/// Why writes are refused, when they are.
read_only: Option<String>,
}
impl Store {
pub fn open(dir: &Path) -> Result<Self> {
open(dir, schema::STEPS)
}
pub fn read_only(&self) -> Option<&str> {
self.read_only.as_deref()
}
fn writable(&self) -> Result<()> {
match &self.read_only {
Some(reason) => Err(Error::ReadOnly(reason.clone())),
None => Ok(()),
}
}
pub fn add_account(&self, address: &str) -> Result<AccountId> {
self.writable()?;
self.conn
.execute("INSERT INTO accounts (address) VALUES (?1)", [address])?;
Ok(AccountId(self.conn.last_insert_rowid()))
}
pub fn accounts(&self) -> Result<Vec<(AccountId, String)>> {
let mut query = self
.conn
.prepare("SELECT id, address FROM accounts ORDER BY id")?;
let rows = query.query_map([], |row| Ok((AccountId(row.get(0)?), row.get(1)?)))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
/// The mailbox by name, made on first use.
pub fn mailbox(&self, account: AccountId, name: &str) -> Result<MailboxId> {
let find = "SELECT id FROM mailboxes WHERE account = ?1 AND name = ?2";
if let Some(id) = self
.conn
.query_row(find, params![account.0, name], |row| row.get(0))
.optional()?
{
return Ok(MailboxId(id));
}
self.writable()?;
self.conn.execute(
"INSERT INTO mailboxes (account, name) VALUES (?1, ?2)",
params![account.0, name],
)?;
Ok(MailboxId(self.conn.last_insert_rowid()))
}
/// The index counts the WAL and shared-memory files.
pub fn sizes(&self) -> Result<Sizes> {
let mut files = 0;
for name in [DB.to_owned(), format!("{DB}-wal"), format!("{DB}-shm")] {
files += match fs::metadata(self.dir.join(&name)) {
Ok(meta) => meta.len(),
Err(err) if err.kind() == io::ErrorKind::NotFound => 0,
Err(err) => return Err(disk("measuring the index", err)),
};
}
let search: i64 = self.conn.query_row(
"SELECT coalesce(sum(pgsize), 0) FROM dbstat
WHERE name = 'search' OR name GLOB 'search_*'",
[],
|row| row.get(0),
)?;
let search = u64::try_from(search)
.map_err(|_| Error::Store(format!("a negative size: {search}")))?;
let index = files.checked_sub(search).ok_or_else(|| {
Error::Store(format!("search pages {search} exceed the files {files}"))
})?;
Ok(Sizes {
index,
search,
originals: folder_size(&self.dir.join(CONTENT))?,
})
}
}
fn open(dir: &Path, steps: &[&str]) -> Result<Store> {
let path = dir.join(DB);
fs::create_dir_all(dir.join(CONTENT)).map_err(|err| disk("making the store", err))?;
let mut conn = Connection::open(&path)?;
let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
let version = usize::try_from(version)
.map_err(|_| Error::Store(format!("schema version {version} is negative")))?;
let target = steps.len();
let refused = if version > target {
Some(format!(
"written by a newer ElyMail (schema v{version}, this one reads v{target})"
))
} else if version < target {
upgrade(&mut conn, dir, version, steps).err()
} else {
None
};
if let Some(reason) = refused {
log::warn!("mail: store opened read-only: {reason}");
drop(conn);
let flags = OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX;
let conn = Connection::open_with_flags(&path, flags)?;
return Ok(Store {
conn,
dir: dir.to_owned(),
read_only: Some(reason),
});
}
conn.pragma_update(None, "foreign_keys", true)?;
conn.pragma_update(None, "journal_mode", "WAL")?;
log::info!("mail: store opened at schema v{target}");
Ok(Store {
conn,
dir: dir.to_owned(),
read_only: None,
})
}
/// A backup comes first; a failure keeps the old data.
fn upgrade(
conn: &mut Connection,
dir: &Path,
version: usize,
steps: &[&str],
) -> std::result::Result<(), String> {
if version > 0 {
backup(conn, dir, version).map_err(|err| format!("no backup before upgrade: {err}"))?;
}
migrate(conn, version, steps).map_err(|err| {
format!(
"upgrade from schema v{version} to v{} failed: {err}",
steps.len()
)
})?;
log::info!("mail: store schema v{version} upgraded to v{}", steps.len());
Ok(())
}
fn migrate(conn: &mut Connection, version: usize, steps: &[&str]) -> rusqlite::Result<()> {
let tx = conn.transaction()?;
for step in &steps[version..] {
tx.execute_batch(step)?;
}
tx.pragma_update(None, "user_version", steps.len() as i64)?;
tx.commit()
}
fn backup(conn: &Connection, dir: &Path, version: usize) -> Result<()> {
let folder = dir.join(BACKUPS);
fs::create_dir_all(&folder).map_err(|err| disk("making the backup folder", err))?;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|err| Error::Store(format!("the clock is before 1970: {err}")))?
.as_secs();
let target = folder.join(format!("mail-v{version}-{now}.db"));
let target = target
.to_str()
.ok_or_else(|| Error::Store("the backup path is not UTF-8".into()))?;
conn.execute("VACUUM INTO ?1", [target])?;
log::info!("mail: store schema v{version} backed up before upgrade");
Ok(())
}
/// Two levels: `content/ab/abcd…`.
fn folder_size(folder: &Path) -> Result<u64> {
let mut total = 0;
for shard in fs::read_dir(folder).map_err(|err| disk("reading the originals", err))? {
let shard = shard.map_err(|err| disk("reading the originals", err))?;
for file in fs::read_dir(shard.path()).map_err(|err| disk("reading the originals", err))? {
let meta = file
.and_then(|file| file.metadata())
.map_err(|err| disk("reading the originals", err))?;
total += meta.len();
}
}
Ok(total)
}
fn disk(step: &str, err: io::Error) -> Error {
Error::Store(format!("{step}: {err}"))
}
+289
View File
@@ -0,0 +1,289 @@
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use html5ever::{
Attribute, LocalName, Namespace, ParseOpts, QualName, local_name, parse_document,
tendril::{StrTendril, TendrilSink},
tree_builder::{ElemName, ElementFlags, NodeOrText, QuirksMode, TreeBuilderOpts, TreeSink},
};
/// Deeper trees stall html5ever.
const DEPTH: usize = 512;
const CHUNK: usize = 4096;
/// Visible HTML text, and whether it stopped short.
pub(super) fn text(html: &str) -> (String, bool) {
let opts = ParseOpts {
tree_builder: TreeBuilderOpts {
// Mail never runs scripts.
scripting_enabled: false,
..Default::default()
},
..Default::default()
};
let mut parser = parse_document(Tree::default(), opts);
let mut rest = html;
let mut short = false;
while !rest.is_empty() {
if parser.tokenizer.sink.sink.deep.get() {
short = true;
break;
}
let mut cut = rest.len().min(CHUNK);
while !rest.is_char_boundary(cut) {
cut += 1;
}
let (head, tail) = rest.split_at(cut);
parser.process(StrTendril::from_slice(head));
rest = tail;
}
(parser.finish().text(), short)
}
enum Data {
Document,
Element { name: QualName, point: bool },
Text(String),
Other,
}
struct Node {
parent: Option<usize>,
children: Vec<usize>,
data: Data,
}
/// The tree html5ever's builder makes.
struct Tree {
nodes: RefCell<Vec<Node>>,
/// An element went past `DEPTH`.
deep: Cell<bool>,
}
impl Default for Tree {
fn default() -> Self {
let document = Node {
parent: None,
children: Vec::new(),
data: Data::Document,
};
Tree {
nodes: RefCell::new(vec![document]),
deep: Cell::new(false),
}
}
}
#[derive(Debug)]
pub(super) struct Name(QualName);
impl ElemName for Name {
fn ns(&self) -> &Namespace {
&self.0.ns
}
fn local_name(&self) -> &LocalName {
&self.0.local
}
}
impl Tree {
fn add(&self, data: Data) -> usize {
let mut nodes = self.nodes.borrow_mut();
nodes.push(Node {
parent: None,
children: Vec::new(),
data,
});
nodes.len() - 1
}
fn detach(&self, node: usize) {
let mut nodes = self.nodes.borrow_mut();
if let Some(parent) = nodes[node].parent.take() {
nodes[parent].children.retain(|&child| child != node);
}
}
/// Inserts a child at index `at`.
fn insert(&self, parent: usize, at: usize, child: NodeOrText<usize>) {
let node = match child {
NodeOrText::AppendText(text) => {
let mut nodes = self.nodes.borrow_mut();
let before = at.checked_sub(1).map(|i| nodes[parent].children[i]);
if let Some(Data::Text(held)) = before.map(|i| &mut nodes[i].data) {
held.push_str(&text);
return;
}
drop(nodes);
self.add(Data::Text(text.to_string()))
}
NodeOrText::AppendNode(node) => {
self.detach(node);
node
}
};
let mut nodes = self.nodes.borrow_mut();
let at = at.min(nodes[parent].children.len());
nodes[parent].children.insert(at, node);
nodes[node].parent = Some(parent);
if matches!(nodes[node].data, Data::Element { .. }) {
let mut up = Some(parent);
let mut depth = 0;
while let Some(next) = up.filter(|_| depth <= DEPTH) {
depth += 1;
up = nodes[next].parent;
}
if depth > DEPTH {
self.deep.set(true);
}
}
}
/// The visible text, read without recursion.
fn text(&self) -> String {
let nodes = self.nodes.borrow();
let mut out = String::new();
let mut stack = vec![0];
while let Some(at) = stack.pop() {
match &nodes[at].data {
Data::Text(text) => out.push_str(text),
Data::Element { name, .. } if hidden(&name.local) => out.push(' '),
Data::Element { .. } | Data::Document => {
// Tags separate words.
out.push(' ');
stack.extend(nodes[at].children.iter().rev());
}
Data::Other => {}
}
}
out
}
}
/// Not drawn, per the HTML rendering rules.
fn hidden(name: &LocalName) -> bool {
matches!(
*name,
local_name!("area")
| local_name!("base")
| local_name!("basefont")
| local_name!("datalist")
| local_name!("head")
| local_name!("iframe")
| local_name!("link")
| local_name!("meta")
| local_name!("noembed")
| local_name!("noframes")
| local_name!("param")
| local_name!("rp")
| local_name!("script")
| local_name!("style")
| local_name!("template")
| local_name!("title")
)
}
impl TreeSink for Tree {
type Handle = usize;
type Output = Self;
type ElemName<'a> = Name;
fn finish(self) -> Self {
self
}
fn parse_error(&self, _msg: Cow<'static, str>) {}
fn get_document(&self) -> usize {
0
}
fn elem_name(&self, target: &usize) -> Name {
match &self.nodes.borrow()[*target].data {
Data::Element { name, .. } => Name(name.clone()),
_ => unreachable!("html5ever asked a non-element for its name"),
}
}
fn create_element(&self, name: QualName, _: Vec<Attribute>, flags: ElementFlags) -> usize {
let point = flags.mathml_annotation_xml_integration_point;
let node = self.add(Data::Element { name, point });
if flags.template {
// Template contents stay out of the tree.
self.add(Data::Other);
}
node
}
fn create_comment(&self, _text: StrTendril) -> usize {
self.add(Data::Other)
}
fn create_pi(&self, _target: StrTendril, _data: StrTendril) -> usize {
self.add(Data::Other)
}
fn append(&self, parent: &usize, child: NodeOrText<usize>) {
let end = self.nodes.borrow()[*parent].children.len();
self.insert(*parent, end, child);
}
fn append_based_on_parent_node(
&self,
element: &usize,
prev_element: &usize,
child: NodeOrText<usize>,
) {
if self.nodes.borrow()[*element].parent.is_some() {
self.append_before_sibling(element, child);
} else {
self.append(prev_element, child);
}
}
fn append_doctype_to_document(&self, _: StrTendril, _: StrTendril, _: StrTendril) {}
fn get_template_contents(&self, target: &usize) -> usize {
target + 1
}
fn same_node(&self, x: &usize, y: &usize) -> bool {
x == y
}
fn set_quirks_mode(&self, _mode: QuirksMode) {}
fn append_before_sibling(&self, sibling: &usize, child: NodeOrText<usize>) {
let (parent, at) = {
let nodes = self.nodes.borrow();
let parent = nodes[*sibling]
.parent
.expect("html5ever names a sibling with a parent");
let at = nodes[parent].children.iter().position(|c| c == sibling);
(parent, at.expect("a sibling among its parent's children"))
};
self.insert(parent, at, child);
}
fn add_attrs_if_missing(&self, _target: &usize, _attrs: Vec<Attribute>) {}
fn remove_from_parent(&self, target: &usize) {
self.detach(*target);
}
fn reparent_children(&self, node: &usize, new_parent: &usize) {
let children = std::mem::take(&mut self.nodes.borrow_mut()[*node].children);
for child in children {
self.nodes.borrow_mut()[child].parent = None;
self.append(new_parent, NodeOrText::AppendNode(child));
}
}
fn is_mathml_annotation_xml_integration_point(&self, handle: &usize) -> bool {
matches!(
self.nodes.borrow()[*handle].data,
Data::Element { point: true, .. }
)
}
}
@@ -0,0 +1,326 @@
use std::{fs, io::ErrorKind, path::Path};
use rusqlite::{Connection, OptionalExtension, Row, ToSql, Transaction, params};
use sha2::{Digest, Sha256};
use super::{CONTENT, MailboxId, MessageId, Store, disk, search};
use crate::{Error, Mail, Mailbox, Result, read};
/// RFC 3501 §2.3.1.1: identity is mailbox, UIDVALIDITY and UID.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Key {
Imap {
uidvalidity: u32,
uid: u32,
},
/// POP3 has one mailbox and UIDL names.
Pop {
uidl: String,
},
}
/// What a sync brought down.
pub enum Fetched<'a> {
Headers(&'a [u8]),
Whole(&'a [u8]),
}
/// A message as indexed; the original is read apart.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stored {
pub id: MessageId,
pub mailbox: MailboxId,
pub key: Key,
pub flags: Vec<String>,
pub message_id: Option<String>,
pub in_reply_to: Vec<String>,
pub references: Vec<String>,
pub subject: Option<String>,
pub from: Vec<Mailbox>,
pub to: Vec<Mailbox>,
pub cc: Vec<Mailbox>,
pub date: Option<i64>,
/// None until the whole message is here.
pub attachments: Option<u32>,
pub whole: bool,
}
const COLUMNS: &str = "id, mailbox, uidvalidity, uid, uidl, message_id, in_reply_to, refs, \
subject, sender, recipients, copies, date, attachments, content";
impl Store {
pub fn find(&self, mailbox: MailboxId, key: &Key) -> Result<Option<MessageId>> {
let found = match key {
Key::Imap { uidvalidity, uid } => self.conn.query_row(
"SELECT id FROM messages WHERE mailbox = ?1 AND uidvalidity = ?2 AND uid = ?3",
params![mailbox.0, uidvalidity, uid],
|row| row.get(0),
),
Key::Pop { uidl } => self.conn.query_row(
"SELECT id FROM messages WHERE mailbox = ?1 AND uidl = ?2",
params![mailbox.0, uidl],
|row| row.get(0),
),
};
Ok(found.optional()?.map(MessageId))
}
/// One key, one message; headers again only set flags.
pub fn put(
&mut self,
mailbox: MailboxId,
key: &Key,
flags: &[&str],
fetched: Fetched,
) -> Result<MessageId> {
self.writable()?;
let existing = self.find(mailbox, key)?;
let bytes = match (fetched, existing) {
(Fetched::Headers(_), Some(id)) => {
self.set_flags(id, flags)?;
return Ok(id);
}
(Fetched::Headers(bytes), None) => {
let mail = read(bytes)?;
return self.write(mailbox, key, flags, &mail, None, None);
}
(Fetched::Whole(bytes), _) => bytes,
};
let mail = read(bytes)?;
let (content, made) = self.keep(bytes)?;
let written = self.write(mailbox, key, flags, &mail, Some(&content), existing);
if written.is_err()
&& made
&& let Err(gone) = drop_unused(&self.conn, &self.dir, &content)
{
log::error!("mail: an unused original stays after a failed write: {gone}");
}
written
}
fn write(
&mut self,
mailbox: MailboxId,
key: &Key,
flags: &[&str],
mail: &Mail,
content: Option<&str>,
existing: Option<MessageId>,
) -> Result<MessageId> {
let (uidvalidity, uid, uidl) = match key {
Key::Imap { uidvalidity, uid } => (Some(*uidvalidity), Some(*uid), None),
Key::Pop { uidl } => (None, None, Some(uidl.as_str())),
};
let attachments = content.map(|_| mail.attachments.len() as u32);
let json = [
serde_json::to_string(&mail.in_reply_to)?,
serde_json::to_string(&mail.references)?,
serde_json::to_string(&mail.from)?,
serde_json::to_string(&mail.to)?,
serde_json::to_string(&mail.cc)?,
];
let mut values: Vec<&dyn ToSql> = vec![
&mail.message_id,
&json[0],
&json[1],
&mail.subject,
&json[2],
&json[3],
&json[4],
&mail.date,
&attachments,
&content,
];
let tx = self.conn.transaction()?;
let mut old: Option<String> = None;
let id = match existing {
Some(id) => {
old = tx.query_row(
"SELECT content FROM messages WHERE id = ?1",
[id.0],
|row| row.get(0),
)?;
values.push(&id.0);
tx.execute(
"UPDATE messages SET message_id = ?1, in_reply_to = ?2, refs = ?3,
subject = ?4, sender = ?5, recipients = ?6, copies = ?7, date = ?8,
attachments = ?9, content = ?10 WHERE id = ?11",
values.as_slice(),
)?;
id
}
None => {
values.extend::<[&dyn ToSql; 4]>([&mailbox.0, &uidvalidity, &uid, &uidl]);
tx.execute(
"INSERT INTO messages (message_id, in_reply_to, refs, subject, sender,
recipients, copies, date, attachments, content, mailbox, uidvalidity,
uid, uidl) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12,
?13, ?14)",
values.as_slice(),
)?;
MessageId(tx.last_insert_rowid())
}
};
replace_flags(&tx, id, flags)?;
search::index(&tx, id, mail, content.is_some())?;
if let Some(old) = old.filter(|old| Some(old.as_str()) != content) {
drop_unused(&tx, &self.dir, &old)?;
}
tx.commit()?;
Ok(id)
}
pub fn set_flags(&mut self, id: MessageId, flags: &[&str]) -> Result<()> {
self.writable()?;
self.content(id)?;
let tx = self.conn.transaction()?;
replace_flags(&tx, id, flags)?;
tx.commit()?;
Ok(())
}
pub fn get(&self, id: MessageId) -> Result<Stored> {
let mut stored = self.conn.query_row(
&format!("SELECT {COLUMNS} FROM messages WHERE id = ?1"),
[id.0],
|found| Ok(row(found)),
)??;
let mut query = self
.conn
.prepare("SELECT flag FROM flags WHERE message = ?1 ORDER BY flag")?;
stored.flags = query
.query_map([id.0], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?;
Ok(stored)
}
/// The original, checked against its hash; None for headers only.
pub fn original(&self, id: MessageId) -> Result<Option<Vec<u8>>> {
self.content(id)?
.map(|hash| load_at(&self.dir, &hash))
.transpose()
}
pub fn remove(&mut self, id: MessageId) -> Result<()> {
self.writable()?;
let content = self.content(id)?;
let tx = self.conn.transaction()?;
tx.execute("DELETE FROM messages WHERE id = ?1", [id.0])?;
if let Some(hash) = content {
drop_unused(&tx, &self.dir, &hash)?;
}
tx.commit()?;
Ok(())
}
fn content(&self, id: MessageId) -> Result<Option<String>> {
self.conn
.query_row(
"SELECT content FROM messages WHERE id = ?1",
[id.0],
|row| row.get(0),
)
.optional()?
.ok_or_else(|| Error::Store(format!("no message {}", id.0)))
}
/// The hash, and whether the file is new.
fn keep(&self, bytes: &[u8]) -> Result<(String, bool)> {
let hash = hex(&Sha256::digest(bytes));
let path = self.dir.join(CONTENT).join(&hash[..2]).join(&hash);
let made = match fs::read(&path) {
Ok(held) if hex(&Sha256::digest(&held)) == hash => return Ok((hash, false)),
Ok(_) => {
log::warn!("mail: original {hash} was damaged; rewritten from the server copy");
false
}
Err(err) if err.kind() == ErrorKind::NotFound => true,
Err(err) => return Err(disk("checking an original", err)),
};
let shard = path.parent().expect("a shard folder");
fs::create_dir_all(shard).map_err(|err| disk("storing an original", err))?;
let staged = shard.join(format!(".{hash}.part"));
if let Err(err) = fs::write(&staged, bytes).and_then(|()| fs::rename(&staged, &path)) {
return Err(match fs::remove_file(&staged) {
Ok(()) => disk("storing an original", err),
Err(gone) if gone.kind() == ErrorKind::NotFound => disk("storing an original", err),
Err(left) => Error::Store(format!(
"storing an original: {err}; the staged copy stayed: {left}"
)),
});
}
Ok((hash, made))
}
}
/// Deletes the file once no row names it; runs before commit.
fn drop_unused(conn: &Connection, dir: &Path, hash: &str) -> Result<()> {
let used: bool = conn.query_row(
"SELECT EXISTS (SELECT 1 FROM messages WHERE content = ?1)",
[hash],
|row| row.get(0),
)?;
if used {
return Ok(());
}
let path = dir.join(CONTENT).join(&hash[..2]).join(hash);
match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == ErrorKind::NotFound => {
log::warn!("mail: original {hash} was already gone");
Ok(())
}
Err(err) => Err(disk("deleting an original", err)),
}
}
fn replace_flags(tx: &Transaction, id: MessageId, flags: &[&str]) -> Result<()> {
tx.execute("DELETE FROM flags WHERE message = ?1", [id.0])?;
for flag in flags {
tx.execute(
"INSERT OR IGNORE INTO flags (message, flag) VALUES (?1, ?2)",
params![id.0, flag],
)?;
}
Ok(())
}
fn row(row: &Row) -> Result<Stored> {
let key = match row.get::<_, Option<String>>(4)? {
Some(uidl) => Key::Pop { uidl },
None => Key::Imap {
uidvalidity: row.get(2)?,
uid: row.get(3)?,
},
};
let json = |at: usize| -> Result<String> { Ok(row.get(at)?) };
Ok(Stored {
id: MessageId(row.get(0)?),
mailbox: MailboxId(row.get(1)?),
key,
flags: Vec::new(),
message_id: row.get(5)?,
in_reply_to: serde_json::from_str(&json(6)?)?,
references: serde_json::from_str(&json(7)?)?,
subject: row.get(8)?,
from: serde_json::from_str(&json(9)?)?,
to: serde_json::from_str(&json(10)?)?,
cc: serde_json::from_str(&json(11)?)?,
date: row.get(12)?,
attachments: row.get(13)?,
whole: row.get::<_, Option<String>>(14)?.is_some(),
})
}
pub(super) fn load_at(dir: &Path, hash: &str) -> Result<Vec<u8>> {
let path = dir.join(CONTENT).join(&hash[..2]).join(hash);
let bytes = fs::read(&path).map_err(|err| disk("reading an original", err))?;
if hex(&Sha256::digest(&bytes)) != hash {
return Err(Error::Store(format!("original {hash} is damaged")));
}
Ok(bytes)
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}
@@ -0,0 +1,51 @@
/// Step `n` upgrades version `n`.
pub(super) const STEPS: &[&str] = &[V1];
const V1: &str = "
CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
address TEXT NOT NULL UNIQUE
);
CREATE TABLE mailboxes (
id INTEGER PRIMARY KEY,
account INTEGER NOT NULL REFERENCES accounts ON DELETE CASCADE,
name TEXT NOT NULL,
UNIQUE (account, name)
);
CREATE TABLE messages (
id INTEGER PRIMARY KEY,
mailbox INTEGER NOT NULL REFERENCES mailboxes ON DELETE CASCADE,
uidvalidity INTEGER,
uid INTEGER,
uidl TEXT,
message_id TEXT,
in_reply_to TEXT NOT NULL,
refs TEXT NOT NULL,
subject TEXT,
sender TEXT NOT NULL,
recipients TEXT NOT NULL,
copies TEXT NOT NULL,
date INTEGER,
attachments INTEGER,
content TEXT,
CHECK ((uid IS NULL) = (uidvalidity IS NULL) AND (uid IS NULL) <> (uidl IS NULL))
);
CREATE UNIQUE INDEX messages_imap ON messages (mailbox, uidvalidity, uid)
WHERE uid IS NOT NULL;
CREATE UNIQUE INDEX messages_pop ON messages (mailbox, uidl) WHERE uidl IS NOT NULL;
CREATE INDEX messages_thread ON messages (message_id);
CREATE INDEX messages_content ON messages (content);
CREATE TABLE flags (
message INTEGER NOT NULL REFERENCES messages ON DELETE CASCADE,
flag TEXT NOT NULL,
PRIMARY KEY (message, flag)
) WITHOUT ROWID;
CREATE INDEX flags_by_flag ON flags (flag, message);
CREATE VIRTUAL TABLE search USING fts5(
subject, people, body, files,
content = '', contentless_delete = 1, tokenize = 'trigram'
);
CREATE TRIGGER messages_gone AFTER DELETE ON messages BEGIN
DELETE FROM search WHERE rowid = old.id;
END;
";
+134
View File
@@ -0,0 +1,134 @@
use rusqlite::{Transaction, params};
use super::{MessageId, Store, html, messages::load_at};
use crate::{Mail, Mailbox, Result, read};
/// Replaces the message's row in the full-text index.
pub(super) fn index(tx: &Transaction, id: MessageId, mail: &Mail, whole: bool) -> Result<()> {
let people = people([&mail.from, &mail.to, &mail.cc]);
let (body, files) = if whole {
contents(id, mail)
} else {
Default::default()
};
put(tx, id, mail.subject.as_deref(), &people, &body, &files)
}
fn put(
tx: &Transaction,
id: MessageId,
subject: Option<&str>,
people: &str,
body: &str,
files: &str,
) -> Result<()> {
tx.execute("DELETE FROM search WHERE rowid = ?1", [id.0])?;
tx.execute(
"INSERT INTO search (rowid, subject, people, body, files) VALUES (?1, ?2, ?3, ?4, ?5)",
params![id.0, subject, people, body, files],
)?;
Ok(())
}
impl Store {
/// Rebuilt from the index rows and the originals.
pub fn rebuild_search(&mut self) -> Result<usize> {
self.writable()?;
let ids: Vec<i64> = {
let mut query = self.conn.prepare("SELECT id FROM messages")?;
query
.query_map([], |row| row.get(0))?
.collect::<rusqlite::Result<_>>()?
};
let tx = self.conn.transaction()?;
// A damaged index may not delete.
let made: String = tx.query_row(
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'search'",
[],
|row| row.get(0),
)?;
tx.execute_batch(&format!("DROP TABLE search; {made};"))?;
for &id in &ids {
let (subject, from, to, cc, content): (
Option<String>,
String,
String,
String,
Option<String>,
) = tx.query_row(
"SELECT subject, sender, recipients, copies, content FROM messages
WHERE id = ?1",
[id],
|row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
))
},
)?;
let lists: [Vec<Mailbox>; 3] = [
serde_json::from_str(&from)?,
serde_json::from_str(&to)?,
serde_json::from_str(&cc)?,
];
let (body, files) = match content {
Some(hash) => contents(MessageId(id), &read(&load_at(&self.dir, &hash)?)?),
None => Default::default(),
};
let people = people([&lists[0], &lists[1], &lists[2]]);
put(
&tx,
MessageId(id),
subject.as_deref(),
&people,
&body,
&files,
)?;
}
let count = ids.len();
tx.commit()?;
log::info!("mail: search index rebuilt for {count} messages");
Ok(count)
}
}
fn people(lists: [&[Mailbox]; 3]) -> String {
let mut out = String::new();
for person in lists.into_iter().flatten() {
if let Some(name) = &person.name {
out.push_str(name);
out.push(' ');
}
out.push_str(&person.email);
out.push('\n');
}
out
}
/// The body text and the attachment names.
fn contents(id: MessageId, mail: &Mail) -> (String, String) {
let body = match (&mail.text, &mail.html) {
(Some(text), _) => text.clone(),
(None, Some(html)) => {
let (text, short) = html::text(html);
if short {
log::warn!(
"mail: message {} nests HTML too deep; its later text is not indexed",
id.0
);
}
text
}
(None, None) => String::new(),
};
let files = mail
.attachments
.iter()
.filter_map(|part| part.name.as_deref())
.collect::<Vec<_>>()
.join("\n");
(body, files)
}
+96
View File
@@ -0,0 +1,96 @@
use std::fs;
use rusqlite::Connection;
use super::{BACKUPS, DB, open, schema::STEPS};
use crate::Error;
const ADD: &str = "ALTER TABLE accounts ADD COLUMN nick TEXT";
const BROKEN: &str = "ALTER TABLE nowhere ADD COLUMN nick TEXT";
fn version(path: &std::path::Path) -> i64 {
Connection::open(path)
.unwrap()
.query_row("PRAGMA user_version", [], |row| row.get(0))
.unwrap()
}
fn backups(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
match fs::read_dir(dir.join(BACKUPS)) {
Ok(entries) => entries.map(|entry| entry.unwrap().path()).collect(),
Err(_) => Vec::new(),
}
}
#[test]
fn a_new_store_is_at_the_last_schema() {
let dir = tempfile::tempdir().unwrap();
let store = open(dir.path(), STEPS).unwrap();
assert_eq!(store.read_only(), None);
assert_eq!(version(&dir.path().join(DB)), STEPS.len() as i64);
assert!(backups(dir.path()).is_empty());
}
#[test]
fn an_upgrade_backs_up_first() {
let dir = tempfile::tempdir().unwrap();
open(dir.path(), &[STEPS[0]])
.unwrap()
.add_account("ann@example.com")
.unwrap();
let store = open(dir.path(), &[STEPS[0], ADD]).unwrap();
assert_eq!(store.read_only(), None);
assert_eq!(version(&dir.path().join(DB)), 2);
let [backup] = backups(dir.path()).try_into().unwrap();
assert_eq!(version(&backup), 1);
let accounts: i64 = Connection::open(&backup)
.unwrap()
.query_row("SELECT count(*) FROM accounts", [], |row| row.get(0))
.unwrap();
assert_eq!(accounts, 1);
}
#[test]
fn a_failed_upgrade_keeps_the_data_and_refuses_writes() {
let dir = tempfile::tempdir().unwrap();
open(dir.path(), &[STEPS[0]])
.unwrap()
.add_account("ann@example.com")
.unwrap();
let store = open(dir.path(), &[STEPS[0], ADD, BROKEN]).unwrap();
let reason = store.read_only().unwrap();
assert!(reason.contains("v1 to v3"), "{reason}");
assert_eq!(store.accounts().unwrap()[0].1, "ann@example.com");
let err = store.add_account("bo@example.com").unwrap_err();
assert!(matches!(err, Error::ReadOnly(_)), "{err}");
drop(store);
assert_eq!(version(&dir.path().join(DB)), 1);
assert_eq!(backups(dir.path()).len(), 1);
let partial = Connection::open(dir.path().join(DB))
.unwrap()
.prepare("SELECT nick FROM accounts")
.map(drop);
assert!(partial.is_err(), "the first step was not rolled back");
}
#[test]
fn a_newer_schema_is_read_only() {
let dir = tempfile::tempdir().unwrap();
drop(open(dir.path(), &[STEPS[0], ADD]).unwrap());
let store = open(dir.path(), &[STEPS[0]]).unwrap();
let reason = store.read_only().unwrap();
assert!(reason.contains("newer"), "{reason}");
assert!(store.accounts().unwrap().is_empty());
}
#[test]
fn no_backup_means_no_upgrade() {
let dir = tempfile::tempdir().unwrap();
drop(open(dir.path(), &[STEPS[0]]).unwrap());
fs::write(dir.path().join(BACKUPS), b"a file in the way").unwrap();
let store = open(dir.path(), &[STEPS[0], ADD]).unwrap();
let reason = store.read_only().unwrap();
assert!(reason.contains("no backup"), "{reason}");
drop(store);
assert_eq!(version(&dir.path().join(DB)), 1);
}
+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());
}