Add thread listing, fix dead path routes
CI / test (push) Successful in 29s

Adds GET /api/threads, grouped server-side: 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. The
thread detail endpoint now returns bodies too, so opening a conversation
is one request rather than one per message.

Fixes three routes that have been dead since the first commit. axum 0.7
spells a path parameter ':id'; '{id}' is axum 0.8 syntax and was being
matched as a literal segment, so GET /api/messages/<id>, GET
/api/threads/<id> and DELETE /api/accounts/<id> all 404'd. This fails
silently — no compile or startup error — and the original smoke test
only exercised list endpoints. Found by clicking a conversation in the
webapp.

Adds tests/routes.rs to cover route shape, verified to fail against the
old syntax.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Mateusz PstruchaandClaude Opus 5 committed 2026-09-22 22:53:13 +02:00
1 parent 6c73a91b8e
commit bc39a1221c
6 files changed
+222 -6

No files matched your search

+1
View File
@@ -7,6 +7,7 @@ The sync server for [Tern](../) — the only component that ever speaks IMAP/SMT
- **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.
- **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.
## What's explicitly deferred
+19 -2
View File
@@ -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))
}
+1
View File
@@ -6,6 +6,7 @@ pub mod messages;
pub mod middleware;
pub mod router;
pub mod state;
pub mod threads;
pub use router::build;
pub use state::AppState;
+5 -4
View File
@@ -1,5 +1,5 @@
use crate::api::state::AppState;
use crate::api::{accounts, auth, events, folders, messages};
use crate::api::{accounts, auth, events, folders, messages, threads};
use axum::routing::{delete, get, post};
use axum::Router;
use tower_http::cors::CorsLayer;
@@ -10,11 +10,12 @@ 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/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/events", get(events::poll))
.route("/healthz", get(|| async { "ok" }))
.layer(TraceLayer::new_for_http())
+94
View File
@@ -0,0 +1,94 @@
//! Thread-grouped listing — one row per conversation, which is how both
//! clients render the inbox.
//!
//! This has to be grouped 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.
//!
//! Cursor is the thread's `last_message_at`, matching the cursor-based
//! (not offset) approach in server-architecture-spec.md §4.
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::ApiResult;
use axum::{
extract::{Query, State},
Json,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Deserialize)]
pub struct ListThreadsQuery {
pub folder_id: Option<Uuid>,
pub before: Option<DateTime<Utc>>,
pub limit: Option<i64>,
}
#[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>,
pub last_message_at: Option<DateTime<Utc>>,
pub message_count: i64,
pub unread_count: i64,
pub has_attachments: bool,
}
#[derive(Serialize)]
pub struct ListThreadsResponse {
pub threads: Vec<ThreadSummary>,
pub next_cursor: Option<DateTime<Utc>>,
}
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 before = q.before.unwrap_or_else(Utc::now);
// Subject comes from the oldest message (the one that started the
// thread); sender and timestamp from the newest, which is what a list
// row should show. Unread is "no \Seen flag" — flags are stored in IMAP
// wire format, so the comparison is against the literal '\Seen'.
let threads: Vec<ThreadSummary> = sqlx::query_as(
r#"
SELECT
m.thread_id,
(ARRAY_AGG(m.subject ORDER BY m.sent_at ASC NULLS LAST))[1] AS subject,
(ARRAY_AGG(COALESCE(NULLIF(m.from_name, ''), m.from_addr)
ORDER BY m.sent_at DESC NULLS LAST))[1] AS last_from,
MAX(m.sent_at) AS last_message_at,
COUNT(*) AS message_count,
COUNT(*) FILTER (WHERE NOT ('\Seen' = ANY(m.flags))) AS unread_count,
BOOL_OR(EXISTS (SELECT 1 FROM attachments att WHERE att.message_id = m.id))
AS has_attachments
FROM messages m
JOIN accounts a ON a.id = m.account_id
WHERE a.user_id = $1
AND ($2::uuid IS NULL OR m.folder_id = $2)
GROUP BY m.thread_id
HAVING MAX(m.sent_at) < $3
ORDER BY last_message_at DESC
LIMIT $4
"#,
)
.bind(user.user_id)
.bind(q.folder_id)
.bind(before)
.bind(limit)
.fetch_all(&state.pool)
.await?;
let next_cursor = threads.last().and_then(|t| t.last_message_at);
Ok(Json(ListThreadsResponse {
threads,
next_cursor,
}))
}
+102
View File
@@ -0,0 +1,102 @@
//! 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 {
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,
},
};
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}")),
] {
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",
] {
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"
);
}