symqtt 0.1.1

Synchronous MQTT 3.1.1/5.0 client — blocking API, no async runtime
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
//! Thread-safe MQTT 3.1.1 session state, independent of any single connection
//!
//! [`Session`] is designed to outlive individual [`Client`](super::Client) instances,
//! enabling inflight QoS 1/2 messages to survive reconnections. Clone is cheap
//! (shared via internal `Arc`). Create one `Session` and pass clones to successive
//! `Client` instances to preserve delivery guarantees across network interruptions.

use std::sync::mpsc::{self, Receiver, SyncSender};
use std::sync::{Arc, Mutex};

use smallvec::SmallVec;
use symqtt_codec::QoS;
use symqtt_codec::v3::{Publish, SubscribeReturnCode};

use super::error::Error;

/// Maximum inflight window (protocol ceiling: packet IDs 1..=65535)
const DEFAULT_MAX_INFLIGHT: u16 = u16::MAX;

/// Result delivered through the completion channel when an ACK arrives
#[derive(Debug, Clone)]
pub enum AckResult {
    /// Operation completed successfully
    Success,
    /// SUBACK with granted QoS per filter
    SubAck(Vec<SubscribeReturnCode>),
    /// Connection lost or protocol error
    Error(Error),
}

/// A message that needs retransmission after reconnect
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Retransmit {
    /// Re-send PUBLISH with DUP=1
    Publish(Publish),
    /// Re-send PUBREL for a QoS 2 flow that already received PUBREC
    PubRel {
        /// Packet identifier of the in-progress QoS 2 flow
        pkid: u16,
    },
}

/// Session state machine errors
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SessionError {
    /// Received an ACK for a packet ID that is not currently tracked
    #[error("unknown packet id: {0}")]
    UnknownPkid(u16),
    /// Received an ACK that does not match the current stage of the packet ID
    #[error("unexpected stage for packet id: {0}")]
    WrongStage(u16),
}

/// Outgoing packet lifecycle stage, tracked per packet ID
enum OutStage {
    /// Packet ID allocated but not yet associated with a message
    Allocated,
    /// QoS 1 PUBLISH sent, waiting for PUBACK
    WaitingPubAck(Publish, SyncSender<AckResult>),
    /// QoS 2 PUBLISH sent, waiting for PUBREC
    WaitingPubRec(Publish, SyncSender<AckResult>),
    /// QoS 2 PUBREC received and PUBREL sent, waiting for PUBCOMP
    WaitingPubComp(SyncSender<AckResult>),
}

/// Slab allocator for outgoing packet IDs with stage tracking
///
/// Maps packet IDs (1-based) to their current lifecycle stage.
/// Uses a circular scan for allocation to distribute IDs evenly.
struct OutgoingSlab {
    slots: Vec<Option<OutStage>>,
    count: u16,
    max: u16,
    next: u16,
}

impl OutgoingSlab {
    fn new(max: u16) -> Self {
        let slots = (0..max).map(|_| None).collect::<Vec<_>>();
        Self {
            max,
            slots,
            count: 0,
            next: 0,
        }
    }

    /// Allocate the next available packet ID using circular scan
    ///
    /// Scans from `self.next` forward, wrapping around, to find the first
    /// unoccupied slot. Returns the 1-based packet ID or None if all slots
    /// are in use.
    fn alloc(&mut self) -> Option<u16> {
        if self.count >= self.max {
            return None;
        }
        let start = self.next;
        loop {
            let idx = self.next as usize;
            self.next = (self.next + 1) % self.max;
            if self.slots[idx].is_none() {
                self.slots[idx] = Some(OutStage::Allocated);
                self.count += 1;
                return Some(idx as u16 + 1);
            }
            if self.next == start {
                return None;
            }
        }
    }

    /// Release a packet ID slot back to the pool
    fn release(&mut self, pkid: u16) {
        let idx = (pkid - 1) as usize;
        if idx < self.slots.len() && self.slots[idx].is_some() {
            self.slots[idx] = None;
            self.count -= 1;
        }
    }

