symqtt 0.1.1

Synchronous MQTT 3.1.1/5.0 client — blocking API, no async runtime
Documentation
//! MQTT 5.0 client implementation with blocking API
//!
//! Provides connection management, publish, subscribe, and lifecycle handling
//! for MQTT 5.0 brokers over any [`Transport`](crate::transport::Transport).
//!
//! Core components:
//! - [`Client`] — thread-safe blocking client; uniquely owns one connection
//! - [`Session`] — connection-independent session state with server property negotiation
//! - [`Token`] — ACK completion handle with reason code support
//!
//! Key differences from v3:
//! - CONNACK negotiation (Receive Maximum, Maximum Packet Size, Topic Alias, etc.)
//! - Reason codes on all acknowledgements
//! - Bidirectional topic alias compression
//! - Enhanced authentication (AUTH packet multi-round)
//! - DISCONNECT with reason code (both directions)

use std::time::Duration;

use bytes::Bytes;

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

pub use auth::{AuthHandler, NoOpAuthHandler};
pub use client::Client;
pub use error::Error;
pub use session::{AckResult, Retransmit, ServerProperties, Session, SessionError};
pub use symqtt_codec::QoS;
pub use symqtt_codec::v5::{Disconnect, Publish, ReasonCode, RetainHandling};
pub use token::{PublishAckDetail, Token};

/// Handler for inbound messages and connection lifecycle events (MQTT 5.0)
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) {}

    /// Called when the server sends a DISCONNECT packet (v5 feature)
    fn on_server_disconnect(&self, _disconnect: &Disconnect) {}
}

/// MQTT 5.0 Last Will and Testament
pub struct Will {
    /// Topic to publish the will message to
    pub topic: String,
    /// Will message payload
    pub payload: Bytes,
    /// QoS for the will message delivery
    pub qos: QoS,
    /// Whether the will message should be retained
    pub retain: bool,
    /// MQTT 5.0 will properties
    pub properties: WillProperties,
}

/// Will properties specific to MQTT 5.0 [MQTTv5-3.1.3.2]
#[derive(Debug, Clone, Default)]
pub struct WillProperties {
    /// Delay in seconds before the server publishes the will
    pub will_delay_interval: Option<u32>,
    /// Payload format: 0 = unspecified bytes, 1 = UTF-8
    pub payload_format_indicator: Option<u8>,
    /// Lifetime in seconds for the will message
    pub message_expiry_interval: Option<u32>,
    /// MIME content type of the will payload
    pub content_type: Option<String>,
    /// Response topic for request/response flow
    pub response_topic: Option<String>,
    /// Correlation data for request/response flow
    pub correlation_data: Option<Bytes>,
    /// User-defined key-value properties
    pub user_properties: Vec<(String, String)>,
}

/// Options for establishing an MQTT 5.0 connection
pub struct ConnectOptions {
    /// Client identifier
    pub client_id: String,
    /// Clean start flag (v5 replaces v3's clean_session)
    pub clean_start: bool,
    /// Keepalive interval
    pub keep_alive: Duration,
    /// Last will message
    pub will: Option<Will>,
    /// Username for authentication
    pub username: Option<String>,
    /// Password for authentication
    pub password: Option<Bytes>,
    /// Timeout for CONNECT handshake
    pub connect_timeout: Option<Duration>,
    /// Timeout for PINGRESP
    pub ping_timeout: Option<Duration>,

    /// Session expiry interval (seconds). 0 = session ends at disconnect.
    pub session_expiry_interval: Option<Duration>,
    /// Client's receive maximum (how many QoS>0 messages client can handle concurrently)
    pub receive_maximum: Option<u16>,
    /// Maximum packet size client is willing to accept
    pub maximum_packet_size: Option<u32>,
    /// Maximum number of topic aliases client supports (inbound)
    pub topic_alias_maximum: Option<u16>,
    /// Request response information from server
    pub request_response_info: bool,
    /// Request problem information (include Reason String / User Properties on failures)
    pub request_problem_info: bool,
    /// User properties to include in CONNECT
    pub user_properties: Vec<(String, String)>,
    /// Enhanced authentication method
    pub auth_method: Option<String>,
    /// Enhanced authentication data
    pub auth_data: Option<Bytes>,
}

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

