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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
//! MQTT 5.0 blocking client implementation
//!
//! Thread model mirrors v3: caller thread encodes/sends, read thread dispatches,
//! keepalive thread pings. Adds CONNACK negotiation, topic alias management,
//! enhanced AUTH, and reason code propagation.

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::QoS;
use symqtt_codec::v5 as codec;
use symqtt_codec::v5::{AuthProperties, AuthStatus};

use crate::pinger::Pinger;
use crate::transport::{Transport, WriteTimeout, Writer};
use crate::v5::auth::{AuthHandler, NoOpAuthHandler};
use crate::v5::error::Error;
use crate::v5::session::{Retransmit, ServerProperties, Session};
use crate::v5::token::{PublishAckDetail, Token};
use crate::v5::topic_alias::{InboundTopicAliases, OutboundTopicAliases};
use crate::v5::{ConnectOptions, InboundHandler, PublishMessage, SubscribeFilter};

/// Packet received during the CONNECT handshake phase
enum HandshakePacket {
    ConnAck(codec::ConnAck),
    Auth(codec::Auth),
}

/// Blocking MQTT 5.0 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`] (or [`Client::connect_with_auth`] for enhanced auth).
/// 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 (with optional multi-round AUTH)
/// 4. Apply CONNACK-negotiated server properties (Receive Maximum, Topic Alias, etc.)
/// 5. If broker reports `session_present`, retransmit inflight messages from [`Session`]
/// 6. Spawn the keepalive thread (using server-overridden or client keep_alive)
///
/// ## Disconnection causes
///
/// The connection terminates in one of the following ways:
///
/// - **User-initiated** (`disconnect()`): sends DISCONNECT with a reason code, wakes all
///   pending tokens with [`Error::Disconnected`], and waits for background threads to exit.
/// - **`Drop`**: sends DISCONNECT (`Success`) and wakes pending tokens, but does
///   not wait for background threads and does not call [`InboundHandler::on_disconnect`].
/// - **Server-initiated**: the broker sends a DISCONNECT packet with a reason code.
///   Terminates with [`Error::ServerDisconnect`].
/// - **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 closed the TCP connection.
///   Terminates with [`Error::Disconnected`].
/// - **IO error**: the read thread encounters an unrecoverable read error.
///   Terminates with [`Error::Io`].
///
/// ## 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::v5::{Client, ConnectOptions, Session, QoS, PublishMessage, InboundHandler};
/// use symqtt::v5::{Publish, Error, Disconnect, SubscribeFilter};
/// use symqtt_transport::tcp::TcpTransport;
/// use symqtt_codec::v5::ReasonCode;
///
/// struct MyHandler;
/// impl InboundHandler for MyHandler {
///     fn on_publish(&self, publish: &Publish) {
///         println!("received: {:?}", publish.topic);
///     }
///     fn on_disconnect(&self, _err: &Error) {
///         println!("disconnected");
///     }
///     fn on_server_disconnect(&self, dc: &Disconnect) {
///         println!("server disconnect: {:?}", dc.reason_code);
///     }
/// }
///
/// // Session survives across reconnections
/// let session = Session::new();
///
/// let opts = ConnectOptions {
///     client_id: "my-v5-client".to_string(),
///     keep_alive: Duration::from_secs(30),
///     ..Default::default()
/// };
///
/// // 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(
///     &[SubscribeFilter::new("sensor/+", QoS::AtLeastOnce)],
///     None,
///     None,
/// ).unwrap();
/// let codes = token.wait_timeout(Duration::from_secs(5)).unwrap();
/// assert!(codes.iter().all(|c| c.is_success()));
///
/// // Publish
/// let msg = PublishMessage::new("sensor/temp", bytes::Bytes::from("25.3"))
///     .qos(QoS::AtLeastOnce);
/// if let Some(token) = client.publish(&msg).unwrap() {
///     let detail = token.wait_timeout(Duration::from_secs(5)).unwrap();
///     assert!(detail.reason_code.is_success());
/// }
///
/// // Disconnect gracefully
/// client.disconnect(ReasonCode::Success, 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, A: AuthHandler = NoOpAuthHandler> {
    inner: Arc<ClientInner<H, T::Write, A>>,
}

