mqtt5 0.31.2

Complete MQTT v5.0 platform with high-performance async client and full-featured broker supporting TCP, TLS, WebSocket, authentication, bridging, and resource monitoring
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
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
//! MQTT v5.0 Client - Direct Async Implementation
//!
//! This client uses direct async/await patterns throughout.

use crate::callback::PublishCallback;
use crate::error::{MqttError, Result};
use crate::packet::publish::PublishPacket;
use crate::packet::subscribe::{SubscribePacket, SubscriptionOptions, TopicFilter};
use crate::packet::unsubscribe::UnsubscribePacket;
use crate::protocol::v5::properties::Properties;
#[cfg(not(target_arch = "wasm32"))]
use crate::transport::tls::TlsConfig;
use crate::types::{
    ConnectOptions, ConnectResult, PublishOptions, PublishResult, SubscribeOptions,
};
use crate::QoS;
use std::future::Future;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::instrument;

mod auth_handler;
pub mod auth_handlers;
mod builders;
mod connection;
#[cfg(not(target_arch = "wasm32"))]
mod direct;
mod error_recovery;
mod inner;
pub mod mock;
mod retry;
mod state;
pub mod r#trait;

pub use auth_handler::{AuthHandler, AuthResponse};
pub use auth_handlers::{JwtAuthHandler, PlainAuthHandler, ScramSha256AuthHandler};

pub use self::connection::{ConnectionEvent, DisconnectReason, ReconnectConfig};
pub use self::error_recovery::{
    is_recoverable, retry_delay, ErrorCallback, ErrorRecoveryConfig, RecoverableError, RetryState,
};
pub use self::mock::{MockCall, MockMqttClient};
pub use self::r#trait::MqttClientTrait;

pub use builders::ConnectionEventCallback;

use self::direct::AutomaticReconnectLifecycle;
#[cfg(not(target_arch = "wasm32"))]
use self::direct::DirectClientInner;

/// Thread-safe MQTT v5.0 client
///
/// # Examples
///
/// ## Basic usage
///
/// ```rust,no_run
/// use mqtt5::MqttClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = MqttClient::new("my-client-id");
///
///     client.connect("mqtt://localhost:1883").await?;
///
///     client.subscribe("temperature/room1", |msg| {
///         println!("Received: {} on topic {}",
///                  String::from_utf8_lossy(&msg.payload),
///                  msg.topic);
///     }).await?;
///
///     client.publish("temperature/room1", b"22.5").await?;
///
///     client.disconnect().await?;
///     Ok(())
/// }
/// ```
///
/// ## Advanced usage with options
///
/// ```rust,no_run
/// use mqtt5::{MqttClient, ConnectOptions, PublishOptions, QoS};
/// use std::time::Duration;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let options = ConnectOptions::new("my-client")
///         .with_clean_start(true)
///         .with_keep_alive(Duration::from_secs(30))
///         .with_credentials("user", b"pass");
///
///     let client = MqttClient::with_options(options);
///
///     client.connect("mqtts://broker.example.com:8883").await?;
///
///     let mut pub_options = PublishOptions::default();
///     pub_options.qos = QoS::ExactlyOnce;
///     pub_options.retain = true;
///
///     client.publish_with_options(
///         "status/device1",
///         b"online",
///         pub_options
///     ).await?;
///
///     Ok(())
/// }
/// ```
#[derive(Clone)]
pub struct MqttClient {
    pub(crate) inner: Arc<RwLock<DirectClientInner>>,
    pub(crate) connection_event_callbacks: Arc<RwLock<Vec<ConnectionEventCallback>>>,
    pub(crate) error_callbacks: Arc<RwLock<Vec<error_recovery::ErrorCallback>>>,
    pub(crate) error_recovery_config: Arc<RwLock<error_recovery::ErrorRecoveryConfig>>,
    pub(crate) connection_mutex: Arc<tokio::sync::Mutex<()>>,
    pub(crate) tls_config: Arc<RwLock<Option<TlsConfig>>>,
    pub(crate) transport_config: Arc<RwLock<crate::transport::ClientTransportConfig>>,
    #[cfg(feature = "transport-quic")]
    pub(crate) quic_client_config: Arc<RwLock<Option<quinn::ClientConfig>>>,
}

