Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 31 additions & 3 deletions crates/tinychannels-module/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn ChannelAdapter>,
Expand All @@ -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;
Expand Down
35 changes: 35 additions & 0 deletions crates/tinychannels-runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
21 changes: 21 additions & 0 deletions crates/tinychannels-runtime/src/lib_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
106 changes: 106 additions & 0 deletions src/providers/email_channel/email_channel_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Notify>, Arc<Notify>)>,
/// The i-th `UID SEARCH` answers with the i-th entry; later ones are empty.
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -805,6 +811,106 @@ 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::<Result<Session<tokio::net::TcpStream>>>()
})
.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 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]
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::<ImapLoginRejected>().is_some(),
"{error:#}"
);
assert!(
error.to_string().starts_with("IMAP login failed:"),
"{error}"
);
}

async fn recv(rx: &mut mpsc::Receiver<ChannelMessage>) -> ChannelMessage {
timeout(HANG_GUARD, rx.recv())
.await
Expand Down
53 changes: 46 additions & 7 deletions src/providers/email_channel/inbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -529,9 +538,16 @@ 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 listening = std::sync::atomic::AtomicBool::new(false);
let attempt = async {
timeout(IMAP_CONNECT_TIMEOUT, connect())
.await
.map_err(|_| anyhow!("IMAP connect timed out after {IMAP_CONNECT_TIMEOUT:?}"))?
};
match self.run_idle_session(&delivery, attempt, &listening).await {
Ok(()) => {
// Clean exit (channel closed)
return Ok(());
Expand All @@ -540,10 +556,27 @@ impl EmailChannel {
return Err(error);
}
Err(e) => {
error!(
"IMAP session error: {}. Reconnecting in {:?}...",
e, backoff
);
// 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;
}
let escalate = streak.record_failure();
if escalate || e.downcast_ref::<super::ImapLoginRejected>().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);
Expand All @@ -552,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<S: ImapStream>(
&self,
delivery: &EmailDelivery<'_>,
connect: impl std::future::Future<Output = Result<Session<S>>>,
listening: &std::sync::atomic::AtomicBool,
) -> Result<()> {
// Connect and authenticate
let mut session = connect.await?;
Expand All @@ -576,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)
Expand Down
9 changes: 9 additions & 0 deletions src/providers/email_channel/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion src/providers/lark/inbound.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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[..]) {
Expand Down
6 changes: 3 additions & 3 deletions src/runtime.rs
Original file line number Diff line number Diff line change
@@ -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,
};
Loading