impl<H: InboundHandler, T: Transport, A: AuthHandler> std::fmt::Debug for Client<H, T, A> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("connected", &self.is_connected())
            .finish_non_exhaustive()
    }
}

/// 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, A> {
    /// Inbound message callback handler
    handler: H,
    /// Enhanced authentication handler for multi-round AUTH flows
    auth_handler: A,
    /// Keepalive state machine tracking send/receive timestamps
    pinger: Pinger,
    /// Session state managing packet ID allocation and inflight 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<()>>>,
    /// Outbound topic alias table (client → server), sized from CONNACK
    outbound_aliases: Mutex<OutboundTopicAliases>,
    /// Inbound topic alias table (server → client), sized from CONNECT
    inbound_aliases: Mutex<InboundTopicAliases>,
    /// Channel for re-authentication result delivery
    reauth_tx: Mutex<Option<mpsc::SyncSender<Result<(), Error>>>>,
}

impl<H: InboundHandler, T: Transport> Client<H, T, NoOpAuthHandler> {
    /// Establish an MQTT 5.0 connection and return a ready-to-use client
    ///
    /// Convenience wrapper over [`Client::connect_with_auth`] that uses
    /// [`NoOpAuthHandler`] (no enhanced authentication).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] when transport operations fail.
    ///
    /// Returns [`Error::ConnectRefused`] when the broker rejects the connection,
    /// carrying the reason code and optional reason string.
    ///
    /// Returns [`Error::Timeout`] when CONNACK is not received within `connect_timeout`.
    ///
    /// # Example
    ///
    /// Requires the `symqtt-transport` crate.
    ///
    /// ```rust,ignore
    /// use std::time::Duration;
    /// use symqtt::v5::{Client, ConnectOptions, Session, InboundHandler, Publish, Error};
    /// use symqtt_transport::tcp::TcpTransport;
    ///
    /// struct Handler;
    /// impl InboundHandler for Handler {
    ///     fn on_publish(&self, _msg: &Publish) {}
    /// }
    ///
    /// let opts = ConnectOptions {
    ///     client_id: "example".to_string(),
    ///     connect_timeout: Some(Duration::from_secs(5)),
    ///     ..Default::default()
    /// };
    /// let transport = TcpTransport::builder("127.0.0.1:1883").connect().unwrap();
    /// let client = Client::connect(opts, Handler, Session::new(), transport).unwrap();
    /// ```
    pub fn connect(opts: ConnectOptions, handler: H, session: Session, transport: T) -> Result<Self, Error> {
        Self::connect_with_auth(opts, handler, session, transport, NoOpAuthHandler)
    }
}

