diff --git a/Cargo.lock b/Cargo.lock index 6f04e98..15076bb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1981,6 +1981,18 @@ dependencies = [ "bitflags", ] +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + [[package]] name = "regex-automata" version = "0.4.18" @@ -2691,6 +2703,7 @@ dependencies = [ "mail-parser 0.11.9", "mail-send", "rand", + "regex", "rustls 0.23.45", "rustls-native-certs", "serde", diff --git a/Cargo.toml b/Cargo.toml index c1204fe..4c0c953 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,6 +23,7 @@ mail-send = "0.4" rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } tokio-rustls = { version = "0.26", default-features = false } rustls-native-certs = "0.8" +regex = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/migrations/0006_tags_rules_threading.sql b/migrations/0006_tags_rules_threading.sql new file mode 100644 index 0000000..bc3e56d --- /dev/null +++ b/migrations/0006_tags_rules_threading.sql @@ -0,0 +1,36 @@ +-- Phase 5: tags, rules, threading (server-architecture-spec.md §3.5, §3.6). + +-- Soft delete. A rule runs on every incoming message, so one with an +-- over-broad pattern must not be able to destroy mail: "delete" moves it to +-- Trash, where it can be restored. +ALTER TABLE messages ADD COLUMN deleted_at TIMESTAMPTZ; + +-- Subject with Re:/Fwd:/[list] prefixes stripped, for the threading +-- fallback that groups replies whose reference headers were removed. +ALTER TABLE messages ADD COLUMN subject_norm TEXT; +CREATE INDEX messages_account_subject_norm_idx ON messages (account_id, subject_norm); + +-- Threading looks up messages by ID and by overlapping References. +CREATE INDEX messages_account_message_id_idx ON messages (account_id, message_id); +CREATE INDEX messages_references_gin_idx ON messages USING GIN (references_); + +-- Normalise any Message-IDs stored bracketed before ingest normalised them +-- (IMAP ENVELOPE returns them bracketed, mail-parser bare). Threading +-- compares these for equality, so both forms must not coexist. +UPDATE messages SET + message_id = btrim(message_id, '<> '), + in_reply_to = btrim(in_reply_to, '<> '), + references_ = ARRAY(SELECT btrim(r, '<> ') FROM unnest(references_) AS r); + +-- System folders are found by role rather than name, so renaming the +-- Archive folder doesn't break archiving. +ALTER TABLE folders ADD COLUMN role TEXT CHECK (role IN ('archive')); +CREATE UNIQUE INDEX folders_user_role_idx ON folders (user_id, role) WHERE role IS NOT NULL; + +-- Tag colours are rendered into the UI, so only plain hex is allowed. +ALTER TABLE tags ADD CONSTRAINT tags_color_hex CHECK (color IS NULL OR color ~ '^#[0-9a-fA-F]{6}$'); + +-- Bumped whenever the threading algorithm changes. An account below the +-- current version has its existing mail re-threaded once, on the next +-- sync start. +ALTER TABLE sync_state ADD COLUMN threading_version INTEGER NOT NULL DEFAULT 0; diff --git a/src/api/folders.rs b/src/api/folders.rs index 5a1a417..169bb9b 100644 --- a/src/api/folders.rs +++ b/src/api/folders.rs @@ -14,11 +14,12 @@ pub async fn list( State(state): State, user: CurrentUser, ) -> ApiResult>> { - let folders: Vec = - sqlx::query_as("SELECT * FROM folders WHERE user_id = $1 ORDER BY name") - .bind(user.user_id) - .fetch_all(&state.pool) - .await?; + let folders: Vec = sqlx::query_as( + "SELECT * FROM folders WHERE user_id = $1 ORDER BY role IS NULL, lower(name)", + ) + .bind(user.user_id) + .fetch_all(&state.pool) + .await?; Ok(Json(folders)) } @@ -35,3 +36,53 @@ pub async fn create( .await?; Ok(Json(folder)) } + +#[derive(Deserialize)] +pub struct RenameFolderRequest { + pub name: String, +} + +pub async fn rename( + State(state): State, + user: CurrentUser, + axum::extract::Path(id): axum::extract::Path, + Json(req): Json, +) -> ApiResult> { + let name = req.name.trim(); + if name.is_empty() || name.len() > 100 { + return Err(crate::error::ApiError::BadRequest( + "folder name must be 1–100 characters".into(), + )); + } + let folder: Option = + sqlx::query_as("UPDATE folders SET name = $3 WHERE id = $1 AND user_id = $2 RETURNING *") + .bind(id) + .bind(user.user_id) + .bind(name) + .fetch_optional(&state.pool) + .await?; + folder.map(Json).ok_or(crate::error::ApiError::NotFound) +} + +/// Messages in a deleted folder go back to the inbox (FK ON DELETE SET +/// NULL) rather than disappearing. The Archive folder can be renamed but +/// not deleted, since archiving needs somewhere to put things. +pub async fn delete( + State(state): State, + user: CurrentUser, + axum::extract::Path(id): axum::extract::Path, +) -> ApiResult> { + let deleted = + sqlx::query("DELETE FROM folders WHERE id = $1 AND user_id = $2 AND role IS NULL") + .bind(id) + .bind(user.user_id) + .execute(&state.pool) + .await? + .rows_affected(); + if deleted == 0 { + return Err(crate::error::ApiError::BadRequest( + "folder not found, or it's the Archive folder, which can't be deleted".into(), + )); + } + Ok(Json(serde_json::json!({ "ok": true }))) +} diff --git a/src/api/mod.rs b/src/api/mod.rs index 7d44afc..9b422ba 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -6,7 +6,9 @@ pub mod messages; pub mod middleware; pub mod outbox; pub mod router; +pub mod rules; pub mod state; +pub mod tags; pub mod threads; pub use router::build; diff --git a/src/api/router.rs b/src/api/router.rs index a7a896e..a64b4dd 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -1,5 +1,5 @@ use crate::api::state::AppState; -use crate::api::{accounts, auth, events, folders, messages, outbox, threads}; +use crate::api::{accounts, auth, events, folders, messages, outbox, rules, tags, threads}; use axum::routing::{delete, get, post, put}; use axum::Router; use tower_http::cors::CorsLayer; @@ -12,11 +12,21 @@ pub fn build(state: AppState) -> Router { .route("/api/accounts", get(accounts::list).post(accounts::create)) .route("/api/accounts/:id", delete(accounts::delete)) .route("/api/folders", get(folders::list).post(folders::create)) + .route( + "/api/folders/:id", + put(folders::rename).delete(folders::delete), + ) + .route("/api/tags", get(tags::list).post(tags::create)) + .route("/api/tags/:id", put(tags::update).delete(tags::delete)) + .route("/api/rules", get(rules::list).post(rules::create)) + .route("/api/rules/reorder", post(rules::reorder)) + .route("/api/rules/:id", put(rules::update).delete(rules::delete)) .route("/api/messages", get(messages::list)) .route("/api/messages/:id", get(messages::get)) .route("/api/threads", get(threads::list)) .route("/api/threads/:id", get(messages::get_thread)) .route("/api/threads/:id/read", post(threads::mark_read)) + .route("/api/threads/:id/actions", post(threads::act)) .route("/api/outbox", get(outbox::list).post(outbox::create)) .route( "/api/outbox/:id", diff --git a/src/api/rules.rs b/src/api/rules.rs new file mode 100644 index 0000000..b05aef7 --- /dev/null +++ b/src/api/rules.rs @@ -0,0 +1,172 @@ +//! CRUD for rules. The engine itself lives in `crate::rules`; this only +//! validates and stores the structured JSON (server-architecture-spec.md +//! §3.5). + +use crate::api::middleware::CurrentUser; +use crate::api::state::AppState; +use crate::error::{ApiError, ApiResult}; +use crate::rules::{self, Action, Conditions}; +use axum::{ + extract::{Path, State}, + Json, +}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use sqlx::types::Json as SqlJson; +use uuid::Uuid; + +#[derive(Serialize, sqlx::FromRow)] +pub struct Rule { + pub id: Uuid, + pub name: String, + pub conditions: SqlJson, + pub actions: SqlJson>, + pub enabled: bool, + pub priority: i32, + pub created_at: DateTime, +} + +#[derive(Deserialize)] +pub struct RuleRequest { + pub name: String, + pub conditions: Conditions, + pub actions: Vec, + #[serde(default = "enabled_default")] + pub enabled: bool, +} + +fn enabled_default() -> bool { + true +} + +#[derive(Deserialize)] +pub struct ReorderRequest { + /// Every rule id, in the new priority order. + pub ids: Vec, +} + +const RULE_COLUMNS: &str = "id, name, conditions, actions, enabled, priority, created_at"; + +async fn check(state: &AppState, user_id: Uuid, req: &RuleRequest) -> ApiResult<()> { + let name = req.name.trim(); + if name.is_empty() || name.len() > 100 { + return Err(ApiError::BadRequest( + "rule name must be 1–100 characters".into(), + )); + } + rules::validate(&req.conditions, &req.actions, true).map_err(ApiError::BadRequest)?; + rules::check_targets(&state.pool, user_id, &req.actions) + .await + .map_err(ApiError::BadRequest) +} + +pub async fn list(State(state): State, user: CurrentUser) -> ApiResult>> { + let rules = sqlx::query_as(&format!( + "SELECT {RULE_COLUMNS} FROM rules WHERE user_id = $1 ORDER BY priority, created_at" + )) + .bind(user.user_id) + .fetch_all(&state.pool) + .await?; + Ok(Json(rules)) +} + +/// New rules go to the bottom of the list, so adding one never changes what +/// the existing ones do. +pub async fn create( + State(state): State, + user: CurrentUser, + Json(req): Json, +) -> ApiResult> { + check(&state, user.user_id, &req).await?; + let rule = sqlx::query_as(&format!( + "INSERT INTO rules (user_id, name, conditions, actions, enabled, priority) \ + VALUES ($1, $2, $3, $4, $5, \ + COALESCE((SELECT MAX(priority) + 1 FROM rules WHERE user_id = $1), 0)) \ + RETURNING {RULE_COLUMNS}" + )) + .bind(user.user_id) + .bind(req.name.trim()) + .bind(SqlJson(&req.conditions)) + .bind(SqlJson(&req.actions)) + .bind(req.enabled) + .fetch_one(&state.pool) + .await?; + Ok(Json(rule)) +} + +pub async fn update( + State(state): State, + user: CurrentUser, + Path(id): Path, + Json(req): Json, +) -> ApiResult> { + check(&state, user.user_id, &req).await?; + let rule: Option = sqlx::query_as(&format!( + "UPDATE rules SET name = $3, conditions = $4, actions = $5, enabled = $6 \ + WHERE id = $1 AND user_id = $2 RETURNING {RULE_COLUMNS}" + )) + .bind(id) + .bind(user.user_id) + .bind(req.name.trim()) + .bind(SqlJson(&req.conditions)) + .bind(SqlJson(&req.actions)) + .bind(req.enabled) + .fetch_optional(&state.pool) + .await?; + rule.map(Json).ok_or(ApiError::NotFound) +} + +pub async fn delete( + State(state): State, + user: CurrentUser, + Path(id): Path, +) -> ApiResult> { + let deleted = sqlx::query("DELETE FROM rules WHERE id = $1 AND user_id = $2") + .bind(id) + .bind(user.user_id) + .execute(&state.pool) + .await? + .rows_affected(); + if deleted == 0 { + return Err(ApiError::NotFound); + } + Ok(Json(serde_json::json!({ "ok": true }))) +} + +/// Takes the complete new order rather than "move rule X up", so the +/// client can't leave two rules at the same priority and make evaluation +/// order depend on insertion time. +pub async fn reorder( + State(state): State, + user: CurrentUser, + Json(req): Json, +) -> ApiResult>> { + let mut tx = state.pool.begin().await?; + let mut existing: Vec = + sqlx::query_scalar("SELECT id FROM rules WHERE user_id = $1 FOR UPDATE") + .bind(user.user_id) + .fetch_all(&mut *tx) + .await?; + + let mut given = req.ids.clone(); + existing.sort(); + given.sort(); + if existing != given { + return Err(ApiError::BadRequest( + "reorder needs every one of your rule ids exactly once".into(), + )); + } + + sqlx::query( + "UPDATE rules SET priority = o.ord - 1 \ + FROM unnest($1::uuid[]) WITH ORDINALITY AS o(id, ord) \ + WHERE rules.id = o.id AND rules.user_id = $2", + ) + .bind(&req.ids) + .bind(user.user_id) + .execute(&mut *tx) + .await?; + tx.commit().await?; + + list(State(state), user).await +} diff --git a/src/api/tags.rs b/src/api/tags.rs new file mode 100644 index 0000000..1882ce7 --- /dev/null +++ b/src/api/tags.rs @@ -0,0 +1,117 @@ +use crate::api::middleware::CurrentUser; +use crate::api::state::AppState; +use crate::error::{ApiError, ApiResult}; +use crate::models::tag::Tag; +use axum::{ + extract::{Path, State}, + Json, +}; +use serde::Deserialize; +use uuid::Uuid; + +#[derive(Deserialize)] +pub struct TagRequest { + pub name: String, + pub color: Option, +} + +/// Colours are rendered into the UI's styles, so only `#rrggbb` is +/// accepted — nothing that could smuggle other CSS in. The database +/// enforces the same with a CHECK constraint. +fn validate(req: &TagRequest) -> ApiResult<(String, Option)> { + let name = req.name.trim(); + if name.is_empty() || name.len() > 64 { + return Err(ApiError::BadRequest( + "tag name must be 1–64 characters".into(), + )); + } + let color = match req.color.as_deref().map(str::trim) { + None | Some("") => None, + Some(c) + if c.len() == 7 + && c.starts_with('#') + && c[1..].chars().all(|ch| ch.is_ascii_hexdigit()) => + { + Some(c.to_lowercase()) + } + Some(c) => { + return Err(ApiError::BadRequest(format!( + "color must look like #rrggbb, got {c:?}" + ))) + } + }; + Ok((name.to_string(), color)) +} + +fn conflict(e: sqlx::Error) -> ApiError { + match e { + sqlx::Error::Database(db) if db.is_unique_violation() => { + ApiError::BadRequest("a tag with that name already exists".into()) + } + other => ApiError::Sqlx(other), + } +} + +pub async fn list(State(state): State, user: CurrentUser) -> ApiResult>> { + let tags = sqlx::query_as("SELECT * FROM tags WHERE user_id = $1 ORDER BY lower(name)") + .bind(user.user_id) + .fetch_all(&state.pool) + .await?; + Ok(Json(tags)) +} + +pub async fn create( + State(state): State, + user: CurrentUser, + Json(req): Json, +) -> ApiResult> { + let (name, color) = validate(&req)?; + let tag = + sqlx::query_as("INSERT INTO tags (user_id, name, color) VALUES ($1, $2, $3) RETURNING *") + .bind(user.user_id) + .bind(name) + .bind(color) + .fetch_one(&state.pool) + .await + .map_err(conflict)?; + Ok(Json(tag)) +} + +pub async fn update( + State(state): State, + user: CurrentUser, + Path(id): Path, + Json(req): Json, +) -> ApiResult> { + let (name, color) = validate(&req)?; + let tag: Option = sqlx::query_as( + "UPDATE tags SET name = $3, color = $4 WHERE id = $1 AND user_id = $2 RETURNING *", + ) + .bind(id) + .bind(user.user_id) + .bind(name) + .bind(color) + .fetch_optional(&state.pool) + .await + .map_err(conflict)?; + tag.map(Json).ok_or(ApiError::NotFound) +} + +/// Removes the tag from every message (cascade). Rules still naming it +/// become no-ops for that action rather than failing. +pub async fn delete( + State(state): State, + user: CurrentUser, + Path(id): Path, +) -> ApiResult> { + let deleted = sqlx::query("DELETE FROM tags WHERE id = $1 AND user_id = $2") + .bind(id) + .bind(user.user_id) + .execute(&state.pool) + .await? + .rows_affected(); + if deleted == 0 { + return Err(ApiError::NotFound); + } + Ok(Json(serde_json::json!({ "ok": true }))) +} diff --git a/src/api/threads.rs b/src/api/threads.rs index 8078753..1c2ff5b 100644 --- a/src/api/threads.rs +++ b/src/api/threads.rs @@ -1,27 +1,62 @@ //! Thread-grouped listing — one row per conversation, which is how both -//! clients render the inbox. +//! clients render a mailbox — plus actions on a whole thread. //! -//! This has to be grouped server-side: a thread's messages are spread +//! Grouping has to happen server-side: a thread's messages are spread //! through the flat message list by date, so a client grouping one page at a //! time would split threads across page boundaries and miscount unread. //! +//! A view selects which threads appear (a thread is in the inbox if *any* +//! of its messages is), but each row summarises the whole conversation. So +//! a reply arriving in an archived thread brings the thread back into the +//! inbox, while the row still shows every message in it. +//! //! Cursor is the thread's `last_message_at`, matching the cursor-based //! (not offset) approach in server-architecture-spec.md §4. use crate::api::middleware::CurrentUser; use crate::api::state::AppState; -use crate::error::ApiResult; +use crate::error::{ApiError, ApiResult}; +use crate::rules::{self, Action}; use axum::{ - extract::{Query, State}, + extract::{Path, Query, State}, Json, }; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use uuid::Uuid; +#[derive(Deserialize, Default, Clone, Copy, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum View { + /// Received mail not filed into any folder. + #[default] + Inbox, + All, + Sent, + Trash, + Folder, + Tag, +} + +impl View { + fn as_str(self) -> &'static str { + match self { + View::Inbox => "inbox", + View::All => "all", + View::Sent => "sent", + View::Trash => "trash", + View::Folder => "folder", + View::Tag => "tag", + } + } +} + #[derive(Deserialize)] pub struct ListThreadsQuery { + #[serde(default)] + pub view: View, pub folder_id: Option, + pub tag_id: Option, pub before: Option>, pub limit: Option, } @@ -36,6 +71,7 @@ pub struct ThreadSummary { pub message_count: i64, pub unread_count: i64, pub has_attachments: bool, + pub tag_ids: Vec, } #[derive(Serialize)] @@ -51,35 +87,72 @@ pub async fn list( ) -> ApiResult> { let limit = q.limit.unwrap_or(50).clamp(1, 200); let before = q.before.unwrap_or_else(Utc::now); + match q.view { + View::Folder if q.folder_id.is_none() => { + return Err(ApiError::BadRequest("view=folder needs folder_id".into())) + } + View::Tag if q.tag_id.is_none() => { + return Err(ApiError::BadRequest("view=tag needs tag_id".into())) + } + _ => {} + } - // Subject comes from the oldest message (the one that started the - // thread); sender and timestamp from the newest, which is what a list - // row should show. Unread is "no \Seen flag" — flags are stored in IMAP - // wire format, so the comparison is against the literal '\Seen'. + // Deleted messages are left out of every summary except Trash's, so a + // thread with one message deleted by a rule doesn't count it. let threads: Vec = sqlx::query_as( r#" + WITH mine AS ( + SELECT m.* FROM messages m + JOIN accounts a ON a.id = m.account_id + WHERE a.user_id = $1 + ), + selected AS ( + SELECT DISTINCT thread_id FROM mine v + WHERE CASE $2 + WHEN 'inbox' THEN v.deleted_at IS NULL AND v.folder_id IS NULL AND v.source = 'imap' + WHEN 'all' THEN v.deleted_at IS NULL + WHEN 'sent' THEN v.deleted_at IS NULL AND v.source = 'sent' + WHEN 'trash' THEN v.deleted_at IS NOT NULL + WHEN 'folder' THEN v.deleted_at IS NULL AND v.folder_id = $3 + WHEN 'tag' THEN v.deleted_at IS NULL AND EXISTS ( + SELECT 1 FROM message_tags mt WHERE mt.message_id = v.id AND mt.tag_id = $4) + END + ) SELECT m.thread_id, - (ARRAY_AGG(m.subject ORDER BY m.sent_at ASC NULLS LAST))[1] AS subject, + -- The root's subject when we have the root (a message that + -- replies to nothing), not merely the earliest-dated message: + -- replies can carry earlier Date headers than their parent, and + -- Date has one-second resolution, so ties are common. Arrival + -- order breaks the remaining ties deterministically. + (ARRAY_AGG(m.subject ORDER BY + (m.in_reply_to IS NOT NULL OR cardinality(m.references_) > 0), + m.sent_at ASC NULLS LAST, + m.created_at ASC))[1] AS subject, (ARRAY_AGG(COALESCE(NULLIF(m.from_name, ''), m.from_addr) ORDER BY m.sent_at DESC NULLS LAST))[1] AS last_from, MAX(m.sent_at) AS last_message_at, COUNT(*) AS message_count, COUNT(*) FILTER (WHERE NOT ('\Seen' = ANY(m.flags))) AS unread_count, - BOOL_OR(EXISTS (SELECT 1 FROM attachments att WHERE att.message_id = m.id)) - AS has_attachments - FROM messages m - JOIN accounts a ON a.id = m.account_id - WHERE a.user_id = $1 - AND ($2::uuid IS NULL OR m.folder_id = $2) + BOOL_OR(EXISTS (SELECT 1 FROM attachments att WHERE att.message_id = m.id)) AS has_attachments, + ARRAY( + SELECT DISTINCT mt.tag_id FROM message_tags mt + JOIN mine m2 ON m2.id = mt.message_id + WHERE m2.thread_id = m.thread_id AND m2.deleted_at IS NULL + ) AS tag_ids + FROM mine m + JOIN selected USING (thread_id) + WHERE ($2 = 'trash') = (m.deleted_at IS NOT NULL) GROUP BY m.thread_id - HAVING MAX(m.sent_at) < $3 + HAVING MAX(m.sent_at) < $5 ORDER BY last_message_at DESC - LIMIT $4 + LIMIT $6 "#, ) .bind(user.user_id) + .bind(q.view.as_str()) .bind(q.folder_id) + .bind(q.tag_id) .bind(before) .bind(limit) .fetch_all(&state.pool) @@ -93,25 +166,63 @@ pub async fn list( })) } +#[derive(Deserialize)] +pub struct ThreadActionsRequest { + pub actions: Vec, +} + +/// Applies actions to every message in a thread — the same action format and +/// code as rules, so "archive this conversation" and "a rule that +/// archives" can't drift apart. +pub async fn act( + State(state): State, + user: CurrentUser, + Path(thread_id): Path, + Json(req): Json, +) -> ApiResult> { + let no_conditions = rules::Conditions { + match_: rules::Match::All, + tests: vec![], + }; + rules::validate(&no_conditions, &req.actions, false).map_err(ApiError::BadRequest)?; + rules::check_targets(&state.pool, user.user_id, &req.actions) + .await + .map_err(ApiError::BadRequest)?; + + let ids: Vec = sqlx::query_scalar( + "SELECT m.id FROM messages m JOIN accounts a ON a.id = m.account_id \ + WHERE m.thread_id = $1 AND a.user_id = $2", + ) + .bind(thread_id) + .bind(user.user_id) + .fetch_all(&state.pool) + .await?; + if ids.is_empty() { + return Err(ApiError::NotFound); + } + + let mut tx = state.pool.begin().await?; + rules::apply_actions(&mut tx, user.user_id, &ids, &req.actions).await?; + tx.commit().await?; + + Ok(Json(serde_json::json!({ "messages": ids.len() }))) +} + /// Marks every message in a thread read. Local state only — sync is /// one-way (server-architecture-spec.md §2.1), so this never reaches the /// source IMAP server. pub async fn mark_read( - State(state): State, + state: State, user: CurrentUser, - axum::extract::Path(thread_id): axum::extract::Path, + thread_id: Path, ) -> ApiResult> { - let updated = sqlx::query( - r#"UPDATE messages m SET flags = array_append(m.flags, '\Seen') - FROM accounts a - WHERE a.id = m.account_id AND a.user_id = $1 AND m.thread_id = $2 - AND NOT ('\Seen' = ANY(m.flags))"#, + act( + state, + user, + thread_id, + Json(ThreadActionsRequest { + actions: vec![Action::MarkRead], + }), ) - .bind(user.user_id) - .bind(thread_id) - .execute(&state.pool) - .await? - .rows_affected(); - - Ok(Json(serde_json::json!({ "updated": updated }))) + .await } diff --git a/src/imap_sync/connection.rs b/src/imap_sync/connection.rs index fd446d4..b7fa66a 100644 --- a/src/imap_sync/connection.rs +++ b/src/imap_sync/connection.rs @@ -126,6 +126,7 @@ impl AccountSyncer { let server_uidvalidity = mailbox.uid_validity.map(|v| v as i64); self.reconcile_uidvalidity(server_uidvalidity).await?; + crate::threading::backfill_if_needed(&self.pool, self.account.id).await?; // Catch up on anything new, then keep going until told to stop. // `Session::idle()` consumes the session and hands back a `Handle`; @@ -387,6 +388,30 @@ impl AccountSyncer { .await?; } + // Threading and rules need the full headers (References isn't in + // ENVELOPE), so they run here rather than at header ingest — the + // message may be visible for the moment between the two. + crate::threading::assign( + &mut tx, + &crate::threading::ThreadInput { + account_id: self.account.id, + row_id: message_row_id, + message_id: parsed.message_id.as_deref(), + in_reply_to: parsed.in_reply_to.as_deref(), + references: &parsed.references, + subject: parsed.subject.as_deref(), + }, + ) + .await?; + + crate::rules::apply_rules( + &mut tx, + self.account.user_id, + message_row_id, + &crate::rules::Facts::from_parsed(&parsed), + ) + .await?; + tx.commit().await?; Ok(()) } diff --git a/src/imap_sync/parse.rs b/src/imap_sync/parse.rs index 07c7573..b606cff 100644 --- a/src/imap_sync/parse.rs +++ b/src/imap_sync/parse.rs @@ -47,6 +47,19 @@ pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result { }) .collect(); + let raw_bytes = message.raw_message(); + let headers = message + .headers() + .iter() + .filter_map(|h| { + let value = raw_bytes.get(h.offset_start as usize..h.offset_end as usize)?; + Some(( + h.name.as_str().to_lowercase(), + unfold(&String::from_utf8_lossy(value)), + )) + }) + .collect(); + Ok(ParsedMessage { message_id, in_reply_to, @@ -60,10 +73,18 @@ pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result { text_body, html_body, attachments, + headers, raw: raw.to_vec(), }) } +/// Joins a folded header (continuation lines start with whitespace) back +/// into one line, so a rule doesn't have to account for where a sender's +/// mailer chose to wrap it. +fn unfold(value: &str) -> String { + value.split_whitespace().collect::>().join(" ") +} + fn first_address(addr: &Address) -> Option<(Option, Option)> { addr.first().map(|a| { ( @@ -78,3 +99,36 @@ fn all_addresses(addr: &Address) -> Vec { .filter_map(|a| a.address().map(|s| s.to_string())) .collect() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exposes_unfolded_raw_headers_including_repeats() { + let raw = b"From: Bob \r\n\ +Received: from a\r\n\ +Received: from b\r\n\ +List-Id: Weekly digest\r\n \r\n\ +X-Spam-Score: 5.3\r\n\ +Subject: hi\r\n\ +\r\n\ +body\r\n"; + let p = parse_raw_message(raw).unwrap(); + let get = |n: &str| { + p.headers + .iter() + .filter(|(k, _)| k == n) + .map(|(_, v)| v.as_str()) + .collect::>() + }; + + assert_eq!( + get("list-id"), + vec!["Weekly digest "] + ); + assert_eq!(get("received"), vec!["from a", "from b"]); + assert_eq!(get("x-spam-score"), vec!["5.3"]); + assert_eq!(get("from"), vec!["Bob "]); + } +} diff --git a/src/lib.rs b/src/lib.rs index 265e003..6d377df 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,5 +6,7 @@ pub mod db; pub mod error; pub mod imap_sync; pub mod models; +pub mod rules; pub mod smtp; pub mod storage; +pub mod threading; diff --git a/src/models/folder.rs b/src/models/folder.rs index 2746fac..62539e9 100644 --- a/src/models/folder.rs +++ b/src/models/folder.rs @@ -8,4 +8,6 @@ pub struct Folder { pub user_id: Uuid, pub name: String, pub created_at: DateTime, + /// 'archive' for the system Archive folder, None for the user's own. + pub role: Option, } diff --git a/src/models/message.rs b/src/models/message.rs index c6743f2..d2c8ea6 100644 --- a/src/models/message.rs +++ b/src/models/message.rs @@ -26,6 +26,8 @@ pub struct Message { /// 'imap' for synced mail, 'sent' for mail sent from Tern. pub source: String, pub created_at: DateTime, + /// Set when moved to Trash. + pub deleted_at: Option>, } #[derive(Debug, Clone, sqlx::FromRow, Serialize)] @@ -50,6 +52,9 @@ pub struct ParsedMessage { pub text_body: Option, pub html_body: Option, pub attachments: Vec, + /// Every header as (lowercased name, unfolded raw value), in order — + /// what rules match against. Repeats (Received, …) are kept. + pub headers: Vec<(String, String)>, pub raw: Vec, } diff --git a/src/models/mod.rs b/src/models/mod.rs index ad06b5a..f99722a 100644 --- a/src/models/mod.rs +++ b/src/models/mod.rs @@ -2,6 +2,7 @@ pub mod account; pub mod folder; pub mod message; pub mod outbox; +pub mod tag; pub mod user; pub use account::Account; diff --git a/src/models/tag.rs b/src/models/tag.rs new file mode 100644 index 0000000..4c81abe --- /dev/null +++ b/src/models/tag.rs @@ -0,0 +1,10 @@ +use serde::Serialize; +use uuid::Uuid; + +#[derive(Debug, Clone, sqlx::FromRow, Serialize)] +pub struct Tag { + pub id: Uuid, + pub user_id: Uuid, + pub name: String, + pub color: Option, +} diff --git a/src/rules.rs b/src/rules.rs new file mode 100644 index 0000000..5817617 --- /dev/null +++ b/src/rules.rs @@ -0,0 +1,681 @@ +//! Rule engine (server-architecture-spec.md §3.5). +//! +//! Rules are structured JSON — a condition list plus an action list — so the +//! webapp can render and edit them without a parser. Conditions are one +//! level deep (`all` / `any` of tests), which is exactly what the editor can +//! show; a deeper tree would make rules the API could create but the UI +//! couldn't edit. +//! +//! Every enabled rule that matches applies, in priority order, until one +//! whose actions include `stop`. That's the Sieve/Outlook model, rather +//! than first-match-wins, because it lets a general rule ("tag anything +//! from a mailing list") and a specific one ("archive this list") both +//! apply. +//! +//! The same `Action` type is used for manual actions from the UI, so +//! "archive this thread" and "a rule that archives" run the same code. + +use crate::models::message::ParsedMessage; +use regex::{Regex, RegexBuilder}; +use serde::{Deserialize, Serialize}; +use sqlx::{PgPool, Postgres, Transaction}; +use std::sync::LazyLock; +use uuid::Uuid; + +/// Patterns are user-written and evaluated against every incoming message. +/// The regex crate matches in linear time, so no pattern can hang ingestion +/// (no catastrophic backtracking); the size cap bounds compile cost too. +const REGEX_SIZE_LIMIT: usize = 256 * 1024; +const MAX_TESTS: usize = 20; +const MAX_ACTIONS: usize = 10; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum Match { + All, + Any, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum Field { + From, + To, + Cc, + /// To and Cc together — "was this sent to the list address". + Recipients, + Subject, + Body, + /// Any header by name, e.g. List-Id, or the PMG spam headers phase 6 + /// will use. + Header, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum Op { + Contains, + Equals, + /// Regular expression, case-insensitive. + Matches, + Exists, + /// Numeric, comparing the first number in the value — so both + /// "5.3" and "Yes, score=5.3" work for spam-score headers. + GreaterThan, + LessThan, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Test { + pub field: Field, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub header: Option, + pub op: Op, + #[serde(default)] + pub value: String, + #[serde(default)] + pub negate: bool, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Conditions { + #[serde(rename = "match")] + pub match_: Match, + pub tests: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Action { + Tag { + tag_id: Uuid, + }, + Untag { + tag_id: Uuid, + }, + /// `None` moves back to the inbox. + Move { + folder_id: Option, + }, + Archive, + MarkRead, + MarkUnread, + /// Soft delete — to Trash, restorable. + Delete, + Restore, + /// Rules only: stop evaluating lower-priority rules. + Stop, +} + +impl Action { + fn allowed_in_rules(&self) -> bool { + matches!( + self, + Action::Tag { .. } + | Action::Move { .. } + | Action::Archive + | Action::MarkRead + | Action::Delete + | Action::Stop + ) + } +} + +/// What a rule can see about a message. +pub struct Facts { + pub from: String, + pub to: String, + pub cc: String, + pub subject: String, + pub body: String, + /// Lowercased names; a header can repeat (Received, …). + pub headers: Vec<(String, String)>, +} + +impl Facts { + pub fn from_parsed(p: &ParsedMessage) -> Self { + let from = match (&p.from_name, &p.from_addr) { + (Some(n), Some(a)) => format!("{n} <{a}>"), + (None, Some(a)) => a.clone(), + (Some(n), None) => n.clone(), + (None, None) => String::new(), + }; + Facts { + from, + to: p.to_addrs.join(", "), + cc: p.cc_addrs.join(", "), + subject: p.subject.clone().unwrap_or_default(), + body: p + .text_body + .clone() + .or_else(|| p.html_body.clone()) + .unwrap_or_default(), + headers: p.headers.clone(), + } + } +} + +/// A validated rule, with its patterns compiled once. +pub struct CompiledRule { + pub id: Uuid, + pub conditions: Conditions, + pub actions: Vec, + patterns: Vec>, +} + +static NUMBER: LazyLock = LazyLock::new(|| Regex::new(r"-?\d+(?:\.\d+)?").unwrap()); + +fn first_number(s: &str) -> Option { + NUMBER.find(s).and_then(|m| m.as_str().parse().ok()) +} + +fn compile_pattern(pattern: &str) -> Result { + RegexBuilder::new(pattern) + .case_insensitive(true) + .size_limit(REGEX_SIZE_LIMIT) + .build() + .map_err(|e| format!("invalid pattern {pattern:?}: {e}")) +} + +/// Structural checks that don't need the database. Ownership of any +/// referenced tag or folder is checked separately by the API. +pub fn validate(conditions: &Conditions, actions: &[Action], for_rule: bool) -> Result<(), String> { + if for_rule { + if conditions.tests.is_empty() { + return Err("a rule needs at least one condition".into()); + } + if conditions.tests.len() > MAX_TESTS { + return Err(format!("at most {MAX_TESTS} conditions per rule")); + } + } + for t in &conditions.tests { + if t.field == Field::Header && t.header.as_deref().map(str::trim).unwrap_or("").is_empty() { + return Err("a header condition needs a header name".into()); + } + match t.op { + Op::Matches => { + compile_pattern(&t.value)?; + } + Op::GreaterThan | Op::LessThan => { + if t.value.trim().parse::().is_err() { + return Err(format!("{:?} needs a number, got {:?}", t.op, t.value)); + } + } + Op::Contains | Op::Equals => { + if t.value.is_empty() { + return Err("contains / equals needs a value".into()); + } + } + Op::Exists => {} + } + } + if actions.is_empty() { + return Err("at least one action is required".into()); + } + if actions.len() > MAX_ACTIONS { + return Err(format!("at most {MAX_ACTIONS} actions")); + } + for a in actions { + if for_rule && !a.allowed_in_rules() { + return Err(format!("{a:?} isn't available as a rule action")); + } + if !for_rule && *a == Action::Stop { + return Err("stop only makes sense inside a rule".into()); + } + } + Ok(()) +} + +impl CompiledRule { + pub fn compile(id: Uuid, conditions: Conditions, actions: Vec) -> Result { + validate(&conditions, &actions, true)?; + let patterns = conditions + .tests + .iter() + .map(|t| { + (t.op == Op::Matches) + .then(|| compile_pattern(&t.value)) + .transpose() + }) + .collect::>()?; + Ok(Self { + id, + conditions, + actions, + patterns, + }) + } + + pub fn matches(&self, facts: &Facts) -> bool { + let mut results = self + .conditions + .tests + .iter() + .zip(&self.patterns) + .map(|(t, re)| eval_test(t, re.as_ref(), facts) != t.negate); + match self.conditions.match_ { + Match::All => results.all(|r| r), + Match::Any => results.any(|r| r), + } + } +} + +fn eval_test(t: &Test, re: Option<&Regex>, facts: &Facts) -> bool { + let recipients; + let values: Vec<&str> = match t.field { + Field::From => vec![&facts.from], + Field::To => vec![&facts.to], + Field::Cc => vec![&facts.cc], + Field::Recipients => { + recipients = format!("{}, {}", facts.to, facts.cc); + vec![&recipients] + } + Field::Subject => vec![&facts.subject], + Field::Body => vec![&facts.body], + Field::Header => { + let name = t.header.as_deref().unwrap_or("").trim().to_lowercase(); + facts + .headers + .iter() + .filter(|(n, _)| *n == name) + .map(|(_, v)| v.as_str()) + .collect() + } + }; + + let needle = t.value.to_lowercase(); + // Any occurrence matching is enough (a header can repeat). + values.iter().any(|v| match t.op { + Op::Exists => !v.trim().is_empty(), + Op::Contains => v.to_lowercase().contains(&needle), + Op::Equals => v.trim().eq_ignore_ascii_case(t.value.trim()), + Op::Matches => re.is_some_and(|re| re.is_match(v)), + Op::GreaterThan => cmp_number(v, &t.value).is_some_and(|(a, b)| a > b), + Op::LessThan => cmp_number(v, &t.value).is_some_and(|(a, b)| a < b), + }) +} + +fn cmp_number(value: &str, threshold: &str) -> Option<(f64, f64)> { + Some((first_number(value)?, threshold.trim().parse().ok()?)) +} + +/// Runs the user's enabled rules against a freshly ingested message, inside +/// the ingest transaction. A rule that no longer compiles (e.g. written +/// before a validation change) is skipped and logged rather than blocking +/// mail. +pub async fn apply_rules( + tx: &mut Transaction<'_, Postgres>, + user_id: Uuid, + message_row_id: Uuid, + facts: &Facts, +) -> sqlx::Result<()> { + let rows: Vec<(Uuid, sqlx::types::Json, sqlx::types::Json>)> = sqlx::query_as( + "SELECT id, conditions, actions FROM rules WHERE user_id = $1 AND enabled ORDER BY priority, created_at", + ) + .bind(user_id) + .fetch_all(&mut **tx) + .await?; + + for (id, conditions, actions) in rows { + let rule = match CompiledRule::compile(id, conditions.0, actions.0) { + Ok(r) => r, + Err(e) => { + tracing::warn!(rule_id = %id, error = %e, "skipping invalid rule"); + continue; + } + }; + if !rule.matches(facts) { + continue; + } + tracing::debug!(rule_id = %id, message = %message_row_id, "rule matched"); + apply_actions(tx, user_id, &[message_row_id], &rule.actions).await?; + if rule.actions.contains(&Action::Stop) { + break; + } + } + Ok(()) +} + +/// Applies actions to messages the caller has already scoped to `user_id`. +/// Tag and folder targets are re-checked against the user here too, so a +/// rule referencing a since-deleted tag is a no-op rather than an error. +pub async fn apply_actions( + tx: &mut Transaction<'_, Postgres>, + user_id: Uuid, + message_ids: &[Uuid], + actions: &[Action], +) -> sqlx::Result<()> { + for action in actions { + match action { + Action::Tag { tag_id } => { + sqlx::query( + "INSERT INTO message_tags (message_id, tag_id) \ + SELECT m, $2 FROM unnest($1::uuid[]) AS m \ + WHERE EXISTS (SELECT 1 FROM tags WHERE id = $2 AND user_id = $3) \ + ON CONFLICT DO NOTHING", + ) + .bind(message_ids) + .bind(tag_id) + .bind(user_id) + .execute(&mut **tx) + .await?; + } + Action::Untag { tag_id } => { + sqlx::query("DELETE FROM message_tags WHERE message_id = ANY($1) AND tag_id = $2") + .bind(message_ids) + .bind(tag_id) + .execute(&mut **tx) + .await?; + } + Action::Move { folder_id } => { + sqlx::query( + "UPDATE messages SET folder_id = $2 WHERE id = ANY($1) \ + AND ($2::uuid IS NULL OR EXISTS (SELECT 1 FROM folders WHERE id = $2 AND user_id = $3))", + ) + .bind(message_ids) + .bind(folder_id) + .bind(user_id) + .execute(&mut **tx) + .await?; + } + Action::Archive => { + let archive = archive_folder(tx, user_id).await?; + sqlx::query("UPDATE messages SET folder_id = $2 WHERE id = ANY($1)") + .bind(message_ids) + .bind(archive) + .execute(&mut **tx) + .await?; + } + Action::MarkRead => { + sqlx::query( + r#"UPDATE messages SET flags = array_append(flags, '\Seen') + WHERE id = ANY($1) AND NOT ('\Seen' = ANY(flags))"#, + ) + .bind(message_ids) + .execute(&mut **tx) + .await?; + } + Action::MarkUnread => { + sqlx::query(r#"UPDATE messages SET flags = array_remove(flags, '\Seen') WHERE id = ANY($1)"#) + .bind(message_ids) + .execute(&mut **tx) + .await?; + } + Action::Delete => { + sqlx::query("UPDATE messages SET deleted_at = now() WHERE id = ANY($1) AND deleted_at IS NULL") + .bind(message_ids) + .execute(&mut **tx) + .await?; + } + Action::Restore => { + sqlx::query("UPDATE messages SET deleted_at = NULL WHERE id = ANY($1)") + .bind(message_ids) + .execute(&mut **tx) + .await?; + } + Action::Stop => {} + } + } + Ok(()) +} + +/// The user's Archive folder, created on first use. An existing folder the +/// user happened to name "Archive" is adopted rather than colliding with it. +pub async fn archive_folder( + tx: &mut Transaction<'_, Postgres>, + user_id: Uuid, +) -> sqlx::Result { + if let Some((id,)) = sqlx::query_as::<_, (Uuid,)>( + "SELECT id FROM folders WHERE user_id = $1 AND role = 'archive'", + ) + .bind(user_id) + .fetch_optional(&mut **tx) + .await? + { + return Ok(id); + } + let (id,): (Uuid,) = sqlx::query_as( + "INSERT INTO folders (user_id, name, role) VALUES ($1, 'Archive', 'archive') \ + ON CONFLICT (user_id, name) DO UPDATE SET role = 'archive' \ + RETURNING id", + ) + .bind(user_id) + .fetch_one(&mut **tx) + .await?; + Ok(id) +} + +/// Whether every tag and folder an action list references belongs to the +/// user — checked when a rule is saved or a manual action is requested. +pub async fn check_targets(pool: &PgPool, user_id: Uuid, actions: &[Action]) -> Result<(), String> { + for a in actions { + let (table, id) = match a { + Action::Tag { tag_id } | Action::Untag { tag_id } => ("tags", *tag_id), + Action::Move { folder_id: Some(f) } => ("folders", *f), + _ => continue, + }; + let exists: bool = sqlx::query_scalar(&format!( + "SELECT EXISTS (SELECT 1 FROM {table} WHERE id = $1 AND user_id = $2)" + )) + .bind(id) + .bind(user_id) + .fetch_one(pool) + .await + .map_err(|e| e.to_string())?; + if !exists { + return Err(format!("{} {id} not found", &table[..table.len() - 1])); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn facts() -> Facts { + Facts { + from: "Newsletter ".into(), + to: "alice@example.com".into(), + cc: "team@example.com".into(), + subject: "Your WEEKLY digest".into(), + body: "Unsubscribe at the bottom".into(), + headers: vec![ + ("list-id".into(), "".into()), + ("x-spam-score".into(), "5.3".into()), + ("x-spam-status".into(), "Yes, score=7.25 required=5".into()), + ("received".into(), "from a".into()), + ("received".into(), "from relay.example.net".into()), + ], + } + } + + fn test(field: Field, op: Op, value: &str) -> Test { + Test { + field, + header: None, + op, + value: value.into(), + negate: false, + } + } + + fn header(name: &str, op: Op, value: &str) -> Test { + Test { + field: Field::Header, + header: Some(name.into()), + op, + value: value.into(), + negate: false, + } + } + + fn rule(match_: Match, tests: Vec) -> CompiledRule { + CompiledRule::compile( + Uuid::nil(), + Conditions { match_, tests }, + vec![Action::MarkRead], + ) + .unwrap() + } + + #[test] + fn contains_and_equals_ignore_case() { + assert!(rule( + Match::All, + vec![test(Field::Subject, Op::Contains, "weekly")] + ) + .matches(&facts())); + assert!(rule( + Match::All, + vec![test(Field::To, Op::Equals, "ALICE@example.com")] + ) + .matches(&facts())); + } + + #[test] + fn all_needs_every_test_any_needs_one() { + let hit = test(Field::Subject, Op::Contains, "digest"); + let miss = test(Field::Subject, Op::Contains, "invoice"); + assert!(!rule(Match::All, vec![hit.clone(), miss.clone()]).matches(&facts())); + assert!(rule(Match::Any, vec![hit, miss]).matches(&facts())); + } + + #[test] + fn negate_inverts_a_test() { + let mut t = test(Field::From, Op::Contains, "lists.example.com"); + t.negate = true; + assert!(!rule(Match::All, vec![t]).matches(&facts())); + } + + #[test] + fn recipients_covers_to_and_cc() { + assert!(rule( + Match::All, + vec![test(Field::Recipients, Op::Contains, "team@")] + ) + .matches(&facts())); + assert!(!rule(Match::All, vec![test(Field::To, Op::Contains, "team@")]).matches(&facts())); + } + + #[test] + fn header_names_are_case_insensitive_and_repeats_are_all_checked() { + assert!(rule( + Match::All, + vec![header("List-ID", Op::Contains, "weekly.lists")] + ) + .matches(&facts())); + assert!(rule( + Match::All, + vec![header("Received", Op::Contains, "relay.example.net")] + ) + .matches(&facts())); + assert!(!rule(Match::All, vec![header("X-Missing", Op::Exists, "")]).matches(&facts())); + } + + #[test] + fn numeric_comparison_reads_the_first_number() { + // Both plain and "Yes, score=N" formats — the phase 6 spam headers. + assert!(rule( + Match::All, + vec![header("X-Spam-Score", Op::GreaterThan, "5")] + ) + .matches(&facts())); + assert!(rule( + Match::All, + vec![header("X-Spam-Status", Op::GreaterThan, "7")] + ) + .matches(&facts())); + assert!(!rule( + Match::All, + vec![header("X-Spam-Score", Op::GreaterThan, "6")] + ) + .matches(&facts())); + assert!( + rule(Match::All, vec![header("X-Spam-Score", Op::LessThan, "6")]).matches(&facts()) + ); + } + + #[test] + fn regex_is_case_insensitive() { + assert!(rule( + Match::All, + vec![test(Field::Subject, Op::Matches, r"^your\s+weekly")] + ) + .matches(&facts())); + } + + #[test] + fn validation_rejects_bad_rules() { + let bad = |tests: Vec, actions: Vec| { + validate( + &Conditions { + match_: Match::All, + tests, + }, + &actions, + true, + ) + .is_err() + }; + assert!(bad(vec![], vec![Action::MarkRead]), "no conditions"); + assert!( + bad(vec![test(Field::Subject, Op::Contains, "x")], vec![]), + "no actions" + ); + assert!( + bad( + vec![test(Field::Subject, Op::Matches, "(unclosed")], + vec![Action::MarkRead] + ), + "bad regex" + ); + assert!( + bad( + vec![test(Field::Subject, Op::GreaterThan, "lots")], + vec![Action::MarkRead] + ), + "non-numeric" + ); + assert!( + bad(vec![header("", Op::Exists, "")], vec![Action::MarkRead]), + "header without a name" + ); + assert!( + bad( + vec![test(Field::Subject, Op::Contains, "")], + vec![Action::MarkRead] + ), + "empty contains" + ); + assert!( + bad( + vec![test(Field::Subject, Op::Contains, "x")], + vec![Action::Restore] + ), + "restore isn't a rule action" + ); + } + + #[test] + fn oversized_patterns_are_rejected() { + // Compiles to far more than the size limit. + let huge = format!("({}){{50}}", "[a-z]{1,500}"); + assert!(compile_pattern(&huge).is_err()); + } + + #[test] + fn actions_round_trip_through_json_as_tagged_objects() { + let a = vec![ + Action::Archive, + Action::Move { folder_id: None }, + Action::Stop, + ]; + let json = serde_json::to_string(&a).unwrap(); + assert_eq!( + json, + r#"[{"type":"archive"},{"type":"move","folder_id":null},{"type":"stop"}]"# + ); + assert_eq!(serde_json::from_str::>(&json).unwrap(), a); + } +} diff --git a/src/smtp/worker.rs b/src/smtp/worker.rs index 76fb826..7a3c4cb 100644 --- a/src/smtp/worker.rs +++ b/src/smtp/worker.rs @@ -281,6 +281,19 @@ async fn record_sent( .fetch_one(&mut *tx) .await?; + crate::threading::assign( + &mut tx, + &crate::threading::ThreadInput { + account_id: item.account_id, + row_id: message_row_id, + message_id: item.message_id.as_deref(), + in_reply_to: item.in_reply_to.as_deref(), + references: &item.references_, + subject: Some(&item.subject), + }, + ) + .await?; + sqlx::query("INSERT INTO bodies (message_id, text_body, html_body) VALUES ($1, $2, NULL)") .bind(message_row_id) .bind(&item.text_body) diff --git a/src/threading.rs b/src/threading.rs new file mode 100644 index 0000000..b9ac230 --- /dev/null +++ b/src/threading.rs @@ -0,0 +1,306 @@ +//! Conversation threading (server-architecture-spec.md §3.6). +//! +//! An incremental, database-backed take on JWZ. Rather than rebuilding every +//! thread tree in memory, each message is linked as it arrives: +//! +//! 1. **Ancestors** — messages whose Message-ID appears in its References +//! or In-Reply-To. +//! 2. **Children that arrived first** — messages whose References or +//! In-Reply-To name *it*. IDLE delivers mail in arrival order, not thread +//! order, so a reply can land before its parent. +//! 3. **Siblings of a missing ancestor** — messages that reference any of +//! the same IDs. This is what JWZ's placeholder containers achieve: two +//! replies to a message we never received still belong together. +//! +//! Every thread those turn up is merged into one. The survivor is the +//! thread holding the oldest message, which keeps repeated merges +//! deterministic. That's also why thread_id is its own generated ID rather +//! than the root's Message-ID: a thread can gain an earlier root later. +//! +//! When a message carries no reference headers at all, a subject fallback +//! applies — but only when the subject marks it as a reply (Re:/Fwd:). Some +//! mailing lists strip References, and their replies should still group; +//! unrelated mail that merely shares a generic subject like "Invoice" +//! must not. +//! +//! Scoped per account: a thread never spans two accounts (§3.6). + +use crate::smtp::compose::bare_id; +use sqlx::{Postgres, Transaction}; +use uuid::Uuid; + +/// Raise this when the algorithm changes; accounts below it are re-threaded +/// once on their next sync start. +pub const THREADING_VERSION: i32 = 1; + +const SUBJECT_FALLBACK_DAYS: i32 = 30; + +const REPLY_PREFIXES: &[&str] = &[ + "re", "fw", "fwd", "aw", "wg", "sv", "vs", "antw", "odp", "pd", +]; + +/// Strips reply/forward prefixes (`Re:`, `Fwd:`, `AW:`, `Re[2]:`…) and +/// mailing-list tags (`[list-name]`) from the front, repeatedly, then +/// lowercases and collapses whitespace. +pub fn normalize_subject(subject: &str) -> String { + let mut s = subject.trim(); + loop { + let before = s; + if let Some(rest) = s.strip_prefix('[') { + if let Some(end) = rest.find(']') { + s = rest[end + 1..].trim_start(); + } + } + if let Some(rest) = strip_reply_prefix(s) { + s = rest.trim_start(); + } + if s == before { + break; + } + } + s.split_whitespace() + .collect::>() + .join(" ") + .to_lowercase() +} + +/// Does the subject start with a reply/forward marker (after any list tag)? +pub fn is_reply_subject(subject: &str) -> bool { + let mut s = subject.trim(); + while let Some(rest) = s.strip_prefix('[') { + match rest.find(']') { + Some(end) => s = rest[end + 1..].trim_start(), + None => break, + } + } + strip_reply_prefix(s).is_some() +} + +fn strip_reply_prefix(s: &str) -> Option<&str> { + let colon = s.find(':')?; + let head = s[..colon].trim(); + // Allow a counter, as in "Re[2]:" or "Re(2):". + let word = head.split(['[', '(']).next().unwrap_or("").trim(); + if head.len() <= 10 && REPLY_PREFIXES.iter().any(|p| word.eq_ignore_ascii_case(p)) { + Some(&s[colon + 1..]) + } else { + None + } +} + +pub struct ThreadInput<'a> { + pub account_id: Uuid, + pub row_id: Uuid, + pub message_id: Option<&'a str>, + pub in_reply_to: Option<&'a str>, + pub references: &'a [String], + pub subject: Option<&'a str>, +} + +/// Links one message into its thread, merging threads where it bridges +/// them. Returns the thread it ended up in. +pub async fn assign( + tx: &mut Transaction<'_, Postgres>, + input: &ThreadInput<'_>, +) -> sqlx::Result { + let own_id = input.message_id.map(bare_id).filter(|s| !s.is_empty()); + let mut candidates: Vec = input + .references + .iter() + .map(|r| bare_id(r)) + .chain(input.in_reply_to.map(bare_id)) + .filter(|r| !r.is_empty() && Some(r) != own_id.as_ref()) + .collect(); + candidates.sort(); + candidates.dedup(); + + let subject_norm = input + .subject + .map(normalize_subject) + .filter(|s| !s.is_empty()); + + sqlx::query("UPDATE messages SET subject_norm = $2 WHERE id = $1") + .bind(input.row_id) + .bind(&subject_norm) + .execute(&mut **tx) + .await?; + + let mut related: Vec<(Uuid,)> = sqlx::query_as( + "SELECT DISTINCT thread_id FROM messages \ + WHERE account_id = $1 AND id <> $2 AND ( \ + message_id = ANY($3) \ + OR in_reply_to = ANY($3) \ + OR references_ && $3 \ + OR ($4::text IS NOT NULL AND (in_reply_to = $4 OR $4 = ANY(references_))) \ + )", + ) + .bind(input.account_id) + .bind(input.row_id) + .bind(&candidates) + .bind(&own_id) + .fetch_all(&mut **tx) + .await?; + + if related.is_empty() && candidates.is_empty() { + if let (Some(norm), Some(subject)) = (&subject_norm, input.subject) { + if is_reply_subject(subject) { + related = sqlx::query_as( + "SELECT thread_id FROM messages \ + WHERE account_id = $1 AND id <> $2 AND subject_norm = $3 \ + AND COALESCE(sent_at, created_at) > now() - make_interval(days => $4) \ + ORDER BY COALESCE(sent_at, created_at) DESC LIMIT 1", + ) + .bind(input.account_id) + .bind(input.row_id) + .bind(norm) + .bind(SUBJECT_FALLBACK_DAYS) + .fetch_all(&mut **tx) + .await?; + } + } + } + + let (own_thread,): (Uuid,) = sqlx::query_as("SELECT thread_id FROM messages WHERE id = $1") + .bind(input.row_id) + .fetch_one(&mut **tx) + .await?; + + let mut threads: Vec = related.into_iter().map(|(t,)| t).collect(); + threads.push(own_thread); + threads.sort(); + threads.dedup(); + if threads.len() == 1 { + return Ok(own_thread); + } + + // Survivor: the thread holding the oldest message. + let (survivor,): (Uuid,) = sqlx::query_as( + "SELECT thread_id FROM messages WHERE account_id = $1 AND thread_id = ANY($2) \ + ORDER BY COALESCE(sent_at, created_at) ASC, created_at ASC LIMIT 1", + ) + .bind(input.account_id) + .bind(&threads) + .fetch_one(&mut **tx) + .await?; + + sqlx::query( + "UPDATE messages SET thread_id = $3 \ + WHERE account_id = $1 AND thread_id = ANY($2) AND thread_id <> $3", + ) + .bind(input.account_id) + .bind(&threads) + .bind(survivor) + .execute(&mut **tx) + .await?; + + // Drafts and queued replies point at a thread too; keep them attached. + sqlx::query("UPDATE outbox SET thread_id = $2 WHERE thread_id = ANY($1) AND thread_id <> $2") + .bind(&threads) + .bind(survivor) + .execute(&mut **tx) + .await?; + + Ok(survivor) +} + +#[derive(sqlx::FromRow)] +struct ThreadingRow { + id: Uuid, + message_id: Option, + in_reply_to: Option, + references_: Vec, + subject: Option, +} + +/// Re-threads an account's existing mail, oldest first, when its +/// threading version is behind. One transaction per message keeps locks +/// short on a large mailbox; an interrupted run just repeats next time, +/// since linking a message twice is harmless. +pub async fn backfill_if_needed(pool: &sqlx::PgPool, account_id: Uuid) -> anyhow::Result<()> { + let version: Option<(i32,)> = + sqlx::query_as("SELECT threading_version FROM sync_state WHERE account_id = $1") + .bind(account_id) + .fetch_optional(pool) + .await?; + if version.map(|(v,)| v >= THREADING_VERSION).unwrap_or(true) { + return Ok(()); + } + + let rows: Vec = sqlx::query_as( + "SELECT id, message_id, in_reply_to, references_, subject FROM messages \ + WHERE account_id = $1 ORDER BY COALESCE(sent_at, created_at) ASC, created_at ASC", + ) + .bind(account_id) + .fetch_all(pool) + .await?; + + tracing::info!(%account_id, messages = rows.len(), "re-threading existing mail"); + for row in &rows { + let mut tx = pool.begin().await?; + assign( + &mut tx, + &ThreadInput { + account_id, + row_id: row.id, + message_id: row.message_id.as_deref(), + in_reply_to: row.in_reply_to.as_deref(), + references: &row.references_, + subject: row.subject.as_deref(), + }, + ) + .await?; + tx.commit().await?; + } + + sqlx::query("UPDATE sync_state SET threading_version = $2 WHERE account_id = $1") + .bind(account_id) + .bind(THREADING_VERSION) + .execute(pool) + .await?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strips_stacked_reply_prefixes_and_list_tags() { + assert_eq!(normalize_subject("Re: Fwd: RE: Roof quote"), "roof quote"); + assert_eq!( + normalize_subject("[tern-dev] Re: [tern-dev] Build broke"), + "build broke" + ); + assert_eq!( + normalize_subject("AW: Re[2]: Termin morgen"), + "termin morgen" + ); + assert_eq!(normalize_subject("Re(3): hello"), "hello"); + } + + #[test] + fn leaves_colons_that_are_not_prefixes() { + assert_eq!( + normalize_subject("Meeting: Q3 planning"), + "meeting: q3 planning" + ); + assert_eq!( + normalize_subject("Ticket 1234: server down"), + "ticket 1234: server down" + ); + } + + #[test] + fn reply_detection_sees_through_list_tags_only() { + assert!(is_reply_subject("Re: invoice")); + assert!(is_reply_subject("[list] Fwd: invoice")); + assert!(!is_reply_subject("Invoice")); + assert!(!is_reply_subject("Meeting: Re-planning")); + } + + #[test] + fn empty_and_prefix_only_subjects_normalise_to_empty() { + assert_eq!(normalize_subject(""), ""); + assert_eq!(normalize_subject("Re:"), ""); + } +} diff --git a/tests/routes.rs b/tests/routes.rs index 6ed337c..e03c1fd 100644 --- a/tests/routes.rs +++ b/tests/routes.rs @@ -63,6 +63,13 @@ async fn parameterised_routes_match() { ("PUT", format!("/api/outbox/{id}")), ("DELETE", format!("/api/outbox/{id}")), ("POST", format!("/api/outbox/{id}/send")), + ("POST", format!("/api/threads/{id}/actions")), + ("PUT", format!("/api/folders/{id}")), + ("DELETE", format!("/api/folders/{id}")), + ("PUT", format!("/api/tags/{id}")), + ("DELETE", format!("/api/tags/{id}")), + ("PUT", format!("/api/rules/{id}")), + ("DELETE", format!("/api/rules/{id}")), ] { let status = status_for(method, &uri).await; assert_ne!( @@ -83,6 +90,8 @@ async fn collection_routes_match() { "/api/threads", "/api/events", "/api/outbox", + "/api/tags", + "/api/rules", ] { let status = status_for("GET", uri).await; assert_ne!(