mqrstt 0.4.2

Pure rust MQTTv5 client implementation Smol and Tokio
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
mod reason_code;
pub use reason_code::PubRelReasonCode;

mod properties;
pub use properties::PubRelProperties;

use bytes::BufMut;
use tokio::io::AsyncReadExt;

use super::{
    VariableInteger,
    error::{DeserializeError, ReadError},
    mqtt_trait::{MqttAsyncRead, MqttRead, MqttWrite, PacketAsyncRead, PacketRead, PacketWrite, WireLength},
};

/// The [`PubRel`] (Publish Release) packet acknowledges the reception of a [`crate::packets::PubRec`] Packet.
///
/// This user does not need to send this message, it is handled internally by the client.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct PubRel {
    pub packet_identifier: u16,
    pub reason_code: PubRelReasonCode,
    pub properties: PubRelProperties,
}

impl PubRel {
    pub fn new(packet_identifier: u16) -> Self {
        Self {
            packet_identifier,
            reason_code: PubRelReasonCode::Success,
            properties: PubRelProperties::default(),
        }
    }
}

impl PacketRead for PubRel {
    fn read(_: u8, remaining_length: usize, mut buf: bytes::Bytes) -> Result<Self, DeserializeError> {
        // reason code and properties are optional if reasoncode is success and properties empty.
        if remaining_length == 2 {
            Ok(Self {
                packet_identifier: u16::read(&mut buf)?,
                reason_code: PubRelReasonCode::Success,
                properties: PubRelProperties::default(),
            })
        } else if remaining_length == 3 {
            Ok(Self {
                packet_identifier: u16::read(&mut buf)?,
                reason_code: PubRelReasonCode::read(&mut buf)?,
                properties: PubRelProperties::default(),
            })
        } else {
            Ok(Self {
                packet_identifier: u16::read(&mut buf)?,
                reason_code: PubRelReasonCode::read(&mut buf)?,
                properties: PubRelProperties::read(&mut buf)?,
            })
        }
    }
}

impl<S> PacketAsyncRead<S> for PubRel
where
    S: tokio::io::AsyncRead + Unpin,
{
    async fn async_read(_: u8, remaining_length: usize, stream: &mut S) -> Result<(Self, usize), ReadError> {
        let mut total_read_bytes = 0;
        let packet_identifier = stream.read_u16().await?;
        total_read_bytes += 2;
        let res = if remaining_length == 2 {
            Self {
                packet_identifier,
                reason_code: PubRelReasonCode::Success,
                properties: PubRelProperties::default(),
            }
        } else {
            let (reason_code, read_bytes) = PubRelReasonCode::async_read(stream).await?;
            total_read_bytes += read_bytes;
            if remaining_length == 3 {
                Self {
                    packet_identifier,
                    reason_code,
                    properties: PubRelProperties::default(),
                }
            } else {
                let (properties, read_bytes) = PubRelProperties::async_read(stream).await?;
                total_read_bytes += read_bytes;
                Self {
                    packet_identifier,
                    reason_code,
                    properties,
                }
            }
        };
        Ok((res, total_read_bytes))
    }
}

impl PacketWrite for PubRel {
    fn write(&self, buf: &mut bytes::BytesMut) -> Result<(), super::error::SerializeError> {
        buf.put_u16(self.packet_identifier);

        if self.reason_code == PubRelReasonCode::Success && self.properties.reason_string.is_none() && self.properties.user_properties.is_empty() {
            // Nothing here
        } else if self.properties.reason_string.is_none() && self.properties.user_properties.is_empty() {
            self.reason_code.write(buf)?;
        } else {
            self.reason_code.write(buf)?;
            self.properties.write(buf)?;
        }
        Ok(())
    }
}
impl<S> crate::packets::mqtt_trait::PacketAsyncWrite<S> for PubRel
where
    S: tokio::io::AsyncWrite + Unpin,
{
    fn async_write(&self, stream: &mut S) -> impl std::future::Future<Output = Result<usize, crate::packets::error::WriteError>> {
        use crate::packets::mqtt_trait::MqttAsyncWrite;
        async move {
            let mut total_written_bytes = 2;
            self.packet_identifier.async_write(stream).await?;

            if self.reason_code == PubRelReasonCode::Success && self.properties.reason_string.is_none() && self.properties.user_properties.is_empty() {
                return Ok(total_written_bytes);
            } else if self.properties.reason_string.is_none() && self.properties.user_properties.is_empty() {
                total_written_bytes += self.reason_code.async_write(stream).await?;
            } else {
                total_written_bytes += self.reason_code.async_write(stream).await?;
                total_written_bytes += self.properties.async_write(stream).await?;
            }
            Ok(total_written_bytes)
        }
    }
}

