symqtt 0.1.1

Synchronous MQTT 3.1.1/5.0 client — blocking API, no async runtime
Documentation
//! Completion token for blocking on broker ACK responses (MQTT 5.0)
//!
//! Unlike v3, v5 tokens can carry detailed ACK information including
//! reason codes and properties.

use std::marker::PhantomData;
use std::sync::mpsc::Receiver;
use std::time::Duration;

use symqtt_codec::v5::{PubAckProperties, ReasonCode};

use super::error::Error;
use super::session::AckResult;

/// Detailed result from a PUBACK/PUBCOMP with reason code and properties
///
/// A broker failure reason code is still delivered as this struct, not as [`Error`].
/// Call [`ReasonCode::is_success`] on [`Self::reason_code`] to decide whether the
/// publish was accepted.
#[derive(Debug, Clone)]
pub struct PublishAckDetail {
    /// Broker reason code from PUBACK/PUBCOMP (or a failed PUBREC)
    ///
    /// Check with [`ReasonCode::is_success`]; values `>= 0x80` are failures
    pub reason_code: ReasonCode,
    /// Additional properties (reason string, user properties)
    pub properties: PubAckProperties,
}

/// Opaque completion handle for waiting on broker acknowledgements
///
/// Type parameter `T` determines the resolved value:
/// - `Token<PublishAckDetail>` — for publish (reason code + properties)
/// - `Token<Vec<ReasonCode>>` — for SUBACK/UNSUBACK (per-filter reason codes)
///
/// Broker failure reason codes complete as `Ok`. Call [`ReasonCode::is_success`]
/// on the returned code(s) to decide whether the operation was accepted.
pub struct Token<T = ()> {
    rx: Receiver<AckResult>,
    _marker: PhantomData<T>,
}

impl<T> std::fmt::Debug for Token<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Token").finish_non_exhaustive()
    }
}

impl<T> Token<T> {
    /// Create a token backed by a completion channel receiver
    pub fn new(rx: Receiver<AckResult>) -> Self {
        Self {
            rx,
            _marker: PhantomData,
        }
    }
}

impl Token<PublishAckDetail> {
    /// Block until the broker ACK arrives
    ///
    /// # Returns
    ///
    /// [`PublishAckDetail`] from PUBACK/PUBCOMP (or a failed PUBREC). A non-success
    /// reason code is still `Ok`; call [`ReasonCode::is_success`] on
    /// [`PublishAckDetail::reason_code`] to check whether the publish was accepted.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Disconnected`] when the completion channel is closed
    /// before an ACK arrives.
    ///
    /// Returns the underlying error if the connection was lost while waiting.
    pub fn wait(self) -> Result<PublishAckDetail, Error> {
        match self.rx.recv() {
            Ok(AckResult::Ack(reason_code, properties)) => Ok(PublishAckDetail {
                reason_code,
                properties,
            }),
            Ok(AckResult::Success) => Ok(PublishAckDetail {
                reason_code: ReasonCode::Success,
                properties: PubAckProperties::default(),
            }),
            Ok(AckResult::Error(e)) => Err(e),
            Ok(_) => Ok(PublishAckDetail {
                reason_code: ReasonCode::Success,
                properties: PubAckProperties::default(),
            }),
            Err(_) => Err(Error::Disconnected),
        }
    }

    /// Block until the broker ACK arrives or `timeout` expires
    ///
    /// # Returns
    ///
    /// Same as [`Self::wait`]: a non-success reason code is still `Ok`. Call
    /// [`ReasonCode::is_success`] on [`PublishAckDetail::reason_code`] to check
    /// whether the publish was accepted.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Timeout`] when no ACK arrives within `timeout`.
    ///
    /// Returns the underlying error if the connection was lost while waiting.
    pub fn wait_timeout(self, timeout: Duration) -> Result<PublishAckDetail, Error> {
        match self.rx.recv_timeout(timeout) {
            Ok(AckResult::Ack(reason_code, properties)) => Ok(PublishAckDetail {
                reason_code,
                properties,
            }),
            Ok(AckResult::Success) => Ok(PublishAckDetail {
                reason_code: ReasonCode::Success,
                properties: PubAckProperties::default(),
            }),
            Ok(AckResult::Error(e)) => Err(e),
            Ok(_) => Ok(PublishAckDetail {
                reason_code: ReasonCode::Success,
                properties: PubAckProperties::default(),
            }),
            Err(_) => Err(Error::Timeout),
        }
    }