impl Default for ConnectOptions {
    fn default() -> Self {
        Self {
            client_id: String::new(),
            clean_start: true,
            keep_alive: Duration::from_secs(60),
            will: None,
            username: None,
            password: None,
            connect_timeout: None,
            ping_timeout: None,
            session_expiry_interval: None,
            receive_maximum: None,
            maximum_packet_size: None,
            topic_alias_maximum: None,
            request_response_info: false,
            request_problem_info: true,
            user_properties: Vec::new(),
            auth_method: None,
            auth_data: None,
        }
    }
}

/// Payload format indicator (MQTT 5.0 property)
///
/// Indicates whether the payload is unspecified bytes or UTF-8 encoded text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PayloadFormatIndicator {
    /// Unspecified byte stream (equivalent to wire value 0)
    Unspecified = 0,
    /// UTF-8 encoded string (equivalent to wire value 1)
    Utf8 = 1,
}

impl PayloadFormatIndicator {
    /// Convert to the wire-level u8 value
    pub fn as_u8(self) -> u8 {
        self as u8
    }
}

/// Parameters for a PUBLISH operation (MQTT 5.0)
pub struct PublishMessage<'a> {
    /// Topic name to publish to
    pub topic: &'a str,
    /// Message payload
    pub payload: Bytes,
    /// Quality of Service level
    pub qos: QoS,
    /// Whether the message should be retained by the broker
    pub retain: bool,
    /// Timeout for waiting on ACK (QoS 1/2)
    pub timeout: Option<Duration>,
    /// Payload format indicator [MQTTv5-3.3.2.3.2]
    pub payload_format_indicator: Option<PayloadFormatIndicator>,
    /// Message expiry interval [MQTTv5-3.3.2.3.3]
    pub message_expiry_interval: Option<Duration>,
    /// Response topic for request/response [MQTTv5-3.3.2.3.5]
    pub response_topic: Option<String>,
    /// Correlation data for request/response [MQTTv5-3.3.2.3.6]
    pub correlation_data: Option<Bytes>,
    /// User properties [MQTTv5-3.3.2.3.7]
    pub user_properties: Vec<(String, String)>,
    /// Content type of the payload [MQTTv5-3.3.2.3.9]
    pub content_type: Option<String>,
}

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,
            payload_format_indicator: None,
            message_expiry_interval: None,
            response_topic: None,
            correlation_data: None,
            user_properties: Vec::new(),
            content_type: None,
        }
    }

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

    /// Set the retain flag
    pub fn retain(mut self, retain: bool) -> Self {
        self.retain = retain;
        self
    }

    /// Set the ACK timeout for QoS 1/2
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Set the payload format indicator [MQTTv5-3.3.2.3.2]
    pub fn payload_format_indicator(mut self, v: PayloadFormatIndicator) -> Self {
        self.payload_format_indicator = Some(v);
        self
    }

    /// Set the message expiry interval [MQTTv5-3.3.2.3.3]
    pub fn message_expiry_interval(mut self, d: Duration) -> Self {
        self.message_expiry_interval = Some(d);
        self
    }

    /// Set the response topic for request/response pattern [MQTTv5-3.3.2.3.5]
    pub fn response_topic(mut self, topic: String) -> Self {
        self.response_topic = Some(topic);
        self
    }

    /// Set the correlation data for request/response pattern [MQTTv5-3.3.2.3.6]
    pub fn correlation_data(mut self, data: Bytes) -> Self {
        self.correlation_data = Some(data);
        self
    }

    /// Append user properties [MQTTv5-3.3.2.3.7]
    pub fn user_properties(mut self, props: impl IntoIterator<Item = (String, String)>) -> Self {
        self.user_properties.extend(props);
        self
    }

    /// Set the content type [MQTTv5-3.3.2.3.9]
    pub fn content_type(mut self, ct: String) -> Self {
        self.content_type = Some(ct);
        self
    }
}

