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
//!
//! A [`Token<T>`] is returned by [`Client::publish`](super::Client::publish),
//! [`Client::subscribe`](super::Client::subscribe), and
//! [`Client::unsubscribe`](super::Client::unsubscribe). The caller uses it to
//! block until the corresponding ACK arrives from the broker.

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

use symqtt_codec::v3::SubscribeReturnCode;

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

/// Opaque completion handle for waiting on broker acknowledgements
///
/// Type parameter `T` determines the resolved value:
/// - `Token<()>` — for PUBACK, PUBCOMP, UNSUBACK (success or error only)
/// - `Token<Vec<SubscribeReturnCode>>` — for SUBACK (carries granted QoS per filter)
pub struct Token<T = ()> {
    rx: Receiver<AckResult>,
    _marker: PhantomData<T>,
}

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

impl Token<()> {
    /// Block until ACK is received
    ///
    /// # 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<(), Error> {
        match self.rx.recv() {
            Ok(AckResult::Success) => Ok(()),
            Ok(AckResult::Error(e)) => Err(e),
            // SubAck can arrive here when an unsubscribe token receives SUBACK
            // due to internal stage reuse — treat as success
            Ok(AckResult::SubAck(_)) => Ok(()),
            Err(_) => Err(Error::Disconnected),
        }
    }

    /// Block until ACK is received or the timeout expires
    ///
    /// # 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<(), Error> {
        match self.rx.recv_timeout(timeout) {
            Ok(AckResult::Success) => Ok(()),
            Ok(AckResult::Error(e)) => Err(e),
            // SubAck can arrive here when an unsubscribe token receives SUBACK
            // due to internal stage reuse — treat as success
            Ok(AckResult::SubAck(_)) => Ok(()),
            Err(_) => Err(Error::Timeout),
        }
    }

    /// Non-blocking check whether the ACK has arrived
    ///
    /// Returns `None` if no result is available yet.
    pub fn try_recv(&self) -> Option<Result<(), Error>> {
        match self.rx.try_recv() {
            Ok(AckResult::Success) => Some(Ok(())),
            Ok(AckResult::Error(e)) => Some(Err(e)),
            Ok(AckResult::SubAck(_)) => Some(Ok(())),
            Err(_) => None,
        }
    }
}

impl Token<Vec<SubscribeReturnCode>> {
    /// Block until SUBACK is received
    ///
    /// # Returns
    ///
    /// The granted [`SubscribeReturnCode`] for each requested topic filter,
    /// in the same order as the original subscribe request.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Disconnected`] when the completion channel is closed
    /// before a SUBACK arrives.
    ///
    /// Returns the underlying error if the connection was lost while waiting.
    pub fn wait(self) -> Result<Vec<SubscribeReturnCode>, Error> {
        match self.rx.recv() {
            Ok(AckResult::SubAck(codes)) => Ok(codes),
            Ok(AckResult::Success) => Ok(vec![]),
            Ok(AckResult::Error(e)) => Err(e),
            Err(_) => Err(Error::Disconnected),
        }
    }

    /// Block until SUBACK is received or the timeout expires
    ///
    /// # Returns
    ///
    /// The granted [`SubscribeReturnCode`] for each requested topic filter,
    /// in the same order as the original subscribe request.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Timeout`] when no SUBACK arrives within `timeout`.
    ///
    /// Returns the underlying error if the connection was lost while waiting.
    pub fn wait_timeout(self, timeout: Duration) -> Result<Vec<SubscribeReturnCode>, Error> {
        match self.rx.recv_timeout(timeout) {
            Ok(AckResult::SubAck(codes)) => Ok(codes),
            Ok(AckResult::Success) => Ok(vec![]),
            Ok(AckResult::Error(e)) => Err(e),
            Err(_) => Err(Error::Timeout),
        }
    }

    /// Non-blocking check whether the SUBACK has arrived
    ///
    /// Returns `None` if no result is available yet.
    pub fn try_recv(&self) -> Option<Result<Vec<SubscribeReturnCode>, Error>> {
        match self.rx.try_recv() {
            Ok(AckResult::SubAck(codes)) => Some(Ok(codes)),
            Ok(AckResult::Success) => Some(Ok(vec![])),
            Ok(AckResult::Error(e)) => Some(Err(e)),
            Err(_) => None,
        }
    }
}