impl MqttClient {
    /// Checks if the client is connected
    pub async fn is_connected(&self) -> bool {
        self.inner.read().await.is_connected()
    }

    /// Gets the client ID
    pub async fn client_id(&self) -> String {
        self.inner
            .read()
            .await
            .session
            .read()
            .await
            .client_id()
            .to_string()
    }

    /// Sets a callback for connection events
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use mqtt5::{MqttClient, ConnectionEvent, DisconnectReason};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = MqttClient::new("my-client");
    ///
    /// client.on_connection_event(|event| {
    ///     match event {
    ///         ConnectionEvent::Connecting => {
    ///             println!("Connecting...");
    ///         }
    ///         ConnectionEvent::Connected { session_present } => {
    ///             println!("Connected! Session present: {}", session_present);
    ///         }
    ///         ConnectionEvent::Disconnected { reason } => {
    ///             println!("Disconnected: {:?}", reason);
    ///         }
    ///         ConnectionEvent::Reconnecting { attempt } => {
    ///             println!("Reconnecting attempt {}", attempt);
    ///         }
    ///         ConnectionEvent::ReconnectFailed { error } => {
    ///             println!("Reconnection failed: {error}");
    ///         }
    ///     }
    /// }).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the callback storage is inaccessible
    pub async fn on_connection_event<F>(&self, callback: F) -> Result<()>
    where
        F: Fn(ConnectionEvent) + Send + Sync + 'static,
    {
        let mut callbacks = self.connection_event_callbacks.write().await;
        callbacks.push(Arc::new(callback));
        Ok(())
    }

    /// Sets an error callback
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    pub async fn on_error<F>(&self, callback: F) -> Result<()>
    where
        F: Fn(&MqttError) + Send + Sync + 'static,
    {
        let mut callbacks = self.error_callbacks.write().await;
        callbacks.push(Box::new(callback));
        Ok(())
    }

    /// Connects to the MQTT broker with default options
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use mqtt5::MqttClient;
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = MqttClient::new("my-client");
    ///
    /// // Connect via TCP
    /// client.connect("mqtt://broker.example.com:1883").await?;
    ///
    /// // Or connect via TLS
    /// // client.connect("mqtts://secure.broker.com:8883").await?;
    ///
    /// // Or use just host:port (defaults to TCP)
    /// // client.connect("localhost:1883").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if connection fails, address is invalid, or transport cannot be established
    #[instrument(skip(self))]
    pub async fn connect(&self, address: &str) -> Result<()> {
        let client_id = self.client_id().await;
        tracing::trace!(client_id = %client_id, address = %address, "MQTT CLIENT - connect() method called");
        tracing::info!(client_id = %client_id, address = %address, "Initiating MQTT connection");

        let result = {
            let connection_guard = self.connection_mutex.lock().await;
            let options = self.inner.read().await.options.clone();
            let result = self.connect_with_options_internal(address, options).await;
            drop(connection_guard);
            result
        };

        match result {
            Ok(connect_result) => {
                tracing::info!(client_id = %client_id, session_present = %connect_result.session_present, "Successfully connected to MQTT broker");
                Ok(())
            }
            Err(e) => {
                tracing::error!(client_id = %client_id, error = %e, "Failed to connect to MQTT broker");
                Err(e)
            }
        }
    }

    /// Connects to the MQTT broker with custom options
    ///
    /// Returns `session_present` flag from CONNACK
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    #[instrument(skip(self, options), fields(client_id = %options.client_id, clean_start = %options.clean_start), level = "debug")]
    pub async fn connect_with_options(
        &self,
        address: &str,
        options: ConnectOptions,
    ) -> Result<ConnectResult> {
        let connection_guard = self.connection_mutex.lock().await;
        let result = self.connect_with_options_internal(address, options).await;
        drop(connection_guard);
        result
    }