impl<H: InboundHandler, T: Transport, A: AuthHandler> Client<H, T, A> {
    /// Establish a connection with enhanced authentication support
    ///
    /// Performs the full CONNECT/CONNACK handshake (including multi-round AUTH
    /// exchanges if `auth_method` is set), applies server-negotiated properties,
    /// retransmits pending inflight messages, and spawns background threads.
    ///
    /// # Errors
    ///
    /// Returns [`Error::Io`] when transport operations fail.
    ///
    /// Returns [`Error::ConnectRefused`] when the broker rejects the connection.
    ///
    /// Returns [`Error::Timeout`] when CONNACK is not received within `connect_timeout`.
    ///
    /// Returns [`Error::AuthFailed`] when the enhanced authentication flow is
    /// aborted by the handler or rejected by the server.
    ///
    /// # Example
    ///
    /// Requires the `symqtt-transport` crate.
    ///
    /// ```rust,ignore
    /// use std::time::Duration;
    /// use bytes::Bytes;
    /// use symqtt::v5::{Client, ConnectOptions, Session, InboundHandler, Publish, Error};
    /// use symqtt::v5::AuthHandler;
    /// use symqtt_transport::tcp::TcpTransport;
    ///
    /// struct Handler;
    /// impl InboundHandler for Handler {
    ///     fn on_publish(&self, _msg: &Publish) {}
    /// }
    ///
    /// struct ScramAuth;
    /// impl AuthHandler for ScramAuth {
    ///     fn on_auth_continue(&self, _server_data: Option<&Bytes>) -> Option<Bytes> {
    ///         Some(Bytes::from_static(b"client-proof"))
    ///     }
    /// }
    ///
    /// let opts = ConnectOptions {
    ///     client_id: "scram-client".to_string(),
    ///     auth_method: Some("SCRAM-SHA-256".to_string()),
    ///     ..Default::default()
    /// };
    /// let transport = TcpTransport::builder("127.0.0.1:1883").connect().unwrap();
    /// let client = Client::connect_with_auth(
    ///     opts, Handler, Session::new(), transport, ScramAuth,
    /// ).unwrap();
    /// ```
    pub fn connect_with_auth(
        opts: ConnectOptions,
        handler: H,
        session: Session,
        transport: T,
        auth_handler: A,
    ) -> Result<Self, Error> {
        log::debug!("connecting 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);
        // handshake: read thread forwards CONNACK/AUTH to the caller blocked in handshake()
        let (handshake_tx, handshake_rx) = mpsc::sync_channel::<HandshakePacket>(4);

        // Topic alias tables start empty; sized after CONNACK
        let client_alias_max = opts.topic_alias_maximum.unwrap_or(0);

        let inner = Arc::new(ClientInner {
            opts,
            pinger,
            handler,
            session,
            auth_handler,
            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),
            outbound_aliases: Mutex::new(OutboundTopicAliases::new(0)), // sized after CONNACK
            inbound_aliases: Mutex::new(InboundTopicAliases::new(client_alias_max)),
            reauth_tx: 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!("m5-r-{}", inner.opts.client_id))
            .spawn(move || {
                let _guard = read_down_tx;
                inner_.read_loop(reader, handshake_tx);
            })?;

        // Perform CONNECT/CONNACK handshake (may include multi-round AUTH)
        if let Err(e) = inner.handshake(handshake_rx) {
            log::warn!("handshake failed: {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);
        }

        // Server may override keepalive via CONNACK property; update pinger accordingly
        let effective_keepalive = inner.effective_keepalive();
        inner.pinger.set_keepalive(effective_keepalive);

        // Spawn keepalive thread only when effective keep_alive > 0;
        // stop_tx allows disconnect() to signal this thread to exit
        if effective_keepalive.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!("m5-ka-{}", inner_.opts.client_id))
                .spawn(move || {
                    let _guard = keepalive_down_tx;
                    inner_.keepalive(stop_rx);
                })?;
        }

        log::debug!("connected successfully");
        Ok(Self { inner })
    }

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

    /// Get negotiated server properties
    pub fn server_properties(&self) -> ServerProperties {
        self.inner.session.server_properties()
    }

