mqtt5 0.38.2

Complete MQTT v5.0 platform with high-performance async client and full-featured broker supporting TCP, TLS, WebSocket, authentication, bridging, and resource monitoring
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
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};

use parking_lot::Mutex;
use tokio::sync::mpsc;
use tracing::{debug, warn};

use crate::callback::CallbackId;
use crate::client::direct::unified::UnifiedWriter;
use crate::packet::puback::PubAckPacket;
use crate::packet::publish::PublishPacket;
use crate::packet::pubrec::PubRecPacket;
use crate::packet::Packet;
use crate::protocol::v5::properties::Properties;
use crate::protocol::v5::reason_codes::ReasonCode;
use crate::session::state::AckResolution;
use crate::session::SessionState;
use crate::transport::PacketWriter;
use crate::validation::strip_shared_subscription_prefix;
use crate::QoS;

type WriterHandle = Arc<tokio::sync::Mutex<UnifiedWriter>>;
type WriterSlot = Arc<tokio::sync::Mutex<Option<WriterHandle>>>;

/// The reason code an unresolved token uses when it is dropped without an explicit
/// decision. Non-success so the acknowledgement records that the message was abandoned.
const DROP_REASON: ReasonCode = ReasonCode::UnspecifiedError;

pub(crate) enum AckKind {
    Ack,
    Reject(ReasonCode),
    DropAuto,
}

pub(crate) struct AckRequest {
    packet_id: u16,
    qos: QoS,
    kind: AckKind,
}

/// A capability to acknowledge exactly one inbound `QoS` > 0 message after the
/// application has durably processed it.
///
/// The token owns its message's Receive-Maximum window slot for its lifetime, so
/// holding it applies backpressure. It is move-only: [`AckToken::ack`] and
/// [`AckToken::reject`] consume it, making a double-acknowledgement a compile error.
/// Dropping it without resolving emits a non-success acknowledgement and warns, so a
/// forgotten token never wedges the window (`DeferredAckToken.tla`, obligation 7).
pub struct AckToken {
    packet_id: u16,
    qos: QoS,
    armed: bool,
    sender: mpsc::UnboundedSender<AckRequest>,
}

impl AckToken {
    /// The packet identifier of the message this token acknowledges.
    #[must_use]
    pub fn packet_id(&self) -> u16 {
        self.packet_id
    }

    /// The `QoS` of the message this token acknowledges.
    #[must_use]
    pub fn qos(&self) -> QoS {
        self.qos
    }

    /// Acknowledges the message after durable processing. Consumes the token.
    pub fn ack(mut self) {
        self.emit(AckKind::Ack);
    }

    /// Rejects the message after failing to process it, sending an error
    /// acknowledgement (an error PUBREC for `QoS` 2). Consumes the token.
    ///
    /// Rejecting is **not at-most-once**: per MQTT-5 `[MQTT-4.3.3-9]`, once the receiver
    /// has sent an error acknowledgement it must treat any later PUBLISH with the same
    /// Packet Identifier as a new message. So if the acknowledgement is lost and the
    /// broker replays the message on reconnect, your callback will see it again. Reject
    /// must therefore be idempotent, like the rest of deferred delivery.
    ///
    /// A non-error `reason` (Reason Code below `0x80`, e.g. `Success`) is normalized to
    /// [`ReasonCode::UnspecifiedError`], so `reject` can never behave as an [`ack`](Self::ack).
    pub fn reject(mut self, reason: ReasonCode) {
        let reason = if reason.is_error() {
            reason
        } else {
            ReasonCode::UnspecifiedError
        };
        self.emit(AckKind::Reject(reason));
    }

    fn emit(&mut self, kind: AckKind) {
        if !self.armed {
            return;
        }
        self.armed = false;
        let _ = self.sender.send(AckRequest {
            packet_id: self.packet_id,
            qos: self.qos,
            kind,
        });
    }
}

impl Drop for AckToken {
    fn drop(&mut self) {
        if self.armed {
            warn!(
                packet_id = self.packet_id,
                qos = ?self.qos,
                "AckToken dropped without ack/reject; auto-acknowledging with a non-success reason"
            );
            self.emit(AckKind::DropAuto);
        }
    }
}

/// Owns the single background task that writes deferred acknowledgements.
///
/// The task is connection-stable: it is spawned on the first connection (never in the
/// constructor, so building a client needs no running runtime) and outlives reconnects,
/// targeting whichever writer is current via a swappable slot. This is what lets a token
/// minted on one connection resolve on the next (the transport reconnect regime of
/// `DeferredAckQoS2Reconnect.tla`). `Drop` is synchronous and cannot await the writer, so
/// tokens only ever enqueue an `AckRequest` here.
pub(crate) struct AckDispatcher {
    tx: mpsc::UnboundedSender<AckRequest>,
    writer_slot: WriterSlot,
    session: Arc<tokio::sync::RwLock<SessionState>>,
    pending_rx: tokio::sync::Mutex<Option<mpsc::UnboundedReceiver<AckRequest>>>,
}