    /// Connects to the MQTT broker using a custom TLS configuration
    ///
    /// # Errors
    ///
    /// Returns an error if connection fails or TLS configuration is invalid
    pub async fn connect_with_tls(
        &self,
        tls_config: crate::transport::tls::TlsConfig,
    ) -> Result<()> {
        let connection_guard = self.connection_mutex.lock().await;
        let options = self.inner.read().await.options.clone();
        let result = self
            .connect_with_tls_and_options_internal(tls_config, options)
            .await;
        drop(connection_guard);
        result.map(|_| ())
    }

    /// Connects to the MQTT broker using custom TLS configuration and connect options
    ///
    /// Returns `session_present` flag from CONNACK
    ///
    /// # Errors
    ///
    /// Returns an error if connection fails or configuration is invalid
    pub async fn connect_with_tls_and_options(
        &self,
        tls_config: crate::transport::tls::TlsConfig,
        options: ConnectOptions,
    ) -> Result<ConnectResult> {
        let connection_guard = self.connection_mutex.lock().await;
        let result = self
            .connect_with_tls_and_options_internal(tls_config, options)
            .await;
        drop(connection_guard);
        result
    }

    /// Disconnects from the MQTT broker
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    #[instrument(skip(self))]
    pub async fn disconnect(&self) -> Result<()> {
        let client_id = self.client_id().await;
        tracing::info!(client_id = %client_id, "Initiating MQTT disconnect");

        let mut inner = self.inner.write().await;
        inner.automatic_reconnect_lifecycle = AutomaticReconnectLifecycle::Stopped;
        match inner.disconnect().await {
            Ok(()) => {
                tracing::info!(client_id = %client_id, "Successfully disconnected from MQTT broker");
                self.trigger_connection_event(ConnectionEvent::Disconnected {
                    reason: DisconnectReason::ClientInitiated,
                })
                .await;
                Ok(())
            }
            Err(e) => {
                tracing::error!(client_id = %client_id, error = %e, "Failed to disconnect from MQTT broker");
                Err(e)
            }
        }
    }

    /// Publishes a message to a topic
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    #[instrument(skip(self, topic, payload))]
    pub async fn publish(
        &self,
        topic: impl Into<String>,
        payload: impl Into<Vec<u8>>,
    ) -> Result<PublishResult> {
        let options = PublishOptions::default();
        self.publish_with_options(topic, payload, options).await
    }

    /// Publishes a message to a topic with specific `QoS` (compatibility method)
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    pub async fn publish_qos(
        &self,
        topic: impl Into<String>,
        payload: impl Into<Vec<u8>>,
        qos: QoS,
    ) -> Result<PublishResult> {
        let options = PublishOptions {
            qos,
            ..Default::default()
        };
        self.publish_with_options(topic, payload, options).await
    }

    /// Publishes a message with custom options
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    #[instrument(skip(self, topic, payload, options), fields(qos = ?options.qos, retain = %options.retain))]
    pub async fn publish_with_options(
        &self,
        topic: impl Into<String>,
        payload: impl Into<Vec<u8>>,
        options: PublishOptions,
    ) -> Result<PublishResult> {
        let topic_str = topic.into();
        let payload_vec = payload.into();
        let client_id = self.client_id().await;

        tracing::debug!(
            client_id = %client_id,
            topic = %topic_str,
            payload_len = payload_vec.len(),
            qos = ?options.qos,
            retain = %options.retain,
            "Publishing MQTT message"
        );

        let inner = self.inner.read().await;
        match inner.publish(topic_str.clone(), payload_vec, options).await {
            Ok(result) => {
                match &result {
                    PublishResult::QoS0 => {
                        tracing::debug!(client_id = %client_id, topic = %topic_str, "Published QoS0 message");
                    }
                    PublishResult::QoS1Or2 { packet_id } => {
                        tracing::debug!(client_id = %client_id, topic = %topic_str, packet_id = %packet_id, "Published QoS1/2 message");
                    }
                }
                Ok(result)
            }
            Err(e) => {
                tracing::error!(client_id = %client_id, topic = %topic_str, error = %e, "Failed to publish MQTT message");
                Err(e)
            }
        }
    }