    /// Publish a message to the broker
    ///
    /// Validates the message against server-negotiated constraints (max QoS,
    /// retain support) before sending. Applies topic alias compression when
    /// the server supports it.
    ///
    /// # 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 with reason code.
    ///
    /// # Errors
    ///
    /// Returns [`Error::QosNotSupported`] when requested QoS exceeds server maximum.
    ///
    /// Returns [`Error::RetainNotSupported`] when retain is set but server disallows it.
    ///
    /// Returns [`Error::WindowFull`] when the inflight window has no available packet IDs.
    ///
    /// Returns [`Error::Disconnected`] when the connection is already closed.
    ///
    /// Returns [`Error::PacketTooLarge`] when the encoded packet exceeds server limit.
    pub fn publish(&self, msg: &PublishMessage<'_>) -> Result<Option<Token<PublishAckDetail>>, Error> {
        log::debug!(
            "publishing topic={:?} qos={:?} retain={} payload_len={}",
            msg.topic,
            msg.qos,
            msg.retain,
            msg.payload.len()
        );

        // Validate against server constraints
        let server = self.inner.session.server_properties();
        if msg.qos > server.maximum_qos {
            return Err(Error::QosNotSupported {
                requested: msg.qos,
                max: server.maximum_qos,
            });
        }
        if msg.retain && !server.retain_available {
            return Err(Error::RetainNotSupported);
        }

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

        // Apply topic alias (outbound)
        if let Some((alias, ok)) = self.inner.outbound_aliases.lock().unwrap().resolve(msg.topic) {
            publish.properties.topic_alias = Some(alias);
            if ok {
                publish.topic = String::new(); // send empty topic when alias is known
            }
        }

        // QoS 0: fire and forget
        if matches!(msg.qos, QoS::AtMostOnce) {
            let pkt = codec::Packet::Publish(publish);
            self.inner.send_packet(&pkt, msg.timeout)?;
            return Ok(None);
        }

        // QoS 1/2: allocate packet ID
        let pkid = self
            .inner
            .session
            .alloc_pkid()
            .ok_or(Error::WindowFull(server.receive_maximum))?;
        publish.pkid = Some(pkid);

        // Inflight keeps the original topic and no alias so reconnect
        // retransmission stays valid after the connection mapping is reset.
        let mut inflight = codec::Publish::from(msg);
        inflight.pkid = Some(pkid);
        let rx = self.inner.session.track_publish(pkid, inflight);

        let pkt = codec::Packet::Publish(publish);

        if let Err(e) = self.inner.send_packet(&pkt, msg.timeout) {
            log::warn!("failed to send publish 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 topic filters
    ///
    /// Returns a [`Token`] that resolves to per-filter reason codes once SUBACK
    /// is received.
    ///
    /// # Errors
    ///
    /// Returns [`Error::SubscriptionIdNotSupported`] when `properties` contains a
    /// subscription identifier but the server does not support it.
    ///
    /// 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,
        filters: &[SubscribeFilter],
        properties: Option<codec::SubscribeProperties>,
        timeout: Option<Duration>,
    ) -> Result<Token<Vec<codec::ReasonCode>>, Error> {
        if let Some(ref props) = properties {
            if props.subscription_identifier.is_some() && !self.inner.session.server_properties().sub_id_available {
                return Err(Error::SubscriptionIdNotSupported);
            }
        }

        let pkid = self
            .inner
            .session
            .alloc_pkid()
            .ok_or(Error::WindowFull(self.inner.session.receive_maximum()))?;

        let pkt = codec::Packet::Subscribe(codec::Subscribe {
            pkid,
            properties: properties.unwrap_or_default(),
            filters: filters.iter().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 pkid={pkid}: {e}");
            self.inner.session.release_pkid(pkid);
            return Err(e);
        }

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

    /// Unsubscribe from topics [MQTTv5-3.10]
    ///
    /// Returns a [`Token`] that resolves to per-topic reason codes 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],
        properties: Option<codec::UnsubscribeProperties>,
        timeout: Option<Duration>,
    ) -> Result<Token<Vec<codec::ReasonCode>>, Error> {
        let pkid = self
            .inner
            .session
            .alloc_pkid()
            .ok_or(Error::WindowFull(self.inner.session.receive_maximum()))?;

        let pkt = codec::Packet::Unsubscribe(codec::Unsubscribe {
            pkid,
            properties: properties.unwrap_or_default(),
            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 pkid={pkid}: {e}");
            self.inner.session.release_pkid(pkid);
            return Err(e);
        }

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

    /// Initiate re-authentication over an existing connection [MQTTv5-4.12.4]
    ///
    /// Requires that `ConnectOptions::auth_method` was set during initial connect.
    /// Blocks until the broker responds with AUTH(Success) or DISCONNECT.
    pub fn reauthenticate(&self, timeout: Option<Duration>) -> Result<(), Error> {
        log::debug!("initiating re-authentication");
        let auth_method = self
            .inner
            .opts
            .auth_method
            .as_ref()
            .ok_or(Error::AuthFailed(symqtt_codec::v5::ReasonCode::NotAuthorized))?
            .clone();

        let initial_data = self.inner.auth_handler.on_auth_continue(None);

        let (tx, rx) = mpsc::sync_channel(1);
        *self.inner.reauth_tx.lock().unwrap() = Some(tx);

        let pkt = codec::Packet::Auth(codec::Auth {
            status: AuthStatus::ReAuthenticate,
            properties: AuthProperties {
                authentication_method: Some(auth_method),
                authentication_data: initial_data,
                ..Default::default()
            },
        });
        self.inner.send_packet(&pkt, timeout)?;

        match timeout {
            Some(t) => rx.recv_timeout(t).map_err(|_| Error::Timeout)?,
            None => rx.recv().map_err(|_| Error::Disconnected)?,
        }
    }

    /// Gracefully disconnect from the broker with a reason code
    ///
    /// 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, reason: codec::ReasonCode, timeout: Option<Duration>) {
        log::debug!("disconnecting with reason={reason:?}");
        let deadline = timeout.map(|t| Instant::now() + t);

        self.inner.graceful_close(reason, timeout, true);

        wait_thread(self.inner.read_done_rx.lock().unwrap().take(), deadline);
        wait_thread(self.inner.keepalive_done_rx.lock().unwrap().take(), deadline);
    }
}

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

impl<H: InboundHandler, W: Write + WriteTimeout + Send, A: AuthHandler> ClientInner<H, W, A> {
    /// Compute effective keepalive: server may override via CONNACK property
    fn effective_keepalive(&self) -> Duration {
        let server_ka = self.session.server_properties().server_keep_alive;
        match server_ka {
            Some(secs) => Duration::from_secs(secs as u64),
            None => self.opts.keep_alive,
        }
    }

    /// Perform the CONNECT/CONNACK handshake
    ///
    /// Sends CONNECT, handles multi-round AUTH exchanges if enhanced auth is
    /// configured, and blocks until CONNACK arrives. On success, applies
    /// server-negotiated properties and retransmits inflight messages.
    fn handshake(&self, hs_rx: mpsc::Receiver<HandshakePacket>) -> 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 or AUTH via the channel.
        // AUTH(Continue) triggers multi-round exchange before CONNACK arrives.
        let connack = loop {
            let pkt = match deadline {
                Some(ddl) => hs_rx
                    .recv_timeout(ddl.saturating_duration_since(Instant::now()))
                    .map_err(|_| Error::Timeout)?,
                None => hs_rx.recv().map_err(|_| Error::Disconnected)?,
            };
            match pkt {
                HandshakePacket::ConnAck(connack) => break connack,
                HandshakePacket::Auth(auth) => {
                    if auth.status != AuthStatus::Continue {
                        return Err(Error::AuthFailed(codec::ReasonCode::NotAuthorized));
                    }
                    let response_data = self
                        .auth_handler
                        .on_auth_continue(auth.properties.authentication_data.as_ref())
                        .ok_or(Error::AuthFailed(codec::ReasonCode::NotAuthorized))?;

                    let reply = codec::Packet::Auth(codec::Auth {
                        status: AuthStatus::Continue,
                        properties: AuthProperties {
                            authentication_method: self.opts.auth_method.clone(),
                            authentication_data: Some(response_data),
                            ..Default::default()
                        },
                    });
                    self.send_packet(&reply, self.opts.connect_timeout)?;
                }
            }
        };

        if connack.reason_code != codec::ReasonCode::Success {
            return Err(Error::ConnectRefused(
                connack.reason_code,
                connack.properties.reason_string.clone(),
            ));
        }

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

        // Apply server-negotiated properties to session (Receive Maximum,
        // Maximum Packet Size, etc.) and collect pending retransmissions
        let retransmits = self.session.on_connack(&connack);

        // Configure outbound topic aliases based on server's topic_alias_maximum
        let server_alias_max = connack.properties.topic_alias_maximum.unwrap_or(0);
        self.outbound_aliases.lock().unwrap().reset(server_alias_max);
        let client_alias_max = self.opts.topic_alias_maximum.unwrap_or(0);
        self.inbound_aliases.lock().unwrap().reset(client_alias_max);

        // Retransmit inflight messages
        log::debug!("retransmitting {} inflight messages", retransmits.len());
        for item in retransmits {
            let pkt = match item {
                Retransmit::Publish(p) => codec::Packet::Publish(*p),
                Retransmit::PubRel { pkid } => codec::Packet::PubRel(codec::PubRel {
                    pkid,
                    reason_code: codec::ReasonCode::Success,
                    properties: codec::PubRelProperties::default(),
                }),
            };
            if let Err(e) = self.send_packet(&pkt, None) {
                log::warn!("failed to retransmit packet: {e}");
            }
        }

        self.auth_handler.on_authenticated();
        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, reason: codec::ReasonCode, timeout: Option<Duration>, notify: bool) {
        let pkt = codec::Packet::Disconnect(codec::Disconnect {
            reason_code: reason,
            properties: codec::DisconnectProperties::default(),
        });
        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
    /// - `notify = false`: skip [`InboundHandler::on_disconnect`] (used by `Drop`)
    fn terminate(&self, error: Error, graceful: bool, notify: bool) {
        // CAS guarantees single execution
        if !self.alive.swap(false, Ordering::SeqCst) {
            return;
        }
        log::debug!("terminating: graceful={graceful} reason={error}");

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

        // Drop stop_tx — unblocks the keepalive thread's recv_timeout()
        self.stop_tx.lock().unwrap().take();

        // Wake pending re-auth caller if any
        if let Some(tx) = self.reauth_tx.lock().unwrap().take() {
            let _ = tx.try_send(Err(error.clone()));
        }

        // Graceful: wake all tokens so callers stop blocking.
        // Ungraceful: preserve inflight state for reconnect retransmission.
        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, decodes complete packets,
    /// and dispatches them. Terminates the connection on EOF or IO error.
    fn read_loop(&self, mut reader: impl Read, hs_tx: mpsc::SyncSender<HandshakePacket>) {
        let mut tmp = [0u8; 4096];
        let mut buf = BytesMut::with_capacity(8192);

        loop {
            if let Err(e) = self.drain_decoded_packets(&mut buf, &hs_tx) {
                self.terminate(e, false, true);
                return;
            }

            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!("PingReq send failed: {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/AUTH during handshake are forwarded via `hs_tx` to the caller
    /// thread. After handshake, AUTH packets go through `handle_post_connect_auth`.
    fn drain_decoded_packets(
        &self,
        buf: &mut BytesMut,
        hs_tx: &mpsc::SyncSender<HandshakePacket>,
    ) -> Result<(), Error> {
        loop {
            match codec::Packet::decode(buf) {
                Ok(Some(pkt)) => {
                    self.pinger.record_received();
                    match pkt {
                        codec::Packet::ConnAck(connack) => {
                            let _ = hs_tx.try_send(HandshakePacket::ConnAck(connack));
                            continue;
                        }
                        codec::Packet::Auth(auth) => {
                            // During handshake, forward via hs_tx;
                            // after connection, hs_tx is disconnected so try_send fails silently
                            if hs_tx.try_send(HandshakePacket::Auth(auth.clone())).is_err() {
                                self.handle_post_connect_auth(auth)?;
                            }
                            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
    fn dispatch_packet(&self, pkt: codec::Packet) -> Result<(), Error> {
        match pkt {
            codec::Packet::PubAck(ack) => {
                log::debug!("received PubAck pkid={} reason={:?}", ack.pkid, ack.reason_code);
                let _ = self.session.on_puback(ack.pkid, ack.reason_code, ack.properties);
            }
            codec::Packet::PubRec(rec) => {
                log::debug!("received PubRec pkid={} reason={:?}", rec.pkid, rec.reason_code);
                match self.session.on_pubrec(rec.pkid, rec.reason_code) {
                    Ok(true) => {
                        log::debug!("sending PubRel pkid={}", rec.pkid);
                        let pubrel = codec::Packet::PubRel(codec::PubRel {
                            pkid: rec.pkid,
                            reason_code: codec::ReasonCode::Success,
                            properties: codec::PubRelProperties::default(),
                        });
                        self.send_packet(&pubrel, None)?;
                    }
                    Ok(false) => {} // PUBREC indicated failure, flow completed
                    Err(_) => {}
                }
            }
            codec::Packet::PubComp(comp) => {
                log::debug!("received PubComp pkid={} reason={:?}", comp.pkid, comp.reason_code);
                let _ = self.session.on_pubcomp(comp.pkid, comp.reason_code, comp.properties);
            }
            codec::Packet::Publish(mut publish) => {
                // Resolve topic alias (inbound)
                let resolved_topic = self
                    .inbound_aliases
                    .lock()
                    .unwrap()
                    .resolve(&publish.topic, publish.properties.topic_alias)?;
                publish.topic = resolved_topic;
                log::debug!(
                    "received Publish topic={:?} qos={:?} pkid={:?} payload_len={}",
                    publish.topic,
                    publish.qos,
                    publish.pkid,
                    publish.payload.len()
                );
                self.handle_inbound_publish(&publish)?;
            }
            codec::Packet::SubAck(suback) => {
                log::debug!("received SubAck pkid={} codes={:?}", suback.pkid, suback.reason_codes);
                self.session
                    .on_suback(suback.pkid, suback.reason_codes, suback.properties);
            }
            codec::Packet::UnsubAck(unsuback) => {
                log::debug!(
                    "received UnsubAck pkid={} codes={:?}",
                    unsuback.pkid,
                    unsuback.reason_codes
                );
                self.session
                    .on_unsuback(unsuback.pkid, unsuback.reason_codes, unsuback.properties);
            }
            codec::Packet::PingResp(_) => {
                log::debug!("received PingResp");
                self.pinger.record_ping_response();
            }
            codec::Packet::PubRel(pubrel) => {
                log::debug!("received PubRel pkid={}, sending PubComp", pubrel.pkid);
                let _ = self.session.release_incoming(pubrel.pkid);
                let pubcomp = codec::Packet::PubComp(codec::PubComp {
                    pkid: pubrel.pkid,
                    reason_code: codec::ReasonCode::Success,
                    properties: codec::PubCompProperties::default(),
                });
                self.send_packet(&pubcomp, None)?;
            }
            codec::Packet::Disconnect(disconnect) => {
                log::debug!("received server Disconnect reason={:?}", disconnect.reason_code);
                self.handler.on_server_disconnect(&disconnect);
                self.terminate(Error::ServerDisconnect(disconnect.reason_code), false, true);
            }
            _ => {}
        }
        Ok(())
    }

    /// Handle AUTH packets received after the initial connection is established
    /// (re-authentication flow) [MQTTv5-4.12.4]
    fn handle_post_connect_auth(&self, auth: codec::Auth) -> Result<(), Error> {
        match auth.status {
            AuthStatus::Continue => {
                let response_data = self
                    .auth_handler
                    .on_auth_continue(auth.properties.authentication_data.as_ref())
                    .ok_or(Error::AuthFailed(codec::ReasonCode::NotAuthorized))?;

                let reply = codec::Packet::Auth(codec::Auth {
                    status: AuthStatus::Continue,
                    properties: AuthProperties {
                        authentication_method: self.opts.auth_method.clone(),
                        authentication_data: Some(response_data),
                        ..Default::default()
                    },
                });
                self.send_packet(&reply, None)?;
            }
            AuthStatus::Success => {
                self.auth_handler.on_authenticated();
                if let Some(tx) = self.reauth_tx.lock().unwrap().take() {
                    let _ = tx.try_send(Ok(()));
                }
            }
            AuthStatus::ReAuthenticate => {
                log::debug!("unexpected ReAuthenticate status from server, ignoring");
            }
        }
        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 => {
                self.handler.on_publish(publish);
            }
            QoS::AtLeastOnce => {
                self.handler.on_publish(publish);
                if let Some(pkid) = publish.pkid {
                    log::debug!("sending PubAck pkid={pkid}");
                    let puback = codec::Packet::PubAck(codec::PubAck {
                        pkid,
                        reason_code: codec::ReasonCode::Success,
                        properties: codec::PubAckProperties::default(),
                    });
                    self.send_packet(&puback, None)?;
                }
            }
            QoS::ExactlyOnce => {
                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}");
                    let pubrec = codec::Packet::PubRec(codec::PubRec {
                        pkid,
                        reason_code: codec::ReasonCode::Success,
                        properties: codec::PubRecProperties::default(),
                    });
                    self.send_packet(&pubrec, None)?;
                }
            }
        }
        Ok(())
    }

    /// Encode a packet and write it to the transport
    ///
    /// Acquires the writer lock, encodes into an intermediate buffer, validates
    /// against server maximum packet size, writes to stream, and flushes.
    fn send_packet(&self, pkt: &codec::Packet, timeout: Option<Duration>) -> Result<(), Error> {
        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)?;
            buf.clear();
            pkt.encode(buf)?;

            // Check maximum packet size (CONNECT is exempt — limit comes from CONNACK)
            if !matches!(pkt, codec::Packet::Connect(_)) {
                let server = self.session.server_properties();
                if server.maximum_packet_size > 0 && buf.len() > server.maximum_packet_size as usize {
                    return Err(Error::PacketTooLarge {
                        size: buf.len(),
                        max: server.maximum_packet_size,
                    });
                }
            }

            log::trace!("sending {} ({} bytes)", packet_name(pkt), buf.len());
            stream.set_write_timeout(timeout)?;
            stream.write_all(buf)?;
            stream.flush()?;
        }
        self.pinger.record_sent();
        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",
        codec::Packet::Auth(_) => "AUTH",
    }
}