impl AckDispatcher {
    pub(crate) fn new(session: Arc<tokio::sync::RwLock<SessionState>>) -> Self {
        let (tx, rx) = mpsc::unbounded_channel::<AckRequest>();
        Self {
            tx,
            writer_slot: Arc::new(tokio::sync::Mutex::new(None)),
            session,
            pending_rx: tokio::sync::Mutex::new(Some(rx)),
        }
    }

    /// Spawns the drain task on the first call, in async context. Subsequent calls are
    /// no-ops, so the task is created once (on the first connection) and outlives reconnects.
    async fn ensure_started(&self) {
        let Some(mut rx) = self.pending_rx.lock().await.take() else {
            return;
        };
        let slot = Arc::clone(&self.writer_slot);
        let session = Arc::clone(&self.session);
        tokio::spawn(async move {
            while let Some(request) = rx.recv().await {
                Self::handle(&request, &slot, &session).await;
            }
        });
    }

    /// Mints a token for a delivered inbound message.
    pub(crate) fn token(&self, packet_id: u16, qos: QoS) -> AckToken {
        AckToken {
            packet_id,
            qos,
            armed: true,
            sender: self.tx.clone(),
        }
    }

    /// Points the drain task at the writer for the current connection, starting the task
    /// on the first call.
    pub(crate) async fn set_writer(&self, writer: WriterHandle) {
        self.ensure_started().await;
        *self.writer_slot.lock().await = Some(writer);
    }

    /// Releases the current connection's writer so its socket can close on disconnect.
    ///
    /// The dispatcher outlives reconnects, but it must NOT keep the writer half alive
    /// across a teardown: a retained clone would hold the socket open and mask an
    /// abnormal disconnect from the broker. Acks enqueued while cleared are recorded
    /// as a resolution and re-sent on the next connection.
    pub(crate) async fn clear_writer(&self) {
        *self.writer_slot.lock().await = None;
    }

    /// Re-sends an acknowledgement for a duplicate that was already resolved,
    /// without a token (used on a post-reconnect replay).
    pub(crate) fn enqueue(&self, packet_id: u16, qos: QoS, kind: AckKind) {
        let _ = self.tx.send(AckRequest {
            packet_id,
            qos,
            kind,
        });
    }

    /// Applies one acknowledgement: records the session state, then writes the ack packet.
    ///
    /// The session is updated **before** the ack reaches the wire, so a packet id the broker
    /// reuses after receiving this ack cannot race an in-flight write and be seen as a stale
    /// duplicate. The write is best-effort; if the connection is gone the recorded state drives
    /// the correct replay on reconnect. For a `QoS` 2 error acknowledgement the per-id deferred
    /// state is cleared, per `[MQTT-4.3.3-9]` (a later same-id PUBLISH is a new message).
    async fn handle(
        request: &AckRequest,
        slot: &WriterSlot,
        session: &Arc<tokio::sync::RwLock<SessionState>>,
    ) {
        let reason = match request.kind {
            AckKind::Ack => ReasonCode::Success,
            AckKind::Reject(r) => r,
            AckKind::DropAuto => DROP_REASON,
        };
        let packet = match request.qos {
            QoS::AtMostOnce => return,
            QoS::AtLeastOnce => Packet::PubAck(PubAckPacket {
                packet_id: request.packet_id,
                reason_code: reason,
                properties: Properties::default(),
            }),
            QoS::ExactlyOnce => Packet::PubRec(PubRecPacket {
                packet_id: request.packet_id,
                reason_code: reason,
                properties: Properties::default(),
            }),
        };

        let is_success = reason == ReasonCode::Success;
        {
            let session = session.read().await;
            match request.qos {
                QoS::AtMostOnce => {}
                QoS::ExactlyOnce if is_success => {
                    session.mark_pubrec_sent(request.packet_id).await;
                    session
                        .set_resolution(request.packet_id, AckResolution::Acked)
                        .await;
                }
                QoS::AtLeastOnce | QoS::ExactlyOnce => {
                    session.acknowledge_inbound(request.packet_id).await;
                    session.clear_inbound_state(request.packet_id).await;
                }
            }
        }

        let writer = slot.lock().await.clone();
        let written = match &writer {
            Some(handle) => handle.lock().await.write_packet(packet).await.is_ok(),
            None => false,
        };
        if !written {
            debug!(
                packet_id = request.packet_id,
                "Deferred ack not written (disconnected); resolution recorded for replay"
            );
        }
    }
}

/// A publish callback that also receives the message's [`AckToken`].
pub(crate) type AckPublishCallback = Arc<dyn Fn(PublishPacket, AckToken) + Send + Sync>;

struct AckCallbackEntry {
    callback: AckPublishCallback,
    topic_filter: String,
}

struct AckDispatchItem {
    callback: AckPublishCallback,
    message: PublishPacket,
    token: AckToken,
}

