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
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
//! Thread-safe MQTT 5.0 session state, independent of connection lifetime
//!
//! Unlike v3, v5 Session stores `ServerProperties` negotiated from CONNACK
//! and uses Receive Maximum to dynamically limit the inflight window.

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

use bytes::Bytes;
use smallvec::SmallVec;
use symqtt_codec::QoS;
use symqtt_codec::v5::{
    ConnAck, PubAckProperties, PubCompProperties, Publish, ReasonCode, SubAckProperties, UnsubAckProperties,
};

use super::error::Error;

/// 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),
}

/// Result delivered through the completion channel when an ACK arrives
#[derive(Debug, Clone)]
pub enum AckResult {
    /// Simple success (used for publish_simple token resolution)
    Success,
    /// PUBACK/PUBCOMP with reason code and properties
    Ack(ReasonCode, PubAckProperties),
    /// SUBACK carrying per-filter reason codes
    SubAck(Vec<ReasonCode>, SubAckProperties),
    /// UNSUBACK carrying per-topic reason codes
    UnsubAck(Vec<ReasonCode>, UnsubAckProperties),
    /// Error (connection lost, etc.)
    Error(Error),
}

/// A message that needs retransmission after reconnect
#[derive(Debug, Clone)]
pub enum Retransmit {
    /// Re-send PUBLISH with DUP=1
    Publish(Box<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,
    },
}

/// Negotiated server capabilities from CONNACK properties [MQTTv5-3.2.2.3]
#[derive(Debug, Clone)]
pub struct ServerProperties {
    /// Maximum number of QoS 1/2 messages server will process concurrently
    pub receive_maximum: u16,
    /// Maximum packet size server is willing to accept (0 = no limit)
    pub maximum_packet_size: u32,
    /// Maximum number of topic aliases the server supports
    pub topic_alias_maximum: u16,
    /// Maximum QoS level the server supports
    pub maximum_qos: QoS,
    /// Whether the server supports retained messages
    pub retain_available: bool,
    /// Whether the server supports wildcard subscriptions
    pub wildcard_sub_available: bool,
    /// Whether the server supports subscription identifiers
    pub sub_id_available: bool,
    /// Whether the server supports shared subscriptions
    pub shared_sub_available: bool,
    /// Server-overridden keepalive interval (seconds)
    pub server_keep_alive: Option<u16>,
    /// Server-assigned session expiry interval (seconds)
    pub session_expiry_interval: Option<u32>,
    /// Server-assigned client identifier (when client sent empty)
    pub assigned_client_id: Option<String>,
    /// Response information for request/response pattern
    pub response_information: Option<String>,
    /// Server reference for client redirection
    pub server_reference: Option<String>,
}

impl Default for ServerProperties {
    fn default() -> Self {
        Self {
            receive_maximum: 65535,
            maximum_packet_size: 0,
            topic_alias_maximum: 0,
            maximum_qos: QoS::ExactlyOnce,
            retain_available: true,
            wildcard_sub_available: true,
            sub_id_available: true,
            shared_sub_available: true,
            server_keep_alive: None,
            session_expiry_interval: None,
            assigned_client_id: None,
            response_information: None,
            server_reference: None,
        }
    }
}

/// Outgoing packet lifecycle stage
enum OutStage {
    /// Packet ID allocated but not yet tracked
    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, PUBREL sent, waiting for PUBCOMP
    WaitingPubComp(SyncSender<AckResult>),
}