    /// Transition a packet ID from Allocated to WaitingPubAck/WaitingPubRec based on QoS
    fn track(&mut self, pkid: u16, publish: Publish, tx: SyncSender<AckResult>) {
        let idx = (pkid - 1) as usize;
        let stage = match publish.qos {
            QoS::AtLeastOnce => OutStage::WaitingPubAck(publish, tx),
            QoS::ExactlyOnce => OutStage::WaitingPubRec(publish, tx),
            QoS::AtMostOnce => return,
        };
        self.slots[idx] = Some(stage);
    }

    /// Track a subscribe/unsubscribe operation (reuses WaitingPubAck stage internally)
    ///
    /// Subscribe/unsubscribe share the same "send and wait for single ACK" pattern
    /// as QoS 1 publish, so we reuse WaitingPubAck with a dummy Publish to avoid
    /// adding a dedicated stage variant.
    fn track_sub(&mut self, pkid: u16, tx: SyncSender<AckResult>) {
        let idx = (pkid - 1) as usize;
        self.slots[idx] = Some(OutStage::WaitingPubAck(
            Publish {
                dup: false,
                qos: QoS::AtLeastOnce,
                retain: false,
                topic: String::new(),
                pkid: None,
                payload: bytes::Bytes::new(),
            },
            tx,
        ));
    }

    /// Handle PUBACK: complete QoS 1 flow, notify the waiting token
    fn on_puback(&mut self, pkid: u16) -> Result<(), SessionError> {
        let idx = (pkid - 1) as usize;
        let Some(stage) = self.slots.get_mut(idx).and_then(Option::take) else {
            return Err(SessionError::UnknownPkid(pkid));
        };

        let OutStage::WaitingPubAck(_, tx) = stage else {
            self.slots[idx] = Some(stage);
            return Err(SessionError::WrongStage(pkid));
        };

        let _ = tx.try_send(AckResult::Success);
        self.count -= 1;

        Ok(())
    }

    /// Handle PUBREC: advance QoS 2 flow from WaitingPubRec to WaitingPubComp
    fn on_pubrec(&mut self, pkid: u16) -> Result<(), SessionError> {
        let idx = (pkid - 1) as usize;
        let Some(stage) = self.slots.get_mut(idx).and_then(Option::take) else {
            return Err(SessionError::UnknownPkid(pkid));
        };

        let OutStage::WaitingPubRec(_, tx) = stage else {
            self.slots[idx] = Some(stage);
            return Err(SessionError::WrongStage(pkid));
        };

        self.slots[idx] = Some(OutStage::WaitingPubComp(tx));

        Ok(())
    }

    /// Handle PUBCOMP: complete QoS 2 flow, notify the waiting token
    fn on_pubcomp(&mut self, pkid: u16) -> Result<(), SessionError> {
        let idx = (pkid - 1) as usize;
        let Some(stage) = self.slots.get_mut(idx).and_then(Option::take) else {
            return Err(SessionError::UnknownPkid(pkid));
        };

        let OutStage::WaitingPubComp(tx) = stage else {
            self.slots[idx] = Some(stage);
            return Err(SessionError::WrongStage(pkid));
        };

        let _ = tx.try_send(AckResult::Success);
        self.count -= 1;

        Ok(())
    }

    /// Handle SUBACK: deliver granted QoS codes to the waiting token
    fn on_suback(&mut self, pkid: u16, codes: Vec<SubscribeReturnCode>) {
        let idx = (pkid - 1) as usize;
        let Some(stage) = self.slots.get_mut(idx).and_then(Option::take) else {
            return;
        };

        let OutStage::WaitingPubAck(_, tx) = stage else {
            self.slots[idx] = Some(stage);
            return;
        };

        let _ = tx.try_send(AckResult::SubAck(codes));
        self.count -= 1;
    }

    /// Handle UNSUBACK: notify the waiting token of completion
    fn on_unsuback(&mut self, pkid: u16) {
        let idx = (pkid - 1) as usize;
        let Some(stage) = self.slots.get_mut(idx).and_then(Option::take) else {
            return;
        };

        let OutStage::WaitingPubAck(_, tx) = stage else {
            self.slots[idx] = Some(stage);
            return;
        };

        let _ = tx.try_send(AckResult::Success);
        self.count -= 1;
    }