    /// Subscribes to a topic with a callback
    ///
    /// # Errors
    ///
    /// Returns an error if subscription fails, topic filter is invalid, or client is not connected
    #[instrument(skip(self, topic_filter, callback))]
    pub async fn subscribe<F>(
        &self,
        topic_filter: impl Into<String>,
        callback: F,
    ) -> Result<(u16, QoS)>
    where
        F: Fn(crate::types::Message) + Send + Sync + 'static,
    {
        let options = SubscribeOptions::default();
        self.subscribe_with_options(topic_filter, options, callback)
            .await
    }

    /// Subscribes to a topic with custom options and a callback
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    #[instrument(skip(self, topic_filter, options, callback), fields(qos = ?options.qos), level = "debug")]
    pub async fn subscribe_with_options<F>(
        &self,
        topic_filter: impl Into<String>,
        options: SubscribeOptions,
        callback: F,
    ) -> Result<(u16, QoS)>
    where
        F: Fn(crate::types::Message) + Send + Sync + 'static,
    {
        let topic_filter_str = topic_filter.into();
        let client_id = self.client_id().await;

        tracing::debug!(
            client_id = %client_id,
            topic_filter = %topic_filter_str,
            qos = ?options.qos,
            "Subscribing to MQTT topic"
        );

        let wrapped_callback = move |packet: PublishPacket| {
            let msg = crate::types::Message::from(packet);
            callback(msg);
        };

        match self
            .subscribe_with_options_raw(topic_filter_str.clone(), options, wrapped_callback)
            .await
        {
            Ok((packet_id, granted_qos)) => {
                tracing::debug!(
                    client_id = %client_id,
                    topic_filter = %topic_filter_str,
                    packet_id = %packet_id,
                    granted_qos = ?granted_qos,
                    "Successfully subscribed to MQTT topic"
                );
                Ok((packet_id, granted_qos))
            }
            Err(e) => {
                tracing::error!(
                    client_id = %client_id,
                    topic_filter = %topic_filter_str,
                    error = %e,
                    "Failed to subscribe to MQTT topic"
                );
                Err(e)
            }
        }
    }

    async fn subscribe_with_options_raw<F>(
        &self,
        topic_filter: impl Into<String>,
        options: SubscribeOptions,
        callback: F,
    ) -> Result<(u16, QoS)>
    where
        F: Fn(PublishPacket) + Send + Sync + 'static,
    {
        let topic_filter = topic_filter.into();

        let inner = self.inner.read().await;
        let callback: PublishCallback = Arc::new(callback);
        let callback_id = inner
            .callback_manager
            .register_with_id(&topic_filter, callback)?;

        let filter = TopicFilter {
            filter: topic_filter.clone(),
            options: SubscriptionOptions {
                qos: options.qos,
                no_local: options.no_local,
                retain_as_published: options.retain_as_published,
                retain_handling: match options.retain_handling {
                    crate::types::RetainHandling::SendAtSubscribe => {
                        crate::packet::subscribe::RetainHandling::SendAtSubscribe
                    }
                    crate::types::RetainHandling::SendIfNew => {
                        crate::packet::subscribe::RetainHandling::SendAtSubscribeIfNew
                    }
                    crate::types::RetainHandling::DontSend => {
                        crate::packet::subscribe::RetainHandling::DoNotSend
                    }
                },
            },
        };

        let mut packet = SubscribePacket {
            packet_id: 0,
            filters: vec![filter],
            properties: Properties::default(),
            protocol_version: inner.options.protocol_version.as_u8(),
        };

        if let Some(sub_id) = options.subscription_identifier {
            packet = packet.with_subscription_identifier(sub_id);
        }

        match inner.subscribe_with_callback(packet, callback_id).await {
            Ok(results) => {
                if let Some(&(packet_id, qos)) = results.first() {
                    Ok((packet_id, qos))
                } else {
                    let _ = inner.callback_manager.unregister(&topic_filter);
                    Err(MqttError::ProtocolError(
                        "No results returned for subscription".to_string(),
                    ))
                }
            }
            Err(e) => {
                let _ = inner.callback_manager.unregister(&topic_filter);
                Err(e)
            }
        }
    }

