PUT /api/accounts/:id replaces an account's settings; the password is kept unless a new one is given. Accounts now have an updated_at, and the sync manager restarts a task whose account changed since it started — the task holds its own copy of the settings. Its status is reset to pending so the old error doesn't linger. Mail already synced stays when it's still the same mailbox (new password, renamed host); a genuinely different mailbox shows up as a UIDVALIDITY change on connect and re-syncs, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3614dffa1a
commit
56e2c89999
6 files changed
+156
-22
No files matched your search
@@ -0,0 +1,4 @@
|
|||||||
|
-- When an account's settings last changed. The sync manager compares it
|
||||||
|
-- with the version its running task started from, and restarts the task
|
||||||
|
-- after an edit (new password, host, …) — the task holds its own copy.
|
||||||
|
ALTER TABLE accounts ADD COLUMN updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
+123
-7
@@ -63,23 +63,42 @@ pub async fn list(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Catches what would otherwise only fail later, in the sync task's log.
|
/// Catches what would otherwise only fail later, in the sync task's log.
|
||||||
fn validate(req: &CreateAccountRequest) -> ApiResult<()> {
|
fn validate_settings(
|
||||||
|
name: &str,
|
||||||
|
imap_host: &str,
|
||||||
|
imap_port: i32,
|
||||||
|
smtp_host: &str,
|
||||||
|
smtp_port: i32,
|
||||||
|
username: &str,
|
||||||
|
) -> ApiResult<()> {
|
||||||
let blank = |s: &str| s.trim().is_empty();
|
let blank = |s: &str| s.trim().is_empty();
|
||||||
if blank(&req.name) || blank(&req.imap_host) || blank(&req.smtp_host) || blank(&req.username) {
|
if blank(name) || blank(imap_host) || blank(smtp_host) || blank(username) {
|
||||||
return Err(ApiError::BadRequest(
|
return Err(ApiError::BadRequest(
|
||||||
"name, IMAP server, SMTP server and login are all required".into(),
|
"name, IMAP server, SMTP server and login are all required".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
for (what, port) in [("IMAP", imap_port), ("SMTP", smtp_port)] {
|
||||||
|
if !(1..=65535).contains(&port) {
|
||||||
|
return Err(ApiError::BadRequest(format!("{what} port must be 1–65535")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate(req: &CreateAccountRequest) -> ApiResult<()> {
|
||||||
|
validate_settings(
|
||||||
|
&req.name,
|
||||||
|
&req.imap_host,
|
||||||
|
req.imap_port,
|
||||||
|
&req.smtp_host,
|
||||||
|
req.smtp_port,
|
||||||
|
&req.username,
|
||||||
|
)?;
|
||||||
if req.password.is_empty() {
|
if req.password.is_empty() {
|
||||||
return Err(ApiError::BadRequest(
|
return Err(ApiError::BadRequest(
|
||||||
"the mailbox password is required".into(),
|
"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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,6 +146,103 @@ pub async fn create(
|
|||||||
Ok(Json(account.into()))
|
Ok(Json(account.into()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The account's settings, replaced as a whole — except the password,
|
||||||
|
/// which stays as it is unless a new one is given.
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct UpdateAccountRequest {
|
||||||
|
pub name: String,
|
||||||
|
pub imap_host: String,
|
||||||
|
pub imap_port: i32,
|
||||||
|
pub smtp_host: String,
|
||||||
|
pub smtp_port: i32,
|
||||||
|
pub username: String,
|
||||||
|
/// Omitted or empty: keep the stored password.
|
||||||
|
pub password: Option<String>,
|
||||||
|
pub email_address: Option<String>,
|
||||||
|
pub display_name: Option<String>,
|
||||||
|
/// Defaults by port, as when creating.
|
||||||
|
pub smtp_use_starttls: Option<bool>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Edits an account. Its sync task is restarted with the new settings.
|
||||||
|
/// Mail already synced stays when it's still the same mailbox (say, a new
|
||||||
|
/// password or a renamed host); pointing it at a different mailbox shows up
|
||||||
|
/// as a UIDVALIDITY change on the next connect, and that re-syncs it.
|
||||||
|
pub async fn update(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
user: CurrentUser,
|
||||||
|
axum::extract::Path(account_id): axum::extract::Path<Uuid>,
|
||||||
|
AppJson(req): AppJson<UpdateAccountRequest>,
|
||||||
|
) -> ApiResult<Json<AccountPublic>> {
|
||||||
|
validate_settings(
|
||||||
|
&req.name,
|
||||||
|
&req.imap_host,
|
||||||
|
req.imap_port,
|
||||||
|
&req.smtp_host,
|
||||||
|
req.smtp_port,
|
||||||
|
&req.username,
|
||||||
|
)?;
|
||||||
|
let sealed = match req.password.as_deref().filter(|p| !p.is_empty()) {
|
||||||
|
Some(p) => Some(state.cipher.encrypt(p)?),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let account: Option<Account> = sqlx::query_as(
|
||||||
|
"UPDATE accounts SET \
|
||||||
|
name = $3, imap_host = $4, imap_port = $5, smtp_host = $6, smtp_port = $7, \
|
||||||
|
username = $8, \
|
||||||
|
email_address = COALESCE($9, CASE WHEN $8 LIKE '%@%' THEN $8 END), \
|
||||||
|
display_name = $10, smtp_use_starttls = $11, \
|
||||||
|
encrypted_password = COALESCE($12, encrypted_password), \
|
||||||
|
password_nonce = COALESCE($13, password_nonce), \
|
||||||
|
updated_at = now() \
|
||||||
|
WHERE id = $1 AND user_id = $2 RETURNING *",
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.bind(user.user_id)
|
||||||
|
.bind(req.name.trim())
|
||||||
|
.bind(req.imap_host.trim())
|
||||||
|
.bind(req.imap_port)
|
||||||
|
.bind(req.smtp_host.trim())
|
||||||
|
.bind(req.smtp_port)
|
||||||
|
.bind(req.username.trim())
|
||||||
|
.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))
|
||||||
|
.bind(sealed.as_ref().map(|s| &s.ciphertext))
|
||||||
|
.bind(sealed.as_ref().map(|s| &s.nonce))
|
||||||
|
.fetch_optional(&state.pool)
|
||||||
|
.await?;
|
||||||
|
let account = account.ok_or(ApiError::NotFound)?;
|
||||||
|
|
||||||
|
// The old status described the old settings.
|
||||||
|
sqlx::query(
|
||||||
|
"UPDATE sync_state SET status = 'pending', last_error = NULL, updated_at = now() \
|
||||||
|
WHERE account_id = $1",
|
||||||
|
)
|
||||||
|
.bind(account_id)
|
||||||
|
.execute(&state.pool)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Restart its sync task now rather than at the manager's next poll.
|
||||||
|
state.sync_wake.notify_one();
|
||||||
|
state
|
||||||
|
.events
|
||||||
|
.emit(user.user_id, Change::config(ConfigKind::Accounts))
|
||||||
|
.await;
|
||||||
|
Ok(Json(account.into()))
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn delete(
|
pub async fn delete(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
user: CurrentUser,
|
user: CurrentUser,
|
||||||
|
|||||||
+5
-2
@@ -3,7 +3,7 @@ use crate::api::{
|
|||||||
accounts, auth, devices, events, folders, messages, outbox, rules, tags, threads,
|
accounts, auth, devices, events, folders, messages, outbox, rules, tags, threads,
|
||||||
};
|
};
|
||||||
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
|
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE};
|
||||||
use axum::routing::{delete, get, post, put};
|
use axum::routing::{get, post, put};
|
||||||
use axum::Router;
|
use axum::Router;
|
||||||
use tower_http::cors::{Any, CorsLayer};
|
use tower_http::cors::{Any, CorsLayer};
|
||||||
use tower_http::trace::TraceLayer;
|
use tower_http::trace::TraceLayer;
|
||||||
@@ -13,7 +13,10 @@ pub fn build(state: AppState) -> Router {
|
|||||||
.route("/api/auth/register", post(auth::register))
|
.route("/api/auth/register", post(auth::register))
|
||||||
.route("/api/auth/login", post(auth::login))
|
.route("/api/auth/login", post(auth::login))
|
||||||
.route("/api/accounts", get(accounts::list).post(accounts::create))
|
.route("/api/accounts", get(accounts::list).post(accounts::create))
|
||||||
.route("/api/accounts/:id", delete(accounts::delete))
|
.route(
|
||||||
|
"/api/accounts/:id",
|
||||||
|
put(accounts::update).delete(accounts::delete),
|
||||||
|
)
|
||||||
.route("/api/folders", get(folders::list).post(folders::create))
|
.route("/api/folders", get(folders::list).post(folders::create))
|
||||||
.route(
|
.route(
|
||||||
"/api/folders/:id",
|
"/api/folders/:id",
|
||||||
|
|||||||
+22
-13
@@ -1,14 +1,16 @@
|
|||||||
//! Spawns and tracks one sync task per account, and stops the task of an
|
//! Spawns and tracks one sync task per account; stops the task of an
|
||||||
//! account that was removed. Woken by the API when accounts change, and
|
//! account that was removed, and restarts the task of one that was edited
|
||||||
//! polls as a fallback.
|
//! (it holds its own copy of the settings). Woken by the API when accounts
|
||||||
|
//! change, and polls as a fallback.
|
||||||
|
|
||||||
use crate::crypto::CredentialCipher;
|
use crate::crypto::CredentialCipher;
|
||||||
use crate::events::EventHub;
|
use crate::events::EventHub;
|
||||||
use crate::imap_sync::connection::AccountSyncer;
|
use crate::imap_sync::connection::AccountSyncer;
|
||||||
use crate::models::account::Account;
|
use crate::models::account::Account;
|
||||||
use crate::storage::BlobStore;
|
use crate::storage::BlobStore;
|
||||||
|
use chrono::{DateTime, Utc};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::sync::Notify;
|
use tokio::sync::Notify;
|
||||||
@@ -23,10 +25,11 @@ pub async fn run(
|
|||||||
events: EventHub,
|
events: EventHub,
|
||||||
wake: Arc<Notify>,
|
wake: Arc<Notify>,
|
||||||
) {
|
) {
|
||||||
let mut running: HashMap<Uuid, tokio::task::JoinHandle<()>> = HashMap::new();
|
// Each task, with the account version (updated_at) it was started from.
|
||||||
|
let mut running: HashMap<Uuid, (tokio::task::JoinHandle<()>, DateTime<Utc>)> = HashMap::new();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
running.retain(|_, handle| !handle.is_finished());
|
running.retain(|_, (handle, _)| !handle.is_finished());
|
||||||
|
|
||||||
match sqlx::query_as::<_, Account>("SELECT * FROM accounts")
|
match sqlx::query_as::<_, Account>("SELECT * FROM accounts")
|
||||||
.fetch_all(&pool)
|
.fetch_all(&pool)
|
||||||
@@ -35,14 +38,20 @@ pub async fn run(
|
|||||||
Ok(accounts) => {
|
Ok(accounts) => {
|
||||||
// A removed account's task would otherwise retry forever
|
// A removed account's task would otherwise retry forever
|
||||||
// against rows that no longer exist.
|
// against rows that no longer exist.
|
||||||
let present: HashSet<Uuid> = accounts.iter().map(|a| a.id).collect();
|
let present: HashMap<Uuid, DateTime<Utc>> =
|
||||||
running.retain(|id, handle| {
|
accounts.iter().map(|a| (a.id, a.updated_at)).collect();
|
||||||
let keep = present.contains(id);
|
running.retain(|id, (handle, version)| match present.get(id) {
|
||||||
if !keep {
|
None => {
|
||||||
tracing::info!(account_id = %id, "account removed; stopping sync task");
|
tracing::info!(account_id = %id, "account removed; stopping sync task");
|
||||||
handle.abort();
|
handle.abort();
|
||||||
|
false
|
||||||
}
|
}
|
||||||
keep
|
Some(current) if current != version => {
|
||||||
|
tracing::info!(account_id = %id, "account edited; restarting sync task");
|
||||||
|
handle.abort();
|
||||||
|
false
|
||||||
|
}
|
||||||
|
Some(_) => true,
|
||||||
});
|
});
|
||||||
for account in accounts {
|
for account in accounts {
|
||||||
if running.contains_key(&account.id) {
|
if running.contains_key(&account.id) {
|
||||||
@@ -56,9 +65,9 @@ pub async fn run(
|
|||||||
blobs: blobs.clone(),
|
blobs: blobs.clone(),
|
||||||
events: events.clone(),
|
events: events.clone(),
|
||||||
};
|
};
|
||||||
let id = syncer.account.id;
|
let (id, version) = (syncer.account.id, syncer.account.updated_at);
|
||||||
let handle = tokio::spawn(syncer.run());
|
let handle = tokio::spawn(syncer.run());
|
||||||
running.insert(id, handle);
|
running.insert(id, (handle, version));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => tracing::error!(error = %e, "failed to list accounts for sync manager"),
|
Err(e) => tracing::error!(error = %e, "failed to list accounts for sync manager"),
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ pub struct Account {
|
|||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub email_address: Option<String>,
|
pub email_address: Option<String>,
|
||||||
pub display_name: Option<String>,
|
pub display_name: Option<String>,
|
||||||
|
pub updated_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Account {
|
impl Account {
|
||||||
|
|||||||
@@ -70,6 +70,7 @@ async fn parameterised_routes_match() {
|
|||||||
("GET", format!("/api/messages/{id}")),
|
("GET", format!("/api/messages/{id}")),
|
||||||
("GET", format!("/api/threads/{id}")),
|
("GET", format!("/api/threads/{id}")),
|
||||||
("DELETE", format!("/api/accounts/{id}")),
|
("DELETE", format!("/api/accounts/{id}")),
|
||||||
|
("PUT", format!("/api/accounts/{id}")),
|
||||||
("POST", format!("/api/threads/{id}/read")),
|
("POST", format!("/api/threads/{id}/read")),
|
||||||
("PUT", format!("/api/outbox/{id}")),
|
("PUT", format!("/api/outbox/{id}")),
|
||||||
("DELETE", format!("/api/outbox/{id}")),
|
("DELETE", format!("/api/outbox/{id}")),
|
||||||
|
|||||||
Reference in new issue
Block a user