2 Commits
Author SHA1 Message Date
Mateusz PstruchaandClaude Opus 5.5 3614dffa1a Bump to 0.8.4
Release / image (push) Successful in 2m49s
CI / test (push) Successful in 4m48s
Release / deploy (push) Successful in 36s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:53:50 +02:00
Mateusz PstruchaandClaude Opus 5.5 dfd446617b Report account sync status; stop syncing removed accounts
CI / test (push) Successful in 4m22s
GET /api/accounts now includes each account's sync status, last error,
when it last changed, whether the first pass finished and how many
messages it has — what an accounts screen needs to show whether a
mailbox is working. The stored error now carries its cause chain
("…failed to lookup address information…", not just "TCP connect to
IMAP host failed").

Removing an account used to leave its sync task retrying forever
against rows that no longer exist; the manager now aborts tasks for
accounts that are gone. It's also woken when accounts are added or
removed, so a new mailbox starts syncing immediately instead of at the
next 30-second poll.

Creating an account now rejects blank hosts/login/password and
out-of-range ports up front, and removing a nonexistent one is a 404.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 13:48:57 +02:00
9 changed files with 120 additions and 18 deletions

No files matched your search

Generated
+1 -1
View File
@@ -3047,7 +3047,7 @@ dependencies = [
[[package]]
name = "tern-server"
version = "0.8.3"
version = "0.8.4"
dependencies = [
"aes-gcm",
"anyhow",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tern-server"
version = "0.8.3"
version = "0.8.4"
edition = "2021"
description = "Tern sync server — the only component that speaks IMAP/SMTP"
+62 -9
View File
@@ -1,8 +1,8 @@
use crate::api::middleware::CurrentUser;
use crate::api::state::AppState;
use crate::error::{ApiResult, AppJson};
use crate::error::{ApiError, ApiResult, AppJson};
use crate::events::{Change, ConfigKind};
use crate::models::account::{Account, AccountPublic};
use crate::models::account::{Account, AccountPublic, AccountSync};
use axum::{extract::State, Json};
use serde::Deserialize;
use uuid::Uuid;
@@ -35,17 +35,60 @@ pub async fn list(
.bind(user.user_id)
.fetch_all(&state.pool)
.await?;
let mut sync: std::collections::HashMap<Uuid, AccountSync> = sqlx::query_as::<_, AccountSync>(
"SELECT s.account_id, s.status, s.last_error, s.updated_at, s.caught_up, \
(SELECT count(*) FROM messages m \
WHERE m.account_id = s.account_id AND m.source = 'imap') AS messages \
FROM sync_state s JOIN accounts a ON a.id = s.account_id WHERE a.user_id = $1",
)
.bind(user.user_id)
.fetch_all(&state.pool)
.await?
.into_iter()
.map(|s| (s.account_id, s))
.collect();
Ok(Json(
accounts.into_iter().map(AccountPublic::from).collect(),
accounts
.into_iter()
.map(|a| {
let id = a.id;
AccountPublic {
sync: sync.remove(&id),
..AccountPublic::from(a)
}
})
.collect(),
))
}
/// Catches what would otherwise only fail later, in the sync task's log.
fn validate(req: &CreateAccountRequest) -> ApiResult<()> {
let blank = |s: &str| s.trim().is_empty();
if blank(&req.name) || blank(&req.imap_host) || blank(&req.smtp_host) || blank(&req.username) {
return Err(ApiError::BadRequest(
"name, IMAP server, SMTP server and login are all required".into(),
));
}
if req.password.is_empty() {
return Err(ApiError::BadRequest(
"the mailbox password is required".into(),
));
}
for (what, port) in [("IMAP", req.imap_port), ("SMTP", req.smtp_port)] {
if !(1..=65535).contains(&port) {
return Err(ApiError::BadRequest(format!("{what} port must be 1–65535")));
}
}
Ok(())
}
pub async fn create(
State(state): State<AppState>,
user: CurrentUser,
AppJson(req): AppJson<CreateAccountRequest>,
) -> ApiResult<Json<AccountPublic>> {
validate(&req)?;
let encrypted = state.cipher.encrypt(&req.password)?;
let account: Account = sqlx::query_as(
@@ -56,12 +99,12 @@ pub async fn create(
COALESCE($10, CASE WHEN $7 LIKE '%@%' THEN $7 END), $11, $12) RETURNING *",
)
.bind(user.user_id)
.bind(&req.name)
.bind(&req.imap_host)
.bind(req.name.trim())
.bind(req.imap_host.trim())
.bind(req.imap_port)
.bind(&req.smtp_host)
.bind(req.smtp_host.trim())
.bind(req.smtp_port)
.bind(&req.username)
.bind(req.username.trim())
.bind(&encrypted.ciphertext)
.bind(&encrypted.nonce)
.bind(req.email_address.as_deref().map(str::trim).filter(|e| !e.is_empty()))
@@ -75,6 +118,8 @@ pub async fn create(
.execute(&state.pool)
.await?;
// Start syncing now rather than at the manager's next poll.
state.sync_wake.notify_one();
state
.events
.emit(user.user_id, Change::config(ConfigKind::Accounts))
@@ -87,12 +132,20 @@ pub async fn delete(
user: CurrentUser,
axum::extract::Path(account_id): axum::extract::Path<Uuid>,
) -> ApiResult<Json<serde_json::Value>> {
sqlx::query("DELETE FROM accounts WHERE id = $1 AND user_id = $2")
// Its mail goes with it (ON DELETE CASCADE); the clients say so before
// asking. Stored files are cleaned up by the retention task's orphan GC.
let deleted = sqlx::query("DELETE FROM accounts WHERE id = $1 AND user_id = $2")
.bind(account_id)
.bind(user.user_id)
.execute(&state.pool)
.await?;
.await?
.rows_affected();
if deleted == 0 {
return Err(ApiError::NotFound);
}
// Stop its sync task now, not at the manager's next poll.
state.sync_wake.notify_one();
state
.events
.emit(user.user_id, Change::config(ConfigKind::Accounts))
+2
View File
@@ -17,6 +17,8 @@ pub struct AppState {
/// Wakes the outbox worker as soon as something is queued, so a send
/// goes out immediately rather than at the next idle poll.
pub outbox_wake: Arc<Notify>,
/// Wakes the sync manager when accounts are added or removed.
pub sync_wake: Arc<Notify>,
pub events: EventHub,
pub pusher: Pusher,
}
+5 -2
View File
@@ -98,8 +98,11 @@ impl AccountSyncer {
return;
}
Err(e) => {
tracing::warn!(account_id = %self.account.id, error = %e, "sync connection dropped, reconnecting");
let _ = self.mark_status("error", Some(&e.to_string())).await;
// {:#} includes the cause chain — "TCP connect failed"
// alone doesn't say it was DNS, a refused port or TLS.
let detail = format!("{e:#}");
tracing::warn!(account_id = %self.account.id, error = %detail, "sync connection dropped, reconnecting");
let _ = self.mark_status("error", Some(&detail)).await;
tokio::time::sleep(backoff.next_delay()).await;
}
}
+28 -5
View File
@@ -1,5 +1,6 @@
//! Spawns and tracks one sync task per account. Polls for newly-added
//! accounts periodically rather than requiring a restart to pick them up.
//! Spawns and tracks one sync task per account, and stops the task of an
//! account that was removed. Woken by the API when accounts change, and
//! polls as a fallback.
use crate::crypto::CredentialCipher;
use crate::events::EventHub;
@@ -7,13 +8,21 @@ use crate::imap_sync::connection::AccountSyncer;
use crate::models::account::Account;
use crate::storage::BlobStore;
use sqlx::PgPool;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Notify;
use uuid::Uuid;
const ACCOUNT_POLL_INTERVAL: Duration = Duration::from_secs(30);
pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, events: EventHub) {
pub async fn run(
pool: PgPool,
cipher: CredentialCipher,
blobs: BlobStore,
events: EventHub,
wake: Arc<Notify>,
) {
let mut running: HashMap<Uuid, tokio::task::JoinHandle<()>> = HashMap::new();
loop {
@@ -24,6 +33,17 @@ pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, event
.await
{
Ok(accounts) => {
// A removed account's task would otherwise retry forever
// against rows that no longer exist.
let present: HashSet<Uuid> = accounts.iter().map(|a| a.id).collect();
running.retain(|id, handle| {
let keep = present.contains(id);
if !keep {
tracing::info!(account_id = %id, "account removed; stopping sync task");
handle.abort();
}
keep
});
for account in accounts {
if running.contains_key(&account.id) {
continue;
@@ -44,6 +64,9 @@ pub async fn run(pool: PgPool, cipher: CredentialCipher, blobs: BlobStore, event
Err(e) => tracing::error!(error = %e, "failed to list accounts for sync manager"),
}
tokio::time::sleep(ACCOUNT_POLL_INTERVAL).await;
tokio::select! {
_ = wake.notified() => {}
_ = tokio::time::sleep(ACCOUNT_POLL_INTERVAL) => {}
}
}
}
+3
View File
@@ -27,11 +27,13 @@ async fn main() -> anyhow::Result<()> {
// The sync manager owns one long-running task per IMAP account
// (server-architecture-spec.md §3.1) — it runs alongside the API server.
let sync_wake = std::sync::Arc::new(tokio::sync::Notify::new());
tokio::spawn(imap_sync::run(
pool.clone(),
cipher.clone(),
blobs.clone(),
events.clone(),
sync_wake.clone(),
));
tokio::spawn(imap_sync::body_backfill::run(pool.clone(), blobs.clone()));
@@ -61,6 +63,7 @@ async fn main() -> anyhow::Result<()> {
session_ttl_hours: config.session_ttl_hours,
config: config.clone(),
outbox_wake,
sync_wake,
events,
pusher,
};
+17
View File
@@ -48,6 +48,22 @@ pub struct AccountPublic {
pub email_address: Option<String>,
pub display_name: Option<String>,
pub created_at: DateTime<Utc>,
/// How syncing is going; filled in by the account list.
pub sync: Option<AccountSync>,
}
/// An account's sync health, for showing whether it's working.
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct AccountSync {
#[serde(skip)]
pub account_id: Uuid,
/// pending | syncing | idle | error
pub status: String,
pub last_error: Option<String>,
pub updated_at: DateTime<Utc>,
/// The first full pass over the mailbox has finished.
pub caught_up: bool,
pub messages: i64,
}
impl From<Account> for AccountPublic {
@@ -64,6 +80,7 @@ impl From<Account> for AccountPublic {
email_address: a.email_address,
display_name: a.display_name,
created_at: a.created_at,
sync: None,
}
}
}
+1
View File
@@ -46,6 +46,7 @@ fn test_router() -> axum::Router {
push: Default::default(),
},
outbox_wake: std::sync::Arc::new(tokio::sync::Notify::new()),
sync_wake: std::sync::Arc::new(tokio::sync::Notify::new()),
};
tern_server::api::build(state)