/// Registry of `subscribe_with_ack` callbacks.
///
/// Unlike [`crate::callback::CallbackManager`], a match resolves to exactly ONE
/// callback: an [`AckToken`] has a single owner and cannot be cloned or fanned out.
/// Delivery runs on a lazily spawned FIFO worker so the user callback never blocks
/// the reader task (obligation 4).
pub(crate) struct AckCallbackManager {
    exact: Mutex<HashMap<String, AckCallbackEntry>>,
    wildcard: Mutex<Vec<AckCallbackEntry>>,
    next_id: AtomicU64,
    dispatch_tx: OnceLock<mpsc::UnboundedSender<AckDispatchItem>>,
}

impl AckCallbackManager {
    pub(crate) fn new() -> Self {
        Self {
            exact: Mutex::new(HashMap::new()),
            wildcard: Mutex::new(Vec::new()),
            next_id: AtomicU64::new(1),
            dispatch_tx: OnceLock::new(),
        }
    }

    fn dispatch_sender(&self) -> &mpsc::UnboundedSender<AckDispatchItem> {
        self.dispatch_tx.get_or_init(|| {
            let (tx, mut rx) = mpsc::unbounded_channel::<AckDispatchItem>();
            tokio::spawn(async move {
                while let Some(item) = rx.recv().await {
                    (item.callback)(item.message, item.token);
                }
            });
            tx
        })
    }

    /// Registers an ack callback for a topic filter, returning its id.
    pub(crate) fn register(&self, topic_filter: &str, callback: AckPublishCallback) -> CallbackId {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let entry = AckCallbackEntry {
            callback,
            topic_filter: topic_filter.to_string(),
        };
        let actual = strip_shared_subscription_prefix(topic_filter).to_string();
        if actual.contains('+') || actual.contains('#') {
            self.wildcard.lock().push(entry);
        } else {
            self.exact.lock().insert(actual, entry);
        }
        id
    }

    /// Removes the ack callback(s) for a topic filter.
    pub(crate) fn unregister(&self, topic_filter: &str) -> bool {
        let actual = strip_shared_subscription_prefix(topic_filter);
        let removed_exact = self.exact.lock().remove(actual).is_some();
        let mut wildcard = self.wildcard.lock();
        let before = wildcard.len();
        wildcard.retain(|e| e.topic_filter != topic_filter);
        removed_exact || wildcard.len() < before
    }

    /// Finds the single best-matching callback for a topic: an exact match wins,
    /// otherwise the first matching wildcard.
    pub(crate) fn find_one(&self, topic: &str) -> Option<AckPublishCallback> {
        if let Some(entry) = self.exact.lock().get(topic) {
            return Some(Arc::clone(&entry.callback));
        }
        let wildcard = self.wildcard.lock();
        for entry in wildcard.iter() {
            let filter = strip_shared_subscription_prefix(&entry.topic_filter);
            if crate::topic_matching::matches(topic, filter) {
                return Some(Arc::clone(&entry.callback));
            }
        }
        None
    }

    /// Hands a message and its token to a callback on the FIFO worker.
    pub(crate) fn dispatch(
        &self,
        callback: AckPublishCallback,
        message: PublishPacket,
        token: AckToken,
    ) {
        let _ = self.dispatch_sender().send(AckDispatchItem {
            callback,
            message,
            token,
        });
    }
}

#[cfg(test)]
mod tests {
    use super::{AckCallbackManager, AckDispatcher, AckPublishCallback};
    use crate::packet::publish::PublishPacket;
    use crate::session::state::{SessionConfig, SessionState};
    use crate::QoS;
    use std::sync::atomic::{AtomicU32, Ordering};
    use std::sync::Arc;

    #[tokio::test]
    async fn duplicate_wildcard_subscription_dispatches_to_a_single_callback() {
        let mgr = AckCallbackManager::new();
        let hits_first = Arc::new(AtomicU32::new(0));
        let hits_second = Arc::new(AtomicU32::new(0));
        let f = Arc::clone(&hits_first);
        let s = Arc::clone(&hits_second);
        let cb_first: AckPublishCallback = Arc::new(move |_p, _t| {
            f.fetch_add(1, Ordering::SeqCst);
        });
        let cb_second: AckPublishCallback = Arc::new(move |_p, _t| {
            s.fetch_add(1, Ordering::SeqCst);
        });
        mgr.register("jobs/#", cb_first);
        mgr.register("jobs/#", cb_second);

        let dispatcher = AckDispatcher::new(Arc::new(tokio::sync::RwLock::new(SessionState::new(
            "t".to_string(),
            SessionConfig::default(),
            true,
        ))));
        let callback = mgr
            .find_one("jobs/build")
            .expect("a wildcard entry matches jobs/build");
        let token = dispatcher.token(1, QoS::ExactlyOnce);
        callback(
            PublishPacket::new("jobs/build", b"x".to_vec(), QoS::ExactlyOnce),
            token,
        );

        assert_eq!(
            hits_first.load(Ordering::SeqCst) + hits_second.load(Ordering::SeqCst),
            1,
            "a matching publish invokes exactly one ack callback, never both"
        );
        assert_eq!(
            hits_second.load(Ordering::SeqCst),
            0,
            "the duplicate registration is shadowed and never fires"
        );
    }
}