    /// Wake all pending tokens with an error (used on graceful disconnect)
    fn wake_all(&mut self, error: Error) {
        for slot in &mut self.slots {
            let Some(stage) = slot.take() else {
                continue;
            };
            match stage {
                OutStage::Allocated => {}
                OutStage::WaitingPubAck(_, tx) | OutStage::WaitingPubRec(_, tx) | OutStage::WaitingPubComp(tx) => {
                    let _ = tx.try_send(AckResult::Error(error.clone()));
                }
            }
        }
        self.count = 0;
    }

    /// Collect all inflight messages that need retransmission after reconnect
    fn pending_retransmit(&self) -> Vec<Retransmit> {
        let mut out = Vec::with_capacity(16);
        for (idx, slot) in self.slots.iter().enumerate() {
            let Some(stage) = slot.as_ref() else {
                continue;
            };
            let pkid = idx as u16 + 1;
            match stage {
                OutStage::WaitingPubAck(publish, _) | OutStage::WaitingPubRec(publish, _) => {
                    let mut p = publish.clone();
                    // DUP=1 signals to the broker that this is a retransmission [MQTT-3.3.1-1]
                    p.dup = true;
                    p.pkid = Some(pkid);
                    out.push(Retransmit::Publish(p));
                }
                OutStage::WaitingPubComp(_) => {
                    // Already received PUBREC — only need to re-send PUBREL
                    out.push(Retransmit::PubRel { pkid });
                }
                OutStage::Allocated => {}
            }
        }
        out
    }

    /// Clear all slots and reset allocation state
    fn clear(&mut self) {
        for slot in &mut self.slots {
            *slot = None;
        }
        self.count = 0;
        self.next = 0;
    }
}

struct SessionInner {
    outgoing: Mutex<OutgoingSlab>,
    /// Incoming QoS 2 packet IDs being tracked for deduplication
    incoming: Mutex<SmallVec<[u16; 8]>>,
}

/// Thread-safe MQTT 3.1.1 session state, independent of connection lifetime
///
/// Clone is cheap — all clones share the same underlying state via `Arc`.
/// Create one `Session` and pass clones to successive [`Client`](super::Client)
/// instances to preserve inflight QoS 1/2 messages across reconnections.
#[derive(Clone)]
pub struct Session {
    inner: Arc<SessionInner>,
}

impl Session {
    /// Create a new session with the default inflight window (65535 packet IDs)
    pub fn new() -> Self {
        Self {
            inner: Arc::new(SessionInner {
                outgoing: Mutex::new(OutgoingSlab::new(DEFAULT_MAX_INFLIGHT)),
                incoming: Mutex::new(SmallVec::new()),
            }),
        }
    }

    /// 创建指定 inflight 窗口大小的 Session,仅用于测试
    pub fn with_max_inflight(max: u16) -> Self {
        Self {
            inner: Arc::new(SessionInner {
                outgoing: Mutex::new(OutgoingSlab::new(max)),
                incoming: Mutex::new(SmallVec::new()),
            }),
        }
    }

    /// Handle CONNACK reception and determine retransmission needs
    ///
    /// If `session_present` is true, the broker preserved session state from a
    /// previous connection — returns all inflight messages that need retransmission
    /// (PUBLISH with DUP=1, or PUBREL for in-progress QoS 2 flows).
    ///
    /// If `session_present` is false, the broker has no prior state — clears all
    /// tracked inflight data and returns an empty list.
    pub fn on_connect(&self, session_present: bool) -> Vec<Retransmit> {
        if session_present {
            self.inner.outgoing.lock().unwrap().pending_retransmit()
        } else {
            self.inner.outgoing.lock().unwrap().clear();
            self.inner.incoming.lock().unwrap().clear();
            Vec::new()
        }
    }

    /// Called when the connection is unexpectedly lost
    ///
    /// Preserves all inflight state — pending tokens remain blocked until a
    /// new Client connects with this session and the broker ACKs arrive
    pub fn on_connection_lost(&self) {
        // intentionally preserve state for next connection
    }

    /// Called on user-initiated disconnect
    ///
    /// Wakes all pending tokens with a [`Error::Disconnected`] error since no
    /// further ACKs will arrive on this connection
    pub fn on_disconnect(&self) {
        self.inner.outgoing.lock().unwrap().wake_all(Error::Disconnected);
    }

