-
Notifications
You must be signed in to change notification settings - Fork 227
/
mod.rs
754 lines (663 loc) · 22.2 KB
/
mod.rs
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
#![allow(dead_code, unused)]
pub mod v4;
pub mod v5;
#[cfg(feature = "websockets")]
pub mod ws;
use std::{io, str::Utf8Error, string::FromUtf8Error};
/// This module is the place where all the protocol specifics gets abstracted
/// out and creates a structures which are common across protocols. Since,
/// MQTT is the core protocol that this broker supports, a lot of structs closely
/// map to what MQTT specifies in its protocol
use bytes::{Buf, BufMut, Bytes, BytesMut};
use crate::Notification;
// TODO: Handle the cases when there are no properties using Inner struct, so
// handling of properties can be made simplier internally
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Packet {
Connect(
Connect,
Option<ConnectProperties>,
Option<LastWill>,
Option<LastWillProperties>,
Option<Login>,
),
ConnAck(ConnAck, Option<ConnAckProperties>),
Publish(Publish, Option<PublishProperties>),
PubAck(PubAck, Option<PubAckProperties>),
PingReq(PingReq),
PingResp(PingResp),
Subscribe(Subscribe, Option<SubscribeProperties>),
SubAck(SubAck, Option<SubAckProperties>),
PubRec(PubRec, Option<PubRecProperties>),
PubRel(PubRel, Option<PubRelProperties>),
PubComp(PubComp, Option<PubCompProperties>),
Unsubscribe(Unsubscribe, Option<UnsubscribeProperties>),
UnsubAck(UnsubAck, Option<UnsubAckProperties>),
Disconnect(Disconnect, Option<DisconnectProperties>),
}
//--------------------------- Connect packet -------------------------------
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PingReq;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PingResp;
/// Connection packet initiated by the client
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Connect {
/// Mqtt keep alive time
pub keep_alive: u16,
/// Client Id
pub client_id: String,
/// Clean session. Asks the broker to clear previous state
pub clean_session: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectProperties {
/// Expiry interval property after loosing connection
pub session_expiry_interval: Option<u32>,
/// Maximum simultaneous packets
pub receive_maximum: Option<u16>,
/// Maximum packet size
pub max_packet_size: Option<u32>,
/// Maximum mapping integer for a topic
pub topic_alias_max: Option<u16>,
pub request_response_info: Option<u8>,
pub request_problem_info: Option<u8>,
/// List of user properties
pub user_properties: Vec<(String, String)>,
/// Method of authentication
pub authentication_method: Option<String>,
/// Authentication data
pub authentication_data: Option<Bytes>,
}
/// LastWill that broker forwards on behalf of the client
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LastWill {
pub topic: Bytes,
pub message: Bytes,
pub qos: QoS,
pub retain: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LastWillProperties {
pub delay_interval: Option<u32>,
pub payload_format_indicator: Option<u8>,
pub message_expiry_interval: Option<u32>,
pub content_type: Option<String>,
pub response_topic: Option<String>,
pub correlation_data: Option<Bytes>,
pub user_properties: Vec<(String, String)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Login {
pub username: String,
pub password: String,
}
//--------------------------- ConnectAck packet -------------------------------
/// Return code in connack
// This contains return codes for both MQTT v311 and v5
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectReturnCode {
Success,
RefusedProtocolVersion,
BadClientId,
ServiceUnavailable,
UnspecifiedError,
MalformedPacket,
ProtocolError,
ImplementationSpecificError,
UnsupportedProtocolVersion,
ClientIdentifierNotValid,
BadUserNamePassword,
NotAuthorized,
ServerUnavailable,
ServerBusy,
Banned,
BadAuthenticationMethod,
TopicNameInvalid,
PacketTooLarge,
QuotaExceeded,
PayloadFormatInvalid,
RetainNotSupported,
QoSNotSupported,
UseAnotherServer,
ServerMoved,
ConnectionRateExceeded,
}
/// Acknowledgement to connect packet
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnAck {
pub session_present: bool,
pub code: ConnectReturnCode,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnAckProperties {
pub session_expiry_interval: Option<u32>,
pub receive_max: Option<u16>,
pub max_qos: Option<u8>,
pub retain_available: Option<u8>,
pub max_packet_size: Option<u32>,
pub assigned_client_identifier: Option<String>,
pub topic_alias_max: Option<u16>,
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
pub wildcard_subscription_available: Option<u8>,
pub subscription_identifiers_available: Option<u8>,
pub shared_subscription_available: Option<u8>,
pub server_keep_alive: Option<u16>,
pub response_information: Option<String>,
pub server_reference: Option<String>,
pub authentication_method: Option<String>,
pub authentication_data: Option<Bytes>,
}
//--------------------------- Publish packet -------------------------------
/// Publish packet
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Publish {
pub(crate) dup: bool,
pub(crate) qos: QoS,
pub(crate) pkid: u16,
pub retain: bool,
pub topic: Bytes,
pub payload: Bytes,
}
impl Publish {
// Constructor for publish. Used in local links as local links shouldn't
// send qos 1 or 2 packets
pub fn new<T: Into<Bytes>>(topic: T, payload: T, retain: bool) -> Publish {
Publish {
dup: false,
qos: QoS::AtMostOnce,
pkid: 0,
retain,
topic: topic.into(),
payload: payload.into(),
}
}
pub fn is_empty(&self) -> bool {
false
}
/// Approximate length for meter
pub fn len(&self) -> usize {
let len = 2 + self.topic.len() + self.payload.len();
match self.qos == QoS::AtMostOnce {
true => len,
false => len + 2,
}
}
/// Serialization which is independent of MQTT
pub fn serialize(&self) -> Bytes {
let mut o = BytesMut::with_capacity(self.len() + 5);
let dup = self.dup as u8;
let qos = self.qos as u8;
let retain = self.retain as u8;
o.put_u8(0b0011_0000 | retain | qos << 1 | dup << 3);
o.put_u16(self.pkid);
o.put_u16(self.topic.len() as u16);
o.extend_from_slice(&self.topic[..]);
// TODO: Change segments to take Buf to prevent this copying
o.extend_from_slice(&self.payload[..]);
o.freeze()
}
/// Serialization which is independent of MQTT
pub fn deserialize(mut o: Bytes) -> Publish {
let header = o.get_u8();
let qos_num = (header & 0b0110) >> 1;
let qos = qos(qos_num).unwrap_or(QoS::AtMostOnce);
let dup = (header & 0b1000) != 0;
let retain = (header & 0b0001) != 0;
let pkid = o.get_u16();
let topic_len = o.get_u16();
let topic = o.split_to(topic_len as usize);
let payload = o;
Publish {
dup,
qos,
retain,
topic,
pkid,
payload,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PublishProperties {
pub payload_format_indicator: Option<u8>,
pub message_expiry_interval: Option<u32>,
pub topic_alias: Option<u16>,
pub response_topic: Option<String>,
pub correlation_data: Option<Bytes>,
pub user_properties: Vec<(String, String)>,
pub subscription_identifiers: Vec<usize>,
pub content_type: Option<String>,
}
//--------------------------- PublishAck packet -------------------------------
/// Return code in puback
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PubAckReason {
Success,
NoMatchingSubscribers,
UnspecifiedError,
ImplementationSpecificError,
NotAuthorized,
TopicNameInvalid,
PacketIdentifierInUse,
QuotaExceeded,
PayloadFormatInvalid,
}
/// Acknowledgement to QoS1 publish
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PubAck {
pub pkid: u16,
pub reason: PubAckReason,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PubAckProperties {
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
}
//--------------------------- Subscribe packet -------------------------------
/// Subscription packet
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Subscribe {
pub pkid: u16,
pub filters: Vec<Filter>,
}
/// Subscription filter
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Filter {
pub path: String,
pub qos: QoS,
pub nolocal: bool,
pub preserve_retain: bool,
pub retain_forward_rule: RetainForwardRule,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RetainForwardRule {
OnEverySubscribe,
OnNewSubscribe,
Never,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubscribeProperties {
pub id: Option<usize>,
pub user_properties: Vec<(String, String)>,
}
//--------------------------- SubscribeAck packet -------------------------------
/// Acknowledgement to subscribe
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubAck {
pub pkid: u16,
pub return_codes: Vec<SubscribeReasonCode>,
}
impl SubAck {
pub fn is_empty(&self) -> bool {
false
}
pub fn len(&self) -> usize {
2 + self.return_codes.len()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubscribeReasonCode {
QoS0,
QoS1,
QoS2,
Success(QoS),
Failure,
Unspecified,
ImplementationSpecific,
NotAuthorized,
TopicFilterInvalid,
PkidInUse,
QuotaExceeded,
SharedSubscriptionsNotSupported,
SubscriptionIdNotSupported,
WildcardSubscriptionsNotSupported,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SubAckProperties {
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
}
//--------------------------- Unsubscribe packet -------------------------------
/// Unsubscribe packet
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unsubscribe {
pub pkid: u16,
pub filters: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsubscribeProperties {
pub user_properties: Vec<(String, String)>,
}
//--------------------------- UnsubscribeAck packet -------------------------------
/// Acknowledgement to unsubscribe
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsubAck {
pub pkid: u16,
pub reasons: Vec<UnsubAckReason>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum UnsubAckReason {
Success,
NoSubscriptionExisted,
UnspecifiedError,
ImplementationSpecificError,
NotAuthorized,
TopicFilterInvalid,
PacketIdentifierInUse,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsubAckProperties {
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
}
//--------------------------- Ping packet -------------------------------
struct Ping;
struct PingResponse;
//------------------------------------------------------------------------
//--------------------------- PubRec packet -------------------------------
/// Return code in connack
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PubRecReason {
Success,
NoMatchingSubscribers,
UnspecifiedError,
ImplementationSpecificError,
NotAuthorized,
TopicNameInvalid,
PacketIdentifierInUse,
QuotaExceeded,
PayloadFormatInvalid,
}
/// Acknowledgement to QoS1 publish
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PubRec {
pub pkid: u16,
pub reason: PubRecReason,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PubRecProperties {
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
}
//------------------------------------------------------------------------
//--------------------------- PubComp packet -------------------------------
/// Return code in connack
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PubCompReason {
Success,
PacketIdentifierNotFound,
}
/// QoS2 Assured publish complete, in response to PUBREL packet
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PubComp {
pub pkid: u16,
pub reason: PubCompReason,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PubCompProperties {
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
}
//------------------------------------------------------------------------
//--------------------------- PubRel packet -------------------------------
/// Return code in connack
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum PubRelReason {
Success,
PacketIdentifierNotFound,
}
/// QoS2 Publish release, in response to PUBREC packet
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PubRel {
pub pkid: u16,
pub reason: PubRelReason,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PubRelProperties {
pub reason_string: Option<String>,
pub user_properties: Vec<(String, String)>,
}
//------------------------------------------------------------------------
//--------------------------- Disconnect packet -------------------------------
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Disconnect {
/// Disconnect Reason Code
pub reason_code: DisconnectReasonCode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum DisconnectReasonCode {
/// Close the connection normally. Do not send the Will Message.
NormalDisconnection,
/// The Client wishes to disconnect but requires that the Server also publishes its Will Message.
DisconnectWithWillMessage,
/// The Connection is closed but the sender either does not wish to reveal the reason, or none of the other Reason Codes apply.
UnspecifiedError,
/// The received packet does not conform to this specification.
MalformedPacket,
/// An unexpected or out of order packet was received.
ProtocolError,
/// The packet received is valid but cannot be processed by this implementation.
ImplementationSpecificError,
/// The request is not authorized.
NotAuthorized,
/// The Server is busy and cannot continue processing requests from this Client.
ServerBusy,
/// The Server is shutting down.
ServerShuttingDown,
/// The Connection is closed because no packet has been received for 1.5 times the Keepalive time.
KeepAliveTimeout,
/// Another Connection using the same ClientID has connected causing this Connection to be closed.
SessionTakenOver,
/// The Topic Filter is correctly formed, but is not accepted by this Sever.
TopicFilterInvalid,
/// The Topic Name is correctly formed, but is not accepted by this Client or Server.
TopicNameInvalid,
/// The Client or Server has received more than Receive Maximum publication for which it has not sent PUBACK or PUBCOMP.
ReceiveMaximumExceeded,
/// The Client or Server has received a PUBLISH packet containing a Topic Alias which is greater than the Maximum Topic Alias it sent in the CONNECT or CONNACK packet.
TopicAliasInvalid,
/// The packet size is greater than Maximum Packet Size for this Client or Server.
PacketTooLarge,
/// The received data rate is too high.
MessageRateTooHigh,
/// An implementation or administrative imposed limit has been exceeded.
QuotaExceeded,
/// The Connection is closed due to an administrative action.
AdministrativeAction,
/// The payload format does not match the one specified by the Payload Format Indicator.
PayloadFormatInvalid,
/// The Server has does not support retained messages.
RetainNotSupported,
/// The Client specified a QoS greater than the QoS specified in a Maximum QoS in the CONNACK.
QoSNotSupported,
/// The Client should temporarily change its Server.
UseAnotherServer,
/// The Server is moved and the Client should permanently change its server location.
ServerMoved,
/// The Server does not support Shared Subscriptions.
SharedSubscriptionNotSupported,
/// This connection is closed because the connection rate is too high.
ConnectionRateExceeded,
/// The maximum connection time authorized for this connection has been exceeded.
MaximumConnectTime,
/// The Server does not support Subscription Identifiers; the subscription is not accepted.
SubscriptionIdentifiersNotSupported,
/// The Server does not support Wildcard subscription; the subscription is not accepted.
WildcardSubscriptionsNotSupported,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DisconnectProperties {
/// Session Expiry Interval in seconds
pub session_expiry_interval: Option<u32>,
/// Human readable reason for the disconnect
pub reason_string: Option<String>,
/// List of user properties
pub user_properties: Vec<(String, String)>,
/// String which can be used by the Client to identify another Server to use.
pub server_reference: Option<String>,
}
//------------------------------------------------------------------------
/// Quality of service
#[repr(u8)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd)]
#[allow(clippy::enum_variant_names)]
pub enum QoS {
#[default]
AtMostOnce = 0,
AtLeastOnce = 1,
ExactlyOnce = 2,
}
/// Maps a number to QoS
pub fn qos(num: u8) -> Option<QoS> {
match num {
0 => Some(QoS::AtMostOnce),
1 => Some(QoS::AtLeastOnce),
2 => Some(QoS::ExactlyOnce),
qos => None,
}
}
/// Checks if a topic or topic filter has wildcards
pub fn has_wildcards(s: &str) -> bool {
s.contains('+') || s.contains('#')
}
/// Checks if a topic is valid
pub fn valid_topic(topic: &str) -> bool {
if topic.contains('+') {
return false;
}
if topic.contains('#') {
return false;
}
true
}
/// Checks if the filter is valid
///
/// <https://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718106>
pub fn valid_filter(filter: &str) -> bool {
if filter.is_empty() {
return false;
}
let hirerarchy = filter.split('/').collect::<Vec<&str>>();
if let Some((last, remaining)) = hirerarchy.split_last() {
for entry in remaining.iter() {
// # is not allowed in filter except as a last entry
// invalid: sport/tennis#/player
// invalid: sport/tennis/#/ranking
if entry.contains('#') {
return false;
}
// + must occupy an entire level of the filter
// invalid: sport+
if entry.len() > 1 && entry.contains('+') {
return false;
}
}
// only single '#" or '+' is allowed in last entry
// invalid: sport/tennis#
// invalid: sport/++
if last.len() != 1 && (last.contains('#') || last.contains('+')) {
return false;
}
}
true
}
/// Checks if topic matches a filter. topic and filter validation isn't done here.
///
/// **NOTE**: 'topic' is a misnomer in the arg. this can also be used to match 2 wild subscriptions
/// **NOTE**: make sure a topic is validated during a publish and filter is validated
/// during a subscribe
pub fn matches(topic: &str, filter: &str) -> bool {
if !topic.is_empty() && topic[..1].contains('$') {
return false;
}
let mut topics = topic.split('/');
let mut filters = filter.split('/');
for f in filters.by_ref() {
// "#" being the last element is validated by the broker with 'valid_filter'
if f == "#" {
return true;
}
// filter still has remaining elements
// filter = a/b/c/# should match topci = a/b/c
// filter = a/b/c/d should not match topic = a/b/c
let top = topics.next();
match top {
Some(t) if t == "#" => return false,
Some(_) if f == "+" => continue,
Some(t) if f != t => return false,
Some(_) => continue,
None => return false,
}
}
// topic has remaining elements and filter's last element isn't "#"
if topics.next().is_some() {
return false;
}
true
}
/// Error during serialization and deserialization
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum Error {
#[error("Invalid return code received as response for connect = {0}")]
InvalidConnectReturnCode(u8),
#[error("Invalid reason = {0}")]
InvalidReason(u8),
#[error("Invalid reason = {0}")]
InvalidRemainingLength(usize),
#[error("Invalid protocol used")]
InvalidProtocol,
#[error("Invalid protocol level")]
InvalidProtocolLevel(u8),
#[error("Invalid packet format")]
IncorrectPacketFormat,
#[error("Invalid packet type = {0}")]
InvalidPacketType(u8),
#[error("Invalid retain forward rule = {0}")]
InvalidRetainForwardRule(u8),
#[error("Invalid QoS level = {0}")]
InvalidQoS(u8),
#[error("Invalid subscribe reason code = {0}")]
InvalidSubscribeReasonCode(u8),
#[error("Packet received has id Zero")]
PacketIdZero,
#[error("Empty Subscription")]
EmptySubscription,
#[error("Subscription had id Zero")]
SubscriptionIdZero,
#[error("Payload size is incorrect")]
PayloadSizeIncorrect,
#[error("Payload is too long")]
PayloadTooLong,
#[error("Payload size has been exceeded by {0} bytes")]
PayloadSizeLimitExceeded(usize),
#[error("Payload is required")]
PayloadRequired,
#[error("Payload is required = {0}")]
PayloadNotUtf8(#[from] Utf8Error),
#[error("Topic not utf-8")]
TopicNotUtf8,
#[error("Promised boundary crossed, contains {0} bytes")]
BoundaryCrossed(usize),
#[error("Packet is malformed")]
MalformedPacket,
#[error("Remaining length is malformed")]
MalformedRemainingLength,
#[error("Invalid property type = {0}")]
InvalidPropertyType(u8),
/// More bytes required to frame packet. Argument
/// implies minimum additional bytes required to
/// proceed further
#[error("Insufficient number of bytes to frame packet, {0} more bytes required")]
InsufficientBytes(usize),
}
pub trait Protocol {
fn read_mut(&mut self, stream: &mut BytesMut, max_size: usize) -> Result<Packet, Error>;
fn write(&self, packet: Packet, write: &mut BytesMut) -> Result<usize, Error>;
}