symqtt-codec 0.1.0

MQTT 3.1.1/5.0 packet codec — role-neutral, runtime-free
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
//! PUBLISH, PUBACK, PUBREC, PUBREL, and PUBCOMP packet encoding/decoding
//! [MQTT-3.3 – MQTT-3.7]
//!
//! ```text
//! PUBLISH packet format [MQTT-3.3]:
//!
//!   Fixed Header:
//!     Byte 1:
//!       Bit 7-4: Packet Type (3)
//!       Bit 3:   DUP flag
//!       Bit 2-1: QoS level (0, 1, or 2)
//!       Bit 0:   RETAIN flag
//!     Byte 2..N: Remaining Length (variable-length integer)
//!
//!   Variable Header:
//!     Topic Name:        UTF-8 string (2-byte length prefix + content)
//!     Packet Identifier: 2 bytes (present only when QoS > 0)
//!
//!   Payload:
//!     Application message (0 or more bytes, up to remaining length)
//!
//! PUBACK / PUBREC / PUBCOMP packet format [MQTT-3.4, 3.5, 3.7]:
//!
//!   Fixed Header:
//!     Byte 1: type << 4 | 0x00 (flags = 0b0000)
//!     Byte 2: 0x02 (remaining length = 2)
//!
//!   Variable Header:
//!     Packet Identifier: 2 bytes (big-endian)
//!
//! PUBREL packet format [MQTT-3.6]:
//!
//!   Fixed Header:
//!     Byte 1: 0x62 (type=6, flags=0b0010)
//!     Byte 2: 0x02 (remaining length = 2)
//!
//!   Variable Header:
//!     Packet Identifier: 2 bytes (big-endian)
//! ```

use bytes::{Bytes, BytesMut};

use crate::primitives::PACKET_ID_LEN;
use crate::{DecodeError, EncodeError, PacketType, QoS, primitives};

/// PUBLISH packet — delivers an application message [MQTT-3.3]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Publish {
    /// Duplicate delivery flag (must be false for QoS 0)
    pub dup: bool,
    /// Quality of Service level
    pub qos: QoS,
    /// Whether the broker should retain this message
    pub retain: bool,
    /// Topic name the message is published to
    pub topic: String,
    /// Packet identifier (present only for QoS 1 and QoS 2)
    pub pkid: Option<u16>,
    /// Application message payload
    pub payload: Bytes,
}

impl Publish {
    /// Fixed header flags carry dup / qos / retain, the only type whose flags vary [MQTT-3.3.1]
    pub(super) fn flags(&self) -> u8 {
        // Bit 3 = DUP, bits 2-1 = QoS, bit 0 = RETAIN
        let mut flags = (self.qos as u8) << 1;
        if self.dup {
            flags |= 0x08;
        }
        if self.retain {
            flags |= 0x01;
        }
        flags
    }

    pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
        self.validate()?;

        primitives::write_string(&self.topic, buf)?;
        if let Some(pkid) = self.pkid {
            primitives::write_u16(pkid, buf);
        }
        buf.extend_from_slice(&self.payload);

        Ok(())
    }

    pub(super) fn encoded_body_len(&self) -> usize {
        let mut len = primitives::string_encoded_len(self.topic.len());
        if self.pkid.is_some() {
            len += PACKET_ID_LEN;
        }
        len += self.payload.len();
        len
    }

    pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
        // PUBLISH is the one type whose flags are data, so there is no fixed value to check
        let qos = QoS::try_from((header_flags >> 1) & 0x03)?;
        let dup = header_flags & 0x08 != 0;
        let retain = header_flags & 0x01 != 0;

        let topic = primitives::read_string(&mut buf)?;
        // The packet identifier is on the wire only when a QoS > 0 flow needs it [MQTT-3.3.2.2]
        let pkid = match qos {
            QoS::AtMostOnce => None,
            QoS::AtLeastOnce | QoS::ExactlyOnce => Some(primitives::read_u16(&mut buf)?),
        };

        // Whatever is left is the application message, so there is nothing to assert consumed
        Ok(Publish {
            dup,
            qos,
            retain,
            topic,
            pkid,
            payload: buf,
        })
    }

    fn validate(&self) -> Result<(), EncodeError> {
        match self.qos {
            QoS::AtMostOnce => {
                if self.pkid.is_some() {
                    return Err(EncodeError::InvalidState {
                        reason: "QoS 0 PUBLISH must not have packet identifier",
                    });
                }
            }
            QoS::AtLeastOnce | QoS::ExactlyOnce => match self.pkid {
                None => {
                    return Err(EncodeError::InvalidState {
                        reason: "QoS 1/2 PUBLISH must have packet identifier",
                    });
                }
                Some(0) => {
                    return Err(EncodeError::InvalidState {
                        reason: "packet identifier must be non-zero",
                    });
                }
                _ => {}
            },
        }
        Ok(())
    }
}

