symqtt 0.1.1

Synchronous MQTT 3.1.1/5.0 client — blocking API, no async runtime
Documentation
//! Keepalive state tracker for MQTT connections.
//!
//! `Pinger` is a pure state machine with no threads, no IO, and no callbacks.
//! It tracks packet activity timestamps and tells the caller what to do next.
//! Usable with any runtime (blocking threads, async, embedded timer loops).

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

/// What the keepalive loop should do next.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PingerAction {
    /// Sleep for the given duration, then poll again.
    Sleep(Duration),
    /// Time to send a PINGREQ.
    SendPing,
    /// Ping response was not received within the timeout — connection is dead.
    TimedOut,
}

/// Pure keepalive state tracker.
///
/// Call [`Pinger::poll`] in your loop to determine the next action.
/// Call the `record_*` methods when packets are sent/received.
pub struct Pinger {
    keepalive_ms: AtomicU64,
    ping_timeout_ms: u64,
    last_packet_sent: AtomicU64,
    last_packet_received: AtomicU64,
    last_ping_response: AtomicU64,
    last_ping_sent: AtomicU64,
}

impl Pinger {
    /// Create a new Pinger with the given keepalive interval and ping timeout.
    pub fn new(keepalive: Duration, ping_timeout: Duration) -> Self {
        let now = crate::time::now_ms();
        Self {
            keepalive_ms: AtomicU64::new(keepalive.as_millis() as u64),
            ping_timeout_ms: ping_timeout.as_millis() as u64,
            last_packet_sent: AtomicU64::new(now),
            last_packet_received: AtomicU64::new(now),
            last_ping_response: AtomicU64::new(now),
            last_ping_sent: AtomicU64::new(0),
        }
    }

    /// Update the keepalive interval (e.g. after server override via CONNACK).
    pub fn set_keepalive(&self, keepalive: Duration) {
        self.keepalive_ms.store(keepalive.as_millis() as u64, Ordering::Relaxed);
    }

    /// Determine the next action the keepalive loop should take.
    pub fn poll(&self) -> PingerAction {
        let now = crate::time::now_ms();
        let last_ping_sent = self.last_ping_sent.load(Ordering::Relaxed);
        let last_resp = self.last_ping_response.load(Ordering::Relaxed);

        if last_ping_sent > 0 && last_ping_sent > last_resp {
            let elapsed = now.saturating_sub(last_ping_sent);
            if elapsed >= self.ping_timeout_ms {
                return PingerAction::TimedOut;
            }
            return PingerAction::Sleep(Duration::from_millis(self.ping_timeout_ms - elapsed));
        }

        let remaining = self.remaining_until_ping(now);
        if remaining > 0 {
            PingerAction::Sleep(Duration::from_millis(remaining))
        } else {
            PingerAction::SendPing
        }
    }

    /// Record that a PINGREQ was sent. Call this after successfully sending the ping.
    #[inline]
    pub fn record_ping_sent(&self) {
        let now = crate::time::now_ms();
        self.last_ping_sent.store(now, Ordering::Relaxed);
        self.last_packet_sent.store(now, Ordering::Relaxed);
    }

    /// Record that a PINGRESP was received.
    #[inline]
    pub fn record_ping_response(&self) {
        self.last_ping_response.store(crate::time::now_ms(), Ordering::Relaxed);
    }

    /// Record that any packet was sent (non-ping packets included).
    #[inline]
    pub fn record_sent(&self) {
        self.last_packet_sent.store(crate::time::now_ms(), Ordering::Relaxed);
    }

    /// Record that any packet was received.
    #[inline]
    pub fn record_received(&self) {
        self.last_packet_received
            .store(crate::time::now_ms(), Ordering::Relaxed);
    }

    fn remaining_until_ping(&self, now: u64) -> u64 {
        let sent = self.last_packet_sent.load(Ordering::Relaxed);
        let recv = self.last_packet_received.load(Ordering::Relaxed);
        let last_activity = sent.min(recv);
        let ping_due = last_activity + self.keepalive_ms.load(Ordering::Relaxed);
        ping_due.saturating_sub(now)
    }
}

#[cfg(test)]
mod tests {
    use std::thread;
    use std::time::Duration;

    use super::*;

    fn make_pinger(keepalive_ms: u64, timeout_ms: u64) -> Pinger {
        Pinger::new(Duration::from_millis(keepalive_ms), Duration::from_millis(timeout_ms))
    }

    #[test]
    fn new_pinger_sleeps_until_keepalive() {
        let p = make_pinger(100, 50);
        match p.poll() {
            PingerAction::Sleep(d) => {
                // Should sleep roughly up to keepalive interval
                assert!(d.as_millis() <= 100);
                assert!(d.as_millis() > 0);
            }
            other => panic!("expected Sleep, got {:?}", other),
        }
    }

    #[test]
    fn send_ping_after_keepalive_elapsed() {
        let p = make_pinger(10, 50);
        thread::sleep(Duration::from_millis(15));
        assert_eq!(p.poll(), PingerAction::SendPing);
    }

    #[test]
    fn record_sent_resets_keepalive_timer() {
        let p = make_pinger(20, 50);
        thread::sleep(Duration::from_millis(15));
        // Activity resets the timer
        p.record_sent();
        match p.poll() {
            PingerAction::Sleep(d) => assert!(d.as_millis() > 0),
            other => panic!("expected Sleep after record_sent, got {:?}", other),
        }
    }

    #[test]
    fn record_received_resets_keepalive_timer() {
        let p = make_pinger(20, 50);
        thread::sleep(Duration::from_millis(15));
        p.record_received();
        match p.poll() {
            PingerAction::Sleep(d) => assert!(d.as_millis() > 0),
            other => panic!("expected Sleep after record_received, got {:?}", other),
        }
    }

    #[test]
    fn timeout_after_ping_sent_without_response() {
        let p = make_pinger(10, 15);
        // Wait for keepalive to expire
        thread::sleep(Duration::from_millis(12));
        assert_eq!(p.poll(), PingerAction::SendPing);

        // Simulate sending ping
        p.record_ping_sent();

        // Now waiting for response — should sleep
        match p.poll() {
            PingerAction::Sleep(d) => assert!(d.as_millis() <= 15),
            other => panic!("expected Sleep while waiting for pong, got {:?}", other),
        }

        // Wait past timeout
        thread::sleep(Duration::from_millis(20));
        assert_eq!(p.poll(), PingerAction::TimedOut);
    }

    #[test]
    fn ping_response_resets_to_normal_sleep() {
        let p = make_pinger(10, 50);
        thread::sleep(Duration::from_millis(12));
        assert_eq!(p.poll(), PingerAction::SendPing);

        p.record_ping_sent();
        // Simulate receiving response
        p.record_ping_response();

        // Should go back to normal keepalive cycle
        match p.poll() {
            PingerAction::Sleep(_) | PingerAction::SendPing => {} // both acceptable
            PingerAction::TimedOut => panic!("should not time out after response"),
        }
    }

    #[test]
    fn record_ping_sent_also_updates_last_packet_sent() {
        let p = make_pinger(50, 80);
        thread::sleep(Duration::from_millis(20));
        // record_ping_sent updates last_packet_sent, and record_received
        // updates last_packet_received — both are used in remaining_until_ping
        p.record_ping_sent();
        p.record_received();
        p.record_ping_response();

        match p.poll() {
            PingerAction::Sleep(d) => {
                // Both sent & received just updated, so should sleep ~full keepalive
                assert!(d.as_millis() >= 30);
            }
            other => panic!("expected Sleep, got {:?}", other),
        }
    }
}