    /// Unsubscribes from a topic
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    #[instrument(skip(self, topic_filter))]
    pub async fn unsubscribe(&self, topic_filter: impl Into<String>) -> Result<()> {
        let topic_filter = topic_filter.into();
        let client_id = self.client_id().await;

        tracing::info!(
            client_id = %client_id,
            topic_filter = %topic_filter,
            "Unsubscribing from MQTT topic"
        );

        let inner = self.inner.read().await;
        let _ = inner.callback_manager.unregister(&topic_filter);

        let packet = UnsubscribePacket {
            packet_id: 0,
            filters: vec![topic_filter.clone()],
            properties: Properties::default(),
            protocol_version: inner.options.protocol_version.as_u8(),
        };

        match inner.unsubscribe(packet).await {
            Ok(()) => {
                tracing::info!(
                    client_id = %client_id,
                    topic_filter = %topic_filter,
                    "Successfully unsubscribed from MQTT topic"
                );
                Ok(())
            }
            Err(e) => {
                tracing::error!(
                    client_id = %client_id,
                    topic_filter = %topic_filter,
                    error = %e,
                    "Failed to unsubscribe from MQTT topic"
                );
                Err(e)
            }
        }
    }

    /// Subscribe to multiple topics at once
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    pub async fn subscribe_many<F>(
        &self,
        topics: Vec<(&str, QoS)>,
        callback: F,
    ) -> Result<Vec<(u16, QoS)>>
    where
        F: Fn(crate::types::Message) + Send + Sync + 'static + Clone,
    {
        let mut results = Vec::new();
        for (topic, qos) in topics {
            let opts = SubscribeOptions {
                qos,
                ..Default::default()
            };
            let result = self
                .subscribe_with_options(topic, opts, callback.clone())
                .await?;
            results.push(result);
        }
        Ok(results)
    }

    /// Unsubscribe from multiple topics at once
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    pub async fn unsubscribe_many(&self, topics: Vec<&str>) -> Result<Vec<(String, Result<()>)>> {
        let mut results = Vec::with_capacity(topics.len());

        for topic in topics {
            let topic_string = topic.to_string();
            let result = self.unsubscribe(topic).await;
            results.push((topic_string, result));
        }

        Ok(results)
    }

    /// Publish a retained message
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    pub async fn publish_retain(
        &self,
        topic: impl Into<String>,
        payload: impl Into<Vec<u8>>,
    ) -> Result<PublishResult> {
        let opts = PublishOptions {
            retain: true,
            ..Default::default()
        };
        self.publish_with_options(topic, payload, opts).await
    }

    /// Publish with `QoS` 0 (convenience method)
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    pub async fn publish_qos0(
        &self,
        topic: impl Into<String>,
        payload: impl Into<Vec<u8>>,
    ) -> Result<PublishResult> {
        self.publish_qos(topic, payload, QoS::AtMostOnce).await
    }

    /// Publish with `QoS` 1 (convenience method)
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    pub async fn publish_qos1(
        &self,
        topic: impl Into<String>,
        payload: impl Into<Vec<u8>>,
    ) -> Result<PublishResult> {
        self.publish_qos(topic, payload, QoS::AtLeastOnce).await
    }

    /// Publish with `QoS` 2 (convenience method)
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    pub async fn publish_qos2(
        &self,
        topic: impl Into<String>,
        payload: impl Into<Vec<u8>>,
    ) -> Result<PublishResult> {
        self.publish_qos(topic, payload, QoS::ExactlyOnce).await
    }

    /// Check if message queuing is enabled
    pub async fn is_queue_on_disconnect(&self) -> bool {
        let inner = self.inner.read().await;
        inner.is_queue_on_disconnect()
    }

    /// Set whether to queue messages when disconnected
    pub async fn set_queue_on_disconnect(&self, enabled: bool) {
        let mut inner = self.inner.write().await;
        inner.set_queue_on_disconnect(enabled);
    }

    /// Get error recovery configuration
    pub async fn error_recovery_config(&self) -> error_recovery::ErrorRecoveryConfig {
        self.error_recovery_config.read().await.clone()
    }

    /// Set error recovery configuration
    pub async fn set_error_recovery_config(&self, config: error_recovery::ErrorRecoveryConfig) {
        *self.error_recovery_config.write().await = config;
    }

    /// Clear all error callbacks
    pub async fn clear_error_callbacks(&self) {
        self.error_callbacks.write().await.clear();
    }