impl WireLength for PubRel {
    fn wire_len(&self) -> usize {
        if self.reason_code == PubRelReasonCode::Success && self.properties.reason_string.is_none() && self.properties.user_properties.is_empty() {
            2
        } else if self.properties.reason_string.is_none() && self.properties.user_properties.is_empty() {
            3
        } else {
            let prop_wire_len = self.properties.wire_len();
            2 + 1 + prop_wire_len.variable_integer_len() + prop_wire_len
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::packets::{
        PropertyType, PubRelReasonCode, VariableInteger,
        mqtt_trait::{MqttAsyncRead, MqttRead, MqttWrite, PacketAsyncRead, PacketRead, PacketWrite, WireLength},
        pubrel::{PubRel, PubRelProperties},
    };
    use bytes::{BufMut, Bytes, BytesMut};

    #[test]
    fn test_wire_len() {
        let mut pubrel = PubRel {
            packet_identifier: 12,
            reason_code: PubRelReasonCode::Success,
            properties: PubRelProperties::default(),
        };

        let mut buf = BytesMut::new();

        pubrel.write(&mut buf).unwrap();

        assert_eq!(2, pubrel.wire_len());
        assert_eq!(2, buf.len());

        pubrel.reason_code = PubRelReasonCode::PacketIdentifierNotFound;
        buf.clear();
        pubrel.write(&mut buf).unwrap();

        assert_eq!(3, pubrel.wire_len());
        assert_eq!(3, buf.len());
    }

    #[test]
    fn test_wire_len2() {
        let mut buf = BytesMut::new();

        let prop = PubRelProperties {
            reason_string: Some("reason string, test 1-2-3.".into()), // 26 + 1 + 2
            user_properties: vec![
                ("This is the key".into(), "This is the value".into()), // 32 + 1 + 2 + 2
                ("Another thingy".into(), "The thingy".into()),         // 24 + 1 + 2 + 2
            ],
        };

        let len = prop.wire_len();
        // determine length of variable integer
        let len_of_wire_len = len.write_variable_integer(&mut buf).unwrap();
        // clear buffer before writing actual properties
        buf.clear();
        prop.write(&mut buf).unwrap();

        assert_eq!(len + len_of_wire_len, buf.len());
    }

    #[test]
    fn test_read_short() {
        let mut expected_pubrel = PubRel {
            packet_identifier: 12,
            reason_code: PubRelReasonCode::Success,
            properties: PubRelProperties::default(),
        };

        let mut buf = BytesMut::new();

        expected_pubrel.write(&mut buf).unwrap();

        assert_eq!(2, buf.len());

        let pubrel = PubRel::read(0, 2, buf.into()).unwrap();

        assert_eq!(expected_pubrel, pubrel);

        let mut buf = BytesMut::new();
        expected_pubrel.reason_code = PubRelReasonCode::PacketIdentifierNotFound;
        expected_pubrel.write(&mut buf).unwrap();

        assert_eq!(3, buf.len());

        let pubrel = PubRel::read(0, 3, buf.into()).unwrap();
        assert_eq!(expected_pubrel, pubrel);
    }

    #[tokio::test]
    async fn test_async_read_short() {
        let mut expected_pubrel = PubRel {
            packet_identifier: 12,
            reason_code: PubRelReasonCode::Success,
            properties: PubRelProperties::default(),
        };

        let mut buf = BytesMut::new();

        expected_pubrel.write(&mut buf).unwrap();

        assert_eq!(2, buf.len());
        let mut stream: &[u8] = &*buf;

        let (pubrel, read_bytes) = PubRel::async_read(0, 2, &mut stream).await.unwrap();

        assert_eq!(expected_pubrel, pubrel);
        assert_eq!(read_bytes, 2);

        let mut buf = BytesMut::new();
        expected_pubrel.reason_code = PubRelReasonCode::PacketIdentifierNotFound;
        expected_pubrel.write(&mut buf).unwrap();

        assert_eq!(3, buf.len());
        let mut stream: &[u8] = &*buf;

        let (pubrel, read_bytes) = PubRel::async_read(0, 3, &mut stream).await.unwrap();
        assert_eq!(read_bytes, 3);
        assert_eq!(expected_pubrel, pubrel);
    }

    #[test]
    fn test_read_simple_pub_rel() {
        let stream = &[
            0x00, 0x0C, // Packet identifier = 12
            0x00, // Reason code success
            0x00, // no properties
        ];
        let buf = Bytes::from(&stream[..]);
        let p_ack = PubRel::read(0, 4, buf).unwrap();

        let expected = PubRel {
            packet_identifier: 12,
            reason_code: PubRelReasonCode::Success,
            properties: PubRelProperties::default(),
        };

        assert_eq!(expected, p_ack);
    }
    #[tokio::test]
    async fn test_async_read_simple_pub_rel() {
        let stream = &[
            0x00, 0x0C, // Packet identifier = 12
            0x00, // Reason code success
            0x00, // no properties
        ];

        let mut stream = stream.as_ref();

        let (p_ack, read_bytes) = PubRel::async_read(0, 4, &mut stream).await.unwrap();

        let expected = PubRel {
            packet_identifier: 12,
            reason_code: PubRelReasonCode::Success,
            properties: PubRelProperties::default(),
        };

        assert_eq!(expected, p_ack);
        assert_eq!(read_bytes, 4);
    }

    #[test]
    fn test_read_write_pubrel_with_properties() {
        let mut buf = BytesMut::new();

        buf.put_u16(65_535u16);
        buf.put_u8(0x92);

        let mut properties = BytesMut::new();
        PropertyType::ReasonString.write(&mut properties).unwrap();
        "reason string, test 1-2-3.".write(&mut properties).unwrap();
        PropertyType::UserProperty.write(&mut properties).unwrap();
        "This is the key".write(&mut properties).unwrap();
        "This is the value".write(&mut properties).unwrap();
        PropertyType::UserProperty.write(&mut properties).unwrap();
        "Another thingy".write(&mut properties).unwrap();
        "The thingy".write(&mut properties).unwrap();

        properties.len().write_variable_integer(&mut buf).unwrap();

        buf.extend(properties);

        // flags can be 0 because not used.
        // remaining_length must be at least 4
        let p_ack = PubRel::read(0, buf.len(), buf.clone().into()).unwrap();

        let mut result = BytesMut::new();
        p_ack.write(&mut result).unwrap();

        assert_eq!(buf.to_vec(), result.to_vec());
    }

    #[tokio::test]
    async fn test_async_read_write_pubrel_with_properties() {
        let mut buf = BytesMut::new();

        buf.put_u16(65_535u16);
        buf.put_u8(0x92);

        let mut properties = BytesMut::new();
        PropertyType::ReasonString.write(&mut properties).unwrap();
        "reason string, test 1-2-3.".write(&mut properties).unwrap();
        PropertyType::UserProperty.write(&mut properties).unwrap();
        "This is the key".write(&mut properties).unwrap();
        "This is the value".write(&mut properties).unwrap();
        PropertyType::UserProperty.write(&mut properties).unwrap();
        "Another thingy".write(&mut properties).unwrap();
        "The thingy".write(&mut properties).unwrap();

        properties.len().write_variable_integer(&mut buf).unwrap();

        buf.extend(properties);

        let mut stream = &*buf;
        // flags can be 0 because not used.
        // remaining_length must be at least 4
        let (p_ack, _) = PubRel::async_read(0, buf.len(), &mut stream).await.unwrap();

        let mut result = BytesMut::new();
        p_ack.write(&mut result).unwrap();

        assert_eq!(buf.to_vec(), result.to_vec());
    }

    #[test]
    fn test_properties() {
        let mut properties_data = BytesMut::new();
        PropertyType::ReasonString.write(&mut properties_data).unwrap();
        "reason string, test 1-2-3.".write(&mut properties_data).unwrap();
        PropertyType::UserProperty.write(&mut properties_data).unwrap();
        "This is the key".write(&mut properties_data).unwrap();
        "This is the value".write(&mut properties_data).unwrap();
        PropertyType::UserProperty.write(&mut properties_data).unwrap();
        "Another thingy".write(&mut properties_data).unwrap();
        "The thingy".write(&mut properties_data).unwrap();

        let mut buf = BytesMut::new();
        properties_data.len().write_variable_integer(&mut buf).unwrap();
        buf.extend(properties_data);

        let properties = PubRelProperties::read(&mut buf.clone().into()).unwrap();
        let mut result = BytesMut::new();
        properties.write(&mut result).unwrap();

        assert_eq!(buf.to_vec(), result.to_vec());
    }

    #[tokio::test]
    async fn test_async_read_properties() {
        let mut properties_data = BytesMut::new();
        PropertyType::ReasonString.write(&mut properties_data).unwrap();
        "reason string, test 1-2-3.".write(&mut properties_data).unwrap();
        PropertyType::UserProperty.write(&mut properties_data).unwrap();
        "This is the key".write(&mut properties_data).unwrap();
        "This is the value".write(&mut properties_data).unwrap();
        PropertyType::UserProperty.write(&mut properties_data).unwrap();
        "Another thingy".write(&mut properties_data).unwrap();
        "The thingy".write(&mut properties_data).unwrap();

        let mut buf = BytesMut::new();
        properties_data.len().write_variable_integer(&mut buf).unwrap();
        buf.extend(properties_data);

        let (properties, read_bytes) = PubRelProperties::async_read(&mut &*buf).await.unwrap();
        let mut result = BytesMut::new();
        properties.write(&mut result).unwrap();

        assert_eq!(buf.to_vec(), result.to_vec());
        assert_eq!(buf.len(), read_bytes);
    }

    #[test]
    fn no_reason_code_or_props() {
        let mut buf = BytesMut::new();

        buf.put_u16(65_535u16);
        let p_ack = PubRel::read(0, buf.len(), buf.clone().into()).unwrap();

        let mut result = BytesMut::new();
        p_ack.write(&mut result).unwrap();

        let expected = PubRel {
            packet_identifier: 65535,
            reason_code: PubRelReasonCode::Success,
            properties: PubRelProperties::default(),
        };
        let mut result = BytesMut::new();
        expected.write(&mut result).unwrap();

        assert_eq!(expected, p_ack);
        assert_eq!(buf.to_vec(), result.to_vec());
    }
}