mqtt_protocol_core/mqtt/packet/qos.rs
1/**
2 * MIT License
3 *
4 * Copyright (c) 2025 Takatoshi Kondo
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24use num_enum::TryFromPrimitive;
25use serde::{Deserialize, Serialize};
26use std::fmt;
27
28/// MQTT Quality of Service levels
29///
30/// Defines the delivery guarantee levels for MQTT message publishing and subscription.
31/// Each QoS level provides different guarantees about message delivery, with higher
32/// levels providing stronger guarantees at the cost of increased overhead.
33///
34/// The QoS level is specified in PUBLISH packets and affects how the message is
35/// handled by both the sender and receiver according to the MQTT protocol specification.
36///
37/// # QoS Level Descriptions
38///
39/// - **QoS 0 (At Most Once)**: Fire-and-forget delivery. Messages are delivered
40/// at most once, or not at all. No acknowledgment is required.
41/// - **QoS 1 (At Least Once)**: Acknowledged delivery. Messages are delivered
42/// at least once. Duplicates may occur but will be handled by the receiver.
43/// - **QoS 2 (Exactly Once)**: Assured delivery. Messages are delivered exactly
44/// once using a four-part handshake protocol.
45///
46/// # Protocol Behavior
47///
48/// Each QoS level has specific protocol requirements:
49///
50/// - **QoS 0**: PUBLISH packet is sent without expecting acknowledgment
51/// - **QoS 1**: PUBLISH packet must be acknowledged with PUBACK
52/// - **QoS 2**: PUBLISH packet initiates a handshake: PUBLISH -> PUBREC -> PUBREL -> PUBCOMP
53///
54/// # Examples
55///
56/// ```ignore
57/// use mqtt_protocol_core::mqtt;
58///
59/// // Fire-and-forget message delivery
60/// let qos0 = mqtt::packet::Qos::AtMostOnce;
61///
62/// // Acknowledged delivery with possible duplicates
63/// let qos1 = mqtt::packet::Qos::AtLeastOnce;
64///
65/// // Exactly-once delivery with handshake
66/// let qos2 = mqtt::packet::Qos::ExactlyOnce;
67///
68/// // Convert from byte value
69/// let qos_from_byte = mqtt::packet::Qos::try_from(1u8).unwrap();
70/// assert_eq!(qos_from_byte, mqtt::packet::Qos::AtLeastOnce);
71/// ```
72#[derive(
73 Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, TryFromPrimitive,
74)]
75#[repr(u8)]
76pub enum Qos {
77 /// QoS level 0: At most once delivery
78 ///
79 /// Messages are delivered at most once, or not at all. There is no
80 /// acknowledgment of delivery and no retry mechanism. This is the
81 /// fastest delivery method but provides no guarantee that the message
82 /// will be received.
83 ///
84 /// This level is suitable for:
85 /// - High-frequency sensor data where missing occasional readings is acceptable
86 /// - Applications where message loss is tolerable
87 /// - Scenarios where network bandwidth and battery life are critical
88 AtMostOnce = 0,
89
90 /// QoS level 1: At least once delivery
91 ///
92 /// Messages are delivered at least once. The receiver acknowledges
93 /// delivery with a PUBACK packet. If the sender doesn't receive the
94 /// acknowledgment within a reasonable time, it retransmits the message.
95 /// Duplicate messages may occur and should be handled by the application.
96 ///
97 /// This level is suitable for:
98 /// - Applications that can handle duplicate messages
99 /// - Scenarios where message delivery is important but duplicates are acceptable
100 /// - Most general-purpose messaging use cases
101 AtLeastOnce = 1,
102
103 /// QoS level 2: Exactly once delivery
104 ///
105 /// Messages are delivered exactly once using a four-part handshake
106 /// protocol (PUBLISH -> PUBREC -> PUBREL -> PUBCOMP). This guarantees
107 /// that messages are neither lost nor duplicated, but requires the
108 /// most network traffic and processing overhead.
109 ///
110 /// This level is suitable for:
111 /// - Financial transactions or billing information
112 /// - Critical control messages
113 /// - Applications where duplicate processing would cause serious problems
114 ExactlyOnce = 2,
115}
116
117/// Implementation of `Display` for `Qos`
118///
119/// Formats the QoS level as a human-readable string representation.
120/// This allows QoS values to be used with `println!`, `format!`, and
121/// other string formatting operations.
122///
123/// # Output Format
124///
125/// * `Qos::AtMostOnce` -> "AtMostOnce"
126/// * `Qos::AtLeastOnce` -> "AtLeastOnce"
127/// * `Qos::ExactlyOnce` -> "ExactlyOnce"
128impl fmt::Display for Qos {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 let s = match self {
131 Self::AtMostOnce => "AtMostOnce",
132 Self::AtLeastOnce => "AtLeastOnce",
133 Self::ExactlyOnce => "ExactlyOnce",
134 };
135 write!(f, "{s}")
136 }
137}