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
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
//! MQTT 3.1.1 blocking client implementation
//!
//! Thread model:
//! - Caller thread: publish/subscribe/unsubscribe encode and write packets directly
//! - Read thread: continuously reads from transport, decodes packets, dispatches to session and handler
//! - Keepalive thread: periodically sends PINGREQ, terminates connection on PINGRESP timeout

use std::io::{Read, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use bytes::BytesMut;
use symqtt_codec::v3 as codec;

use crate::pinger::Pinger;
use crate::transport::{Transport, WriteTimeout, Writer};
use crate::v3::error::Error;
use crate::v3::session::Session;
use crate::v3::token::Token;
use crate::v3::{ConnectOptions, InboundHandler, PublishMessage, QoS, SubscribeReturnCode};

/// Blocking MQTT 3.1.1 client
///
/// Thread-safe (`Send + Sync`). A `Client` uniquely owns one broker connection
/// and is not [`Clone`]. Share it across threads with [`std::sync::Arc`]; public
/// methods may be called concurrently through `&Client`.
///
/// # Lifecycle
///
/// A `Client` represents exactly one connection to a broker. It is created via
/// [`Client::connect`]. Dropping a still-connected `Client` sends DISCONNECT
/// and terminates the connection without waiting for background threads and
/// without calling [`InboundHandler::on_disconnect`]. Use [`Client::disconnect`]
/// when the caller needs to wait for those threads to exit.
///
/// ## Connection establishment
///
/// [`Client::connect`] performs the full lifecycle setup:
/// 1. Split the transport into independent read/write halves
/// 2. Spawn the read thread (ready before CONNECT is sent)
/// 3. Send CONNECT and block until CONNACK is received
/// 4. If broker reports `session_present`, retransmit inflight messages from [`Session`]
/// 5. Spawn the keepalive thread (if `keep_alive > 0`)
///
/// ## Disconnection causes
///
/// The connection terminates in one of the following ways:
///
/// - **User-initiated** (`disconnect()`): sends DISCONNECT, wakes all pending
///   tokens with [`Error::Disconnected`], clears session inflight state, and
///   waits for background threads to exit.
/// - **`Drop`**: sends DISCONNECT and wakes pending tokens, but does not wait
///   for background threads and does not call [`InboundHandler::on_disconnect`].
/// - **Ping timeout**: the keepalive thread detects that PINGRESP was not
///   received within `ping_timeout` after sending PINGREQ. Terminates with
///   [`Error::PingTimeout`].
/// - **Transport EOF**: the read thread observes the remote peer closed the
///   TCP connection. Terminates with [`Error::Disconnected`].
/// - **IO error**: the read thread encounters an unrecoverable read error.
///   Terminates with [`Error::Io`].
/// - **Decode error**: the read thread receives malformed data that cannot be
///   decoded as a valid MQTT packet. Terminates with [`Error::Decode`].
///
/// ## Graceful vs ungraceful termination
///
/// - **Graceful** (`disconnect()` or `Drop`): all pending tokens are woken with
///   an error, session inflight state is cleared. The client is done.
/// - **Ungraceful** (connection lost unexpectedly): inflight state in [`Session`]
///   is preserved. The caller can pass the same `Session` to a new `Client` to
///   reconnect, and inflight QoS 1/2 messages will be retransmitted automatically.
///
/// # Example
///
/// Requires the `symqtt-transport` crate.
///
/// ```rust,ignore
/// use std::time::Duration;
/// use symqtt::v3::{Client, ConnectOptions, Session, QoS, PublishMessage, InboundHandler};
/// use symqtt_transport::tcp::TcpTransport;
/// use symqtt_codec::v3 as codec;
///
/// struct MyHandler;
/// impl InboundHandler for MyHandler {
///     fn on_publish(&self, publish: &codec::Publish) {
///         println!("received: {:?}", publish.topic);
///     }
///     fn on_disconnect(&self, _err: &symqtt::v3::Error) {
///         println!("disconnected");
///     }
/// }
///
/// // Create a session — this survives across reconnections
/// let session = Session::new();
///
/// let opts = ConnectOptions {
///     client_id: "my-client".to_string(),
///     clean_session: true,
///     keep_alive: Duration::from_secs(30),
///     will: None,
///     username: None,
///     password: None,
///     connect_timeout: None,
///     ping_timeout: None,
/// };
///
/// // Connect
/// let transport = TcpTransport::builder("127.0.0.1:1883").connect().unwrap();
/// let client = Client::connect(opts, MyHandler, session.clone(), transport).unwrap();
///
/// // Subscribe
/// let token = client.subscribe(&[("sensor/+", QoS::AtLeastOnce)], None).unwrap();
/// token.wait().unwrap();
///
/// // Publish
/// let msg = PublishMessage::new("sensor/temp", bytes::Bytes::from("25.3"))
///     .qos(QoS::AtLeastOnce);
/// if let Some(token) = client.publish(&msg).unwrap() {
///     token.wait().unwrap();
/// }
///
/// // Disconnect gracefully
/// client.disconnect(Some(Duration::from_secs(5)));
///
/// // To reconnect after an unexpected disconnect, reuse the same session:
/// // let transport2 = TcpTransport::builder("127.0.0.1:1883").connect().unwrap();
/// // let client2 = Client::connect(opts2, MyHandler, session, transport2).unwrap();
/// ```
pub struct Client<H: InboundHandler, T: Transport> {
    inner: Arc<ClientInner<H, T::Write>>,
}

/// Shared connection state behind `Arc`.
///
/// `Client` holds one clone as the unique user-facing owner. The read and
/// keepalive threads hold additional clones for the connection lifetime.
struct ClientInner<H, W> {
    /// Inbound message callback handler
    handler: H,
    /// Keepalive state machine tracking send/receive timestamps
    pinger: Pinger,
    /// Session state managing packet ID allocation and inflight message tracking
    session: Session,
    /// Connection liveness flag; CAS ensures `terminate` runs exactly once
    alive: AtomicBool,
    /// Connection configuration
    opts: ConnectOptions,
    /// Transport write half, mutex-guarded to serialize concurrent writes
    writer: Mutex<Option<Writer<W>>>,
    /// Stop signal sender for the keepalive thread
    stop_tx: Mutex<Option<mpsc::SyncSender<()>>>,
    /// Receiver to wait for read thread exit
    read_done_rx: Mutex<Option<mpsc::Receiver<()>>>,
    /// Receiver to wait for keepalive thread exit
    keepalive_done_rx: Mutex<Option<mpsc::Receiver<()>>>,
}

impl<H: InboundHandler, T: Transport> Client<H, T> {
    /// Establish an MQTT connection and return a ready-to-use client
    ///
    /// Performs the full CONNECT/CONNACK handshake, retransmits any pending
    /// inflight messages from the session if the broker reports `session_present`,
    /// and spawns background threads for reading and keepalive.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] when transport establishment fails.
    ///
    /// Returns [`Error::ConnectRefused`] when the broker rejects the connection,
    /// carrying the specific return code.
    ///
    /// Returns [`Error::Timeout`] when CONNACK is not received within `connect_timeout`.
    pub fn connect(opts: ConnectOptions, handler: H, session: Session, transport: T) -> Result<Self, Error> {
        log::debug!("connecting to broker as client_id={:?}", opts.client_id);
        let pinger = Pinger::new(opts.keep_alive, opts.ping_timeout());

        // Split into independent read/write halves for concurrent use across threads
        let (reader, writer_half) = transport.split();

        // read_down: read thread holds tx as a drop-guard — rx unblocks when thread exits
        let (read_down_tx, read_down_rx) = mpsc::sync_channel::<()>(1);
        // connack: read thread forwards CONNACK to the caller blocked in handshake()
        let (connack_tx, connack_rx) = mpsc::sync_channel::<codec::ConnAck>(1);

        let inner = Arc::new(ClientInner {
            opts,
            pinger,
            handler,
            session,
            writer: Mutex::new(Some(Writer {
                stream: writer_half,
                buf: BytesMut::with_capacity(4096),
            })),
            alive: AtomicBool::new(false),
            stop_tx: Mutex::new(None),
            read_done_rx: Mutex::new(Some(read_down_rx)),
            keepalive_done_rx: Mutex::new(None),
        });

        // Spawn read thread BEFORE sending CONNECT so it's ready for CONNACK
        let inner_ = inner.clone();
        std::thread::Builder::new()
            .name(format!("mqtt-{}-read-loop", inner.opts.client_id))
            .spawn(move || {
                let _guard = read_down_tx;
                inner_.read(reader, connack_tx);
            })?;

        if let Err(e) = inner.handshake(connack_rx) {
            log::warn!("handshake unsuccessful: {e}");
            // Handshake failed — close writer so read thread sees EOF and exits
            inner.alive.store(false, Ordering::SeqCst);
            if let Some(w) = inner.writer.lock().unwrap().take() {
                let _ = w.shutdown();
            }
            return Err(e);
        }

        // Spawn keepalive thread only when keep_alive > 0;
        // stop_tx allows disconnect() to signal this thread to exit
        if inner.opts.keep_alive.as_secs() > 0 {
            let (stop_tx, stop_rx) = mpsc::sync_channel::<()>(1);
            let (keepalive_down_tx, keepalive_down_rx) = mpsc::sync_channel::<()>(1);

            *inner.stop_tx.lock().unwrap() = Some(stop_tx);
            *inner.keepalive_done_rx.lock().unwrap() = Some(keepalive_down_rx);

            let inner_ = inner.clone();
            std::thread::Builder::new()
                .name(format!("mqtt-{}-keepalive-loop", inner_.opts.client_id))
                .spawn(move || {
                    let _guard = keepalive_down_tx;
                    inner_.keepalive(stop_rx);
                })?;
        }

        log::debug!("connected successfully as client_id={:?}", inner.opts.client_id);
        Ok(Self { inner })
    }

    /// Whether the client is still connected to the broker
    pub fn is_connected(&self) -> bool {
        self.inner.alive.load(Ordering::Relaxed)
    }

    /// Gracefully disconnect from the broker
    ///
    /// Sends a DISCONNECT packet, wakes all pending tokens with an error,
    /// and waits for background threads to exit. The `timeout` parameter
    /// controls how long to wait for thread shutdown; `None` waits indefinitely.
    ///
    /// Dropping a still-connected [`Client`] also sends DISCONNECT, but does
    /// not wait for background threads and does not call
    /// [`InboundHandler::on_disconnect`].
    pub fn disconnect(&self, timeout: Option<Duration>) {
        log::debug!("disconnecting gracefully");
        let deadline = timeout.map(|t| Instant::now() + t);

        self.inner.graceful_close(timeout, true);

        // Wait for background threads to exit, bounded by deadline
        wait_thread(self.inner.read_done_rx.lock().unwrap().take(), deadline);
        wait_thread(self.inner.keepalive_done_rx.lock().unwrap().take(), deadline);
    }

    /// Publish a message to the broker
    ///
    /// # Returns
    ///
    /// `Ok(None)` for QoS 0 (fire-and-forget, no acknowledgement expected).
    /// `Ok(Some(token))` for QoS 1/2 where the caller blocks on the token
    /// until the broker sends the corresponding ACK.
    ///
    /// # Errors
    ///
    /// Returns [`Error::WindowFull`] when the inflight window has no available packet IDs.
    ///
    /// Returns [`Error::Disconnected`] when the connection is already closed.
    ///
    /// Returns [`Error::Io`] when writing to the transport fails.
    pub fn publish(&self, msg: &PublishMessage<'_>) -> Result<Option<Token<()>>, Error> {
        log::debug!(
            "publishing to topic={:?} qos={:?} retain={} payload_len={}",
            msg.topic,
            msg.qos,
            msg.retain,
            msg.payload.len()
        );

        let mut publish = codec::Publish::from(msg);

        // QoS 0: fire-and-forget — send immediately, no tracking needed
        if matches!(msg.qos, QoS::AtMostOnce) {
            self.inner.send_packet(&codec::Packet::Publish(publish), msg.timeout)?;
            return Ok(None);
        }

        // QoS 1/2: allocate a packet ID from the inflight window
        let pkid = self.inner.session.alloc_pkid().ok_or(Error::WindowFull)?;
        publish.pkid = Some(pkid);

        // Register the publish in session state BEFORE sending — this ensures
        // the ACK handler can find it even if the response arrives instantly.
        let rx = self.inner.session.track_publish(pkid, publish.clone());

        // Send the packet; on failure, release the packet ID back to the pool
        // so it can be reused by future operations.
        if let Err(e) = self.inner.send_packet(&codec::Packet::Publish(publish), msg.timeout) {
            log::warn!("failed to send publish for pkid={pkid}: {e}");
            self.inner.session.release_pkid(pkid);
            return Err(e);
        }

        log::debug!(
            "publish sent, pkid={pkid} topic={:?} qos={:?} payload_len={}",
            msg.topic,
            msg.qos,
            msg.payload.len()
        );
        Ok(Some(Token::new(rx)))
    }

    /// Subscribe to one or more topic filters
    ///
    /// Returns a [`Token`] that resolves to the granted QoS levels for each
    /// filter once SUBACK is received.
    ///
    /// # Errors
    ///
    /// Returns [`Error::WindowFull`] when the inflight window has no available packet IDs.
    ///
    /// Returns [`Error::Io`] when writing to the transport fails.
    pub fn subscribe(
        &self,
        topics: &[(&str, QoS)],
        timeout: Option<Duration>,
    ) -> Result<Token<Vec<SubscribeReturnCode>>, Error> {
        let pkid = self.inner.session.alloc_pkid().ok_or(Error::WindowFull)?;

        let pkt = codec::Packet::Subscribe(codec::Subscribe {
            pkid,
            filters: topics.iter().copied().map(codec::SubscribeFilter::from).collect(),
        });

        let rx = self.inner.session.track_sub(pkid);

        if let Err(e) = self.inner.send_packet(&pkt, timeout) {
            log::warn!("failed to send subscribe for pkid={pkid}: {e}");
            self.inner.session.release_pkid(pkid);
            return Err(e);
        }

        log::debug!("subscribe sent, pkid={pkid} filters={topics:?}");
        Ok(Token::new(rx))
    }

    /// Unsubscribe from one or more topics
    ///
    /// Returns a [`Token`] that resolves once UNSUBACK is received.
    ///
    /// # Errors
    ///
    /// Returns [`Error::WindowFull`] when the inflight window has no available packet IDs.
    ///
    /// Returns [`Error::Io`] when writing to the transport fails.
    pub fn unsubscribe(&self, topics: &[&str], timeout: Option<Duration>) -> Result<Token<()>, Error> {
        let pkid = self.inner.session.alloc_pkid().ok_or(Error::WindowFull)?;

        let pkt = codec::Packet::Unsubscribe(codec::Unsubscribe {
            pkid,
            topics: topics.iter().map(ToString::to_string).collect(),
        });

        let rx = self.inner.session.track_sub(pkid);

        if let Err(e) = self.inner.send_packet(&pkt, timeout) {
            log::warn!("failed to send unsubscribe for pkid={pkid}: {e}");
            self.inner.session.release_pkid(pkid);
            return Err(e);
        }

        log::debug!("unsubscribe sent, pkid={pkid} topics={topics:?}");
        Ok(Token::new(rx))
    }
}

impl<H: InboundHandler, T: Transport> Drop for Client<H, T> {
    fn drop(&mut self) {
        if !self.inner.alive.load(Ordering::Relaxed) {
            return;
        }
        log::debug!("client dropped, sending DISCONNECT");
        self.inner.graceful_close(Some(Duration::from_secs(1)), false);
    }
}

impl<H: InboundHandler, W: Write + WriteTimeout + Send> ClientInner<H, W> {
    /// Perform the CONNECT/CONNACK handshake
    ///
    /// Sends CONNECT, blocks waiting for CONNACK from the read thread channel.
    /// On success, checks `session_present` and retransmits any inflight
    /// messages from the previous session.
    fn handshake(&self, connack_rx: mpsc::Receiver<codec::ConnAck>) -> Result<(), Error> {
        let deadline = self.opts.connect_timeout.map(|v| Instant::now() + v);

        // Send CONNECT packet and mark connection as alive so read thread
        // can start dispatching packets.
        let connect = codec::Connect::from(&self.opts);
        self.send_packet(&codec::Packet::Connect(connect), self.opts.connect_timeout)?;
        self.alive.store(true, Ordering::SeqCst);

        // Block until the read thread forwards CONNACK via the channel.
        // Use remaining time from the original deadline to avoid double-waiting.
        let connack = match deadline {
            Some(ddl) => connack_rx
                .recv_timeout(ddl.saturating_duration_since(Instant::now()))
                .map_err(|_| Error::Timeout)?,
            None => connack_rx.recv().map_err(|_| Error::Disconnected)?,
        };

        if connack.return_code != codec::ConnectReturnCode::Accepted {
            return Err(Error::ConnectRefused(connack.return_code));
        }

        log::debug!("connack received: session_present={}", connack.session_present);

        // If the broker preserved session state, retransmit all inflight
        // messages (PUBLISH with DUP=1 for QoS 1/2, PUBREL for QoS 2 mid-flow).
        let retransmits = self.session.on_connect(connack.session_present);
        log::debug!("retransmitting {} inflight messages", retransmits.len());
        for item in retransmits {
            let pkt = codec::Packet::from(item);
            if let Err(e) = self.send_packet(&pkt, None) {
                log::warn!("failed to retransmit packet: {e}");
            }
        }

        Ok(())
    }

    /// Send DISCONNECT and run graceful `terminate`. Does not wait for threads.
    ///
    /// `notify` controls whether [`InboundHandler::on_disconnect`] is invoked.
    /// `Drop` passes `false` so user callbacks are not run during destruction.
    fn graceful_close(&self, timeout: Option<Duration>, notify: bool) {
        let pkt = codec::Packet::Disconnect(codec::Disconnect);
        let _ = self.send_packet(&pkt, timeout);
        self.terminate(Error::Disconnected, true, notify);
    }

    /// Terminate the connection and clean up resources
    ///
    /// Uses CAS on `alive` to guarantee single execution.
    /// - `graceful = true` (`disconnect()` or `Drop`): wakes all pending tokens with error
    /// - `graceful = false` (unexpected loss): preserves inflight state for reconnect retransmission
    /// - `notify = false`: skip [`InboundHandler::on_disconnect`] (used by `Drop`)
    fn terminate(&self, error: Error, graceful: bool, notify: bool) {
        // CAS guarantees single execution: if alive was already false,
        // another thread already ran terminate — bail out immediately.
        if !self.alive.swap(false, Ordering::SeqCst) {
            return;
        }
        log::debug!("terminating connection: graceful={graceful} reason={error}");

        // Shut down the writer to close the TCP connection and cause the
        // read thread to see EOF on its next read() call.
        if let Some(w) = self.writer.lock().unwrap().take() {
            let _ = w.shutdown();
        }

        // Drop the stop_tx sender — this unblocks the keepalive thread's
        // recv_timeout() with a Disconnected error, causing it to exit.
        self.stop_tx.lock().unwrap().take();

        // Graceful: user-initiated, no reconnect expected — wake all tokens
        // so callers stop blocking. Ungraceful: preserve inflight state so
        // the next Client can retransmit after reconnection.
        if graceful {
            self.session.on_disconnect();
        } else {
            self.session.on_connection_lost();
        }
        if notify {
            self.handler.on_disconnect(&error);
        }
    }

    /// Read thread main loop
    ///
    /// Reads bytes from transport into a buffer, then calls `drain_decoded_packets`
    /// to decode complete packets and dispatch them. Terminates the connection
    /// on EOF or IO error.
    fn read(&self, mut reader: impl Read, connack_tx: mpsc::SyncSender<codec::ConnAck>) {
        let mut tmp = [0u8; 4096];
        let mut buf = BytesMut::with_capacity(8192);

        loop {
            // First drain any complete packets already buffered from previous
            // reads — a single TCP read may contain multiple MQTT packets.
            if let Err(e) = self.drain_decoded_packets(&mut buf, &connack_tx) {
                self.terminate(e, false, true);
                return;
            }

            // Block on the next TCP read. EOF (Ok(0)) means the remote closed
            // the connection; WouldBlock/TimedOut when alive=false means we are
            // shutting down cleanly (writer was closed by terminate()).
            let n = match reader.read(&mut tmp) {
                Ok(0) => break,
                Ok(n) => n,
                Err(ref e) => {
                    if (e.kind() == std::io::ErrorKind::TimedOut || e.kind() == std::io::ErrorKind::WouldBlock)
                        && !self.alive.load(Ordering::SeqCst)
                    {
                        return;
                    } else {
                        break;
                    }
                }
            };
            buf.extend_from_slice(&tmp[..n]);
        }

        self.terminate(Error::Disconnected, false, true);
    }

    /// Keepalive thread main loop
    ///
    /// Polls the [`Pinger`] state machine in a loop:
    /// - `Sleep(dur)`: wait for next check while listening for the stop signal
    /// - `SendPing`: send PINGREQ and record the send timestamp
    /// - `TimedOut`: PINGRESP was not received in time, terminate the connection
    fn keepalive(&self, stop_rx: mpsc::Receiver<()>) {
        let ping_timeout = self.opts.ping_timeout.or(Some(Duration::from_secs(3)));
        loop {
            match self.pinger.poll() {
                crate::pinger::PingerAction::Sleep(dur) => match stop_rx.recv_timeout(dur) {
                    Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => return,
                    Err(mpsc::RecvTimeoutError::Timeout) => {}
                },
                crate::pinger::PingerAction::SendPing => {
                    if let Err(e) = self.send_packet(&codec::Packet::PingReq(codec::PingReq), ping_timeout) {
                        log::warn!("failed to send PingReq, terminating connection: {e}");
                        self.terminate(e, false, true);
                        return;
                    }
                    self.pinger.record_ping_sent();
                }
                crate::pinger::PingerAction::TimedOut => {
                    log::warn!("ping response timed out, terminating connection");
                    self.terminate(Error::PingTimeout, false, true);
                    return;
                }
            }
        }
    }

    /// Decode all complete packets from the buffer and dispatch each one
    ///
    /// CONNACK is handled specially: forwarded via channel to the caller thread
    /// blocked in `handshake`. All other packets go through `dispatch_packet`.
    fn drain_decoded_packets(
        &self,
        buf: &mut BytesMut,
        connack_tx: &mpsc::SyncSender<codec::ConnAck>,
    ) -> Result<(), Error> {
        loop {
            match codec::Packet::decode(buf) {
                Ok(Some(pkt)) => {
                    self.pinger.record_received();
                    if let codec::Packet::ConnAck(connack) = pkt {
                        let _ = connack_tx.try_send(connack);
                        continue;
                    }
                    self.dispatch_packet(pkt)?;
                }
                Ok(None) => return Ok(()),
                Err(e) => {
                    log::warn!("packet decode error: {e}");
                    return Err(Error::Decode(e));
                }
            }
        }
    }

    /// Route a decoded packet to the appropriate session state transition or handler callback
    fn dispatch_packet(&self, pkt: codec::Packet) -> Result<(), Error> {
        match pkt {
            // QoS 1 outgoing: broker acknowledged receipt — complete the flow
            codec::Packet::PubAck(codec::PubAck { pkid }) => {
                log::debug!("received PubAck pkid={pkid}");
                let _ = self.session.on_puback(pkid);
            }
            // QoS 2 outgoing: broker received PUBLISH — advance to PUBREL stage
            codec::Packet::PubRec(codec::PubRec { pkid }) => {
                log::debug!("received PubRec pkid={pkid}, sending PubRel");
                let _ = self.session.on_pubrec(pkid);
                self.send_packet(&codec::Packet::PubRel(codec::PubRel { pkid }), None)?;
            }
            // QoS 2 outgoing: broker confirmed PUBREL — complete the flow
            codec::Packet::PubComp(codec::PubComp { pkid }) => {
                log::debug!("received PubComp pkid={pkid}");
                let _ = self.session.on_pubcomp(pkid);
            }
            // Inbound PUBLISH from broker: handle per QoS level
            codec::Packet::Publish(publish) => {
                log::debug!(
                    "received Publish topic={:?} qos={:?} pkid={:?} payload_len={}",
                    publish.topic,
                    publish.qos,
                    publish.pkid,
                    publish.payload.len()
                );
                self.handle_inbound_publish(&publish)?;
            }
            // SUBACK: deliver granted QoS codes to the subscribe token
            codec::Packet::SubAck(codec::SubAck { pkid, return_codes }) => {
                log::debug!("received SubAck pkid={pkid} codes={return_codes:?}");
                self.session.on_suback(pkid, return_codes);
            }
            // UNSUBACK: notify the unsubscribe token of completion
            codec::Packet::UnsubAck(codec::UnsubAck { pkid }) => {
                log::debug!("received UnsubAck pkid={pkid}");
                self.session.on_unsuback(pkid);
            }
            // PINGRESP: record that broker is alive, reset ping timeout
            codec::Packet::PingResp(_) => {
                log::debug!("received PingResp");
                self.pinger.record_ping_response();
            }
            // QoS 2 inbound: broker releasing message — remove from dedup set
            // and confirm with PUBCOMP
            codec::Packet::PubRel(codec::PubRel { pkid }) => {
                log::debug!("received PubRel pkid={pkid}, sending PubComp");
                let _ = self.session.release_incoming(pkid);
                self.send_packet(&codec::Packet::PubComp(codec::PubComp { pkid }), None)?;
            }
            _ => {}
        }
        Ok(())
    }

    /// Encode a packet and write it to the transport
    ///
    /// Acquires the writer lock, encodes into the internal buffer, writes to the
    /// underlying stream, and flushes. Updates the pinger's last-sent timestamp
    /// on success.
    fn send_packet(&self, pkt: &codec::Packet, timeout: Option<Duration>) -> Result<(), Error> {
        // Reject sends on a dead connection, except CONNECT which bootstraps it
        if !self.alive.load(Ordering::Relaxed) && !matches!(pkt, codec::Packet::Connect(_)) {
            return Err(Error::Disconnected);
        }
        {
            let mut guard = self.writer.lock().unwrap();
            let Writer { stream, buf } = guard.as_mut().ok_or(Error::Disconnected)?;
            // Encode into an intermediate buffer to avoid partial writes on
            // error — the stream sees a complete packet or nothing.
            buf.clear();
            pkt.encode(buf)?;
            log::trace!("sending {} ({} bytes)", packet_name(pkt), buf.len());
            stream.set_write_timeout(timeout)?;
            stream.write_all(buf)?;
            stream.flush()?;
        }
        // Record activity so the keepalive timer knows we don't need a PINGREQ yet
        self.pinger.record_sent();
        Ok(())
    }

    /// Handle an inbound PUBLISH from the broker according to its QoS level
    ///
    /// - QoS 0: deliver to handler immediately
    /// - QoS 1: deliver to handler, then reply with PUBACK
    /// - QoS 2: deduplicate via session, deliver if not duplicate, then reply with PUBREC
    fn handle_inbound_publish(&self, publish: &codec::Publish) -> Result<(), Error> {
        match publish.qos {
            QoS::AtMostOnce => {
                // QoS 0: no acknowledgement, deliver immediately
                self.handler.on_publish(publish);
            }
            QoS::AtLeastOnce => {
                // QoS 1: deliver first, then acknowledge with PUBACK.
                // The broker may redeliver if PUBACK is lost (at-least-once semantics).
                self.handler.on_publish(publish);
                if let Some(pkid) = publish.pkid {
                    log::debug!("sending PubAck pkid={pkid}");
                    self.send_packet(&codec::Packet::PubAck(codec::PubAck { pkid }), None)?;
                }
            }
            QoS::ExactlyOnce => {
                // QoS 2: deduplicate first — the broker may resend if PUBREC was lost.
                // Only deliver to handler on the first reception of this packet ID.
                // Always respond with PUBREC to advance the broker's state machine.
                if let Some(pkid) = publish.pkid {
                    let is_dup = self.session.track_incoming(pkid);
                    if !is_dup {
                        self.handler.on_publish(publish);
                    }
                    log::debug!("sending PubRec pkid={pkid} dup={is_dup}");
                    self.send_packet(&codec::Packet::PubRec(codec::PubRec { pkid }), None)?;
                }
            }
        }
        Ok(())
    }
}

/// Wait for a thread-done signal with an optional deadline
fn wait_thread(rx: Option<mpsc::Receiver<()>>, deadline: Option<Instant>) {
    if let Some(rx) = rx {
        match deadline {
            Some(dl) => {
                let _ = rx.recv_timeout(dl.saturating_duration_since(Instant::now()));
            }
            None => {
                let _ = rx.recv();
            }
        }
    }
}

fn packet_name(pkt: &codec::Packet) -> &'static str {
    match pkt {
        codec::Packet::Connect(_) => "CONNECT",
        codec::Packet::ConnAck(_) => "CONNACK",
        codec::Packet::Publish(_) => "PUBLISH",
        codec::Packet::PubAck(_) => "PUBACK",
        codec::Packet::PubRec(_) => "PUBREC",
        codec::Packet::PubRel(_) => "PUBREL",
        codec::Packet::PubComp(_) => "PUBCOMP",
        codec::Packet::Subscribe(_) => "SUBSCRIBE",
        codec::Packet::SubAck(_) => "SUBACK",
        codec::Packet::Unsubscribe(_) => "UNSUBSCRIBE",
        codec::Packet::UnsubAck(_) => "UNSUBACK",
        codec::Packet::PingReq(_) => "PINGREQ",
        codec::Packet::PingResp(_) => "PINGRESP",
        codec::Packet::Disconnect(_) => "DISCONNECT",
    }
}