    /// Non-blocking check whether the ACK has arrived
    ///
    /// Returns `None` if no result is available yet.
    ///
    /// # Returns
    ///
    /// Same as [`Self::wait`] when a result is ready: a non-success reason code is
    /// still `Ok`. Call [`ReasonCode::is_success`] on
    /// [`PublishAckDetail::reason_code`] to check whether the publish was accepted.
    pub fn try_recv(&self) -> Option<Result<PublishAckDetail, Error>> {
        match self.rx.try_recv() {
            Ok(AckResult::Ack(reason_code, properties)) => Some(Ok(PublishAckDetail {
                reason_code,
                properties,
            })),
            Ok(AckResult::Success) => Some(Ok(PublishAckDetail {
                reason_code: ReasonCode::Success,
                properties: PubAckProperties::default(),
            })),
            Ok(AckResult::Error(e)) => Some(Err(e)),
            Ok(_) => Some(Ok(PublishAckDetail {
                reason_code: ReasonCode::Success,
                properties: PubAckProperties::default(),
            })),
            Err(_) => None,
        }
    }
}

impl Token<Vec<ReasonCode>> {
    /// Block until SUBACK/UNSUBACK is received
    ///
    /// # Returns
    ///
    /// Per-filter [`ReasonCode`]s in the same order as the original request.
    /// A failed filter is still `Ok`; call [`ReasonCode::is_success`] on each
    /// code to check whether that filter was accepted.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Disconnected`] when the completion channel is closed
    /// before an ACK arrives.
    ///
    /// Returns the underlying error if the connection was lost while waiting.
    pub fn wait(self) -> Result<Vec<ReasonCode>, Error> {
        match self.rx.recv() {
            Ok(AckResult::SubAck(codes, _)) => Ok(codes),
            Ok(AckResult::UnsubAck(codes, _)) => Ok(codes),
            Ok(AckResult::Success) => Ok(vec![]),
            Ok(AckResult::Error(e)) => Err(e),
            Ok(_) => Ok(vec![]),
            Err(_) => Err(Error::Disconnected),
        }
    }

    /// Block until SUBACK/UNSUBACK is received or `timeout` expires
    ///
    /// # Returns
    ///
    /// Same as [`Self::wait`]: a failed filter is still `Ok`. Call
    /// [`ReasonCode::is_success`] on each code to check whether that filter
    /// was accepted.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Timeout`] when no ACK arrives within `timeout`.
    ///
    /// Returns the underlying error if the connection was lost while waiting.
    pub fn wait_timeout(self, timeout: Duration) -> Result<Vec<ReasonCode>, Error> {
        match self.rx.recv_timeout(timeout) {
            Ok(AckResult::SubAck(codes, _)) => Ok(codes),
            Ok(AckResult::UnsubAck(codes, _)) => Ok(codes),
            Ok(AckResult::Success) => Ok(vec![]),
            Ok(AckResult::Error(e)) => Err(e),
            Ok(_) => Ok(vec![]),
            Err(_) => Err(Error::Timeout),
        }
    }

    /// Non-blocking check whether SUBACK/UNSUBACK has arrived
    ///
    /// Returns `None` if no result is available yet.
    ///
    /// # Returns
    ///
    /// Same as [`Self::wait`] when a result is ready: a failed filter is still
    /// `Ok`. Call [`ReasonCode::is_success`] on each code to check whether that
    /// filter was accepted.
    pub fn try_recv(&self) -> Option<Result<Vec<ReasonCode>, Error>> {
        match self.rx.try_recv() {
            Ok(AckResult::SubAck(codes, _)) => Some(Ok(codes)),
            Ok(AckResult::UnsubAck(codes, _)) => Some(Ok(codes)),
            Ok(AckResult::Success) => Some(Ok(vec![])),
            Ok(AckResult::Error(e)) => Some(Err(e)),
            Ok(_) => Some(Ok(vec![])),
            Err(_) => None,
        }
    }
}