    /// Clear all connection event callbacks
    pub async fn clear_connection_event_callbacks(&self) {
        self.connection_event_callbacks.write().await.clear();
    }

    /// Get direct access to session state (for testing)
    #[cfg(test)]
    pub async fn session_state(&self) -> Arc<RwLock<crate::session::SessionState>> {
        Arc::clone(&self.inner.read().await.session)
    }

    /// Sets an authentication handler for enhanced authentication
    pub async fn set_auth_handler(&self, handler: impl AuthHandler + 'static) {
        self.inner.write().await.set_auth_handler(handler);
    }

    /// Initiates re-authentication with the broker
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Client is not connected
    /// - No auth handler is configured
    /// - No authentication method was used during initial connection
    pub async fn reauthenticate(&self) -> Result<()> {
        self.inner.read().await.reauthenticate().await
    }

    /// Simulate abnormal disconnection (for testing will messages)
    ///
    /// # Errors
    ///
    /// Returns an error if the operation fails
    pub async fn disconnect_abnormally(&self) -> Result<()> {
        let mut inner = self.inner.write().await;
        inner.disconnect_with_packet(false).await
    }

    #[cfg(feature = "transport-quic")]
    pub async fn quic_connection(&self) -> Option<Arc<quinn::Connection>> {
        self.inner.read().await.quic_connection.clone()
    }

    #[cfg(feature = "transport-quic")]
    pub async fn was_zero_rtt(&self) -> bool {
        self.inner.read().await.zero_rtt_accepted
    }

    /// Triggers QUIC connection migration by rebinding the endpoint to a new UDP socket.
    ///
    /// # Errors
    ///
    /// Returns `NotConnected` if the client is not connected, or `ConnectionError`
    /// if the transport is not QUIC or rebinding fails.
    #[cfg(all(not(target_arch = "wasm32"), feature = "transport-quic"))]
    pub async fn migrate(&self) -> Result<()> {
        self.inner.read().await.migrate()
    }

    /// Discards a flow's state at the remote peer by opening a bidirectional QUIC stream
    /// with `clean_start=1` and all persistent flags cleared.
    ///
    /// # Errors
    ///
    /// Returns `NotConnected` if the client is not connected, `ConnectionError`
    /// if the transport is not QUIC, or `Timeout` if the peer does not respond.
    #[cfg(all(not(target_arch = "wasm32"), feature = "transport-quic"))]
    pub async fn discard_flow(&self, flow_id: crate::transport::flow::FlowId) -> Result<()> {
        self.inner.read().await.discard_flow(flow_id).await
    }
}

