symqtt 0.1.1

Synchronous MQTT 3.1.1/5.0 client — blocking API, no async runtime
Documentation
//! MQTT 3.1.1 client implementation with blocking API
//!
//! Provides connection management, publish, subscribe, and lifecycle handling
//! for MQTT 3.1.1 brokers over any [`Transport`](crate::transport::Transport).
//!
//! Core components:
//! - [`Client`] — thread-safe blocking client; uniquely owns one connection
//! - [`Session`] — connection-independent session state, preserves QoS 1/2 inflight messages across reconnections
//! - [`Token`] — ACK completion handle, allows callers to block until broker acknowledgement arrives
//!
//! Thread model: caller threads encode and send packets, a dedicated read thread
//! receives and dispatches inbound packets, and a keepalive thread periodically
//! sends PINGREQ to detect broker liveness.

use std::time::Duration;

use bytes::Bytes;

pub(crate) mod client;
pub(crate) mod error;
pub(crate) mod session;
pub(crate) mod token;

pub use client::Client;
pub use error::Error;
pub use session::{AckResult, Retransmit, Session, SessionError};
pub use symqtt_codec::QoS;
pub use symqtt_codec::v3::{Publish, SubscribeReturnCode};
pub use token::Token;

/// Handler for inbound messages and connection lifecycle events
///
/// Implement this trait to receive PUBLISH messages delivered by the broker
/// and to be notified when the connection is lost
pub trait InboundHandler: Send + Sync + 'static {
    /// Called when a PUBLISH message is received from the broker
    fn on_publish(&self, msg: &Publish);

    /// Called when the connection is lost or an unrecoverable error occurs.
    ///
    /// Also invoked by [`Client::disconnect`]. Not called when a still-connected
    /// [`Client`] is dropped.
    fn on_disconnect(&self, _reason: &Error) {}
}

/// MQTT Last Will and Testament configuration
///
/// When the client disconnects ungracefully, the broker publishes this
/// message on behalf of the client to notify other subscribers
pub struct Will {
    /// Topic the will message is published to
    pub topic: String,
    /// Will message payload (arbitrary bytes)
    pub message: Bytes,
    /// QoS level for will message delivery
    pub qos: QoS,
    /// Whether the broker should retain the will message
    pub retain: bool,
}

/// Options for establishing an MQTT 3.1.1 connection
///
/// Encapsulates all CONNECT packet configuration including authentication,
/// keepalive interval, and last will
pub struct ConnectOptions {
    /// Client identifier used by the broker to track session ownership
    pub client_id: String,
    /// Whether the broker should discard any existing session state
    pub clean_session: bool,
    /// Keepalive interval; the client sends PINGREQ if no packets are sent within this period
    pub keep_alive: Duration,
    /// Last will message published by the broker on ungraceful disconnect
    pub will: Option<Will>,
    /// Username for broker authentication
    pub username: Option<String>,
    /// Password for broker authentication
    pub password: Option<Bytes>,
    /// Total timeout for the CONNECT handshake (sending CONNECT + waiting for CONNACK)
    pub connect_timeout: Option<Duration>,
    /// Timeout for waiting on PINGRESP after sending PINGREQ; defaults to `keep_alive` if unset
    pub ping_timeout: Option<Duration>,
}

impl ConnectOptions {
    /// Effective ping timeout: explicit value if set, otherwise falls back to keepalive duration
    pub fn ping_timeout(&self) -> Duration {
        self.ping_timeout.unwrap_or(self.keep_alive)
    }
}

/// Parameters for a PUBLISH operation, configured via builder-style method chaining
///
/// # Example
///
/// ```no_run
/// use std::time::Duration;
/// use bytes::Bytes;
/// use symqtt::v3::{PublishMessage, QoS};
///
/// let msg = PublishMessage::new("sensor/temp", Bytes::from("25.3"))
///     .qos(QoS::AtLeastOnce)
///     .retain(true)
///     .timeout(Duration::from_secs(5));
/// ```
pub struct PublishMessage<'a> {
    pub(crate) topic: &'a str,
    pub(crate) payload: Bytes,
    pub(crate) qos: QoS,
    pub(crate) retain: bool,
    pub(crate) timeout: Option<Duration>,
}

impl<'a> PublishMessage<'a> {
    /// Create publish parameters with defaults: QoS 0, no retain, no timeout
    pub fn new(topic: &'a str, payload: Bytes) -> Self {
        Self {
            topic,
            payload,
            qos: QoS::AtMostOnce,
            retain: false,
            timeout: None,
        }
    }

    /// Set the QoS level for message delivery
    pub fn qos(mut self, qos: QoS) -> Self {
        self.qos = qos;
        self
    }

    /// Set whether the broker should retain this message
    pub fn retain(mut self, retain: bool) -> Self {
        self.retain = retain;
        self
    }

    /// Set the send timeout; returns [`Error::Timeout`] on expiry
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }
}

impl From<&PublishMessage<'_>> for symqtt_codec::v3::Publish {
    fn from(msg: &PublishMessage<'_>) -> Self {
        symqtt_codec::v3::Publish {
            dup: false,
            pkid: None,
            qos: msg.qos,
            retain: msg.retain,
            topic: msg.topic.to_owned(),
            payload: msg.payload.clone(),
        }
    }
}

impl From<&ConnectOptions> for symqtt_codec::v3::Connect {
    fn from(opts: &ConnectOptions) -> Self {
        Self {
            will: opts.will.as_ref().map(symqtt_codec::v3::Will::from),
            keep_alive: opts.keep_alive.as_secs() as u16,
            client_id: opts.client_id.clone(),
            username: opts.username.clone(),
            password: opts.password.clone(),
            clean_session: opts.clean_session,
        }
    }
}

impl From<&Will> for symqtt_codec::v3::Will {
    fn from(w: &Will) -> Self {
        Self {
            qos: w.qos,
            retain: w.retain,
            topic: w.topic.to_owned(),
            message: w.message.clone(),
        }
    }
}