/// Slab allocator for outgoing packet IDs
struct OutgoingSlab {
    /// Slot array indexed by (pkid - 1), each slot holds the current stage or None
    slots: Vec<Option<OutStage>>,
    /// Number of currently allocated packet IDs
    count: u16,
    /// Maximum concurrent packet IDs (from Receive Maximum)
    max: u16,
    /// Next candidate index for allocation (round-robin)
    next: u16,
}

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

    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;
            }
        }
    }

    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;
        }
    }

    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);
    }

    fn track_sub(&mut self, pkid: u16, tx: SyncSender<AckResult>) {
        let idx = (pkid - 1) as usize;
        // Reuse WaitingPubAck with a dummy publish for subscribe/unsubscribe tracking
        self.slots[idx] = Some(OutStage::WaitingPubAck(
            Publish {
                dup: false,
                qos: QoS::AtLeastOnce,
                retain: false,
                topic: String::new(),
                pkid: None,
                properties: Default::default(),
                payload: Bytes::new(),
            },
            tx,
        ));
    }

    fn on_puback(&mut self, pkid: u16, reason_code: ReasonCode, props: PubAckProperties) -> 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::Ack(reason_code, props));
        self.count -= 1;
        Ok(())
    }

    fn on_pubrec(&mut self, pkid: u16, reason_code: ReasonCode) -> Result<bool, 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));
        };
        // If reason code indicates failure, complete the flow immediately
        if reason_code.is_error() {
            let _ = tx.try_send(AckResult::Ack(reason_code, PubAckProperties::default()));
            self.count -= 1;
            return Ok(false); // don't send PUBREL
        }
        self.slots[idx] = Some(OutStage::WaitingPubComp(tx));
        Ok(true) // send PUBREL
    }

    fn on_pubcomp(&mut self, pkid: u16, reason_code: ReasonCode, props: PubCompProperties) -> 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 ack = AckResult::Ack(
            reason_code,
            PubAckProperties {
                reason_string: props.reason_string,
                user_properties: props.user_properties,
            },
        );
        let _ = tx.try_send(ack);
        self.count -= 1;
        Ok(())
    }

    fn on_suback(&mut self, pkid: u16, codes: Vec<ReasonCode>, props: SubAckProperties) {
        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, props));
        self.count -= 1;
    }

    fn on_unsuback(&mut self, pkid: u16, codes: Vec<ReasonCode>, props: UnsubAckProperties) {
        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::UnsubAck(codes, props));
        self.count -= 1;
    }

    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;
    }

    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();
                    p.dup = true;
                    p.pkid = Some(pkid);
                    out.push(Retransmit::Publish(Box::new(p)));
                }
                OutStage::WaitingPubComp(_) => {
                    out.push(Retransmit::PubRel { pkid });
                }
                OutStage::Allocated => {}
            }
        }
        out
    }

    fn clear(&mut self) {
        for slot in &mut self.slots {
            *slot = None;
        }
        self.count = 0;
        self.next = 0;
    }

    /// Dynamically resize the window (shrink or expand) based on server negotiation
    fn set_max(&mut self, new_max: u16) {
        if new_max == self.max {
            return;
        }
        if new_max < self.max {
            // Shrink: just update max, existing allocations beyond are still valid
            // but no new allocations will be made until count drops below new_max
            self.max = new_max;
        } else {
            // Expand: resize slots vector
            self.slots.resize_with(new_max as usize, || None);
            self.max = new_max;
        }
    }
}

struct SessionInner {
    /// Outgoing packet ID slab allocator and lifecycle tracker
    outgoing: Mutex<OutgoingSlab>,
    /// Incoming QoS 2 packet ID dedup set
    incoming: Mutex<SmallVec<[u16; 8]>>,
    /// Server-negotiated properties from CONNACK
    server_props: Mutex<ServerProperties>,
}

