From 3f1d9227c67350a731cd9cf03b98bbca39ef3aa2 Mon Sep 17 00:00:00 2001 From: Mateusz Pstrucha Date: Wed, 23 Sep 2026 12:00:04 +0200 Subject: [PATCH] Add trash retention, stop-after-match and run-now MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .env.example | 3 + README.md | 14 ++- migrations/0007_rule_options.sql | 13 ++ src/api/accounts.rs | 4 +- src/api/auth.rs | 6 +- src/api/folders.rs | 6 +- src/api/outbox.rs | 6 +- src/api/router.rs | 1 + src/api/rules.rs | 58 +++++++-- src/api/tags.rs | 6 +- src/api/threads.rs | 14 ++- src/config.rs | 12 ++ src/error.rs | 14 +++ src/lib.rs | 1 + src/main.rs | 6 + src/retention.rs | 120 +++++++++++++++++++ src/rules.rs | 199 ++++++++++++++++++++++++++----- src/storage.rs | 17 ++- tests/routes.rs | 2 + 19 files changed, 442 insertions(+), 60 deletions(-) create mode 100644 migrations/0007_rule_options.sql create mode 100644 src/retention.rs diff --git a/.env.example b/.env.example index 0f0996d..8530181 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/README.md b/README.md index e02be86..1e39c38 100644 --- a/README.md +++ b/README.md @@ -12,16 +12,22 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT - **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, stop). Run on new mail after its body is fetched; every matching rule applies in priority order until a `stop`. Manual thread actions (`POST /api/threads/:id/actions`) use the same action format and code. +- **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. +- **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. -- **Rules apply to new mail only.** There's no "run this rule on existing mail" yet — the spec marks it optional; it's the natural next addition if you want it. +- **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** — notifications arrive with phases 7–8. +- **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 diff --git a/migrations/0007_rule_options.sql b/migrations/0007_rule_options.sql new file mode 100644 index 0000000..a1e3176 --- /dev/null +++ b/migrations/0007_rule_options.sql @@ -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; diff --git a/src/api/accounts.rs b/src/api/accounts.rs index 23c7d84..7c039de 100644 --- a/src/api/accounts.rs +++ b/src/api/accounts.rs @@ -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, user: CurrentUser, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { let encrypted = state.cipher.encrypt(&req.password)?; diff --git a/src/api/auth.rs b/src/api/auth.rs index 58eba07..b7869fe 100644 --- a/src/api/auth.rs +++ b/src/api/auth.rs @@ -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, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { 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, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { let user: Option = sqlx::query_as("SELECT * FROM users WHERE username = $1") .bind(&req.username) diff --git a/src/api/folders.rs b/src/api/folders.rs index 169bb9b..b69d2b6 100644 --- a/src/api/folders.rs +++ b/src/api/folders.rs @@ -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; @@ -26,7 +26,7 @@ pub async fn list( pub async fn create( State(state): State, user: CurrentUser, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { let folder: Folder = sqlx::query_as("INSERT INTO folders (user_id, name) VALUES ($1, $2) RETURNING *") @@ -46,7 +46,7 @@ pub async fn rename( State(state): State, user: CurrentUser, axum::extract::Path(id): axum::extract::Path, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { let name = req.name.trim(); if name.is_empty() || name.len() > 100 { diff --git a/src/api/outbox.rs b/src/api/outbox.rs index d61d6ed..f785b36 100644 --- a/src/api/outbox.rs +++ b/src/api/outbox.rs @@ -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, user: CurrentUser, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { 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, user: CurrentUser, Path(id): Path, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { let to = compose::normalize_recipients(&req.to).map_err(ApiError::BadRequest)?; let cc = compose::normalize_recipients(&req.cc).map_err(ApiError::BadRequest)?; diff --git a/src/api/router.rs b/src/api/router.rs index a64b4dd..cc41ba5 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -20,6 +20,7 @@ pub fn build(state: AppState) -> Router { .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)) diff --git a/src/api/rules.rs b/src/api/rules.rs index b05aef7..2642b8d 100644 --- a/src/api/rules.rs +++ b/src/api/rules.rs @@ -4,7 +4,7 @@ use crate::api::middleware::CurrentUser; use crate::api::state::AppState; -use crate::error::{ApiError, ApiResult}; +use crate::error::{ApiError, ApiResult, AppJson}; use crate::rules::{self, Action, Conditions}; use axum::{ extract::{Path, State}, @@ -22,6 +22,8 @@ pub struct Rule { pub conditions: SqlJson, pub actions: SqlJson>, pub enabled: bool, + /// Skip lower-priority rules once this one matches. + pub stop_after_match: bool, pub priority: i32, pub created_at: DateTime, } @@ -33,6 +35,8 @@ pub struct RuleRequest { pub actions: Vec, #[serde(default = "enabled_default")] pub enabled: bool, + #[serde(default)] + pub stop_after_match: bool, } fn enabled_default() -> bool { @@ -45,7 +49,8 @@ pub struct ReorderRequest { pub ids: Vec, } -const RULE_COLUMNS: &str = "id, name, conditions, actions, enabled, priority, created_at"; +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(); @@ -75,12 +80,12 @@ pub async fn list(State(state): State, user: CurrentUser) -> ApiResult pub async fn create( State(state): State, user: CurrentUser, - Json(req): Json, + AppJson(req): AppJson, ) -> 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, \ + "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}" )) @@ -89,6 +94,7 @@ pub async fn create( .bind(SqlJson(&req.conditions)) .bind(SqlJson(&req.actions)) .bind(req.enabled) + .bind(req.stop_after_match) .fetch_one(&state.pool) .await?; Ok(Json(rule)) @@ -98,11 +104,12 @@ pub async fn update( State(state): State, user: CurrentUser, Path(id): Path, - Json(req): Json, + AppJson(req): AppJson, ) -> 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 \ + "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) @@ -111,6 +118,7 @@ pub async fn update( .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) @@ -139,7 +147,7 @@ pub async fn delete( pub async fn reorder( State(state): State, user: CurrentUser, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult>> { let mut tx = state.pool.begin().await?; let mut existing: Vec = @@ -170,3 +178,37 @@ pub async fn reorder( 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, + user: CurrentUser, + Path(id): Path, +) -> ApiResult> { + 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, + })) +} diff --git a/src/api/tags.rs b/src/api/tags.rs index 1882ce7..215e6b6 100644 --- a/src/api/tags.rs +++ b/src/api/tags.rs @@ -1,6 +1,6 @@ use crate::api::middleware::CurrentUser; use crate::api::state::AppState; -use crate::error::{ApiError, ApiResult}; +use crate::error::{ApiError, ApiResult, AppJson}; use crate::models::tag::Tag; use axum::{ extract::{Path, State}, @@ -63,7 +63,7 @@ pub async fn list(State(state): State, user: CurrentUser) -> ApiResult pub async fn create( State(state): State, user: CurrentUser, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { let (name, color) = validate(&req)?; let tag = @@ -81,7 +81,7 @@ pub async fn update( State(state): State, user: CurrentUser, Path(id): Path, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { let (name, color) = validate(&req)?; let tag: Option = sqlx::query_as( diff --git a/src/api/threads.rs b/src/api/threads.rs index 1c2ff5b..8e81e74 100644 --- a/src/api/threads.rs +++ b/src/api/threads.rs @@ -15,7 +15,7 @@ use crate::api::middleware::CurrentUser; use crate::api::state::AppState; -use crate::error::{ApiError, ApiResult}; +use crate::error::{ApiError, ApiResult, AppJson}; use crate::rules::{self, Action}; use axum::{ extract::{Path, Query, State}, @@ -72,6 +72,9 @@ pub struct ThreadSummary { pub unread_count: i64, pub has_attachments: bool, pub tag_ids: Vec, + /// 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>, } #[derive(Serialize)] @@ -139,7 +142,9 @@ pub async fn list( 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 + ) 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) @@ -155,6 +160,7 @@ pub async fn list( .bind(q.tag_id) .bind(before) .bind(limit) + .bind(state.config.trash_retention_days as i32) .fetch_all(&state.pool) .await?; @@ -178,7 +184,7 @@ pub async fn act( State(state): State, user: CurrentUser, Path(thread_id): Path, - Json(req): Json, + AppJson(req): AppJson, ) -> ApiResult> { let no_conditions = rules::Conditions { match_: rules::Match::All, @@ -220,7 +226,7 @@ pub async fn mark_read( state, user, thread_id, - Json(ThreadActionsRequest { + AppJson(ThreadActionsRequest { actions: vec![Action::MarkRead], }), ) diff --git a/src/config.rs b/src/config.rs index f890391..3392a54 100644 --- a/src/config.rs +++ b/src/config.rs @@ -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, }) } } diff --git a/src/error.rs b/src/error.rs index 4814440..c4a977c 100644 --- a/src/error.rs +++ b/src/error.rs @@ -45,3 +45,17 @@ impl IntoResponse for ApiError { } pub type ApiResult = Result; + +/// 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(pub T); + +impl From for ApiError { + fn from(rejection: axum::extract::rejection::JsonRejection) -> Self { + ApiError::BadRequest(rejection.body_text()) + } +} diff --git a/src/lib.rs b/src/lib.rs index 6d377df..308aadd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -6,6 +6,7 @@ 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; diff --git a/src/main.rs b/src/main.rs index aa8786d..0f41218 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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(), diff --git a/src/retention.rs b/src/retention.rs new file mode 100644 index 0000000..2d0112e --- /dev/null +++ b/src/retention.rs @@ -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 { + let mut total = 0; + loop { + let mut tx = pool.begin().await?; + let batch: Vec<(Uuid, Option)> = 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 = batch.iter().map(|(id, _)| *id).collect(); + let mut refs: Vec = batch.into_iter().filter_map(|(_, r)| r).collect(); + let attachment_refs: Vec = + 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(()) +} diff --git a/src/rules.rs b/src/rules.rs index 5817617..905c88a 100644 --- a/src/rules.rs +++ b/src/rules.rs @@ -7,10 +7,9 @@ //! 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. +//! 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. @@ -103,8 +102,6 @@ pub enum Action { /// Soft delete — to Trash, restorable. Delete, Restore, - /// Rules only: stop evaluating lower-priority rules. - Stop, } impl Action { @@ -116,7 +113,6 @@ impl Action { | Action::Archive | Action::MarkRead | Action::Delete - | Action::Stop ) } } @@ -134,12 +130,7 @@ pub struct Facts { 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(), - }; + let from = format_from(p.from_name.as_deref(), p.from_addr.as_deref()); Facts { from, to: p.to_addrs.join(", "), @@ -215,13 +206,10 @@ pub fn validate(conditions: &Conditions, actions: &[Action], for_rule: bool) -> if actions.len() > MAX_ACTIONS { return Err(format!("at most {MAX_ACTIONS} actions")); } - for a in actions { - if for_rule && !a.allowed_in_rules() { + 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")); } - if !for_rule && *a == Action::Stop { - return Err("stop only makes sense inside a rule".into()); - } } Ok(()) } @@ -246,6 +234,16 @@ impl CompiledRule { }) } + /// 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 @@ -309,14 +307,21 @@ pub async fn apply_rules( 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", + let rows: Vec = 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 (id, conditions, actions) in rows { + 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) => { @@ -329,13 +334,134 @@ pub async fn apply_rules( } 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) { + if stop_after_match { break; } } Ok(()) } +#[derive(sqlx::FromRow)] +struct ExistingMessage { + id: Uuid, + from_addr: Option, + from_name: Option, + to_addrs: Vec, + cc_addrs: Vec, + subject: Option, + raw_blob_ref: Option, + text_body: Option, + html_body: Option, +} + +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 { + let mut after = Uuid::nil(); + let mut summary = RunSummary { + scanned: 0, + matched: 0, + }; + let needs_headers = rule.needs_headers(); + + loop { + let page: Vec = 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, + pub actions: sqlx::types::Json>, + 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. @@ -413,7 +539,6 @@ pub async fn apply_actions( .execute(&mut **tx) .await?; } - Action::Stop => {} } } Ok(()) @@ -666,16 +791,32 @@ mod tests { #[test] fn actions_round_trip_through_json_as_tagged_objects() { - let a = vec![ - Action::Archive, - Action::Move { folder_id: None }, - Action::Stop, - ]; + 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},{"type":"stop"}]"# + r#"[{"type":"archive"},{"type":"move","folder_id":null}]"# ); assert_eq!(serde_json::from_str::>(&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::(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()); + } } diff --git a/src/storage.rs b/src/storage.rs index 0c65559..e9a2bc2 100644 --- a/src/storage.rs +++ b/src/storage.rs @@ -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 diff --git a/tests/routes.rs b/tests/routes.rs index e03c1fd..b28b9bc 100644 --- a/tests/routes.rs +++ b/tests/routes.rs @@ -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()), }; @@ -70,6 +71,7 @@ async fn parameterised_routes_match() { ("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!(