4 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 4b6eeaca15 Bump to 0.5.0
CI / test (push) Successful in 3m51s
Release / image (push) Successful in 2m48s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:01:40 +02:00
Mateusz PstruchaandClaude Opus 5.5 3f1d9227c6 Add trash retention, stop-after-match and run-now
CI / test (push) Successful in 46s
Mail in Trash is purged after TRASH_RETENTION_DAYS (default 30, 0
disables), hourly. Stored files are content-addressed and shared, so a
file is only removed once nothing references it — and not if written or
reused in the last hour, since ingest writes a file before inserting the
row that points at it. Reusing an existing blob now refreshes its mtime
so that grace period protects it too. Trash rows report when they purge.

"Stop processing further rules" moves from an action to a per-rule
option (stop_after_match): it's a property of the rule, not something
done to a message. Migration 0007 converts existing stop actions, and a
stop submitted as an action is now rejected.

Rules can be run now against existing mail outside Trash, disabled ones
included so a rule can be tried before it's switched on. It pages by
key, one transaction per page, and only re-reads stored raw messages
when the rule tests a header.

All JSON bodies now go through an AppJson extractor so malformed or
mistyped bodies return the API's {"error": …} shape. Axum's default was
a plain-text 422 the webapp could only show as "request failed: 422" —
losing the useful part, e.g. "unknown variant `stop`".

Verified live: the stop flag blocks a lower rule on arriving mail; run
now on a disabled header rule archived 2 of 4 messages; a purge removed
an expired message and its unique raw file while keeping an attachment
file still shared with a live copy, with no orphaned rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:00:04 +02:00
Mateusz PstruchaandClaude Opus 5.5 5809c9e310 Document threading, tags and rules behaviour
CI / test (push) Successful in 50s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 11:26:03 +02:00
Mateusz PstruchaandClaude Opus 5.5 807775726c Add threading, tags, rules and thread actions
CI / test (push) Successful in 3m3s
Threading (§3.6) is an incremental, database-backed JWZ: each message
links to its ancestors, to replies that arrived before it, and to
siblings sharing a missing ancestor (what JWZ's placeholder containers
do), merging every thread it touches into the one holding the oldest
message. Subject-only grouping applies only to Re:/Fwd: messages with no
reference headers, so lists that strip References still thread while
unrelated mail sharing a generic subject never merges. Existing mail is
re-threaded once per account via a versioned backfill.

Rules (§3.5) are structured JSON — one level of all/any tests, exactly
what the editor can show — run after the body is fetched since they need
headers. Every matching rule applies in priority order until a `stop`.
Patterns use the regex crate: linear-time, so a user-written pattern run
against every incoming message can't hang ingest. Numeric comparison
reads the first number in a value, so both "5.3" and "Yes, score=5.3"
spam headers work for phase 6.

Rule "delete" is a soft delete to Trash: a rule with an over-broad
pattern must not be able to destroy mail. Archive moves to a system
folder found by role, so renaming it doesn't break archiving. Manual
thread actions use the same action type and applier as rules, so the two
can't drift.

Thread listing now takes a view (inbox/all/sent/trash/folder/tag). A
thread appears in a view if any message matches, but the row summarises
the whole conversation — so a reply to an archived thread brings it back
to the inbox. Row subjects come from the root when present, not merely
the earliest Date (replies can be dated earlier, and Date ties are
common at one-second resolution).

Verified against a live TLS mail server: out-of-order parent/reply,
replies to a missing root, a list that strips References, and two
unrelated "Invoice" mails kept apart; rules tagging, archiving, trashing
on spam score, and `stop` blocking a lower rule; the backfill rebuilding
the same 9 threads from 13 split messages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 11:19:35 +02:00
31 changed files with 2067 additions and 53 deletions

No files matched your search