/// V5 subscribe filter with full subscription options [MQTTv5-3.8.3.1]
#[derive(Debug)]
pub struct SubscribeFilter {
    /// Topic filter pattern (may include wildcards)
    pub topic: String,
    /// Maximum QoS level the server should deliver
    pub qos: QoS,
    /// If true, server will not send messages originated by this client
    pub no_local: bool,
    /// If true, PUBLISH retain flag is preserved from the original publish
    pub retain_as_published: bool,
    /// Controls when retained messages are sent on subscribe
    pub retain_handling: RetainHandling,
}

impl SubscribeFilter {
    /// Create a simple subscribe filter with defaults
    pub fn new(topic: impl Into<String>, qos: QoS) -> Self {
        Self {
            topic: topic.into(),
            qos,
            no_local: false,
            retain_as_published: false,
            retain_handling: RetainHandling::SendAtSubscribe,
        }
    }
}

/// Convert ConnectOptions to codec Connect packet
impl From<&ConnectOptions> for symqtt_codec::v5::Connect {
    fn from(opts: &ConnectOptions) -> Self {
        Self {
            clean_start: opts.clean_start,
            keep_alive: opts.keep_alive.as_secs() as u16,
            client_id: opts.client_id.clone(),
            username: opts.username.clone(),
            password: opts.password.clone(),
            will: opts.will.as_ref().map(|w| symqtt_codec::v5::Will {
                qos: w.qos,
                retain: w.retain,
                topic: w.topic.clone(),
                payload: w.payload.clone(),
                properties: symqtt_codec::v5::WillProperties {
                    will_delay_interval: w.properties.will_delay_interval,
                    payload_format_indicator: w.properties.payload_format_indicator,
                    message_expiry_interval: w.properties.message_expiry_interval,
                    content_type: w.properties.content_type.clone(),
                    response_topic: w.properties.response_topic.clone(),
                    correlation_data: w.properties.correlation_data.clone(),
                    user_properties: w.properties.user_properties.clone(),
                },
            }),
            properties: symqtt_codec::v5::ConnectProperties {
                session_expiry_interval: opts.session_expiry_interval.map(|v| v.as_secs() as u32),
                receive_maximum: opts.receive_maximum,
                maximum_packet_size: opts.maximum_packet_size,
                topic_alias_maximum: opts.topic_alias_maximum,
                request_response_information: if opts.request_response_info { Some(1) } else { None },
                request_problem_information: if opts.request_problem_info { Some(1) } else { None },
                user_properties: opts.user_properties.clone(),
                authentication_method: opts.auth_method.clone(),
                authentication_data: opts.auth_data.clone(),
            },
        }
    }
}

/// Convert PublishMessage to codec Publish packet
impl From<&PublishMessage<'_>> for Publish {
    fn from(msg: &PublishMessage<'_>) -> Self {
        Publish {
            dup: false,
            qos: msg.qos,
            retain: msg.retain,
            topic: msg.topic.to_owned(),
            pkid: None,
            properties: symqtt_codec::v5::PublishProperties {
                payload_format_indicator: msg.payload_format_indicator.map(|v| v.as_u8()),
                message_expiry_interval: msg
                    .message_expiry_interval
                    .map(|d| d.as_secs().min(u32::MAX as u64) as u32),
                topic_alias: None, // managed internally by Client
                response_topic: msg.response_topic.clone(),
                correlation_data: msg.correlation_data.clone(),
                subscription_identifiers: Vec::new(),
                user_properties: msg.user_properties.clone(),
                content_type: msg.content_type.clone(),
            },
            payload: msg.payload.clone(),
        }
    }
}

/// Convert our SubscribeFilter to codec SubscribeFilter
impl From<&SubscribeFilter> for symqtt_codec::v5::SubscribeFilter {
    fn from(f: &SubscribeFilter) -> Self {
        Self {
            topic: f.topic.clone(),
            qos: f.qos,
            no_local: f.no_local,
            retain_as_published: f.retain_as_published,
            retain_handling: f.retain_handling,
        }
    }
}