poster 0.3.1

MQTTv5 client library written in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use crate::{
    client::{
        error::{HandleClosed, MaximumPacketSizeExceeded, MqttError, SocketClosed},
        handle::ContextHandle,
        message::*,
        opts::{AuthOpts, ConnectOpts},
        rsp::{AuthRsp, ConnectRsp},
        utils,
    },
    codec::*,
    core::{
        base_types::NonZero,
        properties::ReceiveMaximum,
        utils::{ByteLen, Encode, PacketID, SizedPacket},
    },
    io::{RxPacketStream, TxPacketStream},
    QoS,
};
use bytes::{Bytes, BytesMut};
use core::sync::atomic::{AtomicU16, AtomicU32};
use either::{Either, Left, Right};
use futures::{
    channel::{mpsc, oneshot},
    AsyncRead, AsyncWrite, FutureExt, StreamExt,
};
use std::{collections::VecDeque, sync::Arc, time::SystemTime};

use super::error::{InternalError, QuotaExceeded};

const ERRMSG_HANDLE_DROPPED: &str = "Unable to complete async operation.";

struct Session {
    awaiting_ack: VecDeque<(usize, oneshot::Sender<Result<RxPacket, MqttError>>)>,
    subscriptions: VecDeque<(usize, mpsc::UnboundedSender<RxPacket>)>,
    retrasmit_queue: VecDeque<(usize, Bytes)>,
}

struct Connection {
    disconnection_timestamp: Option<SystemTime>,
    session_expiry_interval: u32,
    remote_receive_maximum: u16,
    remote_max_packet_size: Option<u32>,
    send_quota: u16,
}

/// Client context. Responsible for socket management and direct communication with the broker.
///
pub struct Context<RxStreamT, TxStreamT> {
    rx: Option<RxPacketStream<RxStreamT>>,
    tx: Option<TxPacketStream<TxStreamT>>,

    message_queue: mpsc::UnboundedReceiver<ContextMessage>,

    session: Session,
    connection: Connection,
}

