diff --git a/Cargo.lock b/Cargo.lock index e9f08e4..907ef2f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -204,6 +204,7 @@ dependencies = [ "async-trait", "axum-core", "axum-macros", + "base64 0.22.1", "bytes", "futures-util", "http", @@ -222,8 +223,10 @@ dependencies = [ "serde_json", "serde_path_to_error", "serde_urlencoded", + "sha1", "sync_wrapper", "tokio", + "tokio-tungstenite", "tower", "tower-layer", "tower-service", @@ -2877,6 +2880,18 @@ dependencies = [ "tokio-stream", ] +[[package]] +name = "tokio-tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc5f74e248dc973e0dbb7b74c7e0d6fcc301c694ff50049504004ef4d0cdcd9" +dependencies = [ + "futures-util", + "log", + "tokio", + "tungstenite", +] + [[package]] name = "tower" version = "0.5.3" @@ -2983,6 +2998,24 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "tungstenite" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18e5b8366ee7a95b16d32197d0b2604b43a0be89dc5fac9f8e96ccafbaedda8a" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand", + "sha1", + "thiserror 1.0.69", + "utf-8", +] + [[package]] name = "typenum" version = "1.20.1" @@ -3044,6 +3077,12 @@ dependencies = [ "serde", ] +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + [[package]] name = "utf8_iter" version = "1.0.4" diff --git a/Cargo.toml b/Cargo.toml index 102c73d..42c1323 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ description = "Tern sync server — the only component that speaks IMAP/SMTP" [dependencies] tokio = { version = "1", features = ["full"] } -axum = { version = "0.7", features = ["macros"] } +axum = { version = "0.7", features = ["macros", "ws"] } tower = "0.5" tower-http = { version = "0.6", features = ["trace", "cors"] } diff --git a/README.md b/README.md index 0377a14..12cab06 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,11 @@ 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–6) +## What's built (build-order phases 1–7) - **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. -- **Minimal REST API** (`src/api/`): local username/password auth (Argon2 + bearer session tokens), account management (IMAP credentials encrypted at rest with ChaCha20-Poly1305), folder listing, cursor-paginated message listing, single-message + thread-by-id fetch, and a polling `/events` delta endpoint. +- **Minimal REST API** (`src/api/`): local username/password auth (Argon2 + bearer session tokens), account management (IMAP credentials encrypted at rest with ChaCha20-Poly1305), folder listing, cursor-paginated message listing, single-message + thread-by-id fetch. - **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. @@ -14,6 +14,7 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT - **Spam filtering** (`src/spam.rs`, §3.5) — every message's spam score is extracted at ingest from whichever filter header it carries, and a *spam score* rule condition compares it numerically. The webapp's **Add spam filter** creates the spec's threshold rule — score over 5 → Junk, placed first, stopping later rules — as an ordinary rule you can edit. Junk is a system folder like Archive. - **Tags, folders and views** — thread listing takes `view=inbox|all|sent|junk|trash|folder|tag`, paged by an opaque keyset cursor. 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. +- **Change notifications** (`src/events.rs`, `/api/ws`, `/api/events`, §3.8) — every change is appended to an event log and pushed to open WebSockets; the same log serves the polling fallback, so a client switches between the two without losing its place. See [Notifications](#notifications). ## How rules behave @@ -22,7 +23,7 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT - **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. +- **Notify / don't notify.** New mail notifies if it's unread and still in the inbox after rules run. A *don't notify* action silences a message that would; *notify* alerts for one a rule filed away. If several matching rules say different things, the last one applied wins. Both are rule-only, and do nothing when a rule is run on existing mail. ## Spam scores @@ -58,9 +59,25 @@ A few consequences worth knowing, because they aren't visible from the UI: - **Delivery is at-least-once.** If the server accepts a message but the process dies before recording it, it's re-sent. Every attempt reuses the same Message-ID, so a duplicate is at least recognisable as the same message. Exactly-once isn't achievable over SMTP. - **SMTP port conventions:** STARTTLS by default, implicit TLS when the port is 465 — overridable per account with `smtp_use_starttls`. IMAP is implicit TLS only (993); STARTTLS on 143 isn't supported. +## Notifications + +Clients learn about changes from one event log, over either transport: + +- **`GET /api/ws`** — a WebSocket. Browsers can't set headers on one, and a token in the URL would land in proxy logs, so the client authenticates in-band: its first message is `{"type":"auth","token":"","since":}`. The server replies `{"type":"ready","cursor":N,"reset":false}`, replays anything after `since`, then streams `{"type":"event","id":…,"kind":…,"data":…}` as changes happen. It pings every 25 s (inside nginx's default 60 s read timeout) and closes with code 4401 when the session ends. +- **`GET /api/events?since=`** — the polling fallback and delta endpoint: `{events, cursor, reset, more}`. Without `since` it just returns the current cursor. + +Event kinds are `message_new` (with the final `notify` decision, sender and subject), `mailbox_changed` (thread ids, or `null` for "reload everything"), `outbox_changed` and `config_changed` (tags, folders, rules or accounts). They say *what* changed, not the new state; clients re-fetch through the normal API. + +Worth knowing: + +- **Only mail that arrives live notifies.** An account's first sync, and a UIDVALIDITY re-sync, are backlog: they're announced once per batch as `mailbox_changed` and never alert, however recent the mail. +- **Cursors survive seven days.** Events are purged after that; a client presenting an older (or unknown) cursor gets `reset: true` and should reload everything. Replays longer than 1,000 events also reset — reloading is quicker. +- **Ids are ordered by commit, not by start.** Events are inserted under a lock, one at a time, so a client that has seen id N has seen everything before it. Without that, two concurrent inserts could commit out of order and a resuming client would skip one forever. +- **One server process.** Live delivery is an in-process broadcast. Several instances behind a load balancer would each only push their own changes (polling would still be complete) — Postgres `LISTEN/NOTIFY` is the fix if that's ever needed. + ## What's explicitly deferred -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. +Per the spec's suggested build order (§9), not yet built: the Android client and UnifiedPush (phase 8), which will push content-free wake-ups for `message_new` events whose `notify` is true. Also deferred, and worth knowing because they aren't obvious from the code: diff --git a/migrations/0009_events.sql b/migrations/0009_events.sql new file mode 100644 index 0000000..4825f46 --- /dev/null +++ b/migrations/0009_events.sql @@ -0,0 +1,28 @@ +-- Change events for WebSocket push and the polling fallback +-- (server-architecture-spec.md §3.8, webapp-client-spec.md §3). +-- +-- One append-only log per server, read per user. The id is the cursor +-- clients resume from, so it has to be monotonic in commit order — the +-- server serialises inserts (see src/events.rs) rather than relying on the +-- sequence alone, which hands out ids in *start* order across concurrent +-- transactions. +CREATE TABLE events ( + id BIGSERIAL PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + kind TEXT NOT NULL, + payload JSONB NOT NULL DEFAULT '{}', + created_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX events_user_id_id_idx ON events(user_id, id); +CREATE INDEX events_created_at_idx ON events(created_at); + +-- Set when a message is discovered by an incremental sync pass, as opposed +-- to the first sync of an account or a UIDVALIDITY re-sync — only mail that +-- genuinely just arrived is a candidate for a "new mail" notification. +ALTER TABLE messages ADD COLUMN arrived_live BOOLEAN NOT NULL DEFAULT false; + +-- Whether the account has finished its first full pass. Until then every +-- message found is backlog, however recent, and shouldn't notify. +ALTER TABLE sync_state ADD COLUMN caught_up BOOLEAN NOT NULL DEFAULT false; +UPDATE sync_state SET caught_up = last_synced_uid > 0; diff --git a/nginx.conf b/nginx.conf index b567aea..a21e679 100644 --- a/nginx.conf +++ b/nginx.conf @@ -3,6 +3,13 @@ # plain-HTTP local-dev shape) and forwards to the API, which never needs to # be reachable directly. +# Only ask for an upgrade when the client did; plain requests keep +# ordinary keep-alive semantics. +map $http_upgrade $connection_upgrade { + default upgrade; + '' close; +} + server { listen 80; server_name _; @@ -15,8 +22,10 @@ server { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; - # WebSocket upgrade support, once the WS notification endpoint lands. + # WebSocket upgrade for /api/ws (live notifications). The server + # pings every 25 s, so the default 60 s proxy_read_timeout never + # cuts an idle socket. proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection "upgrade"; + proxy_set_header Connection $connection_upgrade; } } diff --git a/src/api/accounts.rs b/src/api/accounts.rs index 7c039de..1d2c88b 100644 --- a/src/api/accounts.rs +++ b/src/api/accounts.rs @@ -1,6 +1,7 @@ use crate::api::middleware::CurrentUser; use crate::api::state::AppState; use crate::error::{ApiResult, AppJson}; +use crate::events::{Change, ConfigKind}; use crate::models::account::{Account, AccountPublic}; use axum::{extract::State, Json}; use serde::Deserialize; @@ -74,6 +75,10 @@ pub async fn create( .execute(&state.pool) .await?; + state + .events + .emit(user.user_id, Change::config(ConfigKind::Accounts)) + .await; Ok(Json(account.into())) } @@ -88,5 +93,9 @@ pub async fn delete( .execute(&state.pool) .await?; + state + .events + .emit(user.user_id, Change::config(ConfigKind::Accounts)) + .await; Ok(Json(serde_json::json!({ "ok": true }))) } diff --git a/src/api/events.rs b/src/api/events.rs index 4645c1c..59c3fbe 100644 --- a/src/api/events.rs +++ b/src/api/events.rs @@ -1,54 +1,283 @@ -//! `GET /events?since=` — the delta/sync endpoint from -//! server-architecture-spec.md §4 and the polling-fallback path from §3.8. -//! WebSocket push is a later build-order phase (§9 item 7); this polling -//! endpoint is what mobile/degraded clients use meanwhile, and stays the -//! fallback afterwards. +//! Change notifications (server-architecture-spec.md §3.8, +//! webapp-client-spec.md §3): `GET /api/ws` pushes events as they happen, +//! `GET /api/events?since=` is the polling fallback and the delta +//! endpoint for clients that were away (§4). Both read the same log, so a +//! client can switch between them mid-stream without losing its place. +//! +//! Cursors are event ids. A client with no cursor asks without `since` and +//! gets the current head; a client whose cursor is too old (events purged) +//! or otherwise unusable gets `reset: true` and should reload everything. -use crate::api::middleware::CurrentUser; +use crate::api::middleware::{session_user, CurrentUser}; use crate::api::state::AppState; use crate::error::ApiResult; -use crate::models::Message; +use crate::events::{self, Event}; +use axum::extract::ws::{CloseFrame, Message, WebSocket, WebSocketUpgrade}; use axum::{ extract::{Query, State}, + response::Response, Json, }; -use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; +use std::time::Duration; +use tokio::sync::broadcast::error::RecvError; +use uuid::Uuid; + +/// Replaying more than this is slower than a client reloading its view. +const MAX_REPLAY: i64 = 1000; +const DEFAULT_POLL_LIMIT: i64 = 500; + +/// Where a client should resume from, given the cursor it presented. +async fn resume_point(state: &AppState, since: Option) -> sqlx::Result<(i64, bool)> { + let head = state.events.head().await?; + Ok(match since { + None => (head, false), + // A cursor from the future means another database (restored backup, + // reinstall) — nothing it says about "what I've seen" holds here. + Some(s) if s > head || events::is_stale(&state.pool, s).await? => (head, true), + Some(s) => (s, false), + }) +} #[derive(Deserialize)] -pub struct EventsQuery { - pub since: Option>, +pub struct PollQuery { + pub since: Option, + pub limit: Option, } #[derive(Serialize)] -pub struct EventsResponse { - pub changed_messages: Vec, - pub cursor: DateTime, +pub struct PollResponse { + pub events: Vec, + /// Pass back as `since` next time. + pub cursor: i64, + /// The cursor couldn't be honoured; reload everything, then carry on + /// from `cursor`. + pub reset: bool, + /// More events are waiting — poll again straight away. + pub more: bool, } pub async fn poll( State(state): State, user: CurrentUser, - Query(q): Query, -) -> ApiResult> { - let since = q - .since - .unwrap_or_else(|| Utc::now() - chrono::Duration::days(1)); - let cursor = Utc::now(); - - let changed_messages: Vec = sqlx::query_as( - "SELECT m.* FROM messages m JOIN accounts a ON a.id = m.account_id \ - WHERE a.user_id = $1 AND m.created_at > $2 \ - ORDER BY m.created_at ASC \ - LIMIT 500", - ) - .bind(user.user_id) - .bind(since) - .fetch_all(&state.pool) - .await?; - - Ok(Json(EventsResponse { - changed_messages, - cursor, + Query(q): Query, +) -> ApiResult> { + let limit = q.limit.unwrap_or(DEFAULT_POLL_LIMIT).clamp(1, MAX_REPLAY); + let (from, reset) = resume_point(&state, q.since).await?; + if reset || q.since.is_none() { + return Ok(Json(PollResponse { + events: vec![], + cursor: from, + reset, + more: false, + })); + } + let events = events::after(&state.pool, user.user_id, from, limit).await?; + Ok(Json(PollResponse { + cursor: events.last().map_or(from, |e| e.id), + more: events.len() as i64 == limit, + events, + reset: false, })) } + +// --- WebSocket ------------------------------------------------------------- + +/// A client has this long after connecting to authenticate. +const AUTH_TIMEOUT: Duration = Duration::from_secs(10); +/// Server pings this often — comfortably inside nginx's default 60 s +/// proxy_read_timeout, so an idle socket isn't cut by the proxy. Each tick +/// also re-checks the session, so logging out or expiry ends the stream. +const HEARTBEAT: Duration = Duration::from_secs(25); + +/// Application close codes (4000–4999 are free for applications). +const CLOSE_UNAUTHORIZED: u16 = 4401; +const CLOSE_BAD_HELLO: u16 = 4400; + +/// First (and only) message a client sends. Browsers can't put an +/// Authorization header on a WebSocket, and a token in the URL would end up +/// in proxy access logs, so the session token travels in-band. +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +enum ClientMsg { + Auth { token: Uuid, since: Option }, +} + +#[derive(Serialize)] +#[serde(tag = "type", rename_all = "snake_case")] +enum ServerMsg<'a> { + /// Authenticated. Same meaning as the poll response's fields; replayed + /// events (if any) follow immediately. + Ready { + cursor: i64, + reset: bool, + }, + Event(&'a Event), +} + +pub async fn socket(State(state): State, ws: WebSocketUpgrade) -> Response { + ws.on_upgrade(move |socket| async move { + if let Err(e) = serve(state, socket).await { + tracing::debug!(error = %e, "websocket ended with error"); + } + }) +} + +async fn send(socket: &mut WebSocket, msg: &ServerMsg<'_>) -> anyhow::Result<()> { + let text = serde_json::to_string(msg)?; + socket.send(Message::Text(text)).await?; + Ok(()) +} + +async fn close(socket: &mut WebSocket, code: u16, reason: &'static str) { + let _ = socket + .send(Message::Close(Some(CloseFrame { + code, + reason: reason.into(), + }))) + .await; +} + +async fn serve(state: AppState, mut socket: WebSocket) -> anyhow::Result<()> { + let hello = match tokio::time::timeout(AUTH_TIMEOUT, socket.recv()).await { + Ok(Some(Ok(Message::Text(t)))) => serde_json::from_str::(&t).ok(), + Ok(_) => None, + Err(_) => { + close(&mut socket, CLOSE_BAD_HELLO, "authenticate first").await; + return Ok(()); + } + }; + let Some(ClientMsg::Auth { token, since }) = hello else { + close(&mut socket, CLOSE_BAD_HELLO, "expected auth message").await; + return Ok(()); + }; + let Some(user_id) = session_user(&state.pool, token).await? else { + close(&mut socket, CLOSE_UNAUTHORIZED, "unauthorized").await; + return Ok(()); + }; + + // Subscribe before reading the backlog: anything emitted in between is + // then seen twice (once from each) rather than not at all, and the id + // check below drops the duplicate. + let mut live = state.events.subscribe(); + let (mut cursor, reset) = resume_point(&state, since).await?; + send(&mut socket, &ServerMsg::Ready { cursor, reset }).await?; + if !reset && since.is_some() { + cursor = catch_up(&state, &mut socket, user_id, cursor).await?; + } + + let mut heartbeat = tokio::time::interval(HEARTBEAT); + heartbeat.tick().await; // the first tick is immediate + loop { + tokio::select! { + received = live.recv() => match received { + Ok(event) => { + if event.user_id == user_id && event.id > cursor { + send(&mut socket, &ServerMsg::Event(&event)).await?; + cursor = event.id; + } + } + // Fell behind the broadcast buffer: the log has everything. + Err(RecvError::Lagged(_)) => { + cursor = catch_up(&state, &mut socket, user_id, cursor).await?; + } + Err(RecvError::Closed) => return Ok(()), + }, + incoming = socket.recv() => match incoming { + // Completes the closing handshake: tungstenite queues its + // reply on reading the client's Close frame but only sends it + // while the stream keeps being polled, so read to the end + // rather than dropping — otherwise the client sees 1006. + Some(Ok(Message::Close(_))) => { + while let Some(Ok(_)) = socket.recv().await {} + return Ok(()); + } + None | Some(Err(_)) => return Ok(()), + // Pongs and anything else a client sends are ignored; axum + // answers pings itself. + Some(Ok(_)) => {} + }, + _ = heartbeat.tick() => { + if session_user(&state.pool, token).await? != Some(user_id) { + close(&mut socket, CLOSE_UNAUTHORIZED, "session ended").await; + return Ok(()); + } + socket.send(Message::Ping(Vec::new())).await?; + } + } + } +} + +/// Sends everything after `cursor` from the log, or a reset if that's more +/// than is worth replaying. Returns the new cursor. +async fn catch_up( + state: &AppState, + socket: &mut WebSocket, + user_id: Uuid, + mut cursor: i64, +) -> anyhow::Result { + let backlog = events::after(&state.pool, user_id, cursor, MAX_REPLAY + 1).await?; + if backlog.len() as i64 > MAX_REPLAY { + let head = state.events.head().await?; + send( + socket, + &ServerMsg::Ready { + cursor: head, + reset: true, + }, + ) + .await?; + return Ok(head); + } + for event in &backlog { + send(socket, &ServerMsg::Event(event)).await?; + cursor = event.id; + } + Ok(cursor) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn server_messages_are_flat_and_tagged() { + let event = Event { + id: 7, + user_id: Uuid::nil(), + kind: "outbox_changed".into(), + payload: serde_json::json!({ "status": "sent" }), + created_at: chrono::DateTime::UNIX_EPOCH, + }; + let v = serde_json::to_value(ServerMsg::Event(&event)).unwrap(); + assert_eq!(v["type"], "event"); + assert_eq!(v["id"], 7); + assert_eq!(v["kind"], "outbox_changed"); + assert_eq!(v["data"]["status"], "sent"); + assert!(v.get("user_id").is_none(), "user id isn't sent to clients"); + + let v = serde_json::to_value(ServerMsg::Ready { + cursor: 3, + reset: true, + }) + .unwrap(); + assert_eq!( + v, + serde_json::json!({ "type": "ready", "cursor": 3, "reset": true }) + ); + } + + #[test] + fn client_hello_parses_with_and_without_cursor() { + let t = Uuid::new_v4(); + let m: ClientMsg = + serde_json::from_str(&format!(r#"{{"type":"auth","token":"{t}","since":12}}"#)) + .unwrap(); + let ClientMsg::Auth { token, since } = m; + assert_eq!((token, since), (t, Some(12))); + let m: ClientMsg = + serde_json::from_str(&format!(r#"{{"type":"auth","token":"{t}"}}"#)).unwrap(); + let ClientMsg::Auth { since, .. } = m; + assert_eq!(since, None); + } +} diff --git a/src/api/folders.rs b/src/api/folders.rs index b69d2b6..664bf29 100644 --- a/src/api/folders.rs +++ b/src/api/folders.rs @@ -1,6 +1,7 @@ use crate::api::middleware::CurrentUser; use crate::api::state::AppState; use crate::error::{ApiResult, AppJson}; +use crate::events::{Change, ConfigKind}; use crate::models::Folder; use axum::{extract::State, Json}; use serde::Deserialize; @@ -34,6 +35,10 @@ pub async fn create( .bind(&req.name) .fetch_one(&state.pool) .await?; + state + .events + .emit(user.user_id, Change::config(ConfigKind::Folders)) + .await; Ok(Json(folder)) } @@ -61,7 +66,12 @@ pub async fn rename( .bind(name) .fetch_optional(&state.pool) .await?; - folder.map(Json).ok_or(crate::error::ApiError::NotFound) + let folder = folder.ok_or(crate::error::ApiError::NotFound)?; + state + .events + .emit(user.user_id, Change::config(ConfigKind::Folders)) + .await; + Ok(Json(folder)) } /// Messages in a deleted folder go back to the inbox (FK ON DELETE SET @@ -84,5 +94,9 @@ pub async fn delete( "folder not found, or it's the Archive folder, which can't be deleted".into(), )); } + state + .events + .emit(user.user_id, Change::config(ConfigKind::Folders)) + .await; Ok(Json(serde_json::json!({ "ok": true }))) } diff --git a/src/api/middleware.rs b/src/api/middleware.rs index b8ee247..018e031 100644 --- a/src/api/middleware.rs +++ b/src/api/middleware.rs @@ -31,15 +31,23 @@ impl FromRequestParts for CurrentUser { .ok_or(ApiError::Unauthorized)?; let token = Uuid::parse_str(token_str).map_err(|_| ApiError::Unauthorized)?; - let row: Option<(Uuid, chrono::DateTime)> = - sqlx::query_as("SELECT user_id, expires_at FROM sessions WHERE token = $1") - .bind(token) - .fetch_optional(&state.pool) - .await?; - - match row { - Some((user_id, expires_at)) if expires_at > Utc::now() => Ok(CurrentUser { user_id }), - _ => Err(ApiError::Unauthorized), - } + session_user(&state.pool, token) + .await? + .map(|user_id| CurrentUser { user_id }) + .ok_or(ApiError::Unauthorized) } } + +/// The user a session token belongs to, if the session exists and hasn't +/// expired. Shared with the WebSocket, which authenticates in-band because +/// browsers can't set headers on a socket. +pub async fn session_user(pool: &sqlx::PgPool, token: Uuid) -> sqlx::Result> { + let row: Option<(Uuid, chrono::DateTime)> = + sqlx::query_as("SELECT user_id, expires_at FROM sessions WHERE token = $1") + .bind(token) + .fetch_optional(pool) + .await?; + Ok(row + .filter(|(_, expires_at)| *expires_at > Utc::now()) + .map(|(user_id, _)| user_id)) +} diff --git a/src/api/outbox.rs b/src/api/outbox.rs index f785b36..b38247a 100644 --- a/src/api/outbox.rs +++ b/src/api/outbox.rs @@ -10,6 +10,7 @@ use crate::api::middleware::CurrentUser; use crate::api::state::AppState; use crate::error::{ApiError, ApiResult, AppJson}; +use crate::events::Change; use crate::models::account::Account; use crate::models::outbox::OutboxItem; use crate::models::Message; @@ -121,6 +122,7 @@ pub async fn create( if req.send { return queue(&state, &account, item).await.map(Json); } + changed(&state, &item).await; Ok(Json(item)) } @@ -152,7 +154,9 @@ pub async fn update( .fetch_optional(&state.pool) .await?; - item.map(Json).ok_or_else(|| editable_or_not_found(id)) + let item = item.ok_or_else(|| editable_or_not_found(id))?; + changed(&state, &item).await; + Ok(Json(item)) } pub async fn send( @@ -190,9 +194,32 @@ pub async fn delete( if deleted == 0 { return Err(editable_or_not_found(id)); } + state + .events + .emit( + user.user_id, + Change::OutboxChanged { + id, + status: "deleted".into(), + }, + ) + .await; Ok(Json(serde_json::json!({ "ok": true }))) } +async fn changed(state: &AppState, item: &OutboxItem) { + state + .events + .emit( + item.user_id, + Change::OutboxChanged { + id: item.id, + status: item.status.clone(), + }, + ) + .await; +} + /// Validates that the message is actually sendable, assigns its Message-ID /// (once — retries reuse it), marks it pending and wakes the worker so it /// goes out now rather than at the next poll. @@ -209,6 +236,9 @@ async fn queue(state: &AppState, account: &Account, item: OutboxItem) -> ApiResu .fetch_one(&state.pool) .await?; + // Announced before the worker is woken, so "pending" can't land in the + // event log after the worker's own "sent". + changed(state, &item).await; state.outbox_wake.notify_one(); Ok(item) } diff --git a/src/api/router.rs b/src/api/router.rs index cc41ba5..274e18e 100644 --- a/src/api/router.rs +++ b/src/api/router.rs @@ -35,6 +35,7 @@ pub fn build(state: AppState) -> Router { ) .route("/api/outbox/:id/send", post(outbox::send)) .route("/api/events", get(events::poll)) + .route("/api/ws", get(events::socket)) .route("/healthz", get(|| async { "ok" })) .layer(TraceLayer::new_for_http()) .layer(CorsLayer::permissive()) diff --git a/src/api/rules.rs b/src/api/rules.rs index 2642b8d..e817379 100644 --- a/src/api/rules.rs +++ b/src/api/rules.rs @@ -5,6 +5,7 @@ use crate::api::middleware::CurrentUser; use crate::api::state::AppState; use crate::error::{ApiError, ApiResult, AppJson}; +use crate::events::{Change, ConfigKind}; use crate::rules::{self, Action, Conditions}; use axum::{ extract::{Path, State}, @@ -97,6 +98,10 @@ pub async fn create( .bind(req.stop_after_match) .fetch_one(&state.pool) .await?; + state + .events + .emit(user.user_id, Change::config(ConfigKind::Rules)) + .await; Ok(Json(rule)) } @@ -121,7 +126,12 @@ pub async fn update( .bind(req.stop_after_match) .fetch_optional(&state.pool) .await?; - rule.map(Json).ok_or(ApiError::NotFound) + let rule = rule.ok_or(ApiError::NotFound)?; + state + .events + .emit(user.user_id, Change::config(ConfigKind::Rules)) + .await; + Ok(Json(rule)) } pub async fn delete( @@ -138,6 +148,10 @@ pub async fn delete( if deleted == 0 { return Err(ApiError::NotFound); } + state + .events + .emit(user.user_id, Change::config(ConfigKind::Rules)) + .await; Ok(Json(serde_json::json!({ "ok": true }))) } @@ -175,6 +189,10 @@ pub async fn reorder( .execute(&mut *tx) .await?; tx.commit().await?; + state + .events + .emit(user.user_id, Change::config(ConfigKind::Rules)) + .await; list(State(state), user).await } @@ -206,6 +224,12 @@ pub async fn run( .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"); + if summary.matched > 0 { + state + .events + .emit(user.user_id, Change::MailboxChanged { thread_ids: None }) + .await; + } Ok(Json(RunResponse { scanned: summary.scanned, diff --git a/src/api/state.rs b/src/api/state.rs index fc416b9..2b28760 100644 --- a/src/api/state.rs +++ b/src/api/state.rs @@ -1,5 +1,6 @@ use crate::config::Config; use crate::crypto::CredentialCipher; +use crate::events::EventHub; use crate::storage::BlobStore; use sqlx::PgPool; use std::sync::Arc; @@ -15,4 +16,5 @@ pub struct AppState { /// Wakes the outbox worker as soon as something is queued, so a send /// goes out immediately rather than at the next idle poll. pub outbox_wake: Arc, + pub events: EventHub, } diff --git a/src/api/tags.rs b/src/api/tags.rs index 215e6b6..3b365f1 100644 --- a/src/api/tags.rs +++ b/src/api/tags.rs @@ -1,6 +1,7 @@ use crate::api::middleware::CurrentUser; use crate::api::state::AppState; use crate::error::{ApiError, ApiResult, AppJson}; +use crate::events::{Change, ConfigKind}; use crate::models::tag::Tag; use axum::{ extract::{Path, State}, @@ -74,6 +75,10 @@ pub async fn create( .fetch_one(&state.pool) .await .map_err(conflict)?; + state + .events + .emit(user.user_id, Change::config(ConfigKind::Tags)) + .await; Ok(Json(tag)) } @@ -94,7 +99,12 @@ pub async fn update( .fetch_optional(&state.pool) .await .map_err(conflict)?; - tag.map(Json).ok_or(ApiError::NotFound) + let tag = tag.ok_or(ApiError::NotFound)?; + state + .events + .emit(user.user_id, Change::config(ConfigKind::Tags)) + .await; + Ok(Json(tag)) } /// Removes the tag from every message (cascade). Rules still naming it @@ -113,5 +123,9 @@ pub async fn delete( if deleted == 0 { return Err(ApiError::NotFound); } + state + .events + .emit(user.user_id, Change::config(ConfigKind::Tags)) + .await; Ok(Json(serde_json::json!({ "ok": true }))) } diff --git a/src/api/threads.rs b/src/api/threads.rs index 692f46e..7b150e2 100644 --- a/src/api/threads.rs +++ b/src/api/threads.rs @@ -16,6 +16,7 @@ use crate::api::middleware::CurrentUser; use crate::api::state::AppState; use crate::error::{ApiError, ApiResult, AppJson}; +use crate::events::Change; use crate::rules::{self, Action}; use axum::{ extract::{Path, Query, State}, @@ -262,6 +263,10 @@ pub async fn act( let mut tx = state.pool.begin().await?; rules::apply_actions(&mut tx, user.user_id, &ids, &req.actions).await?; tx.commit().await?; + state + .events + .emit(user.user_id, Change::threads([thread_id])) + .await; Ok(Json(serde_json::json!({ "messages": ids.len() }))) } diff --git a/src/events.rs b/src/events.rs new file mode 100644 index 0000000..4152f3a --- /dev/null +++ b/src/events.rs @@ -0,0 +1,254 @@ +//! Change events: what the WebSocket pushes and `GET /api/events` returns +//! (server-architecture-spec.md §3.8, webapp-client-spec.md §3). +//! +//! Every event is written to the `events` table first and then broadcast +//! in-process to connected sockets. The table is what makes the cursor +//! meaningful: a client that drops off resumes from the last id it saw, +//! over either transport, and gets exactly what it missed. +//! +//! Events say *that* something changed and where, not the new state — +//! clients re-fetch through the normal API. The exception is `message_new`, +//! which carries sender and subject so an open tab can show a notification +//! without a round trip. Nothing here goes to a third party; content-free +//! UnifiedPush pushes are built from these separately. + +use serde::Serialize; +use sqlx::PgPool; +use std::sync::Arc; +use tokio::sync::{broadcast, Mutex}; +use uuid::Uuid; + +/// How long events are kept. A client whose cursor is older than this is +/// told to reset (reload everything) instead of replaying. +pub const RETENTION_DAYS: i32 = 7; + +/// Live-broadcast buffer. A socket that falls further behind than this +/// catches up from the table instead, so it's a throughput knob, not a +/// correctness one. +const BROADCAST_CAPACITY: usize = 1024; + +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(tag = "kind", content = "data", rename_all = "snake_case")] +pub enum Change { + /// A message finished ingesting (body fetched, threaded, rules run). + /// `notify` is the final decision after rules — clients alert on it and + /// only on it. + MessageNew { + message_id: Uuid, + thread_id: Option, + account_id: Uuid, + notify: bool, + from: Option, + subject: Option, + }, + /// Thread contents or state changed — flags, tags, folder, trash, new + /// messages that aren't notification-worthy. `None` means "could be + /// anything; reload". + MailboxChanged { + thread_ids: Option>, + }, + OutboxChanged { + id: Uuid, + status: String, + }, + /// Tags, folders, rules or accounts were edited. + ConfigChanged { + what: ConfigKind, + }, +} + +#[derive(Debug, Clone, Copy, Serialize, PartialEq)] +#[serde(rename_all = "snake_case")] +pub enum ConfigKind { + Tags, + Folders, + Rules, + Accounts, +} + +/// Thread-id lists longer than this are sent as "reload everything" — a +/// bulk rule run shouldn't produce a megabyte event. +const MAX_THREAD_IDS: usize = 200; + +impl Change { + pub fn config(what: ConfigKind) -> Self { + Change::ConfigChanged { what } + } + + pub fn threads(ids: impl IntoIterator) -> Self { + let mut ids: Vec = ids.into_iter().collect(); + ids.sort(); + ids.dedup(); + Change::MailboxChanged { + thread_ids: (ids.len() <= MAX_THREAD_IDS).then_some(ids), + } + } + + fn split(&self) -> (String, serde_json::Value) { + let mut v = serde_json::to_value(self).expect("Change always serialises"); + let kind = v["kind"].as_str().unwrap_or_default().to_string(); + let data = v + .get_mut("data") + .map(serde_json::Value::take) + .unwrap_or_else(|| serde_json::json!({})); + (kind, data) + } +} + +/// An event as stored and as sent to clients. +#[derive(Debug, Clone, Serialize, sqlx::FromRow)] +pub struct Event { + pub id: i64, + #[serde(skip)] + pub user_id: Uuid, + pub kind: String, + #[serde(rename = "data")] + pub payload: serde_json::Value, + pub created_at: chrono::DateTime, +} + +#[derive(Clone)] +pub struct EventHub { + pool: PgPool, + tx: broadcast::Sender>, + /// Held across insert + broadcast so ids become visible, and are + /// broadcast, in increasing order. Without it two concurrent emits + /// could commit 8 before 7, and a client that read 8 would resume + /// past 7 forever. Emits are one short insert, so contention is cheap. + order: Arc>, +} + +impl EventHub { + pub fn new(pool: PgPool) -> Self { + let (tx, _) = broadcast::channel(BROADCAST_CAPACITY); + Self { + pool, + tx, + order: Arc::new(Mutex::new(())), + } + } + + pub fn subscribe(&self) -> broadcast::Receiver> { + self.tx.subscribe() + } + + /// The cursor a client with no history should start from: the last id + /// handed out. Read from the sequence rather than the table so it + /// stays correct once old events are purged, and under the ordering + /// lock so it can't name an insert that hasn't committed yet. + pub async fn head(&self) -> sqlx::Result { + let _guard = self.order.lock().await; + sqlx::query_scalar( + "SELECT CASE WHEN is_called THEN last_value ELSE 0 END FROM events_id_seq", + ) + .fetch_one(&self.pool) + .await + } + + /// Records and broadcasts a change. Call only after the transaction that + /// made the change has committed — otherwise a client can fetch before + /// the change is visible. Failures are logged, not returned: the change + /// itself already happened, and clients recover on their next reload. + pub async fn emit(&self, user_id: Uuid, change: Change) { + let (kind, payload) = change.split(); + let _guard = self.order.lock().await; + let row: Result = sqlx::query_as( + "INSERT INTO events (user_id, kind, payload) VALUES ($1, $2, $3) \ + RETURNING id, user_id, kind, payload, created_at", + ) + .bind(user_id) + .bind(&kind) + .bind(&payload) + .fetch_one(&self.pool) + .await; + match row { + // No receivers is fine — nobody has a socket open. + Ok(event) => { + let _ = self.tx.send(Arc::new(event)); + } + Err(e) => tracing::error!(error = %e, %kind, "failed to record event"), + } + } +} + +/// The user's events after `since`, oldest first, capped at `limit`. +pub async fn after( + pool: &PgPool, + user_id: Uuid, + since: i64, + limit: i64, +) -> sqlx::Result> { + sqlx::query_as( + "SELECT id, user_id, kind, payload, created_at FROM events \ + WHERE user_id = $1 AND id > $2 ORDER BY id LIMIT $3", + ) + .bind(user_id) + .bind(since) + .bind(limit) + .fetch_all(pool) + .await +} + +/// Whether events after `since` may already have been purged, so replaying +/// from it would silently miss changes. Conservative: it can say yes when +/// nothing was actually lost (e.g. ids skipped by a failed insert), which +/// only costs the client a reload. +pub async fn is_stale(pool: &PgPool, since: i64) -> sqlx::Result { + // Oldest id still kept; if the table is empty, everything up to the + // sequence's current value is gone (or never existed). + let floor: i64 = sqlx::query_scalar( + "SELECT COALESCE((SELECT MIN(id) FROM events), \ + (SELECT CASE WHEN is_called THEN last_value + 1 ELSE last_value END \ + FROM events_id_seq))", + ) + .fetch_one(pool) + .await?; + Ok(since < floor - 1) +} + +pub async fn purge_expired(pool: &PgPool) -> sqlx::Result { + Ok( + sqlx::query("DELETE FROM events WHERE created_at < now() - make_interval(days => $1)") + .bind(RETENTION_DAYS) + .execute(pool) + .await? + .rows_affected(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn changes_split_into_kind_and_data() { + let id = Uuid::nil(); + let (kind, data) = Change::OutboxChanged { + id, + status: "sent".into(), + } + .split(); + assert_eq!(kind, "outbox_changed"); + assert_eq!(data, serde_json::json!({ "id": id, "status": "sent" })); + + let (kind, data) = Change::ConfigChanged { + what: ConfigKind::Tags, + } + .split(); + assert_eq!(kind, "config_changed"); + assert_eq!(data, serde_json::json!({ "what": "tags" })); + } + + #[test] + fn long_thread_lists_become_reload_everything() { + let few = Change::threads([Uuid::nil(), Uuid::nil()]); + assert_eq!( + few, + Change::MailboxChanged { + thread_ids: Some(vec![Uuid::nil()]) + } + ); + let many = Change::threads((0..=MAX_THREAD_IDS).map(|_| Uuid::new_v4())); + assert_eq!(many, Change::MailboxChanged { thread_ids: None }); + } +} diff --git a/src/imap_sync/connection.rs b/src/imap_sync/connection.rs index 6e8acee..6df3b96 100644 --- a/src/imap_sync/connection.rs +++ b/src/imap_sync/connection.rs @@ -13,6 +13,7 @@ //! backlog doesn't block new-mail visibility. use crate::crypto::CredentialCipher; +use crate::events::{Change, EventHub}; use crate::imap_sync::backoff::Backoff; use crate::imap_sync::parse::parse_raw_message; use crate::models::account::Account; @@ -71,6 +72,18 @@ pub struct AccountSyncer { pub pool: PgPool, pub cipher: CredentialCipher, pub blobs: BlobStore, + pub events: EventHub, +} + +/// What ingesting a body produced, for the change event that follows once +/// its transaction has committed. +struct Ingested { + message_id: Uuid, + thread_id: Option, + arrived_live: bool, + notify: bool, + from: Option, + subject: Option, } impl AccountSyncer { @@ -208,8 +221,8 @@ impl AccountSyncer { .execute(&mut *tx) .await?; sqlx::query( - "UPDATE sync_state SET uidvalidity = $2, last_synced_uid = 0, updated_at = now() \ - WHERE account_id = $1", + "UPDATE sync_state SET uidvalidity = $2, last_synced_uid = 0, caught_up = false, \ + updated_at = now() WHERE account_id = $1", ) .bind(self.account.id) .bind(server_uidvalidity) @@ -222,20 +235,21 @@ impl AccountSyncer { Ok(()) } - async fn last_synced_uid(&self) -> Result { - let row: (i64,) = - sqlx::query_as("SELECT last_synced_uid FROM sync_state WHERE account_id = $1") - .bind(self.account.id) - .fetch_one(&self.pool) - .await?; - Ok(row.0) + /// The last UID stored, and whether the first full pass has finished. + async fn sync_position(&self) -> Result<(i64, bool)> { + Ok(sqlx::query_as( + "SELECT last_synced_uid, caught_up FROM sync_state WHERE account_id = $1", + ) + .bind(self.account.id) + .fetch_one(&self.pool) + .await?) } /// Headers-first catch-up pass: fetch ENVELOPE + FLAGS for any UID beyond /// the last one we've stored, insert stub message rows (body_fetched = /// false). Bodies are filled in by `fetch_pending_bodies`. async fn fetch_new_headers(&self, session: &mut ImapSession) -> Result<()> { - let last_uid = self.last_synced_uid().await?; + let (last_uid, caught_up) = self.sync_position().await?; let range = format!("{}:*", last_uid + 1); let fetches: Vec<_> = session @@ -274,8 +288,9 @@ impl AccountSyncer { sqlx::query( "INSERT INTO messages \ - (account_id, uid, message_id, in_reply_to, subject, flags, body_fetched) \ - VALUES ($1, $2, $3, $4, $5, $6, false) \ + (account_id, uid, message_id, in_reply_to, subject, flags, body_fetched, \ + arrived_live) \ + VALUES ($1, $2, $3, $4, $5, $6, false, $7) \ ON CONFLICT (account_id, uid) DO UPDATE SET flags = EXCLUDED.flags", ) .bind(self.account.id) @@ -284,6 +299,7 @@ impl AccountSyncer { .bind(&in_reply_to) .bind(&subject) .bind(&flags) + .bind(caught_up) .execute(&self.pool) .await?; } @@ -295,6 +311,12 @@ impl AccountSyncer { .execute(&self.pool) .await?; } + if !caught_up { + sqlx::query("UPDATE sync_state SET caught_up = true WHERE account_id = $1") + .bind(self.account.id) + .execute(&self.pool) + .await?; + } Ok(()) } @@ -331,6 +353,9 @@ impl AccountSyncer { .await .context("reading UID FETCH body response")?; + // Backlog is announced once per batch rather than per message, + // so an initial sync of thousands doesn't send thousands of events. + let mut backlog_threads = Vec::new(); for f in &fetches { let (Some(uid), Some(raw)) = (f.uid, f.body()) else { continue; @@ -339,14 +364,37 @@ impl AccountSyncer { continue; }; - if let Err(e) = self.store_body(*row_id, raw).await { - tracing::error!(account_id = %self.account.id, uid, error = %e, "failed to store message body"); + match self.store_body(*row_id, raw).await { + Ok(m) if m.arrived_live => { + self.events + .emit( + self.account.user_id, + Change::MessageNew { + message_id: m.message_id, + thread_id: m.thread_id, + account_id: self.account.id, + notify: m.notify, + from: m.from, + subject: m.subject, + }, + ) + .await; + } + Ok(m) => backlog_threads.extend(m.thread_id), + Err(e) => { + tracing::error!(account_id = %self.account.id, uid, error = %e, "failed to store message body") + } } } + if !backlog_threads.is_empty() { + self.events + .emit(self.account.user_id, Change::threads(backlog_threads)) + .await; + } } } - async fn store_body(&self, message_row_id: Uuid, raw: &[u8]) -> Result<()> { + async fn store_body(&self, message_row_id: Uuid, raw: &[u8]) -> Result { let parsed = parse_raw_message(raw)?; let (_, raw_blob_ref) = self.blobs.put(&parsed.raw).await?; @@ -427,7 +475,7 @@ impl AccountSyncer { ) .await?; - crate::rules::apply_rules( + let rules_say = crate::rules::apply_rules( &mut tx, self.account.user_id, message_row_id, @@ -435,8 +483,34 @@ impl AccountSyncer { ) .await?; + // Where the message ended up after rules decides the default: new, + // unread mail that stayed in the inbox notifies; anything a rule + // filed away, junked, deleted or marked read doesn't. A notify / + // don't-notify action overrides that either way — but backlog + // never notifies, whatever the rules say. + let (thread_id, arrived_live, in_inbox_unread): (Option, bool, bool) = + sqlx::query_as( + r#"SELECT thread_id, arrived_live, + folder_id IS NULL AND deleted_at IS NULL AND NOT ('\Seen' = ANY(flags)) + FROM messages WHERE id = $1"#, + ) + .bind(message_row_id) + .fetch_one(&mut *tx) + .await?; + tx.commit().await?; - Ok(()) + Ok(Ingested { + message_id: message_row_id, + thread_id, + arrived_live, + notify: arrived_live && rules_say.unwrap_or(in_inbox_unread), + from: parsed + .from_name + .clone() + .filter(|n| !n.trim().is_empty()) + .or_else(|| parsed.from_addr.clone()), + subject: parsed.subject.clone(), + }) } /// Issues IDLE and waits for either a mailbox change or the renewal diff --git a/src/imap_sync/manager.rs b/src/imap_sync/manager.rs index 4658ce7..657506d 100644 --- a/src/imap_sync/manager.rs +++ b/src/imap_sync/manager.rs @@ -2,6 +2,7 @@ //! accounts periodically rather than requiring a restart to pick them up. use crate::crypto::CredentialCipher; +use crate::events::EventHub; use crate::imap_sync::connection::AccountSyncer; use crate::models::account::Account; use crate::storage::BlobStore; @@ -12,7 +13,7 @@ use uuid::Uuid; const ACCOUNT_POLL_INTERVAL: Duration = Duration::from_secs(30); -pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore) { +pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, events: EventHub) { let mut running: HashMap> = HashMap::new(); loop { @@ -33,6 +34,7 @@ pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore) { pool: pool.clone(), cipher: cipher.clone(), blobs: blobs.clone(), + events: events.clone(), }; let id = syncer.account.id; let handle = tokio::spawn(syncer.run()); diff --git a/src/lib.rs b/src/lib.rs index 62c45ac..003cebd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ pub mod config; pub mod crypto; pub mod db; pub mod error; +pub mod events; pub mod imap_sync; pub mod models; pub mod retention; diff --git a/src/main.rs b/src/main.rs index 0f41218..59d49b5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,10 +20,16 @@ async fn main() -> anyhow::Result<()> { let pool = db::connect(&config.database_url).await?; let cipher = CredentialCipher::new(&config.credential_key); let blobs = BlobStore::new(config.blob_storage_dir.clone()); + let events = tern_server::events::EventHub::new(pool.clone()); // The sync manager owns one long-running task per IMAP account // (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(imap_sync::run( + pool.clone(), + cipher.clone(), + blobs.clone(), + events.clone(), + )); tokio::spawn(tern_server::retention::run( pool.clone(), @@ -37,6 +43,7 @@ async fn main() -> anyhow::Result<()> { cipher.clone(), blobs.clone(), outbox_wake.clone(), + events.clone(), )); let state = AppState { @@ -46,6 +53,7 @@ async fn main() -> anyhow::Result<()> { session_ttl_hours: config.session_ttl_hours, config: config.clone(), outbox_wake, + events, }; let app = api::build(state); diff --git a/src/retention.rs b/src/retention.rs index 2d0112e..671338e 100644 --- a/src/retention.rs +++ b/src/retention.rs @@ -21,20 +21,26 @@ const INTERVAL: Duration = Duration::from_secs(60 * 60); const BATCH: i64 = 500; const BLOB_GRACE: Duration = Duration::from_secs(60 * 60); +/// Hourly housekeeping: expired Trash, and change events older than +/// clients are expected to resume from (`events::RETENTION_DAYS`). 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"), + if retention_days > 0 { + 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"), + } + } + if let Err(e) = crate::events::purge_expired(&pool).await { + tracing::error!(error = %e, "event purge failed"); } tokio::time::sleep(INTERVAL).await; } diff --git a/src/rules.rs b/src/rules.rs index ff212c7..5af98ac 100644 --- a/src/rules.rs +++ b/src/rules.rs @@ -107,6 +107,12 @@ pub enum Action { /// Soft delete — to Trash, restorable. Delete, Restore, + /// Alert about this message even though it didn't stay in the inbox + /// (e.g. filed straight into a folder by an earlier action). + Notify, + /// Don't alert about this message — it still arrives and shows as + /// unread, it just doesn't ping anyone. + DontNotify, } impl Action { @@ -119,8 +125,16 @@ impl Action { | Action::Junk | Action::MarkRead | Action::Delete + | Action::Notify + | Action::DontNotify ) } + + /// Actions that only mean something while a message is being ingested. + /// They're rule-only, and a no-op when a rule is run on existing mail. + fn is_notification(&self) -> bool { + matches!(self, Action::Notify | Action::DontNotify) + } } /// What a rule can see about a message. @@ -227,6 +241,8 @@ pub fn validate(conditions: &Conditions, actions: &[Action], for_rule: bool) -> if let Some(a) = actions.iter().find(|a| !a.allowed_in_rules()) { return Err(format!("{a:?} isn't available as a rule action")); } + } else if let Some(a) = actions.iter().find(|a| a.is_notification()) { + return Err(format!("{a:?} only applies to incoming mail, in a rule")); } Ok(()) } @@ -330,12 +346,18 @@ fn cmp_number(value: &str, threshold: &str) -> Option<(f64, f64)> { /// the ingest transaction. A rule that no longer compiles (e.g. written /// before a validation change) is skipped and logged rather than blocking /// mail. +/// +/// Returns the rules' say on notifying: `Some(true)` for notify, +/// `Some(false)` for don't-notify, `None` if no matching rule expressed +/// one. When several do, the last one applied wins — the same way a later +/// `move` overrides an earlier one. pub async fn apply_rules( tx: &mut Transaction<'_, Postgres>, user_id: Uuid, message_row_id: Uuid, facts: &Facts, -) -> sqlx::Result<()> { +) -> sqlx::Result> { + let mut notify = None; 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", @@ -363,11 +385,20 @@ 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?; + notify = notification_choice(&rule.actions).or(notify); if stop_after_match { break; } } - Ok(()) + Ok(notify) +} + +fn notification_choice(actions: &[Action]) -> Option { + actions.iter().rev().find_map(|a| match a { + Action::Notify => Some(true), + Action::DontNotify => Some(false), + _ => None, + }) } #[derive(sqlx::FromRow)] @@ -580,6 +611,8 @@ pub async fn apply_actions( .execute(&mut **tx) .await?; } + // Decided by the caller from `apply_rules`' return value. + Action::Notify | Action::DontNotify => {} } } Ok(()) @@ -943,4 +976,39 @@ mod tests { ) .needs_headers()); } + + #[test] + fn notification_actions_are_rule_only_and_last_one_wins() { + let only = |actions: Vec, for_rule: bool| { + let tests = if for_rule { + vec![test(Field::Subject, Op::Contains, "x")] + } else { + vec![] + }; + validate( + &Conditions { + match_: Match::All, + tests, + }, + &actions, + for_rule, + ) + }; + assert!(only(vec![Action::DontNotify], true).is_ok()); + assert!(only(vec![Action::Archive, Action::Notify], true).is_ok()); + assert!( + only(vec![Action::DontNotify], false).is_err(), + "a thread action can't suppress a notification that already happened" + ); + + assert_eq!(notification_choice(&[Action::Archive]), None); + assert_eq!( + notification_choice(&[Action::Notify, Action::MarkRead, Action::DontNotify]), + Some(false) + ); + assert_eq!( + serde_json::to_string(&Action::DontNotify).unwrap(), + r#"{"type":"dont_notify"}"# + ); + } } diff --git a/src/smtp/worker.rs b/src/smtp/worker.rs index 7a3c4cb..dc920c5 100644 --- a/src/smtp/worker.rs +++ b/src/smtp/worker.rs @@ -9,6 +9,7 @@ //! clients. True exactly-once isn't achievable over SMTP. use crate::crypto::CredentialCipher; +use crate::events::{Change, EventHub}; use crate::models::account::Account; use crate::models::outbox::OutboxItem; use crate::smtp::compose::{self, Draft, Sender}; @@ -65,7 +66,13 @@ pub fn classify(err: &mail_send::Error) -> Failure { } } -pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, wake: Arc) { +pub async fn run( + pool: PgPool, + cipher: CredentialCipher, + blobs: BlobStore, + wake: Arc, + events: EventHub, +) { if let Err(e) = recover_stale(&pool).await { tracing::error!(error = %e, "failed to recover stale outbox items"); } @@ -79,6 +86,7 @@ pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, wake: // the row stays 'sending' and recover_stale picks it up. tracing::error!(outbox_id = %id, error = %e, "failed to record send outcome"); } + announce(&pool, &events, id).await; continue; } Ok(None) => {} @@ -92,6 +100,32 @@ pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, wake: } } +/// Tells the sender's clients how the attempt went — and, once sent, that +/// the conversation it belongs to has a new message. +async fn announce(pool: &PgPool, events: &EventHub, id: uuid::Uuid) { + let row: Result)>, _> = sqlx::query_as( + "SELECT o.user_id, o.status, m.thread_id FROM outbox o \ + LEFT JOIN messages m ON m.id = o.sent_message_id WHERE o.id = $1", + ) + .bind(id) + .fetch_optional(pool) + .await; + match row { + Ok(Some((user_id, status, thread_id))) => { + events + .emit(user_id, Change::OutboxChanged { id, status }) + .await; + if let Some(thread_id) = thread_id { + events.emit(user_id, Change::threads([thread_id])).await; + } + } + Ok(None) => {} + Err(e) => { + tracing::error!(outbox_id = %id, error = %e, "failed to read outbox item for event") + } + } +} + async fn recover_stale(pool: &PgPool) -> anyhow::Result<()> { let recovered = sqlx::query( "UPDATE outbox SET status = 'pending', next_attempt_at = now(), updated_at = now() \ diff --git a/tests/routes.rs b/tests/routes.rs index b28b9bc..649568d 100644 --- a/tests/routes.rs +++ b/tests/routes.rs @@ -24,6 +24,7 @@ fn test_router() -> axum::Router { .expect("lazy pool"); let state = tern_server::api::AppState { + events: tern_server::events::EventHub::new(pool.clone()), pool, cipher: tern_server::crypto::CredentialCipher::new(&[0u8; 32]), blobs: tern_server::storage::BlobStore::new(std::path::PathBuf::from("/tmp/tern-test")), @@ -91,6 +92,7 @@ async fn collection_routes_match() { "/api/messages", "/api/threads", "/api/events", + "/api/ws", "/api/outbox", "/api/tags", "/api/rules",