#[allow(clippy::manual_async_fn)]
impl MqttClientTrait for MqttClient {
    fn is_connected(&self) -> impl Future<Output = bool> + Send + '_ {
        async move { self.is_connected().await }
    }

    fn client_id(&self) -> impl Future<Output = String> + Send + '_ {
        async move { self.client_id().await }
    }

    fn connect<'a>(&'a self, address: &'a str) -> impl Future<Output = Result<()>> + Send + 'a {
        async move { self.connect(address).await }
    }

    fn connect_with_options<'a>(
        &'a self,
        address: &'a str,
        options: ConnectOptions,
    ) -> impl Future<Output = Result<ConnectResult>> + Send + 'a {
        async move { Box::pin(self.connect_with_options(address, options)).await }
    }

    fn disconnect(&self) -> impl Future<Output = Result<()>> + Send + '_ {
        async move { self.disconnect().await }
    }

    fn publish<'a>(
        &'a self,
        topic: impl Into<String> + Send + 'a,
        payload: impl Into<Vec<u8>> + Send + 'a,
    ) -> impl Future<Output = Result<PublishResult>> + Send + 'a {
        async move { self.publish(topic, payload).await }
    }

    fn publish_qos<'a>(
        &'a self,
        topic: impl Into<String> + Send + 'a,
        payload: impl Into<Vec<u8>> + Send + 'a,
        qos: QoS,
    ) -> impl Future<Output = Result<PublishResult>> + Send + 'a {
        async move { self.publish_qos(topic, payload, qos).await }
    }

    fn publish_with_options<'a>(
        &'a self,
        topic: impl Into<String> + Send + 'a,
        payload: impl Into<Vec<u8>> + Send + 'a,
        options: PublishOptions,
    ) -> impl Future<Output = Result<PublishResult>> + Send + 'a {
        async move { self.publish_with_options(topic, payload, options).await }
    }

    fn subscribe<'a, F>(
        &'a self,
        topic_filter: impl Into<String> + Send + 'a,
        callback: F,
    ) -> impl Future<Output = Result<(u16, QoS)>> + Send + 'a
    where
        F: Fn(crate::types::Message) + Send + Sync + 'static,
    {
        async move { self.subscribe(topic_filter, callback).await }
    }

    fn subscribe_with_options<'a, F>(
        &'a self,
        topic_filter: impl Into<String> + Send + 'a,
        options: SubscribeOptions,
        callback: F,
    ) -> impl Future<Output = Result<(u16, QoS)>> + Send + 'a
    where
        F: Fn(crate::types::Message) + Send + Sync + 'static,
    {
        async move {
            self.subscribe_with_options(topic_filter, options, callback)
                .await
        }
    }

    fn unsubscribe<'a>(
        &'a self,
        topic_filter: impl Into<String> + Send + 'a,
    ) -> impl Future<Output = Result<()>> + Send + 'a {
        async move { self.unsubscribe(topic_filter).await }
    }

    fn subscribe_many<'a, F>(
        &'a self,
        topics: Vec<(&'a str, QoS)>,
        callback: F,
    ) -> impl Future<Output = Result<Vec<(u16, QoS)>>> + Send + 'a
    where
        F: Fn(crate::types::Message) + Send + Sync + 'static + Clone,
    {
        async move { self.subscribe_many(topics, callback).await }
    }

    fn unsubscribe_many<'a>(
        &'a self,
        topics: Vec<&'a str>,
    ) -> impl Future<Output = Result<Vec<(String, Result<()>)>>> + Send + 'a {
        async move { self.unsubscribe_many(topics).await }
    }

    fn publish_retain<'a>(
        &'a self,
        topic: impl Into<String> + Send + 'a,
        payload: impl Into<Vec<u8>> + Send + 'a,
    ) -> impl Future<Output = Result<PublishResult>> + Send + 'a {
        async move { self.publish_retain(topic, payload).await }
    }

    fn publish_qos0<'a>(
        &'a self,
        topic: impl Into<String> + Send + 'a,
        payload: impl Into<Vec<u8>> + Send + 'a,
    ) -> impl Future<Output = Result<PublishResult>> + Send + 'a {
        async move { self.publish_qos0(topic, payload).await }
    }

    fn publish_qos1<'a>(
        &'a self,
        topic: impl Into<String> + Send + 'a,
        payload: impl Into<Vec<u8>> + Send + 'a,
    ) -> impl Future<Output = Result<PublishResult>> + Send + 'a {
        async move { self.publish_qos1(topic, payload).await }
    }

    fn publish_qos2<'a>(
        &'a self,
        topic: impl Into<String> + Send + 'a,
        payload: impl Into<Vec<u8>> + Send + 'a,
    ) -> impl Future<Output = Result<PublishResult>> + Send + 'a {
        async move { self.publish_qos2(topic, payload).await }
    }

    fn is_queue_on_disconnect(&self) -> impl Future<Output = bool> + Send + '_ {
        async move { self.is_queue_on_disconnect().await }
    }

    fn set_queue_on_disconnect(&self, enabled: bool) -> impl Future<Output = ()> + Send + '_ {
        async move { self.set_queue_on_disconnect(enabled).await }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_client_creation() {
        let client = MqttClient::new("test-client");
        assert!(!client.is_connected().await);
        assert_eq!(client.client_id().await, "test-client");
    }

    #[test]
    fn test_parse_address() {
        let (transport, host, port) = MqttClient::parse_address("mqtt://localhost:1883").unwrap();
        assert!(matches!(transport, state::ClientTransportType::Tcp));
        assert_eq!(host, "localhost");
        assert_eq!(port, 1883);

        let (transport, host, port) = MqttClient::parse_address("mqtt://localhost").unwrap();
        assert!(matches!(transport, state::ClientTransportType::Tcp));
        assert_eq!(host, "localhost");
        assert_eq!(port, 1883);

        let (transport, host, port) =
            MqttClient::parse_address("mqtts://broker.example.com").unwrap();
        assert!(matches!(transport, state::ClientTransportType::Tls));
        assert_eq!(host, "broker.example.com");
        assert_eq!(port, 8883);

        let (transport, host, port) =
            MqttClient::parse_address("mqtts://secure.broker:9999").unwrap();
        assert!(matches!(transport, state::ClientTransportType::Tls));
        assert_eq!(host, "secure.broker");
        assert_eq!(port, 9999);

        let (transport, host, port) =
            MqttClient::parse_address("tcp://192.168.1.100:1234").unwrap();
        assert!(matches!(transport, state::ClientTransportType::Tcp));
        assert_eq!(host, "192.168.1.100");
        assert_eq!(port, 1234);

        let (transport, host, port) =
            MqttClient::parse_address("ssl://secure.broker.com:8883").unwrap();
        assert!(matches!(transport, state::ClientTransportType::Tls));
        assert_eq!(host, "secure.broker.com");
        assert_eq!(port, 8883);

        let (transport, host, port) = MqttClient::parse_address("localhost").unwrap();
        assert!(matches!(transport, state::ClientTransportType::Tcp));
        assert_eq!(host, "localhost");
        assert_eq!(port, 1883);

        let (transport, host, port) = MqttClient::parse_address("broker.local:9999").unwrap();
        assert!(matches!(transport, state::ClientTransportType::Tcp));
        assert_eq!(host, "broker.local");
        assert_eq!(port, 9999);

        #[cfg(feature = "transport-websocket")]
        {
            let (transport, host, port) = MqttClient::parse_address("ws://localhost").unwrap();
            assert!(matches!(
                transport,
                state::ClientTransportType::WebSocket(_)
            ));
            assert_eq!(host, "localhost");
            assert_eq!(port, 80);

            let (transport, host, port) = MqttClient::parse_address("ws://localhost:8080").unwrap();
            assert!(matches!(
                transport,
                state::ClientTransportType::WebSocket(_)
            ));
            assert_eq!(host, "localhost");
            assert_eq!(port, 8080);

            let (transport, host, port) = MqttClient::parse_address("wss://secure.broker").unwrap();
            assert!(matches!(
                transport,
                state::ClientTransportType::WebSocketSecure(_)
            ));
            assert_eq!(host, "secure.broker");
            assert_eq!(port, 443);

            let (transport, host, port) =
                MqttClient::parse_address("wss://secure.broker:8443").unwrap();
            assert!(matches!(
                transport,
                state::ClientTransportType::WebSocketSecure(_)
            ));
            assert_eq!(host, "secure.broker");
            assert_eq!(port, 8443);

            let (transport, host, port) =
                MqttClient::parse_address("ws://broker.emqx.io:8083/mqtt").unwrap();
            if let state::ClientTransportType::WebSocket(url) = transport {
                assert_eq!(url, "ws://broker.emqx.io:8083/mqtt");
            } else {
                panic!("Expected WebSocket transport type");
            }
            assert_eq!(host, "broker.emqx.io");
            assert_eq!(port, 8083);

            let (transport, host, port) =
                MqttClient::parse_address("wss://broker.hivemq.com:8884/mqtt").unwrap();
            if let state::ClientTransportType::WebSocketSecure(url) = transport {
                assert_eq!(url, "wss://broker.hivemq.com:8884/mqtt");
            } else {
                panic!("Expected WebSocketSecure transport type");
            }
            assert_eq!(host, "broker.hivemq.com");
            assert_eq!(port, 8884);
        }

        #[cfg(not(feature = "transport-websocket"))]
        {
            assert!(MqttClient::parse_address("ws://localhost").is_err());
            assert!(MqttClient::parse_address("wss://secure.broker").is_err());
        }

        let (transport, host, port) = MqttClient::parse_address("[::1]:1883").unwrap();
        assert!(matches!(transport, state::ClientTransportType::Tcp));
        assert_eq!(host, "[::1]");
        assert_eq!(port, 1883);
    }
}