diff --git a/src/modules/cache/mod.rs b/src/modules/cache/mod.rs index dc73aa2..62b8545 100644 --- a/src/modules/cache/mod.rs +++ b/src/modules/cache/mod.rs @@ -2,11 +2,16 @@ // Licensed under RustMailer License Agreement v1.0 // Unauthorized copying, modification, or distribution is prohibited. +use std::collections::HashMap; use std::sync::{Arc, LazyLock}; -use tokio::sync::Semaphore; +use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore}; +use crate::modules::error::code::ErrorCode; +use crate::modules::error::RustMailerResult; +use crate::modules::imap::pool::MAX_POOL_SIZE; use crate::modules::settings::cli::SETTINGS; +use crate::raise_error; pub mod disk; pub mod imap; @@ -22,3 +27,31 @@ pub static SEMAPHORE: LazyLock> = LazyLock::new(|| { .unwrap_or(num_cpus::get() * 2), )) }); + +/// Per-account sync task registry. Entries are never removed: the number of +/// accounts is license-bounded, so the map stays small even if accounts are +/// deleted and re-created. +static ACCOUNT_SYNC_SEMAPHORES: LazyLock>>> = + LazyLock::new(|| Mutex::new(HashMap::new())); + +/// Acquires a per-account sync slot, bounding each account to at most +/// `MAX_POOL_SIZE` concurrent IMAP sync tasks. Without this bound, a single +/// large mailbox sync can queue more `pool.get()` calls than the account's +/// pool has connections, and the queued tasks hit the 30s pool acquire +/// timeout (INCIDENT-6717207556896619). Combine with the global +/// [`SEMAPHORE`]: acquire the global permit first, then this one. +pub async fn acquire_account_sync_permit( + account_id: u64, +) -> RustMailerResult { + let semaphore = { + let mut registry = ACCOUNT_SYNC_SEMAPHORES.lock().await; + registry + .entry(account_id) + .or_insert_with(|| Arc::new(Semaphore::new(MAX_POOL_SIZE as usize))) + .clone() + }; + semaphore + .acquire_owned() + .await + .map_err(|e| raise_error!(format!("{:#?}", e), ErrorCode::InternalError)) +} diff --git a/src/modules/imap/executor.rs b/src/modules/imap/executor.rs index 7e7298d..9445c73 100644 --- a/src/modules/imap/executor.rs +++ b/src/modules/imap/executor.rs @@ -11,6 +11,7 @@ use bb8::Pool; use futures::{StreamExt, TryStreamExt}; use mail_parser::MessageParser; use std::collections::HashSet; +use std::time::Duration; use tracing::{debug, error, info, warn}; /// The IMAP query to fetch email metadata including headers and body structure. @@ -28,6 +29,49 @@ const BODY_FETCH_COMMAND: &str = "(BODY.PEEK[])"; const HEADER_MESSAGE_ID_QUERY: &str = "(UID BODY.PEEK[HEADER.FIELDS (Message-ID)])"; +/// Upper bound for a single IMAP command sequence running on a checked-out +/// connection. Without it, a stalled or throttled server can pin a pool slot +/// until the socket-level timeout fires (previously 3600s), starving the whole +/// account pool (INCIDENT-6717207556896619). +const IMAP_COMMAND_TIMEOUT: Duration = Duration::from_secs(120); + +/// Runs an IMAP command sequence under [`IMAP_COMMAND_TIMEOUT`] and translates +/// the outcome into a `RustMailerResult`. On error (including timeout) the +/// connection is marked bad so bb8 discards it instead of returning it to the +/// pool in a protocol-desynchronized state. +macro_rules! run_imap_command { + ($session:expr, $label:literal, async $body:block) => { + match tokio::time::timeout(IMAP_COMMAND_TIMEOUT, async $body).await { + Ok(Ok(v)) => Ok(v), + Ok(Err(e)) => { + if is_connection_error(&e) { + $session.is_bad = true; + } + Err(raise_error!( + format!("{} failed: {:#?}", $label, e), + ErrorCode::ImapCommandFailed + )) + } + Err(_) => { + $session.is_bad = true; + warn!( + "IMAP command sequence '{}' timed out after {}s, marking connection as bad", + $label, + IMAP_COMMAND_TIMEOUT.as_secs() + ); + Err(raise_error!( + format!( + "IMAP command sequence '{}' timed out after {}s", + $label, + IMAP_COMMAND_TIMEOUT.as_secs() + ), + ErrorCode::ImapCommandFailed + )) + } + } + }; +} + pub struct ImapExecutor { pool: Pool, } @@ -40,16 +84,9 @@ impl ImapExecutor { pub async fn list_all_mailboxes(&self) -> RustMailerResult> { let mut session = self.pool.get().await?; - let result = async { + let result = run_imap_command!(session, "LIST", async { let list = session.list(Some(""), Some("*")).await?; list.try_collect::>().await - } - .await - .map_err(|e| { - if is_connection_error(&e) { - session.is_bad = true; - } - raise_error!(format!("{:#?}", e), ErrorCode::ImapCommandFailed) })?; if result.is_empty() { @@ -63,16 +100,9 @@ impl ImapExecutor { pub async fn list_all_subscribed_mailboxes(&self) -> RustMailerResult> { let mut session = self.pool.get().await?; - let result = async { + let result = run_imap_command!(session, "LSUB", async { let list_stream = session.lsub(Some(""), Some("*")).await?; list_stream.try_collect::>().await - } - .await - .map_err(|e| { - if is_connection_error(&e) { - session.is_bad = true; - } - raise_error!(format!("{:#?}", e), ErrorCode::ImapCommandFailed) })?; if result.is_empty() { @@ -87,91 +117,58 @@ impl ImapExecutor { pub async fn create_mailbox(&self, mailbox_name: &str) -> RustMailerResult<()> { let mut session = self.pool.get().await?; - session.create(mailbox_name).await.map_err(|e| { - if is_connection_error(&e) { - session.is_bad = true; - } - raise_error!(format!("{:#?}", e), ErrorCode::ImapCommandFailed) - })?; - Ok(()) + run_imap_command!(session, "CREATE", async { + session.create(mailbox_name).await?; + Ok(()) + }) } pub async fn examine_mailbox(&self, mailbox_name: &str) -> RustMailerResult { let mut session = self.pool.get().await?; - session.examine(mailbox_name).await.map_err(|e| { - if is_connection_error(&e) { - session.is_bad = true; - } - raise_error!(format!("{:#?}", e), ErrorCode::ImapCommandFailed) + run_imap_command!(session, "EXAMINE", async { + session.examine(mailbox_name).await }) } - async fn do_expunge( - session: &mut bb8::PooledConnection<'_, ImapConnectionManager>, - mailbox_name: &str, - ) -> Result<(), async_imap::error::Error> { - session.select(mailbox_name).await?; - let _ = session.expunge().await?; - Ok(()) - } - pub async fn expunge_mailbox(&self, mailbox_name: &str) -> RustMailerResult<()> { let mut session: bb8::PooledConnection<'_, ImapConnectionManager> = self.pool.get().await?; - let result = Self::do_expunge(&mut session, mailbox_name).await; - if let Err(e) = result { - if is_connection_error(&e) { - session.is_bad = true; - } - return Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )); - } - Ok(()) + run_imap_command!(session, "EXPUNGE", async { + session.select(mailbox_name).await?; + let _ = session.expunge().await?; + Ok(()) + }) } pub async fn delete_mailbox(&self, mailbox_name: &str) -> RustMailerResult<()> { let mut session = self.pool.get().await?; - session.delete(mailbox_name).await.map_err(|e| { - if is_connection_error(&e) { - session.is_bad = true; - } - raise_error!(format!("{:#?}", e), ErrorCode::ImapCommandFailed) - })?; - Ok(()) + run_imap_command!(session, "DELETE", async { + session.delete(mailbox_name).await?; + Ok(()) + }) } pub async fn rename_mailbox(&self, from: &str, to: &str) -> RustMailerResult<()> { let mut session = self.pool.get().await?; - session.rename(from, to).await.map_err(|e| { - if is_connection_error(&e) { - session.is_bad = true; - } - raise_error!(format!("{:#?}", e), ErrorCode::ImapCommandFailed) - })?; - Ok(()) + run_imap_command!(session, "RENAME", async { + session.rename(from, to).await?; + Ok(()) + }) } pub async fn subscribe_mailbox(&self, mailbox_name: &str) -> RustMailerResult<()> { let mut session = self.pool.get().await?; - session.subscribe(mailbox_name).await.map_err(|e| { - if is_connection_error(&e) { - session.is_bad = true; - } - raise_error!(format!("{:#?}", e), ErrorCode::ImapCommandFailed) - })?; - Ok(()) + run_imap_command!(session, "SUBSCRIBE", async { + session.subscribe(mailbox_name).await?; + Ok(()) + }) } pub async fn unsubscribe_mailbox(&self, mailbox_name: &str) -> RustMailerResult<()> { let mut session = self.pool.get().await?; - session.unsubscribe(mailbox_name).await.map_err(|e| { - if is_connection_error(&e) { - session.is_bad = true; - } - raise_error!(format!("{:#?}", e), ErrorCode::ImapCommandFailed) - })?; - Ok(()) + run_imap_command!(session, "UNSUBSCRIBE", async { + session.unsubscribe(mailbox_name).await?; + Ok(()) + }) } pub async fn fetch_uid_list( @@ -185,7 +182,7 @@ impl ImapExecutor { let uid_set = format!("{}:*", start_uid); let mut session = self.pool.get().await?; - let result: Result, _> = async { + run_imap_command!(session, "UID FETCH uid-list", async { session.examine(mailbox_name).await?; let mut stream = session @@ -212,21 +209,7 @@ impl ImapExecutor { } } Ok(results) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } /// Get the UID of a message by its Message-ID in the specified mailbox. @@ -242,7 +225,7 @@ impl ImapExecutor { ) -> RustMailerResult { let mut session = self.pool.get().await?; - let result: Result = async { + run_imap_command!(session, "FETCH message-id scan", async { session.examine(mailbox_name).await?; let mut stream = session.fetch("1:*", HEADER_MESSAGE_ID_QUERY).await?; @@ -270,22 +253,7 @@ impl ImapExecutor { } Err(async_imap::error::Error::Bad("Message not found".into())) - } - .await; - - match result { - Ok(uid) => Ok(uid), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn retrieve_metadata_paginated( @@ -301,7 +269,7 @@ impl ImapExecutor { let mut session = self.pool.get().await?; - let result: Result<(Vec, u64), async_imap::error::Error> = async { + run_imap_command!(session, "FETCH paginated metadata", async { let total = session.examine(mailbox_name).await?.exists as u64; if total == 0 { @@ -352,22 +320,7 @@ impl ImapExecutor { } Ok((results, total)) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn retrieve_paginated_uid_and_flags( @@ -382,7 +335,7 @@ impl ImapExecutor { let mut session = self.pool.get().await?; - let result: Result, async_imap::error::Error> = async { + run_imap_command!(session, "FETCH paginated uid-flags", async { let total = session.examine(mailbox_name).await?.exists; if total == 0 { @@ -431,22 +384,7 @@ impl ImapExecutor { } } Ok(results) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn uid_fetch_uid_and_flags( @@ -458,7 +396,7 @@ impl ImapExecutor { let mut session = self.pool.get().await?; - let result: Result, async_imap::error::Error> = async { + run_imap_command!(session, "UID FETCH uid-flags", async { session.examine(mailbox_name).await?; let mut stream = session.uid_fetch(uid_set, UID_FLAGS).await?; @@ -475,22 +413,7 @@ impl ImapExecutor { } } Ok(results) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn uid_fetch_body_structure( @@ -500,7 +423,7 @@ impl ImapExecutor { ) -> RustMailerResult> { let mut session = self.pool.get().await?; - let result: Result, async_imap::error::Error> = async { + run_imap_command!(session, "UID FETCH bodystructure", async { session.examine(mailbox_name).await?; let mut stream = session.uid_fetch(uid_set, BODYSTRUCTURE).await?; @@ -520,22 +443,7 @@ impl ImapExecutor { } Ok(results) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn uid_fetch_meta( @@ -546,7 +454,7 @@ impl ImapExecutor { ) -> RustMailerResult> { let mut session = self.pool.get().await?; - let result: Result, async_imap::error::Error> = async { + run_imap_command!(session, "UID FETCH metadata", async { session.examine(mailbox_name).await?; let query = if minimal { @@ -569,22 +477,7 @@ impl ImapExecutor { } Ok(results) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn append( @@ -595,15 +488,12 @@ impl ImapExecutor { content: impl AsRef<[u8]>, ) -> RustMailerResult<()> { let mut session = self.pool.get().await?; - session - .append(mailbox_name, flags, internaldate, content) - .await - .map_err(|e| { - if is_connection_error(&e) { - session.is_bad = true; - } - raise_error!(format!("{:#?}", e), ErrorCode::ImapCommandFailed) - }) + run_imap_command!(session, "APPEND", async { + session + .append(mailbox_name, flags, internaldate, content) + .await?; + Ok(()) + }) } pub async fn uid_fetch_full_message( @@ -613,29 +503,14 @@ impl ImapExecutor { ) -> RustMailerResult> { let mut session = self.pool.get().await?; - let result: Result, async_imap::error::Error> = async { + run_imap_command!(session, "UID FETCH full message", async { session.examine(mailbox_name).await?; let mut stream = session.uid_fetch(uid, BODY_FETCH_COMMAND).await?; let fetch = stream.try_next().await?; Ok(fetch) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn uid_fetch_single_part( @@ -646,7 +521,7 @@ impl ImapExecutor { ) -> RustMailerResult> { let mut session = self.pool.get().await?; - let result: Result, async_imap::error::Error> = async { + run_imap_command!(session, "UID FETCH single part", async { session.examine(mailbox_name).await?; let query = format!("(UID BODY.PEEK[{}])", path); @@ -664,22 +539,7 @@ impl ImapExecutor { } } Ok(results) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn uid_move_envelopes( @@ -690,26 +550,11 @@ impl ImapExecutor { ) -> RustMailerResult<()> { let mut session = self.pool.get().await?; - let result: Result<(), async_imap::error::Error> = async { + run_imap_command!(session, "UID MOVE", async { session.select(from).await?; session.uid_mv(uid_set, to).await?; Ok(()) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn uid_copy_envelopes( @@ -720,26 +565,11 @@ impl ImapExecutor { ) -> RustMailerResult<()> { let mut session = self.pool.get().await?; - let result: Result<(), async_imap::error::Error> = async { + run_imap_command!(session, "UID COPY", async { session.select(from).await?; session.uid_copy(uid_set, to).await?; Ok(()) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } async fn uid_flag_store( @@ -750,7 +580,7 @@ impl ImapExecutor { ) -> RustMailerResult> { let mut session = self.pool.get().await?; - let result: Result, async_imap::error::Error> = async { + run_imap_command!(session, "UID STORE", async { session.select(mailbox_name).await?; let mut stream = session.uid_store(uid_set, query).await?; let mut results = Vec::new(); @@ -766,22 +596,7 @@ impl ImapExecutor { } } Ok(results) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } pub async fn uid_set_flags( @@ -897,26 +712,11 @@ impl ImapExecutor { ) -> RustMailerResult> { let mut session = self.pool.get().await?; - let result: Result, async_imap::error::Error> = async { + run_imap_command!(session, "UID SEARCH", async { session.examine(mailbox_name).await?; let result = session.uid_search(query).await?; Ok(result) - } - .await; - - match result { - Ok(v) => Ok(v), - Err(e) => { - if is_connection_error(&e) { - session.is_bad = true; - } - - Err(raise_error!( - format!("{:#?}", e), - ErrorCode::ImapCommandFailed - )) - } - } + }) } } diff --git a/src/modules/imap/manager.rs b/src/modules/imap/manager.rs index 5ddd193..80b5090 100644 --- a/src/modules/imap/manager.rs +++ b/src/modules/imap/manager.rs @@ -16,16 +16,80 @@ use crate::modules::imap::session::SessionStream; use crate::modules::oauth2::token::OAuth2AccessToken; use crate::{decrypt, raise_error, rustmailer_version}; use async_imap::Session; -use tracing::error; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use tracing::{error, warn}; + +/// Initial backoff applied after a failed IMAP connection attempt (dial, login +/// or capability negotiation). Doubles on consecutive failures up to +/// [`CONNECT_BACKOFF_MAX`] and resets to zero after a successful connection. +const CONNECT_BACKOFF_INITIAL: Duration = Duration::from_secs(30); +/// Upper bound of the connection backoff sequence: 30s → 60s → … → 10min. +const CONNECT_BACKOFF_MAX: Duration = Duration::from_secs(600); #[derive(Debug)] pub struct ImapConnectionManager { pub account_id: u64, + /// Current connection backoff duration in milliseconds; 0 = no backoff. + backoff_ms: AtomicU64, + /// Unix timestamp (ms) before which no new connection attempt may start. + next_attempt_ms: AtomicU64, +} + +fn unix_now_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_millis() as u64) + .unwrap_or(0) } impl ImapConnectionManager { pub fn new(account_id: u64) -> Self { - Self { account_id } + Self { + account_id, + backoff_ms: AtomicU64::new(0), + next_attempt_ms: AtomicU64::new(0), + } + } + + /// Records a failed connection attempt and extends the backoff window. + /// This keeps bb8's dial retries and `min_idle` replenishment from + /// hammering an unreachable or throttling server — every login attempt + /// feeds a server-side throttle (INCIDENT-6717207556896619). + pub(crate) fn note_connection_failure(&self) { + let current = self.backoff_ms.load(Ordering::Relaxed); + let next = if current == 0 { + CONNECT_BACKOFF_INITIAL.as_millis() as u64 + } else { + (current * 2).min(CONNECT_BACKOFF_MAX.as_millis() as u64) + }; + self.backoff_ms.store(next, Ordering::Relaxed); + self.next_attempt_ms + .store(unix_now_ms().saturating_add(next), Ordering::Relaxed); + warn!( + account_id = self.account_id, + backoff_secs = next / 1000, + "IMAP connection attempt failed, backing off before next attempt" + ); + } + + /// Records a successful connection and clears the backoff window. + pub(crate) fn note_connection_success(&self) { + self.backoff_ms.store(0, Ordering::Relaxed); + self.next_attempt_ms.store(0, Ordering::Relaxed); + } + + /// Sleeps until the backoff window (if any) has elapsed. Concurrent + /// callers all park until the window opens, pacing connection storms. + pub(crate) async fn wait_for_backoff(&self) { + loop { + let now = unix_now_ms(); + let until = self.next_attempt_ms.load(Ordering::Relaxed); + if now >= until { + return; + } + tokio::time::sleep(Duration::from_millis(until - now)).await; + } } pub async fn fetch_account(&self) -> RustMailerResult { diff --git a/src/modules/imap/pool.rs b/src/modules/imap/pool.rs index eecefff..059a336 100644 --- a/src/modules/imap/pool.rs +++ b/src/modules/imap/pool.rs @@ -11,13 +11,40 @@ use bb8::Pool; use std::time::Duration; use tracing::{error, warn}; +/// Maximum concurrent IMAP connections per account. Also used to bound +/// per-account sync concurrency in `cache::acquire_account_sync_permit` so +/// sync tasks never queue more `pool.get()` calls than the pool has slots. +pub(crate) const MAX_POOL_SIZE: u32 = 8; + +/// Timeout for the NOOP health probe run when checking a connection out of the +/// pool. Must stay comfortably above the round-trip latency of a trivial +/// command on a throttling server: Gmail under `[THROTTLED]` was observed +/// answering NOOP in 5.7–6.4s, which the previous 5s probe classified as a +/// dead connection — the pool then discarded every healthy connection it +/// touched and re-dialed in a self-sustaining storm +/// (INCIDENT-6717207556896619). +const CONNECTION_PROBE_TIMEOUT: Duration = Duration::from_secs(15); + impl bb8::ManageConnection for ImapConnectionManager { type Connection = MyImapConnection; type Error = RustMailerError; async fn connect(&self) -> RustMailerResult { - let session = self.build().await?; + // Pace repeated dial/login attempts with exponential backoff; without + // this, bb8 retries and min_idle replenishment keep logging in for the + // whole 30s acquire window, feeding the server-side throttle. + self.wait_for_backoff().await; + let session = match self.build().await { + Ok(session) => { + self.note_connection_success(); + session + } + Err(e) => { + self.note_connection_failure(); + return Err(e); + } + }; Ok(MyImapConnection { session, is_bad: false, @@ -32,7 +59,7 @@ impl bb8::ManageConnection for ImapConnectionManager { )); } match tokio::time::timeout( - Duration::from_secs(5), + CONNECTION_PROBE_TIMEOUT, conn.run_command_and_check_ok("NOOP"), ) .await @@ -47,7 +74,10 @@ impl bb8::ManageConnection for ImapConnectionManager { )) } Err(_) => { - warn!("IMAP NOOP timeout"); + warn!( + "IMAP NOOP probe timed out after {}s", + CONNECTION_PROBE_TIMEOUT.as_secs() + ); conn.is_bad = true; Err(raise_error!( "NOOP timeout".into(), @@ -69,7 +99,7 @@ pub async fn build_imap_pool(account_id: u64) -> RustMailerResult