    /// Allocate the next available packet ID
    ///
    /// Returns `None` if the inflight window is full (all 65535 IDs in use)
    pub fn alloc_pkid(&self) -> Option<u16> {
        self.inner.outgoing.lock().unwrap().alloc()
    }

    /// Release a previously allocated packet ID back to the pool
    ///
    /// Used when the send operation fails before the message is tracked
    pub fn release_pkid(&self, pkid: u16) {
        self.inner.outgoing.lock().unwrap().release(pkid);
    }

    /// Record an outgoing PUBLISH and begin tracking its ACK lifecycle
    ///
    /// Returns a [`Receiver`] that resolves when the corresponding ACK arrives
    /// (PUBACK for QoS 1, PUBCOMP for QoS 2)
    pub fn track_publish(&self, pkid: u16, publish: Publish) -> Receiver<AckResult> {
        let (tx, rx) = mpsc::sync_channel(1);
        self.inner.outgoing.lock().unwrap().track(pkid, publish, tx);
        rx
    }

    /// Track a SUBSCRIBE or UNSUBSCRIBE operation
    ///
    /// Returns a [`Receiver`] that resolves on SUBACK or UNSUBACK
    pub fn track_sub(&self, pkid: u16) -> Receiver<AckResult> {
        let (tx, rx) = mpsc::sync_channel(1);
        self.inner.outgoing.lock().unwrap().track_sub(pkid, tx);
        rx
    }

    /// Handle incoming PUBACK — completes a QoS 1 publish flow
    pub fn on_puback(&self, pkid: u16) -> Result<(), SessionError> {
        self.inner.outgoing.lock().unwrap().on_puback(pkid)
    }

    /// Handle incoming PUBREC — advances QoS 2 from WaitingPubRec to WaitingPubComp
    pub fn on_pubrec(&self, pkid: u16) -> Result<(), SessionError> {
        self.inner.outgoing.lock().unwrap().on_pubrec(pkid)
    }

    /// Handle incoming PUBCOMP — completes a QoS 2 publish flow
    pub fn on_pubcomp(&self, pkid: u16) -> Result<(), SessionError> {
        self.inner.outgoing.lock().unwrap().on_pubcomp(pkid)
    }

    /// Handle incoming SUBACK — delivers granted QoS codes to the waiting token
    pub fn on_suback(&self, pkid: u16, codes: Vec<SubscribeReturnCode>) {
        self.inner.outgoing.lock().unwrap().on_suback(pkid, codes);
    }

    /// Handle incoming UNSUBACK — notifies the waiting token of completion
    pub fn on_unsuback(&self, pkid: u16) {
        self.inner.outgoing.lock().unwrap().on_unsuback(pkid);
    }

    /// Track an incoming QoS 2 PUBLISH for deduplication
    ///
    /// Returns `true` if this packet ID was already tracked (duplicate message
    /// that should not be delivered to the handler again)
    pub fn track_incoming(&self, pkid: u16) -> bool {
        let mut incoming = self.inner.incoming.lock().unwrap();
        if incoming.contains(&pkid) {
            true
        } else {
            incoming.push(pkid);
            false
        }
    }

    /// Release an incoming QoS 2 packet ID after PUBREL is received
    ///
    /// # Errors
    ///
    /// Returns [`SessionError::UnknownPkid`] if the packet ID was not being tracked
    pub fn release_incoming(&self, pkid: u16) -> Result<(), SessionError> {
        let mut incoming = self.inner.incoming.lock().unwrap();
        if let Some(pos) = incoming.iter().position(|&id| id == pkid) {
            incoming.swap_remove(pos);
            Ok(())
        } else {
            Err(SessionError::UnknownPkid(pkid))
        }
    }
}

impl Default for Session {
    fn default() -> Self {
        Self::new()
    }
}

impl From<Retransmit> for symqtt_codec::v3::Packet {
    fn from(retransmit: Retransmit) -> Self {
        match retransmit {
            Retransmit::Publish(p) => symqtt_codec::v3::Packet::Publish(p),
            Retransmit::PubRel { pkid } => symqtt_codec::v3::Packet::PubRel(symqtt_codec::v3::PubRel { pkid }),
        }
    }
}