/// PUBACK packet — acknowledges a QoS 1 PUBLISH [MQTT-3.4]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PubAck {
    /// Packet identifier being acknowledged
    pub pkid: u16,
}

/// PUBREC packet — first acknowledgement in the QoS 2 flow [MQTT-3.5]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PubRec {
    /// Packet identifier being acknowledged
    pub pkid: u16,
}

/// PUBREL packet — second acknowledgement in the QoS 2 flow [MQTT-3.6]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PubRel {
    /// Packet identifier being acknowledged
    pub pkid: u16,
}

/// PUBCOMP packet — final acknowledgement in the QoS 2 flow [MQTT-3.7]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PubComp {
    /// Packet identifier being acknowledged
    pub pkid: u16,
}

/// Generate the codec for acknowledgement packets whose body is a lone packet identifier
///
/// PUBACK, PUBREC, PUBREL, and PUBCOMP differ only in their type nibble and fixed flags,
/// so their bodies are encoded and decoded by identical logic.
macro_rules! impl_pkid_ack {
    ($($name:ident => ($packet_type:ident, $flags:expr, $flags_doc:literal)),* $(,)?) => {
        $(
            impl $name {
                #[doc = $flags_doc]
                const FLAGS: u8 = $flags;

                pub(super) fn flags(&self) -> u8 {
                    Self::FLAGS
                }

                pub(super) fn encoded_body_len(&self) -> usize {
                    PACKET_ID_LEN
                }

                pub(super) fn encode_body(&self, buf: &mut BytesMut) -> Result<(), EncodeError> {
                    primitives::write_u16(self.pkid, buf);
                    Ok(())
                }

                pub(super) fn decode_body(header_flags: u8, mut buf: Bytes) -> Result<Self, DecodeError> {
                    if header_flags != Self::FLAGS {
                        return Err(DecodeError::InvalidFlags {
                            packet_type: PacketType::$packet_type,
                            flags: header_flags,
                        });
                    }

                    let pkid = primitives::read_u16(&mut buf)?;
                    // The body is defined as exactly one packet identifier, so a longer
                    // remaining length means the packet is malformed
                    if !buf.is_empty() {
                        return Err(DecodeError::TrailingBytes { count: buf.len() });
                    }

                    Ok(Self { pkid })
                }
            }
        )*
    };
}

impl_pkid_ack! {
    PubAck => (PubAck, 0b0000, "Fixed header flags are always 0b0000 [MQTT-2.2.2, Table 2.2]"),
    PubRec => (PubRec, 0b0000, "Fixed header flags are always 0b0000 [MQTT-2.2.2, Table 2.2]"),
    PubRel => (PubRel, 0b0010, "Fixed header flags are always 0b0010 [MQTT-3.6.1-1]"),
    PubComp => (PubComp, 0b0000, "Fixed header flags are always 0b0000 [MQTT-2.2.2, Table 2.2]"),
}

#[cfg(test)]
mod tests {
    use bytes::{Bytes, BytesMut};

    use super::*;
    use crate::v3::Packet;
    use crate::{DecodeError, EncodeError, PacketType, QoS};

    fn roundtrip(packet: Packet) -> Packet {
        let mut buf = BytesMut::new();
        packet.encode(&mut buf).unwrap();
        Packet::decode(&mut buf).unwrap().unwrap()
    }