+3
View File
@@ -13,4 +13,7 @@ CREDENTIAL_KEY=
BLOB_STORAGE_DIR=./data/blobs
SESSION_TTL_HOURS=720
# Days mail stays in Trash before it's permanently deleted. 0 disables purging.
TRASH_RETENTION_DAYS=30
RUST_LOG=tern_server=debug,tower_http=debug
Generated
+14 -1
View File
@@ -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"
@@ -2675,7 +2687,7 @@ dependencies = [
[[package]]
name = "tern-server"
version = "0.4.0"
version = "0.5.0"
dependencies = [
"anyhow",
"argon2",
@@ -2691,6 +2703,7 @@ dependencies = [
"mail-parser 0.11.9",
"mail-send",
"rand",
"regex",
"rustls 0.23.45",
"rustls-native-certs",
"serde",
+2 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tern-server"
version = "0.4.0"
version = "0.5.0"
edition = "2021"
description = "Tern sync server — the only component that speaks IMAP/SMTP"
@@ -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"
+20 -3
View File
@@ -2,7 +2,7 @@
The sync server for [Tern](../) — the only component that ever speaks IMAP/SMTP. See [`docs/server-architecture-spec.md`](docs/server-architecture-spec.md) for the full design.
## What's built (build-order phases 1–4)
## What's built (build-order phases 1–5)
- **DB schema** (`migrations/`): users/sessions, accounts + per-account sync state, messages/bodies/attachments, folders, tags, rules, devices — the full data model from the spec, even though rules/tags/threading execution isn't implemented yet.
- **IMAP sync engine** (`src/imap_sync/`): one task per account — connects over TLS, selects INBOX, tracks `UIDVALIDITY` (re-syncing the account from scratch if it changes), fetches new mail headers-first (`ENVELOPE`/`FLAGS`) then lazily fills in bodies/attachments in a trailing pass, and IDLEs for pushed changes with a periodic renewal and jittered-backoff reconnect on any failure.
@@ -10,6 +10,24 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT
- **Thread-grouped listing** (`GET /api/threads`): one row per conversation, which is how both clients render the inbox. Grouped server-side because a thread's messages are spread through the flat list by date, so a client grouping page-by-page would split threads across page boundaries and miscount unread.
- **Sending** (`src/smtp/`, `/api/outbox`): drafts and a send queue, drained by a background worker — never in the request path (§3.3). Retries with backoff (1, 2, 4, 8, 16 min), fails fast on 5xx replies and auth or TLS errors, and reclaims messages a crashed worker left mid-send. Replies get In-Reply-To/References derived server-side from the parent message. Sent mail is filed into its thread alongside received mail.
- **Mark read** (`POST /api/threads/:id/read`) — local state only; see below.
- **Threading** (`src/threading.rs`, §3.6) — an incremental, database-backed JWZ. Each message links to its ancestors, to replies that arrived before it, and to siblings sharing a *missing* ancestor (what JWZ's placeholder containers do), merging every thread it touches into the one holding the oldest message. Subject-only grouping applies only to `Re:`/`Fwd:` messages with no reference headers — lists that strip References still thread, while unrelated mail sharing a generic subject never merges. Existing mail is re-threaded once per account via a versioned backfill (`THREADING_VERSION`).
- **Tags, folders and views** — thread listing takes `view=inbox|all|sent|trash|folder|tag`. A thread appears in a view if any of its messages does, but the row summarises the whole conversation, so a reply to an archived thread brings it back to the inbox. Archive is a system folder found by role, so it can be renamed.
- **Rules** (`src/rules.rs`, `/api/rules`, §3.5) — structured JSON: one level of all/any tests (from, to, cc, recipients, subject, body, any header; contains, is, regex, exists, greater/less than) and an action list (tag, move, archive, mark read, delete). Run on new mail after its body is fetched; every matching rule applies in priority order, until one marked *stop after match*. Any rule can also be **run now** against existing mail (`POST /api/rules/:id/run`) — disabled ones too, so a rule can be tried before it's switched on. Manual thread actions (`POST /api/threads/:id/actions`) use the same action format and code.
## How rules behave
- **Delete moves to Trash.** A rule runs on every incoming message, so one with an over-broad pattern must not be able to destroy mail. Trashed mail can be restored until it's purged — see below.
- **Patterns can't hang ingest.** The `regex` crate matches in linear time (no catastrophic backtracking), and patterns are size-capped and validated when the rule is saved.
- **Numeric comparisons read the first number in a value**, so both `X-Spam-Score: 5.3` and `X-Spam-Status: Yes, score=5.3` work — ready for phase 6's PMG headers.
- **Run now** covers everything outside Trash, including mail already filed away, and skips sent mail (rules are for incoming mail). Stored raw messages are only re-read when the rule tests a header, so body/subject/sender rules stay a fast database scan.
- **Rules see a message a moment after it appears.** Headers sync first so new mail shows quickly; rules need the full headers and body, so they run once the body arrives, seconds later.
- **No notify/don't-notify action yet** — it arrives with the notification work in phases 7–8.
## Trash retention
Mail in Trash is permanently deleted after `TRASH_RETENTION_DAYS` (default 30; `0` disables purging), checked hourly. Stored files are content-addressed and shared between identical messages or attachments, so a file is only removed once nothing references it — and not if it was written or reused in the last hour, which covers the gap between ingest writing a file and inserting the row that points at it.
Purged mail doesn't come back: the sync engine only fetches UIDs above the last one it has seen. The exception is a UIDVALIDITY reset, which re-syncs the whole INBOX.
## How sending behaves
@@ -24,11 +42,10 @@ A few consequences worth knowing, because they aren't visible from the UI:
## What's explicitly deferred
Per the spec's suggested build order (§9), not yet built: tag & rule *execution* (schema exists, engine doesn't), the JWZ threading algorithm (each message currently gets its own `thread_id` — no linking/merging pass yet), spam header rules, WebSocket push (the `/events` poll endpoint is the interim/fallback path), and the Android/webapp-facing UnifiedPush integration.
Per the spec's suggested build order (§9), not yet built: spam header rules (the rule engine already supports them — phase 6 is about defaults and a UI for the threshold), WebSocket push (the `/events` poll endpoint is the interim/fallback path), and the Android/webapp-facing UnifiedPush integration.
Also deferred, and worth knowing because they aren't obvious from the code:
- **Most mutations.** Mark-read exists; tagging and moving to folders arrive with phase 5.
- **Permissive CORS.** `CorsLayer::permissive()` is a dev convenience so the Vite dev server on another port can talk to the API. Tighten it when the webapp is served from the same origin behind nginx.
- **API-level rate limiting.** The nginx layer covers most of this — see [`nginx-rate-limiting.md`](nginx-rate-limiting.md). A per-username limiter in the API is the remaining gap.
+36
View File
@@ -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;
+13
View File
@@ -0,0 +1,13 @@
-- "Stop processing further rules" is a property of a rule, not something
-- it does to a message, so it moves out of the action list into a column.
ALTER TABLE rules ADD COLUMN stop_after_match BOOLEAN NOT NULL DEFAULT false;
UPDATE rules SET
stop_after_match = true,
actions = COALESCE(
(SELECT jsonb_agg(a) FROM jsonb_array_elements(actions) AS a WHERE a->>'type' <> 'stop'),
'[]'::jsonb)
WHERE actions @> '[{"type": "stop"}]';
-- Trashed mail is purged after a retention period; the purge scans by age.
CREATE INDEX messages_deleted_at_idx ON messages (deleted_at) WHERE deleted_at IS NOT NULL;
+2 -2
View File
@@ -1,6 +1,6 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::ApiResult;
use crate::error::{ApiResult, AppJson};
use crate::models::account::{Account, AccountPublic};
use axum::{extract::State, Json};
use serde::Deserialize;
@@ -43,7 +43,7 @@ pub async fn list(
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
Json(req): Json<CreateAccountRequest>,
AppJson(req): AppJson<CreateAccountRequest>,
) -> ApiResult<Json<AccountPublic>> {
let encrypted = state.cipher.encrypt(&req.password)?;
+3 -3
View File
@@ -1,6 +1,6 @@
use crate::api::state::AppState;
use crate::auth::{hash_password, verify_password};
use crate::error::{ApiError, ApiResult};
use crate::error::{ApiError, ApiResult, AppJson};
use crate::models::User;
use axum::{extract::State, Json};
use chrono::{Duration, Utc};
@@ -27,7 +27,7 @@ pub struct SessionResponse {
pub async fn register(
State(state): State<AppState>,
Json(req): Json<RegisterRequest>,
AppJson(req): AppJson<RegisterRequest>,
) -> ApiResult<Json<SessionResponse>> {
if req.username.trim().is_empty() || req.password.len() < 8 {
return Err(ApiError::BadRequest(
@@ -55,7 +55,7 @@ pub async fn register(
pub async fn login(
State(state): State<AppState>,
Json(req): Json<LoginRequest>,
AppJson(req): AppJson<LoginRequest>,
) -> ApiResult<Json<SessionResponse>> {
let user: Option<User> = sqlx::query_as("SELECT * FROM users WHERE username = $1")
.bind(&req.username)
+58 -7
View File
@@ -1,6 +1,6 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::ApiResult;
use crate::error::{ApiResult, AppJson};
use crate::models::Folder;
use axum::{extract::State, Json};
use serde::Deserialize;
@@ -14,18 +14,19 @@ pub async fn list(
State(state): State<AppState>,
user: CurrentUser,
) -> ApiResult<Json<Vec<Folder>>> {
let folders: Vec<Folder> =
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<Folder> = 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))
}
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
Json(req): Json<CreateFolderRequest>,
AppJson(req): AppJson<CreateFolderRequest>,
) -> ApiResult<Json<Folder>> {
let folder: Folder =
sqlx::query_as("INSERT INTO folders (user_id, name) VALUES ($1, $2) RETURNING *")
@@ -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<AppState>,
user: CurrentUser,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
AppJson(req): AppJson<RenameFolderRequest>,
) -> ApiResult<Json<Folder>> {
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<Folder> =
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<AppState>,
user: CurrentUser,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
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 })))
}
+2
View File
@@ -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;
+3 -3
View File
@@ -9,7 +9,7 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult};
use crate::error::{ApiError, ApiResult, AppJson};
use crate::models::account::Account;
use crate::models::outbox::OutboxItem;
use crate::models::Message;
@@ -69,7 +69,7 @@ pub async fn list(
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
Json(req): Json<ComposeRequest>,
AppJson(req): AppJson<ComposeRequest>,
) -> ApiResult<Json<OutboxItem>> {
let to = compose::normalize_recipients(&req.to).map_err(ApiError::BadRequest)?;
let cc = compose::normalize_recipients(&req.cc).map_err(ApiError::BadRequest)?;
@@ -130,7 +130,7 @@ pub async fn update(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
Json(req): Json<UpdateDraftRequest>,
AppJson(req): AppJson<UpdateDraftRequest>,
) -> ApiResult<Json<OutboxItem>> {
let to = compose::normalize_recipients(&req.to).map_err(ApiError::BadRequest)?;
let cc = compose::normalize_recipients(&req.cc).map_err(ApiError::BadRequest)?;
+12 -1
View File
@@ -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,22 @@ 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/run", post(rules::run))
.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",
+214
View File
@@ -0,0 +1,214 @@
//! 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, AppJson};
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<Conditions>,
pub actions: SqlJson<Vec<Action>>,
pub enabled: bool,
/// Skip lower-priority rules once this one matches.
pub stop_after_match: bool,
pub priority: i32,
pub created_at: DateTime<Utc>,
}
#[derive(Deserialize)]
pub struct RuleRequest {
pub name: String,
pub conditions: Conditions,
pub actions: Vec<Action>,
#[serde(default = "enabled_default")]
pub enabled: bool,
#[serde(default)]
pub stop_after_match: bool,
}
fn enabled_default() -> bool {
true
}
#[derive(Deserialize)]
pub struct ReorderRequest {
/// Every rule id, in the new priority order.
pub ids: Vec<Uuid>,
}
const RULE_COLUMNS: &str =
"id, name, conditions, actions, enabled, stop_after_match, 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<AppState>, user: CurrentUser) -> ApiResult<Json<Vec<Rule>>> {
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<AppState>,
user: CurrentUser,
AppJson(req): AppJson<RuleRequest>,
) -> ApiResult<Json<Rule>> {
check(&state, user.user_id, &req).await?;
let rule = sqlx::query_as(&format!(
"INSERT INTO rules (user_id, name, conditions, actions, enabled, stop_after_match, priority) \
VALUES ($1, $2, $3, $4, $5, $6, \
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)
.bind(req.stop_after_match)
.fetch_one(&state.pool)
.await?;
Ok(Json(rule))
}
pub async fn update(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
AppJson(req): AppJson<RuleRequest>,
) -> ApiResult<Json<Rule>> {
check(&state, user.user_id, &req).await?;
let rule: Option<Rule> = sqlx::query_as(&format!(
"UPDATE rules SET name = $3, conditions = $4, actions = $5, enabled = $6, \
stop_after_match = $7 \
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)
.bind(req.stop_after_match)
.fetch_optional(&state.pool)
.await?;
rule.map(Json).ok_or(ApiError::NotFound)
}
pub async fn delete(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
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<AppState>,
user: CurrentUser,
AppJson(req): AppJson<ReorderRequest>,
) -> ApiResult<Json<Vec<Rule>>> {
let mut tx = state.pool.begin().await?;
let mut existing: Vec<Uuid> =
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
}
#[derive(Serialize)]
pub struct RunResponse {
pub scanned: usize,
pub matched: usize,
}
/// "Run now": applies one rule to existing received mail. Works on disabled
/// rules too, so a rule can be tried out before it's switched on for new
/// mail. Stored as-is is what runs — unsaved edits in the editor don't.
pub async fn run(
State(state): State<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<RunResponse>> {
let stored: rules::StoredRule = sqlx::query_as(
"SELECT id, conditions, actions, stop_after_match FROM rules WHERE id = $1 AND user_id = $2",
)
.bind(id)
.bind(user.user_id)
.fetch_optional(&state.pool)
.await?
.ok_or(ApiError::NotFound)?;
let rule = rules::CompiledRule::compile(stored.id, stored.conditions.0, stored.actions.0)
.map_err(ApiError::BadRequest)?;
let summary = rules::run_on_existing(&state.pool, &state.blobs, user.user_id, &rule).await?;
tracing::info!(rule_id = %id, scanned = summary.scanned, matched = summary.matched, "ran rule on existing mail");
Ok(Json(RunResponse {
scanned: summary.scanned,
matched: summary.matched,
}))
}
+117
View File
@@ -0,0 +1,117 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiError, ApiResult, AppJson};
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<String>,
}
/// 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<String>)> {
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<AppState>, user: CurrentUser) -> ApiResult<Json<Vec<Tag>>> {
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<AppState>,
user: CurrentUser,
AppJson(req): AppJson<TagRequest>,
) -> ApiResult<Json<Tag>> {
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<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
AppJson(req): AppJson<TagRequest>,
) -> ApiResult<Json<Tag>> {
let (name, color) = validate(&req)?;
let tag: Option<Tag> = 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<AppState>,
user: CurrentUser,
Path(id): Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
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 })))
}
+148 -31
View File
@@ -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, AppJson};
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<Uuid>,
pub tag_id: Option<Uuid>,
pub before: Option<DateTime<Utc>>,
pub limit: Option<i64>,
}
@@ -36,6 +71,10 @@ pub struct ThreadSummary {
pub message_count: i64,
pub unread_count: i64,
pub has_attachments: bool,
pub tag_ids: Vec<Uuid>,
/// In Trash: when the earliest-trashed message in the thread is purged
/// for good. None elsewhere, or when retention is disabled.
pub purges_at: Option<DateTime<Utc>>,
}
#[derive(Serialize)]
@@ -51,37 +90,77 @@ pub async fn list(
) -> ApiResult<Json<ListThreadsResponse>> {
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<ThreadSummary> = 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,
CASE WHEN $2 = 'trash' AND $7 > 0
THEN MIN(m.deleted_at) + make_interval(days => $7) END AS purges_at
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)
.bind(state.config.trash_retention_days as i32)
.fetch_all(&state.pool)
.await?;
@@ -93,25 +172,63 @@ pub async fn list(
}))
}
#[derive(Deserialize)]
pub struct ThreadActionsRequest {
pub actions: Vec<Action>,
}
/// 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<AppState>,
user: CurrentUser,
Path(thread_id): Path<Uuid>,
AppJson(req): AppJson<ThreadActionsRequest>,
) -> ApiResult<Json<serde_json::Value>> {
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<Uuid> = 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<AppState>,
state: State<AppState>,
user: CurrentUser,
axum::extract::Path(thread_id): axum::extract::Path<Uuid>,
thread_id: Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
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,
AppJson(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
}
+12
View File
@@ -10,6 +10,8 @@ pub struct Config {
/// Directory raw MIME blobs and attachments are stored under (§3.2).
pub blob_storage_dir: std::path::PathBuf,
pub session_ttl_hours: i64,
/// Days mail stays in Trash before it's purged for good. 0 disables.
pub trash_retention_days: u32,
}
impl Config {
@@ -42,12 +44,22 @@ impl Config {
.and_then(|v| v.parse().ok())
.unwrap_or(24 * 30);
let trash_retention_days = std::env::var("TRASH_RETENTION_DAYS")
.ok()
.map(|v| {
v.parse()
.context("TRASH_RETENTION_DAYS must be a whole number of days")
})
.transpose()?
.unwrap_or(30);
Ok(Self {
database_url,
bind_addr,
credential_key,
blob_storage_dir,
session_ttl_hours,
trash_retention_days,
})
}
}
+14
View File
@@ -45,3 +45,17 @@ impl IntoResponse for ApiError {
}
pub type ApiResult<T> = Result<T, ApiError>;
/// JSON body extractor whose failures use the API's `{"error": …}` shape.
/// Axum's own `Json` rejects malformed or mistyped bodies with a plain-text
/// 422, which clients can't show properly — and its message is exactly the
/// useful part ("unknown variant `stop`, expected one of …").
#[derive(axum::extract::FromRequest)]
#[from_request(via(axum::Json), rejection(ApiError))]
pub struct AppJson<T>(pub T);
impl From<axum::extract::rejection::JsonRejection> for ApiError {
fn from(rejection: axum::extract::rejection::JsonRejection) -> Self {
ApiError::BadRequest(rejection.body_text())
}
}
+25
View File
@@ -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(())
}
+54
View File
@@ -47,6 +47,19 @@ pub fn parse_raw_message(raw: &[u8]) -> anyhow::Result<ParsedMessage> {
})
.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<ParsedMessage> {
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::<Vec<_>>().join(" ")
}
fn first_address(addr: &Address) -> Option<(Option<String>, Option<String>)> {
addr.first().map(|a| {
(
@@ -78,3 +99,36 @@ fn all_addresses(addr: &Address) -> Vec<String> {
.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 <bob@example.com>\r\n\
Received: from a\r\n\
Received: from b\r\n\
List-Id: Weekly digest\r\n <weekly.lists.example.com>\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::<Vec<_>>()
};
assert_eq!(
get("list-id"),
vec!["Weekly digest <weekly.lists.example.com>"]
);
assert_eq!(get("received"), vec!["from a", "from b"]);
assert_eq!(get("x-spam-score"), vec!["5.3"]);
assert_eq!(get("from"), vec!["Bob <bob@example.com>"]);
}
}
+3
View File
@@ -6,5 +6,8 @@ pub mod db;
pub mod error;
pub mod imap_sync;
pub mod models;
pub mod retention;
pub mod rules;
pub mod smtp;
pub mod storage;
pub mod threading;
+6
View File
@@ -25,6 +25,12 @@ async fn main() -> anyhow::Result<()> {
// (server-architecture-spec.md §3.1) — it runs alongside the API server.
tokio::spawn(imap_sync::run(pool.clone(), cipher.clone(), blobs.clone()));
tokio::spawn(tern_server::retention::run(
pool.clone(),
blobs.clone(),
config.trash_retention_days,
));
let outbox_wake = std::sync::Arc::new(tokio::sync::Notify::new());
tokio::spawn(tern_server::smtp::worker::run(
pool.clone(),
+2
View File
@@ -8,4 +8,6 @@ pub struct Folder {
pub user_id: Uuid,
pub name: String,
pub created_at: DateTime<Utc>,
/// 'archive' for the system Archive folder, None for the user's own.
pub role: Option<String>,
}
+5
View File
@@ -26,6 +26,8 @@ pub struct Message {
/// 'imap' for synced mail, 'sent' for mail sent from Tern.
pub source: String,
pub created_at: DateTime<Utc>,
/// Set when moved to Trash.
pub deleted_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
@@ -50,6 +52,9 @@ pub struct ParsedMessage {
pub text_body: Option<String>,
pub html_body: Option<String>,
pub attachments: Vec<ParsedAttachment>,
/// 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<u8>,
}
+1
View File
@@ -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;
+10
View File
@@ -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<String>,
}
+120
View File
@@ -0,0 +1,120 @@
//! Permanently removes mail that has sat in Trash past the retention period.
//!
//! Stored files are content-addressed and shared: two identical messages or
//! attachments point at the same file. So a file is only removed once no
//! remaining row references it — and not if it was written or reused within
//! the last hour, because ingest writes a file *before* inserting the row
//! that references it. Without that grace period, a purge landing between
//! those two steps for an identical message would delete a file the new row
//! is about to depend on.
//!
//! One consequence of one-way sync: purged mail never comes back, since the
//! sync engine only fetches UIDs above the last one seen. A UIDVALIDITY
//! reset is the exception — that re-syncs the whole INBOX.
use crate::storage::BlobStore;
use sqlx::PgPool;
use std::time::Duration;
use uuid::Uuid;
const INTERVAL: Duration = Duration::from_secs(60 * 60);
const BATCH: i64 = 500;
const BLOB_GRACE: Duration = Duration::from_secs(60 * 60);
pub async fn run(pool: PgPool, blobs: BlobStore, retention_days: u32) {
if retention_days == 0 {
tracing::info!("trash retention disabled (TRASH_RETENTION_DAYS=0)");
return;
}
loop {
match purge(&pool, &blobs, retention_days).await {
Ok(0) => {}
Ok(n) => tracing::info!(
purged = n,
retention_days,
"purged expired messages from trash"
),
Err(e) => tracing::error!(error = %e, "trash purge failed"),
}
tokio::time::sleep(INTERVAL).await;
}
}
pub async fn purge(pool: &PgPool, blobs: &BlobStore, retention_days: u32) -> anyhow::Result<usize> {
let mut total = 0;
loop {
let mut tx = pool.begin().await?;
let batch: Vec<(Uuid, Option<String>)> = sqlx::query_as(
"SELECT id, raw_blob_ref FROM messages \
WHERE deleted_at < now() - make_interval(days => $1) \
ORDER BY deleted_at LIMIT $2 FOR UPDATE SKIP LOCKED",
)
.bind(retention_days as i32)
.bind(BATCH)
.fetch_all(&mut *tx)
.await?;
if batch.is_empty() {
break;
}
let ids: Vec<Uuid> = batch.iter().map(|(id, _)| *id).collect();
let mut refs: Vec<String> = batch.into_iter().filter_map(|(_, r)| r).collect();
let attachment_refs: Vec<String> =
sqlx::query_scalar("SELECT blob_ref FROM attachments WHERE message_id = ANY($1)")
.bind(&ids)
.fetch_all(&mut *tx)
.await?;
refs.extend(attachment_refs);
// Bodies, attachments and tags cascade; an outbox row pointing at a
// purged sent message keeps its record with the link set to NULL.
sqlx::query("DELETE FROM messages WHERE id = ANY($1)")
.bind(&ids)
.execute(&mut *tx)
.await?;
tx.commit().await?;
total += ids.len();
refs.sort();
refs.dedup();
remove_orphaned_blobs(pool, blobs, &refs).await?;
}
Ok(total)
}
async fn remove_orphaned_blobs(
pool: &PgPool,
blobs: &BlobStore,
refs: &[String],
) -> anyhow::Result<()> {
for r in refs {
let still_used: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM messages WHERE raw_blob_ref = $1) \
OR EXISTS (SELECT 1 FROM attachments WHERE blob_ref = $1)",
)
.bind(r)
.fetch_one(pool)
.await?;
if still_used {
continue;
}
let path = blobs.resolve(r);
let recent = tokio::fs::metadata(&path)
.await
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.elapsed().ok())
.is_some_and(|age| age < BLOB_GRACE);
if recent {
continue;
}
match tokio::fs::remove_file(&path).await {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => {
tracing::warn!(path = %path.display(), error = %e, "couldn't remove orphaned blob")
}
}
}
Ok(())
}
+822
View File
@@ -0,0 +1,822 @@
//! 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
//! marked `stop_after_match`. 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<String>,
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<Test>,
}
#[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<Uuid>,
},
Archive,
MarkRead,
MarkUnread,
/// Soft delete — to Trash, restorable.
Delete,
Restore,
}
impl Action {
fn allowed_in_rules(&self) -> bool {
matches!(
self,
Action::Tag { .. }
| Action::Move { .. }
| Action::Archive
| Action::MarkRead
| Action::Delete
)
}
}
/// 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 = format_from(p.from_name.as_deref(), p.from_addr.as_deref());
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<Action>,
patterns: Vec<Option<Regex>>,
}
static NUMBER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-?\d+(?:\.\d+)?").unwrap());
fn first_number(s: &str) -> Option<f64> {
NUMBER.find(s).and_then(|m| m.as_str().parse().ok())
}
fn compile_pattern(pattern: &str) -> Result<Regex, String> {
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::<f64>().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"));
}
if for_rule {
if let Some(a) = actions.iter().find(|a| !a.allowed_in_rules()) {
return Err(format!("{a:?} isn't available as a rule action"));
}
}
Ok(())
}
impl CompiledRule {
pub fn compile(id: Uuid, conditions: Conditions, actions: Vec<Action>) -> Result<Self, String> {
validate(&conditions, &actions, true)?;
let patterns = conditions
.tests
.iter()
.map(|t| {
(t.op == Op::Matches)
.then(|| compile_pattern(&t.value))
.transpose()
})
.collect::<Result<_, _>>()?;
Ok(Self {
id,
conditions,
actions,
patterns,
})
}
/// Header tests need the raw message re-parsed; everything else is in
/// stored columns. Lets a run over existing mail skip parsing when the
/// rule doesn't look at headers.
pub fn needs_headers(&self) -> bool {
self.conditions
.tests
.iter()
.any(|t| t.field == Field::Header)
}
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<StoredRule> = sqlx::query_as(
"SELECT id, conditions, actions, stop_after_match FROM rules \
WHERE user_id = $1 AND enabled ORDER BY priority, created_at",
)
.bind(user_id)
.fetch_all(&mut **tx)
.await?;
for StoredRule {
id,
conditions,
actions,
stop_after_match,
} 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 stop_after_match {
break;
}
}
Ok(())
}
#[derive(sqlx::FromRow)]
struct ExistingMessage {
id: Uuid,
from_addr: Option<String>,
from_name: Option<String>,
to_addrs: Vec<String>,
cc_addrs: Vec<String>,
subject: Option<String>,
raw_blob_ref: Option<String>,
text_body: Option<String>,
html_body: Option<String>,
}
pub struct RunSummary {
pub scanned: usize,
pub matched: usize,
}
const RUN_PAGE: i64 = 500;
/// Applies one rule to the user's existing received mail — "run now".
///
/// Covers everything not in Trash, including mail already filed away, since
/// that's what "apply this rule to what I already have" means. Sent mail is
/// left alone: rules are for incoming mail. Messages whose body hasn't been
/// fetched yet are skipped; they'll meet the rule on ingest anyway.
///
/// Walks by id (keyset, not offset) in pages, one transaction per page, so
/// a large mailbox doesn't hold one enormous transaction. Stored raw
/// messages are only re-read and re-parsed when the rule has a header test.
pub async fn run_on_existing(
pool: &PgPool,
blobs: &crate::storage::BlobStore,
user_id: Uuid,
rule: &CompiledRule,
) -> sqlx::Result<RunSummary> {
let mut after = Uuid::nil();
let mut summary = RunSummary {
scanned: 0,
matched: 0,
};
let needs_headers = rule.needs_headers();
loop {
let page: Vec<ExistingMessage> = sqlx::query_as(
"SELECT m.id, m.from_addr, m.from_name, m.to_addrs, m.cc_addrs, m.subject, \
m.raw_blob_ref, b.text_body, b.html_body \
FROM messages m \
JOIN accounts a ON a.id = m.account_id \
LEFT JOIN bodies b ON b.message_id = m.id \
WHERE a.user_id = $1 AND m.source = 'imap' AND m.deleted_at IS NULL \
AND m.body_fetched AND m.id > $2 \
ORDER BY m.id LIMIT $3",
)
.bind(user_id)
.bind(after)
.bind(RUN_PAGE)
.fetch_all(pool)
.await?;
let Some(last) = page.last() else { break };
after = last.id;
summary.scanned += page.len();
let mut matched = Vec::new();
for m in &page {
let headers = match (&m.raw_blob_ref, needs_headers) {
(Some(r), true) => match blobs.read(r).await {
Ok(raw) => crate::imap_sync::parse::parse_raw_message(&raw)
.map(|p| p.headers)
.unwrap_or_default(),
Err(e) => {
tracing::warn!(message = %m.id, error = %e, "raw message unreadable; header tests won't match");
Vec::new()
}
},
_ => Vec::new(),
};
let facts = Facts {
from: format_from(m.from_name.as_deref(), m.from_addr.as_deref()),
to: m.to_addrs.join(", "),
cc: m.cc_addrs.join(", "),
subject: m.subject.clone().unwrap_or_default(),
body: m
.text_body
.clone()
.or_else(|| m.html_body.clone())
.unwrap_or_default(),
headers,
};
if rule.matches(&facts) {
matched.push(m.id);
}
}
if !matched.is_empty() {
let mut tx = pool.begin().await?;
apply_actions(&mut tx, user_id, &matched, &rule.actions).await?;
tx.commit().await?;
summary.matched += matched.len();
}
}
Ok(summary)
}
fn format_from(name: Option<&str>, addr: Option<&str>) -> String {
match (name, addr) {
(Some(n), Some(a)) => format!("{n} <{a}>"),
(None, Some(a)) => a.to_string(),
(Some(n), None) => n.to_string(),
(None, None) => String::new(),
}
}
#[derive(sqlx::FromRow)]
pub struct StoredRule {
pub id: Uuid,
pub conditions: sqlx::types::Json<Conditions>,
pub actions: sqlx::types::Json<Vec<Action>>,
pub stop_after_match: bool,
}
/// 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?;
}
}
}
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<Uuid> {
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 <news@lists.example.com>".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(), "<weekly.lists.example.com>".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<Test>) -> 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<Test>, actions: Vec<Action>| {
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 }];
let json = serde_json::to_string(&a).unwrap();
assert_eq!(
json,
r#"[{"type":"archive"},{"type":"move","folder_id":null}]"#
);
assert_eq!(serde_json::from_str::<Vec<Action>>(&json).unwrap(), a);
}
#[test]
fn stop_is_no_longer_an_action() {
// It's a rule option now (stop_after_match). A submitted
// {"type":"stop"} must be rejected rather than silently ignored.
assert!(serde_json::from_str::<Action>(r#"{"type":"stop"}"#).is_err());
}
#[test]
fn only_header_tests_need_a_reparse() {
assert!(!rule(Match::All, vec![test(Field::Subject, Op::Contains, "x")]).needs_headers());
assert!(rule(
Match::Any,
vec![
test(Field::Subject, Op::Contains, "x"),
header("List-Id", Op::Exists, "")
]
)
.needs_headers());
}
}
+13
View File
@@ -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)
+16 -1
View File
@@ -35,7 +35,22 @@ impl BlobStore {
let hash = Self::hash(data);
let full_path = self.path_for_hash(&hash);
if !tokio::fs::try_exists(&full_path).await.unwrap_or(false) {
if tokio::fs::try_exists(&full_path).await.unwrap_or(false) {
// Reusing an existing file refreshes its mtime: the trash purge
// won't remove a blob touched within its grace period, which
// covers the gap between this write and the row that will
// reference it being inserted.
let path = full_path.clone();
tokio::task::spawn_blocking(move || {
std::fs::File::options()
.write(true)
.open(&path)
.and_then(|f| f.set_modified(std::time::SystemTime::now()))
})
.await
.context("touching existing blob")?
.with_context(|| format!("touching blob {}", full_path.display()))?;
} else {
if let Some(parent) = full_path.parent() {
tokio::fs::create_dir_all(parent)
.await
+306
View File
@@ -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::<Vec<_>>()
.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<Uuid> {
let own_id = input.message_id.map(bare_id).filter(|s| !s.is_empty());
let mut candidates: Vec<String> = 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<Uuid> = 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<String>,
in_reply_to: Option<String>,
references_: Vec<String>,
subject: Option<String>,
}
/// 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<ThreadingRow> = 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:"), "");
}
}
+11
View File
@@ -34,6 +34,7 @@ fn test_router() -> axum::Router {
credential_key: [0u8; 32],
blob_storage_dir: std::path::PathBuf::from("/tmp/tern-test"),
session_ttl_hours: 1,
trash_retention_days: 30,
},
outbox_wake: std::sync::Arc::new(tokio::sync::Notify::new()),
};
@@ -63,6 +64,14 @@ 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}")),
("POST", format!("/api/rules/{id}/run")),
] {
let status = status_for(method, &uri).await;
assert_ne!(
@@ -83,6 +92,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!(