/// Thread-safe MQTT 5.0 session state
///
/// Clone is cheap — all clones share state via `Arc`.
#[derive(Clone)]
pub struct Session {
    inner: Arc<SessionInner>,
}

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

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

    /// Create a session with a specific max inflight (for testing)
    pub fn with_max_inflight(max: u16) -> Self {
        Self {
            inner: Arc::new(SessionInner {
                outgoing: Mutex::new(OutgoingSlab::new(max)),
                incoming: Mutex::new(SmallVec::new()),
                server_props: Mutex::new(ServerProperties::default()),
            }),
        }
    }

    /// Process CONNACK: apply server properties and determine retransmissions
    pub fn on_connack(&self, connack: &ConnAck) -> Vec<Retransmit> {
        let props = &connack.properties;
        let mut server = self.inner.server_props.lock().unwrap();

        server.receive_maximum = props.receive_maximum.unwrap_or(65535);
        server.maximum_packet_size = props.maximum_packet_size.unwrap_or(0);
        server.topic_alias_maximum = props.topic_alias_maximum.unwrap_or(0);
        server.retain_available = props.retain_available.unwrap_or(1) != 0;
        server.wildcard_sub_available = props.wildcard_subscription_available.unwrap_or(1) != 0;
        server.sub_id_available = props.subscription_identifier_available.unwrap_or(1) != 0;
        server.shared_sub_available = props.shared_subscription_available.unwrap_or(1) != 0;
        server.server_keep_alive = props.server_keep_alive;
        server.session_expiry_interval = props.session_expiry_interval;
        server.assigned_client_id = props.assigned_client_identifier.clone();
        server.response_information = props.response_information.clone();
        server.server_reference = props.server_reference.clone();
        server.maximum_qos = match props.maximum_qos {
            Some(0) => QoS::AtMostOnce,
            Some(1) => QoS::AtLeastOnce,
            _ => QoS::ExactlyOnce,
        };

        // Adjust inflight window to server's receive_maximum
        let receive_max = server.receive_maximum;
        drop(server);

        self.inner.outgoing.lock().unwrap().set_max(receive_max);

        if connack.session_present {
            self.inner.outgoing.lock().unwrap().pending_retransmit()
        } else {
            self.inner.outgoing.lock().unwrap().clear();
            self.inner.incoming.lock().unwrap().clear();
            Vec::new()
        }
    }

    /// Get current server properties (after CONNACK negotiation)
    pub fn server_properties(&self) -> ServerProperties {
        self.inner.server_props.lock().unwrap().clone()
    }

    /// Allocate the next available packet ID
    pub fn alloc_pkid(&self) -> Option<u16> {
        self.inner.outgoing.lock().unwrap().alloc()
    }

    /// Release a packet ID back to the pool (on send failure)
    pub fn release_pkid(&self, pkid: u16) {
        self.inner.outgoing.lock().unwrap().release(pkid);
    }

    /// Track a publish for ACK completion
    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/unsubscribe operation
    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 PUBACK reception
    pub fn on_puback(&self, pkid: u16, reason_code: ReasonCode, props: PubAckProperties) -> Result<(), SessionError> {
        self.inner.outgoing.lock().unwrap().on_puback(pkid, reason_code, props)
    }

    /// Handle PUBREC reception. Returns true if PUBREL should be sent.
    pub fn on_pubrec(&self, pkid: u16, reason_code: ReasonCode) -> Result<bool, SessionError> {
        self.inner.outgoing.lock().unwrap().on_pubrec(pkid, reason_code)
    }

    /// Handle PUBCOMP reception
    pub fn on_pubcomp(&self, pkid: u16, reason_code: ReasonCode, props: PubCompProperties) -> Result<(), SessionError> {
        self.inner.outgoing.lock().unwrap().on_pubcomp(pkid, reason_code, props)
    }

    /// Handle SUBACK reception
    pub fn on_suback(&self, pkid: u16, codes: Vec<ReasonCode>, props: SubAckProperties) {
        self.inner.outgoing.lock().unwrap().on_suback(pkid, codes, props);
    }

    /// Handle UNSUBACK reception
    pub fn on_unsuback(&self, pkid: u16, codes: Vec<ReasonCode>, props: UnsubAckProperties) {
        self.inner.outgoing.lock().unwrap().on_unsuback(pkid, codes, props);
    }

    /// Track an incoming QoS 2 packet ID (returns true if already tracked = duplicate)
    pub fn track_incoming(&self, pkid: u16) -> bool {
        let mut incoming = self.inner.incoming.lock().unwrap();
        if incoming.contains(&pkid) {
            return true;
        }
        incoming.push(pkid);
        false
    }

    /// Release an incoming QoS 2 packet ID (on PUBREL)
    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))
        }
    }

    /// Connection lost unexpectedly — preserve inflight state for reconnection
    pub fn on_connection_lost(&self) {}

    /// User-initiated disconnect — wake all pending tokens with error
    pub fn on_disconnect(&self) {
        self.inner.outgoing.lock().unwrap().wake_all(Error::Disconnected);
    }

    /// Get current receive_maximum from server properties
    pub fn receive_maximum(&self) -> u16 {
        self.inner.server_props.lock().unwrap().receive_maximum
    }
}