    #[test]
    fn publish_qos0_no_pkid() {
        let pkt = Packet::Publish(Publish {
            dup: false,
            qos: QoS::AtMostOnce,
            retain: false,
            topic: "a/b".to_owned(),
            pkid: None,
            payload: Bytes::from_static(b"hi"),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn publish_qos1() {
        let pkt = Packet::Publish(Publish {
            dup: false,
            qos: QoS::AtLeastOnce,
            retain: false,
            topic: "topic".to_owned(),
            pkid: Some(1),
            payload: Bytes::from_static(b"data"),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn publish_qos2_max_pkid() {
        let pkt = Packet::Publish(Publish {
            dup: false,
            qos: QoS::ExactlyOnce,
            retain: false,
            topic: "t".to_owned(),
            pkid: Some(65535),
            payload: Bytes::from_static(b"x"),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn publish_retain_flag() {
        let pkt = Packet::Publish(Publish {
            dup: false,
            qos: QoS::AtMostOnce,
            retain: true,
            topic: "t".to_owned(),
            pkid: None,
            payload: Bytes::new(),
        });
        let mut buf = BytesMut::new();
        pkt.encode(&mut buf).unwrap();
        // First byte: type=3(0x30) | retain(0x01) = 0x31
        assert_eq!(buf[0] & 0x0F, 0x01);
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn publish_dup_flag_qos1() {
        let pkt = Packet::Publish(Publish {
            dup: true,
            qos: QoS::AtLeastOnce,
            retain: false,
            topic: "t".to_owned(),
            pkid: Some(10),
            payload: Bytes::new(),
        });
        let mut buf = BytesMut::new();
        pkt.encode(&mut buf).unwrap();
        // flags: dup=1(bit3) + qos1(bit1) = 0b1010 = 0x0A
        assert_eq!(buf[0] & 0x0F, 0x0A);
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn publish_empty_payload() {
        let pkt = Packet::Publish(Publish {
            dup: false,
            qos: QoS::AtMostOnce,
            retain: false,
            topic: "t".to_owned(),
            pkid: None,
            payload: Bytes::new(),
        });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn publish_all_flags() {
        let pkt = Packet::Publish(Publish {
            dup: true,
            qos: QoS::AtLeastOnce,
            retain: true,
            topic: "t".to_owned(),
            pkid: Some(42),
            payload: Bytes::from_static(b"payload"),
        });
        let mut buf = BytesMut::new();
        pkt.encode(&mut buf).unwrap();
        // flags: dup(0x08) | qos1(0x02) | retain(0x01) = 0x0B
        assert_eq!(buf[0] & 0x0F, 0x0B);
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn publish_encode_qos0_with_pkid_error() {
        let pkt = Packet::Publish(Publish {
            dup: false,
            qos: QoS::AtMostOnce,
            retain: false,
            topic: "t".to_owned(),
            pkid: Some(1),
            payload: Bytes::new(),
        });
        let mut buf = BytesMut::new();
        assert_eq!(
            pkt.encode(&mut buf),
            Err(EncodeError::InvalidState {
                reason: "QoS 0 PUBLISH must not have packet identifier"
            })
        );
    }

    #[test]
    fn publish_encode_qos1_no_pkid_error() {
        let pkt = Packet::Publish(Publish {
            dup: false,
            qos: QoS::AtLeastOnce,
            retain: false,
            topic: "t".to_owned(),
            pkid: None,
            payload: Bytes::new(),
        });
        let mut buf = BytesMut::new();
        assert_eq!(
            pkt.encode(&mut buf),
            Err(EncodeError::InvalidState {
                reason: "QoS 1/2 PUBLISH must have packet identifier"
            })
        );
    }

    #[test]
    fn publish_encode_qos1_pkid_zero_error() {
        let pkt = Packet::Publish(Publish {
            dup: false,
            qos: QoS::AtLeastOnce,
            retain: false,
            topic: "t".to_owned(),
            pkid: Some(0),
            payload: Bytes::new(),
        });
        let mut buf = BytesMut::new();
        assert_eq!(
            pkt.encode(&mut buf),
            Err(EncodeError::InvalidState {
                reason: "packet identifier must be non-zero"
            })
        );
    }

    #[test]
    fn publish_decode_invalid_qos3() {
        // flags with QoS=3 → bits 2-1 = 0b11 → flags byte = 0b0110 = 0x06
        let buf = Bytes::from_static(&[0x00, 0x01, b't']); // minimal topic "t"
        assert_eq!(
            Publish::decode_body(0x06, buf),
            Err(DecodeError::ProtocolError {
                reason: "invalid QoS value"
            })
        );
    }

    #[test]
    fn publish_encode_error_rollback() {
        let pkt = Packet::Publish(Publish {
            dup: false,
            qos: QoS::AtMostOnce,
            retain: false,
            topic: "t".to_owned(),
            pkid: Some(1), // invalid for QoS 0
            payload: Bytes::new(),
        });
        let mut buf = BytesMut::new();
        buf.extend_from_slice(b"pre");
        let _ = pkt.encode(&mut buf);
        // Buffer should be rolled back to original
        assert_eq!(&buf[..], b"pre");
    }

    #[test]
    fn puback_roundtrip() {
        let pkt = Packet::PubAck(PubAck { pkid: 1 });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn puback_max_pkid() {
        let pkt = Packet::PubAck(PubAck { pkid: 65535 });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn puback_invalid_flags() {
        let buf = Bytes::from_static(&[0x00, 0x01]);
        assert_eq!(
            PubAck::decode_body(0x01, buf),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::PubAck,
                flags: 0x01,
            })
        );
    }

    #[test]
    fn puback_trailing_bytes() {
        let buf = Bytes::from_static(&[0x00, 0x01, 0xFF]);
        assert_eq!(
            PubAck::decode_body(0x00, buf),
            Err(DecodeError::TrailingBytes { count: 1 })
        );
    }

    #[test]
    fn pubrec_roundtrip() {
        let pkt = Packet::PubRec(PubRec { pkid: 100 });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn pubrec_invalid_flags() {
        let buf = Bytes::from_static(&[0x00, 0x01]);
        assert_eq!(
            PubRec::decode_body(0x01, buf),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::PubRec,
                flags: 0x01,
            })
        );
    }

    #[test]
    fn pubrel_roundtrip() {
        let pkt = Packet::PubRel(PubRel { pkid: 200 });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn pubrel_flags_are_0010() {
        let mut buf = BytesMut::new();
        Packet::PubRel(PubRel { pkid: 1 }).encode(&mut buf).unwrap();
        // byte 0: type=6(0x60) | flags=0x02 = 0x62
        assert_eq!(buf[0], 0x62);
    }

    #[test]
    fn pubrel_wrong_flags() {
        let buf = Bytes::from_static(&[0x00, 0x01]);
        assert_eq!(
            PubRel::decode_body(0x00, buf),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::PubRel,
                flags: 0x00,
            })
        );
    }

    #[test]
    fn pubcomp_roundtrip() {
        let pkt = Packet::PubComp(PubComp { pkid: 42 });
        assert_eq!(roundtrip(pkt.clone()), pkt);
    }

    #[test]
    fn pubcomp_invalid_flags() {
        let buf = Bytes::from_static(&[0x00, 0x01]);
        assert_eq!(
            PubComp::decode_body(0x01, buf),
            Err(DecodeError::InvalidFlags {
                packet_type: PacketType::PubComp,
                flags: 0x01,
            })
        );
    }

    #[test]
    fn pubcomp_trailing_bytes() {
        let buf = Bytes::from_static(&[0x00, 0x2A, 0x00]);
        assert_eq!(
            PubComp::decode_body(0x00, buf),
            Err(DecodeError::TrailingBytes { count: 1 })
        );
    }

    #[test]
    fn puback_empty_body_error() {
        let buf = Bytes::new();
        assert!(matches!(
            PubAck::decode_body(0x00, buf),
            Err(DecodeError::InsufficientBytes { .. })
        ));
    }
}