From 5239964e50185d49043bab476b001d2071cc5551 Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Wed, 11 Nov 2026 15:16:17 +0530 Subject: [PATCH 1/2] Warn on transient channel disconnects and escalate only on a streak Every failed IMAP IDLE session and every Lark websocket read error was logged with error!, and hosts turn each ERROR into a Sentry event. So ordinary network churn (a server closing an idle connection, resets, timeouts, DNS failures) produced one error per reconnect, although the loops already retry with backoff and recover. - tinychannels-runtime gains FailureStreak and FAILURE_ESCALATE_THRESHOLD (5). A failure inside a streak is a warning, the failure that completes a streak is an error once, and a healthy session ends the streak. - IMAP listen_with_reconnect_to: - warns per failed session and escalates once per streak; - treats a session that logged in as healthy, which also resets the backoff (it previously only grew); - bounds each connect + TLS + login attempt by 30 s, so a server that accepts TCP and never answers can no longer hold the loop; - keeps a refused login (NO/BAD to LOGIN), now typed as ImapLoginRejected, at error level, since only the user can fix it. - Lark: a websocket read error is a warning. Restarts are the module supervisor's job. - The module supervisor (listen_with_supervision) counts restarts. A listener that stayed up 60 s or more counts as healthy and resets the backoff and the streak, and the fifth quick stop in a row is logged once as an error. Tests: - the streak rule; - a hung IMAP connect that times out and is retried (paused time); - a refused login typed as ImapLoginRejected. Closes #171 --- crates/tinychannels-module/src/provider.rs | 34 +++++++++++-- crates/tinychannels-runtime/src/lib.rs | 35 +++++++++++++ crates/tinychannels-runtime/src/lib_tests.rs | 21 ++++++++ .../email_channel/email_channel_tests.rs | 49 +++++++++++++++++++ src/providers/email_channel/inbound.rs | 48 +++++++++++++++--- src/providers/email_channel/mod.rs | 9 ++++ src/providers/lark/inbound.rs | 2 +- src/runtime.rs | 6 +-- 8 files changed, 191 insertions(+), 13 deletions(-) diff --git a/crates/tinychannels-module/src/provider.rs b/crates/tinychannels-module/src/provider.rs index 764868cc3..e4afae751 100644 --- a/crates/tinychannels-module/src/provider.rs +++ b/crates/tinychannels-module/src/provider.rs @@ -727,6 +727,9 @@ impl tinychannels::channel::ChannelInboundSink for ModuleEvents { } } +/// How long a provider listener must stay up to count as a healthy session. +const HEALTHY_LISTENER_RUN: Duration = Duration::from_secs(60); + /// Reconnect execution stays in the module; raw provider errors never cross callbacks. async fn listen_with_supervision( adapter: Arc, @@ -739,11 +742,36 @@ async fn listen_with_supervision( return start_adapter_listener(&adapter, legacy.as_ref(), sink.clone()).await; }; let name = adapter.descriptor().id; - let mut backoff = policy.initial_backoff_secs.max(1); + let initial = policy.initial_backoff_secs.max(1); + let mut backoff = initial; let maximum = policy.max_backoff_secs.max(backoff); + let mut streak = tinychannels::runtime::FailureStreak::default(); loop { - if let Err(error) = start_adapter_listener(&adapter, legacy.as_ref(), sink.clone()).await { - tracing::warn!(provider = %name, %error, "provider listener stopped; restarting"); + let started = tokio::time::Instant::now(); + let outcome = start_adapter_listener(&adapter, legacy.as_ref(), sink.clone()).await; + // A listener that stayed up was healthy: its stop is a fresh + // disconnect, so the streak and the backoff start over. + if started.elapsed() >= HEALTHY_LISTENER_RUN { + streak.record_success(); + backoff = initial; + } + let escalate = streak.record_failure(); + match outcome { + Err(error) if escalate => tracing::error!( + provider = %name, + failures = streak.failures(), + %error, + "provider listener keeps failing; restarting" + ), + Err(error) => { + tracing::warn!(provider = %name, %error, "provider listener stopped; restarting"); + } + Ok(()) if escalate => tracing::error!( + provider = %name, + failures = streak.failures(), + "provider listener keeps stopping; restarting" + ), + Ok(()) => {} } host.report_status(&name, "restarting", Some("provider disconnected".into())) .await; diff --git a/crates/tinychannels-runtime/src/lib.rs b/crates/tinychannels-runtime/src/lib.rs index a8a03b134..9e7b4530c 100644 --- a/crates/tinychannels-runtime/src/lib.rs +++ b/crates/tinychannels-runtime/src/lib.rs @@ -26,6 +26,41 @@ pub use session::{ChannelSession, run_in_session}; /// Maximum reconnect jitter added to a listener retry. pub const MAX_JITTER_MS: u64 = 1_000; +/// Consecutive listener failures, with no healthy session between them, +/// before one is reported as an error rather than a warning. +pub const FAILURE_ESCALATE_THRESHOLD: u32 = 5; + +/// How loudly a reconnect loop reports a failed session. +/// +/// A transient disconnect is ordinary network churn: the loop already retries +/// with backoff, so it is a warning. The same failure repeating with no healthy +/// session in between is worth an error, reported once per streak so a long +/// outage does not log one error per retry. +#[derive(Debug, Default)] +pub struct FailureStreak { + failures: u32, +} + +impl FailureStreak { + /// Record a failed session. Returns `true` exactly when this failure + /// completes a streak of [`FAILURE_ESCALATE_THRESHOLD`], so the caller + /// escalates once. + pub fn record_failure(&mut self) -> bool { + self.failures = self.failures.saturating_add(1); + self.failures == FAILURE_ESCALATE_THRESHOLD + } + + /// A healthy session ends the streak. + pub fn record_success(&mut self) { + self.failures = 0; + } + + /// Failures in the current streak. + pub fn failures(&self) -> u32 { + self.failures + } +} + /// Compute the bounded listener queue capacity for a provider count. pub fn compute_max_in_flight_messages(channel_count: usize) -> usize { channel_count.saturating_mul(4).clamp(8, 64) diff --git a/crates/tinychannels-runtime/src/lib_tests.rs b/crates/tinychannels-runtime/src/lib_tests.rs index 364e22247..3c60c22fd 100644 --- a/crates/tinychannels-runtime/src/lib_tests.rs +++ b/crates/tinychannels-runtime/src/lib_tests.rs @@ -55,3 +55,24 @@ async fn worker_join_logging_accepts_success_and_panic() { assert!(result.is_err()); log_worker_join_result(result.map(|_| ())); } + +#[test] +fn a_failure_streak_escalates_once_and_a_healthy_session_resets_it() { + let mut streak = FailureStreak::default(); + // Transient failures below the threshold stay warnings. + for _ in 1..FAILURE_ESCALATE_THRESHOLD { + assert!(!streak.record_failure()); + } + // The failure that completes the streak escalates, exactly once. + assert!(streak.record_failure()); + assert_eq!(streak.failures(), FAILURE_ESCALATE_THRESHOLD); + assert!( + !streak.record_failure(), + "a long outage escalates once, not per retry" + ); + + // A healthy session starts the count over. + streak.record_success(); + assert_eq!(streak.failures(), 0); + assert!(!streak.record_failure()); +} diff --git a/src/providers/email_channel/email_channel_tests.rs b/src/providers/email_channel/email_channel_tests.rs index 178f31194..8c31a6c8a 100644 --- a/src/providers/email_channel/email_channel_tests.rs +++ b/src/providers/email_channel/email_channel_tests.rs @@ -805,6 +805,55 @@ async fn plain_session( const HANG_GUARD: Duration = Duration::from_secs(20); +/// A server that never answers the connect must not hold the reconnect loop: +/// each attempt is bounded by `IMAP_CONNECT_TIMEOUT` and the loop retries. +#[tokio::test(start_paused = true)] +async fn a_hung_imap_connect_times_out_and_the_loop_retries() { + let channel = imap_channel(&["@example.com"], 30); + let attempts = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let (tx, _rx) = mpsc::channel(1); + let counted = attempts.clone(); + let listen = tokio::spawn(async move { + channel + .listen_with_reconnect(&tx, || { + counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + std::future::pending::>>() + }) + .await + }); + + // Two timeouts plus the 1-2 ms backoffs between them. + tokio::time::sleep(inbound::IMAP_CONNECT_TIMEOUT * 2 + Duration::from_secs(1)).await; + assert!( + attempts.load(std::sync::atomic::Ordering::SeqCst) >= 3, + "each hung attempt timed out and was retried" + ); + listen.abort(); +} + +/// A credentials refusal is typed, so the loop keeps it at error level while +/// ordinary disconnects become warnings. +#[tokio::test] +async fn a_refused_imap_login_is_typed_as_a_login_rejection() { + let (port, _server) = fake_imap(vec![ConnScript { + reject_login: true, + ..Default::default() + }]) + .await; + let channel = imap_channel(&["@example.com"], 30); + + let error = plain_session(&channel, port).await.unwrap_err(); + + assert!( + error.downcast_ref::().is_some(), + "{error:#}" + ); + assert!( + error.to_string().starts_with("IMAP login failed:"), + "{error}" + ); +} + async fn recv(rx: &mut mpsc::Receiver) -> ChannelMessage { timeout(HANG_GUARD, rx.recv()) .await diff --git a/src/providers/email_channel/inbound.rs b/src/providers/email_channel/inbound.rs index d89b51464..7f52581a5 100644 --- a/src/providers/email_channel/inbound.rs +++ b/src/providers/email_channel/inbound.rs @@ -21,6 +21,10 @@ use tokio::sync::mpsc; use tokio::time::{sleep, timeout}; use tracing::info; +/// Bound on one IMAP connect + TLS + login attempt. Without it a server that +/// accepts TCP and never answers would hold the reconnect loop forever. +pub(super) const IMAP_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + fn email_ref() -> ChannelRef { ChannelRef { id: "email".into(), @@ -308,7 +312,12 @@ impl EmailChannel { let session = client .login(&self.config.username, &self.config.password) .await - .map_err(|(e, _)| anyhow!("IMAP login failed: {}", e))?; + .map_err(|(e, _)| match e { + async_imap::error::Error::No(_) | async_imap::error::Error::Bad(_) => { + anyhow::Error::new(super::ImapLoginRejected(e.to_string())) + } + other => anyhow!("IMAP login failed: {}", other), + })?; debug!("IMAP login successful"); Ok(session) @@ -529,9 +538,20 @@ impl EmailChannel { { let mut backoff = self.reconnect_backoff; let max_backoff = self.max_reconnect_backoff; + let mut streak = crate::runtime::FailureStreak::default(); loop { - match self.run_idle_session(&delivery, connect()).await { + let logged_in = std::sync::atomic::AtomicBool::new(false); + let attempt = async { + let session = timeout(IMAP_CONNECT_TIMEOUT, connect()) + .await + .map_err(|_| { + anyhow!("IMAP connect timed out after {IMAP_CONNECT_TIMEOUT:?}") + })??; + logged_in.store(true, std::sync::atomic::Ordering::Relaxed); + Ok::<_, anyhow::Error>(session) + }; + match self.run_idle_session(&delivery, attempt).await { Ok(()) => { // Clean exit (channel closed) return Ok(()); @@ -540,10 +560,26 @@ impl EmailChannel { return Err(error); } Err(e) => { - error!( - "IMAP session error: {}. Reconnecting in {:?}...", - e, backoff - ); + // A session that logged in was healthy: it ends any streak + // and the backoff starts over. + if logged_in.load(std::sync::atomic::Ordering::Relaxed) { + streak.record_success(); + backoff = self.reconnect_backoff; + } + let escalate = streak.record_failure(); + if escalate || e.downcast_ref::().is_some() { + error!( + "IMAP session error ({} in a row): {}. Reconnecting in {:?}...", + streak.failures(), + e, + backoff + ); + } else { + warn!( + "IMAP session error: {}. Reconnecting in {:?}...", + e, backoff + ); + } sleep(backoff).await; // Exponential backoff with cap backoff = std::cmp::min(backoff * 2, max_backoff); diff --git a/src/providers/email_channel/mod.rs b/src/providers/email_channel/mod.rs index ee795fb7e..7ecd3b029 100644 --- a/src/providers/email_channel/mod.rs +++ b/src/providers/email_channel/mod.rs @@ -155,6 +155,15 @@ enum EmailDelivery<'a> { #[error("Email inbound sink rejected an event")] struct InboundSinkRejected; +/// The IMAP server refused the credentials (`NO`/`BAD` to `LOGIN`). +/// +/// Unlike a dropped connection this needs the user to fix their config, so the +/// reconnect loop keeps reporting it as an error. +#[cfg(feature = "email")] +#[derive(Debug, thiserror::Error)] +#[error("IMAP login failed: {0}")] +struct ImapLoginRejected(String); + /// Internal struct for parsed email data #[cfg(feature = "email")] struct ParsedEmail { diff --git a/src/providers/lark/inbound.rs b/src/providers/lark/inbound.rs index 3931be603..14752115a 100644 --- a/src/providers/lark/inbound.rs +++ b/src/providers/lark/inbound.rs @@ -223,7 +223,7 @@ impl LarkChannel { } } None => { tracing::info!("Lark: WS closed — reconnecting"); break; } - Some(Err(e)) => { tracing::error!("Lark: WS read error: {e}"); break; } + Some(Err(e)) => { tracing::warn!("Lark: WS read error: {e}"); break; } }; let frame = match PbFrame::decode(&raw[..]) { diff --git a/src/runtime.rs b/src/runtime.rs index 1d0ced7bd..cd6a1eaba 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -1,7 +1,7 @@ //! Runtime mechanics re-exported from the lightweight runtime crate. pub use tinychannels_runtime::{ - ChannelHealthState, ChannelSession, MAX_JITTER_MS, RuntimeChannelMessage, - classify_health_result, compute_max_in_flight_messages, jitter_millis, log_worker_join_result, - run_dispatch_loop, run_in_session, select_acknowledgment_reaction, + ChannelHealthState, ChannelSession, FAILURE_ESCALATE_THRESHOLD, FailureStreak, MAX_JITTER_MS, + RuntimeChannelMessage, classify_health_result, compute_max_in_flight_messages, jitter_millis, + log_worker_join_result, run_dispatch_loop, run_in_session, select_acknowledgment_reaction, }; From 9284fbbcf1328809e5f81ed366d6267537226134 Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Wed, 11 Nov 2026 16:44:11 +0530 Subject: [PATCH 2/2] Count an IMAP session as healthy only once it is listening A completed LOGIN reset the failure streak and the backoff. But if SELECT then fails (a missing or inaccessible folder), the session never listens, so every attempt reset both: the loop warned forever, never escalated and never slowed down. run_idle_session now takes a `listening` flag, set only after the mailbox is selected and the first unseen scan completes. The reconnect loop resets the streak and the backoff only for such a session. Regression tests drive run_idle_session against the fake server: a session whose SELECT is refused leaves the flag unset, and one that selects and then drops in IDLE sets it. --- .../email_channel/email_channel_tests.rs | 57 +++++++++++++++++++ src/providers/email_channel/inbound.rs | 27 +++++---- 2 files changed, 72 insertions(+), 12 deletions(-) diff --git a/src/providers/email_channel/email_channel_tests.rs b/src/providers/email_channel/email_channel_tests.rs index 8c31a6c8a..b0bbe9f80 100644 --- a/src/providers/email_channel/email_channel_tests.rs +++ b/src/providers/email_channel/email_channel_tests.rs @@ -663,6 +663,8 @@ enum IdleStep { #[derive(Clone, Default)] struct ConnScript { reject_login: bool, + /// Answer `SELECT` with `NO`, as a server does for a missing folder. + reject_select: bool, reject_store: bool, stall_logout: Option<(Arc, Arc)>, /// The i-th `UID SEARCH` answers with the i-th entry; later ones are empty. @@ -713,6 +715,10 @@ async fn serve_connection(sock: tokio::net::TcpStream, script: ConnScript) -> Ve reply.extend_from_slice(format!("{tag} NO bad credentials\r\n").as_bytes()); let _ = write.write_all(&reply).await; continue; + } else if upper.starts_with("SELECT") && script.reject_select { + reply.extend_from_slice(format!("{tag} NO mailbox does not exist\r\n").as_bytes()); + let _ = write.write_all(&reply).await; + continue; } else if upper.starts_with("SELECT") { reply.extend_from_slice( b"* 2 EXISTS\r\n* FLAGS (\\Seen)\r\n* OK [UIDVALIDITY 1234] UIDs valid\r\n", @@ -831,6 +837,57 @@ async fn a_hung_imap_connect_times_out_and_the_loop_retries() { listen.abort(); } +/// A login whose SELECT fails never listens, so the reconnect loop must not +/// count it as healthy: a missing folder would otherwise reset the backoff and +/// the failure streak on every attempt and never escalate. +#[tokio::test] +async fn a_session_that_logs_in_but_cannot_select_is_not_healthy() { + let (port, _server) = fake_imap(vec![ConnScript { + reject_select: true, + ..Default::default() + }]) + .await; + let channel = imap_channel(&["@example.com"], 30); + let (tx, _rx) = mpsc::channel(1); + let listening = std::sync::atomic::AtomicBool::new(false); + + let result = channel + .run_idle_session( + &EmailDelivery::Legacy(&tx), + plain_session(&channel, port), + &listening, + ) + .await; + + assert!(result.is_err(), "SELECT was refused"); + assert!(!listening.load(std::sync::atomic::Ordering::Relaxed)); +} + +/// A session that selects the mailbox and reaches IDLE is healthy, even if +/// the connection drops later. +#[tokio::test] +async fn a_session_that_reaches_idle_is_healthy() { + let (port, _server) = fake_imap(vec![ConnScript { + idles: vec![IdleStep::Truncate], + ..Default::default() + }]) + .await; + let channel = imap_channel(&["@example.com"], 30); + let (tx, _rx) = mpsc::channel(1); + let listening = std::sync::atomic::AtomicBool::new(false); + + let result = channel + .run_idle_session( + &EmailDelivery::Legacy(&tx), + plain_session(&channel, port), + &listening, + ) + .await; + + assert!(result.is_err(), "the dropped IDLE ends the session"); + assert!(listening.load(std::sync::atomic::Ordering::Relaxed)); +} + /// A credentials refusal is typed, so the loop keeps it at error level while /// ordinary disconnects become warnings. #[tokio::test] diff --git a/src/providers/email_channel/inbound.rs b/src/providers/email_channel/inbound.rs index 7f52581a5..c4b0caceb 100644 --- a/src/providers/email_channel/inbound.rs +++ b/src/providers/email_channel/inbound.rs @@ -541,17 +541,13 @@ impl EmailChannel { let mut streak = crate::runtime::FailureStreak::default(); loop { - let logged_in = std::sync::atomic::AtomicBool::new(false); + let listening = std::sync::atomic::AtomicBool::new(false); let attempt = async { - let session = timeout(IMAP_CONNECT_TIMEOUT, connect()) + timeout(IMAP_CONNECT_TIMEOUT, connect()) .await - .map_err(|_| { - anyhow!("IMAP connect timed out after {IMAP_CONNECT_TIMEOUT:?}") - })??; - logged_in.store(true, std::sync::atomic::Ordering::Relaxed); - Ok::<_, anyhow::Error>(session) + .map_err(|_| anyhow!("IMAP connect timed out after {IMAP_CONNECT_TIMEOUT:?}"))? }; - match self.run_idle_session(&delivery, attempt).await { + match self.run_idle_session(&delivery, attempt, &listening).await { Ok(()) => { // Clean exit (channel closed) return Ok(()); @@ -560,9 +556,10 @@ impl EmailChannel { return Err(error); } Err(e) => { - // A session that logged in was healthy: it ends any streak - // and the backoff starts over. - if logged_in.load(std::sync::atomic::Ordering::Relaxed) { + // A session that reached IDLE was healthy: it ends any + // streak and the backoff starts over. Logging in alone is + // not enough: a session whose SELECT fails never listens. + if listening.load(std::sync::atomic::Ordering::Relaxed) { streak.record_success(); backoff = self.reconnect_backoff; } @@ -588,12 +585,17 @@ impl EmailChannel { } } - /// Run a single IDLE session until error or clean shutdown + /// Run a single IDLE session until error or clean shutdown. + /// + /// Sets `listening` once the mailbox is selected and the first unseen + /// scan is done, i.e. once the session is actually serving: the reconnect + /// loop counts only such a session as healthy. #[cfg(feature = "email")] pub(super) async fn run_idle_session( &self, delivery: &EmailDelivery<'_>, connect: impl std::future::Future>>, + listening: &std::sync::atomic::AtomicBool, ) -> Result<()> { // Connect and authenticate let mut session = connect.await?; @@ -612,6 +614,7 @@ impl EmailChannel { // Check for existing unseen messages first self.process_unseen_to(&mut session, delivery, uid_validity) .await?; + listening.store(true, std::sync::atomic::Ordering::Relaxed); loop { // Enter IDLE and wait for changes (consumes session, returns it via result)