Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a2e32cc6f | ||
|
|
90fc65dbf5 | ||
|
|
77c1813539 | ||
|
|
e2bee05b30 | ||
|
|
4b6eeaca15 | ||
|
|
3f1d9227c6 | ||
|
|
5809c9e310 | ||
|
|
807775726c | ||
|
|
d839d57e11 | ||
|
|
fd8ee8311c | ||
|
|
bc39a1221c | ||
|
|
6c73a91b8e |
No files matched your search
@@ -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
|
||||
@@ -30,10 +30,16 @@ jobs:
|
||||
-u '${{ gitea.actor }}' --password-stdin
|
||||
|
||||
- name: Build and push image
|
||||
env:
|
||||
DOCKER_BUILDKIT: '1'
|
||||
run: |
|
||||
IMAGE='${{ steps.meta.outputs.image }}'
|
||||
VERSION='${{ steps.meta.outputs.version }}'
|
||||
docker build -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
|
||||
# --progress=plain: without it BuildKit renders an animated TTY
|
||||
# progress display, repainting every step on each frame. In a log
|
||||
# file that became ~15k lines of cursor-movement escapes for a
|
||||
# build that only has a few hundred lines of real output.
|
||||
docker build --progress=plain -t "$IMAGE:$VERSION" -t "$IMAGE:latest" .
|
||||
docker push "$IMAGE:$VERSION"
|
||||
docker push "$IMAGE:latest"
|
||||
|
||||
|
||||
Generated
+70
-1
@@ -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",
|
||||
@@ -1981,6 +1984,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"
|
||||
@@ -2077,6 +2092,18 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-native-certs"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
|
||||
dependencies = [
|
||||
"openssl-probe",
|
||||
"rustls-pki-types",
|
||||
"schannel",
|
||||
"security-framework",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pemfile"
|
||||
version = "1.0.4"
|
||||
@@ -2663,10 +2690,11 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tern-server"
|
||||
version = "0.2.0"
|
||||
version = "0.7.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"argon2",
|
||||
"async-channel 2.5.0",
|
||||
"async-imap",
|
||||
"async-native-tls",
|
||||
"axum",
|
||||
@@ -2679,12 +2707,17 @@ dependencies = [
|
||||
"mail-parser 0.11.9",
|
||||
"mail-send",
|
||||
"rand",
|
||||
"regex",
|
||||
"rustls 0.23.45",
|
||||
"rustls-native-certs",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"smtp-proto",
|
||||
"sqlx",
|
||||
"thiserror 2.0.20",
|
||||
"tokio",
|
||||
"tokio-rustls 0.26.5",
|
||||
"tokio-test",
|
||||
"tower",
|
||||
"tower-http",
|
||||
@@ -2847,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"
|
||||
@@ -2953,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"
|
||||
@@ -3014,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"
|
||||
|
||||
+13
-2
@@ -1,21 +1,30 @@
|
||||
[package]
|
||||
name = "tern-server"
|
||||
version = "0.2.0"
|
||||
version = "0.7.0"
|
||||
edition = "2021"
|
||||
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"] }
|
||||
|
||||
sqlx = { version = "0.8", features = ["runtime-tokio", "tls-rustls", "postgres", "chrono", "uuid", "migrate"] }
|
||||
|
||||
async-imap = { version = "0.11", default-features = false, features = ["runtime-tokio"] }
|
||||
async-channel = "2" # same major as async-imap uses, for its unsolicited-response channel
|
||||
async-native-tls = { version = "0.6", default-features = false, features = ["runtime-tokio"] }
|
||||
mail-parser = "0.11"
|
||||
mail-send = "0.4"
|
||||
# mail-send trusts only its compiled-in webpki-roots; these let SMTP use the
|
||||
# OS trust store instead, matching IMAP (native-tls) so a mail server with an
|
||||
# internal-CA certificate works for both. default-features = false matters:
|
||||
# rustls' defaults pull in aws-lc-rs, which needs cmake/clang to build.
|
||||
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"
|
||||
@@ -39,3 +48,5 @@ futures = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio-test = "0.4"
|
||||
# Same version mail-send uses, so tests can construct its reply type.
|
||||
smtp-proto = "0.1"
|
||||
@@ -2,22 +2,96 @@
|
||||
|
||||
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–2)
|
||||
## 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.
|
||||
- **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`).
|
||||
- **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
|
||||
|
||||
- **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.
|
||||
- **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
|
||||
|
||||
Proxmox Mail Gateway runs SpamAssassin, and header names are configurable, so the extractor recognises each format seen in practice rather than one fixed header — in order of precision:
|
||||
|
||||
| Header | Example | Read as |
|
||||
|---|---|---|
|
||||
| `X-SPAM-LEVEL` (PMG) | `Spam detection results: 8` followed by per-rule scores, folded over several lines | the total, 8 |
|
||||
| `X-Spam-Score` | `5.3` | 5.3 |
|
||||
| `X-Spam-Status` | `Yes, score=7.2 required=5.0 …` | 7.2 |
|
||||
| `X-Spam-Level` (SpamAssassin) | `*******` | 7 (one per star) |
|
||||
|
||||
The first and last rows are the same header name — PMG and SpamAssassin use it for completely different formats — which is why each format is matched explicitly rather than taking "the first number in the header".
|
||||
|
||||
**PMG only adds its header from spam level 3 by default**, so mail below that has no score at all. That's stored as "unknown", not 0, and a rule treats it as neither over nor under any threshold. Thresholds of 3 and above work as expected; to act on lower scores, change PMG's rule that adds the header.
|
||||
|
||||
Scores are extracted for mail ingested from this version on. Older mail has none stored, but *run now* still finds it: when a stored score is missing it re-reads the raw message.
|
||||
|
||||
## 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
|
||||
|
||||
A few consequences worth knowing, because they aren't visible from the UI:
|
||||
|
||||
- **Sent mail exists only in Tern.** Nothing is appended to the IMAP server's Sent folder — sync is one-way (§2.1) and never writes back. If you ever use another client against the same account, it won't see mail sent from Tern. The same goes for mark-read: it's Tern-local. Bringing either to the source server is the two-way-sync item in §11, not a small add-on.
|
||||
- **TLS always, enforced by type.** `mail-send`'s `connect()` returns a TLS-typed client and fails with `MissingStartTls` rather than downgrading; plaintext would need a separate `connect_plain()` which isn't used. Verified live: pointing an account at a server that doesn't offer STARTTLS fails permanently and delivers nothing.
|
||||
- **SMTP trusts the OS certificate store**, same as IMAP. `mail-send` on its own trusts only compiled-in public CAs, so a mail server with an internal-CA certificate would sync fine and then fail every send. If your mail server uses an internal CA, add it to the container's trust store (`/usr/local/share/ca-certificates` + `update-ca-certificates`) and both protocols will trust it.
|
||||
- **Bcc goes in the envelope only.** `mail-builder`'s `.bcc()` writes an ordinary `Bcc:` header that every recipient would see, so it's deliberately not used; a test checks that blind-copied addresses never reach the rendered message. The Bcc list is kept on the outbox row, not on the sent message.
|
||||
- **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":"<session>","since":<cursor or null>}`. 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=<cursor>`** — 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: SMTP sending/outbox, 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: 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:
|
||||
|
||||
- **Mutation endpoints.** There's no way to mark read, tag, or move a message yet. These arrive with phases 4–5, when there's something to mutate.
|
||||
- **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.
|
||||
|
||||
### Fixed: mail announced mid-fetch could wait for the next renewal
|
||||
|
||||
A server announces new mail once per session, as an untagged `EXISTS` attached to whatever response is in flight. Mail landing while Tern was fetching — or while IDLE was starting — was announced that way; async-imap files such announcements in a side channel instead of waking IDLE, and the server doesn't repeat them. The message then sat unfetched until the next IDLE renewal or the next new mail.
|
||||
|
||||
Measured before the fix: in bursts of 4 messages separated by quiet gaps, 4 of 12 bursts had a message stuck for the whole gap; one message sat 358 s in an earlier run. After: 0 of 12, worst case 0.2 s. The sync loop now drains that channel after IDLE starts and fetches again if it announced mail. Draining also matters on its own — the channel holds 100 entries and silently drops announcements once full.
|
||||
|
||||
IDLE is also renewed every 10 minutes rather than 25; each renewal re-runs the fetch pass, so it doubles as the 5–15 minute safety-net poll the spec asks for (§3.1).
|
||||
|
||||
### Decided: the sync engine only moves forward
|
||||
|
||||
`fetch_new_headers` only looks at UIDs above `last_synced_uid`, so **flag changes and deletions made on the source IMAP server are never noticed.** A message read or deleted in another client stays unread and present in Tern forever.
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
-- Sending: SMTP submission via an outbox queue (server-architecture-spec.md §3.3).
|
||||
|
||||
-- An IMAP username isn't necessarily an email address ("alice" vs
|
||||
-- "alice@example.com"), so the sender identity is stored explicitly.
|
||||
ALTER TABLE accounts ADD COLUMN email_address TEXT;
|
||||
ALTER TABLE accounts ADD COLUMN display_name TEXT;
|
||||
UPDATE accounts SET email_address = username WHERE username LIKE '%@%';
|
||||
|
||||
-- Sent mail lives alongside synced mail so a thread shows both sides of the
|
||||
-- conversation. Sync is one-way and only reads INBOX, so without this a
|
||||
-- reply would vanish from its own thread. Sent rows have no IMAP UID.
|
||||
ALTER TABLE messages ADD COLUMN source TEXT NOT NULL DEFAULT 'imap';
|
||||
ALTER TABLE messages ALTER COLUMN uid DROP NOT NULL;
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_uid_matches_source
|
||||
CHECK ((source = 'imap') = (uid IS NOT NULL));
|
||||
|
||||
CREATE TABLE outbox (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
-- draft: editable, never sent automatically
|
||||
-- pending: queued, waiting for next_attempt_at
|
||||
-- sending: claimed by the worker
|
||||
-- sent / failed: terminal (failed can be edited and re-queued)
|
||||
status TEXT NOT NULL DEFAULT 'draft'
|
||||
CHECK (status IN ('draft', 'pending', 'sending', 'sent', 'failed')),
|
||||
to_addrs TEXT[] NOT NULL DEFAULT '{}',
|
||||
cc_addrs TEXT[] NOT NULL DEFAULT '{}',
|
||||
bcc_addrs TEXT[] NOT NULL DEFAULT '{}',
|
||||
subject TEXT NOT NULL DEFAULT '',
|
||||
text_body TEXT NOT NULL DEFAULT '',
|
||||
-- Reply context, derived server-side from the parent message rather than
|
||||
-- trusted from the client.
|
||||
in_reply_to TEXT,
|
||||
references_ TEXT[] NOT NULL DEFAULT '{}',
|
||||
thread_id UUID,
|
||||
-- Assigned when first queued and reused on every retry, so if a server
|
||||
-- accepted a message but the ack was lost, the retry is recognisably the
|
||||
-- same message to recipients' clients rather than a new one.
|
||||
message_id TEXT,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
last_error TEXT,
|
||||
next_attempt_at TIMESTAMPTZ,
|
||||
sent_message_id UUID REFERENCES messages(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
sent_at TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE INDEX outbox_due_idx ON outbox (next_attempt_at) WHERE status = 'pending';
|
||||
CREATE INDEX outbox_user_status_idx ON outbox (user_id, status);
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Phase 6: a system Junk folder alongside Archive (server-architecture-spec.md
|
||||
-- §3.5 — "score > N → tag as spam / move to Junk").
|
||||
ALTER TABLE folders DROP CONSTRAINT folders_role_check;
|
||||
ALTER TABLE folders ADD CONSTRAINT folders_role_check CHECK (role IN ('archive', 'junk'));
|
||||
@@ -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;
|
||||
+11
-2
@@ -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;
|
||||
}
|
||||
}
|
||||
+26
-4
@@ -1,6 +1,7 @@
|
||||
use crate::api::middleware::CurrentUser;
|
||||
use crate::api::state::AppState;
|
||||
use crate::error::ApiResult;
|
||||
use crate::error::{ApiResult, AppJson};
|
||||
use crate::events::{Change, ConfigKind};
|
||||
use crate::models::account::{Account, AccountPublic};
|
||||
use axum::{extract::State, Json};
|
||||
use serde::Deserialize;
|
||||
@@ -15,6 +16,14 @@ pub struct CreateAccountRequest {
|
||||
pub smtp_port: i32,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
/// From address for sending. Defaults to `username` when that is
|
||||
/// itself an address.
|
||||
pub email_address: Option<String>,
|
||||
pub display_name: Option<String>,
|
||||
/// STARTTLS on a plain connection (587) vs TLS from the first byte
|
||||
/// (465). Defaults by port, since that's the convention nearly every
|
||||
/// provider follows. Either way it's TLS — there's no plaintext option.
|
||||
pub smtp_use_starttls: Option<bool>,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
@@ -35,14 +44,16 @@ 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)?;
|
||||
|
||||
let account: Account = sqlx::query_as(
|
||||
"INSERT INTO accounts \
|
||||
(user_id, name, imap_host, imap_port, smtp_host, smtp_port, username, encrypted_password, password_nonce) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *",
|
||||
(user_id, name, imap_host, imap_port, smtp_host, smtp_port, username, encrypted_password, \
|
||||
password_nonce, email_address, display_name, smtp_use_starttls) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, \
|
||||
COALESCE($10, CASE WHEN $7 LIKE '%@%' THEN $7 END), $11, $12) RETURNING *",
|
||||
)
|
||||
.bind(user.user_id)
|
||||
.bind(&req.name)
|
||||
@@ -53,6 +64,9 @@ pub async fn create(
|
||||
.bind(&req.username)
|
||||
.bind(&encrypted.ciphertext)
|
||||
.bind(&encrypted.nonce)
|
||||
.bind(req.email_address.as_deref().map(str::trim).filter(|e| !e.is_empty()))
|
||||
.bind(req.display_name.as_deref().map(str::trim).filter(|n| !n.is_empty()))
|
||||
.bind(req.smtp_use_starttls.unwrap_or(req.smtp_port != 465))
|
||||
.fetch_one(&state.pool)
|
||||
.await?;
|
||||
|
||||
@@ -61,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()))
|
||||
}
|
||||
|
||||
@@ -75,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 })))
|
||||
}
|
||||
+3
-3
@@ -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)
|
||||
|
||||
+263
-34
@@ -1,54 +1,283 @@
|
||||
//! `GET /events?since=<cursor>` — 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=<cursor>` 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<i64>) -> 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<DateTime<Utc>>,
|
||||
pub struct PollQuery {
|
||||
pub since: Option<i64>,
|
||||
pub limit: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct EventsResponse {
|
||||
pub changed_messages: Vec<Message>,
|
||||
pub cursor: DateTime<Utc>,
|
||||
pub struct PollResponse {
|
||||
pub events: Vec<Event>,
|
||||
/// 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<AppState>,
|
||||
user: CurrentUser,
|
||||
Query(q): Query<EventsQuery>,
|
||||
) -> ApiResult<Json<EventsResponse>> {
|
||||
let since = q
|
||||
.since
|
||||
.unwrap_or_else(|| Utc::now() - chrono::Duration::days(1));
|
||||
let cursor = Utc::now();
|
||||
|
||||
let changed_messages: Vec<Message> = 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<PollQuery>,
|
||||
) -> ApiResult<Json<PollResponse>> {
|
||||
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<i64> },
|
||||
}
|
||||
|
||||
#[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<AppState>, 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::<ClientMsg>(&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<i64> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
+72
-7
@@ -1,6 +1,7 @@
|
||||
use crate::api::middleware::CurrentUser;
|
||||
use crate::api::state::AppState;
|
||||
use crate::error::ApiResult;
|
||||
use crate::error::{ApiResult, AppJson};
|
||||
use crate::events::{Change, ConfigKind};
|
||||
use crate::models::Folder;
|
||||
use axum::{extract::State, Json};
|
||||
use serde::Deserialize;
|
||||
@@ -14,18 +15,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 *")
|
||||
@@ -33,5 +35,68 @@ 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))
|
||||
}
|
||||
|
||||
#[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?;
|
||||
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
|
||||
/// 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(),
|
||||
));
|
||||
}
|
||||
state
|
||||
.events
|
||||
.emit(user.user_id, Change::config(ConfigKind::Folders))
|
||||
.await;
|
||||
Ok(Json(serde_json::json!({ "ok": true })))
|
||||
}
|
||||
+19
-2
@@ -97,11 +97,14 @@ pub async fn get(
|
||||
/// "Fetch thread" endpoint (§3.6) — the client just needs thread_id exposed
|
||||
/// plus a way to pull every message in it; how to render it (collapsed vs
|
||||
/// flat) is left entirely to the client.
|
||||
///
|
||||
/// Bodies are included so opening a conversation is one request rather than
|
||||
/// one per message.
|
||||
pub async fn get_thread(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(thread_id): Path<Uuid>,
|
||||
) -> ApiResult<Json<Vec<Message>>> {
|
||||
) -> ApiResult<Json<Vec<MessageDetail>>> {
|
||||
let messages: Vec<Message> = sqlx::query_as(
|
||||
"SELECT m.* FROM messages m JOIN accounts a ON a.id = m.account_id \
|
||||
WHERE m.thread_id = $1 AND a.user_id = $2 \
|
||||
@@ -112,5 +115,19 @@ pub async fn get_thread(
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
|
||||
Ok(Json(messages))
|
||||
let ids: Vec<Uuid> = messages.iter().map(|m| m.id).collect();
|
||||
let bodies: Vec<Body> = sqlx::query_as("SELECT * FROM bodies WHERE message_id = ANY($1)")
|
||||
.bind(&ids)
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
|
||||
let detailed = messages
|
||||
.into_iter()
|
||||
.map(|message| {
|
||||
let body = bodies.iter().find(|b| b.message_id == message.id).cloned();
|
||||
MessageDetail { message, body }
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Json(detailed))
|
||||
}
|
||||
+18
-10
@@ -31,15 +31,23 @@ impl FromRequestParts<AppState> for CurrentUser {
|
||||
.ok_or(ApiError::Unauthorized)?;
|
||||
let token = Uuid::parse_str(token_str).map_err(|_| ApiError::Unauthorized)?;
|
||||
|
||||
let row: Option<(Uuid, chrono::DateTime<Utc>)> =
|
||||
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<Option<Uuid>> {
|
||||
let row: Option<(Uuid, chrono::DateTime<Utc>)> =
|
||||
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))
|
||||
}
|
||||
@@ -4,8 +4,12 @@ pub mod events;
|
||||
pub mod folders;
|
||||
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;
|
||||
pub use state::AppState;
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Drafts and the send queue (server-architecture-spec.md §3.3).
|
||||
//!
|
||||
//! A draft and a queued message are the same row in different states, so
|
||||
//! "save as draft" and "send" are one endpoint with a flag, and sending an
|
||||
//! existing draft is a state transition rather than a copy.
|
||||
//!
|
||||
//! Nothing here talks SMTP — queuing just marks a row pending and wakes the
|
||||
//! worker, so a slow or unreachable mail server never blocks a request.
|
||||
|
||||
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;
|
||||
use crate::smtp::compose;
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ComposeRequest {
|
||||
pub account_id: Option<Uuid>,
|
||||
#[serde(default)]
|
||||
pub to: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub cc: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub bcc: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub subject: String,
|
||||
#[serde(default)]
|
||||
pub text_body: String,
|
||||
/// Tern's id for the message being replied to. Threading headers are
|
||||
/// derived from it server-side rather than accepted from the client.
|
||||
pub reply_to_message_id: Option<Uuid>,
|
||||
/// false = save as draft, true = queue for sending.
|
||||
#[serde(default)]
|
||||
pub send: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UpdateDraftRequest {
|
||||
pub to: Vec<String>,
|
||||
pub cc: Vec<String>,
|
||||
pub bcc: Vec<String>,
|
||||
pub subject: String,
|
||||
pub text_body: String,
|
||||
}
|
||||
|
||||
/// Everything the reader can still act on. Sent items are left out: once
|
||||
/// sent, a message lives in its thread like any other.
|
||||
pub async fn list(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
) -> ApiResult<Json<Vec<OutboxItem>>> {
|
||||
let items: Vec<OutboxItem> = sqlx::query_as(
|
||||
"SELECT * FROM outbox WHERE user_id = $1 AND status <> 'sent' ORDER BY updated_at DESC",
|
||||
)
|
||||
.bind(user.user_id)
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
Ok(Json(items))
|
||||
}
|
||||
|
||||
pub async fn create(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
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)?;
|
||||
let bcc = compose::normalize_recipients(&req.bcc).map_err(ApiError::BadRequest)?;
|
||||
|
||||
let parent = match req.reply_to_message_id {
|
||||
Some(id) => Some(load_owned_message(&state, user.user_id, id).await?),
|
||||
None => None,
|
||||
};
|
||||
|
||||
// A reply goes out from the account that received the original, unless
|
||||
// the reader explicitly picked another one.
|
||||
let account_id = req
|
||||
.account_id
|
||||
.or(parent.as_ref().map(|p| p.account_id))
|
||||
.ok_or_else(|| ApiError::BadRequest("account_id is required".into()))?;
|
||||
let account = load_owned_account(&state, user.user_id, account_id).await?;
|
||||
|
||||
// Checked before inserting, so a rejected send doesn't leave an orphan
|
||||
// draft behind for a retrying client to duplicate.
|
||||
if req.send {
|
||||
check_sendable(&account, &to, &cc, &bcc)?;
|
||||
}
|
||||
|
||||
let (in_reply_to, references) = match &parent {
|
||||
Some(p) => compose::reply_headers(p.message_id.as_deref(), &p.references_),
|
||||
None => (None, Vec::new()),
|
||||
};
|
||||
|
||||
let item: OutboxItem = sqlx::query_as(
|
||||
"INSERT INTO outbox \
|
||||
(user_id, account_id, to_addrs, cc_addrs, bcc_addrs, subject, text_body, \
|
||||
in_reply_to, references_, thread_id) \
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING *",
|
||||
)
|
||||
.bind(user.user_id)
|
||||
.bind(account.id)
|
||||
.bind(&to)
|
||||
.bind(&cc)
|
||||
.bind(&bcc)
|
||||
.bind(&req.subject)
|
||||
.bind(&req.text_body)
|
||||
.bind(&in_reply_to)
|
||||
.bind(&references)
|
||||
.bind(parent.as_ref().map(|p| p.thread_id))
|
||||
.fetch_one(&state.pool)
|
||||
.await?;
|
||||
|
||||
if req.send {
|
||||
return queue(&state, &account, item).await.map(Json);
|
||||
}
|
||||
changed(&state, &item).await;
|
||||
Ok(Json(item))
|
||||
}
|
||||
|
||||
/// Editing a failed message turns it back into a draft: once changed it's
|
||||
/// no longer the thing that failed, and it shouldn't be retried as-is.
|
||||
pub async fn update(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(id): Path<Uuid>,
|
||||
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)?;
|
||||
let bcc = compose::normalize_recipients(&req.bcc).map_err(ApiError::BadRequest)?;
|
||||
|
||||
let item: Option<OutboxItem> = sqlx::query_as(
|
||||
"UPDATE outbox SET to_addrs = $3, cc_addrs = $4, bcc_addrs = $5, subject = $6, \
|
||||
text_body = $7, status = 'draft', last_error = NULL, updated_at = now() \
|
||||
WHERE id = $1 AND user_id = $2 AND status IN ('draft', 'failed') \
|
||||
RETURNING *",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(user.user_id)
|
||||
.bind(&to)
|
||||
.bind(&cc)
|
||||
.bind(&bcc)
|
||||
.bind(&req.subject)
|
||||
.bind(&req.text_body)
|
||||
.fetch_optional(&state.pool)
|
||||
.await?;
|
||||
|
||||
let item = item.ok_or_else(|| editable_or_not_found(id))?;
|
||||
changed(&state, &item).await;
|
||||
Ok(Json(item))
|
||||
}
|
||||
|
||||
pub async fn send(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> ApiResult<Json<OutboxItem>> {
|
||||
let item: OutboxItem = sqlx::query_as(
|
||||
"SELECT * FROM outbox WHERE id = $1 AND user_id = $2 AND status IN ('draft', 'failed')",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(user.user_id)
|
||||
.fetch_optional(&state.pool)
|
||||
.await?
|
||||
.ok_or_else(|| editable_or_not_found(id))?;
|
||||
|
||||
let account = load_owned_account(&state, user.user_id, item.account_id).await?;
|
||||
queue(&state, &account, item).await.map(Json)
|
||||
}
|
||||
|
||||
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 outbox WHERE id = $1 AND user_id = $2 AND status IN ('draft', 'failed')",
|
||||
)
|
||||
.bind(id)
|
||||
.bind(user.user_id)
|
||||
.execute(&state.pool)
|
||||
.await?
|
||||
.rows_affected();
|
||||
|
||||
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.
|
||||
async fn queue(state: &AppState, account: &Account, item: OutboxItem) -> ApiResult<OutboxItem> {
|
||||
let sender = check_sendable(account, &item.to_addrs, &item.cc_addrs, &item.bcc_addrs)?;
|
||||
|
||||
let item: OutboxItem = sqlx::query_as(
|
||||
"UPDATE outbox SET status = 'pending', attempts = 0, last_error = NULL, \
|
||||
message_id = COALESCE(message_id, $2), next_attempt_at = now(), updated_at = now() \
|
||||
WHERE id = $1 RETURNING *",
|
||||
)
|
||||
.bind(item.id)
|
||||
.bind(compose::new_message_id(&sender))
|
||||
.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)
|
||||
}
|
||||
|
||||
fn check_sendable(
|
||||
account: &Account,
|
||||
to: &[String],
|
||||
cc: &[String],
|
||||
bcc: &[String],
|
||||
) -> ApiResult<String> {
|
||||
if to.is_empty() && cc.is_empty() && bcc.is_empty() {
|
||||
return Err(ApiError::BadRequest(
|
||||
"at least one recipient is required".into(),
|
||||
));
|
||||
}
|
||||
account.sender_address().ok_or_else(|| {
|
||||
ApiError::BadRequest(
|
||||
"this account has no sender address — set email_address on the account first".into(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async fn load_owned_account(
|
||||
state: &AppState,
|
||||
user_id: Uuid,
|
||||
account_id: Uuid,
|
||||
) -> ApiResult<Account> {
|
||||
sqlx::query_as("SELECT * FROM accounts WHERE id = $1 AND user_id = $2")
|
||||
.bind(account_id)
|
||||
.bind(user_id)
|
||||
.fetch_optional(&state.pool)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound)
|
||||
}
|
||||
|
||||
async fn load_owned_message(
|
||||
state: &AppState,
|
||||
user_id: Uuid,
|
||||
message_id: Uuid,
|
||||
) -> ApiResult<Message> {
|
||||
sqlx::query_as(
|
||||
"SELECT m.* FROM messages m JOIN accounts a ON a.id = m.account_id \
|
||||
WHERE m.id = $1 AND a.user_id = $2",
|
||||
)
|
||||
.bind(message_id)
|
||||
.bind(user_id)
|
||||
.fetch_optional(&state.pool)
|
||||
.await?
|
||||
.ok_or(ApiError::NotFound)
|
||||
}
|
||||
|
||||
fn editable_or_not_found(id: Uuid) -> ApiError {
|
||||
ApiError::BadRequest(format!(
|
||||
"outbox item {id} doesn't exist or isn't editable — only drafts and failed messages can be changed"
|
||||
))
|
||||
}
|
||||
+25
-5
@@ -1,6 +1,6 @@
|
||||
use crate::api::state::AppState;
|
||||
use crate::api::{accounts, auth, events, folders, messages};
|
||||
use axum::routing::{delete, get, post};
|
||||
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;
|
||||
use tower_http::trace::TraceLayer;
|
||||
@@ -10,12 +10,32 @@ pub fn build(state: AppState) -> Router {
|
||||
.route("/api/auth/register", post(auth::register))
|
||||
.route("/api/auth/login", post(auth::login))
|
||||
.route("/api/accounts", get(accounts::list).post(accounts::create))
|
||||
.route("/api/accounts/{id}", delete(accounts::delete))
|
||||
.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/{id}", get(messages::get_thread))
|
||||
.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",
|
||||
put(outbox::update).delete(outbox::delete),
|
||||
)
|
||||
.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())
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
//! 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::events::{Change, ConfigKind};
|
||||
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?;
|
||||
state
|
||||
.events
|
||||
.emit(user.user_id, Change::config(ConfigKind::Rules))
|
||||
.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?;
|
||||
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(
|
||||
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);
|
||||
}
|
||||
state
|
||||
.events
|
||||
.emit(user.user_id, Change::config(ConfigKind::Rules))
|
||||
.await;
|
||||
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?;
|
||||
state
|
||||
.events
|
||||
.emit(user.user_id, Change::config(ConfigKind::Rules))
|
||||
.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");
|
||||
if summary.matched > 0 {
|
||||
state
|
||||
.events
|
||||
.emit(user.user_id, Change::MailboxChanged { thread_ids: None })
|
||||
.await;
|
||||
}
|
||||
|
||||
Ok(Json(RunResponse {
|
||||
scanned: summary.scanned,
|
||||
matched: summary.matched,
|
||||
}))
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
use crate::config::Config;
|
||||
use crate::crypto::CredentialCipher;
|
||||
use crate::events::EventHub;
|
||||
use crate::storage::BlobStore;
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
@@ -10,4 +13,8 @@ pub struct AppState {
|
||||
pub blobs: BlobStore,
|
||||
pub session_ttl_hours: i64,
|
||||
pub config: Config,
|
||||
/// 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<Notify>,
|
||||
pub events: EventHub,
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
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},
|
||||
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)?;
|
||||
state
|
||||
.events
|
||||
.emit(user.user_id, Change::config(ConfigKind::Tags))
|
||||
.await;
|
||||
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)?;
|
||||
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
|
||||
/// 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);
|
||||
}
|
||||
state
|
||||
.events
|
||||
.emit(user.user_id, Change::config(ConfigKind::Tags))
|
||||
.await;
|
||||
Ok(Json(serde_json::json!({ "ok": true })))
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
//! Thread-grouped listing — one row per conversation, which is how both
|
||||
//! clients render a mailbox — plus actions on a whole thread.
|
||||
//!
|
||||
//! 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::{ApiError, ApiResult, AppJson};
|
||||
use crate::events::Change;
|
||||
use crate::rules::{self, Action};
|
||||
use axum::{
|
||||
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,
|
||||
/// The system Junk folder, which may not exist yet.
|
||||
Junk,
|
||||
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::Junk => "junk",
|
||||
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>,
|
||||
/// Opaque cursor from a previous page's `next_cursor`.
|
||||
pub before: Option<String>,
|
||||
pub limit: Option<i64>,
|
||||
}
|
||||
|
||||
/// Keyset position: the last row's sort time plus its thread id. The id
|
||||
/// breaks ties — sort times come from Date headers with one-second
|
||||
/// resolution, so a burst of mail shares them, and a timestamp-only cursor
|
||||
/// with `<` would skip every thread tied with the last row of a page.
|
||||
struct Cursor {
|
||||
at: DateTime<Utc>,
|
||||
thread_id: Uuid,
|
||||
}
|
||||
|
||||
impl Cursor {
|
||||
fn encode(at: DateTime<Utc>, thread_id: Uuid) -> String {
|
||||
format!(
|
||||
"{}|{thread_id}",
|
||||
at.to_rfc3339_opts(chrono::SecondsFormat::Micros, true)
|
||||
)
|
||||
}
|
||||
|
||||
fn decode(s: &str) -> Option<Self> {
|
||||
let (at, id) = s.split_once('|')?;
|
||||
Some(Cursor {
|
||||
at: DateTime::parse_from_rfc3339(at).ok()?.with_timezone(&Utc),
|
||||
thread_id: id.parse().ok()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, sqlx::FromRow)]
|
||||
pub struct ThreadSummary {
|
||||
pub thread_id: Uuid,
|
||||
pub subject: Option<String>,
|
||||
/// Display name (falling back to address) of the most recent sender.
|
||||
pub last_from: Option<String>,
|
||||
/// When the newest message arrived, by the sort key described in `list`.
|
||||
pub last_message_at: DateTime<Utc>,
|
||||
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)]
|
||||
pub struct ListThreadsResponse {
|
||||
pub threads: Vec<ThreadSummary>,
|
||||
/// None when this was the last page.
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
State(state): State<AppState>,
|
||||
user: CurrentUser,
|
||||
Query(q): Query<ListThreadsQuery>,
|
||||
) -> ApiResult<Json<ListThreadsResponse>> {
|
||||
let limit = q.limit.unwrap_or(50).clamp(1, 200);
|
||||
let cursor = match q.before.as_deref() {
|
||||
Some(raw) => {
|
||||
Some(Cursor::decode(raw).ok_or_else(|| ApiError::BadRequest("invalid cursor".into()))?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
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()))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// 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.
|
||||
//
|
||||
// Threads sort by `sort_at` = LEAST(COALESCE(sent_at, created_at),
|
||||
// created_at): the Date header, but never later than when we received
|
||||
// the message. A mail with no Date header still sorts (by arrival), and
|
||||
// one dated in the future — clock skew, or spam trying to pin itself to
|
||||
// the top — is clamped to its arrival time. An older mailbox synced
|
||||
// for the first time keeps its real chronology, since its Date headers
|
||||
// all precede the sync.
|
||||
let threads: Vec<ThreadSummary> = sqlx::query_as(
|
||||
r#"
|
||||
WITH mine AS (
|
||||
SELECT m.*, LEAST(COALESCE(m.sent_at, m.created_at), m.created_at) AS sort_at
|
||||
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 'junk' THEN v.deleted_at IS NULL AND v.folder_id =
|
||||
(SELECT id FROM folders WHERE user_id = $1 AND role = 'junk')
|
||||
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,
|
||||
-- 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.sort_at ASC,
|
||||
m.created_at ASC))[1] AS subject,
|
||||
(ARRAY_AGG(COALESCE(NULLIF(m.from_name, ''), m.from_addr)
|
||||
ORDER BY m.sort_at DESC))[1] AS last_from,
|
||||
MAX(m.sort_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,
|
||||
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 $5::timestamptz IS NULL OR (MAX(m.sort_at), m.thread_id) < ($5, $8)
|
||||
ORDER BY last_message_at DESC, m.thread_id DESC
|
||||
LIMIT $6
|
||||
"#,
|
||||
)
|
||||
.bind(user.user_id)
|
||||
.bind(q.view.as_str())
|
||||
.bind(q.folder_id)
|
||||
.bind(q.tag_id)
|
||||
.bind(cursor.as_ref().map(|c| c.at))
|
||||
.bind(limit)
|
||||
.bind(state.config.trash_retention_days as i32)
|
||||
.bind(cursor.as_ref().map(|c| c.thread_id))
|
||||
.fetch_all(&state.pool)
|
||||
.await?;
|
||||
|
||||
let next_cursor = (threads.len() as i64 == limit)
|
||||
.then(|| threads.last())
|
||||
.flatten()
|
||||
.map(|t| Cursor::encode(t.last_message_at, t.thread_id));
|
||||
|
||||
Ok(Json(ListThreadsResponse {
|
||||
threads,
|
||||
next_cursor,
|
||||
}))
|
||||
}
|
||||
|
||||
#[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?;
|
||||
state
|
||||
.events
|
||||
.emit(user.user_id, Change::threads([thread_id]))
|
||||
.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<AppState>,
|
||||
user: CurrentUser,
|
||||
thread_id: Path<Uuid>,
|
||||
) -> ApiResult<Json<serde_json::Value>> {
|
||||
act(
|
||||
state,
|
||||
user,
|
||||
thread_id,
|
||||
AppJson(ThreadActionsRequest {
|
||||
actions: vec![Action::MarkRead],
|
||||
}),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::Cursor;
|
||||
|
||||
#[test]
|
||||
fn cursor_round_trips_with_microseconds_and_id() {
|
||||
let at = chrono::DateTime::parse_from_rfc3339("2026-09-23T10:08:20.123456Z")
|
||||
.unwrap()
|
||||
.with_timezone(&chrono::Utc);
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let c = Cursor::decode(&Cursor::encode(at, id)).unwrap();
|
||||
assert_eq!((c.at, c.thread_id), (at, id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_cursors_are_rejected() {
|
||||
for bad in [
|
||||
"",
|
||||
"2026-09-23T10:08:20Z",
|
||||
"nonsense|also-nonsense",
|
||||
"2026-09-23T10:08:20Z|not-a-uuid",
|
||||
] {
|
||||
assert!(Cursor::decode(bad).is_none(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
+254
@@ -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<Uuid>,
|
||||
account_id: Uuid,
|
||||
notify: bool,
|
||||
from: Option<String>,
|
||||
subject: Option<String>,
|
||||
},
|
||||
/// 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<Vec<Uuid>>,
|
||||
},
|
||||
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<Item = Uuid>) -> Self {
|
||||
let mut ids: Vec<Uuid> = 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<chrono::Utc>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct EventHub {
|
||||
pool: PgPool,
|
||||
tx: broadcast::Sender<Arc<Event>>,
|
||||
/// 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<Mutex<()>>,
|
||||
}
|
||||
|
||||
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<Arc<Event>> {
|
||||
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<i64> {
|
||||
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<Event, _> = 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<Vec<Event>> {
|
||||
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<bool> {
|
||||
// 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<u64> {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
+180
-24
@@ -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;
|
||||
@@ -25,9 +26,26 @@ use sqlx::PgPool;
|
||||
use std::time::Duration;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Re-issue IDLE this often even if the server hasn't timed out, and treat a
|
||||
/// connection as stalled if nothing happens for this long.
|
||||
const IDLE_RENEW: Duration = Duration::from_secs(25 * 60);
|
||||
/// Re-issue IDLE this often even if nothing happened. Each renewal re-runs
|
||||
/// the fetch pass, so it doubles as the safety-net poll the spec asks for
|
||||
/// (§3.1, 5–15 min) in case a notification is ever lost — and keeps well
|
||||
/// inside the ~30 min after which servers drop an IDLE session.
|
||||
const IDLE_RENEW: Duration = Duration::from_secs(10 * 60);
|
||||
|
||||
/// Empties async-imap's side channel of unsolicited responses, reporting
|
||||
/// whether any of them announced new mail. Draining also matters on its
|
||||
/// own: the channel holds 100 entries and silently drops announcements once
|
||||
/// full, which an undrained long-lived session eventually reaches.
|
||||
fn announced_new_mail(
|
||||
notices: &async_channel::Receiver<async_imap::types::UnsolicitedResponse>,
|
||||
) -> bool {
|
||||
use async_imap::types::UnsolicitedResponse as U;
|
||||
let mut new_mail = false;
|
||||
while let Ok(notice) = notices.try_recv() {
|
||||
new_mail |= matches!(notice, U::Exists(_) | U::Recent(_));
|
||||
}
|
||||
new_mail
|
||||
}
|
||||
const BODY_FETCH_BATCH: i64 = 25;
|
||||
|
||||
type ImapSession = async_imap::Session<async_native_tls::TlsStream<tokio::net::TcpStream>>;
|
||||
@@ -54,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<Uuid>,
|
||||
arrived_live: bool,
|
||||
notify: bool,
|
||||
from: Option<String>,
|
||||
subject: Option<String>,
|
||||
}
|
||||
|
||||
impl AccountSyncer {
|
||||
@@ -126,6 +156,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`;
|
||||
@@ -164,18 +195,34 @@ impl AccountSyncer {
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
// Account creation leaves uidvalidity NULL, so this is a first
|
||||
// sync rather than a change — record it without the scary reset
|
||||
// path, which would otherwise log a false "UIDVALIDITY changed"
|
||||
// warning for every newly added account.
|
||||
Some((None,)) => {
|
||||
sqlx::query(
|
||||
"UPDATE sync_state SET uidvalidity = $2, updated_at = now() WHERE account_id = $1",
|
||||
)
|
||||
.bind(self.account.id)
|
||||
.bind(server_uidvalidity)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
Some((stored,)) if stored != server_uidvalidity => {
|
||||
// UIDVALIDITY changed: every previously cached UID is now
|
||||
// meaningless. Drop this account's messages and start over.
|
||||
// meaningless. Drop this account's synced messages and start
|
||||
// over — only the IMAP-sourced ones: mail sent from Tern
|
||||
// shares this table but exists nowhere else, so deleting it
|
||||
// here would lose it for good.
|
||||
tracing::warn!(account_id = %self.account.id, "UIDVALIDITY changed, re-syncing folder from scratch");
|
||||
let mut tx = self.pool.begin().await?;
|
||||
sqlx::query("DELETE FROM messages WHERE account_id = $1")
|
||||
sqlx::query("DELETE FROM messages WHERE account_id = $1 AND source = 'imap'")
|
||||
.bind(self.account.id)
|
||||
.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)
|
||||
@@ -188,20 +235,21 @@ impl AccountSyncer {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn last_synced_uid(&self) -> Result<i64> {
|
||||
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
|
||||
@@ -227,19 +275,22 @@ impl AccountSyncer {
|
||||
let subject = envelope
|
||||
.and_then(|e| e.subject.as_ref())
|
||||
.map(|s| String::from_utf8_lossy(s).to_string());
|
||||
// ENVELOPE gives these bracketed; mail-parser (which overwrites
|
||||
// them once the body arrives) gives them bare. Store one form.
|
||||
let message_id = envelope
|
||||
.and_then(|e| e.message_id.as_ref())
|
||||
.map(|s| String::from_utf8_lossy(s).to_string());
|
||||
.map(|s| crate::smtp::compose::bare_id(&String::from_utf8_lossy(s)));
|
||||
let in_reply_to = envelope
|
||||
.and_then(|e| e.in_reply_to.as_ref())
|
||||
.map(|s| String::from_utf8_lossy(s).to_string());
|
||||
.map(|s| crate::smtp::compose::bare_id(&String::from_utf8_lossy(s)));
|
||||
|
||||
let flags: Vec<String> = f.flags().map(|flag| flag_to_wire(&flag)).collect();
|
||||
|
||||
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)
|
||||
@@ -248,6 +299,7 @@ impl AccountSyncer {
|
||||
.bind(&in_reply_to)
|
||||
.bind(&subject)
|
||||
.bind(&flags)
|
||||
.bind(caught_up)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
}
|
||||
@@ -259,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(())
|
||||
}
|
||||
@@ -268,7 +326,8 @@ impl AccountSyncer {
|
||||
async fn fetch_pending_bodies(&self, session: &mut ImapSession) -> Result<()> {
|
||||
loop {
|
||||
let pending: Vec<(Uuid, i64)> = sqlx::query_as(
|
||||
"SELECT id, uid FROM messages WHERE account_id = $1 AND body_fetched = false \
|
||||
"SELECT id, uid FROM messages \
|
||||
WHERE account_id = $1 AND source = 'imap' AND body_fetched = false \
|
||||
ORDER BY uid ASC LIMIT $2",
|
||||
)
|
||||
.bind(self.account.id)
|
||||
@@ -294,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;
|
||||
@@ -302,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<Ingested> {
|
||||
let parsed = parse_raw_message(raw)?;
|
||||
let (_, raw_blob_ref) = self.blobs.put(&parsed.raw).await?;
|
||||
|
||||
@@ -368,8 +453,64 @@ impl AccountSyncer {
|
||||
.await?;
|
||||
}
|
||||
|
||||
sqlx::query("UPDATE messages SET spam_score = $2 WHERE id = $1")
|
||||
.bind(message_row_id)
|
||||
.bind(crate::spam::extract_score(&parsed.headers).map(|s| s as f32))
|
||||
.execute(&mut *tx)
|
||||
.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?;
|
||||
|
||||
let rules_say = crate::rules::apply_rules(
|
||||
&mut tx,
|
||||
self.account.user_id,
|
||||
message_row_id,
|
||||
&crate::rules::Facts::from_parsed(&parsed),
|
||||
)
|
||||
.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<Uuid>, 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
|
||||
@@ -379,6 +520,8 @@ impl AccountSyncer {
|
||||
/// caller can keep using it. `Session::idle()` takes the session by
|
||||
/// value; `Handle::done()` gives it back once IDLE ends.
|
||||
async fn idle_until_change(&self, session: ImapSession) -> Result<(bool, ImapSession)> {
|
||||
// Cloned before idle() takes the session, so it can be read mid-IDLE.
|
||||
let notices = session.unsolicited_responses.clone();
|
||||
let mut handle = session.idle();
|
||||
if let Err(e) = handle.init().await {
|
||||
tracing::warn!(account_id = %self.account.id, error = %e, "server rejected IDLE, falling back to polling");
|
||||
@@ -389,6 +532,19 @@ impl AccountSyncer {
|
||||
return Ok((false, session));
|
||||
}
|
||||
|
||||
// A server announces new mail once per session, as an untagged
|
||||
// EXISTS attached to whatever response is in flight. Mail landing
|
||||
// during our own fetches, or while IDLE was starting up, was
|
||||
// announced that way — async-imap files those in a side channel
|
||||
// rather than waking IDLE, and the server won't repeat them. The
|
||||
// wait below only sees responses from here on, so without this the
|
||||
// message would sit unfetched until the next renewal.
|
||||
if announced_new_mail(¬ices) {
|
||||
tracing::debug!(account_id = %self.account.id, "new mail announced before IDLE began");
|
||||
let session = handle.done().await.context("DONE after IDLE failed")?;
|
||||
return Ok((true, session));
|
||||
}
|
||||
|
||||
let (idle_wait, _stop_source) = handle.wait_with_timeout(IDLE_RENEW);
|
||||
let wait_result = idle_wait.await;
|
||||
|
||||
|
||||
@@ -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<Uuid, tokio::task::JoinHandle<()>> = 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());
|
||||
|
||||
@@ -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>"]);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,12 @@ 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;
|
||||
pub mod rules;
|
||||
pub mod smtp;
|
||||
pub mod spam;
|
||||
pub mod storage;
|
||||
pub mod threading;
|
||||
+24
-1
@@ -20,10 +20,31 @@ 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(),
|
||||
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(),
|
||||
cipher.clone(),
|
||||
blobs.clone(),
|
||||
outbox_wake.clone(),
|
||||
events.clone(),
|
||||
));
|
||||
|
||||
let state = AppState {
|
||||
pool,
|
||||
@@ -31,6 +52,8 @@ async fn main() -> anyhow::Result<()> {
|
||||
blobs,
|
||||
session_ttl_hours: config.session_ttl_hours,
|
||||
config: config.clone(),
|
||||
outbox_wake,
|
||||
events,
|
||||
};
|
||||
|
||||
let app = api::build(state);
|
||||
|
||||
@@ -18,6 +18,20 @@ pub struct Account {
|
||||
pub encrypted_password: Vec<u8>,
|
||||
pub password_nonce: Vec<u8>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub email_address: Option<String>,
|
||||
pub display_name: Option<String>,
|
||||
}
|
||||
|
||||
impl Account {
|
||||
/// The From address for mail sent from this account. Falls back to the
|
||||
/// login name only when that is itself an address — an IMAP username is
|
||||
/// often a bare "alice", which can't be sent from.
|
||||
pub fn sender_address(&self) -> Option<String> {
|
||||
self.email_address
|
||||
.clone()
|
||||
.filter(|a| !a.trim().is_empty())
|
||||
.or_else(|| self.username.contains('@').then(|| self.username.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// What the API actually returns — never the encrypted credential blob.
|
||||
@@ -31,6 +45,8 @@ pub struct AccountPublic {
|
||||
pub smtp_host: String,
|
||||
pub smtp_port: i32,
|
||||
pub username: String,
|
||||
pub email_address: Option<String>,
|
||||
pub display_name: Option<String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
@@ -45,6 +61,8 @@ impl From<Account> for AccountPublic {
|
||||
smtp_host: a.smtp_host,
|
||||
smtp_port: a.smtp_port,
|
||||
username: a.username,
|
||||
email_address: a.email_address,
|
||||
display_name: a.display_name,
|
||||
created_at: a.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -7,7 +7,8 @@ pub struct Message {
|
||||
pub id: Uuid,
|
||||
pub account_id: Uuid,
|
||||
pub folder_id: Option<Uuid>,
|
||||
pub uid: i64,
|
||||
/// None for mail sent from Tern, which never came from IMAP.
|
||||
pub uid: Option<i64>,
|
||||
pub message_id: Option<String>,
|
||||
pub in_reply_to: Option<String>,
|
||||
pub references_: Vec<String>,
|
||||
@@ -22,7 +23,11 @@ pub struct Message {
|
||||
pub spam_score: Option<f32>,
|
||||
pub body_fetched: bool,
|
||||
pub raw_blob_ref: Option<String>,
|
||||
/// '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)]
|
||||
@@ -47,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,6 +1,8 @@
|
||||
pub mod account;
|
||||
pub mod folder;
|
||||
pub mod message;
|
||||
pub mod outbox;
|
||||
pub mod tag;
|
||||
pub mod user;
|
||||
|
||||
pub use account::Account;
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
|
||||
pub struct OutboxItem {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub account_id: Uuid,
|
||||
pub status: String,
|
||||
pub to_addrs: Vec<String>,
|
||||
pub cc_addrs: Vec<String>,
|
||||
pub bcc_addrs: Vec<String>,
|
||||
pub subject: String,
|
||||
pub text_body: String,
|
||||
pub in_reply_to: Option<String>,
|
||||
pub references_: Vec<String>,
|
||||
pub thread_id: Option<Uuid>,
|
||||
pub message_id: Option<String>,
|
||||
pub attempts: i32,
|
||||
pub last_error: Option<String>,
|
||||
pub next_attempt_at: Option<DateTime<Utc>>,
|
||||
pub sent_message_id: Option<Uuid>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
pub sent_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! 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);
|
||||
|
||||
/// 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)");
|
||||
}
|
||||
loop {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
+1014
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,316 @@
|
||||
//! Turning an outbox row into bytes on the wire plus an SMTP envelope.
|
||||
//!
|
||||
//! Kept free of I/O so the parts that must be exactly right — what ends up
|
||||
//! in headers versus the envelope, and how reply headers chain — are unit
|
||||
//! tested without a mail server.
|
||||
|
||||
use mail_send::mail_builder::MessageBuilder;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Who the SMTP transaction is addressed to. Distinct from the headers:
|
||||
/// Bcc recipients appear here and nowhere in the message itself.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Envelope {
|
||||
pub mail_from: String,
|
||||
pub rcpt_to: Vec<String>,
|
||||
}
|
||||
|
||||
pub struct Sender<'a> {
|
||||
pub email: &'a str,
|
||||
pub display_name: Option<&'a str>,
|
||||
}
|
||||
|
||||
pub struct Draft<'a> {
|
||||
pub to: &'a [String],
|
||||
pub cc: &'a [String],
|
||||
pub bcc: &'a [String],
|
||||
pub subject: &'a str,
|
||||
pub text_body: &'a str,
|
||||
pub message_id: &'a str,
|
||||
pub in_reply_to: Option<&'a str>,
|
||||
pub references: &'a [String],
|
||||
pub date_unix: i64,
|
||||
}
|
||||
|
||||
/// Message-IDs are stored without angle brackets. IMAP's ENVELOPE returns
|
||||
/// them bracketed while mail-parser returns them bare, so everything is
|
||||
/// normalised to one form at the boundary — otherwise the same message
|
||||
/// could be stored under two different IDs depending on which path wrote it
|
||||
/// last, and reply chains / threading would fail to match.
|
||||
pub fn bare_id(id: &str) -> String {
|
||||
id.trim()
|
||||
.trim_start_matches('<')
|
||||
.trim_end_matches('>')
|
||||
.trim()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Validates and normalises a recipient list from user input: trims,
|
||||
/// drops blanks, dedupes case-insensitively. Rejects anything that isn't a
|
||||
/// plain `local@domain` — in particular anything with whitespace, commas,
|
||||
/// angle brackets or line breaks, which are the ingredients for header
|
||||
/// injection or smuggling extra recipients into a field.
|
||||
pub fn normalize_recipients(input: &[String]) -> Result<Vec<String>, String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for raw in input {
|
||||
let addr = raw.trim();
|
||||
if addr.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let valid = !addr
|
||||
.chars()
|
||||
.any(|c| c.is_whitespace() || matches!(c, ',' | ';' | '<' | '>' | '"'))
|
||||
&& matches!(addr.split_once('@'), Some((local, domain))
|
||||
if !local.is_empty() && !domain.is_empty() && !domain.contains('@') && domain.contains('.'));
|
||||
if !valid {
|
||||
return Err(format!("not a valid email address: {addr:?}"));
|
||||
}
|
||||
if !out.iter().any(|a| a.eq_ignore_ascii_case(addr)) {
|
||||
out.push(addr.to_string());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Headers for a reply to `parent`: In-Reply-To is the parent's ID, and
|
||||
/// References is the parent's chain plus the parent itself.
|
||||
///
|
||||
/// Long chains are trimmed to the first ID plus the most recent ones, as
|
||||
/// RFC 5322 §3.6.4 suggests — the root anchors the thread, the tail links
|
||||
/// the immediate ancestors, and the middle is what's safe to drop.
|
||||
pub fn reply_headers(
|
||||
parent_message_id: Option<&str>,
|
||||
parent_references: &[String],
|
||||
) -> (Option<String>, Vec<String>) {
|
||||
const MAX_REFERENCES: usize = 20;
|
||||
|
||||
let parent = parent_message_id.map(bare_id).filter(|id| !id.is_empty());
|
||||
|
||||
let mut refs: Vec<String> = Vec::new();
|
||||
for id in parent_references
|
||||
.iter()
|
||||
.map(|r| bare_id(r))
|
||||
.chain(parent.clone())
|
||||
{
|
||||
if !id.is_empty() && !refs.contains(&id) {
|
||||
refs.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
if refs.len() > MAX_REFERENCES {
|
||||
let tail = refs.split_off(refs.len() - (MAX_REFERENCES - 1));
|
||||
refs.truncate(1);
|
||||
refs.extend(tail);
|
||||
}
|
||||
|
||||
(parent, refs)
|
||||
}
|
||||
|
||||
pub fn new_message_id(sender_email: &str) -> String {
|
||||
let domain = sender_email
|
||||
.rsplit_once('@')
|
||||
.map(|(_, d)| d)
|
||||
.unwrap_or("tern.invalid");
|
||||
format!("{}@{}", Uuid::new_v4(), domain)
|
||||
}
|
||||
|
||||
pub fn render(sender: &Sender, draft: &Draft) -> anyhow::Result<(Vec<u8>, Envelope)> {
|
||||
let from: (String, String) = (
|
||||
sender.display_name.unwrap_or("").to_string(),
|
||||
sender.email.to_string(),
|
||||
);
|
||||
|
||||
let mut builder = MessageBuilder::new()
|
||||
.from(from)
|
||||
.subject(strip_line_breaks(draft.subject))
|
||||
.message_id(bare_id(draft.message_id))
|
||||
.date(draft.date_unix)
|
||||
.text_body(draft.text_body.to_string());
|
||||
|
||||
if !draft.to.is_empty() {
|
||||
builder = builder.to(draft.to.to_vec());
|
||||
}
|
||||
if !draft.cc.is_empty() {
|
||||
builder = builder.cc(draft.cc.to_vec());
|
||||
}
|
||||
// Deliberately no builder.bcc(): mail-builder writes Bcc as an ordinary
|
||||
// header, which would show every blind-copied address to every
|
||||
// recipient. Bcc goes into the envelope below and nowhere else.
|
||||
if let Some(parent) = draft.in_reply_to {
|
||||
builder = builder.in_reply_to(bare_id(parent));
|
||||
}
|
||||
if !draft.references.is_empty() {
|
||||
builder = builder.references(
|
||||
draft
|
||||
.references
|
||||
.iter()
|
||||
.map(|r| bare_id(r))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
}
|
||||
|
||||
let bytes = builder.write_to_vec()?;
|
||||
|
||||
let mut rcpt_to: Vec<String> = Vec::new();
|
||||
for addr in draft.to.iter().chain(draft.cc).chain(draft.bcc) {
|
||||
if !rcpt_to.iter().any(|a| a.eq_ignore_ascii_case(addr)) {
|
||||
rcpt_to.push(addr.clone());
|
||||
}
|
||||
}
|
||||
|
||||
Ok((
|
||||
bytes,
|
||||
Envelope {
|
||||
mail_from: sender.email.to_string(),
|
||||
rcpt_to,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
fn strip_line_breaks(s: &str) -> String {
|
||||
s.replace(['\r', '\n'], " ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn draft<'a>(to: &'a [String], cc: &'a [String], bcc: &'a [String]) -> Draft<'a> {
|
||||
Draft {
|
||||
to,
|
||||
cc,
|
||||
bcc,
|
||||
subject: "Hello",
|
||||
text_body: "body text",
|
||||
message_id: "abc@example.com",
|
||||
in_reply_to: None,
|
||||
references: &[],
|
||||
date_unix: 1_790_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
fn sender() -> Sender<'static> {
|
||||
Sender {
|
||||
email: "alice@example.com",
|
||||
display_name: Some("Alice"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bcc_goes_in_envelope_but_never_in_the_message() {
|
||||
let to = vec!["bob@example.com".to_string()];
|
||||
let bcc = vec!["secret@example.com".to_string()];
|
||||
let (bytes, envelope) = render(&sender(), &draft(&to, &[], &bcc)).unwrap();
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
|
||||
assert!(envelope.rcpt_to.contains(&"secret@example.com".to_string()));
|
||||
assert!(
|
||||
!text.contains("secret@example.com"),
|
||||
"bcc address leaked into message:\n{text}"
|
||||
);
|
||||
assert!(
|
||||
!text.to_ascii_lowercase().contains("bcc:"),
|
||||
"a Bcc header was written:\n{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn envelope_dedupes_across_fields() {
|
||||
let to = vec!["bob@example.com".to_string()];
|
||||
let cc = vec![
|
||||
"BOB@example.com".to_string(),
|
||||
"carol@example.com".to_string(),
|
||||
];
|
||||
let (_, envelope) = render(&sender(), &draft(&to, &cc, &[])).unwrap();
|
||||
assert_eq!(
|
||||
envelope.rcpt_to,
|
||||
vec!["bob@example.com", "carol@example.com"]
|
||||
);
|
||||
assert_eq!(envelope.mail_from, "alice@example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_headers_are_rendered_bracketed() {
|
||||
let to = vec!["bob@example.com".to_string()];
|
||||
let refs = vec![
|
||||
"root@example.com".to_string(),
|
||||
"parent@example.com".to_string(),
|
||||
];
|
||||
let mut d = draft(&to, &[], &[]);
|
||||
d.in_reply_to = Some("parent@example.com");
|
||||
d.references = &refs;
|
||||
let text = String::from_utf8(render(&sender(), &d).unwrap().0).unwrap();
|
||||
|
||||
assert!(text.contains("In-Reply-To: <parent@example.com>"), "{text}");
|
||||
assert!(
|
||||
text.contains("<root@example.com>") && text.contains("References:"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains("Message-ID: <abc@example.com>"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subject_line_breaks_cannot_inject_headers() {
|
||||
let to = vec!["bob@example.com".to_string()];
|
||||
let mut d = draft(&to, &[], &[]);
|
||||
d.subject = "hi\r\nBcc: attacker@example.com";
|
||||
let text = String::from_utf8(render(&sender(), &d).unwrap().0).unwrap();
|
||||
assert!(!text.contains("\r\nBcc:"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_id_strips_brackets_and_whitespace() {
|
||||
assert_eq!(bare_id(" <abc@x.y> "), "abc@x.y");
|
||||
assert_eq!(bare_id("abc@x.y"), "abc@x.y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_headers_chain_parent_onto_references() {
|
||||
let refs = vec!["<root@x>".to_string()];
|
||||
let (irt, chain) = reply_headers(Some("<parent@x>"), &refs);
|
||||
assert_eq!(irt.as_deref(), Some("parent@x"));
|
||||
assert_eq!(chain, vec!["root@x", "parent@x"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reply_headers_trim_long_chains_keeping_root_and_tail() {
|
||||
let refs: Vec<String> = (0..30).map(|i| format!("m{i}@x")).collect();
|
||||
let (_, chain) = reply_headers(Some("parent@x"), &refs);
|
||||
assert_eq!(chain.len(), 20);
|
||||
assert_eq!(chain.first().unwrap(), "m0@x", "root must survive trimming");
|
||||
assert_eq!(
|
||||
chain.last().unwrap(),
|
||||
"parent@x",
|
||||
"direct parent must survive trimming"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipients_are_validated_and_deduped() {
|
||||
let ok = normalize_recipients(&[
|
||||
" bob@example.com ".into(),
|
||||
"".into(),
|
||||
"Bob@Example.com".into(),
|
||||
"carol@example.org".into(),
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(ok, vec!["bob@example.com", "carol@example.org"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipients_reject_injection_shapes() {
|
||||
for bad in [
|
||||
"bob@example.com, eve@example.com",
|
||||
"Bob <bob@example.com>",
|
||||
"bob@example.com\r\nBcc: eve@example.com",
|
||||
"no-at-sign",
|
||||
"a@b@c.com",
|
||||
"bob@localhost",
|
||||
] {
|
||||
assert!(
|
||||
normalize_recipients(&[bad.to_string()]).is_err(),
|
||||
"accepted {bad:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod compose;
|
||||
pub mod tls;
|
||||
pub mod worker;
|
||||
@@ -0,0 +1,44 @@
|
||||
//! TLS connector for SMTP submission, trusting the OS certificate store.
|
||||
//!
|
||||
//! mail-send's own connector trusts only its compiled-in `webpki-roots`
|
||||
//! (public CAs). IMAP goes through native-tls, which uses the OS store — so
|
||||
//! without this, a self-hosted mail server with an internal-CA certificate
|
||||
//! would sync fine and then fail every send on certificate verification.
|
||||
//! Using the OS store here keeps both protocols trusting the same thing.
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use tokio_rustls::TlsConnector;
|
||||
|
||||
static CONNECTOR: OnceLock<TlsConnector> = OnceLock::new();
|
||||
|
||||
pub fn connector() -> Result<TlsConnector> {
|
||||
if let Some(c) = CONNECTOR.get() {
|
||||
return Ok(c.clone());
|
||||
}
|
||||
|
||||
let mut roots = rustls::RootCertStore::empty();
|
||||
let loaded = rustls_native_certs::load_native_certs();
|
||||
for err in &loaded.errors {
|
||||
tracing::warn!(error = %err, "skipping unreadable certificate in the OS trust store");
|
||||
}
|
||||
let (added, _ignored) = roots.add_parsable_certificates(loaded.certs);
|
||||
anyhow::ensure!(
|
||||
added > 0,
|
||||
"no usable certificates in the OS trust store — SMTP TLS cannot verify any server"
|
||||
);
|
||||
|
||||
// Explicit provider rather than the process default: if anything in the
|
||||
// dependency tree ever enables a second rustls backend, the implicit
|
||||
// default becomes ambiguous and ClientConfig::builder() panics.
|
||||
let config = rustls::ClientConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.context("building rustls protocol config")?
|
||||
.with_root_certificates(roots)
|
||||
.with_no_client_auth();
|
||||
|
||||
let connector = TlsConnector::from(Arc::new(config));
|
||||
Ok(CONNECTOR.get_or_init(|| connector).clone())
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
//! Drains the outbox: claims due items, submits them over SMTP, and either
|
||||
//! records them as sent or schedules a retry (server-architecture-spec.md
|
||||
//! §3.3 — never send synchronously in the request path).
|
||||
//!
|
||||
//! Delivery is at-least-once. If the process dies after the SMTP server has
|
||||
//! accepted a message but before we record it, the item is reclaimed and
|
||||
//! sent again. Reusing the same Message-ID on every attempt means that
|
||||
//! duplicate is at least recognisable as the same message to recipients'
|
||||
//! 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};
|
||||
use crate::storage::BlobStore;
|
||||
use anyhow::Context;
|
||||
use chrono::Utc;
|
||||
use mail_send::SmtpClientBuilder;
|
||||
use sqlx::PgPool;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
pub const MAX_ATTEMPTS: i32 = 6;
|
||||
const IDLE_POLL: Duration = Duration::from_secs(30);
|
||||
const SMTP_TIMEOUT: Duration = Duration::from_secs(60);
|
||||
/// A row still marked 'sending' this long after its last update belongs to
|
||||
/// a worker that died mid-send; it's put back in the queue.
|
||||
const STALE_SENDING_AFTER_MINUTES: i32 = 10;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Failure {
|
||||
/// Worth retrying: network trouble, timeouts, 4xx "try again later".
|
||||
Transient(String),
|
||||
/// Retrying can't help: 5xx rejections, bad credentials, misconfigured
|
||||
/// account. Failing fast shows the reader the reason immediately rather
|
||||
/// than after half an hour of backoff.
|
||||
Permanent(String),
|
||||
}
|
||||
|
||||
/// 1, 2, 4, 8, 16 minutes between attempts — about half an hour of trying
|
||||
/// in total across MAX_ATTEMPTS before the item is marked failed.
|
||||
pub fn retry_delay(attempts_so_far: i32) -> Duration {
|
||||
let exp = attempts_so_far.clamp(1, 16) - 1;
|
||||
Duration::from_secs(60 * 2u64.pow(exp as u32)).min(Duration::from_secs(30 * 60))
|
||||
}
|
||||
|
||||
pub fn classify(err: &mail_send::Error) -> Failure {
|
||||
use mail_send::Error as E;
|
||||
let msg = err.to_string();
|
||||
match err {
|
||||
E::UnexpectedReply(resp) if resp.code >= 500 => Failure::Permanent(msg),
|
||||
E::UnexpectedReply(_) => Failure::Transient(msg),
|
||||
E::AuthenticationFailed(_)
|
||||
| E::MissingCredentials
|
||||
| E::UnsupportedAuthMechanism
|
||||
| E::MissingStartTls
|
||||
| E::InvalidTLSName
|
||||
| E::MissingMailFrom
|
||||
| E::MissingRcptTo => Failure::Permanent(msg),
|
||||
// Almost always an untrusted or mismatched certificate rather than
|
||||
// a transient handshake hiccup — a config problem, so fail fast.
|
||||
E::Tls(_) => Failure::Permanent(msg),
|
||||
_ => Failure::Transient(msg),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(
|
||||
pool: PgPool,
|
||||
cipher: CredentialCipher,
|
||||
blobs: BlobStore,
|
||||
wake: Arc<Notify>,
|
||||
events: EventHub,
|
||||
) {
|
||||
if let Err(e) = recover_stale(&pool).await {
|
||||
tracing::error!(error = %e, "failed to recover stale outbox items");
|
||||
}
|
||||
|
||||
loop {
|
||||
match claim_next(&pool).await {
|
||||
Ok(Some(item)) => {
|
||||
let id = item.id;
|
||||
if let Err(e) = process(&pool, &cipher, &blobs, item).await {
|
||||
// Only reached if recording the outcome itself failed —
|
||||
// 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) => {}
|
||||
Err(e) => tracing::error!(error = %e, "failed to claim outbox item"),
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = wake.notified() => {}
|
||||
_ = tokio::time::sleep(IDLE_POLL) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<Option<(uuid::Uuid, String, Option<uuid::Uuid>)>, _> = 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() \
|
||||
WHERE status = 'sending' AND updated_at < now() - make_interval(mins => $1)",
|
||||
)
|
||||
.bind(STALE_SENDING_AFTER_MINUTES)
|
||||
.execute(pool)
|
||||
.await?
|
||||
.rows_affected();
|
||||
if recovered > 0 {
|
||||
tracing::warn!(
|
||||
recovered,
|
||||
"re-queued outbox items left mid-send by a previous run"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// SKIP LOCKED so that several server instances can share one queue
|
||||
/// without two of them picking up the same message.
|
||||
async fn claim_next(pool: &PgPool) -> anyhow::Result<Option<OutboxItem>> {
|
||||
Ok(sqlx::query_as(
|
||||
"UPDATE outbox SET status = 'sending', attempts = attempts + 1, updated_at = now() \
|
||||
WHERE id = ( \
|
||||
SELECT id FROM outbox \
|
||||
WHERE status = 'pending' AND next_attempt_at <= now() \
|
||||
ORDER BY next_attempt_at \
|
||||
FOR UPDATE SKIP LOCKED \
|
||||
LIMIT 1) \
|
||||
RETURNING *",
|
||||
)
|
||||
.fetch_optional(pool)
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn process(
|
||||
pool: &PgPool,
|
||||
cipher: &CredentialCipher,
|
||||
blobs: &BlobStore,
|
||||
item: OutboxItem,
|
||||
) -> anyhow::Result<()> {
|
||||
match send(pool, cipher, &item).await {
|
||||
Ok((bytes, sender_email, sender_name)) => {
|
||||
record_sent(
|
||||
pool,
|
||||
blobs,
|
||||
&item,
|
||||
&bytes,
|
||||
&sender_email,
|
||||
sender_name.as_deref(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
Err(Failure::Permanent(reason)) => record_failed(pool, &item, &reason).await,
|
||||
Err(Failure::Transient(reason)) if item.attempts >= MAX_ATTEMPTS => {
|
||||
record_failed(
|
||||
pool,
|
||||
&item,
|
||||
&format!("gave up after {} attempts: {reason}", item.attempts),
|
||||
)
|
||||
.await
|
||||
}
|
||||
Err(Failure::Transient(reason)) => {
|
||||
let delay = retry_delay(item.attempts);
|
||||
tracing::warn!(outbox_id = %item.id, attempt = item.attempts, ?delay, %reason, "send failed, will retry");
|
||||
sqlx::query(
|
||||
"UPDATE outbox SET status = 'pending', last_error = $2, updated_at = now(), \
|
||||
next_attempt_at = now() + make_interval(secs => $3) WHERE id = $1",
|
||||
)
|
||||
.bind(item.id)
|
||||
.bind(&reason)
|
||||
.bind(delay.as_secs_f64())
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(
|
||||
pool: &PgPool,
|
||||
cipher: &CredentialCipher,
|
||||
item: &OutboxItem,
|
||||
) -> Result<(Vec<u8>, String, Option<String>), Failure> {
|
||||
let account: Account = sqlx::query_as("SELECT * FROM accounts WHERE id = $1")
|
||||
.bind(item.account_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| Failure::Transient(format!("loading account: {e}")))?;
|
||||
|
||||
let sender_email = account.sender_address().ok_or_else(|| {
|
||||
Failure::Permanent(
|
||||
"account has no sender address — set email_address on the account".into(),
|
||||
)
|
||||
})?;
|
||||
|
||||
let message_id = item
|
||||
.message_id
|
||||
.clone()
|
||||
.ok_or_else(|| Failure::Permanent("queued without a Message-ID".into()))?;
|
||||
|
||||
let draft = Draft {
|
||||
to: &item.to_addrs,
|
||||
cc: &item.cc_addrs,
|
||||
bcc: &item.bcc_addrs,
|
||||
subject: &item.subject,
|
||||
text_body: &item.text_body,
|
||||
message_id: &message_id,
|
||||
in_reply_to: item.in_reply_to.as_deref(),
|
||||
references: &item.references_,
|
||||
date_unix: Utc::now().timestamp(),
|
||||
};
|
||||
let sender = Sender {
|
||||
email: &sender_email,
|
||||
display_name: account.display_name.as_deref(),
|
||||
};
|
||||
let (bytes, envelope) = compose::render(&sender, &draft)
|
||||
.map_err(|e| Failure::Permanent(format!("rendering message: {e}")))?;
|
||||
|
||||
let password = cipher
|
||||
.decrypt(&account.encrypted_password, &account.password_nonce)
|
||||
.map_err(|e| Failure::Permanent(format!("decrypting SMTP password: {e}")))?;
|
||||
|
||||
let connector = crate::smtp::tls::connector().map_err(|e| Failure::Permanent(e.to_string()))?;
|
||||
|
||||
// Port 587 with STARTTLS is the spec's default (§3.3); implicit TLS
|
||||
// (typically 465) when STARTTLS is off. Never plaintext — mail-send's
|
||||
// connect() returns a TLS-typed client and errors with MissingStartTls
|
||||
// rather than falling back.
|
||||
let mut builder = SmtpClientBuilder::new(account.smtp_host.clone(), account.smtp_port as u16)
|
||||
.implicit_tls(!account.smtp_use_starttls)
|
||||
.credentials((account.username.clone(), password))
|
||||
.timeout(SMTP_TIMEOUT);
|
||||
builder.tls_connector = connector;
|
||||
|
||||
let message = mail_send::smtp::message::Message {
|
||||
mail_from: envelope.mail_from.clone().into(),
|
||||
rcpt_to: envelope.rcpt_to.iter().map(|r| r.clone().into()).collect(),
|
||||
body: bytes.clone().into(),
|
||||
};
|
||||
|
||||
let mut client = builder.connect().await.map_err(|e| classify(&e))?;
|
||||
client.send(message).await.map_err(|e| classify(&e))?;
|
||||
let _ = client.quit().await;
|
||||
|
||||
Ok((bytes, sender_email, account.display_name))
|
||||
}
|
||||
|
||||
/// Puts the sent message into the thread it belongs to, in the same
|
||||
/// transaction that marks the outbox item sent — so there's never a moment
|
||||
/// where it's recorded as sent but missing from the conversation.
|
||||
async fn record_sent(
|
||||
pool: &PgPool,
|
||||
blobs: &BlobStore,
|
||||
item: &OutboxItem,
|
||||
bytes: &[u8],
|
||||
sender_email: &str,
|
||||
sender_name: Option<&str>,
|
||||
) -> anyhow::Result<()> {
|
||||
let (_, raw_ref) = blobs
|
||||
.put(bytes)
|
||||
.await
|
||||
.context("storing sent message blob")?;
|
||||
|
||||
let mut tx = pool.begin().await?;
|
||||
|
||||
let (message_row_id,): (uuid::Uuid,) = sqlx::query_as(
|
||||
r#"INSERT INTO messages
|
||||
(account_id, uid, source, message_id, in_reply_to, references_, thread_id,
|
||||
from_addr, from_name, to_addrs, cc_addrs, subject, sent_at, flags,
|
||||
body_fetched, raw_blob_ref)
|
||||
VALUES ($1, NULL, 'sent', $2, $3, $4, COALESCE($5, gen_random_uuid()),
|
||||
$6, $7, $8, $9, $10, now(), ARRAY['\Seen'], true, $11)
|
||||
RETURNING id"#,
|
||||
)
|
||||
.bind(item.account_id)
|
||||
.bind(item.message_id.as_deref().map(compose::bare_id))
|
||||
.bind(&item.in_reply_to)
|
||||
.bind(&item.references_)
|
||||
.bind(item.thread_id)
|
||||
.bind(sender_email)
|
||||
.bind(sender_name)
|
||||
.bind(&item.to_addrs)
|
||||
.bind(&item.cc_addrs)
|
||||
.bind(&item.subject)
|
||||
.bind(&raw_ref)
|
||||
.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)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE outbox SET status = 'sent', sent_at = now(), updated_at = now(), \
|
||||
last_error = NULL, sent_message_id = $2 WHERE id = $1",
|
||||
)
|
||||
.bind(item.id)
|
||||
.bind(message_row_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
tracing::info!(outbox_id = %item.id, recipients = item.to_addrs.len() + item.cc_addrs.len() + item.bcc_addrs.len(), "message sent");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn record_failed(pool: &PgPool, item: &OutboxItem, reason: &str) -> anyhow::Result<()> {
|
||||
tracing::warn!(outbox_id = %item.id, %reason, "send failed permanently");
|
||||
sqlx::query(
|
||||
"UPDATE outbox SET status = 'failed', last_error = $2, updated_at = now() WHERE id = $1",
|
||||
)
|
||||
.bind(item.id)
|
||||
.bind(reason)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn backoff_doubles_and_caps() {
|
||||
let mins: Vec<u64> = (1..=MAX_ATTEMPTS)
|
||||
.map(|a| retry_delay(a).as_secs() / 60)
|
||||
.collect();
|
||||
assert_eq!(mins, vec![1, 2, 4, 8, 16, 30]);
|
||||
assert_eq!(retry_delay(40), Duration::from_secs(30 * 60));
|
||||
}
|
||||
|
||||
fn reply(code: u16) -> mail_send::Error {
|
||||
mail_send::Error::UnexpectedReply(smtp_proto::Response {
|
||||
code,
|
||||
esc: [0, 0, 0],
|
||||
message: String::new(),
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn five_hundreds_are_permanent_four_hundreds_retry() {
|
||||
assert!(matches!(classify(&reply(550)), Failure::Permanent(_)));
|
||||
assert!(matches!(classify(&reply(421)), Failure::Transient(_)));
|
||||
assert!(matches!(classify(&reply(451)), Failure::Transient(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_trouble_retries_config_trouble_does_not() {
|
||||
assert!(matches!(
|
||||
classify(&mail_send::Error::Timeout),
|
||||
Failure::Transient(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
classify(&mail_send::Error::Io(std::io::Error::other("reset"))),
|
||||
Failure::Transient(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
classify(&mail_send::Error::MissingStartTls),
|
||||
Failure::Permanent(_)
|
||||
));
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
//! Spam score extraction from filter headers (server-architecture-spec.md
|
||||
//! §3.5, build-order phase 6).
|
||||
//!
|
||||
//! Proxmox Mail Gateway runs SpamAssassin and reports through headers whose
|
||||
//! names are configurable, so this recognises the formats actually seen in
|
||||
//! the wild rather than one fixed header:
|
||||
//!
|
||||
//! - PMG's `X-SPAM-LEVEL: Spam detection results: 8` — folded across lines,
|
||||
//! with each matching rule and its score listed after the total.
|
||||
//! - `X-Spam-Score: 5.3` — a bare number.
|
||||
//! - `X-Spam-Status: Yes, score=7.2 required=5.0 …` — SpamAssassin's status.
|
||||
//! - `X-Spam-Level: *******` — SpamAssassin's star bar, one per point.
|
||||
//!
|
||||
//! Note the name collision: PMG and SpamAssassin both use X-Spam-Level (header
|
||||
//! names are case-insensitive), for completely different formats. Taking
|
||||
//! "the first number in the header" would work for PMG and read nothing
|
||||
//! from the star bar, so each format is matched explicitly.
|
||||
//!
|
||||
//! PMG only adds its header from spam level 3 upwards by default, so mail
|
||||
//! below that has no score — `None`, meaning "not flagged", not "zero".
|
||||
|
||||
use regex::Regex;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
static PMG_RESULTS: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?i)spam detection results:\s*(-?\d+(?:\.\d+)?)").unwrap());
|
||||
static STATUS_SCORE: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"(?i)\bscore=(-?\d+(?:\.\d+)?)").unwrap());
|
||||
static BARE_NUMBER: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^\s*(-?\d+(?:\.\d+)?)\s*$").unwrap());
|
||||
|
||||
fn values_of<'a>(headers: &'a [(String, String)], name: &'a str) -> impl Iterator<Item = &'a str> {
|
||||
headers
|
||||
.iter()
|
||||
.filter(move |(n, _)| n == name)
|
||||
.map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
/// The message's spam score, from the most specific header present.
|
||||
/// `headers` are (lowercased name, unfolded value) pairs.
|
||||
pub fn extract_score(headers: &[(String, String)]) -> Option<f64> {
|
||||
let values = |name: &'static str| values_of(headers, name);
|
||||
|
||||
// PMG's detailed result, the one this deployment is built around.
|
||||
for v in values("x-spam-level") {
|
||||
if let Some(c) = PMG_RESULTS.captures(v) {
|
||||
return c[1].parse().ok();
|
||||
}
|
||||
}
|
||||
for v in values("x-spam-score") {
|
||||
if let Some(c) = BARE_NUMBER.captures(v) {
|
||||
return c[1].parse().ok();
|
||||
}
|
||||
}
|
||||
for v in values("x-spam-status") {
|
||||
if let Some(c) = STATUS_SCORE.captures(v) {
|
||||
return c[1].parse().ok();
|
||||
}
|
||||
}
|
||||
// SpamAssassin's star bar is the least precise (whole points, floored),
|
||||
// so it's the last resort.
|
||||
for v in values("x-spam-level") {
|
||||
let v = v.trim();
|
||||
if !v.is_empty() && v.chars().all(|c| c == '*') {
|
||||
return Some(v.len() as f64);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn h(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(n, v)| (n.to_string(), v.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pmg_detection_results_take_the_total_not_a_rule_score() {
|
||||
// As unfolded by the parser: total first, then per-rule scores —
|
||||
// including negative ones that must not be mistaken for the total.
|
||||
let pmg = "Spam detection results: 8 DKIM_SIGNED 0.1 Message has a DKIM or DK signature, not necessarily valid DKIM_VALID -0.1 Message has at least one valid DKIM or DK signature";
|
||||
assert_eq!(extract_score(&h(&[("x-spam-level", pmg)])), Some(8.0));
|
||||
assert_eq!(
|
||||
extract_score(&h(&[("x-spam-level", "Spam detection results: -1.5")])),
|
||||
Some(-1.5)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spamassassin_star_bar_counts_stars() {
|
||||
assert_eq!(extract_score(&h(&[("x-spam-level", "*******")])), Some(7.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_score_and_status_formats() {
|
||||
assert_eq!(extract_score(&h(&[("x-spam-score", "5.3")])), Some(5.3));
|
||||
assert_eq!(
|
||||
extract_score(&h(&[(
|
||||
"x-spam-status",
|
||||
"Yes, score=7.25 required=5.0 tests=BAYES_99"
|
||||
)])),
|
||||
Some(7.25)
|
||||
);
|
||||
assert_eq!(
|
||||
extract_score(&h(&[("x-spam-status", "No, score=1.41")])),
|
||||
Some(1.41)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pmg_wins_over_less_precise_headers() {
|
||||
let both = h(&[
|
||||
("x-spam-level", "****"),
|
||||
("x-spam-status", "Yes, score=4.9"),
|
||||
("x-spam-level", "Spam detection results: 6"),
|
||||
]);
|
||||
assert_eq!(extract_score(&both), Some(6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unflagged_mail_has_no_score_rather_than_zero() {
|
||||
assert_eq!(
|
||||
extract_score(&h(&[("subject", "hi"), ("x-spam-flag", "NO")])),
|
||||
None
|
||||
);
|
||||
// Not a star bar, not a number: ignored rather than guessed at.
|
||||
assert_eq!(extract_score(&h(&[("x-spam-score", "high")])), None);
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -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
|
||||
|
||||
@@ -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:"), "");
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
//! Route-shape tests.
|
||||
//!
|
||||
//! These exist because path-parameter syntax is version-specific and fails
|
||||
//! silently: axum 0.7 spells a parameter `:id`, while 0.8 spells it `{id}`.
|
||||
//! Using the wrong one doesn't error at compile time or startup — the router
|
||||
//! just treats it as a literal segment and every request 404s. Three
|
||||
//! endpoints shipped broken that way, and a list-endpoint smoke test didn't
|
||||
//! notice.
|
||||
//!
|
||||
//! A 404 here means the route isn't matching. Any other status (401 without
|
||||
//! credentials, 500 with no database) means it matched, which is all these
|
||||
//! assert.
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use tower::ServiceExt;
|
||||
|
||||
/// Builds the real router against a lazily-connected pool. The pool is never
|
||||
/// used, because every request under test stops at the auth extractor or the
|
||||
/// router itself — but it has to be a real `PgPool` to construct AppState.
|
||||
fn test_router() -> axum::Router {
|
||||
let pool = sqlx::postgres::PgPoolOptions::new()
|
||||
.connect_lazy("postgres://tern:tern@127.0.0.1:1/placeholder")
|
||||
.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")),
|
||||
session_ttl_hours: 1,
|
||||
config: tern_server::config::Config {
|
||||
database_url: String::new(),
|
||||
bind_addr: String::new(),
|
||||
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()),
|
||||
};
|
||||
|
||||
tern_server::api::build(state)
|
||||
}
|
||||
|
||||
async fn status_for(method: &str, uri: &str) -> StatusCode {
|
||||
let request = Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
|
||||
test_router().oneshot(request).await.unwrap().status()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn parameterised_routes_match() {
|
||||
let id = "4f6cf11f-da82-49cf-9988-7b450b97a1c3";
|
||||
|
||||
for (method, uri) in [
|
||||
("GET", format!("/api/messages/{id}")),
|
||||
("GET", format!("/api/threads/{id}")),
|
||||
("DELETE", format!("/api/accounts/{id}")),
|
||||
("POST", format!("/api/threads/{id}/read")),
|
||||
("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!(
|
||||
status,
|
||||
StatusCode::NOT_FOUND,
|
||||
"{method} {uri} did not match any route — check the path parameter syntax \
|
||||
against the axum version in Cargo.toml"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn collection_routes_match() {
|
||||
for uri in [
|
||||
"/api/accounts",
|
||||
"/api/folders",
|
||||
"/api/messages",
|
||||
"/api/threads",
|
||||
"/api/events",
|
||||
"/api/ws",
|
||||
"/api/outbox",
|
||||
"/api/tags",
|
||||
"/api/rules",
|
||||
] {
|
||||
let status = status_for("GET", uri).await;
|
||||
assert_ne!(
|
||||
status,
|
||||
StatusCode::NOT_FOUND,
|
||||
"GET {uri} did not match any route"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn healthz_is_public() {
|
||||
assert_eq!(status_for("GET", "/healthz").await, StatusCode::OK);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_route_still_404s() {
|
||||
assert_eq!(
|
||||
status_for("GET", "/api/nope").await,
|
||||
StatusCode::NOT_FOUND,
|
||||
"sanity check: a genuinely missing route should 404"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user