impl<RxStreamT, TxStreamT> Context<RxStreamT, TxStreamT>
where
    RxStreamT: AsyncRead + Unpin,
    TxStreamT: AsyncWrite + Unpin,
{
    fn is_reconnect(connection: &Connection) -> bool {
        connection.disconnection_timestamp.is_some()
    }

    fn session_expired(connection: &Connection) -> bool {
        debug_assert!(Self::is_reconnect(connection));

        if connection.session_expiry_interval == 0 {
            return true;
        }

        if connection.session_expiry_interval == u32::MAX {
            return false;
        }

        let elapsed = connection
            .disconnection_timestamp
            .map(|timestamp| timestamp.elapsed().unwrap())
            .map(|elapsed| elapsed.as_secs())
            .map(|elapsed| {
                if elapsed > u32::MAX as u64 {
                    u32::MAX
                } else {
                    elapsed as u32
                }
            })
            .unwrap();

        connection.session_expiry_interval >= elapsed
    }

    fn reset_session(session: &mut Session) {
        session.awaiting_ack.clear();
        session.subscriptions.clear();
        session.retrasmit_queue.clear();
    }

    fn validate_packet_size(connection: &Connection, packet: &[u8]) -> Result<(), MqttError> {
        if connection.remote_max_packet_size.is_none()
            || packet.len() <= connection.remote_max_packet_size.unwrap() as usize
        {
            Ok(())
        } else {
            Err(MaximumPacketSizeExceeded.into())
        }
    }

    async fn handle_message(
        tx: &mut TxPacketStream<TxStreamT>,
        connection: &mut Connection,
        session: &mut Session,
        msg: ContextMessage,
    ) -> Result<(), MqttError> {
        match msg {
            ContextMessage::FireAndForget(msg) => {
                if let Err(err) = Self::validate_packet_size(connection, msg.packet.as_ref()) {
                    msg.response_channel
                        .send(Err(err))
                        .map_err(|_| InternalError::from(ERRMSG_HANDLE_DROPPED))?;
                    return Ok(());
                }

                tx.write(msg.packet.freeze().as_ref()).await?;
                msg.response_channel
                    .send(Ok(()))
                    .map_err(|_| InternalError::from(ERRMSG_HANDLE_DROPPED))?;
            }
            ContextMessage::AwaitAck(mut msg) => {
                if let Err(err) = Self::validate_packet_size(connection, msg.packet.as_ref()) {
                    msg.response_channel
                        .send(Err(err))
                        .map_err(|_| InternalError::from(ERRMSG_HANDLE_DROPPED))?;
                    return Ok(());
                }

                let packet_id = msg.packet.first().unwrap() >> 4; // Extract packet id, being the four MSB bits

                if packet_id == PublishTx::PACKET_ID {
                    if connection.send_quota == 0 {
                        msg.response_channel
                            .send(Err(QuotaExceeded.into()))
                            .map_err(|_| InternalError::from(ERRMSG_HANDLE_DROPPED))?;
                        return Ok(());
                    }

                    connection.send_quota -= 1;

                    tx.write(msg.packet.as_ref()).await?;

                    let fixed_hdr = msg.packet.get_mut(0).unwrap();
                    *fixed_hdr |= (1 << 3) as u8; // Set DUP flag in the PUBLISH fixed header

                    session
                        .awaiting_ack
                        .push_back((msg.action_id, msg.response_channel));

                    session
                        .retrasmit_queue
                        .push_back((msg.action_id, msg.packet.freeze()));
                } else if packet_id == PubrelTx::PACKET_ID {
                    tx.write(msg.packet.as_ref()).await?;
                    session
                        .awaiting_ack
                        .push_back((msg.action_id, msg.response_channel));

                    session
                        .retrasmit_queue
                        .push_back((msg.action_id, msg.packet.freeze()));
                } else {
                    tx.write(msg.packet.as_ref()).await?;
                    session
                        .awaiting_ack
                        .push_back((msg.action_id, msg.response_channel));
                }
            }
            ContextMessage::Subscribe(msg) => {
                if let Err(err) = Self::validate_packet_size(connection, msg.packet.as_ref()) {
                    msg.response_channel
                        .send(Err(err))
                        .map_err(|_| InternalError::from(ERRMSG_HANDLE_DROPPED))?;
                    return Ok(());
                }

                session
                    .awaiting_ack
                    .push_back((msg.action_id, msg.response_channel));
                session
                    .subscriptions
                    .push_back((msg.subscription_identifier, msg.stream));

                tx.write(msg.packet.freeze().as_ref()).await?;
            }
        }

        Ok(())
    }

    async fn ack<'a, ReasonT>(
        tx: &mut TxPacketStream<TxStreamT>,
        packet_id: NonZero<u16>,
    ) -> Result<(), MqttError>
    where
        AckTx<'a, ReasonT>: Encode + PacketID + FixedHeader,
        ReasonT: Default + Clone + PartialEq + ByteLen,
    {
        let mut builder = AckTxBuilder::default();
        builder.packet_identifier(packet_id);
        builder.reason(ReasonT::default());
        let ack = builder.build().unwrap();

        let mut buf = BytesMut::with_capacity(ack.packet_len());
        ack.encode(&mut buf);

        tx.write(buf.freeze().as_ref()).await?;
        Ok(())
    }

    async fn handle_packet(
        tx: &mut TxPacketStream<TxStreamT>,
        connection: &mut Connection,
        session: &mut Session,
        packet: RxPacket,
    ) -> Result<(), MqttError> {
        match packet {
            RxPacket::Publish(publish) => {
                if let Some(subscription_identifier) =
                    publish
                        .subscription_identifier
                        .map(|subscription_identifier| {
                            NonZero::from(subscription_identifier).get().value() as usize
                        })
                {
                    let qos = publish.qos;
                    let maybe_packet_id = publish.packet_identifier;

                    if let Some((_, subscription)) =
                        utils::linear_search_by_key(&session.subscriptions, subscription_identifier)
                            .map(|pos| &mut session.subscriptions[pos])
                    {
                        // User may drop the receiving stream,
                        // in that case remove it from the active subscriptions map.
                        if (subscription.unbounded_send(RxPacket::Publish(publish))).is_err() {
                            utils::linear_search_by_key(
                                &session.subscriptions,
                                subscription_identifier,
                            )
                            .and_then(|pos| session.subscriptions.remove(pos));
                        }
                    }

                    if let Some(packet_id) = maybe_packet_id {
                        match qos {
                            QoS::AtLeastOnce => Self::ack::<PubackReason>(tx, packet_id).await?,
                            QoS::ExactlyOnce => Self::ack::<PubrecReason>(tx, packet_id).await?,
                            _ => unreachable!("No acknowledgement for QoS==0."),
                        }
                    }
                }
            }
            RxPacket::Disconnect(disconnect) => {
                if disconnect.reason == DisconnectReason::Success {
                    return Ok(()); // Graceful disconnection.
                }

                return Err(disconnect.into());
            }
            RxPacket::Puback(puback) => {
                let rx_packet = RxPacket::Puback(puback);
                let action_id = utils::rx_action_id(&rx_packet);

                if connection.send_quota != connection.remote_receive_maximum {
                    connection.send_quota += 1;
                }

                utils::linear_search_by_key(&session.retrasmit_queue, action_id)
                    .and_then(|pos| session.retrasmit_queue.remove(pos));

                if let Some((_, sender)) =
                    utils::linear_search_by_key(&session.awaiting_ack, action_id)
                        .and_then(|pos| session.awaiting_ack.remove(pos))
                {
                    sender
                        .send(Ok(rx_packet))
                        .map_err(|_| InternalError::from(ERRMSG_HANDLE_DROPPED))?;
                }
            }
            RxPacket::Pubcomp(pubcomp) => {
                let rx_packet = RxPacket::Pubcomp(pubcomp);
                let action_id = utils::rx_action_id(&rx_packet);

                if connection.send_quota != connection.remote_receive_maximum {
                    connection.send_quota += 1;
                }

                utils::linear_search_by_key(&session.retrasmit_queue, action_id)
                    .and_then(|pos| session.retrasmit_queue.remove(pos));

                if let Some((_, sender)) =
                    utils::linear_search_by_key(&session.awaiting_ack, action_id)
                        .and_then(|pos| session.awaiting_ack.remove(pos))
                {
                    sender
                        .send(Ok(rx_packet))
                        .map_err(|_| InternalError::from(ERRMSG_HANDLE_DROPPED))?;
                }
            }
            RxPacket::Pubrel(pubrel) => {
                let packet_id = pubrel.packet_identifier;
                Self::ack::<PubcompReason>(tx, packet_id).await?
            }
            other => {
                let action_id = utils::rx_action_id(&other);

                if let Some((_, sender)) =
                    utils::linear_search_by_key(&session.awaiting_ack, action_id)
                        .and_then(|pos| session.awaiting_ack.remove(pos))
                {
                    sender
                        .send(Ok(other))
                        .map_err(|_| InternalError::from(ERRMSG_HANDLE_DROPPED))?;
                }
            }
        }

        Ok(())
    }

    fn handle_connack(connection: &mut Connection, connack: &ConnackRx) {
        if connack.session_expiry_interval.is_some() {
            connection.session_expiry_interval =
                connack.session_expiry_interval.map(u32::from).unwrap();
        }

        if connack.maximum_packet_size.is_some() {
            connection.remote_max_packet_size = connack
                .maximum_packet_size
                .map(NonZero::from)
                .map(u32::from);
        }

        connection.remote_receive_maximum = u16::from(NonZero::from(connack.receive_maximum));
        connection.send_quota = connection.remote_receive_maximum;
    }

    async fn retransmit(
        tx: &mut TxPacketStream<TxStreamT>,
        connection: &mut Connection,
        session: &mut Session,
    ) -> Result<(), MqttError> {
        connection.disconnection_timestamp = None;

        for (_, packet) in session.retrasmit_queue.iter() {
            tx.write(packet.as_ref()).await?;
        }

        Ok(())
    }

    /// Creates a new [Context] instance, paired with [ContextHandle].
    ///
    pub fn new() -> (Self, ContextHandle) {
        let (sender, receiver) = mpsc::unbounded();

        (
            Self {
                rx: None,
                tx: None,
                message_queue: receiver,

                session: Session {
                    awaiting_ack: VecDeque::new(),
                    subscriptions: VecDeque::new(),
                    retrasmit_queue: VecDeque::new(),
                },
                connection: Connection {
                    disconnection_timestamp: None,
                    session_expiry_interval: 0,
                    remote_receive_maximum: u16::from(NonZero::from(ReceiveMaximum::default())),
                    remote_max_packet_size: None,
                    send_quota: u16::from(NonZero::from(ReceiveMaximum::default())),
                },
            },
            ContextHandle {
                sender,
                packet_id: Arc::new(AtomicU16::from(1)),
                sub_id: Arc::new(AtomicU32::from(1)),
            },
        )
    }

    /// Sets up communication primitives for the context. This is the first method
    /// to call when starting the connection with the broker.
    ///
    /// # Arguments
    /// * `rx` - Read half of the stream, must be [AsyncRead] + [Unpin].
    /// * `tx` - Write half of the stream, must be [AsyncWrite] + [Unpin].
    ///
    /// # Note
    /// Calling any other member function before prior call to [set_up](Context::set_up) will panic.
    ///
    pub fn set_up(&mut self, (rx, tx): (RxStreamT, TxStreamT)) -> &mut Self {
        self.rx = Some(RxPacketStream::from(rx));
        self.tx = Some(TxPacketStream::from(tx));
        self
    }

    /// Performs connection with the broker on the protocol level. Calling this method corresponds to sending the
    /// [Connect](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901033) packet.
    ///
    /// If [authentication_method](ConnectOpts::authentication_method) and [authentication_data](ConnectOpts::authentication_data) are
    /// set in [`opts`](ConnectOpts), the extended authorization is performed, the result of calling this method
    /// is then [AuthRsp]. Otherwise, the return type is [ConnectRsp].
    ///
    /// When the [reason](crate::reason::ConnectReason) in the CONNACK packet is greater or equal 0x80, the
    /// [ConnectError](crate::error::ConnectError) is returned.
    ///
    /// When in extended authorization mode, the authorize method is used for subsequent
    /// authorization requests.
    ///
    /// # Panics
    /// When invoked without prior call to [set_up](Context::set_up).
    ///
    pub async fn connect<'a>(
        &mut self,
        opts: ConnectOpts<'a>,
    ) -> Result<Either<ConnectRsp, AuthRsp>, MqttError> {
        assert!(
            self.rx.is_some() && self.tx.is_some(),
            "Context must be set up before connecting."
        );

        let packet = opts.build()?;
        self.connection.session_expiry_interval =
            packet.session_expiry_interval.map(u32::from).unwrap_or(0);

        let mut buf = BytesMut::with_capacity(packet.packet_len());
        packet.encode(&mut buf);

        let tx = self.tx.as_mut().unwrap();
        let rx = self.rx.as_mut().unwrap();

        tx.write(buf.as_ref()).await?;

        match rx
            .next()
            .await
            .transpose()
            .map_err(MqttError::from)
            .and_then(|maybe_next| maybe_next.ok_or(SocketClosed.into()))?
        {
            RxPacket::Connack(connack) => {
                Self::handle_connack(&mut self.connection, &connack);
                Ok(Left(ConnectRsp::try_from(connack)?))
            }
            RxPacket::Auth(auth) => Ok(Right(AuthRsp::try_from(auth)?)),
            _ => {
                unreachable!("Unexpected packet type.");
            }
        }
    }

    /// Performs extended authorization between the client and the broker. It corresponds to sending the
    /// [Auth](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901217) packet.
    /// User may perform multiple calls of this method, as needed, until the ConnectRsp is returned,
    /// meaning the authorization is successful.
    ///
    /// When the [reason](crate::reason::AuthReason) in the AUTH packet is greater or equal 0x80, the
    /// [AuthError](crate::error::AuthError) is returned.
    ///
    /// # Panics
    /// When invoked without prior call to [set_up](Context::set_up).
    ///
    pub async fn authorize<'a>(
        &mut self,
        opts: AuthOpts<'a>,
    ) -> Result<Either<ConnectRsp, AuthRsp>, MqttError> {
        assert!(
            self.rx.is_some() && self.tx.is_some(),
            "Context must be set up before authorizing."
        );

        let packet = opts.build()?;

        let mut buf = BytesMut::with_capacity(packet.packet_len());
        packet.encode(&mut buf);

        let tx = self.tx.as_mut().unwrap();
        let rx = self.rx.as_mut().unwrap();

        tx.write(buf.as_ref()).await?;

        match rx
            .next()
            .await
            .transpose()
            .map_err(MqttError::from)
            .and_then(|maybe_next| maybe_next.ok_or(SocketClosed.into()))?
        {
            RxPacket::Connack(connack) => {
                Self::handle_connack(&mut self.connection, &connack);
                Ok(Left(ConnectRsp::try_from(connack)?))
            }
            RxPacket::Auth(auth) => Ok(Right(AuthRsp::try_from(auth)?)),
            _ => {
                unreachable!("Unexpected packet type.");
            }
        }
    }

    /// Starts processing MQTT traffic, blocking (on .await) the current task until
    /// graceful disconnection or error. Successful disconnection via [disconnect](ContextHandle::disconnect) method or
    /// receiving a [Disconnect](https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901205)
    /// packet with reason a code equal to 0 (success) is considered a graceful disconnection.
    ///
    /// # Panics
    /// When invoked without prior call to [set_up](Context::set_up).
    ///
    pub async fn run(&mut self) -> Result<(), MqttError>
    where
        RxStreamT: AsyncRead + Unpin,
        TxStreamT: AsyncWrite + Unpin,
    {
        assert!(
            self.rx.is_some() && self.tx.is_some(),
            "Context must be set up before running."
        );

        let rx = self.rx.as_mut().unwrap();
        let tx = self.tx.as_mut().unwrap();
        let message_queue = &mut self.message_queue;
        let session = &mut self.session;
        let connection = &mut self.connection;

        if Self::is_reconnect(connection) {
            if Self::session_expired(connection) {
                Self::reset_session(session);
            }

            Self::retransmit(tx, connection, session).await?;
        }

        let mut pck_fut = rx.next().fuse();
        let mut msg_fut = message_queue.next();

        loop {
            futures::select! {
                maybe_rx_packet = pck_fut => {
                    let rx_packet = maybe_rx_packet.ok_or(SocketClosed)?;
                    Self::handle_packet(tx, connection, session, rx_packet?).await?;
                    pck_fut = rx.next().fuse();
                },
                maybe_msg = msg_fut => {
                    Self::handle_message(tx, connection, session, maybe_msg.ok_or(HandleClosed)?).await?;
                    msg_fut = message_queue.next();
                }
            }
        }
    }
}